1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #37185 from seejohnrun/config-symbols

Use symbols everywhere for database configurations
This commit is contained in:
Eileen M. Uchitelle 2019-09-13 13:03:11 -04:00 committed by GitHub
commit 42dea6b0f6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
36 changed files with 426 additions and 392 deletions

View file

@ -1,3 +1,7 @@
* Add `DatabaseConfig#configuration_hash` to return database configuration hashes with symbol keys, and use all symbol-key configuration hashes internally. Deprecate `DatabaseConfig#config` which returns a String-keyed `Hash` with the same values.
*John Crepezzi*, *Eileen Uchitelle*
* Allow column names to be passed to `remove_index` positionally along with other options. * Allow column names to be passed to `remove_index` positionally along with other options.
Passing other options can be necessary to make `remove_index` correctly reversible. Passing other options can be necessary to make `remove_index` correctly reversible.

View file

@ -385,14 +385,14 @@ module ActiveRecord
@spec = spec @spec = spec
@checkout_timeout = (spec.config[:checkout_timeout] && spec.config[:checkout_timeout].to_f) || 5 @checkout_timeout = (spec.underlying_configuration_hash[:checkout_timeout] && spec.underlying_configuration_hash[:checkout_timeout].to_f) || 5
if @idle_timeout = spec.config.fetch(:idle_timeout, 300) if @idle_timeout = spec.underlying_configuration_hash.fetch(:idle_timeout, 300)
@idle_timeout = @idle_timeout.to_f @idle_timeout = @idle_timeout.to_f
@idle_timeout = nil if @idle_timeout <= 0 @idle_timeout = nil if @idle_timeout <= 0
end end
# default max pool size to 5 # default max pool size to 5
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 @size = (spec.underlying_configuration_hash[:pool] && spec.underlying_configuration_hash[:pool].to_i) || 5
# This variable tracks the cache of threads mapped to reserved connections, with the # This variable tracks the cache of threads mapped to reserved connections, with the
# sole purpose of speeding up the +connection+ method. It is not the authoritative # sole purpose of speeding up the +connection+ method. It is not the authoritative
@ -422,7 +422,7 @@ module ActiveRecord
# +reaping_frequency+ is configurable mostly for historical reasons, but it could # +reaping_frequency+ is configurable mostly for historical reasons, but it could
# also be useful if someone wants a very low +idle_timeout+. # also be useful if someone wants a very low +idle_timeout+.
reaping_frequency = spec.config.fetch(:reaping_frequency, 60) reaping_frequency = spec.underlying_configuration_hash.fetch(:reaping_frequency, 60)
@reaper = Reaper.new(self, reaping_frequency && reaping_frequency.to_f) @reaper = Reaper.new(self, reaping_frequency && reaping_frequency.to_f)
@reaper.run @reaper.run
end end
@ -505,7 +505,7 @@ module ActiveRecord
# Raises: # Raises:
# - ActiveRecord::ExclusiveConnectionTimeoutError if unable to gain ownership of all # - ActiveRecord::ExclusiveConnectionTimeoutError if unable to gain ownership of all
# connections in the pool within a timeout interval (default duration is # connections in the pool within a timeout interval (default duration is
# <tt>spec.config[:checkout_timeout] * 2</tt> seconds). # <tt>spec.underlying_configuration_hash[:checkout_timeout] * 2</tt> seconds).
def disconnect(raise_on_acquisition_timeout = true) def disconnect(raise_on_acquisition_timeout = true)
with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do
synchronize do synchronize do
@ -526,7 +526,7 @@ module ActiveRecord
# #
# The pool first tries to gain ownership of all connections. If unable to # The pool first tries to gain ownership of all connections. If unable to
# do so within a timeout interval (default duration is # do so within a timeout interval (default duration is
# <tt>spec.config[:checkout_timeout] * 2</tt> seconds), then the pool is forcefully # <tt>spec.underlying_configuration_hash[:checkout_timeout] * 2</tt> seconds), then the pool is forcefully
# disconnected without any regard for other connection owning threads. # disconnected without any regard for other connection owning threads.
def disconnect! def disconnect!
disconnect(false) disconnect(false)
@ -557,7 +557,7 @@ module ActiveRecord
# Raises: # Raises:
# - ActiveRecord::ExclusiveConnectionTimeoutError if unable to gain ownership of all # - ActiveRecord::ExclusiveConnectionTimeoutError if unable to gain ownership of all
# connections in the pool within a timeout interval (default duration is # connections in the pool within a timeout interval (default duration is
# <tt>spec.config[:checkout_timeout] * 2</tt> seconds). # <tt>spec.underlying_configuration_hash[:checkout_timeout] * 2</tt> seconds).
def clear_reloadable_connections(raise_on_acquisition_timeout = true) def clear_reloadable_connections(raise_on_acquisition_timeout = true)
with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do
synchronize do synchronize do
@ -579,7 +579,7 @@ module ActiveRecord
# #
# The pool first tries to gain ownership of all connections. If unable to # The pool first tries to gain ownership of all connections. If unable to
# do so within a timeout interval (default duration is # do so within a timeout interval (default duration is
# <tt>spec.config[:checkout_timeout] * 2</tt> seconds), then the pool forcefully # <tt>spec.underlying_configuration_hash[:checkout_timeout] * 2</tt> seconds), then the pool forcefully
# clears the cache and reloads connections without any regard for other # clears the cache and reloads connections without any regard for other
# connection owning threads. # connection owning threads.
def clear_reloadable_connections! def clear_reloadable_connections!
@ -899,7 +899,7 @@ module ActiveRecord
alias_method :release, :remove_connection_from_thread_cache alias_method :release, :remove_connection_from_thread_cache
def new_connection def new_connection
Base.send(spec.adapter_method, spec.config).tap do |conn| Base.send(spec.adapter_method, spec.underlying_configuration_hash).tap do |conn|
conn.check_version conn.check_version
end end
end end
@ -1074,7 +1074,7 @@ module ActiveRecord
} }
if spec if spec
payload[:spec_name] = spec.name payload[:spec_name] = spec.name
payload[:config] = spec.config payload[:config] = spec.underlying_configuration_hash
end end
message_bus.instrument("!connection.active_record", payload) do message_bus.instrument("!connection.active_record", payload) do
@ -1149,7 +1149,7 @@ module ActiveRecord
if pool = owner_to_pool.delete(spec_name) if pool = owner_to_pool.delete(spec_name)
pool.automatic_reconnect = false pool.automatic_reconnect = false
pool.disconnect! pool.disconnect!
pool.spec.config pool.spec.underlying_configuration_hash
end end
end end

View file

@ -5,14 +5,18 @@ require "uri"
module ActiveRecord module ActiveRecord
module ConnectionAdapters module ConnectionAdapters
class ConnectionSpecification #:nodoc: class ConnectionSpecification #:nodoc:
attr_reader :name, :config, :adapter_method attr_reader :name, :adapter_method
def initialize(name, config, adapter_method) def initialize(name, config, adapter_method)
@name, @config, @adapter_method = name, config, adapter_method @name, @config, @adapter_method = name, config, adapter_method
end end
def underlying_configuration_hash
@config
end
def initialize_dup(original) def initialize_dup(original)
@config = original.config.dup @config = original.underlying_configuration_hash.dup
end end
def to_hash def to_hash
@ -26,14 +30,14 @@ module ActiveRecord
# url = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000" # url = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000"
# ConnectionUrlResolver.new(url).to_hash # ConnectionUrlResolver.new(url).to_hash
# # => { # # => {
# "adapter" => "postgresql", # adapter: "postgresql",
# "host" => "localhost", # host: "localhost",
# "port" => 9000, # port: 9000,
# "database" => "foo_test", # database: "foo_test",
# "username" => "foo", # username: "foo",
# "password" => "bar", # password: "bar",
# "pool" => "5", # pool: "5",
# "timeout" => "3000" # timeout: "3000"
# } # }
def initialize(url) def initialize(url)
raise "Database URL cannot be empty" if url.blank? raise "Database URL cannot be empty" if url.blank?
@ -65,29 +69,31 @@ module ActiveRecord
# Converts the query parameters of the URI into a hash. # Converts the query parameters of the URI into a hash.
# #
# "localhost?pool=5&reaping_frequency=2" # "localhost?pool=5&reaping_frequency=2"
# # => { "pool" => "5", "reaping_frequency" => "2" } # # => { pool: "5", reaping_frequency: "2" }
# #
# returns empty hash if no query present. # returns empty hash if no query present.
# #
# "localhost" # "localhost"
# # => {} # # => {}
def query_hash def query_hash
Hash[(@query || "").split("&").map { |pair| pair.split("=") }] Hash[(@query || "").split("&").map { |pair| pair.split("=") }].symbolize_keys
end end
def raw_config def raw_config
if uri.opaque if uri.opaque
query_hash.merge( query_hash.merge(
"adapter" => @adapter, adapter: @adapter,
"database" => uri.opaque) database: uri.opaque
)
else else
query_hash.merge( query_hash.merge(
"adapter" => @adapter, adapter: @adapter,
"username" => uri.user, username: uri.user,
"password" => uri.password, password: uri.password,
"port" => uri.port, port: uri.port,
"database" => database_from_path, database: database_from_path,
"host" => uri.hostname) host: uri.hostname
)
end end
end end
@ -126,13 +132,13 @@ module ActiveRecord
# #
# configurations = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } } # configurations = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
# Resolver.new(configurations).resolve(:production) # Resolver.new(configurations).resolve(:production)
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3"} # # => { host: "localhost", database: "foo", adapter: "sqlite3"}
# #
# Initialized with URL configuration strings. # Initialized with URL configuration strings.
# #
# configurations = { "production" => "postgresql://localhost/foo" } # configurations = { "production" => "postgresql://localhost/foo" }
# Resolver.new(configurations).resolve(:production) # Resolver.new(configurations).resolve(:production)
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } # # => { host: "localhost", database: "foo", adapter: "postgresql" }
# #
def resolve(config_or_env, pool_name = nil) def resolve(config_or_env, pool_name = nil)
if config_or_env if config_or_env
@ -151,8 +157,8 @@ module ActiveRecord
# spec = Resolver.new(config).spec(:production) # spec = Resolver.new(config).spec(:production)
# spec.adapter_method # spec.adapter_method
# # => "sqlite3_connection" # # => "sqlite3_connection"
# spec.config # spec.underlying_configuration_hash
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } # # => { host: "localhost", database: "foo", adapter: "sqlite3" }
# #
def spec(config) def spec(config)
pool_name = config if config.is_a?(Symbol) pool_name = config if config.is_a?(Symbol)
@ -205,12 +211,12 @@ module ActiveRecord
# One layer deep hash of connection values. # One layer deep hash of connection values.
# #
# Resolver.new({}).resolve_connection("adapter" => "sqlite3") # Resolver.new({}).resolve_connection("adapter" => "sqlite3")
# # => { "adapter" => "sqlite3" } # # => { adapter: "sqlite3" }
# #
# Connection URL. # Connection URL.
# #
# Resolver.new({}).resolve_connection("postgresql://localhost/foo") # Resolver.new({}).resolve_connection("postgresql://localhost/foo")
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } # # => { host: "localhost", database: "foo", adapter: "postgresql" }
# #
def resolve_connection(config_or_env, pool_name = nil) def resolve_connection(config_or_env, pool_name = nil)
case config_or_env case config_or_env
@ -236,16 +242,16 @@ module ActiveRecord
# configurations = #<ActiveRecord::DatabaseConfigurations:0x00007fd9fdace3e0 # configurations = #<ActiveRecord::DatabaseConfigurations:0x00007fd9fdace3e0
# @configurations=[ # @configurations=[
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd9fdace250 # #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd9fdace250
# @env_name="production", @spec_name="primary", @config={"database"=>"my_db"}> # @env_name="production", @spec_name="primary", @config={database: "my_db"}>
# ]> # ]>
# #
# Resolver.new(configurations).resolve_symbol_connection(:production, "primary") # Resolver.new(configurations).resolve_symbol_connection(:production, "primary")
# # => { "database" => "my_db" } # # => { database: "my_db" }
def resolve_symbol_connection(env_name, pool_name) def resolve_symbol_connection(env_name, pool_name)
db_config = configurations.find_db_config(env_name) db_config = configurations.find_db_config(env_name)
if db_config if db_config
resolve_connection(db_config.config).merge("name" => pool_name.to_s) resolve_connection(db_config.configuration_hash).merge(name: pool_name.to_s)
else else
raise AdapterNotSpecified, <<~MSG raise AdapterNotSpecified, <<~MSG
The `#{env_name}` database is not configured for the `#{ActiveRecord::ConnectionHandling::DEFAULT_ENV.call}` environment. The `#{env_name}` database is not configured for the `#{ActiveRecord::ConnectionHandling::DEFAULT_ENV.call}` environment.
@ -275,8 +281,8 @@ module ActiveRecord
# hash and merges with the rest of the hash. # hash and merges with the rest of the hash.
# Connection details inside of the "url" key win any merge conflicts # Connection details inside of the "url" key win any merge conflicts
def resolve_hash_connection(spec) def resolve_hash_connection(spec)
if spec["url"] && !spec["url"].match?(/^jdbc:/) if spec[:url] && !spec[:url].match?(/^jdbc:/)
connection_hash = resolve_url_connection(spec.delete("url")) connection_hash = resolve_url_connection(spec.delete(:url))
spec.merge!(connection_hash) spec.merge!(connection_hash)
end end
spec spec
@ -285,7 +291,7 @@ module ActiveRecord
# Takes a connection URL. # Takes a connection URL.
# #
# Resolver.new({}).resolve_url_connection("postgresql://localhost/foo") # Resolver.new({}).resolve_url_connection("postgresql://localhost/foo")
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } # # => { host: "localhost", database: "foo", adapter: "postgresql" }
# #
def resolve_url_connection(url) def resolve_url_connection(url)
ConnectionUrlResolver.new(url).to_hash ConnectionUrlResolver.new(url).to_hash

