databases.rake 23.3 KB
Newer Older
1
db_namespace = namespace :db do
2 3
  task :load_config => :rails_env do
    require 'active_record'
4
    ActiveRecord::Base.configurations = Rails.application.config.database_configuration
5
    ActiveRecord::Migrator.migrations_paths = Rails.application.paths["db/migrate"].to_a
6 7 8 9 10 11

    if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
      if engine.paths["db/migrate"].existent
        ActiveRecord::Migrator.migrations_paths += engine.paths["db/migrate"].to_a
      end
    end
12 13
  end

14
  namespace :create do
15
    # desc 'Create all the local databases defined in config/database.yml'
16
    task :all => :load_config do
17
      ActiveRecord::Base.configurations.each_value do |config|
18 19
        # Skip entries that don't have a database key, such as the first entry here:
        #
20 21
        #  defaults: &defaults
        #    adapter: mysql
22
        #    username: root
23
        #    password:
24
        #    host: localhost
25 26
        #
        #  development:
27 28 29 30
        #    database: blog_development
        #    <<: *defaults
        next unless config['database']
        # Only connect to local databases
31
        local_database?(config) { create_database(config) }
32 33 34 35
      end
    end
  end

36
  desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
37
  task :create => :load_config do
38 39
    # Make the test database at the same time as the development one, if it exists
    if Rails.env.development? && ActiveRecord::Base.configurations['test']
40 41
      create_database(ActiveRecord::Base.configurations['test'])
    end
42
    create_database(ActiveRecord::Base.configurations[Rails.env])
43 44
  end

45 46
  def create_database(config)
    begin
47 48 49 50 51 52 53 54
      if config['adapter'] =~ /sqlite/
        if File.exist?(config['database'])
          $stderr.puts "#{config['database']} already exists"
        else
          begin
            # Create the SQLite database
            ActiveRecord::Base.establish_connection(config)
            ActiveRecord::Base.connection
T
Thiago Pradi 已提交
55 56
          rescue Exception => e
            $stderr.puts e, *(e.backtrace)
57 58 59
            $stderr.puts "Couldn't create database for #{config.inspect}"
          end
        end
J
Joshua Peek 已提交
60
        return # Skip the else clause of begin/rescue
61 62 63 64
      else
        ActiveRecord::Base.establish_connection(config)
        ActiveRecord::Base.connection
      end
65 66
    rescue
      case config['adapter']
J
Jeremy Kemper 已提交
67
      when /mysql/
68
        @charset   = ENV['CHARSET']   || 'utf8'
69
        @collation = ENV['COLLATION'] || 'utf8_unicode_ci'
70
        creation_options = {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)}
71
        error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
72
        access_denied_error = 1045
73
        begin
74
          ActiveRecord::Base.establish_connection(config.merge('database' => nil))
75
          ActiveRecord::Base.connection.create_database(config['database'], creation_options)
76
          ActiveRecord::Base.establish_connection(config)
77 78
        rescue error_class => sqlerr
          if sqlerr.errno == access_denied_error
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            print "#{sqlerr.error}. \nPlease provide the root password for your mysql installation\n>"
            root_password = $stdin.gets.strip
            grant_statement = "GRANT ALL PRIVILEGES ON #{config['database']}.* " \
              "TO '#{config['username']}'@'localhost' " \
              "IDENTIFIED BY '#{config['password']}' WITH GRANT OPTION;"
            ActiveRecord::Base.establish_connection(config.merge(
                'database' => nil, 'username' => 'root', 'password' => root_password))
            ActiveRecord::Base.connection.create_database(config['database'], creation_options)
            ActiveRecord::Base.connection.execute grant_statement
            ActiveRecord::Base.establish_connection(config)
          else
            $stderr.puts sqlerr.error
            $stderr.puts "Couldn't create database for #{config.inspect}, charset: #{config['charset'] || @charset}, collation: #{config['collation'] || @collation}"
            $stderr.puts "(if you set the charset manually, make sure you have a matching collation)" if config['charset']
          end
94
        end
95
      when 'postgresql'
96
        @encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
97
        begin
98
          ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
99
          ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
