database_tasks.rb 11.5 KB
Newer Older
1 2
module ActiveRecord
  module Tasks # :nodoc:
3
    class DatabaseAlreadyExists < StandardError; end # :nodoc:
4
    class DatabaseNotSupported < StandardError; end # :nodoc:
5

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

46
      extend self
P
Pat Allan 已提交
47

48 49
      attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader
      attr_accessor :database_configuration
50

51
      LOCAL_HOSTS = ["127.0.0.1", "localhost"]
52

53
      def check_protected_environments!
54
        unless ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"]
S
schneems 已提交
55 56 57 58 59 60 61
          current = ActiveRecord::Migrator.current_environment
          stored  = ActiveRecord::Migrator.last_stored_environment

          if ActiveRecord::Migrator.protected_environment?
            raise ActiveRecord::ProtectedEnvironmentError.new(stored)
          end

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

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

74 75 76
      register_task(/mysql/,        'ActiveRecord::Tasks::MySQLDatabaseTasks')
      register_task(/postgresql/,   'ActiveRecord::Tasks::PostgreSQLDatabaseTasks')
      register_task(/sqlite/,       'ActiveRecord::Tasks::SQLiteDatabaseTasks')
K
kennyj 已提交
77

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

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

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

      def root
        @root ||= Rails.root
      end

      def env
        @env ||= Rails.env
      end

      def seed_loader
        @seed_loader ||= Rails.application
      end

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

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

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

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

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

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

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

164
      def migrate
P
Philippe Guay 已提交
165 166
        raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty?

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

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

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

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

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

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

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

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

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

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

226
      def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc:
227 228
        file ||= schema_file(format)

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

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

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

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

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

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

288
      private
P
Pat Allan 已提交
289

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

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

302 303 304 305
          configurations = ActiveRecord::Base.configurations.values_at(*environments)
          configurations.compact.each do |configuration|
            yield configuration unless configuration["database"].blank?
          end
306 307
        end

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

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

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