Deprecate ConnectionPool#connection

Replaced by `#lease_connection` to better reflect what it does.

`ActiveRecord::Base#connection` is deprecated in the same way
but without a removal timeline nor a deprecation warning.

Inside the Active Record test suite, we do remove `Base.connection`
to ensure it's not used internally.

Some callsites have been converted to use `with_connection`,
some other have been more simply migrated to `lease_connection`
and will serve as a list of callsites to convert for
https://github.com/rails/rails/pull/50793
This commit is contained in:
Jean Boussier 2024-03-01 12:18:50 +01:00
parent 75e3407917
commit 7263da542b
277 changed files with 1474 additions and 1397 deletions

@ -23,7 +23,7 @@ def setup
ActiveRecord::Base.establish_connection database_config ActiveRecord::Base.establish_connection database_config
begin begin
ActiveRecord::Base.connection.connect! ActiveRecord::Base.lease_connection.connect!
rescue rescue
@rx_adapter = @tx_adapter = nil @rx_adapter = @tx_adapter = nil
skip "Couldn't connect to PostgreSQL: #{database_config.inspect}" skip "Couldn't connect to PostgreSQL: #{database_config.inspect}"
@ -68,7 +68,7 @@ def active?
def test_default_subscription_connection_identifier def test_default_subscription_connection_identifier
subscribe_as_queue("channel") { } subscribe_as_queue("channel") { }
identifiers = ActiveRecord::Base.connection.exec_query("SELECT application_name FROM pg_stat_activity").rows identifiers = ActiveRecord::Base.lease_connection.exec_query("SELECT application_name FROM pg_stat_activity").rows
assert_includes identifiers, ["ActionCable-PID-#{$$}"] assert_includes identifiers, ["ActionCable-PID-#{$$}"]
end end
@ -81,7 +81,7 @@ def test_custom_subscription_connection_identifier
subscribe_as_queue("channel", adapter) { } subscribe_as_queue("channel", adapter) { }
identifiers = ActiveRecord::Base.connection.exec_query("SELECT application_name FROM pg_stat_activity").rows identifiers = ActiveRecord::Base.lease_connection.exec_query("SELECT application_name FROM pg_stat_activity").rows
assert_includes identifiers, ["hello-world-42"] assert_includes identifiers, ["hello-world-42"]
end end
end end

@ -8,7 +8,7 @@ class ActionMailbox::MigrationsTest < ActiveSupport::TestCase
@original_verbose = ActiveRecord::Migration.verbose @original_verbose = ActiveRecord::Migration.verbose
ActiveRecord::Migration.verbose = false ActiveRecord::Migration.verbose = false
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@original_options = Rails.configuration.generators.options.deep_dup @original_options = Rails.configuration.generators.options.deep_dup
end end

@ -44,7 +44,7 @@ def setup
def reconnect def reconnect
return unless able_to_connect return unless able_to_connect
ActiveRecord::Base.connection.reconnect! ActiveRecord::Base.lease_connection.reconnect!
load_schema load_schema
end end
@ -56,9 +56,9 @@ def setup_connection
options = defaults.merge adapter: adapter, timeout: 500 options = defaults.merge adapter: adapter, timeout: 500
ActiveRecord::Base.establish_connection(options) ActiveRecord::Base.establish_connection(options)
ActiveRecord::Base.configurations = { "sqlite3_ar_integration" => options } ActiveRecord::Base.configurations = { "sqlite3_ar_integration" => options }
ActiveRecord::Base.connection ActiveRecord::Base.lease_connection
Object.const_set :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name("type") unless Object.const_defined?(:QUOTED_TYPE) Object.const_set :QUOTED_TYPE, ActiveRecord::Base.lease_connection.quote_column_name("type") unless Object.const_defined?(:QUOTED_TYPE)
else else
raise "Can't setup connection since ActiveRecord isn't loaded." raise "Can't setup connection since ActiveRecord isn't loaded."
end end
@ -67,7 +67,7 @@ def setup_connection
# Load actionpack sqlite3 tables # Load actionpack sqlite3 tables
def load_schema def load_schema
File.read(File.expand_path("fixtures/db_definitions/sqlite.sql", __dir__)).split(";").each do |sql| File.read(File.expand_path("fixtures/db_definitions/sqlite.sql", __dir__)).split(";").each do |sql|
ActiveRecord::Base.connection.execute(sql) unless sql.blank? ActiveRecord::Base.lease_connection.execute(sql) unless sql.blank?
end end
end end
@ -107,7 +107,7 @@ def run(*args)
end end
def capture_sql def capture_sql
ActiveRecord::Base.connection.materialize_transactions ActiveRecord::Base.lease_connection.materialize_transactions
SQLCounter.clear_log SQLCounter.clear_log
yield yield
SQLCounter.log.dup SQLCounter.log.dup

@ -1,3 +1,20 @@
* Deprecate `ActiveRecord::Base.connection` in favor of `.lease_connection`
The method has been renamed as `lease_connection` to better reflect that the returned
connection will be held for the duration of the request or job.
This deprecation is a soft deprecation, no warnings will be issued and there is no
current plan to remove the method.
*Jean Boussier*
* Deprecate `ActiveRecord::ConnectionAdapters::ConnectionPool#connection`
The method has been renamed as `lease_connection` to better reflect that the returned
connection will be held for the duration of the request or job.
*Jean Boussier*
* Expose a generic fixture accessor for fixture names that may conflict with Minitest * Expose a generic fixture accessor for fixture names that may conflict with Minitest
```ruby ```ruby

@ -176,10 +176,10 @@ def self.email
end end
x.report "Model.log" do x.report "Model.log" do
Exhibit.connection.send(:log, "hello", "world") { } Exhibit.lease_connection.send(:log, "hello", "world") { }
end end
x.report "AR.execute(query)" do x.report "AR.execute(query)" do
ActiveRecord::Base.connection.execute("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}") ActiveRecord::Base.lease_connection.execute("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}")
end end
end end

@ -63,7 +63,7 @@ def reset_negative_cache # :nodoc:
# Reloads the \target and returns +self+ on success. # Reloads the \target and returns +self+ on success.
# The QueryCache is cleared if +force+ is true. # The QueryCache is cleared if +force+ is true.
def reload(force = false) def reload(force = false)
klass.connection.clear_query_cache if force && klass klass.connection_pool.clear_query_cache if force && klass
reset reset
reset_scope reset_scope
load_target load_target
@ -231,12 +231,14 @@ def find_target
end end
binds = AssociationScope.get_bind_values(owner, reflection.chain) binds = AssociationScope.get_bind_values(owner, reflection.chain)
sc.execute(binds, klass.connection) do |record| klass.with_connection do |c|
set_inverse_instance(record) sc.execute(binds, c) do |record|
if owner.strict_loading_n_plus_one_only? && reflection.macro == :has_many set_inverse_instance(record)
record.strict_loading! if owner.strict_loading_n_plus_one_only? && reflection.macro == :has_many
else record.strict_loading!
record.strict_loading!(false, mode: owner.strict_loading_mode) else
record.strict_loading!(false, mode: owner.strict_loading_mode)
end
end end
end end
end end

@ -91,7 +91,7 @@ def strict_loading?
def append_constraints(join, constraints) def append_constraints(join, constraints)
if join.is_a?(Arel::Nodes::StringJoin) if join.is_a?(Arel::Nodes::StringJoin)
join_string = Arel::Nodes::And.new(constraints.unshift join.left) join_string = Arel::Nodes::And.new(constraints.unshift join.left)
join.left = Arel.sql(base_klass.connection.visitor.compile(join_string)) join.left = Arel.sql(base_klass.lease_connection.visitor.compile(join_string))
else else
right = join.right right = join.right
right.expr = Arel::Nodes::And.new(constraints.unshift right.expr) right.expr = Arel::Nodes::And.new(constraints.unshift right.expr)

@ -233,7 +233,7 @@ module ActiveRecord # :nodoc:
# #
# Connections are usually created through # Connections are usually created through
# {ActiveRecord::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] and retrieved # {ActiveRecord::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] and retrieved
# by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this # by ActiveRecord::Base.lease_connection. All classes inheriting from ActiveRecord::Base will use this
# connection. But you can also set a class-specific connection. For example, if Course is an # connection. But you can also set a class-specific connection. For example, if Course is an
# ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt> # ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
# and Course and all of its subclasses will use this connection instead. # and Course and all of its subclasses will use this connection instead.

@ -190,7 +190,7 @@ def flush_idle_connections!(role = nil)
# for (not necessarily the current class). # for (not necessarily the current class).
def retrieve_connection(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) # :nodoc: def retrieve_connection(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) # :nodoc:
pool = retrieve_connection_pool(connection_name, role: role, shard: shard, strict: true) pool = retrieve_connection_pool(connection_name, role: role, shard: shard, strict: true)
pool.connection pool.lease_connection
end end
# Returns true if a connection that's accessible to this class has # Returns true if a connection that's accessible to this class has

@ -69,7 +69,7 @@ def db_config
# Connections can be obtained and used from a connection pool in several # Connections can be obtained and used from a connection pool in several
# ways: # ways:
# #
# 1. Simply use {ActiveRecord::Base.connection}[rdoc-ref:ConnectionHandling.connection]. # 1. Simply use {ActiveRecord::Base.lease_connection}[rdoc-ref:ConnectionHandling.connection].
# When you're done with the connection(s) and wish it to be returned to the pool, you call # When you're done with the connection(s) and wish it to be returned to the pool, you call
# {ActiveRecord::Base.connection_handler.clear_active_connections!}[rdoc-ref:ConnectionAdapters::ConnectionHandler#clear_active_connections!]. # {ActiveRecord::Base.connection_handler.clear_active_connections!}[rdoc-ref:ConnectionAdapters::ConnectionHandler#clear_active_connections!].
# This is the default behavior for Active Record when used in conjunction with # This is the default behavior for Active Record when used in conjunction with
@ -139,46 +139,46 @@ def clear(connection)
end end
end end
if ObjectSpace.const_defined?(:WeakKeyMap) # RUBY_VERSION >= 3.3
WeakKeyMap = ::ObjectSpace::WeakKeyMap # :nodoc:
else
class WeakKeyMap # :nodoc:
def initialize
@map = ObjectSpace::WeakMap.new
@values = nil
@size = 0
end
alias_method :clear, :initialize
def [](key)
prune if @map.size != @size
@map[key]
end
def []=(key, value)
@map[key] = value
prune if @map.size != @size
value
end
def delete(key)
if value = self[key]
self[key] = nil
prune
end
value
end
private
def prune(force = false)
@values = @map.values
@size = @map.size
end
end
end
class LeaseRegistry # :nodoc: class LeaseRegistry # :nodoc:
if ObjectSpace.const_defined?(:WeakKeyMap) # RUBY_VERSION >= 3.3
WeakKeyMap = ::ObjectSpace::WeakKeyMap # :nodoc:
else
class WeakKeyMap # :nodoc:
def initialize
@map = ObjectSpace::WeakMap.new
@values = nil
@size = 0
end
alias_method :clear, :initialize
def [](key)
prune if @map.size != @size
@map[key]
end
def []=(key, value)
@map[key] = value
prune if @map.size != @size
value
end
def delete(key)
if value = self[key]
self[key] = nil
prune
end
value
end
private
def prune(force = false)
@values = @map.values
@size = @map.size
end
end
end
def initialize def initialize
@mutex = Mutex.new @mutex = Mutex.new
@map = WeakKeyMap.new @map = WeakKeyMap.new
@ -293,7 +293,13 @@ def lease_connection
lease.connection ||= checkout lease.connection ||= checkout
end end
alias_method :connection, :lease_connection # TODO: deprecate def connection
ActiveRecord.deprecator.warn(<<~MSG)
ConnectionPoool#connection is deprecated and will be removed
in Rails 7.3. Use #lease_connection instead
MSG
lease_connection
end
def pin_connection!(lock_thread) # :nodoc: def pin_connection!(lock_thread) # :nodoc:
raise "There is already a pinned connection" if @pinned_connection raise "There is already a pinned connection" if @pinned_connection

@ -296,9 +296,9 @@ def truncate_tables(*table_names) # :nodoc:
# #transaction will raise exceptions when it tries to release the # #transaction will raise exceptions when it tries to release the
# already-automatically-released savepoints: # already-automatically-released savepoints:
# #
# Model.connection.transaction do # BEGIN # Model.lease_connection.transaction do # BEGIN
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 # Model.lease_connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
# Model.connection.create_table(...) # Model.lease_connection.create_table(...)
# # active_record_1 now automatically released # # active_record_1 now automatically released
# end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error! # end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
# end # end

@ -23,7 +23,7 @@ module ConnectionAdapters # :nodoc:
# and +:limit+ options, etc. # and +:limit+ options, etc.
# #
# All the concrete database adapters follow the interface laid down in this class. # All the concrete database adapters follow the interface laid down in this class.
# {ActiveRecord::Base.connection}[rdoc-ref:ConnectionHandling#connection] returns an AbstractAdapter object, which # {ActiveRecord::Base.lease_connection}[rdoc-ref:ConnectionHandling#lease_connection] returns an AbstractAdapter object, which
# you can use. # you can use.
# #
# Most of the methods in the adapter are useful during migrations. Most # Most of the methods in the adapter are useful during migrations. Most

@ -377,8 +377,8 @@ def type_caster # :nodoc:
end end
def cached_find_by_statement(key, &block) # :nodoc: def cached_find_by_statement(key, &block) # :nodoc:
cache = @find_by_statement_cache[connection.prepared_statements] cache = @find_by_statement_cache[lease_connection.prepared_statements]
cache.compute_if_absent(key) { StatementCache.create(connection, &block) } cache.compute_if_absent(key) { StatementCache.create(lease_connection, &block) }
end end
private private
@ -431,7 +431,7 @@ def cached_find_by(keys, values)
} }
begin begin
statement.execute(values.flatten, connection).first statement.execute(values.flatten, lease_connection).first
rescue TypeError rescue TypeError
raise ActiveRecord::StatementInvalid raise ActiveRecord::StatementInvalid
end end

@ -58,7 +58,7 @@ def initialize(message = nil, connection_pool: nil)
end end
# Raised when connection to the database could not been established (for example when # Raised when connection to the database could not been established (for example when
# {ActiveRecord::Base.connection=}[rdoc-ref:ConnectionHandling#connection] # {ActiveRecord::Base.lease_connection=}[rdoc-ref:ConnectionHandling#lease_connection]
# is given a +nil+ object). # is given a +nil+ object).
class ConnectionNotEstablished < AdapterError class ConnectionNotEstablished < AdapterError
def initialize(message = nil, connection_pool: nil) def initialize(message = nil, connection_pool: nil)