100
          ActiveRecord::Base.establish_connection(config)
T
Thiago Pradi 已提交
101 102
        rescue Exception => e
          $stderr.puts e, *(e.backtrace)
103 104
          $stderr.puts "Couldn't create database for #{config.inspect}"
        end
105
      end
106
    else
107
      $stderr.puts "#{config['database']} already exists"
108 109
    end
  end
110

111
  namespace :drop do
112
    # desc 'Drops all the local databases defined in config/database.yml'
113
    task :all => :load_config do
114
      ActiveRecord::Base.configurations.each_value do |config|
115 116
        # Skip entries that don't have a database key
        next unless config['database']
117 118 119 120
        begin
          # Only connect to local databases
          local_database?(config) { drop_database(config) }
        rescue Exception => e
121
          $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
122
        end
123
      end
124 125
    end
  end
126

127
  desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
128
  task :drop => :load_config do
129
    config = ActiveRecord::Base.configurations[Rails.env || 'development']
130 131 132
    begin
      drop_database(config)
    rescue Exception => e
133
      $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
134
    end
135 136
  end

137 138 139 140
  def local_database?(config, &block)
    if %w( 127.0.0.1 localhost ).include?(config['host']) || config['host'].blank?
      yield
    else
141
      $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."
142 143 144 145
    end
  end


146
  desc "Migrate the database (options: VERSION=x, VERBOSE=false)."
147
  task :migrate => [:environment, :load_config] do
148
    ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
149
    ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
150
    db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
151 152
  end

153
  namespace :migrate do
154
    # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
155
    task :redo => [:environment, :load_config] do
156
      if ENV["VERSION"]
157 158
        db_namespace["migrate:down"].invoke
        db_namespace["migrate:up"].invoke
159
      else
160 161
        db_namespace["rollback"].invoke
        db_namespace["migrate"].invoke
162 163
      end
    end
164

165
    # desc 'Resets your database using your migrations for the current environment'
166
    task :reset => ["db:drop", "db:create", "db:migrate"]
167

168
    # desc 'Runs the "up" for a given migration VERSION.'
169
    task :up => [:environment, :load_config] do
170 171
      version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
      raise "VERSION is required" unless version
172
      ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version)
173
      db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
174 175
    end

176
    # desc 'Runs the "down" for a given migration VERSION.'
177
    task :down => [:environment, :load_config] do
178 179
      version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
      raise "VERSION is required" unless version
180
      ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version)
181
      db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
182
    end
183 184

    desc "Display status of migrations"
185
    task :status => [:environment, :load_config] do
186
      config = ActiveRecord::Base.configurations[Rails.env || 'development']
187 188 189 190 191
      ActiveRecord::Base.establish_connection(config)
      unless ActiveRecord::Base.connection.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
        puts 'Schema migrations table does not exist yet.'
        next  # means "return" for rake task
      end
192
      db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
193 194 195
      file_list = []
      Dir.foreach(File.join(Rails.root, 'db', 'migrate')) do |file|
        # only files matching "20091231235959_some_name.rb" pattern
196
        if match_data = /^(\d{14})_(.+)\.rb$/.match(file)
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
          status = db_list.delete(match_data[1]) ? 'up' : 'down'
          file_list << [status, match_data[1], match_data[2]]
        end
      end
      # output
      puts "\ndatabase: #{config['database']}\n\n"
      puts "#{"Status".center(8)}  #{"Migration ID".ljust(14)}  Migration Name"
      puts "-" * 50
      file_list.each do |file|
        puts "#{file[0].center(8)}  #{file[1].ljust(14)}  #{file[2].humanize}"
      end
      db_list.each do |version|
        puts "#{'up'.center(8)}  #{version.ljust(14)}  *** NO FILE ***"
      end
      puts
    end
213 214
  end

215
  desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
216
  task :rollback => [:environment, :load_config] do
217
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
218
    ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
219
    db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
220 221
  end

222
  # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
223
  task :forward => [:environment, :load_config] do
224
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
225
    ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step)
226
    db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
227 228
  end

229
  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
230
  task :reset => [ 'db:drop', 'db:setup' ]
231

