database_tasks.rb 18.6 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
require "active_record/database_configurations"

5 6
module ActiveRecord
  module Tasks # :nodoc:
7
    class DatabaseNotSupported < StandardError; end # :nodoc:
8

9
    # ActiveRecord::Tasks::DatabaseTasks is a utility class, which encapsulates
10 11
    # logic behind common tasks used to manage database and migrations.
    #
12
    # The tasks defined here are used with Rails commands provided by Active Record.
13 14
    #
    # In order to use DatabaseTasks, a few config values need to be set. All the needed
15 16 17 18
    # config values are set by Rails already, so it's necessary to do it only if you
    # want to change the defaults or when you want to use Active Record outside of Rails
    # (in such case after configuring the database tasks, you can also use the rake tasks
    # defined in Active Record).
19
    #
20
    # The possible config values are:
21
    #
22 23 24 25 26 27 28
    # * +env+: current environment (like Rails.env).
    # * +database_configuration+: configuration of your databases (as in +config/database.yml+).
    # * +db_dir+: your +db+ directory.
    # * +fixtures_path+: a path to fixtures directory.
    # * +migrations_paths+: a list of paths to directories with migrations.
    # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method.
    # * +root+: a path to the root of the application.
29
    #
30
    # Example usage of DatabaseTasks outside Rails could look as such:
31
    #
32
    #   include ActiveRecord::Tasks
33
    #   DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
34 35
    #   DatabaseTasks.db_dir = 'db'
    #   # other settings...
36
    #
37
    #   DatabaseTasks.create_current('production')
38
    module DatabaseTasks
39 40
      ##
      # :singleton-method:
41
      # Extra flags passed to database CLI tool (mysqldump/pg_dump) when calling db:schema:dump
42 43 44 45
      mattr_accessor :structure_dump_flags, instance_accessor: false

      ##
      # :singleton-method:
46
      # Extra flags passed to database CLI tool when calling db:schema:load
47 48
      mattr_accessor :structure_load_flags, instance_accessor: false

49
      extend self
P
Pat Allan 已提交
50

51
      attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader
52
      deprecate :current_config=
53
      attr_accessor :database_configuration
54

55
      LOCAL_HOSTS = ["127.0.0.1", "localhost"]
56

57
      def check_protected_environments!
58
        unless ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"]
59 60
          current = ActiveRecord::Base.connection.migration_context.current_environment
          stored  = ActiveRecord::Base.connection.migration_context.last_stored_environment
S
schneems 已提交
61

62
          if ActiveRecord::Base.connection.migration_context.protected_environment?
S
schneems 已提交
63 64 65
            raise ActiveRecord::ProtectedEnvironmentError.new(stored)
          end

66 67
          if stored && stored != current
            raise ActiveRecord::EnvironmentMismatchError.new(current: current, stored: stored)
S
schneems 已提交
68
          end
69 70 71 72
        end
      rescue ActiveRecord::NoDatabaseError
      end

73 74 75 76 77
      def register_task(pattern, task)
        @tasks ||= {}
        @tasks[pattern] = task
      end

78 79 80
      register_task(/mysql/,        "ActiveRecord::Tasks::MySQLDatabaseTasks")
      register_task(/postgresql/,   "ActiveRecord::Tasks::PostgreSQLDatabaseTasks")
      register_task(/sqlite/,       "ActiveRecord::Tasks::SQLiteDatabaseTasks")
K
kennyj 已提交
81

82 83 84 85 86
      def db_dir
        @db_dir ||= Rails.application.config.paths["db"].first
      end

      def migrations_paths
87
        @migrations_paths ||= Rails.application.paths["db/migrate"].to_a
88 89 90
      end

      def fixtures_path
91
        @fixtures_path ||= if ENV["FIXTURES_PATH"]
92
          File.join(root, ENV["FIXTURES_PATH"])
93 94 95
        else
          File.join(root, "test", "fixtures")
        end
96 97 98 99 100 101 102 103 104 105
      end

      def root
        @root ||= Rails.root
      end

      def env
        @env ||= Rails.env
      end

106 107 108
      def spec
        @spec ||= "primary"
      end
109
      deprecate spec: "please use name instead"
110 111 112 113

      def name
        @name ||= "primary"
      end
114

115 116 117 118
      def seed_loader
        @seed_loader ||= Rails.application
      end

119 120 121 122
      def current_config(options = {})
        if options.has_key?(:config)
          @current_config = options[:config]
        else
123
          env_name = options[:env] || env
124
          name = options[:spec] || "primary"
125

126
          @current_config ||= ActiveRecord::Base.configurations.configs_for(env_name: env_name, name: name)&.configuration_hash
127 128
        end
      end
129
      deprecate :current_config
