databases.rake 23.8 KB
Newer Older
1 2
require 'active_support/core_ext/object/inclusion'

3
db_namespace = namespace :db do
4 5
  task :load_config => :rails_env do
    require 'active_record'
6
    ActiveRecord::Base.configurations = Rails.application.config.database_configuration
A
Arun Agrawal 已提交
7
    ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a
8 9

    if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
A
Arun Agrawal 已提交
10 11
      if engine.paths['db/migrate'].existent
        ActiveRecord::Migrator.migrations_paths += engine.paths['db/migrate'].to_a
12 13
      end
    end
14 15
  end

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

38
  desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
39
  task :create => :load_config do
40
    configs_for_environment.each { |config| create_database(config) }
41 42
  end

43 44 45 46 47 48
  def mysql_creation_options(config)
    @charset   = ENV['CHARSET']   || 'utf8'
    @collation = ENV['COLLATION'] || 'utf8_unicode_ci'
    {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)}
  end

49 50
  def create_database(config)
    begin
51 52 53 54 55 56 57 58
      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 已提交
59 60
          rescue Exception => e
            $stderr.puts e, *(e.backtrace)
61 62 63
            $stderr.puts "Couldn't create database for #{config.inspect}"
          end
        end
J
Joshua Peek 已提交
64
        return # Skip the else clause of begin/rescue
65 66 67 68
      else
        ActiveRecord::Base.establish_connection(config)
        ActiveRecord::Base.connection
      end
69 70
    rescue
      case config['adapter']
J
Jeremy Kemper 已提交
71
      when /mysql/
72 73 74 75 76 77 78
        if config['adapter'] =~ /jdbc/
          #FIXME After Jdbcmysql gives this class
          require 'active_record/railties/jdbcmysql_error'
          error_class = ArJdbcMySQL::Error
        else
          error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
        end
79
        access_denied_error = 1045
80
        begin
81
          ActiveRecord::Base.establish_connection(config.merge('database' => nil))
82
          ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
83
          ActiveRecord::Base.establish_connection(config)
84 85
        rescue error_class => sqlerr
          if sqlerr.errno == access_denied_error
86 87 88 89 90 91 92
            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))
93
            ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
94 95 96 97 98 99 100
            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
101
        end
102
      when /postgresql/
103
        @encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
104
        begin
105
          ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
106
          ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
107
          ActiveRecord::Base.establish_connection(config)
T
Thiago Pradi 已提交
108 109
        rescue Exception => e
          $stderr.puts e, *(e.backtrace)
110 111
          $stderr.puts "Couldn't create database for #{config.inspect}"
        end
112
      end
113
    else
114 115
      # Bug with 1.9.2 Calling return within begin still executes else
      $stderr.puts "#{config['database']} already exists" unless config['adapter'] =~ /sqlite/
116 117
    end
  end
118

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

135
  desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
136
  task :drop => :load_config do
137
    configs_for_environment.each { |config| drop_database_and_rescue(config) }
138 139
  end

140
  def local_database?(config, &block)
A
Arun Agrawal 已提交
141
    if config['host'].in?(['127.0.0.1', 'localhost']) || config['host'].blank?
142 143
      yield
    else
144
      $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."
145 146 147 148
    end
  end


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

156
  namespace :migrate do
157
    # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
158
    task :redo => [:environment, :load_config] do
A
Arun Agrawal 已提交
159 160 161
      if ENV['VERSION']
        db_namespace['migrate:down'].invoke
        db_namespace['migrate:up'].invoke
162
      else
A
Arun Agrawal 已提交
163 164
        db_namespace['rollback'].invoke
        db_namespace['migrate'].invoke
165 166
      end
    end
167

168
    # desc 'Resets your database using your migrations for the current environment'
A
Arun Agrawal 已提交
169
    task :reset => ['db:drop', 'db:create', 'db:migrate']
170

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

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