@ -17,16 +17,17 @@ def collecting_queries_for_explain # :nodoc:
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings. # Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
# Returns a formatted string ready to be logged. # Returns a formatted string ready to be logged.
def exec_explain(queries, options = []) # :nodoc: def exec_explain(queries, options = []) # :nodoc:
str = queries.map do |sql, binds| str = with_connection do |c|
msg = +"#{build_explain_clause(options)} #{sql}" queries.map do |sql, binds|
unless binds.empty? msg = +"#{build_explain_clause(c, options)} #{sql}"
msg << " " unless binds.empty?
msg << binds.map { |attr| render_bind(attr) }.inspect msg << " "
end msg << binds.map { |attr| render_bind(c, attr) }.inspect
msg << "\n" end
msg << connection.explain(sql, binds, options) msg << "\n"
end.join("\n") msg << c.explain(sql, binds, options)
end.join("\n")
end
# Overriding inspect to be more human readable, especially in the console. # Overriding inspect to be more human readable, especially in the console.
def str.inspect def str.inspect
self self
@ -36,7 +37,7 @@ def str.inspect
end end
private private
def render_bind(attr) def render_bind(connection, attr)
if ActiveModel::Attribute === attr if ActiveModel::Attribute === attr
value = if attr.type.binary? && attr.value value = if attr.type.binary? && attr.value
"<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>"
@ -51,7 +52,7 @@ def render_bind(attr)
[attr&.name, value] [attr&.name, value]
end end
def build_explain_clause(options = []) def build_explain_clause(connection, options = [])
if connection.respond_to?(:build_explain_clause, true) if connection.respond_to?(:build_explain_clause, true)
connection.build_explain_clause(options) connection.build_explain_clause(options)
else else

@ -143,7 +143,9 @@ def execute_or_wait
start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
@mutex.synchronize do @mutex.synchronize do
if pending? if pending?
execute_query(@pool.connection) @pool.with_connection do |connection|
execute_query(connection)
end
else else
@lock_wait = (Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - start) @lock_wait = (Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - start)
end end

@ -8,7 +8,7 @@ class InsertAll # :nodoc:
attr_reader :on_duplicate, :update_only, :returning, :unique_by, :update_sql attr_reader :on_duplicate, :update_only, :returning, :unique_by, :update_sql
def initialize(model, inserts, on_duplicate:, update_only: nil, returning: nil, unique_by: nil, record_timestamps: nil) def initialize(model, inserts, on_duplicate:, update_only: nil, returning: nil, unique_by: nil, record_timestamps: nil)
@model, @connection, @inserts = model, model.connection, inserts.map(&:stringify_keys) @model, @connection, @inserts = model, model.lease_connection, inserts.map(&:stringify_keys)
@on_duplicate, @update_only, @returning, @unique_by = on_duplicate, update_only, returning, unique_by @on_duplicate, @update_only, @returning, @unique_by = on_duplicate, update_only, returning, unique_by
@record_timestamps = record_timestamps.nil? ? model.record_timestamps : record_timestamps @record_timestamps = record_timestamps.nil? ? model.record_timestamps : record_timestamps

@ -178,7 +178,7 @@ def collection_cache_key(collection = all, timestamp_column = :updated_at) # :no
def can_use_fast_cache_version?(timestamp) def can_use_fast_cache_version?(timestamp)
timestamp.is_a?(String) && timestamp.is_a?(String) &&
cache_timestamp_format == :usec && cache_timestamp_format == :usec &&
self.class.connection.default_timezone == :utc && self.class.lease_connection.default_timezone == :utc &&
!updated_at_came_from_user? !updated_at_came_from_user?
end end

@ -374,7 +374,7 @@ def sequence_name
def reset_sequence_name # :nodoc: def reset_sequence_name # :nodoc:
@explicit_sequence_name = false @explicit_sequence_name = false
@sequence_name = connection.default_sequence_name(table_name, primary_key) @sequence_name = lease_connection.default_sequence_name(table_name, primary_key)
end end
# Sets the name of the sequence to use when generating ids to the given # Sets the name of the sequence to use when generating ids to the given
@ -399,13 +399,13 @@ def sequence_name=(value)
# Determines if the primary key values should be selected from their # Determines if the primary key values should be selected from their
# corresponding sequence before the insert statement. # corresponding sequence before the insert statement.
def prefetch_primary_key? def prefetch_primary_key?
connection.prefetch_primary_key?(table_name) lease_connection.prefetch_primary_key?(table_name)
end end
# Returns the next value that will be used as the primary key on # Returns the next value that will be used as the primary key on
# an insert statement. # an insert statement.
def next_sequence_value def next_sequence_value
connection.next_sequence_value(sequence_name) lease_connection.next_sequence_value(sequence_name)
end end
# Indicates whether the table associated with this class exists # Indicates whether the table associated with this class exists
@ -433,7 +433,7 @@ def columns
def _returning_columns_for_insert # :nodoc: def _returning_columns_for_insert # :nodoc:
@_returning_columns_for_insert ||= begin @_returning_columns_for_insert ||= begin
auto_populated_columns = columns.filter_map do |c| auto_populated_columns = columns.filter_map do |c|
c.name if connection.return_value_after_insert?(c) c.name if lease_connection.return_value_after_insert?(c)
end end
auto_populated_columns.empty? ? Array(primary_key) : auto_populated_columns auto_populated_columns.empty? ? Array(primary_key) : auto_populated_columns
@ -518,7 +518,7 @@ def content_columns
# end # end
# end # end
def reset_column_information def reset_column_information
connection.clear_cache! lease_connection.clear_cache!
([self] + descendants).each(&:undefine_attribute_methods) ([self] + descendants).each(&:undefine_attribute_methods)
schema_cache.clear_data_source_cache!(table_name) schema_cache.clear_data_source_cache!(table_name)
@ -613,7 +613,7 @@ def compute_table_name
end end
def type_for_column(column) def type_for_column(column)
type = connection.lookup_cast_type_from_column(column) type = lease_connection.lookup_cast_type_from_column(column)
if immutable_strings_by_default && type.respond_to?(:to_immutable_string) if immutable_strings_by_default && type.respond_to?(:to_immutable_string)
type = type.to_immutable_string type = type.to_immutable_string

@ -581,16 +581,18 @@ def _insert_record(values, returning) # :nodoc:
im = Arel::InsertManager.new(arel_table) im = Arel::InsertManager.new(arel_table)
if values.empty? with_connection do |c|
im.insert(connection.empty_insert_statement_value(primary_key)) if values.empty?
else im.insert(c.empty_insert_statement_value(primary_key))
im.insert(values.transform_keys { |name| arel_table[name] }) else
end im.insert(values.transform_keys { |name| arel_table[name] })
end
connection.insert( c.insert(
im, "#{self} Create", primary_key || false, primary_key_value, im, "#{self} Create", primary_key || false, primary_key_value,
returning: returning returning: returning
) )
end
end end
def _update_record(values, constraints) # :nodoc: def _update_record(values, constraints) # :nodoc:
@ -607,7 +609,9 @@ def _update_record(values, constraints) # :nodoc:
um.set(values.transform_keys { |name| arel_table[name] }) um.set(values.transform_keys { |name| arel_table[name] })
um.wheres = constraints um.wheres = constraints
connection.update(um, "#{self} Update") with_connection do |c|
c.update(um, "#{self} Update")
end
end end
def _delete_record(constraints) # :nodoc: def _delete_record(constraints) # :nodoc:
@ -623,7 +627,9 @@ def _delete_record(constraints) # :nodoc:
dm = Arel::DeleteManager.new(arel_table) dm = Arel::DeleteManager.new(arel_table)
dm.wheres = constraints dm.wheres = constraints
connection.delete(dm, "#{self} Destroy") with_connection do |c|
c.delete(dm, "#{self} Destroy")
end
end end
private private
@ -1069,7 +1075,7 @@ def toggle!(attribute)
# end # end
# #
def reload(options = nil) def reload(options = nil)
self.class.connection.clear_query_cache self.class.connection_pool.clear_query_cache
fresh_object = if apply_scoping?(options) fresh_object = if apply_scoping?(options)
_find_record((options || {}).merge(all_queries: true)) _find_record((options || {}).merge(all_queries: true))

@ -42,7 +42,7 @@ def self.complete(pools)
end end
ActiveRecord::Base.connection_handler.each_connection_pool do |pool| ActiveRecord::Base.connection_handler.each_connection_pool do |pool|
pool.release_connection if pool.active_connection? && !pool.connection.transaction_open? pool.release_connection if pool.active_connection? && !pool.lease_connection.transaction_open?
end end
end end

@ -59,7 +59,7 @@ def async_find_by_sql(sql, binds = [], preparable: nil, &block)
end end
def _query_by_sql(sql, binds = [], preparable: nil, async: false) # :nodoc: def _query_by_sql(sql, binds = [], preparable: nil, async: false) # :nodoc:
connection.select_all(sanitize_sql(sql), "#{name} Load", binds, preparable: preparable, async: async) lease_connection.select_all(sanitize_sql(sql), "#{name} Load", binds, preparable: preparable, async: async)
end end
def _load_from_sql(result_set, &block) # :nodoc: def _load_from_sql(result_set, &block) # :nodoc:
@ -99,12 +99,12 @@ def _load_from_sql(result_set, &block) # :nodoc:
# #
# * +sql+ - An SQL statement which should return a count query from the database, see the example above. # * +sql+ - An SQL statement which should return a count query from the database, see the example above.
def count_by_sql(sql) def count_by_sql(sql)
connection.select_value(sanitize_sql(sql), "#{name} Count").to_i lease_connection.select_value(sanitize_sql(sql), "#{name} Count").to_i
end end
# Same as <tt>#count_by_sql</tt> but perform the query asynchronously and returns an ActiveRecord::Promise. # Same as <tt>#count_by_sql</tt> but perform the query asynchronously and returns an ActiveRecord::Promise.
def async_count_by_sql(sql) def async_count_by_sql(sql)
connection.select_value(sanitize_sql(sql), "#{name} Count", async: true).then(&:to_i) lease_connection.select_value(sanitize_sql(sql), "#{name} Count", async: true).then(&:to_i)
end end
end end
end end

@ -265,7 +265,7 @@ def find_or_create_by!(attributes, &block)
def create_or_find_by(attributes, &block) def create_or_find_by(attributes, &block)
transaction(requires_new: true) { create(attributes, &block) } transaction(requires_new: true) { create(attributes, &block) }
rescue ActiveRecord::RecordNotUnique rescue ActiveRecord::RecordNotUnique
if connection.transaction_open? if lease_connection.transaction_open?
where(attributes).lock.find_by!(attributes) where(attributes).lock.find_by!(attributes)
else else
find_by!(attributes) find_by!(attributes)
@ -278,7 +278,7 @@ def create_or_find_by(attributes, &block)
def create_or_find_by!(attributes, &block) def create_or_find_by!(attributes, &block)
transaction(requires_new: true) { create!(attributes, &block) } transaction(requires_new: true) { create!(attributes, &block) }
rescue ActiveRecord::RecordNotUnique rescue ActiveRecord::RecordNotUnique
if connection.transaction_open? if lease_connection.transaction_open?
where(attributes).lock.find_by!(attributes) where(attributes).lock.find_by!(attributes)
else else
find_by!(attributes) find_by!(attributes)
@ -468,28 +468,30 @@ def compute_cache_version(timestamp_column) # :nodoc:
else else
collection = eager_loading? ? apply_join_dependency : self collection = eager_loading? ? apply_join_dependency : self
column = connection.visitor.compile(table[timestamp_column]) with_connection do |c|
select_values = "COUNT(*) AS #{adapter_class.quote_column_name("size")}, MAX(%s) AS timestamp" column = c.visitor.compile(table[timestamp_column])
select_values = "COUNT(*) AS #{adapter_class.quote_column_name("size")}, MAX(%s) AS timestamp"
if collection.has_limit_or_offset? if collection.has_limit_or_offset?
query = collection.select("#{column} AS collection_cache_key_timestamp") query = collection.select("#{column} AS collection_cache_key_timestamp")
query._select!(table[Arel.star]) if distinct_value && collection.select_values.empty? query._select!(table[Arel.star]) if distinct_value && collection.select_values.empty?
subquery_alias = "subquery_for_cache_key" subquery_alias = "subquery_for_cache_key"
subquery_column = "#{subquery_alias}.collection_cache_key_timestamp" subquery_column = "#{subquery_alias}.collection_cache_key_timestamp"
arel = query.build_subquery(subquery_alias, select_values % subquery_column) arel = query.build_subquery(subquery_alias, select_values % subquery_column)
else else
query = collection.unscope(:order) query = collection.unscope(:order)
query.select_values = [select_values % column] query.select_values = [select_values % column]
arel = query.arel arel = query.arel
end end
size, timestamp = connection.select_rows(arel, nil).first size, timestamp = c.select_rows(arel, nil).first
if size if size
column_type = klass.type_for_attribute(timestamp_column) column_type = klass.type_for_attribute(timestamp_column)
timestamp = column_type.deserialize(timestamp) timestamp = column_type.deserialize(timestamp)
else else
size = 0 size = 0
end
end end
end end
@ -599,7 +601,9 @@ def update_all(updates)
table[primary_key] table[primary_key]
end end
stmt = arel.compile_update(values, key, having_clause_ast, group_values_arel_columns) stmt = arel.compile_update(values, key, having_clause_ast, group_values_arel_columns)
klass.connection.update(stmt, "#{klass} Update All").tap { reset } klass.with_connection do |c|
c.update(stmt, "#{klass} Update All").tap { reset }
end
end end
def update(id = :all, attributes) # :nodoc: def update(id = :all, attributes) # :nodoc:
@ -738,7 +742,9 @@ def delete_all
end end
stmt = arel.compile_delete(key, having_clause_ast, group_values_arel_columns) stmt = arel.compile_delete(key, having_clause_ast, group_values_arel_columns)
klass.connection.delete(stmt, "#{klass} Delete All").tap { reset } klass.with_connection do |c|
c.delete(stmt, "#{klass} Delete All").tap { reset }
end
end end
# Finds and destroys all records matching the specified conditions. # Finds and destroys all records matching the specified conditions.
@ -786,17 +792,19 @@ def delete_by(*args)
# #
# ASYNC Post Load (0.0ms) (db time 2ms) SELECT "posts".* FROM "posts" LIMIT 100 # ASYNC Post Load (0.0ms) (db time 2ms) SELECT "posts".* FROM "posts" LIMIT 100
def load_async def load_async
return load if !connection.async_enabled? with_connection do |c|
return load if !c.async_enabled?
unless loaded? unless loaded?
result = exec_main_query(async: connection.current_transaction.closed?) result = exec_main_query(async: c.current_transaction.closed?)
if result.is_a?(Array) if result.is_a?(Array)
@records = result @records = result
else else
@future_result = result @future_result = result
end
@loaded = true
end end
@loaded = true
end end
self self
@ -852,8 +860,9 @@ def to_sql
relation.to_sql relation.to_sql
end end
else else
conn = klass.connection klass.with_connection do |conn|
conn.unprepared_statement { conn.to_sql(arel) } conn.unprepared_statement { conn.to_sql(arel) }
end
end end
end end
@ -938,7 +947,7 @@ def has_limit_or_offset? # :nodoc:
end end
def alias_tracker(joins = [], aliases = nil) # :nodoc: def alias_tracker(joins = [], aliases = nil) # :nodoc:
ActiveRecord::Associations::AliasTracker.create(connection, table.name, joins, aliases) ActiveRecord::Associations::AliasTracker.create(lease_connection, table.name, joins, aliases)
end end
class StrictLoadingScope # :nodoc: class StrictLoadingScope # :nodoc:
@ -1062,13 +1071,15 @@ def exec_main_query(async: false)
if where_clause.contradiction? if where_clause.contradiction?
[].freeze [].freeze
elsif eager_loading? elsif eager_loading?
apply_join_dependency do |relation, join_dependency| with_connection do |c|
if relation.null_relation? apply_join_dependency do |relation, join_dependency|
[].freeze if relation.null_relation?
else [].freeze
relation = join_dependency.apply_column_aliases(relation) else
@_join_dependency = join_dependency relation = join_dependency.apply_column_aliases(relation)
connection.select_all(relation.arel, "SQL", async: async) @_join_dependency = join_dependency
c.select_all(relation.arel, "SQL", async: async)
end
end end
end end
else else

