databases.rake 15.4 KB
Newer Older
1
require 'active_record'
2

3
db_namespace = namespace :db do
4
  task :load_config do
5
    ActiveRecord::Base.configurations       = ActiveRecord::Tasks::DatabaseTasks.database_configuration || {}
6
    ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
7 8
  end

9
  namespace :create do
10
    task :all => :load_config do
11
      ActiveRecord::Tasks::DatabaseTasks.create_all
12 13 14
    end
  end

15
  desc 'Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV it defaults to creating the development and test databases.'
16
  task :create => [:load_config] do
17
    ActiveRecord::Tasks::DatabaseTasks.create_current
18
  end
19

20
  namespace :drop do
21
    task :all => :load_config do
22
      ActiveRecord::Tasks::DatabaseTasks.drop_all
23 24
    end
  end
25

26
  desc 'Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to dropping the development and test databases.'
27
  task :drop => [:load_config] do
28
    ActiveRecord::Tasks::DatabaseTasks.drop_current
29 30
  end

K
kennyj 已提交
31
  desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
32
  task :migrate => [:environment, :load_config] do
33
    ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
34 35 36
    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 已提交
37 38 39 40 41 42 43 44 45 46
    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
47 48 49
    # 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
50 51
  end

52
  namespace :migrate do
53
    # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
54
    task :redo => [:environment, :load_config] do
A
Arun Agrawal 已提交
55 56 57
      if ENV['VERSION']
        db_namespace['migrate:down'].invoke
        db_namespace['migrate:up'].invoke
58
      else
A
Arun Agrawal 已提交
59 60
        db_namespace['rollback'].invoke
        db_namespace['migrate'].invoke
61 62
      end
    end
63

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

67
    # desc 'Runs the "up" for a given migration VERSION.'
68
    task :up => [:environment, :load_config] do
A
Arun Agrawal 已提交
69 70
      version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
      raise 'VERSION is required' unless version
71
      ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version)
A
Aaron Patterson 已提交
72
      db_namespace['_dump'].invoke
73 74
    end

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

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

115
  desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
116
  task :rollback => [:environment, :load_config] do
117
    step = ENV['STEP'] ? ENV['STEP'].to_i : 1
118
    ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
A
Aaron Patterson 已提交
119
    db_namespace['_dump'].invoke
120 121
  end

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

129
  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
130
  task :reset => [:environment, :load_config] do
131 132 133
    db_namespace["drop"].invoke
    db_namespace["setup"].invoke
  end
134

135
  # desc "Retrieves the charset for the current environment's database"
136
  task :charset => [:environment, :load_config] do
S
Simon Jefford 已提交
137
    puts ActiveRecord::Tasks::DatabaseTasks.charset_current
138 139
  end

140
  # desc "Retrieves the collation for the current environment's database"
141
  task :collation => [:environment, :load_config] do
142 143 144
    begin
      puts ActiveRecord::Tasks::DatabaseTasks.collation_current
    rescue NoMethodError
145
      $stderr.puts 'Sorry, your database adapter is not supported yet. Feel free to submit a patch.'
146
    end
147
  end
148

A
Arun Agrawal 已提交
149
  desc 'Retrieves the current schema version number'
150
  task :version => [:environment, :load_config] do
151
    puts "Current version: #{ActiveRecord::Migrator.current_version}"
152 153
  end

154
  # desc "Raises an error if there are pending migrations"
155
  task :abort_if_pending_migrations => :environment do
156
    pending_migrations = ActiveRecord::Migrator.open(ActiveRecord::Migrator.migrations_paths).pending_migrations
157

158
    if pending_migrations.any?
159
      puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}"
160 161
      pending_migrations.each do |pending_migration|
        puts '  %4d %s' % [pending_migration.version, pending_migration.name]
162
      end
163
      abort %{Run `rake db:migrate` to update your database then try again.}
164 165 166
    end
  end

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

  desc 'Load the seed data from db/seeds.rb'
171
  task :seed do
172
    db_namespace['abort_if_pending_migrations'].invoke
173
    ActiveRecord::Tasks::DatabaseTasks.load_seed
174 175
  end

176
  namespace :fixtures do
177
    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."
178
    task :load => [:environment, :load_config] do
179 180
      require 'active_record/fixtures'

181 182 183 184 185 186
      base_dir = if ENV['FIXTURES_PATH']
        File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
      else
        ActiveRecord::Tasks::DatabaseTasks.fixtures_path
      end

187
      fixtures_dir = File.join [base_dir, ENV['FIXTURES_DIR']].compact
188

189
      (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
190
        ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_file)
191 192
      end
    end
193

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

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