A
Arun Agrawal 已提交
187
    desc 'Display status of migrations'
188
    task :status => [:environment, :load_config] do
189
      config = ActiveRecord::Base.configurations[Rails.env || 'development']
190 191 192 193 194
      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
195
      db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
196
      file_list = []
197 198 199 200 201 202 203
      ActiveRecord::Migrator.migrations_paths.each do |path|
        Dir.foreach(path) do |file|
          # only files matching "20091231235959_some_name.rb" pattern
          if match_data = /^(\d{14})_(.+)\.rb$/.match(file)
            status = db_list.delete(match_data[1]) ? 'up' : 'down'
            file_list << [status, match_data[1], match_data[2].humanize]
          end
204 205
        end
      end
206 207 208
      db_list.map! do |version|
        ['up', version, '********** NO FILE **********']
      end
209 210
      # output
      puts "\ndatabase: #{config['database']}\n\n"
A
Arun Agrawal 已提交
211
      puts "#{'Status'.center(8)}  #{'Migration ID'.ljust(14)}  Migration Name"
212
      puts "-" * 50
213 214
      (db_list + file_list).sort_by {|migration| migration[1]}.each do |migration|
        puts "#{migration[0].center(8)}  #{migration[1].ljust(14)}  #{migration[2]}"
215 216 217
      end
      puts
    end
218 219
  end

220
  desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
221
  task :rollback => [:environment, :load_config] do
222
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
223
    ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
A
Arun Agrawal 已提交
224
    db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
225 226
  end

227
  # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
228
  task :forward => [:environment, :load_config] do
229
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
230
    ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step)
A
Arun Agrawal 已提交
231
    db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
232 233
  end

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

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

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

A
Arun Agrawal 已提交
267
  desc 'Retrieves the current schema version number'
268
  task :version => :environment do
269
    puts "Current version: #{ActiveRecord::Migrator.current_version}"
270 271
  end

272
  # desc "Raises an error if there are pending migrations"
273
  task :abort_if_pending_migrations => :environment do
274
    if defined? ActiveRecord
275
      pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
276

277 278 279 280 281
      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
C
Cyril Wack 已提交
282
        abort %{Run `rake db:migrate` to update your database then try again.}
283 284 285 286
      end
    end
  end

287
  desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)'
288 289 290
  task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ]

  desc 'Load the seed data from db/seeds.rb'
291
  task :seed => 'db:abort_if_pending_migrations' do
292
    Rails.application.load_seed
293 294
  end

295
  namespace :fixtures do
296
    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."
297
    task :load => :environment do
298 299
      require 'active_record/fixtures'

300
      ActiveRecord::Base.establish_connection(Rails.env)
301
      base_dir     = File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
302
      fixtures_dir = File.join [base_dir, ENV['FIXTURES_DIR']].compact
303

