database_tasks.rb 13.4 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.database_configuration
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
      def migrate
186
        check_target_version
P
Philippe Guay 已提交
187 188

        scope = ENV["SCOPE"]
189
        verbose_was, Migration.verbose = Migration.verbose, verbose?
190

191
        Base.connection.migration_context.migrate(target_version) do |migration|
192 193
          scope.blank? || scope == migration.scope
        end
194

195
        ActiveRecord::Base.clear_cache!
196 197
      ensure
        Migration.verbose = verbose_was
198 199
      end

200 201 202 203 204 205 206 207 208 209
      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

210
      def charset_current(environment = env, specification_name = spec)
211
        charset ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config
S
Simon Jefford 已提交
212 213 214 215
      end

      def charset(*arguments)
        configuration = arguments.first
216
        class_for_adapter(configuration["adapter"]).new(*arguments).charset
S
Simon Jefford 已提交
217 218
      end

219
      def collation_current(environment = env, specification_name = spec)
220
        collation ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config
221 222 223 224
      end

      def collation(*arguments)
        configuration = arguments.first
225
        class_for_adapter(configuration["adapter"]).new(*arguments).collation
226 227
      end

228
      def purge(configuration)
229
        class_for_adapter(configuration["adapter"]).new(configuration).purge
230
      end
P
Pat Allan 已提交
231

232 233 234 235 236 237 238 239 240 241
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

      def purge_current(environment = env)
        each_current_configuration(environment) { |configuration|
          purge configuration
        }
242
        ActiveRecord::Base.establish_connection(environment.to_sym)
243 244
      end

K
kennyj 已提交
245 246 247
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
248
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
249 250
      end

K
kennyj 已提交
251 252 253
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
254
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
255 256
      end

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

260
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
261 262 263
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

264 265 266 267
        case format
        when :ruby
          load(file)
        when :sql
268
          structure_load(configuration, file)
269 270 271
        else
          raise ArgumentError, "unknown format #{format.inspect}"
        end
272
        ActiveRecord::InternalMetadata.create_table
273
        ActiveRecord::InternalMetadata[:environment] = environment
274 275
      ensure
        Migration.verbose = verbose_was
276 277
      end

278
      def schema_file(format = ActiveRecord::Base.schema_format)
279 280 281 282
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
283 284
        case format
        when :ruby
285
          "schema.rb"
286
        when :sql
287
          "structure.sql"
288 289 290
        end
      end

291 292 293 294 295 296 297 298 299 300
      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

301
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
302
        each_current_configuration(environment) { |configuration, spec_name, env|
303
          load_schema(configuration, format, file, env, spec_name)
304
        }
305
        ActiveRecord::Base.establish_connection(environment.to_sym)
306 307
      end

308
      def check_schema_file(filename)
A
Arun Agrawal 已提交
309
        unless File.exist?(filename)
310
          message = +%{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}
311
          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)
312 313 314 315
          Kernel.abort message
        end
      end

316 317 318 319
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
320 321
          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" \
322 323 324 325
                "Seed loader should respond to load_seed method"
        end
      end

326 327 328 329 330 331 332 333 334 335
      # 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

336
      private
337 338 339
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
340

341
        def class_for_adapter(adapter)
342 343
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
344 345
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
346
          task.is_a?(String) ? task.constantize : task
347
        end
P
Pat Allan 已提交
348

349 350 351
        def each_current_configuration(environment)
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
352

353
          environments.each do |env|
354
            ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
355
              yield db_config.config, db_config.spec_name, env
356
            end
357
          end
358 359
        end

360
        def each_local_configuration
361 362
          ActiveRecord::Base.configurations.configs_for.each do |db_config|
            configuration = db_config.config
363 364
            next unless configuration["database"]

365 366 367 368 369
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
370 371
          end
        end
P
Pat Allan 已提交
372

373 374 375
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
376
    end
P
Pat Allan 已提交
377
  end
378
end