databases.rake 18.1 KB
Newer Older
1
require 'active_support/core_ext/object/inclusion'
2
require 'active_record'
3

4
db_namespace = namespace :db do
5
  task :load_config => :rails_env do
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
    task :all => :load_config do
P
Pat Allan 已提交
18
      ActiveRecord::Tasks::DatabaseTasks.create_all
19 20 21
    end
  end

22
  desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
23
  task :create => :load_config do
P
Pat Allan 已提交
24
    ActiveRecord::Tasks::DatabaseTasks.create_current
25
  end
26

27
  namespace :drop do
28
    task :all => :load_config do
P
Pat Allan 已提交
29
      ActiveRecord::Tasks::DatabaseTasks.drop_all
30 31
    end
  end
32

33
  desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
34
  task :drop => :load_config do
P
Pat Allan 已提交
35
    ActiveRecord::Tasks::DatabaseTasks.drop_current
36 37
  end

K
kennyj 已提交
38
  desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
39
  task :migrate => [:environment, :load_config] do
40
    ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
41 42 43
    ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) do |migration|
      ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope)
    end
A
Aaron Patterson 已提交
44 45 46 47 48 49 50 51 52 53
    db_namespace['_dump'].invoke
  end

  task :_dump do
    case ActiveRecord::Base.schema_format
    when :ruby then db_namespace["schema:dump"].invoke
    when :sql  then db_namespace["structure:dump"].invoke
    else
      raise "unknown schema format #{ActiveRecord::Base.schema_format}"
    end
54 55 56
    # Allow this task to be called as many times as required. An example is the
    # migrate:redo task, which calls other two internally that depend on this one.
    db_namespace['_dump'].reenable
57 58
  end

59
  namespace :migrate do
60
    # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
61
    task :redo => [:environment, :load_config] do
A
Arun Agrawal 已提交
62 63 64
      if ENV['VERSION']
        db_namespace['migrate:down'].invoke
        db_namespace['migrate:up'].invoke
65
      else
A
Arun Agrawal 已提交
66 67
        db_namespace['rollback'].invoke
        db_namespace['migrate'].invoke
68 69
      end
    end
70

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

74
    # desc 'Runs the "up" for a given migration VERSION.'
75
    task :up => [:environment, :load_config] do
A
Arun Agrawal 已提交
76 77
      version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
      raise 'VERSION is required' unless version
78
      ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version)
A
Aaron Patterson 已提交
79
      db_namespace['_dump'].invoke
80 81
    end

82
    # desc 'Runs the "down" for a given migration VERSION.'
83
    task :down => [:environment, :load_config] do
A
Arun Agrawal 已提交
84 85
      version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
      raise 'VERSION is required' unless version
86
      ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version)
A
Aaron Patterson 已提交
87
      db_namespace['_dump'].invoke
88
    end
89

A
Arun Agrawal 已提交
90
    desc 'Display status of migrations'
91
    task :status => [:environment, :load_config] do
92
      config = ActiveRecord::Base.configurations[Rails.env || 'development']
93 94 95 96 97
      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
98
      db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
99
      db_list.map! { |version| "%.3d" % version }
100
      file_list = []
101 102
      ActiveRecord::Migrator.migrations_paths.each do |path|
        Dir.foreach(path) do |file|
103 104
          # match "20091231235959_some_name.rb" and "001_some_name.rb" pattern
          if match_data = /^(\d{3,})_(.+)\.rb$/.match(file)
105 106 107
            status = db_list.delete(match_data[1]) ? 'up' : 'down'
            file_list << [status, match_data[1], match_data[2].humanize]
          end
108 109
        end
      end
110 111 112
      db_list.map! do |version|
        ['up', version, '********** NO FILE **********']
      end
113 114
      # output
      puts "\ndatabase: #{config['database']}\n\n"
A
Arun Agrawal 已提交
115
      puts "#{'Status'.center(8)}  #{'Migration ID'.ljust(14)}  Migration Name"
116
      puts "-" * 50
117 118
      (db_list + file_list).sort_by {|migration| migration[1]}.each do |migration|
        puts "#{migration[0].center(8)}  #{migration[1].ljust(14)}  #{migration[2]}"
