database_tasks.rb 14.9 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
        databases = Rails.application.config.load_database_yaml
146
        database_configs = ActiveRecord::DatabaseConfigurations.new(databases).configs_for(env_name: Rails.env)
147 148 149 150 151 152

        # 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 已提交
153 154 155
        end
      end

156
      def create_current(environment = env)
157 158 159
        each_current_configuration(environment) { |configuration|
          create configuration
        }
160
        ActiveRecord::Base.establish_connection(environment.to_sym)
161
      end
P
Pat Allan 已提交
162

163
      def drop(*arguments)
164
        configuration = arguments.first
165
        class_for_adapter(configuration["adapter"]).new(*arguments).drop
166
        $stdout.puts "Dropped database '#{configuration['database']}'" if verbose?
167
      rescue ActiveRecord::NoDatabaseError
168
        $stderr.puts "Database '#{configuration['database']}' does not exist"
169
      rescue Exception => error
170
        $stderr.puts error
171
        $stderr.puts "Couldn't drop database '#{configuration['database']}'"
172
        raise
173
      end
P
Pat Allan 已提交
174

175
      def drop_all
176 177
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
178

179
      def drop_current(environment = env)
180 181 182 183
        each_current_configuration(environment) { |configuration|
          drop configuration
        }
      end
P
Pat Allan 已提交
184

185 186 187
      def truncate_tables(configuration)
        ActiveRecord::Base.connected_to(database: { truncation: configuration }) do
          table_names = ActiveRecord::Base.connection.tables
188
          table_names -= [
189 190
            SchemaMigration.table_name,
            InternalMetadata.table_name
191 192
          ]

R
Ryuta Kamizono 已提交
193
          ActiveRecord::Base.connection.truncate_tables(*table_names)
194 195
        end
      end
196
      private :truncate_tables
197 198 199 200 201 202 203

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

204
      def migrate
205
        check_target_version
P
Philippe Guay 已提交
206 207

        scope = ENV["SCOPE"]
208
        verbose_was, Migration.verbose = Migration.verbose, verbose?
209

210
        Base.connection.migration_context.migrate(target_version) do |migration|
211 212
          scope.blank? || scope == migration.scope
        end
213

214
        ActiveRecord::Base.clear_cache!
215 216
      ensure
        Migration.verbose = verbose_was
217 218
      end

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
      def migrate_status
        unless ActiveRecord::SchemaMigration.table_exists?
          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

234 235 236 237 238 239 240 241 242 243
      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

244
      def charset_current(environment = env, specification_name = spec)
245
        charset ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config
S
Simon Jefford 已提交
246 247 248 249
      end

      def charset(*arguments)
        configuration = arguments.first
250
        class_for_adapter(configuration["adapter"]).new(*arguments).charset
S
Simon Jefford 已提交
251 252
      end

253
      def collation_current(environment = env, specification_name = spec)
254
        collation ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config
255 256 257 258
      end

      def collation(*arguments)
        configuration = arguments.first
259
        class_for_adapter(configuration["adapter"]).new(*arguments).collation
260 261
      end

262
      def purge(configuration)
263
        class_for_adapter(configuration["adapter"]).new(configuration).purge
264
      end
P
Pat Allan 已提交
265

266 267 268 269 270 271 272 273 274 275
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

      def purge_current(environment = env)
        each_current_configuration(environment) { |configuration|
          purge configuration
        }
276
        ActiveRecord::Base.establish_connection(environment.to_sym)
277 278
      end

K
kennyj 已提交
279 280 281
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
282
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
283 284
      end

K
kennyj 已提交
285 286 287
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
288
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
289 290
      end

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

294
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
295 296 297
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

298 299 300 301
        case format
        when :ruby
          load(file)
        when :sql
302
          structure_load(configuration, file)
303 304 305
        else
          raise ArgumentError, "unknown format #{format.inspect}"
        end
306
        ActiveRecord::InternalMetadata.create_table
307
        ActiveRecord::InternalMetadata[:environment] = environment
308 309
      ensure
        Migration.verbose = verbose_was
310 311
      end

312
      def schema_file(format = ActiveRecord::Base.schema_format)
313 314 315 316
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
317 318
        case format
        when :ruby
319
          "schema.rb"
320
        when :sql
321
          "structure.sql"
322 323 324
        end
      end

325 326 327 328 329 330 331 332 333
      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
334 335 336 337 338 339 340 341 342 343

      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
344

345
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
346
        each_current_configuration(environment) { |configuration, spec_name, env|
347
          load_schema(configuration, format, file, env, spec_name)
348
        }
349
        ActiveRecord::Base.establish_connection(environment.to_sym)
350 351
      end

352
      def check_schema_file(filename)
A
Arun Agrawal 已提交
353
        unless File.exist?(filename)
354
          message = +%{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}
355
          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)
356 357 358 359
          Kernel.abort message
        end
      end

360 361 362 363
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
364 365
          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" \
366 367 368 369
                "Seed loader should respond to load_seed method"
        end
      end

370 371 372 373 374 375 376 377 378 379
      # 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

380
      private
381 382 383
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
384

385
        def class_for_adapter(adapter)
386 387
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
388 389
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
390
          task.is_a?(String) ? task.constantize : task
391
        end
P
Pat Allan 已提交
392

393 394 395
        def each_current_configuration(environment)
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
396

397
          environments.each do |env|
398
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
399
              yield db_config.config, db_config.spec_name, env
400
            end
401
          end
402 403
        end

404
        def each_local_configuration
405 406
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
            configuration = db_config.config
407 408
            next unless configuration["database"]

409 410 411 412 413
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
414 415
          end
        end
P
Pat Allan 已提交
416

417 418 419
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
420
    end
P
Pat Allan 已提交
421
  end
422
end