View file

@ -227,7 +227,7 @@ module ActiveRecord
# #
# Please use only for reading. # Please use only for reading.
def connection_config def connection_config
connection_pool.spec.config connection_pool.spec.underlying_configuration_hash
end end
def connection_pool def connection_pool

View file

@ -43,9 +43,9 @@ module ActiveRecord
# #
# #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ # #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development", # #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
# @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, # @spec_name="primary", @config={adapter: "sqlite3", database: "db/development.sqlite3"}>,
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production", # #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production",
# @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/production.sqlite3"}> # @spec_name="primary", @config={adapter: "sqlite3", database: "db/production.sqlite3"}>
# ]> # ]>
def self.configurations=(config) def self.configurations=(config)
@@configurations = ActiveRecord::DatabaseConfigurations.new(config) @@configurations = ActiveRecord::DatabaseConfigurations.new(config)

View file

@ -61,7 +61,7 @@ module ActiveRecord
# { database: "my_db", adapter: "mysql2" } # { database: "my_db", adapter: "mysql2" }
def default_hash(env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s) def default_hash(env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s)
default = find_db_config(env) default = find_db_config(env)
default.config if default default.configuration_hash if default
end end
alias :[] :default_hash alias :[] :default_hash
@ -96,14 +96,14 @@ module ActiveRecord
def each def each
throw_getter_deprecation(:each) throw_getter_deprecation(:each)
configurations.each { |config| configurations.each { |config|
yield [config.env_name, config.config] yield [config.env_name, config.configuration_hash]
} }
end end
def first def first
throw_getter_deprecation(:first) throw_getter_deprecation(:first)
config = configurations.first config = configurations.first
[config.env_name, config.config] [config.env_name, config.configuration_hash]
end end
private private
@ -147,7 +147,7 @@ module ActiveRecord
when String when String
build_db_config_from_string(env_name, spec_name, config) build_db_config_from_string(env_name, spec_name, config)
when Hash when Hash
build_db_config_from_hash(env_name, spec_name, config.stringify_keys) build_db_config_from_hash(env_name, spec_name, config.symbolize_keys)
else else
raise InvalidConfigurationError, "'{ #{env_name} => #{config} }' is not a valid configuration. Expected '#{config}' to be a URL string or a Hash." raise InvalidConfigurationError, "'{ #{env_name} => #{config} }' is not a valid configuration. Expected '#{config}' to be a URL string or a Hash."
end end
@ -164,10 +164,10 @@ module ActiveRecord
end end
def build_db_config_from_hash(env_name, spec_name, config) def build_db_config_from_hash(env_name, spec_name, config)
if config.has_key?("url") if config.has_key?(:url)
url = config["url"] url = config[:url]
config_without_url = config.dup config_without_url = config.dup
config_without_url.delete "url" config_without_url.delete :url
ActiveRecord::DatabaseConfigurations::UrlConfig.new(env_name, spec_name, url, config_without_url) ActiveRecord::DatabaseConfigurations::UrlConfig.new(env_name, spec_name, url, config_without_url)
else else
@ -179,7 +179,7 @@ module ActiveRecord
configs.map do |config| configs.map do |config|
next config if config.url_config? || config.env_name != current_env next config if config.url_config? || config.env_name != current_env
url_config = environment_url_config(current_env, config.spec_name, config.config) url_config = environment_url_config(current_env, config.spec_name, config.configuration_hash)
url_config || config url_config || config
end end
end end
@ -205,7 +205,7 @@ module ActiveRecord
configs_for(env_name: args.first) configs_for(env_name: args.first)
when :values when :values
throw_getter_deprecation(method) throw_getter_deprecation(method)
configurations.map(&:config) configurations.map(&:configuration_hash)
when :[]= when :[]=
throw_setter_deprecation(method) throw_setter_deprecation(method)

View file

@ -13,6 +13,11 @@ module ActiveRecord
@spec_name = spec_name @spec_name = spec_name
end end
def config
ActiveSupport::Deprecation.warn("DatabaseConfig#config will be removed in 6.2.0 in favor of DatabaseConfigurations#configuration_hash which returns a hash with symbol keys")
configuration_hash.stringify_keys
end
def replica? def replica?
raise NotImplementedError raise NotImplementedError
end end
@ -26,7 +31,7 @@ module ActiveRecord
end end
def to_legacy_hash def to_legacy_hash
{ env_name => config } { env_name => configuration_hash.stringify_keys }
end end
def for_current_env? def for_current_env?

View file

@ -12,7 +12,7 @@ module ActiveRecord
# Becomes: # Becomes:
# #
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 # #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10
# @env_name="development", @spec_name="primary", @config={"database"=>"db_name"}> # @env_name="development", @spec_name="primary", @config={database: "db_name"}>
# #
# ==== Options # ==== Options
# #
@ -25,25 +25,27 @@ module ActiveRecord
# database adapter, name, and other important information for database # database adapter, name, and other important information for database
# connections. # connections.
class HashConfig < DatabaseConfig class HashConfig < DatabaseConfig
attr_reader :config
def initialize(env_name, spec_name, config) def initialize(env_name, spec_name, config)
super(env_name, spec_name) super(env_name, spec_name)
@config = config @config = config.symbolize_keys
end
def configuration_hash
@config
end end
# Determines whether a database configuration is for a replica / readonly # Determines whether a database configuration is for a replica / readonly
# connection. If the +replica+ key is present in the config, +replica?+ will # connection. If the +replica+ key is present in the config, +replica?+ will
# return +true+. # return +true+.
def replica? def replica?
config["replica"] configuration_hash[:replica]
end end
# The migrations paths for a database configuration. If the # The migrations paths for a database configuration. If the
# +migrations_paths+ key is present in the config, +migrations_paths+ # +migrations_paths+ key is present in the config, +migrations_paths+
# will return its value. # will return its value.
def migrations_paths def migrations_paths
config["migrations_paths"] configuration_hash[:migrations_paths]
end end
end end
end end

View file

@ -14,7 +14,7 @@ module ActiveRecord
# #
# #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fdc3238f340 # #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fdc3238f340
# @env_name="default_env", @spec_name="primary", # @env_name="default_env", @spec_name="primary",
# @config={"adapter"=>"postgresql", "database"=>"foo", "host"=>"localhost"}, # @config={adapter: "postgresql", database: "foo", host: "localhost"},
# @url="postgres://localhost/foo"> # @url="postgres://localhost/foo">
# #
# ==== Options # ==== Options
@ -29,14 +29,18 @@ module ActiveRecord
# database adapter, name, and other important information for database # database adapter, name, and other important information for database
# connections. # connections.
class UrlConfig < DatabaseConfig class UrlConfig < DatabaseConfig
attr_reader :url, :config attr_reader :url
def initialize(env_name, spec_name, url, config = {}) def initialize(env_name, spec_name, url, config = {})
super(env_name, spec_name) super(env_name, spec_name)
@config = build_config(config, url) @config = build_config(config, url).symbolize_keys
@url = url @url = url
end end
def configuration_hash
@config
end
def url_config? # :nodoc: def url_config? # :nodoc:
true true
end end
@ -45,20 +49,20 @@ module ActiveRecord
# connection. If the +replica+ key is present in the config, +replica?+ will # connection. If the +replica+ key is present in the config, +replica?+ will
# return +true+. # return +true+.
def replica? def replica?
config["replica"] configuration_hash[:replica]
end end
# The migrations paths for a database configuration. If the # The migrations paths for a database configuration. If the
# +migrations_paths+ key is present in the config, +migrations_paths+ # +migrations_paths+ key is present in the config, +migrations_paths+
# will return its value. # will return its value.
def migrations_paths def migrations_paths
config["migrations_paths"] configuration_hash[:migrations_paths]
end end
private private
def build_url_hash(url) def build_url_hash(url)
if url.nil? || /^jdbc:/.match?(url) if url.nil? || /^jdbc:/.match?(url)
{ "url" => url } { url: url }
else else
ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(url).to_hash ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(url).to_hash
end end

View file

@ -591,7 +591,7 @@ module ActiveRecord
all_configs = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env) all_configs = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env)
needs_update = !all_configs.all? do |db_config| needs_update = !all_configs.all? do |db_config|
Tasks::DatabaseTasks.schema_up_to_date?(db_config.config, ActiveRecord::Base.schema_format, nil, Rails.env, db_config.spec_name) Tasks::DatabaseTasks.schema_up_to_date?(db_config.configuration_hash, ActiveRecord::Base.schema_format, nil, Rails.env, db_config.spec_name)
end end
if needs_update if needs_update

View file