@ -310,7 +310,9 @@ def pluck(*column_names)
if where_clause.contradiction? if where_clause.contradiction?
ActiveRecord::Result.empty(async: @async) ActiveRecord::Result.empty(async: @async)
else else
klass.connection.select_all(relation.arel, "#{klass.name} Pluck", async: @async) klass.with_connection do |c|
c.select_all(relation.arel, "#{klass.name} Pluck", async: @async)
end
end end
end end
result.then do |result| result.then do |result|
@ -385,7 +387,9 @@ def ids
ActiveRecord::Result.empty ActiveRecord::Result.empty
else else
skip_query_cache_if_necessary do skip_query_cache_if_necessary do
klass.connection.select_all(relation, "#{klass.name} Ids", async: @async) klass.with_connection do |c|
c.select_all(relation, "#{klass.name} Ids", async: @async)
end
end end
end end
@ -474,7 +478,9 @@ def execute_simple_calculation(operation, column_name, distinct) # :nodoc:
ActiveRecord::Result.empty ActiveRecord::Result.empty
else else
skip_query_cache_if_necessary do skip_query_cache_if_necessary do
@klass.connection.select_all(query_builder, "#{@klass.name} #{operation.capitalize}", async: @async) @klass.with_connection do |c|
c.select_all(query_builder, "#{@klass.name} #{operation.capitalize}", async: @async)
end
end end
end end
@ -500,10 +506,10 @@ def execute_grouped_calculation(operation, column_name, distinct) # :nodoc:
end end
group_fields = arel_columns(group_fields) group_fields = arel_columns(group_fields)
column_alias_tracker = ColumnAliasTracker.new(connection) column_alias_tracker = ColumnAliasTracker.new(lease_connection)
group_aliases = group_fields.map { |field| group_aliases = group_fields.map { |field|
field = connection.visitor.compile(field) if Arel.arel_node?(field) field = lease_connection.visitor.compile(field) if Arel.arel_node?(field)
column_alias_tracker.alias_for(field.to_s.downcase) column_alias_tracker.alias_for(field.to_s.downcase)
} }
group_columns = group_aliases.zip(group_fields) group_columns = group_aliases.zip(group_fields)
@ -529,7 +535,12 @@ def execute_grouped_calculation(operation, column_name, distinct) # :nodoc:
relation.group_values = group_fields relation.group_values = group_fields
relation.select_values = select_values relation.select_values = select_values
result = skip_query_cache_if_necessary { @klass.connection.select_all(relation.arel, "#{@klass.name} #{operation.capitalize}", async: @async) } result = skip_query_cache_if_necessary do
@klass.with_connection do |c|
c.select_all(relation.arel, "#{@klass.name} #{operation.capitalize}", async: @async)
end
end
result.then do |calculated_data| result.then do |calculated_data|
if association if association
key_ids = calculated_data.collect { |row| row[group_aliases.first] } key_ids = calculated_data.collect { |row| row[group_aliases.first] }

@ -374,7 +374,11 @@ def exists?(conditions = :none)
relation = construct_relation_for_exists(conditions) relation = construct_relation_for_exists(conditions)
return false if relation.where_clause.contradiction? return false if relation.where_clause.contradiction?
skip_query_cache_if_necessary { connection.select_rows(relation.arel, "#{name} Exists?").size == 1 } skip_query_cache_if_necessary do
with_connection do |c|
c.select_rows(relation.arel, "#{name} Exists?").size == 1
end
end
end end
# Returns true if the relation contains the given record or false otherwise. # Returns true if the relation contains the given record or false otherwise.
@ -467,7 +471,9 @@ def apply_join_dependency(eager_loading: group_values.empty?)
) )
) )
relation = skip_query_cache_if_necessary do relation = skip_query_cache_if_necessary do
klass.connection.distinct_relation_for_primary_key(relation) klass.with_connection do |c|
c.distinct_relation_for_primary_key(relation)
end
end end
end end

@ -1653,7 +1653,7 @@ def build_arel(aliases = nil)
arel.where(where_clause.ast) unless where_clause.empty? arel.where(where_clause.ast) unless where_clause.empty?
arel.having(having_clause.ast) unless having_clause.empty? arel.having(having_clause.ast) unless having_clause.empty?
arel.take(build_cast_value("LIMIT", connection.sanitize_limit(limit_value))) if limit_value arel.take(build_cast_value("LIMIT", lease_connection.sanitize_limit(limit_value))) if limit_value
arel.skip(build_cast_value("OFFSET", offset_value.to_i)) if offset_value arel.skip(build_cast_value("OFFSET", offset_value.to_i)) if offset_value
arel.group(*arel_columns(group_values.uniq)) unless group_values.empty? arel.group(*arel_columns(group_values.uniq)) unless group_values.empty?

@ -8,7 +8,7 @@ module ActiveRecord
# {#exec_query}[rdoc-ref:ConnectionAdapters::DatabaseStatements#exec_query] # {#exec_query}[rdoc-ref:ConnectionAdapters::DatabaseStatements#exec_query]
# on any database connection adapter. For example: # on any database connection adapter. For example:
# #
# result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts') # result = ActiveRecord::Base.lease_connection.exec_query('SELECT id, title, body FROM posts')
# result # => #<ActiveRecord::Result:0xdeadbeef> # result # => #<ActiveRecord::Result:0xdeadbeef>
# #
# # Get the column names of the result: # # Get the column names of the result:

@ -169,7 +169,7 @@ def sanitize_sql_array(ary)
elsif statement.blank? elsif statement.blank?
statement statement
else else
statement % values.collect { |value| connection.quote_string(value.to_s) } statement % values.collect { |value| lease_connection.quote_string(value.to_s) }
end end
end end
@ -196,13 +196,13 @@ def disallow_raw_sql!(args, permit: adapter_class.column_name_matcher) # :nodoc:
def replace_bind_variables(statement, values) def replace_bind_variables(statement, values)
raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size)
bound = values.dup bound = values.dup
c = connection c = lease_connection
statement.gsub(/\?/) do statement.gsub(/\?/) do
replace_bind_variable(bound.shift, c) replace_bind_variable(bound.shift, c)
end end
end end
def replace_bind_variable(value, c = connection) def replace_bind_variable(value, c = lease_connection)
if ActiveRecord::Relation === value if ActiveRecord::Relation === value
value.to_sql value.to_sql
else else
@ -224,7 +224,7 @@ def replace_named_bind_variables(statement, bind_vars)
end end
end end
def quote_bound_value(value, c = connection) def quote_bound_value(value, c = lease_connection)
if value.respond_to?(:map) && !value.acts_like?(:string) if value.respond_to?(:map) && !value.acts_like?(:string)
values = value.map { |v| v.respond_to?(:id_for_database) ? v.id_for_database : v } values = value.map { |v| v.respond_to?(:id_for_database) ? v.id_for_database : v }
if values.empty? if values.empty?

@ -4,14 +4,14 @@ module ActiveRecord
# Statement cache is used to cache a single statement in order to avoid creating the AST again. # Statement cache is used to cache a single statement in order to avoid creating the AST again.
# Initializing the cache is done by passing the statement in the create block: # Initializing the cache is done by passing the statement in the create block:
# #
# cache = StatementCache.create(Book.connection) do |params| # cache = StatementCache.create(ClothingItem.lease_connection) do |params|
# Book.where(name: "my book").where("author_id > 3") # Book.where(name: "my book").where("author_id > 3")
# end # end
# #
# The cached statement is executed by using the # The cached statement is executed by using the
# {connection.execute}[rdoc-ref:ConnectionAdapters::DatabaseStatements#execute] method: # {connection.execute}[rdoc-ref:ConnectionAdapters::DatabaseStatements#execute] method:
# #
# cache.execute([], Book.connection) # cache.execute([], ClothingItem.lease_connection)
# #
# The relation returned by the block is cached, and for each # The relation returned by the block is cached, and for each
# {execute}[rdoc-ref:ConnectionAdapters::DatabaseStatements#execute] # {execute}[rdoc-ref:ConnectionAdapters::DatabaseStatements#execute]
@ -20,13 +20,13 @@ module ActiveRecord
# If you want to cache the statement without the values you can use the +bind+ method of the # If you want to cache the statement without the values you can use the +bind+ method of the
# block parameter. # block parameter.
# #
# cache = StatementCache.create(Book.connection) do |params| # cache = StatementCache.create(ClothingItem.lease_connection) do |params|
# Book.where(name: params.bind) # Book.where(name: params.bind)
# end # end
# #
# And pass the bind values as the first argument of +execute+ call. # And pass the bind values as the first argument of +execute+ call.
# #
# cache.execute(["my book"], Book.connection) # cache.execute(["my book"], ClothingItem.lease_connection)
class StatementCache # :nodoc: class StatementCache # :nodoc:
class Substitute; end # :nodoc: class Substitute; end # :nodoc:

@ -489,7 +489,7 @@ def load_seed
# Dumps the schema cache in YAML format for the connection into the file # Dumps the schema cache in YAML format for the connection into the file
# #
# ==== Examples # ==== Examples
# ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.connection, "tmp/schema_dump.yaml") # ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.lease_connection, "tmp/schema_dump.yaml")
def dump_schema_cache(conn_or_pool, filename) def dump_schema_cache(conn_or_pool, filename)
conn_or_pool.schema_cache.dump_to(filename) conn_or_pool.schema_cache.dump_to(filename)
end end
@ -509,9 +509,9 @@ def with_temporary_pool_for_each(env: ActiveRecord::Tasks::DatabaseTasks.env, na
end end
end end
def with_temporary_connection(db_config, clobber: false) # :nodoc: def with_temporary_connection(db_config, clobber: false, &block) # :nodoc:
with_temporary_pool(db_config, clobber: clobber) do |pool| with_temporary_pool(db_config, clobber: clobber) do |pool|
yield pool.connection pool.with_connection(&block)
end end
end end
@ -520,7 +520,7 @@ def migration_class # :nodoc:
end end
def migration_connection # :nodoc: def migration_connection # :nodoc:
migration_class.connection migration_class.lease_connection
end end
def migration_connection_pool # :nodoc: def migration_connection_pool # :nodoc:

@ -71,7 +71,7 @@ def structure_load(filename, extra_flags)
attr_reader :db_config, :configuration_hash attr_reader :db_config, :configuration_hash
def connection def connection
ActiveRecord::Base.connection ActiveRecord::Base.lease_connection
end end
def establish_connection(config = db_config) def establish_connection(config = db_config)

@ -88,7 +88,7 @@ def structure_load(filename, extra_flags)
attr_reader :db_config, :configuration_hash attr_reader :db_config, :configuration_hash
def connection def connection
ActiveRecord::Base.connection ActiveRecord::Base.lease_connection
end end
def establish_connection(config = db_config) def establish_connection(config = db_config)

@ -66,7 +66,7 @@ def structure_load(filename, extra_flags)
attr_reader :db_config, :root attr_reader :db_config, :root
def connection def connection
ActiveRecord::Base.connection ActiveRecord::Base.lease_connection
end end
def establish_connection(config = db_config) def establish_connection(config = db_config)

@ -157,7 +157,7 @@ def setup_transactional_fixtures
@fixture_connection_pools = ActiveRecord::Base.connection_handler.connection_pool_list(:writing) @fixture_connection_pools = ActiveRecord::Base.connection_handler.connection_pool_list(:writing)
@fixture_connection_pools.each do |pool| @fixture_connection_pools.each do |pool|
pool.pin_connection!(lock_threads) pool.pin_connection!(lock_threads)
pool.connection pool.lease_connection
end end
# When connections are established in the future, begin a transaction too # When connections are established in the future, begin a transaction too
@ -172,7 +172,7 @@ def setup_transactional_fixtures
unless @fixture_connection_pools.include?(pool) unless @fixture_connection_pools.include?(pool)
pool.pin_connection!(lock_threads) pool.pin_connection!(lock_threads)
pool.connection pool.lease_connection
@fixture_connection_pools << pool @fixture_connection_pools << pool
end end
end end

@ -16,7 +16,7 @@ module QueryAssertions
# assert_queries_count(1, include_schema: true) { Post.columns } # assert_queries_count(1, include_schema: true) { Post.columns }
# #
def assert_queries_count(count = nil, include_schema: false, &block) def assert_queries_count(count = nil, include_schema: false, &block)
ActiveRecord::Base.connection.materialize_transactions ActiveRecord::Base.lease_connection.materialize_transactions
counter = SQLCounter.new counter = SQLCounter.new
ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do
@ -57,7 +57,7 @@ def assert_no_queries(include_schema: false, &block)
# assert_queries_match(/FROM pg_attribute/i, include_schema: true) { Post.columns } # assert_queries_match(/FROM pg_attribute/i, include_schema: true) { Post.columns }
# #
def assert_queries_match(match, count: nil, include_schema: false, &block) def assert_queries_match(match, count: nil, include_schema: false, &block)
ActiveRecord::Base.connection.materialize_transactions ActiveRecord::Base.lease_connection.materialize_transactions
counter = SQLCounter.new counter = SQLCounter.new
ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do

@ -75,7 +75,7 @@ def all_timestamp_attributes_in_model
end end
def current_time_from_proper_timezone def current_time_from_proper_timezone
connection.default_timezone == :utc ? Time.now.utc : Time.now lease_connection.default_timezone == :utc ? Time.now.utc : Time.now
end end
protected protected

@ -208,9 +208,9 @@ module Transactions
# database error will occur because the savepoint has already been # database error will occur because the savepoint has already been
# automatically released. The following example demonstrates the problem: # automatically released. The following example demonstrates the problem:
# #
# Model.connection.transaction do # BEGIN # Model.lease_connection.transaction do # BEGIN
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 # Model.lease_connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
# Model.connection.create_table(...) # active_record_1 now automatically released # Model.lease_connection.create_table(...) # active_record_1 now automatically released
# end # RELEASE SAVEPOINT active_record_1 # end # RELEASE SAVEPOINT active_record_1
# # ^^^^ BOOM! database error! # # ^^^^ BOOM! database error!
# end # end
@ -394,7 +394,7 @@ def rolledback!(force_restore_state: false, should_run_callbacks: true) # :nodoc
# instance. # instance.
def with_transaction_returning_status def with_transaction_returning_status
status = nil status = nil
connection = self.class.connection connection = self.class.lease_connection
ensure_finalize = !connection.transaction_open? ensure_finalize = !connection.transaction_open?
connection.transaction do connection.transaction do
@ -496,7 +496,7 @@ def transaction_include_any_action?(actions)
# Add the record to the current transaction so that the #after_rollback and #after_commit # Add the record to the current transaction so that the #after_rollback and #after_commit
# callbacks can be called. # callbacks can be called.
def add_to_transaction(ensure_finalize = true) def add_to_transaction(ensure_finalize = true)
self.class.connection.add_transaction_record(self, ensure_finalize) self.class.lease_connection.add_transaction_record(self, ensure_finalize)
end end
def has_transactional_callbacks? def has_transactional_callbacks?

@ -19,7 +19,7 @@ def type_for_attribute(attr_name)
if schema_cache.data_source_exists?(table_name) if schema_cache.data_source_exists?(table_name)
column = schema_cache.columns_hash(table_name)[attr_name.to_s] column = schema_cache.columns_hash(table_name)[attr_name.to_s]
if column if column
type = @klass.connection.lookup_cast_type_from_column(column) type = @klass.lease_connection.lookup_cast_type_from_column(column)
end end
end end

@ -114,12 +114,12 @@ def build_relation(klass, attribute, value)
return relation.none! if bind.unboundable? return relation.none! if bind.unboundable?
if !options.key?(:case_sensitive) || bind.nil? if !options.key?(:case_sensitive) || bind.nil?
klass.connection.default_uniqueness_comparison(attr, bind) klass.lease_connection.default_uniqueness_comparison(attr, bind)
elsif options[:case_sensitive] elsif options[:case_sensitive]
klass.connection.case_sensitive_comparison(attr, bind) klass.lease_connection.case_sensitive_comparison(attr, bind)
else else
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation # will use SQL LOWER function before comparison, unless it detects a case insensitive collation
klass.connection.case_insensitive_comparison(attr, bind) klass.lease_connection.case_insensitive_comparison(attr, bind)
end end
end end

@ -147,7 +147,7 @@ def invert
# Maybe we should just use `Table.engine`? :'( # Maybe we should just use `Table.engine`? :'(
def to_sql(engine = Table.engine) def to_sql(engine = Table.engine)
collector = Arel::Collectors::SQLString.new collector = Arel::Collectors::SQLString.new
collector = engine.connection.visitor.accept self, collector collector = engine.lease_connection.visitor.accept self, collector
collector.value collector.value
end end

@ -52,7 +52,7 @@ def to_dot
def to_sql(engine = Table.engine) def to_sql(engine = Table.engine)
collector = Arel::Collectors::SQLString.new collector = Arel::Collectors::SQLString.new
collector = engine.connection.visitor.accept @ast, collector collector = engine.lease_connection.visitor.accept @ast, collector
collector.value collector.value
end end

@ -72,7 +72,7 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase
assert_equal 2, delete_sqls.count assert_equal 2, delete_sqls.count
delete_sqls.each do |sql| delete_sqls.each do |sql|
assert_match(/#{Regexp.escape(Sharded::Tag.connection.quote_table_name("sharded_tags.blog_id"))} =/, sql) assert_match(/#{Regexp.escape(Sharded::Tag.lease_connection.quote_table_name("sharded_tags.blog_id"))} =/, sql)
end end
ensure ensure
Sharded::Tag.delete_all Sharded::Tag.delete_all
@ -185,7 +185,7 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase
delete_sqls = sql.select { |sql| sql.start_with?("DELETE") } delete_sqls = sql.select { |sql| sql.start_with?("DELETE") }
assert_equal 1, delete_sqls.count assert_equal 1, delete_sqls.count
assert_match(/#{Regexp.escape(Sharded::BlogPost.connection.quote_table_name("sharded_blog_posts.blog_id"))} =/, delete_sqls.first) assert_match(/#{Regexp.escape(Sharded::BlogPost.lease_connection.quote_table_name("sharded_blog_posts.blog_id"))} =/, delete_sqls.first)
ensure ensure
Sharded::BlogPostDestroyAsync.delete_all Sharded::BlogPostDestroyAsync.delete_all
Sharded::CommentDestroyAsync.delete_all Sharded::CommentDestroyAsync.delete_all
@ -307,7 +307,7 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase
assert_equal 2, delete_sqls.count assert_equal 2, delete_sqls.count
delete_sqls.each do |sql| delete_sqls.each do |sql|
assert_match(/#{Regexp.escape(Sharded::Tag.connection.quote_table_name("sharded_comments.blog_id"))} =/, sql) assert_match(/#{Regexp.escape(Sharded::Tag.lease_connection.quote_table_name("sharded_comments.blog_id"))} =/, sql)
end end
ensure ensure
Sharded::CommentDestroyAsync.delete_all Sharded::CommentDestroyAsync.delete_all

@ -8,7 +8,7 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase
setup do setup do
@original_verbose = ActiveRecord::Migration.verbose @original_verbose = ActiveRecord::Migration.verbose
ActiveRecord::Migration.verbose = false ActiveRecord::Migration.verbose = false
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@pool = ActiveRecord::Base.connection_pool @pool = ActiveRecord::Base.connection_pool
@schema_migration = @pool.schema_migration @schema_migration = @pool.schema_migration
@schema_migration.delete_all_versions @schema_migration.delete_all_versions
@ -162,7 +162,7 @@ def test_timestamps_without_null_set_null_to_false_on_change_table
assert @connection.column_exists?(:has_timestamps, :updated_at, null: false) assert @connection.column_exists?(:has_timestamps, :updated_at, null: false)
end end
if ActiveRecord::Base.connection.supports_bulk_alter? if ActiveRecord::Base.lease_connection.supports_bulk_alter?
def test_timestamps_without_null_set_null_to_false_on_change_table_with_bulk def test_timestamps_without_null_set_null_to_false_on_change_table_with_bulk
ActiveRecord::Schema.define do ActiveRecord::Schema.define do
create_table :has_timestamps create_table :has_timestamps
@ -212,7 +212,7 @@ def test_timestamps_sets_precision_on_change_table
assert @connection.column_exists?(:has_timestamps, :updated_at, precision: 6, null: false) assert @connection.column_exists?(:has_timestamps, :updated_at, precision: 6, null: false)
end end
if ActiveRecord::Base.connection.supports_bulk_alter? if ActiveRecord::Base.lease_connection.supports_bulk_alter?
def test_timestamps_sets_precision_on_change_table_with_bulk def test_timestamps_sets_precision_on_change_table_with_bulk
ActiveRecord::Schema.define do ActiveRecord::Schema.define do
create_table :has_timestamps create_table :has_timestamps

@ -8,13 +8,13 @@ class ActiveRecordTest < ActiveRecord::TestCase
unless in_memory_db? unless in_memory_db?
test ".disconnect_all! closes all connections" do test ".disconnect_all! closes all connections" do
ActiveRecord::Base.connection.connect! ActiveRecord::Base.lease_connection.connect!
assert_predicate ActiveRecord::Base, :connected? assert_predicate ActiveRecord::Base, :connected?
ActiveRecord.disconnect_all! ActiveRecord.disconnect_all!
assert_not_predicate ActiveRecord::Base, :connected? assert_not_predicate ActiveRecord::Base, :connected?
ActiveRecord::Base.connection.connect! ActiveRecord::Base.lease_connection.connect!
assert_predicate ActiveRecord::Base, :connected? assert_predicate ActiveRecord::Base, :connected?
end end
end end

@ -10,7 +10,7 @@
module ActiveRecord module ActiveRecord
class AdapterPreventWritesTest < ActiveRecord::TestCase class AdapterPreventWritesTest < ActiveRecord::TestCase
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def test_preventing_writes_predicate def test_preventing_writes_predicate
@ -79,7 +79,7 @@ def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes
end end
end end
if ActiveRecord::Base.connection.supports_common_table_expressions? if ActiveRecord::Base.lease_connection.supports_common_table_expressions?
def test_doesnt_error_when_a_read_query_with_a_cte_is_called_while_preventing_writes def test_doesnt_error_when_a_read_query_with_a_cte_is_called_while_preventing_writes
@connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')") @connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')")

@ -10,14 +10,14 @@
module ActiveRecord module ActiveRecord
class AdapterTest < ActiveRecord::TestCase class AdapterTest < ActiveRecord::TestCase
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.materialize_transactions @connection.materialize_transactions
end end
## ##
# PostgreSQL does not support null bytes in strings # PostgreSQL does not support null bytes in strings
unless current_adapter?(:PostgreSQLAdapter) || unless current_adapter?(:PostgreSQLAdapter) ||
(current_adapter?(:SQLite3Adapter) && !ActiveRecord::Base.connection.prepared_statements) (current_adapter?(:SQLite3Adapter) && !ActiveRecord::Base.lease_connection.prepared_statements)
def test_update_prepared_statement def test_update_prepared_statement
b = Book.create(name: "my \x00 book") b = Book.create(name: "my \x00 book")
b.reload b.reload
@ -152,7 +152,7 @@ def test_not_specifying_database_name_for_cross_database_selects
ActiveRecord::Base.establish_connection(db_config.configuration_hash.except(:database)) ActiveRecord::Base.establish_connection(db_config.configuration_hash.except(:database))
config = ARTest.test_configuration_hashes config = ARTest.test_configuration_hashes
ActiveRecord::Base.connection.execute( ActiveRecord::Base.lease_connection.execute(
"SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \
"FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses"
) )
@ -168,11 +168,11 @@ def test_disable_prepared_statements
db_config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary") db_config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary")
ActiveRecord::Base.establish_connection(db_config.configuration_hash.merge(prepared_statements: true)) ActiveRecord::Base.establish_connection(db_config.configuration_hash.merge(prepared_statements: true))
assert_predicate ActiveRecord::Base.connection, :prepared_statements? assert_predicate ActiveRecord::Base.lease_connection, :prepared_statements?
ActiveRecord.disable_prepared_statements = true ActiveRecord.disable_prepared_statements = true
ActiveRecord::Base.establish_connection(db_config.configuration_hash.merge(prepared_statements: true)) ActiveRecord::Base.establish_connection(db_config.configuration_hash.merge(prepared_statements: true))
assert_not_predicate ActiveRecord::Base.connection, :prepared_statements? assert_not_predicate ActiveRecord::Base.lease_connection, :prepared_statements?
ensure ensure
ActiveRecord.disable_prepared_statements = original_prepared_statements ActiveRecord.disable_prepared_statements = original_prepared_statements
ActiveRecord::Base.establish_connection :arunit ActiveRecord::Base.establish_connection :arunit
@ -224,7 +224,7 @@ def test_value_limit_violations_are_translated_to_specific_exception
def test_numeric_value_out_of_ranges_are_translated_to_specific_exception def test_numeric_value_out_of_ranges_are_translated_to_specific_exception
error = assert_raises(ActiveRecord::RangeError) do error = assert_raises(ActiveRecord::RangeError) do
Book.connection.create("INSERT INTO books(author_id) VALUES (9223372036854775808)") Book.lease_connection.create("INSERT INTO books(author_id) VALUES (9223372036854775808)")
end end
assert_not_nil error.cause assert_not_nil error.cause
@ -257,7 +257,7 @@ def test_select_all_always_return_activerecord_result
assert result.is_a?(ActiveRecord::Result) assert result.is_a?(ActiveRecord::Result)
end end
if ActiveRecord::Base.connection.prepared_statements if ActiveRecord::Base.lease_connection.prepared_statements
def test_select_all_insert_update_delete_with_casted_binds def test_select_all_insert_update_delete_with_casted_binds
binds = [Event.type_for_attribute("id").serialize(1)] binds = [Event.type_for_attribute("id").serialize(1)]
bind_param = Arel::Nodes::BindParam.new(nil) bind_param = Arel::Nodes::BindParam.new(nil)
@ -329,7 +329,7 @@ class AdapterForeignKeyTest < ActiveRecord::TestCase
fixtures :fk_test_has_pk fixtures :fk_test_has_pk
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def test_foreign_key_violations_are_translated_to_specific_exception_with_validate_false def test_foreign_key_violations_are_translated_to_specific_exception_with_validate_false
@ -393,7 +393,7 @@ class AdapterTestWithoutTransaction < ActiveRecord::TestCase
fixtures :posts, :authors, :author_addresses fixtures :posts, :authors, :author_addresses
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def test_create_with_query_cache def test_create_with_query_cache
@ -464,19 +464,19 @@ def test_truncate_tables_with_query_cache
end end
# test resetting sequences in odd tables in PostgreSQL # test resetting sequences in odd tables in PostgreSQL
if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!) if ActiveRecord::Base.lease_connection.respond_to?(:reset_pk_sequence!)
require "models/movie" require "models/movie"
require "models/subscriber" require "models/subscriber"
def test_reset_empty_table_with_custom_pk def test_reset_empty_table_with_custom_pk
Movie.delete_all Movie.delete_all
Movie.connection.reset_pk_sequence! "movies" Movie.lease_connection.reset_pk_sequence! "movies"
assert_equal 1, Movie.create(name: "fight club").id assert_equal 1, Movie.create(name: "fight club").id
end end
def test_reset_table_with_non_integer_pk def test_reset_table_with_non_integer_pk
Subscriber.delete_all Subscriber.delete_all
Subscriber.connection.reset_pk_sequence! "subscribers" Subscriber.lease_connection.reset_pk_sequence! "subscribers"
sub = Subscriber.new(name: "robert drake") sub = Subscriber.new(name: "robert drake")
sub.id = "bob drake" sub.id = "bob drake"
assert_nothing_raised { sub.save! } assert_nothing_raised { sub.save! }
@ -500,7 +500,7 @@ class AdapterConnectionTest < ActiveRecord::TestCase
fixtures :posts, :authors, :author_addresses fixtures :posts, :authors, :author_addresses
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
assert_predicate @connection, :active? assert_predicate @connection, :active?
end end
@ -620,7 +620,7 @@ def teardown
# Quote string will not verify a broken connection (although it may # Quote string will not verify a broken connection (although it may
# reconnect in some cases) # reconnect in some cases)
Post.connection.quote_string("") Post.lease_connection.quote_string("")
# Because the connection hasn't been verified since checkout, # Because the connection hasn't been verified since checkout,
# and the query cannot safely be retried, the connection will be # and the query cannot safely be retried, the connection will be
@ -853,35 +853,35 @@ def threads(count, times)
end end
end end
if ActiveRecord::Base.connection.supports_advisory_locks? if ActiveRecord::Base.lease_connection.supports_advisory_locks?
class AdvisoryLocksEnabledTest < ActiveRecord::TestCase class AdvisoryLocksEnabledTest < ActiveRecord::TestCase
include ConnectionHelper include ConnectionHelper
def test_advisory_locks_enabled? def test_advisory_locks_enabled?
assert_predicate ActiveRecord::Base.connection, :advisory_locks_enabled? assert_predicate ActiveRecord::Base.lease_connection, :advisory_locks_enabled?
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection( ActiveRecord::Base.establish_connection(
orig_connection.merge(advisory_locks: false) orig_connection.merge(advisory_locks: false)
) )
assert_not ActiveRecord::Base.connection.advisory_locks_enabled? assert_not ActiveRecord::Base.lease_connection.advisory_locks_enabled?
ActiveRecord::Base.establish_connection( ActiveRecord::Base.establish_connection(
orig_connection.merge(advisory_locks: true) orig_connection.merge(advisory_locks: true)
) )
assert_predicate ActiveRecord::Base.connection, :advisory_locks_enabled? assert_predicate ActiveRecord::Base.lease_connection, :advisory_locks_enabled?
end end
end end
end end
end end
if ActiveRecord::Base.connection.savepoint_errors_invalidate_transactions? if ActiveRecord::Base.lease_connection.savepoint_errors_invalidate_transactions?
class InvalidateTransactionTest < ActiveRecord::TestCase class InvalidateTransactionTest < ActiveRecord::TestCase
def test_invalidates_transaction_on_rollback_error def test_invalidates_transaction_on_rollback_error
@invalidated = false @invalidated = false
connection = ActiveRecord::Base.connection connection = ActiveRecord::Base.lease_connection
connection.transaction do connection.transaction do
connection.send(:with_raw_connection) do connection.send(:with_raw_connection) do

@ -7,8 +7,8 @@ class ActiveSchemaTest < ActiveRecord::AbstractMysqlTestCase
include ConnectionHelper include ConnectionHelper
def setup def setup
ActiveRecord::Base.connection.send(:default_row_format) ActiveRecord::Base.lease_connection.send(:default_row_format)
ActiveRecord::Base.connection.singleton_class.class_eval do ActiveRecord::Base.lease_connection.singleton_class.class_eval do
alias_method :execute_without_stub, :execute alias_method :execute_without_stub, :execute
def execute(sql, name = nil) def execute(sql, name = nil)
ActiveSupport::Notifications.instrumenter.instrument( ActiveSupport::Notifications.instrumenter.instrument(
@ -83,14 +83,14 @@ def test_add_index
def test_index_in_create def test_index_in_create
%w(SPATIAL FULLTEXT UNIQUE).each do |type| %w(SPATIAL FULLTEXT UNIQUE).each do |type|
expected = /\ACREATE TABLE `people` \(#{type} INDEX `index_people_on_last_name` \(`last_name`\)\)/ expected = /\ACREATE TABLE `people` \(#{type} INDEX `index_people_on_last_name` \(`last_name`\)\)/
actual = ActiveRecord::Base.connection.create_table(:people, id: false) do |t| actual = ActiveRecord::Base.lease_connection.create_table(:people, id: false) do |t|
t.index :last_name, type: type t.index :last_name, type: type
end end
assert_match expected, actual assert_match expected, actual
end end
expected = /\ACREATE TABLE `people` \(INDEX `index_people_on_last_name` USING btree \(`last_name`\(10\)\)\)/ expected = /\ACREATE TABLE `people` \(INDEX `index_people_on_last_name` USING btree \(`last_name`\(10\)\)\)/
actual = ActiveRecord::Base.connection.create_table(:people, id: false) do |t| actual = ActiveRecord::Base.lease_connection.create_table(:people, id: false) do |t|
t.index :last_name, length: 10, using: :btree t.index :last_name, length: 10, using: :btree
end end
assert_match expected, actual assert_match expected, actual
@ -100,7 +100,7 @@ def test_index_in_bulk_change
%w(SPATIAL FULLTEXT UNIQUE).each do |type| %w(SPATIAL FULLTEXT UNIQUE).each do |type|
expected = "ALTER TABLE `people` ADD #{type} INDEX `index_people_on_last_name` (`last_name`)" expected = "ALTER TABLE `people` ADD #{type} INDEX `index_people_on_last_name` (`last_name`)"
assert_queries_match(expected) do assert_queries_match(expected) do
ActiveRecord::Base.connection.change_table(:people, bulk: true) do |t| ActiveRecord::Base.lease_connection.change_table(:people, bulk: true) do |t|
t.index :last_name, type: type t.index :last_name, type: type
end end
end end
@ -108,7 +108,7 @@ def test_index_in_bulk_change
expected = "ALTER TABLE `people` ADD INDEX `index_people_on_last_name` USING btree (`last_name`(10)), ALGORITHM = COPY" expected = "ALTER TABLE `people` ADD INDEX `index_people_on_last_name` USING btree (`last_name`(10)), ALGORITHM = COPY"
assert_queries_match(expected) do assert_queries_match(expected) do
ActiveRecord::Base.connection.change_table(:people, bulk: true) do |t| ActiveRecord::Base.lease_connection.change_table(:people, bulk: true) do |t|
t.index :last_name, length: 10, using: :btree, algorithm: :copy t.index :last_name, length: 10, using: :btree, algorithm: :copy
end end
end end
@ -119,7 +119,7 @@ def test_drop_table
end end
def test_create_mysql_database_with_encoding def test_create_mysql_database_with_encoding
if ActiveRecord::Base.connection.send(:row_format_dynamic_by_default?) if ActiveRecord::Base.lease_connection.send(:row_format_dynamic_by_default?)
assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8mb4`", create_database(:matt) assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8mb4`", create_database(:matt)
else else
error = assert_raises(RuntimeError) { create_database(:matt) } error = assert_raises(RuntimeError) { create_database(:matt) }
@ -149,31 +149,31 @@ def test_drop_table_with_specific_database
def test_add_timestamps def test_add_timestamps
with_real_execute do with_real_execute do
ActiveRecord::Base.connection.create_table :delete_me ActiveRecord::Base.lease_connection.create_table :delete_me
ActiveRecord::Base.connection.add_timestamps :delete_me, null: true ActiveRecord::Base.lease_connection.add_timestamps :delete_me, null: true
assert column_exists?("delete_me", "updated_at", "datetime") assert column_exists?("delete_me", "updated_at", "datetime")
assert column_exists?("delete_me", "created_at", "datetime") assert column_exists?("delete_me", "created_at", "datetime")
ensure ensure
ActiveRecord::Base.connection.drop_table :delete_me rescue nil ActiveRecord::Base.lease_connection.drop_table :delete_me rescue nil
end end
end end
def test_remove_timestamps def test_remove_timestamps
with_real_execute do with_real_execute do
ActiveRecord::Base.connection.create_table :delete_me do |t| ActiveRecord::Base.lease_connection.create_table :delete_me do |t|
t.timestamps null: true t.timestamps null: true
end end
ActiveRecord::Base.connection.remove_timestamps :delete_me, null: true ActiveRecord::Base.lease_connection.remove_timestamps :delete_me, null: true
assert_not column_exists?("delete_me", "updated_at", "datetime") assert_not column_exists?("delete_me", "updated_at", "datetime")
assert_not column_exists?("delete_me", "created_at", "datetime") assert_not column_exists?("delete_me", "created_at", "datetime")
ensure ensure
ActiveRecord::Base.connection.drop_table :delete_me rescue nil ActiveRecord::Base.lease_connection.drop_table :delete_me rescue nil
end end
end end
def test_indexes_in_create def test_indexes_in_create
expected = /\ACREATE TEMPORARY TABLE `temp` \(INDEX `index_temp_on_zip` \(`zip`\)\)(?: ROW_FORMAT=DYNAMIC)? AS SELECT id, name, zip FROM a_really_complicated_query/ expected = /\ACREATE TEMPORARY TABLE `temp` \(INDEX `index_temp_on_zip` \(`zip`\)\)(?: ROW_FORMAT=DYNAMIC)? AS SELECT id, name, zip FROM a_really_complicated_query/
actual = ActiveRecord::Base.connection.create_table(:temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query") do |t| actual = ActiveRecord::Base.lease_connection.create_table(:temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query") do |t|
t.index :zip t.index :zip
end end
@ -182,7 +182,7 @@ def test_indexes_in_create
private private
def with_real_execute def with_real_execute
ActiveRecord::Base.connection.singleton_class.class_eval do ActiveRecord::Base.lease_connection.singleton_class.class_eval do
alias_method :execute_with_stub, :execute alias_method :execute_with_stub, :execute
remove_method :execute remove_method :execute
alias_method :execute, :execute_without_stub alias_method :execute, :execute_without_stub
@ -190,13 +190,13 @@ def with_real_execute
yield yield
ensure ensure
ActiveRecord::Base.connection.singleton_class.class_eval do ActiveRecord::Base.lease_connection.singleton_class.class_eval do
remove_method :execute remove_method :execute
alias_method :execute, :execute_with_stub alias_method :execute, :execute_with_stub
end end
end end
def method_missing(...) def method_missing(...)
ActiveRecord::Base.connection.public_send(...) ActiveRecord::Base.lease_connection.public_send(...)
end end
end end

@ -7,7 +7,7 @@ class AdapterPreventWritesTest < ActiveRecord::AbstractMysqlTestCase
include DdlHelper include DdlHelper
def setup def setup
@conn = ActiveRecord::Base.connection @conn = ActiveRecord::Base.lease_connection
end end
def test_errors_when_an_insert_query_is_called_while_preventing_writes def test_errors_when_an_insert_query_is_called_while_preventing_writes

@ -7,7 +7,7 @@ class AutoIncrementTest < ActiveRecord::AbstractMysqlTestCase
include SchemaDumpingHelper include SchemaDumpingHelper
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def teardown def teardown

@ -7,7 +7,7 @@ class CharsetCollationTest < ActiveRecord::AbstractMysqlTestCase
include SchemaDumpingHelper include SchemaDumpingHelper
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table :charset_collations, id: { type: :string, collation: "utf8mb4_bin" }, force: true do |t| @connection.create_table :charset_collations, id: { type: :string, collation: "utf8mb4_bin" }, force: true do |t|
t.string :string_ascii_bin, charset: "ascii", collation: "ascii_bin" t.string :string_ascii_bin, charset: "ascii", collation: "ascii_bin"
t.text :text_ucs2_unicode_ci, charset: "ucs2", collation: "ucs2_unicode_ci" t.text :text_ucs2_unicode_ci, charset: "ucs2", collation: "ucs2_unicode_ci"

@ -10,7 +10,7 @@ def setup
super super
@subscriber = SQLSubscriber.new @subscriber = SQLSubscriber.new
@subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def teardown def teardown
@ -37,7 +37,7 @@ def test_no_automatic_reconnection_after_timeout
assert_not_predicate @connection, :active? assert_not_predicate @connection, :active?
ensure ensure
# Repair all fixture connections so other tests won't break. # Repair all fixture connections so other tests won't break.
@fixture_connection_pools.each { |p| p.connection.verify! } @fixture_connection_pools.each { |p| p.lease_connection.verify! }
end end
def test_successful_reconnection_after_timeout_with_manual_reconnect def test_successful_reconnection_after_timeout_with_manual_reconnect
@ -74,7 +74,7 @@ def test_active_after_disconnect
def test_wait_timeout_as_string def test_wait_timeout_as_string
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge(wait_timeout: "60")) ActiveRecord::Base.establish_connection(orig_connection.merge(wait_timeout: "60"))
result = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.wait_timeout") result = ActiveRecord::Base.lease_connection.select_value("SELECT @@SESSION.wait_timeout")
assert_equal 60, result assert_equal 60, result
end end
end end
@ -82,7 +82,7 @@ def test_wait_timeout_as_string
def test_wait_timeout_as_url def test_wait_timeout_as_url
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge("url" => "#{orig_connection[:adapter]}:///?wait_timeout=60")) ActiveRecord::Base.establish_connection(orig_connection.merge("url" => "#{orig_connection[:adapter]}:///?wait_timeout=60"))
result = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.wait_timeout") result = ActiveRecord::Base.lease_connection.select_value("SELECT @@SESSION.wait_timeout")
assert_equal 60, result assert_equal 60, result
end end
end end
@ -91,7 +91,7 @@ def test_character_set_connection_is_configured
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
configuration_hash = orig_connection.except(:encoding, :collation) configuration_hash = orig_connection.except(:encoding, :collation)
ActiveRecord::Base.establish_connection(configuration_hash.merge!(encoding: "cp932")) ActiveRecord::Base.establish_connection(configuration_hash.merge!(encoding: "cp932"))
connection = ActiveRecord::Base.connection connection = ActiveRecord::Base.lease_connection
assert_equal "cp932", connection.show_variable("character_set_client") assert_equal "cp932", connection.show_variable("character_set_client")
assert_equal "cp932", connection.show_variable("character_set_results") assert_equal "cp932", connection.show_variable("character_set_results")
@ -107,8 +107,8 @@ def test_collation_connection_is_configured
assert_equal "utf8mb4_unicode_ci", @connection.show_variable("collation_connection") assert_equal "utf8mb4_unicode_ci", @connection.show_variable("collation_connection")
assert_equal 1, @connection.query_value("SELECT 'こんにちは' = 'コンニチハ'") assert_equal 1, @connection.query_value("SELECT 'こんにちは' = 'コンニチハ'")
assert_equal "utf8mb4_general_ci", ARUnit2Model.connection.show_variable("collation_connection") assert_equal "utf8mb4_general_ci", ARUnit2Model.lease_connection.show_variable("collation_connection")
assert_equal 0, ARUnit2Model.connection.query_value("SELECT 'こんにちは' = 'コンニチハ'") assert_equal 0, ARUnit2Model.lease_connection.query_value("SELECT 'こんにちは' = 'コンニチハ'")
end end
def test_mysql_default_in_strict_mode def test_mysql_default_in_strict_mode
@ -119,7 +119,7 @@ def test_mysql_default_in_strict_mode
def test_mysql_strict_mode_disabled def test_mysql_strict_mode_disabled
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge(strict: false)) ActiveRecord::Base.establish_connection(orig_connection.merge(strict: false))
result = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.sql_mode") result = ActiveRecord::Base.lease_connection.select_value("SELECT @@SESSION.sql_mode")
assert_no_match %r(STRICT_ALL_TABLES), result assert_no_match %r(STRICT_ALL_TABLES), result
end end
end end
@ -127,8 +127,8 @@ def test_mysql_strict_mode_disabled
def test_mysql_strict_mode_specified_default def test_mysql_strict_mode_specified_default
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge(strict: :default)) ActiveRecord::Base.establish_connection(orig_connection.merge(strict: :default))
global_sql_mode = ActiveRecord::Base.connection.select_value("SELECT @@GLOBAL.sql_mode") global_sql_mode = ActiveRecord::Base.lease_connection.select_value("SELECT @@GLOBAL.sql_mode")
session_sql_mode = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.sql_mode") session_sql_mode = ActiveRecord::Base.lease_connection.select_value("SELECT @@SESSION.sql_mode")
assert_equal global_sql_mode, session_sql_mode assert_equal global_sql_mode, session_sql_mode
end end
end end
@ -136,7 +136,7 @@ def test_mysql_strict_mode_specified_default
def test_mysql_sql_mode_variable_overrides_strict_mode def test_mysql_sql_mode_variable_overrides_strict_mode
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { "sql_mode" => "ansi" })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { "sql_mode" => "ansi" }))
result = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.sql_mode") result = ActiveRecord::Base.lease_connection.select_value("SELECT @@SESSION.sql_mode")
assert_no_match %r(STRICT_ALL_TABLES), result assert_no_match %r(STRICT_ALL_TABLES), result
end end
end end
@ -145,14 +145,14 @@ def test_mysql_sql_mode_variable_overrides_strict_mode
def test_passing_arbitrary_flags_to_adapter def test_passing_arbitrary_flags_to_adapter
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge(flags: Mysql2::Client::COMPRESS)) ActiveRecord::Base.establish_connection(orig_connection.merge(flags: Mysql2::Client::COMPRESS))
assert_equal (Mysql2::Client::COMPRESS | Mysql2::Client::FOUND_ROWS), ActiveRecord::Base.connection.raw_connection.query_options[:flags] assert_equal (Mysql2::Client::COMPRESS | Mysql2::Client::FOUND_ROWS), ActiveRecord::Base.lease_connection.raw_connection.query_options[:flags]
end end
end end
def test_passing_flags_by_array_to_adapter def test_passing_flags_by_array_to_adapter
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge(flags: ["COMPRESS"])) ActiveRecord::Base.establish_connection(orig_connection.merge(flags: ["COMPRESS"]))
assert_equal ["COMPRESS", "FOUND_ROWS"], ActiveRecord::Base.connection.raw_connection.query_options[:flags] assert_equal ["COMPRESS", "FOUND_ROWS"], ActiveRecord::Base.lease_connection.raw_connection.query_options[:flags]
end end
end end
end end
@ -160,7 +160,7 @@ def test_passing_flags_by_array_to_adapter
def test_mysql_set_session_variable def test_mysql_set_session_variable
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: 3 })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: 3 }))
session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" session_mode = ActiveRecord::Base.lease_connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
assert_equal 3, session_mode.rows.first.first.to_i assert_equal 3, session_mode.rows.first.first.to_i
end end
end end
@ -168,14 +168,14 @@ def test_mysql_set_session_variable
def test_mysql_set_session_variable_to_default def test_mysql_set_session_variable_to_default
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: :default })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: :default }))
global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT" global_mode = ActiveRecord::Base.lease_connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT"
session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" session_mode = ActiveRecord::Base.lease_connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
assert_equal global_mode.rows, session_mode.rows assert_equal global_mode.rows, session_mode.rows
end end
end end
def test_logs_name_show_variable def test_logs_name_show_variable
ActiveRecord::Base.connection.materialize_transactions ActiveRecord::Base.lease_connection.materialize_transactions
@subscriber.logged.clear @subscriber.logged.clear
@connection.show_variable "foo" @connection.show_variable "foo"
assert_equal "SCHEMA", @subscriber.logged[0][1] assert_equal "SCHEMA", @subscriber.logged[0][1]