130

131 132
      def create(configuration, *arguments)
        db_config = resolve_configuration(configuration)
133
        database_adapter_for(db_config, *arguments).create
134
        $stdout.puts "Created database '#{db_config.database}'" if verbose?
135
      rescue DatabaseAlreadyExists
136
        $stderr.puts "Database '#{db_config.database}' already exists" if verbose?
137
      rescue Exception => error
138
        $stderr.puts error
139
        $stderr.puts "Couldn't create '#{db_config.database}' database. Please check your configuration."
140
        raise
141
      end
P
Pat Allan 已提交
142

143
      def create_all
144
        old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name)
145
        each_local_configuration { |db_config| create(db_config) }
146
        if old_pool
147
          ActiveRecord::Base.connection_handler.establish_connection(old_pool.db_config)
148
        end
149
      end
P
Pat Allan 已提交
150

151
      def setup_initial_database_yaml
152 153
        return {} unless defined?(Rails)

154 155 156 157 158 159 160 161 162 163
        begin
          Rails.application.config.load_database_yaml
        rescue
          $stderr.puts "Rails couldn't infer whether you are using multiple databases from your database.yml and can't generate the tasks for the non-primary databases. If you'd like to use this feature, please simplify your ERB."

          {}
        end
      end

      def for_each(databases)
164 165
        return {} unless defined?(Rails)

166
        database_configs = ActiveRecord::DatabaseConfigurations.new(databases).configs_for(env_name: Rails.env)
167 168 169 170 171

        # if this is a single database application we don't want tasks for each primary database
        return if database_configs.count == 1

        database_configs.each do |db_config|
172
          yield db_config.name
E
eileencodes 已提交
173 174 175
        end
      end

176 177 178 179 180 181 182
      def raise_for_multi_db(environment = env, command:)
        db_configs = ActiveRecord::Base.configurations.configs_for(env_name: environment)

        if db_configs.count > 1
          dbs_list = []

          db_configs.each do |db|
183
            dbs_list << "#{command}:#{db.name}"
184 185 186 187 188 189
          end

          raise "You're using a multiple database application. To use `#{command}` you must run the namespaced task with a VERSION. Available tasks are #{dbs_list.to_sentence}."
        end
      end

190 191
      def create_current(environment = env, name = nil)
        each_current_configuration(environment, name) { |db_config| create(db_config) }
192
        ActiveRecord::Base.establish_connection(environment.to_sym)
193
      end
P
Pat Allan 已提交
194

195 196
      def drop(configuration, *arguments)
        db_config = resolve_configuration(configuration)
197
        database_adapter_for(db_config, *arguments).drop
198
        $stdout.puts "Dropped database '#{db_config.database}'" if verbose?
199
      rescue ActiveRecord::NoDatabaseError
200
        $stderr.puts "Database '#{db_config.database}' does not exist"
201
      rescue Exception => error
202
        $stderr.puts error
203
        $stderr.puts "Couldn't drop database '#{db_config.database}'"
204
        raise
205
      end
P
Pat Allan 已提交
206

207
      def drop_all
208
        each_local_configuration { |db_config| drop(db_config) }
209
      end
P
Pat Allan 已提交
210

211
      def drop_current(environment = env)
212
        each_current_configuration(environment) { |db_config| drop(db_config) }
213
      end
P
Pat Allan 已提交
214

215
      def truncate_tables(db_config)
216 217 218 219
        ActiveRecord::Base.establish_connection(db_config)

        connection = ActiveRecord::Base.connection
        connection.truncate_tables(*connection.tables)
220
      end
221
      private :truncate_tables
222 223 224

      def truncate_all(environment = env)
        ActiveRecord::Base.configurations.configs_for(env_name: environment).each do |db_config|
225
          truncate_tables(db_config)
226 227 228
        end
      end

229
      def migrate
230
        check_target_version
P
Philippe Guay 已提交
231 232

        scope = ENV["SCOPE"]
233
        verbose_was, Migration.verbose = Migration.verbose, verbose?
234

235
        Base.connection.migration_context.migrate(target_version) do |migration|
236 237
          scope.blank? || scope == migration.scope
        end
238

239
        ActiveRecord::Base.clear_cache!
240 241
      ensure
        Migration.verbose = verbose_was
242 243
      end

244
      def migrate_status
245
        unless ActiveRecord::Base.connection.schema_migration.table_exists?
246 247 248 249
          Kernel.abort "Schema migrations table does not exist yet."
        end

        # output
J
John Crepezzi 已提交
250
        puts "\ndatabase: #{ActiveRecord::Base.connection_db_config.database}\n\n"
