PostgreSQL用のRakefileサンプル

最終更新日: 2011年5月15日

HomeBack

  1. サンプル

[WindowsとLinuxで同じRakefileを使用する] へ戻る

サンプル

#
# For PostgreSQL
#
namespace :psql do
  task :default => [:create, :migrate, :drop]

  ENV_PGPASSWORD = "PGPASSWORD"

  ENV[ENV_PGPASSWORD ]  = PASSWORD
  def get_psql_password()
    pass = ENV[ENV_PGPASSWORD]
    if !pass || pass.empty? then
      system "stty -echo"
      puts "input database password"
      pass = STDIN.gets
      system "stty echo"
      ENV[ENV_PGPASSWORD] = pass.chop
    end
  end

  def get_psql_dbname()
    if DBNAME && DBNAME.length > 0 then
      return DBNAME
    elsif ENV.include?('dbname') then
      return ENV['dbname']
    else
      puts "input database name"
      dbname = STDIN.gets
      ENV['dbname'] = dbname.chop
      return ENV['dbname']
    end
  end

  desc "create database"
  task :create do
    dbname = get_psql_dbname()
    get_psql_password()
    sh "#{PGPATH}createdb -U #{PGUSER}  #{dbname}"
  end

  desc "drop database"
  task :drop do
    dbname = get_psql_dbname()
    get_psql_password()
    sh "#{PGPATH}dropdb -U #{PGUSER} #{dbname}"
  end

  desc "migrate database"
  task :migrate do
    dbname = get_psql_dbname()
    get_psql_password()
    sh "#{PGPATH}psql -U #{PGUSER} -d #{dbname} < #{MIGRATE_DDL}"
  end

  def psql_exec(q)
    dbname = get_psql_dbname()
    get_psql_password()
    sh "#{PGPATH}psql -U #{PGUSER} -d #{dbname} -c \"#{q}\""
  end

  desc "execute query (psql:exec[\"QUERY\"])"
  task :exec, "query" do |x, args|
    psql_exec(args.query)
  end

  desc "show databases"
  task :databases do
    sh "#{PGPATH}psql -U #{PGUSER} -c \"\\l\""
  end

  desc "show tables (\\d)"
  task :tables do
    psql_exec("\\d")
  end

  desc "describe table (psql:desc[TABLENAME])"
  task :desc, "table_name" do |x, args|
    psql_exec("\\d #{args.table_name}")
  end
end


HomeBack