@ -29,7 +29,7 @@ db_namespace = namespace :db do
desc "Create #{spec_name} database for current environment" desc "Create #{spec_name} database for current environment"
task spec_name => :load_config do task spec_name => :load_config do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Tasks::DatabaseTasks.create(db_config.config) ActiveRecord::Tasks::DatabaseTasks.create(db_config.configuration_hash)
end end
end end
end end
@ -48,7 +48,7 @@ db_namespace = namespace :db do
desc "Drop #{spec_name} database for current environment" desc "Drop #{spec_name} database for current environment"
task spec_name => [:load_config, :check_protected_environments] do task spec_name => [:load_config, :check_protected_environments] do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Tasks::DatabaseTasks.drop(db_config.config) ActiveRecord::Tasks::DatabaseTasks.drop(db_config.configuration_hash)
end end
end end
end end
@ -81,7 +81,7 @@ db_namespace = namespace :db do
desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)." desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
task migrate: :load_config do task migrate: :load_config do
ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.migrate ActiveRecord::Tasks::DatabaseTasks.migrate
end end
db_namespace["_dump"].invoke db_namespace["_dump"].invoke
@ -107,7 +107,7 @@ db_namespace = namespace :db do
desc "Migrate #{spec_name} database for current environment" desc "Migrate #{spec_name} database for current environment"
task spec_name => :load_config do task spec_name => :load_config do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.migrate ActiveRecord::Tasks::DatabaseTasks.migrate
end end
end end
@ -150,7 +150,7 @@ db_namespace = namespace :db do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.check_target_version ActiveRecord::Tasks::DatabaseTasks.check_target_version
ActiveRecord::Base.connection.migration_context.run( ActiveRecord::Base.connection.migration_context.run(
:up, :up,
@ -184,7 +184,7 @@ db_namespace = namespace :db do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.check_target_version ActiveRecord::Tasks::DatabaseTasks.check_target_version
ActiveRecord::Base.connection.migration_context.run( ActiveRecord::Base.connection.migration_context.run(
:down, :down,
@ -199,7 +199,7 @@ db_namespace = namespace :db do
desc "Display status of migrations" desc "Display status of migrations"
task status: :load_config do task status: :load_config do
ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.migrate_status ActiveRecord::Tasks::DatabaseTasks.migrate_status
end end
end end
@ -209,7 +209,7 @@ db_namespace = namespace :db do
desc "Display status of migrations for #{spec_name} database" desc "Display status of migrations for #{spec_name} database"
task spec_name => :load_config do task spec_name => :load_config do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.migrate_status ActiveRecord::Tasks::DatabaseTasks.migrate_status
end end
end end
@ -253,7 +253,7 @@ db_namespace = namespace :db do
# desc "Raises an error if there are pending migrations" # desc "Raises an error if there are pending migrations"
task abort_if_pending_migrations: :load_config do task abort_if_pending_migrations: :load_config do
pending_migrations = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).flat_map do |db_config| pending_migrations = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).flat_map do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Base.connection.migration_context.open.pending_migrations ActiveRecord::Base.connection.migration_context.open.pending_migrations
end end
@ -274,7 +274,7 @@ db_namespace = namespace :db do
# desc "Raises an error if there are pending migrations for #{spec_name} database" # desc "Raises an error if there are pending migrations for #{spec_name} database"
task spec_name => :load_config do task spec_name => :load_config do
db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name)
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
pending_migrations = ActiveRecord::Base.connection.migration_context.open.pending_migrations pending_migrations = ActiveRecord::Base.connection.migration_context.open.pending_migrations
@ -297,18 +297,18 @@ db_namespace = namespace :db do
seed = false seed = false
ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
# Skipped when no database # Skipped when no database
ActiveRecord::Tasks::DatabaseTasks.migrate ActiveRecord::Tasks::DatabaseTasks.migrate
if ActiveRecord::Base.dump_schema_after_migration if ActiveRecord::Base.dump_schema_after_migration
ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.config, ActiveRecord::Base.schema_format, db_config.spec_name) ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.configuration_hash, ActiveRecord::Base.schema_format, db_config.spec_name)
end end
rescue ActiveRecord::NoDatabaseError rescue ActiveRecord::NoDatabaseError
ActiveRecord::Tasks::DatabaseTasks.create_current(db_config.env_name, db_config.spec_name) ActiveRecord::Tasks::DatabaseTasks.create_current(db_config.env_name, db_config.spec_name)
ActiveRecord::Tasks::DatabaseTasks.load_schema( ActiveRecord::Tasks::DatabaseTasks.load_schema(
db_config.config, db_config.configuration_hash,
ActiveRecord::Base.schema_format, ActiveRecord::Base.schema_format,
nil, nil,
db_config.env_name, db_config.env_name,
@ -385,8 +385,8 @@ db_namespace = namespace :db do
desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record" desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record"
task dump: :load_config do task dump: :load_config do
ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.config, :ruby, db_config.spec_name) ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.configuration_hash, :ruby, db_config.spec_name)
end end
db_namespace["schema:dump"].reenable db_namespace["schema:dump"].reenable
@ -405,7 +405,7 @@ db_namespace = namespace :db do
desc "Creates a db/schema_cache.yml file." desc "Creates a db/schema_cache.yml file."
task dump: :load_config do task dump: :load_config do
ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
filename = ActiveRecord::Tasks::DatabaseTasks.cache_dump_filename(db_config.spec_name) filename = ActiveRecord::Tasks::DatabaseTasks.cache_dump_filename(db_config.spec_name)
ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache( ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(
ActiveRecord::Base.connection, ActiveRecord::Base.connection,
@ -428,8 +428,8 @@ db_namespace = namespace :db do
desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql" desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql"
task dump: :load_config do task dump: :load_config do
ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config|
ActiveRecord::Base.establish_connection(db_config.config) ActiveRecord::Base.establish_connection(db_config.configuration_hash)
ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.config, :sql, db_config.spec_name) ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.configuration_hash, :sql, db_config.spec_name)
end end
db_namespace["structure:dump"].reenable db_namespace["structure:dump"].reenable
@ -462,7 +462,7 @@ db_namespace = namespace :db do
ActiveRecord::Schema.verbose = false ActiveRecord::Schema.verbose = false
ActiveRecord::Base.configurations.configs_for(env_name: "test").each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: "test").each do |db_config|
filename = ActiveRecord::Tasks::DatabaseTasks.dump_filename(db_config.spec_name, :ruby) filename = ActiveRecord::Tasks::DatabaseTasks.dump_filename(db_config.spec_name, :ruby)
ActiveRecord::Tasks::DatabaseTasks.load_schema(db_config.config, :ruby, filename, "test") ActiveRecord::Tasks::DatabaseTasks.load_schema(db_config.configuration_hash, :ruby, filename, "test")
end end
ensure ensure
if should_reconnect if should_reconnect
@ -474,14 +474,14 @@ db_namespace = namespace :db do
task load_structure: %w(db:test:purge) do task load_structure: %w(db:test:purge) do
ActiveRecord::Base.configurations.configs_for(env_name: "test").each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: "test").each do |db_config|
filename = ActiveRecord::Tasks::DatabaseTasks.dump_filename(db_config.spec_name, :sql) filename = ActiveRecord::Tasks::DatabaseTasks.dump_filename(db_config.spec_name, :sql)
ActiveRecord::Tasks::DatabaseTasks.load_schema(db_config.config, :sql, filename, "test") ActiveRecord::Tasks::DatabaseTasks.load_schema(db_config.configuration_hash, :sql, filename, "test")
end end
end end
# desc "Empty the test database" # desc "Empty the test database"
task purge: %w(load_config check_protected_environments) do task purge: %w(load_config check_protected_environments) do
ActiveRecord::Base.configurations.configs_for(env_name: "test").each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: "test").each do |db_config|
ActiveRecord::Tasks::DatabaseTasks.purge(db_config.config) ActiveRecord::Tasks::DatabaseTasks.purge(db_config.configuration_hash)
end end
end end

View file

@ -116,19 +116,19 @@ module ActiveRecord
if options.has_key?(:config) if options.has_key?(:config)
@current_config = options[:config] @current_config = options[:config]
else else
@current_config ||= ActiveRecord::Base.configurations.configs_for(env_name: options[:env], spec_name: options[:spec]).config @current_config ||= ActiveRecord::Base.configurations.configs_for(env_name: options[:env], spec_name: options[:spec]).underlying_configuration_hash
end end
end end
def create(*arguments) def create(*arguments)
configuration = arguments.first configuration = arguments.first.symbolize_keys
class_for_adapter(configuration["adapter"]).new(*arguments).create class_for_adapter(configuration[:adapter]).new(*arguments).create
$stdout.puts "Created database '#{configuration['database']}'" if verbose? $stdout.puts "Created database '#{configuration[:database]}'" if verbose?
rescue DatabaseAlreadyExists rescue DatabaseAlreadyExists
$stderr.puts "Database '#{configuration['database']}' already exists" if verbose? $stderr.puts "Database '#{configuration[:database]}' already exists" if verbose?
rescue Exception => error rescue Exception => error
$stderr.puts error $stderr.puts error
$stderr.puts "Couldn't create '#{configuration['database']}' database. Please check your configuration." $stderr.puts "Couldn't create '#{configuration[:database]}' database. Please check your configuration."
raise raise
end end
@ -187,14 +187,14 @@ module ActiveRecord
end end
def drop(*arguments) def drop(*arguments)
configuration = arguments.first configuration = arguments.first.symbolize_keys
class_for_adapter(configuration["adapter"]).new(*arguments).drop class_for_adapter(configuration[:adapter]).new(*arguments).drop
$stdout.puts "Dropped database '#{configuration['database']}'" if verbose? $stdout.puts "Dropped database '#{configuration[:database]}'" if verbose?
rescue ActiveRecord::NoDatabaseError rescue ActiveRecord::NoDatabaseError
$stderr.puts "Database '#{configuration['database']}' does not exist" $stderr.puts "Database '#{configuration[:database]}' does not exist"
rescue Exception => error rescue Exception => error
$stderr.puts error $stderr.puts error
$stderr.puts "Couldn't drop database '#{configuration['database']}'" $stderr.puts "Couldn't drop database '#{configuration[:database]}'"
raise raise
end end
@ -224,7 +224,7 @@ module ActiveRecord
def truncate_all(environment = env) def truncate_all(environment = env)
ActiveRecord::Base.configurations.configs_for(env_name: environment).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: environment).each do |db_config|
truncate_tables db_config.config truncate_tables db_config.configuration_hash
end end
end end
@ -269,25 +269,26 @@ module ActiveRecord
end end
def charset_current(environment = env, specification_name = spec) def charset_current(environment = env, specification_name = spec)
charset ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config charset ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).configuration_hash
end end
def charset(*arguments) def charset(*arguments)
configuration = arguments.first configuration = arguments.first.symbolize_keys
class_for_adapter(configuration["adapter"]).new(*arguments).charset class_for_adapter(configuration[:adapter]).new(*arguments).charset
end end
def collation_current(environment = env, specification_name = spec) def collation_current(environment = env, specification_name = spec)
collation ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).config collation ActiveRecord::Base.configurations.configs_for(env_name: environment, spec_name: specification_name).configuration_hash
end end
def collation(*arguments) def collation(*arguments)
configuration = arguments.first configuration = arguments.first.symbolize_keys
class_for_adapter(configuration["adapter"]).new(*arguments).collation class_for_adapter(configuration[:adapter]).new(*arguments).collation
end end
def purge(configuration) def purge(configuration)
class_for_adapter(configuration["adapter"]).new(configuration).purge configuration = configuration.symbolize_keys
class_for_adapter(configuration[:adapter]).new(configuration).purge
end end
def purge_all def purge_all
@ -304,15 +305,15 @@ module ActiveRecord
end end
def structure_dump(*arguments) def structure_dump(*arguments)
configuration = arguments.first configuration = arguments.first.symbolize_keys
filename = arguments.delete_at 1 filename = arguments.delete_at 1
class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags) class_for_adapter(configuration[:adapter]).new(*arguments).structure_dump(filename, structure_dump_flags)
end end
def structure_load(*arguments) def structure_load(*arguments)
configuration = arguments.first configuration = arguments.first.symbolize_keys
filename = arguments.delete_at 1 filename = arguments.delete_at 1
class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags) class_for_adapter(configuration[:adapter]).new(*arguments).structure_load(filename, structure_load_flags)
end end
def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env, spec_name = "primary") # :nodoc: def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env, spec_name = "primary") # :nodoc:
@ -475,26 +476,26 @@ module ActiveRecord
ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config|
next if spec_name && spec_name != db_config.spec_name next if spec_name && spec_name != db_config.spec_name
yield db_config.config, db_config.spec_name, env yield db_config.configuration_hash, db_config.spec_name, env
end end
end end
end end
def each_local_configuration def each_local_configuration
ActiveRecord::Base.configurations.configs_for.each do |db_config| ActiveRecord::Base.configurations.configs_for.each do |db_config|
configuration = db_config.config configuration = db_config.configuration_hash
next unless configuration["database"] next unless configuration[:database]
if local_database?(configuration) if local_database?(configuration)
yield configuration yield configuration
else else
$stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host." $stderr.puts "This task only modifies local databases. #{configuration[:database]} is on a remote host."
end end
end end
end end
def local_database?(configuration) def local_database?(configuration)
configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"]) configuration[:host].blank? || LOCAL_HOSTS.include?(configuration[:host])
end end
def schema_sha1(file) def schema_sha1(file)

View file

