database_tasks.rb 11.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"]
S
schneems 已提交
57 58 59 60 61 62 63
          current = ActiveRecord::Migrator.current_environment
          stored  = ActiveRecord::Migrator.last_stored_environment

          if ActiveRecord::Migrator.protected_environment?
            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']}'"
121
      rescue DatabaseAlreadyExists
122
        $stderr.puts "Database '#{configuration['database']}' already exists"
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']}'"
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
      def migrate
P
Philippe Guay 已提交
167 168
        raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty?

169
        verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] != "false" : true
170
        version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
P
Philippe Guay 已提交
171
        scope = ENV["SCOPE"]
172
        verbose_was, Migration.verbose = Migration.verbose, verbose
173
        Migrator.migrate(migrations_paths, version) do |migration|
174 175
          scope.blank? || scope == migration.scope
        end
176
        ActiveRecord::Base.clear_cache!
177 178
      ensure
        Migration.verbose = verbose_was
179 180
      end

181
      def charset_current(environment = env)
S
Simon Jefford 已提交
182 183 184 185 186
        charset ActiveRecord::Base.configurations[environment]
      end

      def charset(*arguments)
        configuration = arguments.first
187
        class_for_adapter(configuration["adapter"]).new(*arguments).charset
S
Simon Jefford 已提交
188 189
      end

190
      def collation_current(environment = env)
191 192 193 194 195
        collation ActiveRecord::Base.configurations[environment]
      end

      def collation(*arguments)
        configuration = arguments.first
196
        class_for_adapter(configuration["adapter"]).new(*arguments).collation
197 198
      end

199
      def purge(configuration)
200
        class_for_adapter(configuration["adapter"]).new(configuration).purge
201
      end
P
Pat Allan 已提交
202

203 204 205 206 207 208 209 210 211 212
      def purge_all
        each_local_configuration { |configuration|
          purge configuration
        }
      end

      def purge_current(environment = env)
        each_current_configuration(environment) { |configuration|
          purge configuration
        }
213
        ActiveRecord::Base.establish_connection(environment.to_sym)
214 215
      end

K
kennyj 已提交
216 217 218
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
219
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags)
K
kennyj 已提交
220 221
      end

K
kennyj 已提交
222 223 224
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
225
        class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags)
K
kennyj 已提交
226 227
      end

228
      def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env) # :nodoc:
229 230
        file ||= schema_file(format)

231 232 233
        case format
        when :ruby
          check_schema_file(file)
234
          ActiveRecord::Base.establish_connection(configuration)
235 236 237
          load(file)
        when :sql
          check_schema_file(file)
238
          structure_load(configuration, file)
239 240 241
        else
          raise ArgumentError, "unknown format #{format.inspect}"
        end
242
        ActiveRecord::InternalMetadata.create_table
243
        ActiveRecord::InternalMetadata[:environment] = environment
244 245
      end

246
      def schema_file(format = ActiveRecord::Base.schema_format)
247 248 249 250 251 252 253 254
        case format
        when :ruby
          File.join(db_dir, "schema.rb")
        when :sql
          File.join(db_dir, "structure.sql")
        end
      end

255
      def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
256 257
        each_current_configuration(environment) { |configuration, configuration_environment|
          load_schema configuration, format, file, configuration_environment
258
        }
259
        ActiveRecord::Base.establish_connection(environment.to_sym)
260 261
      end

262
      def check_schema_file(filename)
A
Arun Agrawal 已提交
263
        unless File.exist?(filename)
264
          message = %{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}.dup
265
          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)
266 267 268 269
          Kernel.abort message
        end
      end

270 271 272 273
      def load_seed
        if seed_loader
          seed_loader.load_seed
        else
274 275
          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" \
276 277 278 279
                "Seed loader should respond to load_seed method"
        end
      end

280 281 282 283 284 285 286 287 288 289
      # 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

290
      private
P
Pat Allan 已提交
291

292
        def class_for_adapter(adapter)
293 294
          _key, task = @tasks.each_pair.detect { |pattern, _task| adapter[pattern] }
          unless task
295 296
            raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
          end
297
          task.is_a?(String) ? task.constantize : task
298
        end
P
Pat Allan 已提交
299

300 301 302
        def each_current_configuration(environment)
          environments = [environment]
          environments << "test" if environment == "development"
P
Pat Allan 已提交
303

304 305 306 307
          ActiveRecord::Base.configurations.slice(*environments).each do |configuration_environment, configuration|
            next unless configuration["database"]

            yield configuration, configuration_environment
308
          end
309 310
        end

311 312 313
        def each_local_configuration
          ActiveRecord::Base.configurations.each_value do |configuration|
            next unless configuration["database"]
P
Pat Allan 已提交
314

315 316 317 318 319
            if local_database?(configuration)
              yield configuration
            else
              $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
            end
320 321
          end
        end
P
Pat Allan 已提交
322

323 324 325
        def local_database?(configuration)
          configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"])
        end
326
    end
P
Pat Allan 已提交
327
  end
328
end