251 252 253 254 255 256 257 258
        puts "#{'Status'.center(8)}  #{'Migration ID'.ljust(14)}  Migration Name"
        puts "-" * 50
        ActiveRecord::Base.connection.migration_context.migrations_status.each do |status, version, name|
          puts "#{status.center(8)}  #{version.ljust(14)}  #{name}"
        end
        puts
      end

259 260 261 262 263 264 265 266 267 268
      def check_target_version
        if target_version && !(Migration::MigrationFilenameRegexp.match?(ENV["VERSION"]) || /\A\d+\z/.match?(ENV["VERSION"]))
          raise "Invalid format of target version: `VERSION=#{ENV['VERSION']}`"
        end
      end

      def target_version
        ENV["VERSION"].to_i if ENV["VERSION"] && !ENV["VERSION"].empty?
      end

269 270
      def charset_current(env_name = env, db_name = name)
        db_config = ActiveRecord::Base.configurations.configs_for(env_name: env_name, name: db_name)
271
        charset(db_config)
S
Simon Jefford 已提交
272 273
      end

274 275
      def charset(configuration, *arguments)
        db_config = resolve_configuration(configuration)
276
        database_adapter_for(db_config, *arguments).charset
S
Simon Jefford 已提交
277 278
      end

279 280
      def collation_current(env_name = env, db_name = name)
        db_config = ActiveRecord::Base.configurations.configs_for(env_name: env_name, name: db_name)
281
        collation(db_config)
282 283
      end

284 285
      def collation(configuration, *arguments)
        db_config = resolve_configuration(configuration)
286
        database_adapter_for(db_config, *arguments).collation
287 288
      end

289
      def purge(configuration)
290
        db_config = resolve_configuration(configuration)
291
        database_adapter_for(db_config).purge
292
      end
P
Pat Allan 已提交
293

294
      def purge_all
295
        each_local_configuration { |db_config| purge(db_config) }
296 297 298
      end

      def purge_current(environment = env)
299
        each_current_configuration(environment) { |db_config| purge(db_config) }
300
        ActiveRecord::Base.establish_connection(environment.to_sym)
301 302
      end

303 304 305
      def structure_dump(configuration, *arguments)
        db_config = resolve_configuration(configuration)
        filename = arguments.delete_at(0)