@ -8,23 +8,23 @@ module ActiveRecord
delegate :connection, :establish_connection, to: ActiveRecord::Base delegate :connection, :establish_connection, to: ActiveRecord::Base
def initialize(configuration) def initialize(configuration)
@configuration = configuration @configuration = configuration.symbolize_keys
end end
def create def create
establish_connection configuration_without_database establish_connection configuration_without_database
connection.create_database configuration["database"], creation_options connection.create_database configuration[:database], creation_options
establish_connection configuration establish_connection configuration
end end
def drop def drop
establish_connection configuration establish_connection configuration
connection.drop_database configuration["database"] connection.drop_database configuration[:database]
end end
def purge def purge
establish_connection configuration establish_connection configuration
connection.recreate_database configuration["database"], creation_options connection.recreate_database configuration[:database], creation_options
end end
def charset def charset
@ -44,10 +44,10 @@ module ActiveRecord
ignore_tables = ActiveRecord::SchemaDumper.ignore_tables ignore_tables = ActiveRecord::SchemaDumper.ignore_tables
if ignore_tables.any? if ignore_tables.any?
args += ignore_tables.map { |table| "--ignore-table=#{configuration['database']}.#{table}" } args += ignore_tables.map { |table| "--ignore-table=#{configuration[:database]}.#{table}" }
end end
args.concat(["#{configuration['database']}"]) args.concat(["#{configuration[:database]}"])
args.unshift(*extra_flags) if extra_flags args.unshift(*extra_flags) if extra_flags
run_cmd("mysqldump", args, "dumping") run_cmd("mysqldump", args, "dumping")
@ -56,7 +56,7 @@ module ActiveRecord
def structure_load(filename, extra_flags) def structure_load(filename, extra_flags)
args = prepare_command_options args = prepare_command_options
args.concat(["--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}]) args.concat(["--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}])
args.concat(["--database", "#{configuration['database']}"]) args.concat(["--database", "#{configuration[:database]}"])
args.unshift(*extra_flags) if extra_flags args.unshift(*extra_flags) if extra_flags
run_cmd("mysql", args, "loading") run_cmd("mysql", args, "loading")
@ -66,29 +66,29 @@ module ActiveRecord
attr_reader :configuration attr_reader :configuration
def configuration_without_database def configuration_without_database
configuration.merge("database" => nil) configuration.merge(database: nil)
end end
def creation_options def creation_options
Hash.new.tap do |options| Hash.new.tap do |options|
options[:charset] = configuration["encoding"] if configuration.include? "encoding" options[:charset] = configuration[:encoding] if configuration.include? :encoding
options[:collation] = configuration["collation"] if configuration.include? "collation" options[:collation] = configuration[:collation] if configuration.include? :collation
end end
end end
def prepare_command_options def prepare_command_options
args = { args = {
"host" => "--host", host: "--host",
"port" => "--port", port: "--port",
"socket" => "--socket", socket: "--socket",
"username" => "--user", username: "--user",
"password" => "--password", password: "--password",
"encoding" => "--default-character-set", encoding: "--default-character-set",
"sslca" => "--ssl-ca", sslca: "--ssl-ca",
"sslcert" => "--ssl-cert", sslcert: "--ssl-cert",
"sslcapath" => "--ssl-capath", sslcapath: "--ssl-capath",
"sslcipher" => "--ssl-cipher", sslcipher: "--ssl-cipher",
"sslkey" => "--ssl-key" sslkey: "--ssl-key"
}.map { |opt, arg| "#{arg}=#{configuration[opt]}" if configuration[opt] }.compact }.map { |opt, arg| "#{arg}=#{configuration[opt]}" if configuration[opt] }.compact
args args

View file

@ -13,19 +13,19 @@ module ActiveRecord
to: ActiveRecord::Base to: ActiveRecord::Base
def initialize(configuration) def initialize(configuration)
@configuration = configuration @configuration = configuration.symbolize_keys
end end
def create(master_established = false) def create(master_established = false)
establish_master_connection unless master_established establish_master_connection unless master_established
connection.create_database configuration["database"], connection.create_database configuration[:database],
configuration.merge("encoding" => encoding) configuration.merge(encoding: encoding)
establish_connection configuration establish_connection configuration
end end
def drop def drop
establish_master_connection establish_master_connection
connection.drop_database configuration["database"] connection.drop_database configuration[:database]
end end
def charset def charset
@ -48,7 +48,7 @@ module ActiveRecord
search_path = \ search_path = \
case ActiveRecord::Base.dump_schemas case ActiveRecord::Base.dump_schemas
when :schema_search_path when :schema_search_path
configuration["schema_search_path"] configuration[:schema_search_path]
when :all when :all
nil nil
when String when String
@ -68,7 +68,7 @@ module ActiveRecord
args += ignore_tables.flat_map { |table| ["-T", table] } args += ignore_tables.flat_map { |table| ["-T", table] }
end end
args << configuration["database"] args << configuration[:database]
run_cmd("pg_dump", args, "dumping") run_cmd("pg_dump", args, "dumping")
remove_sql_header_comments(filename) remove_sql_header_comments(filename)
File.open(filename, "a") { |f| f << "SET search_path TO #{connection.schema_search_path};\n\n" } File.open(filename, "a") { |f| f << "SET search_path TO #{connection.schema_search_path};\n\n" }
@ -78,7 +78,7 @@ module ActiveRecord
set_psql_env set_psql_env
args = ["-v", ON_ERROR_STOP_1, "-q", "-X", "-f", filename] args = ["-v", ON_ERROR_STOP_1, "-q", "-X", "-f", filename]
args.concat(Array(extra_flags)) if extra_flags args.concat(Array(extra_flags)) if extra_flags
args << configuration["database"] args << configuration[:database]
run_cmd("psql", args, "loading") run_cmd("psql", args, "loading")
end end
@ -86,21 +86,21 @@ module ActiveRecord
attr_reader :configuration attr_reader :configuration
def encoding def encoding
configuration["encoding"] || DEFAULT_ENCODING configuration[:encoding] || DEFAULT_ENCODING
end end
def establish_master_connection def establish_master_connection
establish_connection configuration.merge( establish_connection configuration.merge(
"database" => "postgres", database: "postgres",
"schema_search_path" => "public" schema_search_path: "public"
) )
end end
def set_psql_env def set_psql_env
ENV["PGHOST"] = configuration["host"] if configuration["host"] ENV["PGHOST"] = configuration[:host] if configuration[:host]
ENV["PGPORT"] = configuration["port"].to_s if configuration["port"] ENV["PGPORT"] = configuration[:port].to_s if configuration[:port]
ENV["PGPASSWORD"] = configuration["password"].to_s if configuration["password"] ENV["PGPASSWORD"] = configuration[:password].to_s if configuration[:password]
ENV["PGUSER"] = configuration["username"].to_s if configuration["username"] ENV["PGUSER"] = configuration[:username].to_s if configuration[:username]
end end
def run_cmd(cmd, args, action) def run_cmd(cmd, args, action)

View file

@ -6,11 +6,11 @@ module ActiveRecord
delegate :connection, :establish_connection, to: ActiveRecord::Base delegate :connection, :establish_connection, to: ActiveRecord::Base
def initialize(configuration, root = ActiveRecord::Tasks::DatabaseTasks.root) def initialize(configuration, root = ActiveRecord::Tasks::DatabaseTasks.root)
@configuration, @root = configuration, root @configuration, @root = configuration.symbolize_keys, root
end end
def create def create
raise DatabaseAlreadyExists if File.exist?(configuration["database"]) raise DatabaseAlreadyExists if File.exist?(configuration[:database])
establish_connection configuration establish_connection configuration
connection connection
@ -18,7 +18,7 @@ module ActiveRecord
def drop def drop
require "pathname" require "pathname"
path = Pathname.new configuration["database"] path = Pathname.new configuration[:database]
file = path.absolute? ? path.to_s : File.join(root, path) file = path.absolute? ? path.to_s : File.join(root, path)
FileUtils.rm(file) FileUtils.rm(file)
@ -40,7 +40,7 @@ module ActiveRecord
def structure_dump(filename, extra_flags) def structure_dump(filename, extra_flags)
args = [] args = []
args.concat(Array(extra_flags)) if extra_flags args.concat(Array(extra_flags)) if extra_flags
args << configuration["database"] args << configuration[:database]
ignore_tables = ActiveRecord::SchemaDumper.ignore_tables ignore_tables = ActiveRecord::SchemaDumper.ignore_tables
if ignore_tables.any? if ignore_tables.any?
@ -53,7 +53,7 @@ module ActiveRecord
end end
def structure_load(filename, extra_flags) def structure_load(filename, extra_flags)
dbfile = configuration["database"] dbfile = configuration[:database]
flags = extra_flags.join(" ") if extra_flags flags = extra_flags.join(" ") if extra_flags
`sqlite3 #{flags} #{dbfile} < "#{filename}"` `sqlite3 #{flags} #{dbfile} < "#{filename}"`
end end

View file

@ -12,8 +12,8 @@ module ActiveRecord
old, ENV["VERBOSE"] = ENV["VERBOSE"], "false" old, ENV["VERBOSE"] = ENV["VERBOSE"], "false"
ActiveRecord::Base.configurations.configs_for(env_name: env_name).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: env_name).each do |db_config|
db_config.config["database"] += "-#{i}" db_config.configuration_hash[:database] += "-#{i}"
ActiveRecord::Tasks::DatabaseTasks.reconstruct_from_schema(db_config.config, ActiveRecord::Base.schema_format, nil, env_name, db_config.spec_name) ActiveRecord::Tasks::DatabaseTasks.reconstruct_from_schema(db_config.configuration_hash, ActiveRecord::Base.schema_format, nil, env_name, db_config.spec_name)
end end
ensure ensure
ActiveRecord::Base.establish_connection(Rails.env.to_sym) ActiveRecord::Base.establish_connection(Rails.env.to_sym)

View file

@ -11,7 +11,7 @@ module ActiveRecord
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.connection
db = Post.connection_pool.spec.config[:database] db = Post.connection_pool.spec.underlying_configuration_hash[:database]
table = Post.table_name table = Post.table_name
@db_name = db @db_name = db

View file

@ -537,8 +537,7 @@ module ActiveRecord
end end
def test_statement_closed def test_statement_closed
db = ::SQLite3::Database.new(ActiveRecord::Base. db = ::SQLite3::Database.new(ActiveRecord::Base.configurations["arunit"][:database])
configurations["arunit"]["database"])
statement = ::SQLite3::Statement.new(db, statement = ::SQLite3::Statement.new(db,
"CREATE TABLE statement_test (number integer not null)") "CREATE TABLE statement_test (number integer not null)")
statement.stub(:step, -> { raise ::SQLite3::BusyException.new("busy") }) do statement.stub(:step, -> { raise ::SQLite3::BusyException.new("busy") }) do

View file

@ -62,13 +62,13 @@ module ActiveRecord
@handler.establish_connection(:readonly) @handler.establish_connection(:readonly)
assert_not_nil pool = @handler.retrieve_connection_pool("readonly") assert_not_nil pool = @handler.retrieve_connection_pool("readonly")
assert_equal "db/readonly.sqlite3", pool.spec.config[:database] assert_equal "db/readonly.sqlite3", pool.spec.underlying_configuration_hash[:database]
assert_not_nil pool = @handler.retrieve_connection_pool("primary") assert_not_nil pool = @handler.retrieve_connection_pool("primary")
assert_equal "db/primary.sqlite3", pool.spec.config[:database] assert_equal "db/primary.sqlite3", pool.spec.underlying_configuration_hash[:database]
assert_not_nil pool = @handler.retrieve_connection_pool("common") assert_not_nil pool = @handler.retrieve_connection_pool("common")
assert_equal "db/common.sqlite3", pool.spec.config[:database] assert_equal "db/common.sqlite3", pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ENV["RAILS_ENV"] = previous_env ENV["RAILS_ENV"] = previous_env
@ -92,7 +92,7 @@ module ActiveRecord
ActiveRecord::Base.establish_connection ActiveRecord::Base.establish_connection
assert_match "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.config[:database] assert_match "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ENV["RAILS_ENV"] = previous_env ENV["RAILS_ENV"] = previous_env
@ -115,7 +115,7 @@ module ActiveRecord
ActiveRecord::Base.establish_connection ActiveRecord::Base.establish_connection
assert_match "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.config[:database] assert_match "db/primary.sqlite3", ActiveRecord::Base.connection.pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ENV["RAILS_ENV"] = previous_env ENV["RAILS_ENV"] = previous_env
@ -131,7 +131,7 @@ module ActiveRecord
@handler.establish_connection(:development) @handler.establish_connection(:development)
assert_not_nil pool = @handler.retrieve_connection_pool("development") assert_not_nil pool = @handler.retrieve_connection_pool("development")
assert_equal "db/primary.sqlite3", pool.spec.config[:database] assert_equal "db/primary.sqlite3", pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
end end
@ -146,7 +146,7 @@ module ActiveRecord
@handler.establish_connection(:development_readonly) @handler.establish_connection(:development_readonly)
assert_not_nil pool = @handler.retrieve_connection_pool("development_readonly") assert_not_nil pool = @handler.retrieve_connection_pool("development_readonly")
assert_equal "db/readonly.sqlite3", pool.spec.config[:database] assert_equal "db/readonly.sqlite3", pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
end end
@ -172,8 +172,9 @@ module ActiveRecord
assert_instance_of ActiveRecord::DatabaseConfigurations::HashConfig, db_config assert_instance_of ActiveRecord::DatabaseConfigurations::HashConfig, db_config
assert_instance_of String, db_config.env_name assert_instance_of String, db_config.env_name
assert_instance_of String, db_config.spec_name assert_instance_of String, db_config.spec_name
db_config.config.keys.each do |key|
assert_instance_of String, key db_config.configuration_hash.keys.each do |key|
assert_instance_of Symbol, key
end end
end end
ensure ensure
@ -209,7 +210,7 @@ module ActiveRecord
assert_same klass2.connection, ActiveRecord::Base.connection assert_same klass2.connection, ActiveRecord::Base.connection
pool = klass2.establish_connection(ActiveRecord::Base.connection_pool.spec.config) pool = klass2.establish_connection(ActiveRecord::Base.connection_pool.spec.underlying_configuration_hash)
assert_same klass2.connection, pool.connection assert_same klass2.connection, pool.connection
assert_not_same klass2.connection, ActiveRecord::Base.connection assert_not_same klass2.connection, ActiveRecord::Base.connection

