database_tasks.rb 16.3 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 DatabaseAlreadyExists < StandardError; end # :nodoc:
8
    class DatabaseNotSupported < StandardError; end # :nodoc:
9

10
    # ActiveRecord::Tasks::DatabaseTasks is a utility class, which encapsulates
11 12
    # logic behind common tasks used to manage database and migrations.
    #
13
    # The tasks defined here are used with Rails commands provided by Active Record.
14 15
    #
    # In order to use DatabaseTasks, a few config values need to be set. All the needed
16 17 18 19
    # 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).
20
    #
21
    # The possible config values are:
22
    #
23 24 25 26 27 28 29
    # * +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.
30
    #
31
    # Example usage of DatabaseTasks outside Rails could look as such:
32
    #
33
    #   include ActiveRecord::Tasks
34
    #   DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
35 36
    #   DatabaseTasks.db_dir = 'db'
    #   # other settings...
37
    #
38
    #   DatabaseTasks.create_current('production')
39
    module DatabaseTasks
40 41 42 43 44 45 46 47 48 49
      ##
      # :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

50
      extend self
P
Pat Allan 已提交
51

52 53
      attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader
      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
      def current_config(options = {})
115
        options.reverse_merge! env: env
116
        options[:spec] ||= "primary"
117 118 119
        if options.has_key?(:config)
          @current_config = options[:config]
        else
120
          @current_config ||= ActiveRecord::Base.configurations.configs_for(env_name: options[:env], spec_name: options[:spec]).config
121 122 123
        end
      end

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

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

E
eileencodes 已提交
144
      def for_each
145 146
        return {} unless defined?(Rails)

147
        databases = Rails.application.config.load_database_yaml
148
        database_configs = ActiveRecord::DatabaseConfigurations.new(databases).configs_for(env_name: Rails.env)
149 150 151 152 153 154

        # 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 已提交
155 156 157
        end
      end

158 159 160 161 162 163 164 165 166 167 168 169 170 171
      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

172 173
      def create_current(environment = env, spec_name = nil)
        each_current_configuration(environment, spec_name) { |configuration|
174 175
          create configuration
        }
176
        ActiveRecord::Base.establish_connection(environment.to_sym)
177
      end
P
Pat Allan 已提交
178

179
      def drop(*arguments)
180
        configuration = arguments.first
181
        class_for_adapter(configuration["adapter"]).new(*arguments).drop
182
        $stdout.puts "Dropped database '#{configuration['database']}'" if verbose?
183
      rescue ActiveRecord::NoDatabaseError
184
        $stderr.puts "Database '#{configuration['database']}' does not exist"
185
      rescue Exception => error
186
        $stderr.puts error
187
        $stderr.puts "Couldn't drop database '#{configuration['database']}'"
188
        raise
189
      end
P
Pat Allan 已提交
190

191
      def drop_all
192 193
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
194

195
      def drop_current(environment = env)
196 197 198 199
        each_current_configuration(environment) { |configuration|
          drop configuration
        }
      end
P
Pat Allan 已提交
200

201 202
      def truncate_tables(configuration)
        ActiveRecord::Base.connected_to(database: { truncation: configuration }) do
203 204
          conn = ActiveRecord::Base.connection
          table_names = conn.tables
205
          table_names -= [
206
            conn.schema_migration.table_name,
207
            InternalMetadata.table_name
208 209
          ]

R
Ryuta Kamizono 已提交
210
          ActiveRecord::Base.connection.truncate_tables(*table_names)
211 212
        end
      end
213
      private :truncate_tables
214 215 216 217 218 219 220

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

221
      def migrate
222
        check_target_version
P
Philippe Guay 已提交
223 224

        scope = ENV["SCOPE"]
225
        verbose_was, Migration.verbose = Migration.verbose, verbose?
226

227
        Base.connection.migration_context.migrate(target_version) do |migration|
228 229
          scope.blank? || scope == migration.scope
        end
230

231
        ActiveRecord::Base.clear_cache!
232 233
      ensure
        Migration.verbose = verbose_was
234 235
      end

236
      def migrate_status
237
        unless ActiveRecord::Base.connection.schema_migration.table_exists?
238 239 240 241 242 243 244 245 246 247 248 249 250
          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

251 252 253 254 255 256 257 258 259 260
      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

261
      def charset_current(environment = env, specification_name = spec)
262
        charset ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config
S
Simon Jefford 已提交
263 264 265 266
      end

      def charset(*arguments)
        configuration = arguments.first
267
        class_for_adapter(configuration["adapter"]).new(*arguments).charset
S
Simon Jefford 已提交
268 269
      end

270
      def collation_current(environment = env, specification_name = spec)
271
        collation ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config
272 273 274 275
      end

      def collation(*arguments)
        configuration = arguments.first
276
        class_for_adapter(configuration["adapter"]).new(*arguments).collation
277 278
      end

279
      def purge(configuration)
280
        class_for_adapter(configuration["adapter"]).new(configuration).purge
281
      end
P
Pat Allan 已提交
282

283 284 285 286 287 288 289 290 291 292
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

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

K
kennyj 已提交
296 297 298
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
299
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
300 301
      end

K
kennyj 已提交
302 303 304
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
305
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
306 307
      end

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

311
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
312 313 314
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

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

329
      def dump_schema(configuration, format = ActiveRecord::Base.schema_format, spec_name = "primary") # :nodoc:
330 331
        require "active_record/schema_dumper"
        filename = dump_filename(spec_name, format)
332
        connection = ActiveRecord::Base.connection
333 334 335 336 337 338 339 340

        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)
341
          if connection.schema_migration.table_exists?
342
            File.open(filename, "a") do |f|
343
              f.puts connection.dump_schema_information
344 345 346 347 348 349
              f.print "\n"
            end
          end
        end
      end

350
      def schema_file(format = ActiveRecord::Base.schema_format)
351 352 353 354
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
355 356
        case format
        when :ruby
357
          "schema.rb"
358
        when :sql
359
          "structure.sql"
360 361 362
        end
      end

363 364 365 366 367 368 369 370 371
      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
372 373 374 375 376 377 378 379 380 381

      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
382

383
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
384
        each_current_configuration(environment) { |configuration, spec_name, env|
385
          load_schema(configuration, format, file, env, spec_name)
386
        }
387
        ActiveRecord::Base.establish_connection(environment.to_sym)
388 389
      end

390
      def check_schema_file(filename)
A
Arun Agrawal 已提交
391
        unless File.exist?(filename)
392
          message = +%{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}
393
          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)
394 395 396 397
          Kernel.abort message
        end
      end

398 399 400 401
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
402 403
          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" \
404 405 406 407
                "Seed loader should respond to load_seed method"
        end
      end

408 409 410 411 412 413 414 415 416 417
      # 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

418
      private
419 420 421
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
422

423
        def class_for_adapter(adapter)
424 425
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
426 427
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
428
          task.is_a?(String) ? task.constantize : task
429
        end
P
Pat Allan 已提交
430

431
        def each_current_configuration(environment, spec_name = nil)
432 433
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
434

435
          environments.each do |env|
436
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
437 438
              next if spec_name && spec_name != db_config.spec_name

439
              yield db_config.config, db_config.spec_name, env
440
            end
441
          end
442 443
        end

444
        def each_local_configuration
445 446
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
            configuration = db_config.config
447 448
            next unless configuration["database"]

449 450 451 452 453
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
454 455
          end
        end
P
Pat Allan 已提交
456

457 458 459
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
460
    end
P
Pat Allan 已提交
461
  end
462
end