232
  # desc "Retrieves the charset for the current environment's database"
233
  task :charset => :environment do
234
    config = ActiveRecord::Base.configurations[Rails.env || 'development']
235
    case config['adapter']
J
Jeremy Kemper 已提交
236
    when /mysql/
237 238
      ActiveRecord::Base.establish_connection(config)
      puts ActiveRecord::Base.connection.charset
239 240 241
    when 'postgresql'
      ActiveRecord::Base.establish_connection(config)
      puts ActiveRecord::Base.connection.encoding
242 243 244
    when 'sqlite3'
      ActiveRecord::Base.establish_connection(config)
      puts ActiveRecord::Base.connection.encoding
245
    else
246
      $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
247 248 249
    end
  end

250
  # desc "Retrieves the collation for the current environment's database"
251
  task :collation => :environment do
252
    config = ActiveRecord::Base.configurations[Rails.env || 'development']
253
    case config['adapter']
J
Jeremy Kemper 已提交
254
    when /mysql/
255 256 257
      ActiveRecord::Base.establish_connection(config)
      puts ActiveRecord::Base.connection.collation
    else
258
      $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
259 260
    end
  end
261 262 263

  desc "Retrieves the current schema version number"
  task :version => :environment do
264
    puts "Current version: #{ActiveRecord::Migrator.current_version}"
265 266
  end

267
  # desc "Raises an error if there are pending migrations"
268
  task :abort_if_pending_migrations => :environment do
269
    if defined? ActiveRecord
270
      pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
271

272 273 274 275 276
      if pending_migrations.any?
        puts "You have #{pending_migrations.size} pending migrations:"
        pending_migrations.each do |pending_migration|
          puts '  %4d %s' % [pending_migration.version, pending_migration.name]
        end
P
Pratik Naik 已提交
277
        abort %{Run "rake db:migrate" to update your database then try again.}
278 279 280 281
      end
    end
  end

282
  desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)'
283 284 285
  task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ]

  desc 'Load the seed data from db/seeds.rb'
286
  task :seed => 'db:abort_if_pending_migrations' do
287
    Rails.application.load_seed
288 289
  end

290
  namespace :fixtures do
291
    desc "Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
292
    task :load => :environment do
293 294
      require 'active_record/fixtures'

295
      ActiveRecord::Base.establish_connection(Rails.env)
296
      base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
297 298
      fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir

299 300
      (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir["#{fixtures_dir}/**/*.{yml,csv}"]).each do |fixture_file|
        Fixtures.create_fixtures(fixtures_dir, fixture_file[(fixtures_dir.size + 1)..-5])
301 302
      end
    end
303

304
    # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
305
    task :identify => :environment do
306 307
      require 'active_record/fixtures'

308 309
      label, id = ENV["LABEL"], ENV["ID"]
      raise "LABEL or ID required" if label.blank? && id.blank?
310

311
      puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label
312

313 314
      base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
      Dir["#{base_dir}/**/*.yml"].each do |file|
315 316 317
        if data = YAML::load(ERB.new(IO.read(file)).result)
          data.keys.each do |key|
            key_id = Fixtures.identify(key)
318

319 320 321 322 323 324 325
            if key == label || key_id == id.to_i
              puts "#{file}: #{key} (#{key_id})"
            end
          end
        end
      end
    end
326
  end
327

328 329
  namespace :schema do
    desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
330
    task :dump => :load_config do
331
      require 'active_record/schema_dumper'
