database_tasks.rb 12.6 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 139 140 141 142 143
      def for_each
        databases = Rails.application.config.load_database_yaml
        ActiveRecord::DatabaseConfigurations.configs_for(Rails.env, databases) do |spec_name, _|
          yield spec_name
        end
      end

144
      def create_current(environment = env)
145 146 147
        each_current_configuration(environment) { |configuration|
          create configuration
        }
148
        ActiveRecord::Base.establish_connection(environment.to_sym)
149
      end
P
Pat Allan 已提交
150

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

163
      def drop_all
164 165
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
166

167
      def drop_current(environment = env)
168 169 170 171
        each_current_configuration(environment) { |configuration|
          drop configuration
        }
      end
P
Pat Allan 已提交
172

173
      def migrate
174
        check_target_version
P
Philippe Guay 已提交
175 176

        scope = ENV["SCOPE"]
177
        verbose_was, Migration.verbose = Migration.verbose, verbose?
178
        Base.connection.migration_context.migrate(target_version) do |migration|
179 180
          scope.blank? || scope == migration.scope
        end
181
        ActiveRecord::Base.clear_cache!
182 183
      ensure
        Migration.verbose = verbose_was
184 185
      end

186 187 188 189 190 191 192 193 194 195
      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

196
      def charset_current(environment = env)
S
Simon Jefford 已提交
197 198 199 200 201
        charset ActiveRecord::Base.configurations[environment]
      end

      def charset(*arguments)
        configuration = arguments.first
202
        class_for_adapter(configuration["adapter"]).new(*arguments).charset
S
Simon Jefford 已提交
203 204
      end

205
      def collation_current(environment = env)
206 207 208 209 210
        collation ActiveRecord::Base.configurations[environment]
      end

      def collation(*arguments)
        configuration = arguments.first
211
        class_for_adapter(configuration["adapter"]).new(*arguments).collation
212 213
      end

214
      def purge(configuration)
215
        class_for_adapter(configuration["adapter"]).new(configuration).purge
216
      end
P
Pat Allan 已提交
217

218 219 220 221 222 223 224 225 226 227
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

      def purge_current(environment = env)
        each_current_configuration(environment) { |configuration|
          purge configuration
        }
228
        ActiveRecord::Base.establish_connection(environment.to_sym)
229 230
      end

K
kennyj 已提交
231 232 233
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
234
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
235 236
      end

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

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

246 247 248
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

249 250 251 252
        case format
        when :ruby
          load(file)
        when :sql
253
          structure_load(configuration, file)
254 255 256
        else
          raise ArgumentError, "unknown format #{format.inspect}"
        end
257
        ActiveRecord::InternalMetadata.create_table
258
        ActiveRecord::InternalMetadata[:environment] = environment
259 260
      end

261
      def schema_file(format = ActiveRecord::Base.schema_format)
262 263 264 265
        File.join(db_dir, schema_file_type(format))
      end

      def schema_file_type(format = ActiveRecord::Base.schema_format)
266 267
        case format
        when :ruby
268
          "schema.rb"
269
        when :sql
270
          "structure.sql"
271 272 273
        end
      end

274 275 276 277 278 279 280 281 282 283
      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

284
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
285
        each_current_configuration(environment) { |configuration, spec_name, env|
286
          load_schema(configuration, format, file, env, spec_name)
287
        }
288
        ActiveRecord::Base.establish_connection(environment.to_sym)
289 290
      end

291
      def check_schema_file(filename)
A
Arun Agrawal 已提交
292
        unless File.exist?(filename)
293
          message = %{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}.dup
294
          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)
295 296 297 298
          Kernel.abort message
        end
      end

299 300 301 302
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
303 304
          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" \
305 306 307 308
                "Seed loader should respond to load_seed method"
        end
      end

309 310 311 312 313 314 315 316 317 318
      # 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

319
      private
320 321 322
        def verbose?
          ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
        end
P
Pat Allan 已提交
323

324
        def class_for_adapter(adapter)
325 326
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
327 328
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
329
          task.is_a?(String) ? task.constantize : task
330
        end
P
Pat Allan 已提交
331

332 333 334
        def each_current_configuration(environment)
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
335

336
          environments.each do |env|
E
eileencodes 已提交
337
            ActiveRecord::DatabaseConfigurations.configs_for(env) do |spec_name, configuration|
338 339
              yield configuration, spec_name, env
            end
340
          end
341 342
        end

343 344
        def each_local_configuration
          ActiveRecord::Base.configurations.each_value do |configuration|
345 346
            next unless configuration["database"]

347 348 349 350 351
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
352 353
          end
        end
P
Pat Allan 已提交
354

355 356 357
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
358
    end
P
Pat Allan 已提交
359
  end
360
end