@ -4,7 +4,7 @@
class DatetimePrecisionQuotingTest < ActiveRecord::AbstractMysqlTestCase class DatetimePrecisionQuotingTest < ActiveRecord::AbstractMysqlTestCase
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
test "microsecond precision for MySQL gte 5.6.4" do test "microsecond precision for MySQL gte 5.6.4" do

@ -3,7 +3,7 @@
require "cases/helper" require "cases/helper"
require "cases/json_shared_test_cases" require "cases/json_shared_test_cases"
if ActiveRecord::Base.connection.supports_json? if ActiveRecord::Base.lease_connection.supports_json?
class JSONTest < ActiveRecord::AbstractMysqlTestCase class JSONTest < ActiveRecord::AbstractMysqlTestCase
include JSONSharedTestCases include JSONSharedTestCases
self.use_transactional_tests = false self.use_transactional_tests = false

@ -10,7 +10,7 @@ class BooleanType < ActiveRecord::Base
end end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.clear_cache! @connection.clear_cache!
@connection.create_table("mysql_booleans") do |t| @connection.create_table("mysql_booleans") do |t|
t.boolean "archived" t.boolean "archived"

@ -19,7 +19,7 @@ class EnumTest < ActiveRecord::Base
end end
def setup def setup
EnumTest.connection.create_table :enum_tests, id: false, force: true do |t| EnumTest.lease_connection.create_table :enum_tests, id: false, force: true do |t|
t.column :enum_column, "enum('text','blob','tiny','medium','long','unsigned','bigint')" t.column :enum_column, "enum('text','blob','tiny','medium','long','unsigned','bigint')"
t.column :state, "TINYINT(1)" t.column :state, "TINYINT(1)"
end end