332
      File.open(ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb", "w") do |file|
333 334
        ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
      end
335
      db_namespace["schema:dump"].reenable
336
    end
337

338 339
    desc "Load a schema.rb file into the database"
    task :load => :environment do
340
      file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
341 342 343
      if File.exists?(file)
        load(file)
      else
344
        abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
345
      end
346
    end
347 348
  end

349
  namespace :structure do
350
    desc "Dump the database structure to an SQL file"
351 352
    task :dump => :environment do
      abcs = ActiveRecord::Base.configurations
353
      case abcs[Rails.env]["adapter"]
J
Jeremy Kemper 已提交
354
      when /mysql/, "oci", "oracle"
355 356
        ActiveRecord::Base.establish_connection(abcs[Rails.env])
        File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
357
      when "postgresql"
358 359 360 361
        ENV['PGHOST']     = abcs[Rails.env]["host"] if abcs[Rails.env]["host"]
        ENV['PGPORT']     = abcs[Rails.env]["port"].to_s if abcs[Rails.env]["port"]
        ENV['PGPASSWORD'] = abcs[Rails.env]["password"].to_s if abcs[Rails.env]["password"]
        search_path = abcs[Rails.env]["schema_search_path"]
362 363 364
        unless search_path.blank?
          search_path = search_path.split(",").map{|search_path| "--schema=#{search_path.strip}" }.join(" ")
        end
365
        `pg_dump -i -U "#{abcs[Rails.env]["username"]}" -s -x -O -f db/#{Rails.env}_structure.sql #{search_path} #{abcs[Rails.env]["database"]}`
366
        raise "Error dumping database" if $?.exitstatus == 1
367
      when "sqlite", "sqlite3"
368 369
        dbfile = abcs[Rails.env]["database"] || abcs[Rails.env]["dbfile"]
        `#{abcs[Rails.env]["adapter"]} #{dbfile} .schema > db/#{Rails.env}_structure.sql`
370
      when "sqlserver"
371 372
        `scptxfr /s #{abcs[Rails.env]["host"]} /d #{abcs[Rails.env]["database"]} /I /f db\\#{Rails.env}_structure.sql /q /A /r`
        `scptxfr /s #{abcs[Rails.env]["host"]} /d #{abcs[Rails.env]["database"]} /I /F db\ /q /A /r`
373
      when "firebird"
374 375 376
        set_firebird_env(abcs[Rails.env])
        db_string = firebird_db_string(abcs[Rails.env])
        sh "isql -a #{db_string} > #{Rails.root}/db/#{Rails.env}_structure.sql"
377
      else
378
        raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'"
379 380
      end

381
      if ActiveRecord::Base.connection.supports_migrations?
382
        File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
383
      end
384
    end
385
  end
386

387
  namespace :test do
388
    # desc "Recreate the test database from the current schema.rb"
389
    task :load => 'db:test:purge' do
390
      ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
391
      ActiveRecord::Schema.verbose = false
392
      db_namespace["schema:load"].invoke
393
    end
394

395
    # desc "Recreate the test database from the current environment's database schema"
396
    task :clone => %w(db:schema:dump db:test:load)
397

398
    # desc "Recreate the test databases from the development structure"
399 400 401
    task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
      abcs = ActiveRecord::Base.configurations
      case abcs["test"]["adapter"]
J
Jeremy Kemper 已提交
402
      when /mysql/
403 404
        ActiveRecord::Base.establish_connection(:test)
        ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
405
        IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split("\n\n").each do |table|
406 407
          ActiveRecord::Base.connection.execute(table)
        end
408
      when "postgresql"
409 410 411
        ENV['PGHOST']     = abcs["test"]["host"] if abcs["test"]["host"]
        ENV['PGPORT']     = abcs["test"]["port"].to_s if abcs["test"]["port"]
        ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
412
        `psql -U "#{abcs["test"]["username"]}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs["test"]["database"]} #{abcs["test"]["template"]}`
413 414
      when "sqlite", "sqlite3"
        dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
415
        `#{abcs["test"]["adapter"]} #{dbfile} < #{Rails.root}/db/#{Rails.env}_structure.sql`
416
      when "sqlserver"
417
        `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{Rails.env}_structure.sql`
418
      when "oci", "oracle"
419
        ActiveRecord::Base.establish_connection(:test)
420
        IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split(";\n\n").each do |ddl|
421 422
          ActiveRecord::Base.connection.execute(ddl)
        end
423
      when "firebird"
424 425
        set_firebird_env(abcs["test"])
        db_string = firebird_db_string(abcs["test"])
426
        sh "isql -i #{Rails.root}/db/#{Rails.env}_structure.sql #{db_string}"
427 428
      else
        raise "Task not supported by '#{abcs["test"]["adapter"]}'"
429 430
      end
    end
431

432
    # desc "Empty the test database"
433 434 435
    task :purge => :environment do
      abcs = ActiveRecord::Base.configurations
      case abcs["test"]["adapter"]
J
Jeremy Kemper 已提交
436
      when /mysql/
437
        ActiveRecord::Base.establish_connection(:test)
438
        ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"], abcs["test"])
439 440
      when "postgresql"
        ActiveRecord::Base.clear_active_connections!
441 442
        drop_database(abcs['test'])
        create_database(abcs['test'])
443 444 445
      when "sqlite","sqlite3"
        dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
        File.delete(dbfile) if File.exist?(dbfile)
446
      when "sqlserver"
447 448
        dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-')
        `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}`
449
        `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{Rails.env}_structure.sql`
450
      when "oci", "oracle"
451 452 453 454
        ActiveRecord::Base.establish_connection(:test)
        ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
          ActiveRecord::Base.connection.execute(ddl)
        end
455
      when "firebird"
456 457 458 459
        ActiveRecord::Base.establish_connection(:test)
        ActiveRecord::Base.connection.recreate_database!
      else
        raise "Task not supported by '#{abcs["test"]["adapter"]}'"
460 461
      end
    end
462

463
    # desc 'Check for pending migrations and load the test schema'
464
    task :prepare => 'db:abort_if_pending_migrations' do
465
      if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
466
        db_namespace[{ :sql  => "test:clone_structure", :ruby => "test:load" }[ActiveRecord::Base.schema_format]].invoke
467
      end
468
    end
469 470
  end

471
  namespace :sessions do
472
    # desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
473 474
    task :create => :environment do
      raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
475
      require 'rails/generators'
476
      Rails::Generators.configure!
477
      require 'rails/generators/rails/session_migration/session_migration_generator'
478
      Rails::Generators::SessionMigrationGenerator.start [ ENV["MIGRATION"] || "add_sessions_table" ]
479 480
    end

481
    # desc "Clear the sessions table"
482
    task :clear => :environment do
483
      ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
484 485
    end
  end
486 487
end

488
namespace :railties do
489
  namespace :install do
490
    # desc "Copies missing migrations from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
491 492 493 494 495 496 497 498 499 500 501 502
    task :migrations => :"db:load_config" do
      to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map {|n| n.strip }
      railties = {}
      Rails.application.railties.all do |railtie|
        next unless to_load == :all || to_load.include?(railtie.railtie_name)

        if railtie.respond_to?(:paths) && (path = railtie.paths["db/migrate"].first)
          railties[railtie.railtie_name] = path
        end
      end

      on_skip = Proc.new do |name, migration|
503
        puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
504 505 506 507 508 509
      end

      on_copy = Proc.new do |name, migration, old_path|
        puts "Copied migration #{migration.basename} from #{name}"
      end

510
      ActiveRecord::Migration.copy( ActiveRecord::Migrator.migrations_paths.first, railties,
511 512 513
                                    :on_skip => on_skip, :on_copy => on_copy)
    end
  end
514 515
end

516 517
task 'test:prepare' => 'db:test:prepare'

518 519
def drop_database(config)
  case config['adapter']
J
Jeremy Kemper 已提交
520
  when /mysql/
521
    ActiveRecord::Base.establish_connection(config)
522
    ActiveRecord::Base.connection.drop_database config['database']
523
  when /^sqlite/
524 525
    require 'pathname'
    path = Pathname.new(config['database'])
526
    file = path.absolute? ? path.to_s : File.join(Rails.root, path)
527 528

    FileUtils.rm(file)
529
  when 'postgresql'
530
    ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
531
    ActiveRecord::Base.connection.drop_database config['database']
532 533 534
  end
end

535
def session_table_name
536
  ActiveRecord::SessionStore::Session.table_name
537
end
J
Jeremy Kemper 已提交
538 539 540 541 542 543 544 545

def set_firebird_env(config)
  ENV["ISC_USER"]     = config["username"].to_s if config["username"]
  ENV["ISC_PASSWORD"] = config["password"].to_s if config["password"]
end

def firebird_db_string(config)
  FireRuby::Database.db_string_for(config.symbolize_keys)
546
end