304
      (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.{yml,csv}"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
J
Jason Noble 已提交
305
        ActiveRecord::Fixtures.create_fixtures(fixtures_dir, fixture_file)
306 307
      end
    end
308

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

A
Arun Agrawal 已提交
313 314
      label, id = ENV['LABEL'], ENV['ID']
      raise 'LABEL or ID required' if label.blank? && id.blank?
315

J
Jason Noble 已提交
316
      puts %Q(The fixture ID for "#{label}" is #{ActiveRecord::Fixtures.identify(label)}.) if label
317

318 319
      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|
320 321
        if data = YAML::load(ERB.new(IO.read(file)).result)
          data.keys.each do |key|
J
Jason Noble 已提交
322
            key_id = ActiveRecord::Fixtures.identify(key)
323

324 325 326 327 328 329 330
            if key == label || key_id == id.to_i
              puts "#{file}: #{key} (#{key_id})"
            end
          end
        end
      end
    end
331
  end
332

333
  namespace :schema do
A
Arun Agrawal 已提交
334
    desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR'
335
    task :dump => [:environment, :load_config] do
336
      require 'active_record/schema_dumper'
337 338
      filename = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
      File.open(filename, "w:utf-8") do |file|
339
        ActiveRecord::Base.establish_connection(Rails.env)
340 341
        ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
      end
A
Arun Agrawal 已提交
342
      db_namespace['schema:dump'].reenable
343
    end
344

A
Arun Agrawal 已提交
345
    desc 'Load a schema.rb file into the database'
346
    task :load => :environment do
347
      file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
348 349 350
      if File.exists?(file)
        load(file)
      else
C
Cyril Wack 已提交
351
        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}
352
      end
353
    end
354 355
  end

356
  namespace :structure do
A
Arun Agrawal 已提交
357
    desc 'Dump the database structure to an SQL file'
358 359
    task :dump => :environment do
      abcs = ActiveRecord::Base.configurations
A
Arun Agrawal 已提交
360 361
      case abcs[Rails.env]['adapter']
      when /mysql/, 'oci', 'oracle'
362 363
        ActiveRecord::Base.establish_connection(abcs[Rails.env])
        File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
364
      when /postgresql/
A
Arun Agrawal 已提交
365 366 367 368
        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']
369
        unless search_path.blank?
370
          search_path = search_path.split(",").map{|search_path_part| "--schema=#{search_path_part.strip}" }.join(" ")
371
        end
A
Arun Agrawal 已提交
372 373
        `pg_dump -i -U "#{abcs[Rails.env]['username']}" -s -x -O -f db/#{Rails.env}_structure.sql #{search_path} #{abcs[Rails.env]['database']}`
        raise 'Error dumping database' if $?.exitstatus == 1
374
      when /sqlite/
A
Arun Agrawal 已提交
375
        dbfile = abcs[Rails.env]['database'] || abcs[Rails.env]['dbfile']
376
        `sqlite3 #{dbfile} .schema > db/#{Rails.env}_structure.sql`
A
Arun Agrawal 已提交
377
      when 'sqlserver'
378
        `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f db\\#{Rails.env}_structure.sql -A -U`
379
      when "firebird"
380 381 382
        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"
383
      else
384
        raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'"
385 386
      end

387
      if ActiveRecord::Base.connection.supports_migrations?
388
        File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
389
      end
390
    end
391
  end
392

393
  namespace :test do
394
    # desc "Recreate the test database from the current schema.rb"
395
    task :load => 'db:test:purge' do
396
      ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
397
      ActiveRecord::Schema.verbose = false
A
Arun Agrawal 已提交
398
      db_namespace['schema:load'].invoke
399
    end
400

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

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

438
    # desc "Empty the test database"
439 440
    task :purge => :environment do
      abcs = ActiveRecord::Base.configurations
A
Arun Agrawal 已提交
441
      case abcs['test']['adapter']
J
Jeremy Kemper 已提交
442
      when /mysql/
443
        ActiveRecord::Base.establish_connection(:test)
444
        ActiveRecord::Base.connection.recreate_database(abcs['test']['database'], mysql_creation_options(abcs['test']))
445
      when /postgresql/
446
        ActiveRecord::Base.clear_active_connections!
447 448
        drop_database(abcs['test'])
        create_database(abcs['test'])
449
      when /sqlite/
A
Arun Agrawal 已提交
450
        dbfile = abcs['test']['database'] || abcs['test']['dbfile']
451
        File.delete(dbfile) if File.exist?(dbfile)
A
Arun Agrawal 已提交
452
      when 'sqlserver'
453 454 455 456 457
        test = abcs.deep_dup['test']
        test_database = test['database']
        test['database'] = 'master'
        ActiveRecord::Base.establish_connection(test)
        ActiveRecord::Base.connection.recreate_database!(test_database)
458
      when "oci", "oracle"
459 460 461 462
        ActiveRecord::Base.establish_connection(:test)
        ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
          ActiveRecord::Base.connection.execute(ddl)
        end
A
Arun Agrawal 已提交
463
      when 'firebird'
464 465 466
        ActiveRecord::Base.establish_connection(:test)
        ActiveRecord::Base.connection.recreate_database!
      else
A
Arun Agrawal 已提交
467
        raise "Task not supported by '#{abcs['test']['adapter']}'"
468 469
      end
    end
470

471
    # desc 'Check for pending migrations and load the test schema'
472
    task :prepare => 'db:abort_if_pending_migrations' do
473
      if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
A
Arun Agrawal 已提交
474
        db_namespace[{ :sql  => 'test:clone_structure', :ruby => 'test:load' }[ActiveRecord::Base.schema_format]].invoke
475
      end
476
    end
477 478
  end

479
  namespace :sessions do
480
    # desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
481
    task :create => :environment do
A
Arun Agrawal 已提交
482
      raise 'Task unavailable to this database (no migration support)' unless ActiveRecord::Base.connection.supports_migrations?
483
      Rails.application.load_generators
484
      require 'rails/generators/rails/session_migration/session_migration_generator'
A
Arun Agrawal 已提交
485
      Rails::Generators::SessionMigrationGenerator.start [ ENV['MIGRATION'] || 'add_sessions_table' ]
486 487
    end

488
    # desc "Clear the sessions table"
489
    task :clear => :environment do
490
      ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
491 492
    end
  end
493 494
end

495
namespace :railties do
496
  namespace :install do
497
    # desc "Copies missing migrations from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
A
Arun Agrawal 已提交
498 499
    task :migrations => :'db:load_config' do
      to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip }
500
      railties = ActiveSupport::OrderedHash.new
501 502 503
      Rails.application.railties.all do |railtie|
        next unless to_load == :all || to_load.include?(railtie.railtie_name)

A
Arun Agrawal 已提交
504
        if railtie.respond_to?(:paths) && (path = railtie.paths['db/migrate'].first)
505 506 507 508 509
          railties[railtie.railtie_name] = path
        end
      end

      on_skip = Proc.new do |name, migration|
510
        puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
511 512 513 514 515 516
      end

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

517
      ActiveRecord::Migration.copy( ActiveRecord::Migrator.migrations_paths.first, railties,
518 519 520
                                    :on_skip => on_skip, :on_copy => on_copy)
    end
  end
521 522
end

523 524
task 'test:prepare' => 'db:test:prepare'

525 526
def drop_database(config)
  case config['adapter']
J
Jeremy Kemper 已提交
527
  when /mysql/
528
    ActiveRecord::Base.establish_connection(config)
529
    ActiveRecord::Base.connection.drop_database config['database']
530
  when /sqlite/
531 532
    require 'pathname'
    path = Pathname.new(config['database'])
533
    file = path.absolute? ? path.to_s : File.join(Rails.root, path)
534 535

    FileUtils.rm(file)
536
  when /postgresql/
537
    ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
538
    ActiveRecord::Base.connection.drop_database config['database']
539 540 541
  end
end

542 543 544 545 546 547 548 549 550
def drop_database_and_rescue(config)
  begin
    drop_database(config)
  rescue Exception => e
    $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
  end
end

def configs_for_environment
551 552
  environments = [Rails.env]
  environments << 'test' if Rails.env.development?
553
  ActiveRecord::Base.configurations.values_at(*environments).compact.reject { |config| config['database'].blank? }
554 555
end

556
def session_table_name
557
  ActiveRecord::SessionStore::Session.table_name
558
end
J
Jeremy Kemper 已提交
559 560

def set_firebird_env(config)
A
Arun Agrawal 已提交
561 562
  ENV['ISC_USER']     = config['username'].to_s if config['username']
  ENV['ISC_PASSWORD'] = config['password'].to_s if config['password']
J
Jeremy Kemper 已提交
563 564 565 566
end

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