View file

@ -82,10 +82,10 @@ module ActiveRecord
ActiveRecord::Base.connects_to(database: { writing: :primary, reading: :readonly }) ActiveRecord::Base.connects_to(database: { writing: :primary, reading: :readonly })
assert_not_nil pool = ActiveRecord::Base.connection_handlers[:writing].retrieve_connection_pool("primary") assert_not_nil pool = ActiveRecord::Base.connection_handlers[:writing].retrieve_connection_pool("primary")
assert_equal "db/primary.sqlite3", pool.spec.config[:database] assert_equal "db/primary.sqlite3", pool.spec.underlying_configuration_hash[:database]
assert_not_nil pool = ActiveRecord::Base.connection_handlers[:reading].retrieve_connection_pool("primary") assert_not_nil pool = ActiveRecord::Base.connection_handlers[:reading].retrieve_connection_pool("primary")
assert_equal "db/readonly.sqlite3", pool.spec.config[:database] assert_equal "db/readonly.sqlite3", pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ActiveRecord::Base.establish_connection(:arunit) ActiveRecord::Base.establish_connection(:arunit)
@ -140,10 +140,10 @@ module ActiveRecord
ActiveRecord::Base.connects_to(database: { default: :primary, readonly: :readonly }) ActiveRecord::Base.connects_to(database: { default: :primary, readonly: :readonly })
assert_not_nil pool = ActiveRecord::Base.connection_handlers[:default].retrieve_connection_pool("primary") assert_not_nil pool = ActiveRecord::Base.connection_handlers[:default].retrieve_connection_pool("primary")
assert_equal "db/primary.sqlite3", pool.spec.config[:database] assert_equal "db/primary.sqlite3", pool.spec.underlying_configuration_hash[:database]
assert_not_nil pool = ActiveRecord::Base.connection_handlers[:readonly].retrieve_connection_pool("primary") assert_not_nil pool = ActiveRecord::Base.connection_handlers[:readonly].retrieve_connection_pool("primary")
assert_equal "db/readonly.sqlite3", pool.spec.config[:database] assert_equal "db/readonly.sqlite3", pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ActiveRecord::Base.establish_connection(:arunit) ActiveRecord::Base.establish_connection(:arunit)
@ -162,7 +162,7 @@ module ActiveRecord
assert_equal handler, ActiveRecord::Base.connection_handlers[:writing] assert_equal handler, ActiveRecord::Base.connection_handlers[:writing]
assert_not_nil pool = handler.retrieve_connection_pool("primary") assert_not_nil pool = handler.retrieve_connection_pool("primary")
assert_equal({ adapter: "postgresql", database: "bar", host: "localhost" }, pool.spec.config) assert_equal({ adapter: "postgresql", database: "bar", host: "localhost" }, pool.spec.underlying_configuration_hash)
end end
ensure ensure
ActiveRecord::Base.establish_connection(:arunit) ActiveRecord::Base.establish_connection(:arunit)
@ -182,7 +182,7 @@ module ActiveRecord
assert_equal handler, ActiveRecord::Base.connection_handlers[:writing] assert_equal handler, ActiveRecord::Base.connection_handlers[:writing]
assert_not_nil pool = handler.retrieve_connection_pool("primary") assert_not_nil pool = handler.retrieve_connection_pool("primary")
assert_equal(config, pool.spec.config) assert_equal(config, pool.spec.underlying_configuration_hash)
end end
ensure ensure
ActiveRecord::Base.establish_connection(:arunit) ActiveRecord::Base.establish_connection(:arunit)
@ -222,7 +222,7 @@ module ActiveRecord
assert_equal handler, ActiveRecord::Base.connection_handlers[:writing] assert_equal handler, ActiveRecord::Base.connection_handlers[:writing]
assert_not_nil pool = handler.retrieve_connection_pool("primary") assert_not_nil pool = handler.retrieve_connection_pool("primary")
assert_equal(config["default_env"]["animals"], pool.spec.config) assert_equal(config["default_env"]["animals"], pool.spec.underlying_configuration_hash)
end end
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
@ -249,7 +249,7 @@ module ActiveRecord
assert_equal handler, ActiveRecord::Base.connection_handlers[:writing] assert_equal handler, ActiveRecord::Base.connection_handlers[:writing]
assert_not_nil pool = handler.retrieve_connection_pool("primary") assert_not_nil pool = handler.retrieve_connection_pool("primary")
assert_equal(config["default_env"]["primary"], pool.spec.config) assert_equal(config["default_env"]["primary"], pool.spec.underlying_configuration_hash)
end end
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
@ -284,7 +284,7 @@ module ActiveRecord
ActiveRecord::Base.connects_to database: { writing: :development, reading: :development_readonly } ActiveRecord::Base.connects_to database: { writing: :development, reading: :development_readonly }
assert_not_nil pool = ActiveRecord::Base.connection_handlers[:reading].retrieve_connection_pool("primary") assert_not_nil pool = ActiveRecord::Base.connection_handlers[:reading].retrieve_connection_pool("primary")
assert_equal "db/readonly.sqlite3", pool.spec.config[:database] assert_equal "db/readonly.sqlite3", pool.spec.underlying_configuration_hash[:database]
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ActiveRecord::Base.establish_connection(:arunit) ActiveRecord::Base.establish_connection(:arunit)

View file

@ -7,7 +7,7 @@ module ActiveRecord
class ConnectionSpecificationTest < ActiveRecord::TestCase class ConnectionSpecificationTest < ActiveRecord::TestCase
def test_dup_deep_copy_config def test_dup_deep_copy_config
spec = ConnectionSpecification.new("primary", { a: :b }, "bar") spec = ConnectionSpecification.new("primary", { a: :b }, "bar")
assert_not_equal(spec.config.object_id, spec.dup.config.object_id) assert_not_equal(spec.underlying_configuration_hash.object_id, spec.dup.underlying_configuration_hash.object_id)
end end
end end
end end

View file

@ -48,7 +48,7 @@ module ActiveRecord
ENV["DATABASE_URL"] = "postgres://localhost/foo" ENV["DATABASE_URL"] = "postgres://localhost/foo"
config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } } config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } }
actual = resolve_spec(:default_env, config) actual = resolve_spec(:default_env, config)
expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost", "name" => "default_env" } expected = { adapter: "postgresql", database: "foo", host: "localhost", name: "default_env" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -58,7 +58,7 @@ module ActiveRecord
config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } } config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } }
actual = resolve_spec(:foo, config) actual = resolve_spec(:foo, config)
expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost", "name" => "foo" } expected = { adapter: "postgresql", database: "foo", host: "localhost", name: "foo" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -66,7 +66,7 @@ module ActiveRecord
ENV["RAILS_ENV"] = "foo" ENV["RAILS_ENV"] = "foo"
config = { "foo" => { "adapter" => "postgres", "url" => ENV["DATABASE_URL"] } } config = { "foo" => { "adapter" => "postgres", "url" => ENV["DATABASE_URL"] } }
actual = resolve_spec(:foo, config) actual = resolve_spec(:foo, config)
expected = { "adapter" => "postgres", "url" => nil, "name" => "foo" } expected = { adapter: "postgres", url: nil, name: "foo" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -76,7 +76,7 @@ module ActiveRecord
config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } } config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } }
actual = resolve_spec(:foo, config) actual = resolve_spec(:foo, config)
expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost", "name" => "foo" } expected = { adapter: "postgresql", database: "foo", host: "localhost", name: "foo" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -84,7 +84,7 @@ module ActiveRecord
ENV["DATABASE_URL"] = "postgres://localhost/foo" ENV["DATABASE_URL"] = "postgres://localhost/foo"
config = { "production" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" } } config = { "production" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" } }
actual = resolve_spec(:production, config) actual = resolve_spec(:production, config)
expected = { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost", "name" => "production" } expected = { adapter: "not_postgres", database: "not_foo", host: "localhost", name: "production" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -94,7 +94,7 @@ module ActiveRecord
config = { "production" => { "adapter" => "postgresql", "database" => "foo_prod" }, "test" => { "adapter" => "postgresql", "database" => "foo_test" } } config = { "production" => { "adapter" => "postgresql", "database" => "foo_prod" }, "test" => { "adapter" => "postgresql", "database" => "foo_test" } }
actual = resolve_spec(:test, config) actual = resolve_spec(:test, config)
expected = { "adapter" => "postgresql", "database" => "foo_test", "host" => "localhost", "name" => "test" } expected = { adapter: "postgresql", database: "foo_test", host: "localhost", name: "test" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -110,7 +110,7 @@ module ActiveRecord
ENV["DATABASE_URL"] = "not-postgres://not-localhost/not_foo" ENV["DATABASE_URL"] = "not-postgres://not-localhost/not_foo"
config = { "production" => { "adapter" => "also_not_postgres", "database" => "also_not_foo" } } config = { "production" => { "adapter" => "also_not_postgres", "database" => "also_not_foo" } }
actual = resolve_spec("postgres://localhost/foo", config) actual = resolve_spec("postgres://localhost/foo", config)
expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } expected = { adapter: "postgresql", database: "foo", host: "localhost" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -132,7 +132,7 @@ module ActiveRecord
ENV["DATABASE_URL"] = "ibm-db://localhost/foo" ENV["DATABASE_URL"] = "ibm-db://localhost/foo"
config = { "default_env" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" } } config = { "default_env" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" } }
actual = resolve_spec(:default_env, config) actual = resolve_spec(:default_env, config)
expected = { "adapter" => "ibm_db", "database" => "foo", "host" => "localhost", "name" => "default_env" } expected = { adapter: "ibm_db", database: "foo", host: "localhost", name: "default_env" }
assert_equal expected, actual assert_equal expected, actual
end end
@ -351,19 +351,19 @@ module ActiveRecord
} }
configs = ActiveRecord::DatabaseConfigurations.new(config) configs = ActiveRecord::DatabaseConfigurations.new(config)
actual = configs.configs_for(env_name: "default_env", spec_name: "primary").config actual = configs.configs_for(env_name: "default_env", spec_name: "primary").configuration_hash
expected = { expected = {
"adapter" => "postgresql", adapter: "postgresql",
"database" => "foo", database: "foo",
"host" => "localhost", host: "localhost",
"pool" => 5 pool: 5
} }
assert_equal expected, actual assert_equal expected, actual
configs = ActiveRecord::DatabaseConfigurations.new(config) configs = ActiveRecord::DatabaseConfigurations.new(config)
actual = configs.configs_for(env_name: "default_env", spec_name: "animals").config actual = configs.configs_for(env_name: "default_env", spec_name: "animals").configuration_hash
expected = { "pool" => 5 } expected = { pool: 5 }
assert_equal expected, actual assert_equal expected, actual
end end
@ -381,12 +381,12 @@ module ActiveRecord
} }
configs = ActiveRecord::DatabaseConfigurations.new(config) configs = ActiveRecord::DatabaseConfigurations.new(config)
actual = configs.configs_for(env_name: "default_env", spec_name: "primary").config actual = configs.configs_for(env_name: "default_env", spec_name: "primary").configuration_hash
assert_equal "primary", actual["database"] assert_equal "primary", actual[:database]
configs = ActiveRecord::DatabaseConfigurations.new(config) configs = ActiveRecord::DatabaseConfigurations.new(config)
actual = configs.configs_for(env_name: "default_env", spec_name: "animals").config actual = configs.configs_for(env_name: "default_env", spec_name: "animals").configuration_hash
assert_equal "animals", actual["database"] assert_equal "animals", actual[:database]
ensure ensure
ENV.delete("PRIMARY_DATABASE_URL") ENV.delete("PRIMARY_DATABASE_URL")
ENV.delete("ANIMALS_DATABASE_URL") ENV.delete("ANIMALS_DATABASE_URL")
@ -397,14 +397,14 @@ module ActiveRecord
config = { "production" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" }, "default_env" => {} } config = { "production" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" }, "default_env" => {} }
actual = resolve_spec(:production, config) actual = resolve_spec(:production, config)
assert_equal config["production"].merge("name" => "production"), actual assert_equal config["production"].symbolize_keys.merge(name: "production"), actual
actual = resolve_spec(:default_env, config) actual = resolve_spec(:default_env, config)
assert_equal({ assert_equal({
"host" => "localhost", host: "localhost",
"database" => "foo", database: "foo",
"adapter" => "postgresql", adapter: "postgresql",
"name" => "default_env" name: "default_env"
}, actual) }, actual)
end end
end end

