databases.rake 14.1 KB
Newer Older
1 2
# frozen_string_literal: true

3
require "active_record"
4

5
db_namespace = namespace :db do
6
  desc "Set the environment value for the database"
7
  task "environment:set" => :load_config do
8
    ActiveRecord::InternalMetadata.create_table
9
    ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Base.connection.migration_context.current_environment
10 11
  end

12
  task check_protected_environments: :load_config do
13 14 15
    ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!
  end

16
  task load_config: :environment do
17
    ActiveRecord::Base.configurations       = ActiveRecord::Tasks::DatabaseTasks.database_configuration || {}
18
    ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
19 20
  end

21
  namespace :create do
22
    task all: :load_config do
23
      ActiveRecord::Tasks::DatabaseTasks.create_all
24 25 26
    end
  end

27
  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 or when RAILS_ENV is development, it defaults to creating the development and test databases."
28
  task create: [:load_config] do
29
    ActiveRecord::Tasks::DatabaseTasks.create_current
30
  end
31

32
  namespace :drop do
33
    task all: [:load_config, :check_protected_environments] do
34
      ActiveRecord::Tasks::DatabaseTasks.drop_all
35 36
    end
  end
37

38
  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 or when RAILS_ENV is development, it defaults to dropping the development and test databases."
39
  task drop: [:load_config, :check_protected_environments] do
40 41 42 43
    db_namespace["drop:_unsafe"].invoke
  end

  task "drop:_unsafe" => [:load_config] do
44
    ActiveRecord::Tasks::DatabaseTasks.drop_current
45 46
  end

47
  namespace :purge do
48
    task all: [:load_config, :check_protected_environments] do
49 50 51 52
      ActiveRecord::Tasks::DatabaseTasks.purge_all
    end
  end

53
  # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:purge:all to purge all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
54
  task purge: [:load_config, :check_protected_environments] do
55 56 57
    ActiveRecord::Tasks::DatabaseTasks.purge_current
  end

K
kennyj 已提交
58
  desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
59
  task migrate: :load_config do
60
    ActiveRecord::Tasks::DatabaseTasks.migrate
61
    db_namespace["_dump"].invoke
A
Aaron Patterson 已提交
62 63
  end

64
  # IMPORTANT: This task won't dump the schema if ActiveRecord::Base.dump_schema_after_migration is set to false
A
Aaron Patterson 已提交
65
  task :_dump do
66 67 68 69 70 71 72
    if ActiveRecord::Base.dump_schema_after_migration
      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
A
Aaron Patterson 已提交
73
    end
74 75
    # 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.
76
    db_namespace["_dump"].reenable
77 78
  end

79
  namespace :migrate do
80
    # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
81
    task redo: :load_config do
P
Philippe Guay 已提交
82 83
      raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty?

84 85 86
      if ENV["VERSION"]
        db_namespace["migrate:down"].invoke
        db_namespace["migrate:up"].invoke
87
      else
88 89
        db_namespace["rollback"].invoke
        db_namespace["migrate"].invoke
90 91
      end
    end
92

93
    # desc 'Resets your database using your migrations for the current environment'
94
    task reset: ["db:drop", "db:create", "db:migrate"]
95

96
    # desc 'Runs the "up" for a given migration VERSION.'
97
    task up: :load_config do
98
      raise "VERSION is required" if !ENV["VERSION"] || ENV["VERSION"].empty?
P
Philippe Guay 已提交
99

100 101
      ActiveRecord::Tasks::DatabaseTasks.check_target_version

102
      ActiveRecord::Base.connection.migration_context.run(
103 104 105
        :up,
        ActiveRecord::Tasks::DatabaseTasks.target_version
      )
106
      db_namespace["_dump"].invoke
107 108
    end

109
    # desc 'Runs the "down" for a given migration VERSION.'
110
    task down: :load_config do
111
      raise "VERSION is required - To go down one migration, use db:rollback" if !ENV["VERSION"] || ENV["VERSION"].empty?
112 113 114

      ActiveRecord::Tasks::DatabaseTasks.check_target_version

115
      ActiveRecord::Base.connection.migration_context.run(
116 117 118
        :down,
        ActiveRecord::Tasks::DatabaseTasks.target_version
      )
119
      db_namespace["_dump"].invoke
120
    end
121

122
    desc "Display status of migrations"
123
    task status: :load_config do