@ -66,6 +66,6 @@ def supports_analyze?
end end
def conn def conn
ActiveRecord::Base.connection ActiveRecord::Base.lease_connection
end end
end end

@ -15,7 +15,7 @@ class Sample < ActiveRecord::Base
@abort, Thread.abort_on_exception = Thread.abort_on_exception, false @abort, Thread.abort_on_exception = Thread.abort_on_exception, false
Thread.report_on_exception, @original_report_on_exception = false, Thread.report_on_exception Thread.report_on_exception, @original_report_on_exception = false, Thread.report_on_exception
connection = ActiveRecord::Base.connection connection = ActiveRecord::Base.lease_connection
connection.clear_cache! connection.clear_cache!
connection.create_table("samples", force: true) do |t| connection.create_table("samples", force: true) do |t|
@ -27,14 +27,14 @@ class Sample < ActiveRecord::Base
teardown do teardown do
ActiveRecord::Base.connection_handler.clear_active_connections!(:all) ActiveRecord::Base.connection_handler.clear_active_connections!(:all)
ActiveRecord::Base.connection.drop_table "samples", if_exists: true ActiveRecord::Base.lease_connection.drop_table "samples", if_exists: true
Thread.abort_on_exception = @abort Thread.abort_on_exception = @abort
Thread.report_on_exception = @original_report_on_exception Thread.report_on_exception = @original_report_on_exception
end end
test "deadlock correctly raises Deadlocked inside nested SavepointTransaction" do test "deadlock correctly raises Deadlocked inside nested SavepointTransaction" do
connection = Sample.connection connection = Sample.lease_connection
assert_raises(ActiveRecord::Deadlocked) do assert_raises(ActiveRecord::Deadlocked) do
barrier = Concurrent::CyclicBarrier.new(2) barrier = Concurrent::CyclicBarrier.new(2)
@ -182,7 +182,7 @@ def make_parent_transaction_dirty
end end
def assert_current_transaction_is_savepoint_transaction def assert_current_transaction_is_savepoint_transaction
current_transaction = Sample.connection.current_transaction current_transaction = Sample.lease_connection.current_transaction
unless current_transaction.is_a?(ActiveRecord::ConnectionAdapters::SavepointTransaction) unless current_transaction.is_a?(ActiveRecord::ConnectionAdapters::SavepointTransaction)
flunk("current transaction is not a savepoint transaction") flunk("current transaction is not a savepoint transaction")
end end

@ -5,7 +5,7 @@
class QuotingTest < ActiveRecord::AbstractMysqlTestCase class QuotingTest < ActiveRecord::AbstractMysqlTestCase
def setup def setup
super super
@conn = ActiveRecord::Base.connection @conn = ActiveRecord::Base.lease_connection
end end
def test_cast_bound_integer def test_cast_bound_integer

@ -59,7 +59,7 @@ def with_encoding_utf8mb4
end end
def connection def connection
@connection ||= ActiveRecord::Base.connection @connection ||= ActiveRecord::Base.lease_connection
end end
def execute(sql) def execute(sql)

@ -10,7 +10,7 @@ class SchemaTest < ActiveRecord::AbstractMysqlTestCase
fixtures :posts fixtures :posts
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
db = Post.connection_pool.db_config.database db = Post.connection_pool.db_config.database
table = Post.table_name table = Post.table_name
@db_name = db @db_name = db
@ -108,7 +108,7 @@ def test_drop_temporary_table
class MysqlAnsiQuotesTest < ActiveRecord::AbstractMysqlTestCase class MysqlAnsiQuotesTest < ActiveRecord::AbstractMysqlTestCase
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.execute("SET SESSION sql_mode='ANSI_QUOTES'") @connection.execute("SET SESSION sql_mode='ANSI_QUOTES'")
end end

@ -10,7 +10,7 @@ class SetTest < ActiveRecord::Base
end end
def setup def setup
SetTest.connection.create_table :set_tests, id: false, force: true do |t| SetTest.lease_connection.create_table :set_tests, id: false, force: true do |t|
t.column :set_column, "set('text','blob','tiny','medium','long','unsigned','bigint')" t.column :set_column, "set('text','blob','tiny','medium','long','unsigned','bigint')"
end end
end end

@ -8,8 +8,8 @@ class StoredProcedureTest < ActiveRecord::AbstractMysqlTestCase
fixtures :topics fixtures :topics
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
unless ActiveRecord::Base.connection.database_version >= "5.6.0" unless ActiveRecord::Base.lease_connection.database_version >= "5.6.0"
skip("no stored procedure support") skip("no stored procedure support")
end end
end end

@ -11,6 +11,6 @@ def test_binary_types
end end
def type_to_sql(type, limit = nil) def type_to_sql(type, limit = nil)
ActiveRecord::Base.connection.type_to_sql(type, limit: limit) ActiveRecord::Base.lease_connection.type_to_sql(type, limit: limit)
end end
end end

@ -7,7 +7,7 @@ class TableOptionsTest < ActiveRecord::AbstractMysqlTestCase
include SchemaDumpingHelper include SchemaDumpingHelper
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def teardown def teardown
@ -92,12 +92,12 @@ def setup
def teardown def teardown
ActiveRecord::Base.logger = @logger_was ActiveRecord::Base.logger = @logger_was
ActiveRecord::Migration.verbose = @verbose_was ActiveRecord::Migration.verbose = @verbose_was
ActiveRecord::Base.connection.drop_table "mysql_table_options", if_exists: true ActiveRecord::Base.lease_connection.drop_table "mysql_table_options", if_exists: true
ActiveRecord::Base.connection_pool.schema_migration.delete_all_versions rescue nil ActiveRecord::Base.connection_pool.schema_migration.delete_all_versions rescue nil
end end
test "new migrations do not contain default ENGINE=InnoDB option" do test "new migrations do not contain default ENGINE=InnoDB option" do
ActiveRecord::Base.connection.create_table "mysql_table_options", force: true ActiveRecord::Base.lease_connection.create_table "mysql_table_options", force: true
assert_no_match %r{ENGINE=InnoDB}, @log.string assert_no_match %r{ENGINE=InnoDB}, @log.string

