database_tasks.rb 18.5 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 41 42 43 44 45 46 47 48
      ##
      # :singleton-method:
      # Extra flags passed to database CLI tool (mysqldump/pg_dump) when calling db:structure:dump
      mattr_accessor :structure_dump_flags, instance_accessor: false

      ##
      # :singleton-method:
      # Extra flags passed to database CLI tool when calling db:structure:load
      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 109
      def spec
        @spec ||= "primary"
      end

110 111 112 113
      def seed_loader
        @seed_loader ||= Rails.application
      end

114 115 116 117
      def current_config(options = {})
        if options.has_key?(:config)
          @current_config = options[:config]
        else
118 119 120 121
          env_name = options[:env] || env
          spec_name = options[:spec] || "primary"

          @current_config ||= ActiveRecord::Base.configurations.configs_for(env_name: env_name, spec_name: spec_name)&.configuration_hash
122 123
        end
      end
124
      deprecate :current_config
125

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

138
      def create_all
139
        old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name)
140
        each_local_configuration { |db_config| create(db_config) }
141
        if old_pool
142
          ActiveRecord::Base.connection_handler.establish_connection(old_pool.db_config)
143
        end
144
      end
P
Pat Allan 已提交
145

146
      def setup_initial_database_yaml
147 148
        return {} unless defined?(Rails)

149 150 151 152 153 154 155 156 157 158
        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)
159 160
        return {} unless defined?(Rails)

161
        database_configs = ActiveRecord::DatabaseConfigurations.new(databases).configs_for(env_name: Rails.env)
162 163 164 165 166 167

        # 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|
          yield db_config.spec_name
E
eileencodes 已提交
168 169 170
        end
      end

171 172 173 174 175 176 177 178 179 180 181 182 183 184
      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|
            dbs_list << "#{command}:#{db.spec_name}"
          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

185
      def create_current(environment = env, spec_name = nil)
186
        each_current_configuration(environment, spec_name) { |db_config| create(db_config) }
187
        ActiveRecord::Base.establish_connection(environment.to_sym)
188
      end
P
Pat Allan 已提交
189

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

202
      def drop_all
203
        each_local_configuration { |db_config| drop(db_config) }
204
      end
P
Pat Allan 已提交
205

206
      def drop_current(environment = env)
207
        each_current_configuration(environment) { |db_config| drop(db_config) }
208
      end
P
Pat Allan 已提交
209

210
      def truncate_tables(db_config)
211 212 213 214
        ActiveRecord::Base.establish_connection(db_config)

        connection = ActiveRecord::Base.connection
        connection.truncate_tables(*connection.tables)
215
      end
216
      private :truncate_tables
217 218 219

      def truncate_all(environment = env)
        ActiveRecord::Base.configurations.configs_for(env_name: environment).each do |db_config|
220
          truncate_tables(db_config)
221 222 223
        end
      end

224
      def migrate
225
        check_target_version
P
Philippe Guay 已提交
226 227

        scope = ENV["SCOPE"]
228
        verbose_was, Migration.verbose = Migration.verbose, verbose?
229

230
        Base.connection.migration_context.migrate(target_version) do |migration|
231 232
          scope.blank? || scope == migration.scope
        end
233

234
        ActiveRecord::Base.clear_cache!
235 236
      ensure
        Migration.verbose = verbose_was
237 238
      end

239
      def migrate_status
240
        unless ActiveRecord::Base.connection.schema_migration.table_exists?
241 242 243 244 245 246 247 248 249 250 251 252 253
          Kernel.abort "Schema migrations table does not exist yet."
        end

        # output
        puts "\ndatabase: #{ActiveRecord::Base.connection_config[:database]}\n\n"
        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

254 255 256 257 258 259 260 261 262 263
      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

264 265 266
      def charset_current(env_name = env, spec_name = spec)
        db_config = ActiveRecord::Base.configurations.configs_for(env_name: env_name, spec_name: spec_name)
        charset(db_config)
S
Simon Jefford 已提交
267 268
      end

269 270
      def charset(configuration, *arguments)
        db_config = resolve_configuration(configuration)
271
        database_adapter_for(db_config, *arguments).charset
S
Simon Jefford 已提交
272 273
      end

274 275 276
      def collation_current(env_name = env, spec_name = spec)
        db_config = ActiveRecord::Base.configurations.configs_for(env_name: env_name, spec_name: spec_name)
        collation(db_config)
277 278
      end

279 280
      def collation(configuration, *arguments)
        db_config = resolve_configuration(configuration)
281
        database_adapter_for(db_config, *arguments).collation
282 283
      end

284
      def purge(configuration)
285
        db_config = resolve_configuration(configuration)
286
        database_adapter_for(db_config).purge
287
      end
P
Pat Allan 已提交
288

289
      def purge_all
290
        each_local_configuration { |db_config| purge(db_config) }
291 292 293
      end

      def purge_current(environment = env)
294
        each_current_configuration(environment) { |db_config| purge(db_config) }
295
        ActiveRecord::Base.establish_connection(environment.to_sym)
296 297
      end