306
        database_adapter_for(db_config, *arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
307 308
      end

309 310 311
      def structure_load(configuration, *arguments)
        db_config = resolve_configuration(configuration)
        filename = arguments.delete_at(0)
312
        database_adapter_for(db_config, *arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
313 314
      end

315
      def load_schema(db_config, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc:
316
        file ||= dump_filename(db_config.name, format)
317

318
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
319
        check_schema_file(file)
320
        ActiveRecord::Base.establish_connection(db_config)
321

322 323 324 325
        case format
        when :ruby
          load(file)
        when :sql
326
          structure_load(db_config, file)
327 328 329
        else
          raise ArgumentError, "unknown format #{format.inspect}"
        end
330
        ActiveRecord::InternalMetadata.create_table
331
        ActiveRecord::InternalMetadata[:environment] = db_config.env_name
332
        ActiveRecord::InternalMetadata[:schema_sha1] = schema_sha1(file)
333 334
      ensure
        Migration.verbose = verbose_was
335 336
      end

337
      def schema_up_to_date?(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = nil, name = nil)
338 339
        db_config = resolve_configuration(configuration)

340 341
        if environment || name
          ActiveSupport::Deprecation.warn("`environment` and `name` will be removed as parameters in 6.2.0, you may now pass an ActiveRecord::DatabaseConfigurations::DatabaseConfig as `configuration` instead.")
342 343
        end

344
        name ||= db_config.name
345

346
        file ||= dump_filename(name, format)
347 348 349

        return true unless File.exist?(file)

350
        ActiveRecord::Base.establish_connection(db_config)
351 352

        return false unless ActiveRecord::InternalMetadata.enabled?
353
        return false unless ActiveRecord::InternalMetadata.table_exists?
354

355 356 357
        ActiveRecord::InternalMetadata[:schema_sha1] == schema_sha1(file)
      end

358
      def reconstruct_from_schema(db_config, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc:
359
        file ||= dump_filename(db_config.name, format)
360 361 362

        check_schema_file(file)

363
        ActiveRecord::Base.establish_connection(db_config)
364

365 366
        if schema_up_to_date?(db_config, format, file)
          truncate_tables(db_config)
367
        else
368 369
          purge(db_config)
          load_schema(db_config, format, file)
370 371
        end
      rescue ActiveRecord::NoDatabaseError
372 373
        create(db_config)
        load_schema(db_config, format, file)
374 375
      end

376
      def dump_schema(db_config, format = ActiveRecord::Base.schema_format) # :nodoc:
377
        require "active_record/schema_dumper"
378
        filename = dump_filename(db_config.name, format)
379
        connection = ActiveRecord::Base.connection
380 381 382 383 384 385 386

        case format
        when :ruby
          File.open(filename, "w:utf-8") do |file|
            ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
          end
        when :sql
387
          structure_dump(db_config, filename)
388
          if connection.schema_migration.table_exists?
389
            File.open(filename, "a") do |f|
390
              f.puts connection.dump_schema_information
391 392 393 394 395 396
              f.print "\n"
            end
          end
        end
      end

397
      def schema_file(format = ActiveRecord::Base.schema_format)
398 399 400 401
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
402 403
        case format
        when :ruby
404
          "schema.rb"
405
        when :sql
406
          "structure.sql"
407 408 409
        end
      end

410 411
      def dump_filename(db_config_name, format = ActiveRecord::Base.schema_format)
        filename = if ActiveRecord::Base.configurations.primary?(db_config_name)
412 413
          schema_file_type(format)
        else
414
          "#{db_config_name}_#{schema_file_type(format)}"
415 416 417 418
        end

        ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, filename)
      end
419

420 421
      def cache_dump_filename(db_config_name, schema_cache_path: nil)
        filename = if ActiveRecord::Base.configurations.primary?(db_config_name)
422 423
          "schema_cache.yml"
        else
424
          "#{db_config_name}_schema_cache.yml"
425 426
        end

427
        schema_cache_path || ENV["SCHEMA_CACHE"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, filename)
428
      end
429

430
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
431 432 433
        each_current_configuration(environment) do |db_config|
          load_schema(db_config, format, file)
        end
434
        ActiveRecord::Base.establish_connection(environment.to_sym)
435 436
      end

437
      def check_schema_file(filename)
A
Arun Agrawal 已提交
438
        unless File.exist?(filename)
439
          message = +%{#{filename} doesn't exist yet. Run `bin/rails db:migrate` to create it, then try again.}
440
          message << %{ 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.} if defined?(::Rails.root)
441 442 443 444
          Kernel.abort message
        end
      end

445 446 447 448
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
449 450
          raise "You tried to load seed data, but no seed loader is specified. Please specify seed " \
                "loader with ActiveRecord::Tasks::DatabaseTasks.seed_loader = your_seed_loader\n" \
451 452 453 454
                "Seed loader should respond to load_seed method"
        end
      end

455 456 457 458 459
      # Dumps the schema cache in YAML format for the connection into the file
      #
      # ==== Examples:
      #   ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.connection, "tmp/schema_dump.yaml")
      def dump_schema_cache(conn, filename)
460
        conn.schema_cache.dump_to(filename)
461 462
      end

463 464 465 466
      def clear_schema_cache(filename)
        FileUtils.rm_f filename, verbose: false
      end

467
      private
468
        def resolve_configuration(configuration)
469
          Base.configurations.resolve(configuration)
470 471
        end

472 473 474
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
475

476 477 478 479 480 481 482 483 484 485 486
        # Create a new instance for the specified db configuration object
        # For classes that have been converted to use db_config objects, pass a
        # `DatabaseConfig`, otherwise pass a `Hash`
        def database_adapter_for(db_config, *arguments)
          klass = class_for_adapter(db_config.adapter)
          converted = klass.respond_to?(:using_database_configurations?) && klass.using_database_configurations?

          config = converted ? db_config : db_config.configuration_hash
          klass.new(config, *arguments)
        end

487
        def class_for_adapter(adapter)
488 489
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
490 491
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
492
          task.is_a?(String) ? task.constantize : task
493
        end
P
Pat Allan 已提交
494

495
        def each_current_configuration(environment, name = nil)
496
          environments = [environment]
497
          environments << "test" if environment == "development" && !ENV["SKIP_TEST_DATABASE"] && !ENV["DATABASE_URL"]
P
Pat Allan 已提交
498

499
          environments.each do |env|
500
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
501
              next if name && name != db_config.name
502

503
              yield db_config
504
            end
505
          end
506 507
        end

508
        def each_local_configuration
509
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
510
            next unless db_config.database
511

512 513
            if local_database?(db_config)
              yield db_config
514
            else
515
              $stderr.puts "This task only modifies local databases. #{db_config.database} is on a remote host."
516
            end
517 518
          end
        end
P
Pat Allan 已提交
519

520
        def local_database?(db_config)
J
John Crepezzi 已提交
521
          host = db_config.host
522
          host.blank? || LOCAL_HOSTS.include?(host)
523
        end
524 525 526 527

        def schema_sha1(file)
          Digest::SHA1.hexdigest(File.read(file))
        end
528
    end
P
Pat Allan 已提交
529
  end
530
end