119 120 121
      end
      puts
    end
122 123
  end

124
  desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
125
  task :rollback => [:environment, :load_config] do
126
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
127
    ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
A
Aaron Patterson 已提交
128
    db_namespace['_dump'].invoke
129 130
  end

131
  # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
132
  task :forward => [:environment, :load_config] do
133
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
134
    ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step)
A
Aaron Patterson 已提交
135
    db_namespace['_dump'].invoke
136 137
  end

138
  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
139
  task :reset => [:environment, :load_config] do
140 141 142
    db_namespace["drop"].invoke
    db_namespace["setup"].invoke
  end
143

144
  # desc "Retrieves the charset for the current environment's database"
145
  task :charset => [:environment, :load_config] do
S
Simon Jefford 已提交
146
    puts ActiveRecord::Tasks::DatabaseTasks.charset_current
147 148
  end

149
  # desc "Retrieves the collation for the current environment's database"
150
  task :collation => [:environment, :load_config] do
151 152 153 154 155
    begin
      puts ActiveRecord::Tasks::DatabaseTasks.collation_current
    rescue NoMethodError
      $stderr.puts 'Sorry, your database adapter is not supported yet, feel free to submit a patch'
    end
156
  end
157

A
Arun Agrawal 已提交
158
  desc 'Retrieves the current schema version number'
159
  task :version => [:environment, :load_config] do
160
    puts "Current version: #{ActiveRecord::Migrator.current_version}"
161 162
  end

163
  # desc "Raises an error if there are pending migrations"
164
  task :abort_if_pending_migrations => [:environment, :load_config] do
165
    pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
166

167 168 169 170
    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]
171
      end
172
      abort %{Run `rake db:migrate` to update your database then try again.}
173 174 175
    end
  end

176
  desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)'
177
  task :setup => ['db:schema:load_if_ruby', 'db:structure:load_if_sql', :seed]
178 179

  desc 'Load the seed data from db/seeds.rb'
180
  task :seed do
181
    db_namespace['abort_if_pending_migrations'].invoke
182
    Rails.application.load_seed
183 184
  end

185
  namespace :fixtures do
186
    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."
187
    task :load => [:environment, :load_config] do
188 189
      require 'active_record/fixtures'

190
      ActiveRecord::Base.establish_connection(Rails.env)
191
      base_dir     = File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
192
      fixtures_dir = File.join [base_dir, ENV['FIXTURES_DIR']].compact
193

194
      (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
J
Jason Noble 已提交
195
        ActiveRecord::Fixtures.create_fixtures(fixtures_dir, fixture_file)
196 197
      end
    end
198

199
    # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
200
    task :identify => [:environment, :load_config] do
201 202
      require 'active_record/fixtures'

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

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

208 209
      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|
210 211
        if data = YAML::load(ERB.new(IO.read(file)).result)
          data.keys.each do |key|
J
Jason Noble 已提交
212
            key_id = ActiveRecord::Fixtures.identify(key)
213

214 215 216 217 218 219 220
            if key == label || key_id == id.to_i
              puts "#{file}: #{key} (#{key_id})"
            end
          end
        end
      end
    end
221
  end
222

223
  namespace :schema do
A
Arun Agrawal 已提交
224
    desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR'
225
    task :dump => [:environment, :load_config] do
226
      require 'active_record/schema_dumper'
227 228
      filename = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
      File.open(filename, "w:utf-8") do |file|
229
        ActiveRecord::Base.establish_connection(Rails.env)
230 231
        ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
      end
A
Arun Agrawal 已提交
232
      db_namespace['schema:dump'].reenable
233
    end
234

A
Arun Agrawal 已提交
235
    desc 'Load a schema.rb file into the database'
236
    task :load => [:environment, :load_config] do
237
      file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
238 239 240
      if File.exists?(file)
        load(file)
      else
C
Cyril Wack 已提交
241
        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}
242
      end
243
    end
244 245 246 247

    task :load_if_ruby => 'db:create' do
      db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
    end
248 249 250

    namespace :cache do
      desc 'Create a db/schema_cache.dump file.'
251
      task :dump => [:environment, :load_config] do