124
      unless ActiveRecord::SchemaMigration.table_exists?
125
        abort "Schema migrations table does not exist yet."
126
      end
127

128
      # output
129
      puts "\ndatabase: #{ActiveRecord::Base.connection_config[:database]}\n\n"
A
Arun Agrawal 已提交
130
      puts "#{'Status'.center(8)}  #{'Migration ID'.ljust(14)}  Migration Name"
131
      puts "-" * 50
132
      ActiveRecord::Base.connection.migration_context.migrations_status.each do |status, version, name|
133
        puts "#{status.center(8)}  #{version.ljust(14)}  #{name}"
134 135 136
      end
      puts
    end
137 138
  end

139
  desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)."
140
  task rollback: :load_config do
141
    step = ENV["STEP"] ? ENV["STEP"].to_i : 1
142
    ActiveRecord::Base.connection.migration_context.rollback(step)
143
    db_namespace["_dump"].invoke
144 145
  end

146
  # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
147
  task forward: :load_config do
148
    step = ENV["STEP"] ? ENV["STEP"].to_i : 1
149
    ActiveRecord::Base.connection.migration_context.forward(step)
150
    db_namespace["_dump"].invoke
151 152
  end

153
  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
154
  task reset: [ "db:drop", "db:setup" ]
155

156
  # desc "Retrieves the charset for the current environment's database"
157
  task charset: :load_config do
S
Simon Jefford 已提交
158
    puts ActiveRecord::Tasks::DatabaseTasks.charset_current
159 160
  end

161
  # desc "Retrieves the collation for the current environment's database"
162
  task collation: :load_config do
163 164 165
    begin
      puts ActiveRecord::Tasks::DatabaseTasks.collation_current
    rescue NoMethodError
166
      $stderr.puts "Sorry, your database adapter is not supported yet. Feel free to submit a patch."
167
    end
168
  end
169

170
  desc "Retrieves the current schema version number"
171
  task version: :load_config do
172
    puts "Current version: #{ActiveRecord::Base.connection.migration_context.current_version}"
173 174
  end

175
  # desc "Raises an error if there are pending migrations"
176
  task abort_if_pending_migrations: :load_config do
177
    pending_migrations = ActiveRecord::Base.connection.migration_context.open.pending_migrations
178

179
    if pending_migrations.any?
180
      puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}"
181
      pending_migrations.each do |pending_migration|
182
        puts "  %4d %s" % [pending_migration.version, pending_migration.name]
183
      end
184
      abort %{Run `rails db:migrate` to update your database then try again.}
185 186 187
    end
  end

188
  desc "Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)"
189
  task setup: ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed]
190

191
  desc "Loads the seed data from db/seeds.rb"
192
  task :seed do
193
    db_namespace["abort_if_pending_migrations"].invoke
194
    ActiveRecord::Tasks::DatabaseTasks.load_seed
195 196
  end

197
  namespace :fixtures do
198
    desc "Loads 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."
199
    task load: :load_config do
200
      require "active_record/fixtures"
201

202
      base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path
203

204
      fixtures_dir = if ENV["FIXTURES_DIR"]
205
        File.join base_dir, ENV["FIXTURES_DIR"]
206 207 208
      else
        base_dir
      end
209

210
      fixture_files = if ENV["FIXTURES"]
211
        ENV["FIXTURES"].split(",")
212 213
      else
        # The use of String#[] here is to support namespaced fixtures.
214
        Dir["#{fixtures_dir}/**/*.yml"].map { |f| f[(fixtures_dir.size + 1)..-5] }
215
      end
216

217
      ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_files)
218
    end
219

220
    # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
221
    task identify: :load_config do
222
      require "active_record/fixtures"
223

224 225
      label, id = ENV["LABEL"], ENV["ID"]
      raise "LABEL or ID required" if label.blank? && id.blank?
226

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

229
      base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path
230

231
      Dir["#{base_dir}/**/*.yml"].each do |file|
E
eileencodes 已提交
232
        if data = YAML.load(ERB.new(IO.read(file)).result)
233
          data.each_key do |key|
234
            key_id = ActiveRecord::FixtureSet.identify(key)
235

236 237 238 239 240 241 242
            if key == label || key_id == id.to_i
              puts "#{file}: #{key} (#{key_id})"
            end
          end
        end
      end
    end
243
  end
244

245
  namespace :schema do
246
    desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record"