View file

@ -199,7 +199,7 @@ module ActiveRecord
def test_idle_timeout_configuration def test_idle_timeout_configuration
@pool.disconnect! @pool.disconnect!
spec = ActiveRecord::Base.connection_pool.spec spec = ActiveRecord::Base.connection_pool.spec
spec.config.merge!(idle_timeout: "0.02") spec.underlying_configuration_hash.merge!(idle_timeout: "0.02")
@pool = ConnectionPool.new(spec) @pool = ConnectionPool.new(spec)
idle_conn = @pool.checkout idle_conn = @pool.checkout
@pool.checkin(idle_conn) @pool.checkin(idle_conn)
@ -224,7 +224,7 @@ module ActiveRecord
def test_disable_flush def test_disable_flush
@pool.disconnect! @pool.disconnect!
spec = ActiveRecord::Base.connection_pool.spec spec = ActiveRecord::Base.connection_pool.spec
spec.config.merge!(idle_timeout: -5) spec.underlying_configuration_hash.merge!(idle_timeout: -5)
@pool = ConnectionPool.new(spec) @pool = ConnectionPool.new(spec)
idle_conn = @pool.checkout idle_conn = @pool.checkout
@pool.checkin(idle_conn) @pool.checkin(idle_conn)
@ -719,7 +719,7 @@ module ActiveRecord
private private
def with_single_connection_pool def with_single_connection_pool
one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup
one_conn_spec.config[:pool] = 1 # this is safe to do, because .dupped ConnectionSpecification also auto-dups its config one_conn_spec.underlying_configuration_hash[:pool] = 1 # this is safe to do, because .dupped ConnectionSpecification also auto-dups its config
yield(pool = ConnectionPool.new(one_conn_spec)) yield(pool = ConnectionPool.new(one_conn_spec))
ensure ensure
pool.disconnect! if pool pool.disconnect! if pool

View file

@ -40,98 +40,104 @@ module ActiveRecord
def test_url_from_environment def test_url_from_environment
spec = resolve :production, "production" => "abstract://foo?encoding=utf8" spec = resolve :production, "production" => "abstract://foo?encoding=utf8"
assert_equal({ assert_equal({
"adapter" => "abstract", adapter: "abstract",
"host" => "foo", host: "foo",
"encoding" => "utf8", encoding: "utf8",
"name" => "production" }, spec) name: "production"
}, spec)
end end
def test_url_sub_key def test_url_sub_key
spec = resolve :production, "production" => { "url" => "abstract://foo?encoding=utf8" } spec = resolve :production, "production" => { "url" => "abstract://foo?encoding=utf8" }
assert_equal({ assert_equal({
"adapter" => "abstract", adapter: "abstract",
"host" => "foo", host: "foo",
"encoding" => "utf8", encoding: "utf8",
"name" => "production" }, spec) name: "production"
}, spec)
end end
def test_url_sub_key_merges_correctly def test_url_sub_key_merges_correctly
hash = { "url" => "abstract://foo?encoding=utf8&", "adapter" => "sqlite3", "host" => "bar", "pool" => "3" } hash = { "url" => "abstract://foo?encoding=utf8&", "adapter" => "sqlite3", "host" => "bar", "pool" => "3" }
spec = resolve :production, "production" => hash spec = resolve :production, "production" => hash
assert_equal({ assert_equal({
"adapter" => "abstract", adapter: "abstract",
"host" => "foo", host: "foo",
"encoding" => "utf8", encoding: "utf8",
"pool" => "3", pool: "3",
"name" => "production" }, spec) name: "production"
}, spec)
end end
def test_url_host_no_db def test_url_host_no_db
spec = resolve "abstract://foo?encoding=utf8" spec = resolve "abstract://foo?encoding=utf8"
assert_equal({ assert_equal({
"adapter" => "abstract", adapter: "abstract",
"host" => "foo", host: "foo",
"encoding" => "utf8" }, spec) encoding: "utf8"
}, spec)
end end
def test_url_missing_scheme def test_url_missing_scheme
spec = resolve "foo" spec = resolve "foo"
assert_equal({ assert_equal({ database: "foo" }, spec)
"database" => "foo" }, spec)
end end
def test_url_host_db def test_url_host_db
spec = resolve "abstract://foo/bar?encoding=utf8" spec = resolve "abstract://foo/bar?encoding=utf8"
assert_equal({ assert_equal({
"adapter" => "abstract", adapter: "abstract",
"database" => "bar", database: "bar",
"host" => "foo", host: "foo",
"encoding" => "utf8" }, spec) encoding: "utf8"
}, spec)
end end
def test_url_port def test_url_port
spec = resolve "abstract://foo:123?encoding=utf8" spec = resolve "abstract://foo:123?encoding=utf8"
assert_equal({ assert_equal({
"adapter" => "abstract", adapter: "abstract",
"port" => 123, port: 123,
"host" => "foo", host: "foo",
"encoding" => "utf8" }, spec) encoding: "utf8"
}, spec)
end end
def test_encoded_password def test_encoded_password
password = "am@z1ng_p@ssw0rd#!" password = "am@z1ng_p@ssw0rd#!"
encoded_password = URI.encode_www_form_component(password) encoded_password = URI.encode_www_form_component(password)
spec = resolve "abstract://foo:#{encoded_password}@localhost/bar" spec = resolve "abstract://foo:#{encoded_password}@localhost/bar"
assert_equal password, spec["password"] assert_equal password, spec[:password]
end end
def test_url_with_authority_for_sqlite3 def test_url_with_authority_for_sqlite3
spec = resolve "sqlite3:///foo_test" spec = resolve "sqlite3:///foo_test"
assert_equal("/foo_test", spec["database"]) assert_equal("/foo_test", spec[:database])
end end
def test_url_absolute_path_for_sqlite3 def test_url_absolute_path_for_sqlite3
spec = resolve "sqlite3:/foo_test" spec = resolve "sqlite3:/foo_test"
assert_equal("/foo_test", spec["database"]) assert_equal("/foo_test", spec[:database])
end end
def test_url_relative_path_for_sqlite3 def test_url_relative_path_for_sqlite3
spec = resolve "sqlite3:foo_test" spec = resolve "sqlite3:foo_test"
assert_equal("foo_test", spec["database"]) assert_equal("foo_test", spec[:database])
end end
def test_url_memory_db_for_sqlite3 def test_url_memory_db_for_sqlite3
spec = resolve "sqlite3::memory:" spec = resolve "sqlite3::memory:"
assert_equal(":memory:", spec["database"]) assert_equal(":memory:", spec[:database])
end end
def test_url_sub_key_for_sqlite3 def test_url_sub_key_for_sqlite3
spec = resolve :production, "production" => { "url" => "sqlite3:foo?encoding=utf8" } spec = resolve :production, "production" => { "url" => "sqlite3:foo?encoding=utf8" }
assert_equal({ assert_equal({
"adapter" => "sqlite3", adapter: "sqlite3",
"database" => "foo", database: "foo",
"encoding" => "utf8", encoding: "utf8",
"name" => "production" }, spec) name: "production"
}, spec)
end end
def test_spec_name_on_key_lookup def test_spec_name_on_key_lookup

View file

@ -36,7 +36,7 @@ class DatabaseConfigurationsTest < ActiveRecord::TestCase
original_rails_env = ENV["RAILS_ENV"] original_rails_env = ENV["RAILS_ENV"]
ENV["RAILS_ENV"] = "arunit" ENV["RAILS_ENV"] = "arunit"
assert_equal ActiveRecord::Base.configurations.configs_for(env_name: "arunit", spec_name: "primary").config, ActiveRecord::Base.configurations.default_hash assert_equal ActiveRecord::Base.configurations.configs_for(env_name: "arunit", spec_name: "primary").configuration_hash, ActiveRecord::Base.configurations.default_hash
ensure ensure
ENV["RAILS_ENV"] = original_rails_env ENV["RAILS_ENV"] = original_rails_env
end end
@ -89,7 +89,7 @@ class LegacyDatabaseConfigurationsTest < ActiveRecord::TestCase
end end
def test_first_is_deprecated def test_first_is_deprecated
first_config = ActiveRecord::Base.configurations.configurations.map(&:config).first first_config = ActiveRecord::Base.configurations.configurations.map(&:configuration_hash).first
assert_deprecated do assert_deprecated do
env_name, config = ActiveRecord::Base.configurations.first env_name, config = ActiveRecord::Base.configurations.first
assert_equal "arunit", env_name assert_equal "arunit", env_name
@ -106,12 +106,18 @@ class LegacyDatabaseConfigurationsTest < ActiveRecord::TestCase
end end
def test_values_are_deprecated def test_values_are_deprecated
config_hashes = ActiveRecord::Base.configurations.configurations.map(&:config) config_hashes = ActiveRecord::Base.configurations.configurations.map(&:configuration_hash)
assert_deprecated do assert_deprecated do
assert_equal config_hashes, ActiveRecord::Base.configurations.values assert_equal config_hashes, ActiveRecord::Base.configurations.values
end end
end end
def test_deprecated_config_method
db_config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", spec_name: "primary")
assert_equal db_config.configuration_hash.stringify_keys, assert_deprecated { db_config.config }
end
def test_unsupported_method_raises def test_unsupported_method_raises
assert_raises NotImplementedError do assert_raises NotImplementedError do
ActiveRecord::Base.configurations.select { |a| a == "foo" } ActiveRecord::Base.configurations.select { |a| a == "foo" }

View file

@ -37,7 +37,7 @@ end
def in_memory_db? def in_memory_db?
current_adapter?(:SQLite3Adapter) && current_adapter?(:SQLite3Adapter) &&
ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:" ActiveRecord::Base.connection_pool.spec.underlying_configuration_hash[:database] == ":memory:"
end end
def subsecond_precision_supported? def subsecond_precision_supported?

View file

