database_tasks.rb 12.0 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

137
      def create_current(environment = env)
138 139 140
        each_current_configuration(environment) { |configuration|
          create configuration
        }
141
        ActiveRecord::Base.establish_connection(environment.to_sym)
142
      end
P
Pat Allan 已提交
143

144
      def drop(*arguments)
145
        configuration = arguments.first
146
        class_for_adapter(configuration["adapter"]).new(*arguments).drop
147
        $stdout.puts "Dropped database '#{configuration['database']}'" if verbose?
148
      rescue ActiveRecord::NoDatabaseError
149
        $stderr.puts "Database '#{configuration['database']}' does not exist"
150
      rescue Exception => error
151
        $stderr.puts error
152
        $stderr.puts "Couldn't drop database '#{configuration['database']}'"
153
        raise
154
      end
P
Pat Allan 已提交
155

156
      def drop_all
157 158
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
159

160
      def drop_current(environment = env)
161 162 163 164
        each_current_configuration(environment) { |configuration|
          drop configuration
        }
      end
P
Pat Allan 已提交
165

166 167 168 169
      def verbose?
        ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
      end

170
      def migrate
171
        check_target_version
P
Philippe Guay 已提交
172

173
        verbose = verbose?
P
Philippe Guay 已提交
174
        scope = ENV["SCOPE"]
175
        verbose_was, Migration.verbose = Migration.verbose, verbose
176
        Base.connection.migration_context.migrate(target_version) do |migration|
177 178
          scope.blank? || scope == migration.scope
        end
179
        ActiveRecord::Base.clear_cache!
180 181
      ensure
        Migration.verbose = verbose_was
182 183
      end

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

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

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

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

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

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

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

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

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

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

241
      def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env) # :nodoc:
242 243
        file ||= schema_file(format)

244 245 246
        check_schema_file(file)
        ActiveRecord::Base.establish_connection(configuration)

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

259
      def schema_file(format = ActiveRecord::Base.schema_format)
260 261 262 263 264 265 266 267
        case format
        when :ruby
          File.join(db_dir, "schema.rb")
        when :sql
          File.join(db_dir, "structure.sql")
        end
      end

268
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
269 270
        each_current_configuration(environment) { |configuration, configuration_environment|
          load_schema configuration, format, file, configuration_environment
271
        }
272
        ActiveRecord::Base.establish_connection(environment.to_sym)
273 274
      end

275
      def check_schema_file(filename)
A
Arun Agrawal 已提交
276
        unless File.exist?(filename)
277
          message = %{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}.dup
278
          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)
279 280 281 282
          Kernel.abort message
        end
      end

283 284 285 286
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
287 288
          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" \
289 290 291 292
                "Seed loader should respond to load_seed method"
        end
      end

293 294 295 296 297 298 299 300 301 302
      # 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

303
      private
P
Pat Allan 已提交
304

305
        def class_for_adapter(adapter)
306 307
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
308 309
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
310
          task.is_a?(String) ? task.constantize : task
311
        end
P
Pat Allan 已提交
312

313 314 315
        def each_current_configuration(environment)
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
316

317
          ActiveRecord::Base.configurations.slice(*environments).each do |configuration_environment, configuration|
318 319
            next unless configuration["database"]

320
            yield configuration, configuration_environment
321
          end
322 323
        end

324 325
        def each_local_configuration
          ActiveRecord::Base.configurations.each_value do |configuration|
326 327
            next unless configuration["database"]

328 329 330 331 332
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
333 334
          end
        end
P
Pat Allan 已提交
335

336 337 338
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
339
    end
P
Pat Allan 已提交
340
  end
341
end