298 299 300
      def structure_dump(configuration, *arguments)
        db_config = resolve_configuration(configuration)
        filename = arguments.delete_at(0)
301
        database_adapter_for(db_config, *arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
302 303
      end

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

310 311
      def load_schema(db_config, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc:
        file ||= dump_filename(db_config.spec_name, format)
312

313
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
314
        check_schema_file(file)
315
        ActiveRecord::Base.establish_connection(db_config)
316

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

332 333 334 335 336 337 338 339 340
      def schema_up_to_date?(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = nil, spec_name = nil)
        db_config = resolve_configuration(configuration)

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

        spec_name ||= db_config.spec_name

341 342 343 344
        file ||= dump_filename(spec_name, format)

        return true unless File.exist?(file)

345
        ActiveRecord::Base.establish_connection(db_config)
346 347 348 349
        return false unless ActiveRecord::InternalMetadata.table_exists?
        ActiveRecord::InternalMetadata[:schema_sha1] == schema_sha1(file)
      end

350 351
      def reconstruct_from_schema(db_config, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc:
        file ||= dump_filename(db_config.spec_name, format)
352 353 354

        check_schema_file(file)

355
        ActiveRecord::Base.establish_connection(db_config)
356

357 358
        if schema_up_to_date?(db_config, format, file)
          truncate_tables(db_config)
359
        else
360 361
          purge(db_config)
          load_schema(db_config, format, file)
362 363
        end
      rescue ActiveRecord::NoDatabaseError
364 365
        create(db_config)
        load_schema(db_config, format, file)
366 367
      end

368
      def dump_schema(db_config, format = ActiveRecord::Base.schema_format) # :nodoc:
369
        require "active_record/schema_dumper"
370
        filename = dump_filename(db_config.spec_name, format)
371
        connection = ActiveRecord::Base.connection
372 373 374 375 376 377 378

        case format
        when :ruby
          File.open(filename, "w:utf-8") do |file|
            ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
          end
        when :sql
379
          structure_dump(db_config, filename)
380
          if connection.schema_migration.table_exists?
381
            File.open(filename, "a") do |f|
382
              f.puts connection.dump_schema_information
383 384 385 386 387 388
              f.print "\n"
            end
          end
        end
      end

389
      def schema_file(format = ActiveRecord::Base.schema_format)
390 391 392 393
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
394 395
        case format
        when :ruby
396
          "schema.rb"
397
        when :sql
398
          "structure.sql"
399 400 401
        end
      end

402 403 404 405 406 407 408 409 410
      def dump_filename(namespace, format = ActiveRecord::Base.schema_format)
        filename = if namespace == "primary"
          schema_file_type(format)
        else
          "#{namespace}_#{schema_file_type(format)}"
        end

        ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, filename)
      end
411 412 413 414 415 416 417 418 419 420

      def cache_dump_filename(namespace)
        filename = if namespace == "primary"
          "schema_cache.yml"
        else
          "#{namespace}_schema_cache.yml"
        end

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

422
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
423 424 425
        each_current_configuration(environment) do |db_config|
          load_schema(db_config, format, file)
        end
426
        ActiveRecord::Base.establish_connection(environment.to_sym)
427 428
      end

429
      def check_schema_file(filename)
A
Arun Agrawal 已提交
430
        unless File.exist?(filename)
431
          message = +%{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}
432
          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)
433 434 435 436
          Kernel.abort message
        end
      end

437 438 439 440
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
441 442
          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" \
443 444 445 446
                "Seed loader should respond to load_seed method"
        end
      end

447 448 449 450 451 452 453 454 455 456
      # 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)
        conn.schema_cache.clear!
        conn.data_sources.each { |table| conn.schema_cache.add(table) }
        open(filename, "wb") { |f| f.write(YAML.dump(conn.schema_cache)) }
      end

457
      private
458 459 460 461 462
        def resolve_configuration(configuration)
          resolver = ConnectionAdapters::Resolver.new(ActiveRecord::Base.configurations)
          resolver.resolve(configuration)
        end

463 464 465
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
466

467 468 469 470 471 472 473 474 475 476 477
        # 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

478
        def class_for_adapter(adapter)
479 480
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
481 482
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
483
          task.is_a?(String) ? task.constantize : task
484
        end
P
Pat Allan 已提交
485

486
        def each_current_configuration(environment, spec_name = nil)
487 488
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
489

490
          environments.each do |env|
491
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
492 493
              next if spec_name && spec_name != db_config.spec_name

494
              yield db_config
495
            end
496
          end
497 498
        end

499
        def each_local_configuration
500
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
501
            next unless db_config.database
502

503 504
            if local_database?(db_config)
              yield db_config
505
            else
506
              $stderr.puts "This task only modifies local databases. #{db_config.database} is on a remote host."
507
            end
508 509
          end
        end
P
Pat Allan 已提交
510

511 512 513
        def local_database?(db_config)
          host = db_config.configuration_hash[:host]
          host.blank? || LOCAL_HOSTS.include?(host)
514
        end
515 516 517 518

        def schema_sha1(file)
          Digest::SHA1.hexdigest(File.read(file))
        end
519
    end
P
Pat Allan 已提交
520
  end
521
end