database_tasks.rb 18.1 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 52
      attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader
      attr_accessor :database_configuration
53

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

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

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

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

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

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

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

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

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

      def root
        @root ||= Rails.root
      end

      def env
        @env ||= Rails.env
      end

105 106 107 108
      def spec
        @spec ||= "primary"
      end

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

113
      def current_config(options = {})
114
        options.reverse_merge! env: env
115
        options[:spec] ||= "primary"
116 117 118
        if options.has_key?(:config)
          @current_config = options[:config]
        else
119
          @current_config ||= ActiveRecord::Base.configurations.configs_for(env_name: options[:env], spec_name: options[:spec]).db_config.configuration_hash
120 121 122
        end
      end

123
      def create(*arguments)
124 125 126
        configuration = arguments.first.symbolize_keys
        class_for_adapter(configuration[:adapter]).new(*arguments).create
        $stdout.puts "Created database '#{configuration[:database]}'" if verbose?
127
      rescue DatabaseAlreadyExists
128
        $stderr.puts "Database '#{configuration[:database]}' already exists" if verbose?
129
      rescue Exception => error
130
        $stderr.puts error
131
        $stderr.puts "Couldn't create '#{configuration[:database]}' database. Please check your configuration."
132
        raise
133
      end
P
Pat Allan 已提交
134

135
      def create_all
136
        old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name)
137
        each_local_configuration { |configuration| create configuration }
138
        if old_pool
139
          ActiveRecord::Base.connection_handler.establish_connection(old_pool.spec.db_config.configuration_hash)
140
        end
141
      end
P
Pat Allan 已提交
142

143
      def setup_initial_database_yaml
144 145
        return {} unless defined?(Rails)

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

158
        database_configs = ActiveRecord::DatabaseConfigurations.new(databases).configs_for(env_name: Rails.env)
159 160 161 162 163 164

        # 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 已提交
165 166 167
        end
      end

168 169 170 171 172 173 174 175 176 177 178 179 180 181
      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

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

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

201
      def drop_all
202 203
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
204

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

211 212
      def truncate_tables(configuration)
        ActiveRecord::Base.connected_to(database: { truncation: configuration }) do
213 214
          conn = ActiveRecord::Base.connection
          table_names = conn.tables
215
          table_names -= [
216
            conn.schema_migration.table_name,
217
            InternalMetadata.table_name
218 219
          ]

R
Ryuta Kamizono 已提交
220
          ActiveRecord::Base.connection.truncate_tables(*table_names)
221 222
        end
      end
223
      private :truncate_tables
224 225 226

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

231
      def migrate
232
        check_target_version
P
Philippe Guay 已提交
233 234

        scope = ENV["SCOPE"]
235
        verbose_was, Migration.verbose = Migration.verbose, verbose?
236

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

241
        ActiveRecord::Base.clear_cache!
242 243
      ensure
        Migration.verbose = verbose_was
244 245
      end

246
      def migrate_status
247
        unless ActiveRecord::Base.connection.schema_migration.table_exists?
248 249 250 251 252 253 254 255 256 257 258 259 260
          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

261 262 263 264 265 266 267 268 269 270
      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

271
      def charset_current(environment = env, specification_name = spec)
272
        charset ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).configuration_hash
S
Simon Jefford 已提交
273 274 275
      end

      def charset(*arguments)
276 277
        configuration = arguments.first.symbolize_keys
        class_for_adapter(configuration[:adapter]).new(*arguments).charset
S
Simon Jefford 已提交
278 279
      end

280
      def collation_current(environment = env, specification_name = spec)
281
        collation ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).configuration_hash
282 283 284
      end

      def collation(*arguments)
285 286
        configuration = arguments.first.symbolize_keys
        class_for_adapter(configuration[:adapter]).new(*arguments).collation
287 288
      end

289
      def purge(configuration)
290 291
        configuration = configuration.symbolize_keys
        class_for_adapter(configuration[:adapter]).new(configuration).purge
292
      end
P
Pat Allan 已提交
293

294 295 296 297 298 299 300 301 302 303
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

      def purge_current(environment = env)
        each_current_configuration(environment) { |configuration|
          purge configuration
        }
304
        ActiveRecord::Base.establish_connection(environment.to_sym)
305 306
      end

K
kennyj 已提交
307
      def structure_dump(*arguments)
308
        configuration = arguments.first.symbolize_keys
K
kennyj 已提交
309
        filename = arguments.delete_at 1
310
        class_for_adapter(configuration[:adapter]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
311 312
      end

K
kennyj 已提交
313
      def structure_load(*arguments)
314
        configuration = arguments.first.symbolize_keys
K
kennyj 已提交
315
        filename = arguments.delete_at 1
316
        class_for_adapter(configuration[:adapter]).new(*arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
317 318
      end

319 320
      def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env, spec_name = "primary") # :nodoc:
        file ||= dump_filename(spec_name, format)
321

322
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
323 324 325
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

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

341 342 343 344 345 346 347 348 349 350
      def schema_up_to_date?(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env, spec_name = "primary")
        file ||= dump_filename(spec_name, format)

        return true unless File.exist?(file)

        ActiveRecord::Base.establish_connection(configuration)
        return false unless ActiveRecord::InternalMetadata.table_exists?
        ActiveRecord::InternalMetadata[:schema_sha1] == schema_sha1(file)
      end

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
      def reconstruct_from_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env, spec_name = "primary") # :nodoc:
        file ||= dump_filename(spec_name, format)

        check_schema_file(file)

        ActiveRecord::Base.establish_connection(configuration)

        if schema_up_to_date?(configuration, format, file, environment, spec_name)
          truncate_tables(configuration)
        else
          purge(configuration)
          load_schema(configuration, format, file, environment, spec_name)
        end
      rescue ActiveRecord::NoDatabaseError
        create(configuration)
        load_schema(configuration, format, file, environment, spec_name)
      end

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

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

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

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

403 404 405 406 407 408 409 410 411
      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
412 413 414 415 416 417 418 419 420 421

      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
422

423
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
424
        each_current_configuration(environment) { |configuration, spec_name, env|
425
          load_schema(configuration, format, file, env, spec_name)
426
        }
427
        ActiveRecord::Base.establish_connection(environment.to_sym)
428 429
      end

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

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

448 449 450 451 452 453 454 455 456 457
      # 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

458
      private
459 460 461
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
462

463
        def class_for_adapter(adapter)
464 465
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
466 467
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
468
          task.is_a?(String) ? task.constantize : task
469
        end
P
Pat Allan 已提交
470

471
        def each_current_configuration(environment, spec_name = nil)
472 473
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
474

475
          environments.each do |env|
476
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
477 478
              next if spec_name && spec_name != db_config.spec_name

479
              yield db_config.configuration_hash, db_config.spec_name, env
480
            end
481
          end
482 483
        end

484
        def each_local_configuration
485
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
486 487
            configuration = db_config.configuration_hash
            next unless configuration[:database]
488

489 490 491
            if local_database?(configuration)
              yield configuration
            else
492
              $stderr.puts "This task only modifies local databases. #{configuration[:database]} is on a remote host."
493
            end
494 495
          end
        end
P
Pat Allan 已提交
496

497
        def local_database?(configuration)
498
          configuration[:host].blank? || LOCAL_HOSTS.include?(configuration[:host])
499
        end
500 501 502 503

        def schema_sha1(file)
          Digest::SHA1.hexdigest(File.read(file))
        end
504
    end
P
Pat Allan 已提交
505
  end
506
end