@ -15,7 +15,7 @@ class Sample < ActiveRecord::Base
@abort, Thread.abort_on_exception = Thread.abort_on_exception, false @abort, Thread.abort_on_exception = Thread.abort_on_exception, false
Thread.report_on_exception, @original_report_on_exception = false, Thread.report_on_exception Thread.report_on_exception, @original_report_on_exception = false, Thread.report_on_exception
connection = ActiveRecord::Base.connection connection = ActiveRecord::Base.lease_connection
connection.clear_cache! connection.clear_cache!
connection.transaction do connection.transaction do
@ -29,14 +29,14 @@ class Sample < ActiveRecord::Base
end end
teardown do teardown do
ActiveRecord::Base.connection.drop_table "samples", if_exists: true ActiveRecord::Base.lease_connection.drop_table "samples", if_exists: true
Thread.abort_on_exception = @abort Thread.abort_on_exception = @abort
Thread.report_on_exception = @original_report_on_exception Thread.report_on_exception = @original_report_on_exception
end end
test "raises Deadlocked when a deadlock is encountered" do test "raises Deadlocked when a deadlock is encountered" do
connection = Sample.connection connection = Sample.lease_connection
assert_raises(ActiveRecord::Deadlocked) do assert_raises(ActiveRecord::Deadlocked) do
barrier = Concurrent::CyclicBarrier.new(2) barrier = Concurrent::CyclicBarrier.new(2)
@ -81,11 +81,11 @@ class Sample < ActiveRecord::Base
begin begin
Sample.transaction do Sample.transaction do
latch1.wait latch1.wait
Sample.connection.execute("SET innodb_lock_wait_timeout = 1") Sample.lease_connection.execute("SET innodb_lock_wait_timeout = 1")
Sample.lock.find(s.id) Sample.lock.find(s.id)
end end
ensure ensure
Sample.connection.execute("SET innodb_lock_wait_timeout = DEFAULT") Sample.lease_connection.execute("SET innodb_lock_wait_timeout = DEFAULT")
latch2.count_down latch2.count_down
thread.join thread.join
end end
@ -93,7 +93,7 @@ class Sample < ActiveRecord::Base
end end
test "raises StatementTimeout when statement timeout exceeded" do test "raises StatementTimeout when statement timeout exceeded" do
skip unless ActiveRecord::Base.connection.show_variable("max_execution_time") skip unless ActiveRecord::Base.lease_connection.show_variable("max_execution_time")
error = assert_raises(ActiveRecord::StatementTimeout) do error = assert_raises(ActiveRecord::StatementTimeout) do
s = Sample.create!(value: 1) s = Sample.create!(value: 1)
latch1 = Concurrent::CountDownLatch.new latch1 = Concurrent::CountDownLatch.new
@ -110,11 +110,11 @@ class Sample < ActiveRecord::Base
begin begin
Sample.transaction do Sample.transaction do
latch1.wait latch1.wait
Sample.connection.execute("SET max_execution_time = 1") Sample.lease_connection.execute("SET max_execution_time = 1")
Sample.lock.find(s.id) Sample.lock.find(s.id)
end end
ensure ensure
Sample.connection.execute("SET max_execution_time = DEFAULT") Sample.lease_connection.execute("SET max_execution_time = DEFAULT")
latch2.count_down latch2.count_down
thread.join thread.join
end end
@ -132,7 +132,7 @@ class Sample < ActiveRecord::Base
Sample.lock.find(s.id) Sample.lock.find(s.id)
latch.count_down latch.count_down
sleep(0.5) sleep(0.5)
conn = Sample.connection conn = Sample.lease_connection
pid = conn.query_value("SELECT id FROM information_schema.processlist WHERE info LIKE '% FOR UPDATE'") pid = conn.query_value("SELECT id FROM information_schema.processlist WHERE info LIKE '% FOR UPDATE'")
conn.execute("KILL QUERY #{pid}") conn.execute("KILL QUERY #{pid}")
end end

@ -11,7 +11,7 @@ class UnsignedType < ActiveRecord::Base
end end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("unsigned_types", force: true) do |t| @connection.create_table("unsigned_types", force: true) do |t|
t.integer :unsigned_integer, unsigned: true t.integer :unsigned_integer, unsigned: true
t.bigint :unsigned_bigint, unsigned: true t.bigint :unsigned_bigint, unsigned: true

@ -3,7 +3,7 @@
require "cases/helper" require "cases/helper"
require "support/schema_dumping_helper" require "support/schema_dumping_helper"
if ActiveRecord::Base.connection.supports_virtual_columns? if ActiveRecord::Base.lease_connection.supports_virtual_columns?
class VirtualColumnTest < ActiveRecord::AbstractMysqlTestCase class VirtualColumnTest < ActiveRecord::AbstractMysqlTestCase
include SchemaDumpingHelper include SchemaDumpingHelper
@ -13,7 +13,7 @@ class VirtualColumn < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table :virtual_columns, force: true do |t| @connection.create_table :virtual_columns, force: true do |t|
t.string :name t.string :name
t.virtual :upper_name, type: :string, as: "UPPER(`name`)" t.virtual :upper_name, type: :string, as: "UPPER(`name`)"

@ -5,7 +5,7 @@
class WarningsTest < ActiveRecord::AbstractMysqlTestCase class WarningsTest < ActiveRecord::AbstractMysqlTestCase
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@original_db_warnings_action = :ignore @original_db_warnings_action = :ignore
end end

@ -3,12 +3,12 @@
require "cases/helper" require "cases/helper"
require "support/schema_dumping_helper" require "support/schema_dumping_helper"
if ActiveRecord::Base.connection.supports_check_constraints? if ActiveRecord::Base.lease_connection.supports_check_constraints?
class Mysql2CheckConstraintQuotingTest < ActiveRecord::Mysql2TestCase class Mysql2CheckConstraintQuotingTest < ActiveRecord::Mysql2TestCase
include SchemaDumpingHelper include SchemaDumpingHelper
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table "trades", force: true do |t| @connection.create_table "trades", force: true do |t|
t.string :name t.string :name
end end
@ -25,7 +25,7 @@ def test_check_constraint_no_duplicate_expression_quoting
assert_equal 1, check_constraints.size assert_equal 1, check_constraints.size
expression = check_constraints.first.expression expression = check_constraints.first.expression
if ActiveRecord::Base.connection.mariadb? if ActiveRecord::Base.lease_connection.mariadb?
assert_equal "`name` <> 'forbidden_string'", expression assert_equal "`name` <> 'forbidden_string'", expression
else else
assert_equal "`name` <> _utf8mb4'forbidden_string'", expression assert_equal "`name` <> _utf8mb4'forbidden_string'", expression

@ -7,7 +7,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase
include DdlHelper include DdlHelper
def setup def setup
@conn = ActiveRecord::Base.connection @conn = ActiveRecord::Base.lease_connection
@original_db_warnings_action = :ignore @original_db_warnings_action = :ignore
end end
@ -265,7 +265,7 @@ def test_read_timeout_exception
ActiveRecord::Base.establish_connection( ActiveRecord::Base.establish_connection(
db_config.configuration_hash.merge("read_timeout" => 1) db_config.configuration_hash.merge("read_timeout" => 1)
) )
connection = ActiveRecord::Base.connection connection = ActiveRecord::Base.lease_connection
error = assert_raises(ActiveRecord::AdapterTimeout) do error = assert_raises(ActiveRecord::AdapterTimeout) do
connection.execute("SELECT SLEEP(2)") connection.execute("SELECT SLEEP(2)")

@ -29,7 +29,7 @@ def test_establishes_connection_without_database
mock.expect(:call, nil, [adapter: "mysql2", database: nil]) mock.expect(:call, nil, [adapter: "mysql2", database: nil])
mock.expect(:call, nil, [db_config]) mock.expect(:call, nil, [db_config])
ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:lease_connection, @connection) do
ActiveRecord::Base.stub(:establish_connection, mock) do ActiveRecord::Base.stub(:establish_connection, mock) do
ActiveRecord::Tasks::DatabaseTasks.create(db_config) ActiveRecord::Tasks::DatabaseTasks.create(db_config)
end end
@ -76,7 +76,7 @@ def test_when_database_created_successfully_outputs_info_to_stdout
def test_create_when_database_exists_outputs_info_to_stderr def test_create_when_database_exists_outputs_info_to_stderr
with_stubbed_connection_establish_connection do with_stubbed_connection_establish_connection do
ActiveRecord::Base.connection.stub( ActiveRecord::Base.lease_connection.stub(
:create_database, :create_database,
proc { raise ActiveRecord::DatabaseAlreadyExists } proc { raise ActiveRecord::DatabaseAlreadyExists }
) do ) do
@ -90,7 +90,7 @@ def test_create_when_database_exists_outputs_info_to_stderr
private private
def with_stubbed_connection_establish_connection(&block) def with_stubbed_connection_establish_connection(&block)
ActiveRecord::Base.stub(:establish_connection, nil) do ActiveRecord::Base.stub(:establish_connection, nil) do
ActiveRecord::Base.stub(:connection, @connection, &block) ActiveRecord::Base.stub(:lease_connection, @connection, &block)
end end
end end
end end
@ -139,7 +139,7 @@ def teardown
def test_establishes_connection_to_mysql_database def test_establishes_connection_to_mysql_database
db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("default_env", "primary", @configuration) db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("default_env", "primary", @configuration)
ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:lease_connection, @connection) do
assert_called_with( assert_called_with(
ActiveRecord::Base, ActiveRecord::Base,
:establish_connection, :establish_connection,
@ -169,7 +169,7 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout
private private
def with_stubbed_connection_establish_connection(&block) def with_stubbed_connection_establish_connection(&block)
ActiveRecord::Base.stub(:establish_connection, nil) do ActiveRecord::Base.stub(:establish_connection, nil) do
ActiveRecord::Base.stub(:connection, @connection, &block) ActiveRecord::Base.stub(:lease_connection, @connection, &block)
end end
end end
end end
@ -186,7 +186,7 @@ def setup
def test_establishes_connection_without_database def test_establishes_connection_without_database
db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("default_env", "primary", @configuration) db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("default_env", "primary", @configuration)
ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:lease_connection, @connection) do
assert_called(ActiveRecord::Base, :establish_connection, times: 2) do assert_called(ActiveRecord::Base, :establish_connection, times: 2) do
ActiveRecord::Tasks::DatabaseTasks.purge(db_config) ActiveRecord::Tasks::DatabaseTasks.purge(db_config)
end end
@ -217,7 +217,7 @@ def test_recreates_database_with_the_given_options
private private
def with_stubbed_connection_establish_connection(&block) def with_stubbed_connection_establish_connection(&block)
ActiveRecord::Base.stub(:establish_connection, nil) do ActiveRecord::Base.stub(:establish_connection, nil) do
ActiveRecord::Base.stub(:connection, @connection, &block) ActiveRecord::Base.stub(:lease_connection, @connection, &block)
end end
end end
end end
@ -232,7 +232,7 @@ def setup
end end
def test_db_retrieves_charset def test_db_retrieves_charset
ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:lease_connection, @connection) do
assert_called(@connection, :charset) do assert_called(@connection, :charset) do
ActiveRecord::Tasks::DatabaseTasks.charset @configuration ActiveRecord::Tasks::DatabaseTasks.charset @configuration
end end
@ -250,7 +250,7 @@ def setup
end end
def test_db_retrieves_collation def test_db_retrieves_collation
ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:lease_connection, @connection) do
assert_called(@connection, :collation) do assert_called(@connection, :collation) do
ActiveRecord::Tasks::DatabaseTasks.collation @configuration ActiveRecord::Tasks::DatabaseTasks.collation @configuration
end end
@ -313,7 +313,7 @@ def test_structure_dump_with_hash_extra_flags_for_the_correct_driver
def test_structure_dump_with_ignore_tables def test_structure_dump_with_ignore_tables
filename = "awesome-file.sql" filename = "awesome-file.sql"
ActiveRecord::Base.connection.stub(:data_sources, ["foo", "bar", "prefix_foo", "ignored_foo"]) do ActiveRecord::Base.lease_connection.stub(:data_sources, ["foo", "bar", "prefix_foo", "ignored_foo"]) do
ActiveRecord::SchemaDumper.stub(:ignore_tables, [/^prefix_/, "ignored_foo"]) do ActiveRecord::SchemaDumper.stub(:ignore_tables, [/^prefix_/, "ignored_foo"]) do
assert_called_with( assert_called_with(
Kernel, Kernel,

@ -4,7 +4,7 @@
class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase
def setup def setup
ActiveRecord::Base.connection.materialize_transactions ActiveRecord::Base.lease_connection.materialize_transactions
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
def execute(sql, name = nil) sql end def execute(sql, name = nil) sql end
@ -112,6 +112,6 @@ def test_remove_index_with_wrong_option
private private
def method_missing(...) def method_missing(...)
ActiveRecord::Base.connection.public_send(...) ActiveRecord::Base.lease_connection.public_send(...)
end end
end end

@ -12,7 +12,7 @@ class PgArray < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
enable_extension!("hstore", @connection) enable_extension!("hstore", @connection)
@ -269,7 +269,7 @@ def test_quoting_non_standard_delimiters
oid = ActiveRecord::ConnectionAdapters::PostgreSQL::OID oid = ActiveRecord::ConnectionAdapters::PostgreSQL::OID
comma_delim = oid::Array.new(ActiveRecord::Type::String.new, ",") comma_delim = oid::Array.new(ActiveRecord::Type::String.new, ",")
semicolon_delim = oid::Array.new(ActiveRecord::Type::String.new, ";") semicolon_delim = oid::Array.new(ActiveRecord::Type::String.new, ";")
conn = PgArray.connection conn = PgArray.lease_connection
assert_equal %({"hello,",world;}), conn.type_cast(comma_delim.serialize(strings)) assert_equal %({"hello,",world;}), conn.type_cast(comma_delim.serialize(strings))
assert_equal %({hello,;"world;"}), conn.type_cast(semicolon_delim.serialize(strings)) assert_equal %({hello,;"world;"}), conn.type_cast(semicolon_delim.serialize(strings))

@ -11,7 +11,7 @@ class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase
class PostgresqlBitString < ActiveRecord::Base; end class PostgresqlBitString < ActiveRecord::Base; end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("postgresql_bit_strings", force: true) do |t| @connection.create_table("postgresql_bit_strings", force: true) do |t|
t.bit :a_bit, default: "00000011", limit: 8 t.bit :a_bit, default: "00000011", limit: 8
t.bit_varying :a_bit_varying, default: "0011", limit: 4 t.bit_varying :a_bit_varying, default: "0011", limit: 4
@ -59,7 +59,7 @@ def test_schema_dumping
assert_match %r{t\.bit_varying\s+"a_bit_varying",\s+limit: 4,\s+default: "0011"$}, output assert_match %r{t\.bit_varying\s+"a_bit_varying",\s+limit: 4,\s+default: "0011"$}, output
end end
if ActiveRecord::Base.connection.prepared_statements if ActiveRecord::Base.lease_connection.prepared_statements
def test_assigning_invalid_hex_string_raises_exception def test_assigning_invalid_hex_string_raises_exception
assert_raises(ActiveRecord::StatementInvalid) { PostgresqlBitString.create! a_bit: "FF" } assert_raises(ActiveRecord::StatementInvalid) { PostgresqlBitString.create! a_bit: "FF" }
assert_raises(ActiveRecord::StatementInvalid) { PostgresqlBitString.create! a_bit_varying: "F" } assert_raises(ActiveRecord::StatementInvalid) { PostgresqlBitString.create! a_bit_varying: "F" }

@ -11,7 +11,7 @@ class ByteaDataType < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.transaction do @connection.transaction do
@connection.create_table("bytea_data_type") do |t| @connection.create_table("bytea_data_type") do |t|
t.binary "payload" t.binary "payload"
@ -87,7 +87,7 @@ def test_via_to_sql
def test_via_to_sql_with_complicating_connection def test_via_to_sql_with_complicating_connection
Thread.new do Thread.new do
other_conn = ActiveRecord::Base.connection other_conn = ActiveRecord::Base.lease_connection
other_conn.execute("SET standard_conforming_strings = off") other_conn.execute("SET standard_conforming_strings = off")
other_conn.execute("SET escape_string_warning = off") other_conn.execute("SET escape_string_warning = off")
end.join end.join

@ -6,7 +6,7 @@ class PostgresqlCaseInsensitiveTest < ActiveRecord::PostgreSQLTestCase
class Default < ActiveRecord::Base; end class Default < ActiveRecord::Base; end
def test_case_insensitiveness def test_case_insensitiveness
connection = ActiveRecord::Base.connection connection = ActiveRecord::Base.lease_connection
attr = Default.arel_table[:char1] attr = Default.arel_table[:char1]
comparison = connection.case_insensitive_comparison(attr, nil) comparison = connection.case_insensitive_comparison(attr, nil)

@ -9,7 +9,7 @@ class PGChangeSchemaTest < ActiveRecord::PostgreSQLTestCase
def setup def setup
super super
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
connection.create_table(:strings) do |t| connection.create_table(:strings) do |t|
t.string :somedate t.string :somedate
end end

@ -10,7 +10,7 @@ class Citext < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
enable_extension!("citext", @connection) enable_extension!("citext", @connection)

@ -7,7 +7,7 @@ class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper include SchemaDumpingHelper
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table :postgresql_collations, force: true do |t| @connection.create_table :postgresql_collations, force: true do |t|
t.string :string_c, collation: "C" t.string :string_c, collation: "C"
t.text :text_posix, collation: "POSIX" t.text :text_posix, collation: "POSIX"

@ -13,7 +13,7 @@ class PostgresqlComposite < ActiveRecord::Base
def setup def setup
super super
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.transaction do @connection.transaction do
@connection.execute <<~SQL @connection.execute <<~SQL
CREATE TYPE full_address AS CREATE TYPE full_address AS

@ -13,7 +13,7 @@ class NonExistentTable < ActiveRecord::Base
def setup def setup
super super
@subscriber = SQLSubscriber.new @subscriber = SQLSubscriber.new
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.materialize_transactions @connection.materialize_transactions
@subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
end end
@ -53,7 +53,7 @@ def test_connection_options
NonExistentTable.establish_connection(params) NonExistentTable.establish_connection(params)
# Verify the connection param has been applied. # Verify the connection param has been applied.
expect = NonExistentTable.connection.query("show geqo").first.first expect = NonExistentTable.lease_connection.query("show geqo").first.first
assert_equal "off", expect assert_equal "off", expect
ensure ensure
NonExistentTable.remove_connection NonExistentTable.remove_connection
@ -126,7 +126,7 @@ def test_schema_names_logs_name
assert_equal "SCHEMA", @subscriber.logged[0][1] assert_equal "SCHEMA", @subscriber.logged[0][1]
end end
if ActiveRecord::Base.connection.prepared_statements if ActiveRecord::Base.lease_connection.prepared_statements
def test_statement_key_is_logged def test_statement_key_is_logged
bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new) bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new)
@connection.exec_query("SELECT $1::integer", "SQL", [bind], prepare: true) @connection.exec_query("SELECT $1::integer", "SQL", [bind], prepare: true)
@ -145,13 +145,13 @@ def test_reconnection_after_actual_disconnection_with_verify
assert_predicate @connection, :active? assert_predicate @connection, :active?
ensure ensure
# Repair all fixture connections so other tests won't break. # Repair all fixture connections so other tests won't break.
@fixture_connection_pools.each { |p| p.connection.verify! } @fixture_connection_pools.each { |p| p.lease_connection.verify! }
end end
def test_set_session_variable_true def test_set_session_variable_true
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: true })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: true }))
set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" set_true = ActiveRecord::Base.lease_connection.exec_query "SHOW DEBUG_PRINT_PLAN"
assert_equal [["on"]], set_true.rows assert_equal [["on"]], set_true.rows
end end
end end
@ -159,7 +159,7 @@ def test_set_session_variable_true
def test_set_session_variable_false def test_set_session_variable_false
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: false })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: false }))
set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" set_false = ActiveRecord::Base.lease_connection.exec_query "SHOW DEBUG_PRINT_PLAN"
assert_equal [["off"]], set_false.rows assert_equal [["off"]], set_false.rows
end end
end end
@ -181,7 +181,7 @@ def test_set_session_variable_default
def test_set_session_timezone def test_set_session_timezone
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { timezone: "America/New_York" })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { timezone: "America/New_York" }))
assert_equal "America/New_York", ActiveRecord::Base.connection.query_value("SHOW TIME ZONE") assert_equal "America/New_York", ActiveRecord::Base.lease_connection.query_value("SHOW TIME ZONE")
end end
end end