@ -68,7 +68,7 @@ module ActiveRecord
def test_reaping_frequency_configuration def test_reaping_frequency_configuration
spec = ActiveRecord::Base.connection_pool.spec.dup spec = ActiveRecord::Base.connection_pool.spec.dup
spec.config[:reaping_frequency] = "10.01" spec.underlying_configuration_hash[:reaping_frequency] = "10.01"
pool = ConnectionPool.new spec pool = ConnectionPool.new spec
assert_equal 10.01, pool.reaper.frequency assert_equal 10.01, pool.reaper.frequency
ensure ensure
@ -77,7 +77,7 @@ module ActiveRecord
def test_connection_pool_starts_reaper def test_connection_pool_starts_reaper
spec = ActiveRecord::Base.connection_pool.spec.dup spec = ActiveRecord::Base.connection_pool.spec.dup
spec.config[:reaping_frequency] = "0.0001" spec.underlying_configuration_hash[:reaping_frequency] = "0.0001"
pool = ConnectionPool.new spec pool = ConnectionPool.new spec
@ -95,7 +95,7 @@ module ActiveRecord
def test_reaper_works_after_pool_discard def test_reaper_works_after_pool_discard
spec = ActiveRecord::Base.connection_pool.spec.dup spec = ActiveRecord::Base.connection_pool.spec.dup
spec.config[:reaping_frequency] = "0.0001" spec.underlying_configuration_hash[:reaping_frequency] = "0.0001"
2.times do 2.times do
pool = ConnectionPool.new spec pool = ConnectionPool.new spec
@ -126,7 +126,7 @@ module ActiveRecord
def test_connection_pool_starts_reaper_in_fork def test_connection_pool_starts_reaper_in_fork
spec = ActiveRecord::Base.connection_pool.spec.dup spec = ActiveRecord::Base.connection_pool.spec.dup
spec.config[:reaping_frequency] = "0.0001" spec.underlying_configuration_hash[:reaping_frequency] = "0.0001"
pool = ConnectionPool.new spec pool = ConnectionPool.new spec
pool.checkout pool.checkout

View file