252 253 254 255 256 257 258 259 260
        con = ActiveRecord::Base.connection
        filename = File.join(Rails.application.config.paths["db"].first, "schema_cache.dump")

        con.schema_cache.clear!
        con.tables.each { |table| con.schema_cache.add(table) }
        open(filename, 'wb') { |f| f.write(Marshal.dump(con.schema_cache)) }
      end

      desc 'Clear a db/schema_cache.dump file.'
261
      task :clear => [:environment, :load_config] do
262 263 264 265 266
        filename = File.join(Rails.application.config.paths["db"].first, "schema_cache.dump")
        FileUtils.rm(filename) if File.exists?(filename)
      end
    end

267 268
  end

269
  namespace :structure do
270 271 272 273
    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
274

275 276 277 278
    def firebird_db_string(config)
      FireRuby::Database.db_string_for(config.symbolize_keys)
    end

V
Vijay Dev 已提交
279
    desc 'Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql'
280
    task :dump => [:environment, :load_config] do
281
      abcs = ActiveRecord::Base.configurations
282
      filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql")
A
Arun Agrawal 已提交
283
      case abcs[Rails.env]['adapter']
K
kennyj 已提交
284 285 286
      when /mysql/, /postgresql/, /sqlite/
        ActiveRecord::Tasks::DatabaseTasks.structure_dump(abcs[Rails.env], filename)
      when 'oci', 'oracle'
287
        ActiveRecord::Base.establish_connection(abcs[Rails.env])
288
        File.open(filename, "w:utf-8") { |f| f << ActiveRecord::Base.connection.structure_dump }
A
Arun Agrawal 已提交
289
      when 'sqlserver'
290
        `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f #{filename} -A -U`
291
      when "firebird"
292 293
        set_firebird_env(abcs[Rails.env])
        db_string = firebird_db_string(abcs[Rails.env])
294
        sh "isql -a #{db_string} > #{filename}"
295
      else
296
        raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'"
297 298
      end

299
      if ActiveRecord::Base.connection.supports_migrations?
300
        File.open(filename, "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
301
      end
302
      db_namespace['structure:dump'].reenable
303
    end
304

305 306 307
    # desc "Recreate the databases from the structure.sql file"
    task :load => [:environment, :load_config] do
      env = ENV['RAILS_ENV'] || 'test'
308

309
      abcs = ActiveRecord::Base.configurations
310
      filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql")
311
      case abcs[env]['adapter']
K
kennyj 已提交
312
      when /mysql/, /postgresql/, /sqlite/
313
        ActiveRecord::Tasks::DatabaseTasks.structure_load(abcs[env], filename)
A
Arun Agrawal 已提交
314
      when 'sqlserver'
315
        `sqlcmd -S #{abcs[env]['host']} -d #{abcs[env]['database']} -U #{abcs[env]['username']} -P #{abcs[env]['password']} -i #{filename}`
A
Arun Agrawal 已提交
316
      when 'oci', 'oracle'
317
        ActiveRecord::Base.establish_connection(abcs[env])
318
        IO.read(filename).split(";\n\n").each do |ddl|
319 320
          ActiveRecord::Base.connection.execute(ddl)
        end
A
Arun Agrawal 已提交
321
      when 'firebird'
322 323
        set_firebird_env(abcs[env])
        db_string = firebird_db_string(abcs[env])
324
        sh "isql -i #{filename} #{db_string}"
325
      else
326
        raise "Task not supported by '#{abcs[env]['adapter']}'"
327 328
      end
    end
329 330 331 332

    task :load_if_sql => 'db:create' do
      db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
    end
333 334 335
  end

  namespace :test do
336 337

    # desc "Recreate the test database from the current schema"
338
    task :load => 'db:test:purge' do
339 340 341 342 343
      case ActiveRecord::Base.schema_format
        when :ruby
          db_namespace["test:load_schema"].invoke
        when :sql
          db_namespace["test:load_structure"].invoke
344
      end
345
    end
346

347 348 349 350 351 352 353
    # desc "Recreate the test database from an existent schema.rb file"
    task :load_schema => 'db:test:purge' do
      ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
      ActiveRecord::Schema.verbose = false
      db_namespace["schema:load"].invoke
    end

354 355
    # desc "Recreate the test database from an existent structure.sql file"
    task :load_structure => 'db:test:purge' do
356 357
      begin
        old_env, ENV['RAILS_ENV'] = ENV['RAILS_ENV'], 'test'
358
        db_namespace["structure:load"].invoke
359 360 361
      ensure
        ENV['RAILS_ENV'] = old_env
      end
362
    end
363

364 365 366 367 368 369 370 371 372 373
    # desc "Recreate the test database from a fresh schema"
    task :clone do
      case ActiveRecord::Base.schema_format
        when :ruby
          db_namespace["test:clone_schema"].invoke
        when :sql
          db_namespace["test:clone_structure"].invoke
      end
    end

374
    # desc "Recreate the test database from a fresh schema.rb file"
375
    task :clone_schema => ["db:schema:dump", "db:test:load_schema"]
376

377 378
    # desc "Recreate the test database from a fresh structure.sql file"
    task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ]
