database_tasks.rb 12.9 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
module ActiveRecord
  module Tasks # :nodoc:
5
    class DatabaseAlreadyExists < StandardError; end # :nodoc:
6
    class DatabaseNotSupported < StandardError; end # :nodoc:
7

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

48
      extend self
P
Pat Allan 已提交
49

50 51
      attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader
      attr_accessor :database_configuration
52

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

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

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

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

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

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

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

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

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

      def root
        @root ||= Rails.root
      end

      def env
        @env ||= Rails.env
      end

      def seed_loader
        @seed_loader ||= Rails.application
      end

108
      def current_config(options = {})
109
        options.reverse_merge! env: env
110 111 112
        if options.has_key?(:config)
          @current_config = options[:config]
        else
113
          @current_config ||= ActiveRecord::Base.configurations[options[:env]]
114 115 116
        end
      end

117
      def create(*arguments)
118
        configuration = arguments.first
119
        class_for_adapter(configuration["adapter"]).new(*arguments).create
120
        $stdout.puts "Created database '#{configuration['database']}'" if verbose?
121
      rescue DatabaseAlreadyExists
122
        $stderr.puts "Database '#{configuration['database']}' already exists" if verbose?
123
      rescue Exception => error
124
        $stderr.puts error
125
        $stderr.puts "Couldn't create database for #{configuration.inspect}"
126
        raise
127
      end
P
Pat Allan 已提交
128

129
      def create_all
130
        old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name)
131
        each_local_configuration { |configuration| create configuration }
132
        if old_pool
A
Arthur Neves 已提交
133
          ActiveRecord::Base.connection_handler.establish_connection(old_pool.spec.to_hash)
134
        end
135
      end
P
Pat Allan 已提交
136

E
eileencodes 已提交
137 138
      def for_each
        databases = Rails.application.config.load_database_yaml
139 140 141 142 143 144 145
        database_configs = ActiveRecord::DatabaseConfigurations.configs_for(Rails.env, databases)

        # 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 已提交
146 147 148
        end
      end

149
      def create_current(environment = env)
150 151 152
        each_current_configuration(environment) { |configuration|
          create configuration
        }
153
        ActiveRecord::Base.establish_connection(environment.to_sym)
154
      end
P
Pat Allan 已提交
155

156
      def drop(*arguments)
157
        configuration = arguments.first
158
        class_for_adapter(configuration["adapter"]).new(*arguments).drop
159
        $stdout.puts "Dropped database '#{configuration['database']}'" if verbose?
160
      rescue ActiveRecord::NoDatabaseError
161
        $stderr.puts "Database '#{configuration['database']}' does not exist"
162
      rescue Exception => error
163
        $stderr.puts error
164
        $stderr.puts "Couldn't drop database '#{configuration['database']}'"
165
        raise
166
      end
P
Pat Allan 已提交
167

168
      def drop_all
169 170
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
171

172
      def drop_current(environment = env)
173 174 175 176
        each_current_configuration(environment) { |configuration|
          drop configuration
        }
      end
P
Pat Allan 已提交
177

178
      def migrate
179
        check_target_version
P
Philippe Guay 已提交
180 181

        scope = ENV["SCOPE"]
182
        verbose_was, Migration.verbose = Migration.verbose, verbose?
183
        Base.connection.migration_context.migrate(target_version) do |migration|
184 185
          scope.blank? || scope == migration.scope
        end
186
        ActiveRecord::Base.clear_cache!
187 188
      ensure
        Migration.verbose = verbose_was
189 190
      end

191 192 193 194 195 196 197 198 199 200
      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

201
      def charset_current(environment = env)
S
Simon Jefford 已提交
202 203 204 205 206
        charset ActiveRecord::Base.configurations[environment]
      end

      def charset(*arguments)
        configuration = arguments.first
207
        class_for_adapter(configuration["adapter"]).new(*arguments).charset
S
Simon Jefford 已提交
208 209
      end

210
      def collation_current(environment = env)
211 212 213 214 215
        collation ActiveRecord::Base.configurations[environment]
      end

      def collation(*arguments)
        configuration = arguments.first
216
        class_for_adapter(configuration["adapter"]).new(*arguments).collation
217 218
      end

219
      def purge(configuration)
220
        class_for_adapter(configuration["adapter"]).new(configuration).purge
221
      end
P
Pat Allan 已提交
222

223 224 225 226 227 228 229 230 231 232
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

      def purge_current(environment = env)
        each_current_configuration(environment) { |configuration|
          purge configuration
        }
233
        ActiveRecord::Base.establish_connection(environment.to_sym)
234 235
      end

K
kennyj 已提交
236 237 238
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
239
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
240 241
      end

K
kennyj 已提交
242 243 244
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
245
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
246 247
      end

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

251
        verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"]
252 253 254
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

255 256 257 258
        case format
        when :ruby
          load(file)
        when :sql
259
          structure_load(configuration, file)
260 261 262
        else
          raise ArgumentError, "unknown format #{format.inspect}"
        end
263
        ActiveRecord::InternalMetadata.create_table
264
        ActiveRecord::InternalMetadata[:environment] = environment
265 266
      ensure
        Migration.verbose = verbose_was
267 268
      end

269
      def schema_file(format = ActiveRecord::Base.schema_format)
270 271 272 273
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
274 275
        case format
        when :ruby
276
          "schema.rb"
277
        when :sql
278
          "structure.sql"
279 280 281
        end
      end

282 283 284 285 286 287 288 289 290 291
      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

292
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
293
        each_current_configuration(environment) { |configuration, spec_name, env|
294
          load_schema(configuration, format, file, env, spec_name)
295
        }
296
        ActiveRecord::Base.establish_connection(environment.to_sym)
297 298
      end

299
      def check_schema_file(filename)
A
Arun Agrawal 已提交
300
        unless File.exist?(filename)
301
          message = %{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}.dup
302
          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)
303 304 305 306
          Kernel.abort message
        end
      end

307 308 309 310
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
311 312
          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" \
313 314 315 316
                "Seed loader should respond to load_seed method"
        end
      end

317 318 319 320 321 322 323 324 325 326
      # 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

327
      private
328 329 330
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
331

332
        def class_for_adapter(adapter)
333 334
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
335 336
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
337
          task.is_a?(String) ? task.constantize : task
338
        end
P
Pat Allan 已提交
339

340 341 342
        def each_current_configuration(environment)
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
343

344
          environments.each do |env|
E
eileencodes 已提交
345
            ActiveRecord::DatabaseConfigurations.configs_for(env) do |spec_name, configuration|
346 347
              yield configuration, spec_name, env
            end
348
          end
349 350
        end

351 352
        def each_local_configuration
          ActiveRecord::Base.configurations.each_value do |configuration|
353 354
            next unless configuration["database"]

355 356 357 358 359
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
360 361
          end
        end
P
Pat Allan 已提交
362

363 364 365
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
366
    end
P
Pat Allan 已提交
367
  end
368
end