require_relative “../simplest_migrations”

namespace :db do

desc "Drop the database"
task :drop do
  SimplestMigrations::Database.execute "DROP DATABASE IF EXISTS #{SimplestMigrations::Database.name}", "postgres"
end

desc "Create the database"
task :create do
  begin
    SimplestMigrations::Database.execute "CREATE DATABASE #{SimplestMigrations::Database.name}", "postgres"
  rescue ActiveRecord::StatementInvalid => ex
    unless ex.to_s =~ /DuplicateDatabase/
      raise ex
    end
  end
end

desc "Migrate the database"
task :migrate do
  SimplestMigrations::Database.migrate
end

desc "Rebuild the database"
task reset: [:drop, :create, :load]

desc "Create a new migration: rake db:new name=NAME"
task :new_migration do |t, args|
  name = ENV['NAME'] || 'new_migration'
  FileUtils.touch("db/migrate/#{Time.now.strftime('%Y%m%d%H%M%S')}_#{name}.rb")
  Rake::Task["db:dump"].invoke
end

desc "Dump the current database schema"
task :dump do
  file = "db/structure.sql"

  SimplestMigrations::Database.set_pg_environment

  command = "pg_dump -s -x -O -f #{file} #{SimplestMigrations::Database.name}"
  Kernel.system(command)

  command = "pg_dump -t schema_migrations -a #{SimplestMigrations::Database.name} >> #{file}"
  Kernel.system(command)
end

desc "Load the database from the cached schema"
task :load do
  file = "db/structure.sql"

  SimplestMigrations::Database.set_pg_environment

  command = "psql #{SimplestMigrations::Database.name} < #{file}"
  Kernel.system(command)
end

end