379

380
    # desc "Empty the test database"
381
    task :purge => [:environment, :load_config] do
382
      abcs = ActiveRecord::Base.configurations
A
Arun Agrawal 已提交
383
      case abcs['test']['adapter']
P
Pat Allan 已提交
384 385
      when /mysql/, /postgresql/, /sqlite/
        ActiveRecord::Tasks::DatabaseTasks.purge abcs['test']
A
Arun Agrawal 已提交
386
      when 'sqlserver'
387 388 389 390 391
        test = abcs.deep_dup['test']
        test_database = test['database']
        test['database'] = 'master'
        ActiveRecord::Base.establish_connection(test)
        ActiveRecord::Base.connection.recreate_database!(test_database)
392
      when "oci", "oracle"
393 394 395 396
        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 已提交
397
      when 'firebird'
398 399 400
        ActiveRecord::Base.establish_connection(:test)
        ActiveRecord::Base.connection.recreate_database!
      else
A
Arun Agrawal 已提交
401
        raise "Task not supported by '#{abcs['test']['adapter']}'"
402 403
      end
    end
404

405
    # desc 'Check for pending migrations and load the test schema'
406
    task :prepare => 'db:abort_if_pending_migrations' do
407
      unless ActiveRecord::Base.configurations.blank?
408
        db_namespace['test:load'].invoke
409
      end
410
    end
411 412
  end

413
  namespace :sessions do
414
    # desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
415
    task :create => [:environment, :load_config] do
A
Arun Agrawal 已提交
416
      raise 'Task unavailable to this database (no migration support)' unless ActiveRecord::Base.connection.supports_migrations?
417
      Rails.application.load_generators
418
      require 'rails/generators/rails/session_migration/session_migration_generator'
A
Arun Agrawal 已提交
419
      Rails::Generators::SessionMigrationGenerator.start [ ENV['MIGRATION'] || 'add_sessions_table' ]
420 421
    end

422
    # desc "Clear the sessions table"
423
    task :clear => [:environment, :load_config] do
424
      ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::SessionStore::Session.table_name}"
425 426
    end
  end
427 428
end

429
namespace :railties do
430
  namespace :install do
S
Santiago Pastorino 已提交
431
    # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2"
A
Arun Agrawal 已提交
432 433
    task :migrations => :'db:load_config' do
      to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip }
R
Raghunadh 已提交
434
      railties = {}
435
      Rails.application.railties.each do |railtie|
436 437
        next unless to_load == :all || to_load.include?(railtie.railtie_name)

A
Arun Agrawal 已提交
438
        if railtie.respond_to?(:paths) && (path = railtie.paths['db/migrate'].first)
439 440 441 442 443
          railties[railtie.railtie_name] = path
        end
      end

      on_skip = Proc.new do |name, migration|
444
        puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
445 446 447 448 449 450
      end

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

451
      ActiveRecord::Migration.copy( ActiveRecord::Migrator.migrations_paths.first, railties,
452 453 454
                                    :on_skip => on_skip, :on_copy => on_copy)
    end
  end
455 456
end

457 458
task 'test:prepare' => 'db:test:prepare'