@ -262,7 +262,7 @@ module ActiveRecord
assert_called_with( assert_called_with(
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
["database" => "test-db"], [database: "test-db"],
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
ActiveSupport::StringInquirer.new("test") ActiveSupport::StringInquirer.new("test")
@ -276,7 +276,7 @@ module ActiveRecord
assert_called_with( assert_called_with(
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"], [adapter: "abstract", database: "prod-db", host: "prod-db-host"],
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
ActiveSupport::StringInquirer.new("production") ActiveSupport::StringInquirer.new("production")
@ -291,8 +291,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "test-db"] [database: "test-db"]
], ],
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
@ -311,8 +311,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "test-db"] [database: "test-db"]
], ],
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
@ -362,8 +362,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
[ [
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
@ -379,8 +379,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
[ [
["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"], [adapter: "abstract", database: "prod-db", host: "prod-db-host"],
["adapter" => "abstract", "database" => "secondary-prod-db", "host" => "secondary-prod-db-host"] [adapter: "abstract", database: "secondary-prod-db", host: "secondary-prod-db-host"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
@ -396,10 +396,10 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "secondary-dev-db"], [database: "secondary-dev-db"],
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
@ -418,10 +418,10 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:create, :create,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "secondary-dev-db"], [database: "secondary-dev-db"],
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create_current( ActiveRecord::Tasks::DatabaseTasks.create_current(
@ -570,7 +570,7 @@ module ActiveRecord
def test_drops_current_environment_database def test_drops_current_environment_database
with_stubbed_configurations do with_stubbed_configurations do
assert_called_with(ActiveRecord::Tasks::DatabaseTasks, :drop, assert_called_with(ActiveRecord::Tasks::DatabaseTasks, :drop,
["database" => "test-db"]) do [database: "test-db"]) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
ActiveSupport::StringInquirer.new("test") ActiveSupport::StringInquirer.new("test")
) )
@ -581,7 +581,7 @@ module ActiveRecord
def test_drops_current_environment_database_with_url def test_drops_current_environment_database_with_url
with_stubbed_configurations do with_stubbed_configurations do
assert_called_with(ActiveRecord::Tasks::DatabaseTasks, :drop, assert_called_with(ActiveRecord::Tasks::DatabaseTasks, :drop,
["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"]) do [adapter: "abstract", database: "prod-db", host: "prod-db-host"]) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
ActiveSupport::StringInquirer.new("production") ActiveSupport::StringInquirer.new("production")
) )
@ -595,8 +595,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:drop, :drop,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "test-db"] [database: "test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
@ -615,8 +615,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:drop, :drop,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "test-db"] [database: "test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
@ -654,8 +654,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:drop, :drop,
[ [
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
@ -671,8 +671,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:drop, :drop,
[ [
["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"], [adapter: "abstract", database: "prod-db", host: "prod-db-host"],
["adapter" => "abstract", "database" => "secondary-prod-db", "host" => "secondary-prod-db-host"] [adapter: "abstract", database: "secondary-prod-db", host: "secondary-prod-db-host"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
@ -688,10 +688,10 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:drop, :drop,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "secondary-dev-db"], [database: "secondary-dev-db"],
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
@ -710,10 +710,10 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:drop, :drop,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "secondary-dev-db"], [database: "secondary-dev-db"],
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop_current( ActiveRecord::Tasks::DatabaseTasks.drop_current(
@ -922,7 +922,7 @@ module ActiveRecord
assert_called_with( assert_called_with(
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:purge, :purge,
["database" => "prod-db"] [database: "prod-db"]
) do ) do
assert_called_with(ActiveRecord::Base, :establish_connection, [:production]) do assert_called_with(ActiveRecord::Base, :establish_connection, [:production]) do
ActiveRecord::Tasks::DatabaseTasks.purge_current("production") ActiveRecord::Tasks::DatabaseTasks.purge_current("production")
@ -942,7 +942,7 @@ module ActiveRecord
assert_called_with( assert_called_with(
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:purge, :purge,
["database" => "my-db"] [database: "my-db"]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.purge_all ActiveRecord::Tasks::DatabaseTasks.purge_all
end end
@ -1043,8 +1043,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:truncate_tables, :truncate_tables,
[ [
["database" => "test-db"], [database: "test-db"],
["database" => "secondary-test-db"] [database: "secondary-test-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.truncate_all( ActiveRecord::Tasks::DatabaseTasks.truncate_all(
@ -1060,8 +1060,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:truncate_tables, :truncate_tables,
[ [
["adapter" => "abstract", "database" => "prod-db", "host" => "prod-db-host"], [adapter: "abstract", database: "prod-db", host: "prod-db-host"],
["adapter" => "abstract", "database" => "secondary-prod-db", "host" => "secondary-prod-db-host"] [adapter: "abstract", database: "secondary-prod-db", host: "secondary-prod-db-host"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.truncate_all( ActiveRecord::Tasks::DatabaseTasks.truncate_all(
@ -1077,8 +1077,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:truncate_tables, :truncate_tables,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "secondary-dev-db"] [database: "secondary-dev-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.truncate_all( ActiveRecord::Tasks::DatabaseTasks.truncate_all(
@ -1097,8 +1097,8 @@ module ActiveRecord
ActiveRecord::Tasks::DatabaseTasks, ActiveRecord::Tasks::DatabaseTasks,
:truncate_tables, :truncate_tables,
[ [
["database" => "dev-db"], [database: "dev-db"],
["database" => "secondary-dev-db"] [database: "secondary-dev-db"]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.truncate_all( ActiveRecord::Tasks::DatabaseTasks.truncate_all(

View file

@ -29,8 +29,8 @@ if current_adapter?(:Mysql2Adapter)
ActiveRecord::Base, ActiveRecord::Base,
:establish_connection, :establish_connection,
[ [
[ "adapter" => "mysql2", "database" => nil ], [ adapter: "mysql2", database: nil ],
[ "adapter" => "mysql2", "database" => "my-app-db" ], [ adapter: "mysql2", database: "my-app-db" ],
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create @configuration ActiveRecord::Tasks::DatabaseTasks.create @configuration
@ -72,8 +72,8 @@ if current_adapter?(:Mysql2Adapter)
ActiveRecord::Base, ActiveRecord::Base,
:establish_connection, :establish_connection,
[ [
["adapter" => "mysql2", "database" => nil], [adapter: "mysql2", database: nil],
[@configuration] [@configuration.symbolize_keys]
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create @configuration ActiveRecord::Tasks::DatabaseTasks.create @configuration
@ -158,7 +158,7 @@ if current_adapter?(:Mysql2Adapter)
assert_called_with( assert_called_with(
ActiveRecord::Base, ActiveRecord::Base,
:establish_connection, :establish_connection,
[@configuration] [@configuration.symbolize_keys]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop @configuration ActiveRecord::Tasks::DatabaseTasks.drop @configuration
end end
@ -205,7 +205,7 @@ if current_adapter?(:Mysql2Adapter)
assert_called_with( assert_called_with(
ActiveRecord::Base, ActiveRecord::Base,
:establish_connection, :establish_connection,
[@configuration] [@configuration.symbolize_keys]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.purge @configuration ActiveRecord::Tasks::DatabaseTasks.purge @configuration
end end

View file

@ -27,13 +27,13 @@ if current_adapter?(:PostgreSQLAdapter)
:establish_connection, :establish_connection,
[ [
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "postgres", database: "postgres",
"schema_search_path" => "public" schema_search_path: "public"
], ],
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "my-app-db" database: "my-app-db"
] ]
] ]
) do ) do
@ -47,7 +47,7 @@ if current_adapter?(:PostgreSQLAdapter)
assert_called_with( assert_called_with(
@connection, @connection,
:create_database, :create_database,
["my-app-db", @configuration.merge("encoding" => "utf8")] ["my-app-db", @configuration.symbolize_keys.merge(encoding: "utf8")]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create @configuration ActiveRecord::Tasks::DatabaseTasks.create @configuration
end end
@ -59,7 +59,7 @@ if current_adapter?(:PostgreSQLAdapter)
assert_called_with( assert_called_with(
@connection, @connection,
:create_database, :create_database,
["my-app-db", @configuration.merge("encoding" => "latin")] ["my-app-db", @configuration.symbolize_keys.merge(encoding: "latin")]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.create @configuration. ActiveRecord::Tasks::DatabaseTasks.create @configuration.
merge("encoding" => "latin") merge("encoding" => "latin")
@ -74,10 +74,10 @@ if current_adapter?(:PostgreSQLAdapter)
:create_database, :create_database,
[ [
"my-app-db", "my-app-db",
@configuration.merge( @configuration.symbolize_keys.merge(
"encoding" => "utf8", encoding: "utf8",
"collation" => "ja_JP.UTF8", collation: "ja_JP.UTF8",
"ctype" => "ja_JP.UTF8" ctype: "ja_JP.UTF8"
) )
] ]
) do ) do
@ -94,12 +94,12 @@ if current_adapter?(:PostgreSQLAdapter)
:establish_connection, :establish_connection,
[ [
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "postgres", database: "postgres",
"schema_search_path" => "public" schema_search_path: "public"
], ],
[ [
@configuration @configuration.symbolize_keys
] ]
] ]
) do ) do
@ -169,9 +169,9 @@ if current_adapter?(:PostgreSQLAdapter)
ActiveRecord::Base, ActiveRecord::Base,
:establish_connection, :establish_connection,
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "postgres", database: "postgres",
"schema_search_path" => "public" schema_search_path: "public"
] ]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.drop @configuration ActiveRecord::Tasks::DatabaseTasks.drop @configuration
@ -238,13 +238,13 @@ if current_adapter?(:PostgreSQLAdapter)
:establish_connection, :establish_connection,
[ [
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "postgres", database: "postgres",
"schema_search_path" => "public" schema_search_path: "public"
], ],
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "my-app-db" database: "my-app-db"
] ]
] ]
) do ) do
@ -269,7 +269,7 @@ if current_adapter?(:PostgreSQLAdapter)
assert_called_with( assert_called_with(
@connection, @connection,
:create_database, :create_database,
["my-app-db", @configuration.merge("encoding" => "utf8")] ["my-app-db", @configuration.symbolize_keys.merge(encoding: "utf8")]
) do ) do
ActiveRecord::Tasks::DatabaseTasks.purge @configuration ActiveRecord::Tasks::DatabaseTasks.purge @configuration
end end
@ -284,12 +284,12 @@ if current_adapter?(:PostgreSQLAdapter)
:establish_connection, :establish_connection,
[ [
[ [
"adapter" => "postgresql", adapter: "postgresql",
"database" => "postgres", database: "postgres",
"schema_search_path" => "public" schema_search_path: "public"
], ],
[ [
@configuration @configuration.symbolize_keys
] ]
] ]
) do ) do

View file

@ -54,7 +54,7 @@ if current_adapter?(:SQLite3Adapter)
end end
def test_db_create_establishes_a_connection def test_db_create_establishes_a_connection
assert_called_with(ActiveRecord::Base, :establish_connection, [@configuration]) do assert_called_with(ActiveRecord::Base, :establish_connection, [@configuration.symbolize_keys]) do
ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root"
end end
end end

View file

@ -17,54 +17,54 @@ module Rails
def start def start
ENV["RAILS_ENV"] ||= @options[:environment] || environment ENV["RAILS_ENV"] ||= @options[:environment] || environment
case config["adapter"] case config[:adapter]
when /^(jdbc)?mysql/ when /^(jdbc)?mysql/
args = { args = {
"host" => "--host", host: "--host",
"port" => "--port", port: "--port",
"socket" => "--socket", socket: "--socket",
"username" => "--user", username: "--user",
"encoding" => "--default-character-set", encoding: "--default-character-set",
"sslca" => "--ssl-ca", sslca: "--ssl-ca",
"sslcert" => "--ssl-cert", sslcert: "--ssl-cert",
"sslcapath" => "--ssl-capath", sslcapath: "--ssl-capath",
"sslcipher" => "--ssl-cipher", sslcipher: "--ssl-cipher",
"sslkey" => "--ssl-key" sslkey: "--ssl-key"
}.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
if config["password"] && @options["include_password"] if config[:password] && @options[:include_password]
args << "--password=#{config['password']}" args << "--password=#{config[:password]}"
elsif config["password"] && !config["password"].to_s.empty? elsif config[:password] && !config[:password].to_s.empty?
args << "-p" args << "-p"
end end
args << config["database"] args << config[:database]
find_cmd_and_exec(["mysql", "mysql5"], *args) find_cmd_and_exec(["mysql", "mysql5"], *args)
when /^postgres|^postgis/ when /^postgres|^postgis/
ENV["PGUSER"] = config["username"] if config["username"] ENV["PGUSER"] = config[:username] if config[:username]
ENV["PGHOST"] = config["host"] if config["host"] ENV["PGHOST"] = config[:host] if config[:host]
ENV["PGPORT"] = config["port"].to_s if config["port"] ENV["PGPORT"] = config[:port].to_s if config[:port]
ENV["PGPASSWORD"] = config["password"].to_s if config["password"] && @options["include_password"] ENV["PGPASSWORD"] = config[:password].to_s if config[:password] && @options[:include_password]
find_cmd_and_exec("psql", config["database"]) find_cmd_and_exec("psql", config[:database])
when "sqlite3" when "sqlite3"
args = [] args = []
args << "-#{@options['mode']}" if @options["mode"] args << "-#{@options[:mode]}" if @options[:mode]
args << "-header" if @options["header"] args << "-header" if @options[:header]
args << File.expand_path(config["database"], Rails.respond_to?(:root) ? Rails.root : nil) args << File.expand_path(config[:database], Rails.respond_to?(:root) ? Rails.root : nil)
find_cmd_and_exec("sqlite3", *args) find_cmd_and_exec("sqlite3", *args)
when "oracle", "oracle_enhanced" when "oracle", "oracle_enhanced"
logon = "" logon = ""
if config["username"] if config[:username]
logon = config["username"].dup logon = config[:username].dup
logon << "/#{config['password']}" if config["password"] && @options["include_password"] logon << "/#{config[:password]}" if config[:password] && @options[:include_password]
logon << "@#{config['database']}" if config["database"] logon << "@#{config[:database]}" if config[:database]
end end
find_cmd_and_exec("sqlplus", logon) find_cmd_and_exec("sqlplus", logon)
@ -72,20 +72,20 @@ module Rails
when "sqlserver" when "sqlserver"
args = [] args = []
args += ["-D", "#{config['database']}"] if config["database"] args += ["-D", "#{config[:database]}"] if config[:database]
args += ["-U", "#{config['username']}"] if config["username"] args += ["-U", "#{config[:username]}"] if config[:username]
args += ["-P", "#{config['password']}"] if config["password"] args += ["-P", "#{config[:password]}"] if config[:password]
if config["host"] if config[:host]
host_arg = +"#{config['host']}" host_arg = +"#{config[:host]}"
host_arg << ":#{config['port']}" if config["port"] host_arg << ":#{config[:port]}" if config[:port]
args += ["-S", host_arg] args += ["-S", host_arg]
end end
find_cmd_and_exec("sqsh", *args) find_cmd_and_exec("sqsh", *args)
else else
abort "Unknown command-line client for #{config['database']}." abort "Unknown command-line client for #{config[:database]}."
end end
end end
@ -94,12 +94,12 @@ module Rails
# We need to check whether the user passed the database the # We need to check whether the user passed the database the
# first time around to show a consistent error message to people # first time around to show a consistent error message to people
# relying on 2-level database configuration. # relying on 2-level database configuration.
if @options["database"] && configurations[database].blank? if @options[:database] && configurations[database].blank?
raise ActiveRecord::AdapterNotSpecified, "'#{database}' database is not configured. Available configuration: #{configurations.inspect}" raise ActiveRecord::AdapterNotSpecified, "'#{database}' database is not configured. Available configuration: #{configurations.inspect}"
elsif configurations[environment].blank? && configurations[database].blank? elsif configurations[environment].blank? && configurations[database].blank?
raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}" raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}"
else else
configurations[database] || configurations[environment].presence (configurations[database] || configurations[environment].presence).symbolize_keys
end end
end end
end end

View file

@ -51,7 +51,7 @@ module ApplicationTests
test "db:create and db:drop without database URL" do test "db:create and db:drop without database URL" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
db_create_and_drop ActiveRecord::Base.configurations[Rails.env]["database"] db_create_and_drop ActiveRecord::Base.configurations[Rails.env][:database]
end end
test "db:create and db:drop with database URL" do test "db:create and db:drop with database URL" do
@ -310,7 +310,7 @@ module ApplicationTests
test "db:migrate and db:migrate:status without database_url" do test "db:migrate and db:migrate:status without database_url" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
db_migrate_and_status ActiveRecord::Base.configurations[Rails.env]["database"] db_migrate_and_status ActiveRecord::Base.configurations[Rails.env][:database]
end end
test "db:migrate and db:migrate:status with database_url" do test "db:migrate and db:migrate:status with database_url" do
@ -350,7 +350,7 @@ module ApplicationTests
test "db:fixtures:load without database_url" do test "db:fixtures:load without database_url" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
db_fixtures_load ActiveRecord::Base.configurations[Rails.env]["database"] db_fixtures_load ActiveRecord::Base.configurations[Rails.env][:database]
end end
test "db:fixtures:load with database_url" do test "db:fixtures:load with database_url" do
@ -385,7 +385,7 @@ module ApplicationTests
test "db:structure:dump and db:structure:load without database_url" do test "db:structure:dump and db:structure:load without database_url" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env]["database"] db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env][:database]
end end
test "db:structure:dump and db:structure:load with database_url" do test "db:structure:dump and db:structure:load with database_url" do
@ -396,7 +396,7 @@ module ApplicationTests
test "db:structure:dump and db:structure:load set ar_internal_metadata" do test "db:structure:dump and db:structure:load set ar_internal_metadata" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env]["database"] db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env][:database]
assert_equal "test", rails("runner", "-e", "test", "puts ActiveRecord::InternalMetadata[:environment]").strip assert_equal "test", rails("runner", "-e", "test", "puts ActiveRecord::InternalMetadata[:environment]").strip
assert_equal "development", rails("runner", "puts ActiveRecord::InternalMetadata[:environment]").strip assert_equal "development", rails("runner", "puts ActiveRecord::InternalMetadata[:environment]").strip
@ -475,7 +475,7 @@ module ApplicationTests
require "#{app_path}/app/models/book" require "#{app_path}/app/models/book"
# if structure is not loaded correctly, exception would be raised # if structure is not loaded correctly, exception would be raised
assert_equal 0, Book.count assert_equal 0, Book.count
assert_match ActiveRecord::Base.configurations["test"]["database"], assert_match ActiveRecord::Base.configurations["test"][:database],
ActiveRecord::Base.connection_config[:database] ActiveRecord::Base.connection_config[:database]
end end
end end

View file

@ -220,14 +220,14 @@ module ApplicationTests
test "db:create and db:drop works on all databases for env" do test "db:create and db:drop works on all databases for env" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).each do |db_config|
db_create_and_drop db_config.spec_name, db_config.config["database"] db_create_and_drop db_config.spec_name, db_config.configuration_hash[:database]
end end
end end
test "db:create:namespace and db:drop:namespace works on specified databases" do test "db:create:namespace and db:drop:namespace works on specified databases" do
require "#{app_path}/config/environment" require "#{app_path}/config/environment"
ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).each do |db_config| ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).each do |db_config|
db_create_and_drop_namespace db_config.spec_name, db_config.config["database"] db_create_and_drop_namespace db_config.spec_name, db_config.configuration_hash[:database]
end end
end end
@ -359,7 +359,7 @@ module ApplicationTests
db_migrate_and_schema_dump_and_load "schema" db_migrate_and_schema_dump_and_load "schema"
app_file "db/seeds.rb", <<-RUBY app_file "db/seeds.rb", <<-RUBY
print Book.connection.pool.spec.config[:database] print Book.connection.pool.spec.underlying_configuration_hash[:database]
RUBY RUBY
output = rails("db:seed") output = rails("db:seed")

View file

@ -966,7 +966,7 @@ module ApplicationTests
class EnvironmentTest < ActiveSupport::TestCase class EnvironmentTest < ActiveSupport::TestCase
def test_environment def test_environment
test_db = ActiveRecord::Base.configurations[#{env.dump}]["database"] test_db = ActiveRecord::Base.configurations[#{env.dump}][:database]
db_file = ActiveRecord::Base.connection_config[:database] db_file = ActiveRecord::Base.connection_config[:database]
assert_match(test_db, db_file) assert_match(test_db, db_file)
assert_equal #{env.dump}, ENV["RAILS_ENV"] assert_equal #{env.dump}, ENV["RAILS_ENV"]

View file

@ -29,7 +29,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
} }
} }
app_db_config(config_sample) do app_db_config(config_sample) do
assert_equal config_sample["test"], Rails::DBConsole.new.config assert_equal config_sample["test"].symbolize_keys, Rails::DBConsole.new.config
end end
end end
@ -44,14 +44,14 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
def test_config_with_database_url_only def test_config_with_database_url_only
ENV["DATABASE_URL"] = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000" ENV["DATABASE_URL"] = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000"
expected = { expected = {
"adapter" => "postgresql", adapter: "postgresql",
"host" => "localhost", host: "localhost",
"port" => 9000, port: 9000,
"database" => "foo_test", database: "foo_test",
"username" => "foo", username: "foo",
"password" => "bar", password: "bar",
"pool" => "5", pool: "5",
"timeout" => "3000" timeout: "3000"
}.sort }.sort
app_db_config(nil) do app_db_config(nil) do
@ -75,7 +75,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
} }
} }
app_db_config(sample_config) do app_db_config(sample_config) do
assert_equal host, Rails::DBConsole.new.config["host"] assert_equal host, Rails::DBConsole.new.config[:host]
end end
end end
@ -212,7 +212,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
} }
app_db_config(sample_config) do app_db_config(sample_config) do
assert_equal "postgresql", Rails::DBConsole.new.config["adapter"] assert_equal "postgresql", Rails::DBConsole.new.config[:adapter]
end end
end end
@ -295,7 +295,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
def start(config = {}, argv = []) def start(config = {}, argv = [])
@dbconsole = make_dbconsole.new(parse_arguments(argv)) @dbconsole = make_dbconsole.new(parse_arguments(argv))
@dbconsole.stub(:config, config.stringify_keys) do @dbconsole.stub(:config, config) do
capture_abort { @dbconsole.start } capture_abort { @dbconsole.start }
end end
end end