database_tasks.rb 17.2 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]).config
120 121 122
        end
      end

123
      def create(*arguments)
124
        configuration = arguments.first
125
        class_for_adapter(configuration["adapter"]).new(*arguments).create
126
        $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
A
Arthur Neves 已提交
139
          ActiveRecord::Base.connection_handler.establish_connection(old_pool.spec.to_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
        configuration = arguments.first
191
        class_for_adapter(configuration["adapter"]).new(*arguments).drop
192
        $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 227 228 229 230

      def truncate_all(environment = env)
        ActiveRecord::Base.configurations.configs_for(env_name: environment).each do |db_config|
          truncate_tables db_config.config
        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).config
S
Simon Jefford 已提交
273 274 275 276
      end

      def charset(*arguments)
        configuration = arguments.first
277
        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).config
282 283 284 285
      end

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

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

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

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

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

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

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

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

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

340 341 342 343 344 345 346 347 348 349
      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

350
      def dump_schema(configuration, format = ActiveRecord::Base.schema_format, spec_name = "primary") # :nodoc:
351 352
        require "active_record/schema_dumper"
        filename = dump_filename(spec_name, format)
353
        connection = ActiveRecord::Base.connection
354 355 356 357 358 359 360 361

        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)
362
          if connection.schema_migration.table_exists?
363
            File.open(filename, "a") do |f|
364
              f.puts connection.dump_schema_information
365 366 367 368 369 370
              f.print "\n"
            end
          end
        end
      end

371
      def schema_file(format = ActiveRecord::Base.schema_format)
372 373 374 375
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
376 377
        case format
        when :ruby
378
          "schema.rb"
379
        when :sql
380
          "structure.sql"
381 382 383
        end
      end

384 385 386 387 388 389 390 391 392
      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
393 394 395 396 397 398 399 400 401 402

      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
403

404
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
405
        each_current_configuration(environment) { |configuration, spec_name, env|
406
          load_schema(configuration, format, file, env, spec_name)
407
        }
408
        ActiveRecord::Base.establish_connection(environment.to_sym)
409 410
      end

411
      def check_schema_file(filename)
A
Arun Agrawal 已提交
412
        unless File.exist?(filename)
413
          message = +%{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}
414
          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)
415 416 417 418
          Kernel.abort message
        end
      end

419 420 421 422
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
423 424
          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" \
425 426 427 428
                "Seed loader should respond to load_seed method"
        end
      end

429 430 431 432 433 434 435 436 437 438
      # 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

439
      private
440 441 442
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
443

444
        def class_for_adapter(adapter)
445 446
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
447 448
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
449
          task.is_a?(String) ? task.constantize : task
450
        end
P
Pat Allan 已提交
451

452
        def each_current_configuration(environment, spec_name = nil)
453 454
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
455

456
          environments.each do |env|
457
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
458 459
              next if spec_name && spec_name != db_config.spec_name

460
              yield db_config.config, db_config.spec_name, env
461
            end
462
          end
463 464
        end

465
        def each_local_configuration
466 467
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
            configuration = db_config.config
468 469
            next unless configuration["database"]

470 471 472 473 474
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
475 476
          end
        end
P
Pat Allan 已提交
477

478 479 480
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
481 482 483 484

        def schema_sha1(file)
          Digest::SHA1.hexdigest(File.read(file))
        end
485
    end
P
Pat Allan 已提交
486
  end
487
end