247
    task dump: :load_config do
248
      require "active_record/schema_dumper"
249
      filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema.rb")
250
      File.open(filename, "w:utf-8") do |file|
251 252
        ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
      end
253
      db_namespace["schema:dump"].reenable
254
    end
255

256
    desc "Loads a schema.rb file into the database"
257
    task load: [:load_config, :check_protected_environments] do
258
      ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV["SCHEMA"])
259
    end
260

261
    task load_if_ruby: ["db:create", :environment] do
262 263
      db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
    end
264 265

    namespace :cache do
K
Kir Shatrov 已提交
266
      desc "Creates a db/schema_cache.yml file."
267
      task dump: :load_config do
K
Kir Shatrov 已提交
268 269
        conn = ActiveRecord::Base.connection
        filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.yml")
270
        ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(conn, filename)
271 272
      end

K
Kir Shatrov 已提交
273
      desc "Clears a db/schema_cache.yml file."
274
      task clear: :load_config do
K
Kir Shatrov 已提交
275
        filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.yml")
276
        rm_f filename, verbose: false
277 278 279
      end
    end

280 281
  end

282
  namespace :structure do
283
    desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql"
284
    task dump: :load_config do
285
      filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql")
286
      current_config = ActiveRecord::Tasks::DatabaseTasks.current_config
K
kennyj 已提交
287
      ActiveRecord::Tasks::DatabaseTasks.structure_dump(current_config, filename)
288

289
      if ActiveRecord::SchemaMigration.table_exists?
290 291
        File.open(filename, "a") do |f|
          f.puts ActiveRecord::Base.connection.dump_schema_information
C
Chad Jolly 已提交
292
          f.print "\n"
293
        end
294
      end
295
      db_namespace["structure:dump"].reenable
296
    end
297

298
    desc "Recreates the databases from the structure.sql file"
299
    task load: [:load_config, :check_protected_environments] do
300
      ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, ENV["SCHEMA"])
301
    end
302

303
    task load_if_sql: ["db:create", :environment] do
304 305
      db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
    end
306 307 308
  end

  namespace :test do
309
    # desc "Recreate the test database from the current schema"
310
    task load: %w(db:test:purge) do
311
      case ActiveRecord::Base.schema_format
312 313 314 315
      when :ruby
        db_namespace["test:load_schema"].invoke
      when :sql
        db_namespace["test:load_structure"].invoke
316
      end
317
    end
318

319
    # desc "Recreate the test database from an existent schema.rb file"
320
    task load_schema: %w(db:test:purge) do
321
      begin
322
        should_reconnect = ActiveRecord::Base.connection_pool.active_connection?
323
        ActiveRecord::Schema.verbose = false
324
        ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :ruby, ENV["SCHEMA"], "test"
325
      ensure
326 327 328
        if should_reconnect
          ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env])
        end
329
      end
330 331
    end

332
    # desc "Recreate the test database from an existent structure.sql file"
333
    task load_structure: %w(db:test:purge) do
334
      ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"], "test"
335
    end
336

337
    # desc "Empty the test database"
338
    task purge: %w(load_config check_protected_environments) do
339
      ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations["test"]
340
    end
341

B
Brandon Conway 已提交
342
    # desc 'Load the test schema'
343
    task prepare: :load_config do
344
      unless ActiveRecord::Base.configurations.blank?
345
        db_namespace["test:load"].invoke
346
      end
347
    end
348 349 350
  end
end

351
namespace :railties do
352
  namespace :install do
S
Santiago Pastorino 已提交
353
    # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2"
354
    task migrations: :'db:load_config' do
355
      to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map(&:strip)
R
Raghunadh 已提交
356
      railties = {}
357
      Rails.application.migration_railties.each do |railtie|
358 359
        next unless to_load == :all || to_load.include?(railtie.railtie_name)

360
        if railtie.respond_to?(:paths) && (path = railtie.paths["db/migrate"].first)
361 362 363 364 365
          railties[railtie.railtie_name] = path
        end
      end

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

369
      on_copy = Proc.new do |name, migration|
370 371 372
        puts "Copied migration #{migration.basename} from #{name}"
      end

373
      ActiveRecord::Migration.copy(ActiveRecord::Tasks::DatabaseTasks.migrations_paths.first, railties,
374
                                    on_skip: on_skip, on_copy: on_copy)
375 376
    end
  end
377
end