201
      puts %Q(The fixture ID for "#{label}" is #{ActiveRecord::FixtureSet.identify(label)}.) if label
202

203 204 205 206 207 208 209
      base_dir = if ENV['FIXTURES_PATH']
        File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
      else
        ActiveRecord::Tasks::DatabaseTasks.fixtures_path
      end


210
      Dir["#{base_dir}/**/*.yml"].each do |file|
211 212
        if data = YAML::load(ERB.new(IO.read(file)).result)
          data.keys.each do |key|
213
            key_id = ActiveRecord::FixtureSet.identify(key)
214

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

224
  namespace :schema do
225
    desc 'Create a db/schema.rb file that is portable against any DB supported by AR'
226
    task :dump => [:environment, :load_config] do
227
      require 'active_record/schema_dumper'
228
      filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb')
229
      File.open(filename, "w:utf-8") do |file|
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
      ActiveRecord::Tasks::DatabaseTasks.load_schema(:ruby, ENV['SCHEMA'])
238
    end
239

240
    task :load_if_ruby => ['db:create', :environment] do
241 242
      db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
    end
243 244 245

    namespace :cache do
      desc 'Create a db/schema_cache.dump file.'
246
      task :dump => [:environment, :load_config] do
247
        con = ActiveRecord::Base.connection
248
        filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
249 250 251 252 253 254 255

        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.'
256
      task :clear => [:environment, :load_config] do
257
        filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
A
Arun Agrawal 已提交
258
        FileUtils.rm(filename) if File.exist?(filename)
259 260 261
      end
    end

262 263
  end

264
  namespace :structure do
V
Vijay Dev 已提交
265
    desc 'Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql'
266
    task :dump => [:environment, :load_config] do
267
      filename = ENV['DB_STRUCTURE'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql")
268
      current_config = ActiveRecord::Tasks::DatabaseTasks.current_config
K
kennyj 已提交
269
      ActiveRecord::Tasks::DatabaseTasks.structure_dump(current_config, filename)
270

271
      if ActiveRecord::Base.connection.supports_migrations?
272 273
        File.open(filename, "a") do |f|
          f.puts ActiveRecord::Base.connection.dump_schema_information
C
Chad Jolly 已提交
274
          f.print "\n"
275
        end
276
      end
277
      db_namespace['structure:dump'].reenable
278
    end
279

280 281
    # desc "Recreate the databases from the structure.sql file"
    task :load => [:environment, :load_config] do
282
      ActiveRecord::Tasks::DatabaseTasks.load_schema(:sql, ENV['DB_STRUCTURE'])
283
    end
284

285
    task :load_if_sql => ['db:create', :environment] do
286 287
      db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
    end
288 289 290
  end

  namespace :test do
291

292 293 294 295 296 297 298
    task :deprecated do
      Rake.application.top_level_tasks.grep(/^db:test:/).each do |task|
        $stderr.puts "WARNING: #{task} is deprecated. The Rails test helper now maintains " \
                     "your test schema automatically, see the release notes for details."
      end
    end

299
    # desc "Recreate the test database from the current schema"
300
    task :load => %w(db:test:deprecated db:test:purge) do
301 302 303 304 305
      case ActiveRecord::Base.schema_format
        when :ruby
          db_namespace["test:load_schema"].invoke
        when :sql
          db_namespace["test:load_structure"].invoke
306
      end
307
    end
308

309
    # desc "Recreate the test database from an existent schema.rb file"
310
    task :load_schema => %w(db:test:deprecated db:test:purge) do
311
      begin
312
        should_reconnect = ActiveRecord::Base.connection_pool.active_connection?
313 314 315 316
        ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
        ActiveRecord::Schema.verbose = false
        db_namespace["schema:load"].invoke
      ensure
317 318 319
        if should_reconnect
          ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env])
        end
320
      end
321 322
    end

323
    # desc "Recreate the test database from an existent structure.sql file"
324
    task :load_structure => %w(db:test:deprecated db:test:purge) do
325
      begin
326
        ActiveRecord::Tasks::DatabaseTasks.current_config(:config => ActiveRecord::Base.configurations['test'])
327
        db_namespace["structure:load"].invoke
328
      ensure
329
        ActiveRecord::Tasks::DatabaseTasks.current_config(:config => nil)
330
      end
331
    end
332

333
    # desc "Recreate the test database from a fresh schema"
334
    task :clone => %w(db:test:deprecated environment) do
335 336 337 338 339 340 341 342
      case ActiveRecord::Base.schema_format
        when :ruby
          db_namespace["test:clone_schema"].invoke
        when :sql
          db_namespace["test:clone_structure"].invoke
      end
    end

343
    # desc "Recreate the test database from a fresh schema.rb file"
344
    task :clone_schema => %w(db:test:deprecated db:schema:dump db:test:load_schema)
345

346
    # desc "Recreate the test database from a fresh structure.sql file"
347
    task :clone_structure => %w(db:test:deprecated db:structure:dump db:test:load_structure)
348

349
    # desc "Empty the test database"
350
    task :purge => %w(db:test:deprecated environment load_config) do
K
kennyj 已提交
351
      ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations['test']
352
    end
353

354
    # desc 'Check for pending migrations and load the test schema'
355
    task :prepare => %w(db:test:deprecated environment load_config) do
356
      unless ActiveRecord::Base.configurations.blank?
357
        db_namespace['test:load'].invoke
358
      end
359
    end
360 361 362
  end
end

363
namespace :railties do
364
  namespace :install do
S
Santiago Pastorino 已提交
365
    # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2"
A
Arun Agrawal 已提交
366 367
    task :migrations => :'db:load_config' do
      to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip }
R
Raghunadh 已提交
368
      railties = {}
369
      Rails.application.railties.each do |railtie|
370 371
        next unless to_load == :all || to_load.include?(railtie.railtie_name)

A
Arun Agrawal 已提交
372
        if railtie.respond_to?(:paths) && (path = railtie.paths['db/migrate'].first)
373 374 375 376 377
          railties[railtie.railtie_name] = path
        end
      end

      on_skip = Proc.new do |name, migration|
378
        puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
379 380
      end

381
      on_copy = Proc.new do |name, migration|
382 383 384
        puts "Copied migration #{migration.basename} from #{name}"
      end

385
      ActiveRecord::Migration.copy(ActiveRecord::Migrator.migrations_paths.first, railties,
386 387 388
                                    :on_skip => on_skip, :on_copy => on_copy)
    end
  end
389
end