@ -19,7 +19,7 @@ class Thing < ActiveRecord::Base
def setup def setup
@previous_unlogged_tables = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables @previous_unlogged_tables = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = false ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = false
end end

@ -17,7 +17,7 @@ class PostgresqlLtree < ActiveRecord::Base
class PostgresqlDataTypeTest < ActiveRecord::PostgreSQLTestCase class PostgresqlDataTypeTest < ActiveRecord::PostgreSQLTestCase
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.execute("INSERT INTO postgresql_times (id, time_interval, scaled_time_interval) VALUES (1, '1 year 2 days ago', '3 weeks ago')") @connection.execute("INSERT INTO postgresql_times (id, time_interval, scaled_time_interval) VALUES (1, '1 year 2 days ago', '3 weeks ago')")
@first_time = PostgresqlTime.find(1) @first_time = PostgresqlTime.find(1)
@ -75,7 +75,7 @@ class PostgresqlInternalDataTypeTest < ActiveRecord::PostgreSQLTestCase
include DdlHelper include DdlHelper
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
def test_name_column_type def test_name_column_type

@ -5,7 +5,7 @@
class PostgresqlDeferredConstraintsTest < ActiveRecord::PostgreSQLTestCase class PostgresqlDeferredConstraintsTest < ActiveRecord::PostgreSQLTestCase
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@fk = @connection.foreign_keys("authors").first.name @fk = @connection.foreign_keys("authors").first.name
@other_fk = @connection.foreign_keys("lessons_students").first.name @other_fk = @connection.foreign_keys("lessons_students").first.name
end end

@ -11,7 +11,7 @@ class PostgresqlDomain < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.transaction do @connection.transaction do
@connection.execute "CREATE DOMAIN custom_money as numeric(8,2)" @connection.execute "CREATE DOMAIN custom_money as numeric(8,2)"
@connection.create_table("postgresql_domains") do |t| @connection.create_table("postgresql_domains") do |t|

@ -20,7 +20,7 @@ class PostgresqlEnum < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.transaction do @connection.transaction do
@connection.create_enum("mood", ["sad", "ok", "happy"]) @connection.create_enum("mood", ["sad", "ok", "happy"])
@connection.create_table("postgresql_enums") do |t| @connection.create_table("postgresql_enums") do |t|

@ -26,7 +26,7 @@ def change
def setup def setup
super super
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@pool = ActiveRecord::Base.connection_pool @pool = ActiveRecord::Base.connection_pool
@old_table_name_prefix = ActiveRecord::Base.table_name_prefix @old_table_name_prefix = ActiveRecord::Base.table_name_prefix

@ -3,7 +3,7 @@
require "cases/helper" require "cases/helper"
require "models/professor" require "models/professor"
if ActiveRecord::Base.connection.supports_foreign_tables? if ActiveRecord::Base.lease_connection.supports_foreign_tables?
class ForeignTableTest < ActiveRecord::TestCase class ForeignTableTest < ActiveRecord::TestCase
self.use_transactional_tests = false self.use_transactional_tests = false
@ -18,7 +18,7 @@ class ForeignProfessorWithPk < ForeignProfessor
def setup def setup
@professor = Professor.create(name: "Nicola") @professor = Professor.create(name: "Nicola")
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
enable_extension!("postgres_fdw", @connection) enable_extension!("postgres_fdw", @connection)
foreign_db_config = ARTest.test_configuration_hashes["arunit2"] foreign_db_config = ARTest.test_configuration_hashes["arunit2"]
@ -52,7 +52,7 @@ def teardown
def test_table_exists def test_table_exists
table_name = ForeignProfessor.table_name table_name = ForeignProfessor.table_name
assert_not ActiveRecord::Base.connection.table_exists?(table_name) assert_not ActiveRecord::Base.lease_connection.table_exists?(table_name)
end end
def test_foreign_tables_are_valid_data_sources def test_foreign_tables_are_valid_data_sources

@ -8,7 +8,7 @@ class PostgresqlFullTextTest < ActiveRecord::PostgreSQLTestCase
class Tsvector < ActiveRecord::Base; end class Tsvector < ActiveRecord::Base; end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("tsvectors") do |t| @connection.create_table("tsvectors") do |t|
t.tsvector "text_vector" t.tsvector "text_vector"
end end

@ -19,7 +19,7 @@ class PostgresqlPoint < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("postgresql_points") do |t| @connection.create_table("postgresql_points") do |t|
t.point :x t.point :x
t.point :y, default: [12.2, 13.3] t.point :y, default: [12.2, 13.3]
@ -167,7 +167,7 @@ class PostgresqlGeometricTest < ActiveRecord::PostgreSQLTestCase
class PostgresqlGeometric < ActiveRecord::Base; end class PostgresqlGeometric < ActiveRecord::Base; end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("postgresql_geometrics") do |t| @connection.create_table("postgresql_geometrics") do |t|
t.lseg :a_line_segment t.lseg :a_line_segment
t.box :a_box t.box :a_box
@ -247,10 +247,10 @@ class PostgreSQLGeometricLineTest < ActiveRecord::PostgreSQLTestCase
class PostgresqlLine < ActiveRecord::Base; end class PostgresqlLine < ActiveRecord::Base; end
setup do setup do
unless ActiveRecord::Base.connection.database_version >= 90400 unless ActiveRecord::Base.lease_connection.database_version >= 90400
skip("line type is not fully implemented") skip("line type is not fully implemented")
end end
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("postgresql_lines") do |t| @connection.create_table("postgresql_lines") do |t|
t.line :a_line t.line :a_line
end end
@ -293,7 +293,7 @@ class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase
def setup def setup
super super
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@table_name = :testings @table_name = :testings
end end

@ -13,7 +13,7 @@ class Hstore < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
enable_extension!("hstore", @connection) enable_extension!("hstore", @connection)

@ -9,7 +9,7 @@ class PostgresqlInfinity < ActiveRecord::Base
end end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table(:postgresql_infinities) do |t| @connection.create_table(:postgresql_infinities) do |t|
t.float :float t.float :float
t.datetime :datetime t.datetime :datetime

@ -8,7 +8,7 @@ class PgInteger < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.transaction do @connection.transaction do
@connection.create_table "pg_integers", force: true do |t| @connection.create_table "pg_integers", force: true do |t|

@ -11,7 +11,7 @@ class IntervalDataType < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.transaction do @connection.transaction do
@connection.create_table("interval_data_types") do |t| @connection.create_table("interval_data_types") do |t|
t.interval "maximum_term" t.interval "maximum_term"

@ -50,7 +50,7 @@ def change
end end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
end end
teardown do teardown do

@ -10,7 +10,7 @@ class Ltree < ActiveRecord::Base
end end
def setup def setup
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
enable_extension!("ltree", @connection) enable_extension!("ltree", @connection)

@ -11,7 +11,7 @@ class PostgresqlMoney < ActiveRecord::Base
end end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.execute("set lc_monetary = 'C'") @connection.execute("set lc_monetary = 'C'")
@connection.create_table("postgresql_moneys", force: true) do |t| @connection.create_table("postgresql_moneys", force: true) do |t|
t.money "wealth" t.money "wealth"

@ -8,7 +8,7 @@ class PostgresqlNetworkTest < ActiveRecord::PostgreSQLTestCase
class PostgresqlNetworkAddress < ActiveRecord::Base; end class PostgresqlNetworkAddress < ActiveRecord::Base; end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("postgresql_network_addresses", force: true) do |t| @connection.create_table("postgresql_network_addresses", force: true) do |t|
t.inet "inet_address", default: "192.168.1.1" t.inet "inet_address", default: "192.168.1.1"
t.cidr "cidr_address", default: "192.168.1.0/24" t.cidr "cidr_address", default: "192.168.1.0/24"

@ -6,7 +6,7 @@ class PostgresqlNumberTest < ActiveRecord::PostgreSQLTestCase
class PostgresqlNumber < ActiveRecord::Base; end class PostgresqlNumber < ActiveRecord::Base; end
setup do setup do
@connection = ActiveRecord::Base.connection @connection = ActiveRecord::Base.lease_connection
@connection.create_table("postgresql_numbers", force: true) do |t| @connection.create_table("postgresql_numbers", force: true) do |t|
t.column "single", "REAL" t.column "single", "REAL"
t.column "double", "DOUBLE PRECISION" t.column "double", "DOUBLE PRECISION"

@ -8,7 +8,7 @@ class PostgresqlOptimizerHintsTest < ActiveRecord::PostgreSQLTestCase
fixtures :posts fixtures :posts
def setup def setup
enable_extension!("pg_hint_plan", ActiveRecord::Base.connection) enable_extension!("pg_hint_plan", ActiveRecord::Base.lease_connection)
end end
def test_optimizer_hints def test_optimizer_hints

Some files were not shown because too many files have changed in this diff Show More