From 7263da542b66084dae93af8bc3bd502c8710154b Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Fri, 1 Mar 2024 12:18:50 +0100 Subject: [PATCH] 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 --- .../subscription_adapter/postgresql_test.rb | 6 +- actionmailbox/test/migrations_test.rb | 2 +- actionview/test/active_record_unit.rb | 10 +- activerecord/CHANGELOG.md | 17 ++ activerecord/examples/performance.rb | 4 +- .../active_record/associations/association.rb | 16 +- .../join_dependency/join_association.rb | 2 +- activerecord/lib/active_record/base.rb | 2 +- .../abstract/connection_handler.rb | 2 +- .../abstract/connection_pool.rb | 88 +++++----- .../abstract/database_statements.rb | 6 +- .../connection_adapters/abstract_adapter.rb | 2 +- activerecord/lib/active_record/core.rb | 6 +- activerecord/lib/active_record/errors.rb | 2 +- activerecord/lib/active_record/explain.rb | 25 +-- .../lib/active_record/future_result.rb | 4 +- activerecord/lib/active_record/insert_all.rb | 2 +- activerecord/lib/active_record/integration.rb | 2 +- .../lib/active_record/model_schema.rb | 12 +- activerecord/lib/active_record/persistence.rb | 30 ++-- activerecord/lib/active_record/query_cache.rb | 2 +- activerecord/lib/active_record/querying.rb | 6 +- activerecord/lib/active_record/relation.rb | 93 ++++++----- .../active_record/relation/calculations.rb | 23 ++- .../active_record/relation/finder_methods.rb | 10 +- .../active_record/relation/query_methods.rb | 2 +- activerecord/lib/active_record/result.rb | 2 +- .../lib/active_record/sanitization.rb | 8 +- .../lib/active_record/statement_cache.rb | 8 +- .../lib/active_record/tasks/database_tasks.rb | 8 +- .../tasks/mysql_database_tasks.rb | 2 +- .../tasks/postgresql_database_tasks.rb | 2 +- .../tasks/sqlite_database_tasks.rb | 2 +- .../lib/active_record/test_fixtures.rb | 4 +- .../active_record/testing/query_assertions.rb | 4 +- activerecord/lib/active_record/timestamp.rb | 2 +- .../lib/active_record/transactions.rb | 10 +- .../active_record/type_caster/connection.rb | 2 +- .../active_record/validations/uniqueness.rb | 6 +- activerecord/lib/arel/nodes/node.rb | 2 +- activerecord/lib/arel/tree_manager.rb | 2 +- .../destroy_association_async_test.rb | 6 +- .../test/cases/active_record_schema_test.rb | 6 +- activerecord/test/cases/active_record_test.rb | 4 +- .../test/cases/adapter_prevent_writes_test.rb | 4 +- activerecord/test/cases/adapter_test.rb | 40 ++--- .../active_schema_test.rb | 34 ++-- .../adapter_prevent_writes_test.rb | 2 +- .../auto_increment_test.rb | 2 +- .../charset_collation_test.rb | 2 +- .../abstract_mysql_adapter/connection_test.rb | 34 ++-- .../datetime_precision_quoting_test.rb | 2 +- .../abstract_mysql_adapter/json_test.rb | 2 +- .../mysql_boolean_test.rb | 2 +- .../abstract_mysql_adapter/mysql_enum_test.rb | 2 +- .../mysql_explain_test.rb | 2 +- .../nested_deadlock_test.rb | 8 +- .../abstract_mysql_adapter/quoting_test.rb | 2 +- .../schema_migrations_test.rb | 2 +- .../abstract_mysql_adapter/schema_test.rb | 4 +- .../abstract_mysql_adapter/set_test.rb | 2 +- .../abstract_mysql_adapter/sp_test.rb | 4 +- .../abstract_mysql_adapter/sql_types_test.rb | 2 +- .../table_options_test.rb | 6 +- .../transaction_test.rb | 18 +- .../unsigned_type_test.rb | 2 +- .../virtual_column_test.rb | 4 +- .../abstract_mysql_adapter/warnings_test.rb | 2 +- .../mysql2/check_constraint_quoting_test.rb | 6 +- .../adapters/mysql2/mysql2_adapter_test.rb | 4 +- .../cases/adapters/mysql2/mysql2_rake_test.rb | 20 +-- .../adapters/postgresql/active_schema_test.rb | 4 +- .../cases/adapters/postgresql/array_test.rb | 4 +- .../adapters/postgresql/bit_string_test.rb | 4 +- .../cases/adapters/postgresql/bytea_test.rb | 4 +- .../postgresql/case_insensitive_test.rb | 2 +- .../adapters/postgresql/change_schema_test.rb | 2 +- .../cases/adapters/postgresql/citext_test.rb | 2 +- .../adapters/postgresql/collation_test.rb | 2 +- .../adapters/postgresql/composite_test.rb | 2 +- .../adapters/postgresql/connection_test.rb | 14 +- .../postgresql/create_unlogged_tables_test.rb | 2 +- .../adapters/postgresql/datatype_test.rb | 4 +- .../postgresql/deferred_constraints_test.rb | 2 +- .../cases/adapters/postgresql/domain_test.rb | 2 +- .../cases/adapters/postgresql/enum_test.rb | 2 +- .../postgresql/extension_migration_test.rb | 2 +- .../adapters/postgresql/foreign_table_test.rb | 6 +- .../adapters/postgresql/full_text_test.rb | 2 +- .../adapters/postgresql/geometric_test.rb | 10 +- .../cases/adapters/postgresql/hstore_test.rb | 2 +- .../adapters/postgresql/infinity_test.rb | 2 +- .../cases/adapters/postgresql/integer_test.rb | 2 +- .../adapters/postgresql/interval_test.rb | 2 +- .../postgresql/invertible_migration_test.rb | 2 +- .../cases/adapters/postgresql/ltree_test.rb | 2 +- .../cases/adapters/postgresql/money_test.rb | 2 +- .../cases/adapters/postgresql/network_test.rb | 2 +- .../cases/adapters/postgresql/numbers_test.rb | 2 +- .../postgresql/optimizer_hints_test.rb | 2 +- .../adapters/postgresql/partitions_test.rb | 4 +- .../postgresql_adapter_prevent_writes_test.rb | 2 +- .../postgresql/postgresql_adapter_test.rb | 6 +- .../postgresql/postgresql_rake_test.rb | 22 +-- .../prepared_statements_disabled_test.rb | 2 +- .../cases/adapters/postgresql/quoting_test.rb | 2 +- .../cases/adapters/postgresql/range_test.rb | 2 +- .../postgresql/referential_integrity_test.rb | 4 +- .../adapters/postgresql/rename_table_test.rb | 2 +- .../postgresql/schema_authorization_test.rb | 4 +- .../cases/adapters/postgresql/schema_test.rb | 28 ++-- .../cases/adapters/postgresql/serial_test.rb | 8 +- .../postgresql/statement_pool_test.rb | 2 +- .../adapters/postgresql/timestamp_test.rb | 14 +- .../postgresql/transaction_nested_test.rb | 18 +- .../adapters/postgresql/transaction_test.rb | 26 +-- .../adapters/postgresql/type_lookup_test.rb | 2 +- .../cases/adapters/postgresql/uuid_test.rb | 6 +- .../postgresql/virtual_column_test.rb | 4 +- .../cases/adapters/postgresql/xml_test.rb | 2 +- .../cases/adapters/sqlite3/collation_test.rb | 2 +- .../cases/adapters/sqlite3/copy_table_test.rb | 2 +- .../cases/adapters/sqlite3/quoting_test.rb | 2 +- .../sqlite3_adapter_prevent_writes_test.rb | 2 +- .../adapters/sqlite3/sqlite3_adapter_test.rb | 26 +-- .../adapters/sqlite3/sqlite_rake_test.rb | 4 +- .../adapters/sqlite3/virtual_column_test.rb | 4 +- .../adapters/trilogy/trilogy_adapter_test.rb | 4 +- .../adapters/trilogy/trilogy_rake_test.rb | 20 +-- activerecord/test/cases/annotate_test.rb | 2 +- .../test/cases/arel/collectors/bind_test.rb | 2 +- .../cases/arel/collectors/composite_test.rb | 2 +- .../cases/arel/collectors/sql_string_test.rb | 2 +- .../substitute_bind_collector_test.rb | 2 +- .../test/cases/arel/insert_manager_test.rb | 2 +- .../test/cases/arel/nodes/equality_test.rb | 6 +- .../test/cases/arel/nodes/sql_literal_test.rb | 2 +- .../test/cases/arel/select_manager_test.rb | 6 +- .../test/cases/arel/support/fake_record.rb | 20 ++- .../visitors/dispatch_contamination_test.rb | 2 +- .../test/cases/arel/visitors/mysql_test.rb | 2 +- .../test/cases/arel/visitors/postgres_test.rb | 2 +- .../test/cases/arel/visitors/sqlite_test.rb | 2 +- .../test/cases/arel/visitors/to_sql_test.rb | 2 +- .../belongs_to_associations_test.rb | 8 +- .../eager_singularization_test.rb | 2 +- .../test/cases/associations/eager_test.rb | 6 +- ...s_and_belongs_to_many_associations_test.rb | 18 +- .../has_many_associations_test.rb | 10 +- .../has_many_through_associations_test.rb | 4 +- .../associations/has_one_associations_test.rb | 4 +- ...through_disable_joins_associations_test.rb | 2 +- .../nested_through_associations_test.rb | 2 +- .../test/cases/associations/required_test.rb | 2 +- activerecord/test/cases/associations_test.rb | 14 +- .../test/cases/asynchronous_queries_test.rb | 4 +- activerecord/test/cases/attributes_test.rb | 2 +- .../test/cases/autosave_association_test.rb | 6 +- .../test/cases/base_prevent_writes_test.rb | 10 +- activerecord/test/cases/base_test.rb | 14 +- activerecord/test/cases/batches_test.rb | 22 +-- .../test/cases/bind_parameter_test.rb | 4 +- activerecord/test/cases/cache_key_test.rb | 2 +- activerecord/test/cases/calculations_test.rb | 10 +- activerecord/test/cases/column_alias_test.rb | 2 +- activerecord/test/cases/comment_test.rb | 4 +- .../adapter_leasing_test.rb | 4 +- .../connection_handler_test.rb | 48 +++--- .../connection_handlers_multi_db_test.rb | 22 +-- .../connection_handlers_sharding_db_test.rb | 74 ++++---- .../connection_swapping_nested_test.rb | 42 ++--- .../mysql_type_lookup_test.rb | 2 +- .../connection_adapters/schema_cache_test.rb | 4 +- .../connection_adapters/type_lookup_test.rb | 2 +- .../test/cases/connection_handling_test.rb | 18 +- .../test/cases/connection_management_test.rb | 6 +- .../test/cases/connection_pool_test.rb | 68 ++++---- activerecord/test/cases/core_test.rb | 2 +- .../test/cases/database_selector_test.rb | 16 +- .../test/cases/database_statements_test.rb | 2 +- .../test/cases/date_time_precision_test.rb | 2 +- activerecord/test/cases/defaults_test.rb | 16 +- activerecord/test/cases/dirty_test.rb | 4 +- activerecord/test/cases/disconnected_test.rb | 2 +- activerecord/test/cases/encryption/helper.rb | 2 +- activerecord/test/cases/excluding_test.rb | 4 +- .../test/cases/explain_subscriber_test.rb | 2 +- activerecord/test/cases/explain_test.rb | 18 +- activerecord/test/cases/finder_test.rb | 30 ++-- activerecord/test/cases/fixtures_test.rb | 82 ++++----- activerecord/test/cases/helper.rb | 6 +- .../test/cases/hot_compatibility_test.rb | 18 +- activerecord/test/cases/inheritance_test.rb | 14 +- activerecord/test/cases/insert_all_test.rb | 4 +- .../test/cases/instrumentation_test.rb | 7 +- .../test/cases/invertible_migration_test.rb | 39 ++--- .../test/cases/json_shared_test_cases.rb | 4 +- activerecord/test/cases/locking_test.rb | 24 +-- .../test/cases/log_subscriber_test.rb | 4 +- .../test/cases/marshal_serialization_test.rb | 2 +- .../cases/migration/change_schema_test.rb | 24 +-- .../test/cases/migration/change_table_test.rb | 2 +- .../cases/migration/check_constraint_test.rb | 8 +- .../migration/column_positioning_test.rb | 2 +- .../cases/migration/command_recorder_test.rb | 6 +- .../cases/migration/compatibility_test.rb | 14 +- .../cases/migration/create_join_table_test.rb | 2 +- .../migration/exclusion_constraint_test.rb | 6 +- .../test/cases/migration/foreign_key_test.rb | 20 +-- activerecord/test/cases/migration/helper.rb | 2 +- .../test/cases/migration/index_test.rb | 2 +- .../migration/references_foreign_key_test.rb | 8 +- .../cases/migration/references_index_test.rb | 2 +- .../migration/schema_definitions_test.rb | 2 +- .../cases/migration/unique_constraint_test.rb | 6 +- activerecord/test/cases/migration_test.rb | 158 +++++++++--------- .../test/cases/multi_db_migrator_test.rb | 10 +- activerecord/test/cases/multiple_db_test.rb | 32 ++-- activerecord/test/cases/persistence_test.rb | 18 +- .../test/cases/pooled_connections_test.rb | 6 +- .../cases/prepared_statement_status_test.rb | 6 +- activerecord/test/cases/primary_class_test.rb | 4 +- activerecord/test/cases/primary_keys_test.rb | 14 +- activerecord/test/cases/query_cache_test.rb | 154 ++++++++--------- activerecord/test/cases/query_logs_test.rb | 20 +-- activerecord/test/cases/quoting_test.rb | 4 +- .../test/cases/relation/delete_all_test.rb | 4 +- .../test/cases/relation/load_async_test.rb | 22 +-- .../test/cases/relation/merging_test.rb | 6 +- .../cases/relation/predicate_builder_test.rb | 2 +- .../test/cases/relation/update_all_test.rb | 4 +- activerecord/test/cases/relation/with_test.rb | 2 +- activerecord/test/cases/relation_test.rb | 6 +- activerecord/test/cases/reserved_word_test.rb | 2 +- activerecord/test/cases/sanitize_test.rb | 30 ++-- activerecord/test/cases/schema_dumper_test.rb | 34 ++-- .../cases/scoping/default_scoping_test.rb | 10 +- .../test/cases/serialized_attribute_test.rb | 4 +- .../test/cases/statement_cache_test.rb | 31 ++-- .../test/cases/statement_invalid_test.rb | 8 +- activerecord/test/cases/store_test.rb | 2 +- .../test/cases/tasks/database_tasks_test.rb | 6 +- activerecord/test/cases/test_case.rb | 4 +- .../test/cases/time_precision_test.rb | 2 +- activerecord/test/cases/timestamp_test.rb | 8 +- .../test/cases/transaction_callbacks_test.rb | 6 +- .../cases/transaction_instrumentation_test.rb | 10 +- .../test/cases/transaction_isolation_test.rb | 10 +- activerecord/test/cases/transactions_test.rb | 118 ++++++------- activerecord/test/cases/unconnected_test.rb | 2 +- .../test/cases/unsafe_raw_sql_test.rb | 6 +- .../validations/uniqueness_validation_test.rb | 2 +- activerecord/test/cases/view_test.rb | 12 +- activerecord/test/models/bird.rb | 2 +- activerecord/test/models/contact.rb | 6 +- activerecord/test/models/parrot.rb | 6 +- activerecord/test/models/post.rb | 4 +- .../test/schema/postgresql_specific_schema.rb | 4 +- activerecord/test/schema/schema.rb | 18 +- activerecord/test/support/adapter_helper.rb | 12 +- activerecord/test/support/connection.rb | 2 +- .../test/support/load_schema_helper.rb | 2 +- .../test/support/schema_dumping_helper.rb | 4 +- activestorage/test/migrations_test.rb | 2 +- activestorage/test/models/attachment_test.rb | 4 +- .../commands/dbconsole/dbconsole_command.rb | 2 +- .../rails/generators/generated_attribute.rb | 2 +- railties/test/application/bin_setup_test.rb | 2 +- .../test/application/configuration_test.rb | 12 +- railties/test/application/console_test.rb | 2 +- .../initializers/frameworks_test.rb | 12 +- railties/test/application/loading_test.rb | 8 +- railties/test/application/query_logs_test.rb | 8 +- railties/test/application/rake/dbs_test.rb | 56 +++---- .../test/application/rake/multi_dbs_test.rb | 20 +-- railties/test/application/test_test.rb | 4 +- railties/test/json_params_parsing_test.rb | 2 +- 277 files changed, 1474 insertions(+), 1397 deletions(-) diff --git a/actioncable/test/subscription_adapter/postgresql_test.rb b/actioncable/test/subscription_adapter/postgresql_test.rb index 21d7dcd103..5dd091621e 100644 --- a/actioncable/test/subscription_adapter/postgresql_test.rb +++ b/actioncable/test/subscription_adapter/postgresql_test.rb @@ -23,7 +23,7 @@ def setup ActiveRecord::Base.establish_connection database_config begin - ActiveRecord::Base.connection.connect! + ActiveRecord::Base.lease_connection.connect! rescue @rx_adapter = @tx_adapter = nil skip "Couldn't connect to PostgreSQL: #{database_config.inspect}" @@ -68,7 +68,7 @@ def active? def test_default_subscription_connection_identifier 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-#{$$}"] end @@ -81,7 +81,7 @@ def test_custom_subscription_connection_identifier 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"] end end diff --git a/actionmailbox/test/migrations_test.rb b/actionmailbox/test/migrations_test.rb index 34fce61182..eb18781e03 100644 --- a/actionmailbox/test/migrations_test.rb +++ b/actionmailbox/test/migrations_test.rb @@ -8,7 +8,7 @@ class ActionMailbox::MigrationsTest < ActiveSupport::TestCase @original_verbose = ActiveRecord::Migration.verbose ActiveRecord::Migration.verbose = false - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @original_options = Rails.configuration.generators.options.deep_dup end diff --git a/actionview/test/active_record_unit.rb b/actionview/test/active_record_unit.rb index f49717a5b8..f9e50e93cf 100644 --- a/actionview/test/active_record_unit.rb +++ b/actionview/test/active_record_unit.rb @@ -44,7 +44,7 @@ def setup def reconnect return unless able_to_connect - ActiveRecord::Base.connection.reconnect! + ActiveRecord::Base.lease_connection.reconnect! load_schema end @@ -56,9 +56,9 @@ def setup_connection options = defaults.merge adapter: adapter, timeout: 500 ActiveRecord::Base.establish_connection(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 raise "Can't setup connection since ActiveRecord isn't loaded." end @@ -67,7 +67,7 @@ def setup_connection # Load actionpack sqlite3 tables def load_schema 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 @@ -107,7 +107,7 @@ def run(*args) end def capture_sql - ActiveRecord::Base.connection.materialize_transactions + ActiveRecord::Base.lease_connection.materialize_transactions SQLCounter.clear_log yield SQLCounter.log.dup diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 999945b21c..6524d1da80 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -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 ```ruby diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb index 024e503ec7..4e3fe2fb6e 100644 --- a/activerecord/examples/performance.rb +++ b/activerecord/examples/performance.rb @@ -176,10 +176,10 @@ def self.email end x.report "Model.log" do - Exhibit.connection.send(:log, "hello", "world") { } + Exhibit.lease_connection.send(:log, "hello", "world") { } end 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 diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index 32d910591f..d4ca692cbf 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -63,7 +63,7 @@ def reset_negative_cache # :nodoc: # Reloads the \target and returns +self+ on success. # The QueryCache is cleared if +force+ is true. def reload(force = false) - klass.connection.clear_query_cache if force && klass + klass.connection_pool.clear_query_cache if force && klass reset reset_scope load_target @@ -231,12 +231,14 @@ def find_target end binds = AssociationScope.get_bind_values(owner, reflection.chain) - sc.execute(binds, klass.connection) do |record| - set_inverse_instance(record) - if owner.strict_loading_n_plus_one_only? && reflection.macro == :has_many - record.strict_loading! - else - record.strict_loading!(false, mode: owner.strict_loading_mode) + klass.with_connection do |c| + sc.execute(binds, c) do |record| + set_inverse_instance(record) + if owner.strict_loading_n_plus_one_only? && reflection.macro == :has_many + record.strict_loading! + else + record.strict_loading!(false, mode: owner.strict_loading_mode) + end end end end diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index 88f21b80ca..434181700c 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -91,7 +91,7 @@ def strict_loading? def append_constraints(join, constraints) if join.is_a?(Arel::Nodes::StringJoin) 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 right = join.right right.expr = Arel::Nodes::And.new(constraints.unshift right.expr) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index ef1cabd18f..c4a38f8d59 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -233,7 +233,7 @@ module ActiveRecord # :nodoc: # # Connections are usually created through # {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 # ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection # and Course and all of its subclasses will use this connection instead. diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb index c5158f7077..c1962812f8 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb @@ -190,7 +190,7 @@ def flush_idle_connections!(role = nil) # for (not necessarily the current class). 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.connection + pool.lease_connection end # Returns true if a connection that's accessible to this class has diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 9b57d9a9e2..1a7e44f910 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -69,7 +69,7 @@ def db_config # Connections can be obtained and used from a connection pool in several # 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 # {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 @@ -139,46 +139,46 @@ def clear(connection) 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: + 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 @mutex = Mutex.new @map = WeakKeyMap.new @@ -293,7 +293,13 @@ def lease_connection lease.connection ||= checkout 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: raise "There is already a pinned connection" if @pinned_connection diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index 35f453461f..62e925a31b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -296,9 +296,9 @@ def truncate_tables(*table_names) # :nodoc: # #transaction will raise exceptions when it tries to release the # already-automatically-released savepoints: # - # Model.connection.transaction do # BEGIN - # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 - # Model.connection.create_table(...) + # Model.lease_connection.transaction do # BEGIN + # Model.lease_connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 + # Model.lease_connection.create_table(...) # # active_record_1 now automatically released # end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error! # end diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index dbc5ac02f5..c945e9959e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -23,7 +23,7 @@ module ConnectionAdapters # :nodoc: # and +:limit+ options, etc. # # 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. # # Most of the methods in the adapter are useful during migrations. Most diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index eaf1ca3cf0..dad3354ef2 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -377,8 +377,8 @@ def type_caster # :nodoc: end def cached_find_by_statement(key, &block) # :nodoc: - cache = @find_by_statement_cache[connection.prepared_statements] - cache.compute_if_absent(key) { StatementCache.create(connection, &block) } + cache = @find_by_statement_cache[lease_connection.prepared_statements] + cache.compute_if_absent(key) { StatementCache.create(lease_connection, &block) } end private @@ -431,7 +431,7 @@ def cached_find_by(keys, values) } begin - statement.execute(values.flatten, connection).first + statement.execute(values.flatten, lease_connection).first rescue TypeError raise ActiveRecord::StatementInvalid end diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index 0e1adc83f5..8d58b2155d 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -58,7 +58,7 @@ def initialize(message = nil, connection_pool: nil) end # 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). class ConnectionNotEstablished < AdapterError def initialize(message = nil, connection_pool: nil) diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb index 53dbf4ccac..20e939656d 100644 --- a/activerecord/lib/active_record/explain.rb +++ b/activerecord/lib/active_record/explain.rb @@ -17,16 +17,17 @@ def collecting_queries_for_explain # :nodoc: # Makes the adapter execute EXPLAIN for the tuples of queries and bindings. # Returns a formatted string ready to be logged. def exec_explain(queries, options = []) # :nodoc: - str = queries.map do |sql, binds| - msg = +"#{build_explain_clause(options)} #{sql}" - unless binds.empty? - msg << " " - msg << binds.map { |attr| render_bind(attr) }.inspect - end - msg << "\n" - msg << connection.explain(sql, binds, options) - end.join("\n") - + str = with_connection do |c| + queries.map do |sql, binds| + msg = +"#{build_explain_clause(c, options)} #{sql}" + unless binds.empty? + msg << " " + msg << binds.map { |attr| render_bind(c, attr) }.inspect + end + msg << "\n" + msg << c.explain(sql, binds, options) + end.join("\n") + end # Overriding inspect to be more human readable, especially in the console. def str.inspect self @@ -36,7 +37,7 @@ def str.inspect end private - def render_bind(attr) + def render_bind(connection, attr) if ActiveModel::Attribute === attr value = if attr.type.binary? && attr.value "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" @@ -51,7 +52,7 @@ def render_bind(attr) [attr&.name, value] end - def build_explain_clause(options = []) + def build_explain_clause(connection, options = []) if connection.respond_to?(:build_explain_clause, true) connection.build_explain_clause(options) else diff --git a/activerecord/lib/active_record/future_result.rb b/activerecord/lib/active_record/future_result.rb index 6b1c9ab3c8..fdb778aa68 100644 --- a/activerecord/lib/active_record/future_result.rb +++ b/activerecord/lib/active_record/future_result.rb @@ -143,7 +143,9 @@ def execute_or_wait start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) @mutex.synchronize do if pending? - execute_query(@pool.connection) + @pool.with_connection do |connection| + execute_query(connection) + end else @lock_wait = (Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - start) end diff --git a/activerecord/lib/active_record/insert_all.rb b/activerecord/lib/active_record/insert_all.rb index a53d906e8b..41742d3ac7 100644 --- a/activerecord/lib/active_record/insert_all.rb +++ b/activerecord/lib/active_record/insert_all.rb @@ -8,7 +8,7 @@ class InsertAll # :nodoc: 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) - @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 @record_timestamps = record_timestamps.nil? ? model.record_timestamps : record_timestamps diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb index ae48bfce94..1efb9d4e34 100644 --- a/activerecord/lib/active_record/integration.rb +++ b/activerecord/lib/active_record/integration.rb @@ -178,7 +178,7 @@ def collection_cache_key(collection = all, timestamp_column = :updated_at) # :no def can_use_fast_cache_version?(timestamp) timestamp.is_a?(String) && cache_timestamp_format == :usec && - self.class.connection.default_timezone == :utc && + self.class.lease_connection.default_timezone == :utc && !updated_at_came_from_user? end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index f1f0eff4bd..1567913e08 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -374,7 +374,7 @@ def sequence_name def reset_sequence_name # :nodoc: @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 # 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 # corresponding sequence before the insert statement. def prefetch_primary_key? - connection.prefetch_primary_key?(table_name) + lease_connection.prefetch_primary_key?(table_name) end # Returns the next value that will be used as the primary key on # an insert statement. def next_sequence_value - connection.next_sequence_value(sequence_name) + lease_connection.next_sequence_value(sequence_name) end # Indicates whether the table associated with this class exists @@ -433,7 +433,7 @@ def columns def _returning_columns_for_insert # :nodoc: @_returning_columns_for_insert ||= begin 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 auto_populated_columns.empty? ? Array(primary_key) : auto_populated_columns @@ -518,7 +518,7 @@ def content_columns # end # end def reset_column_information - connection.clear_cache! + lease_connection.clear_cache! ([self] + descendants).each(&:undefine_attribute_methods) schema_cache.clear_data_source_cache!(table_name) @@ -613,7 +613,7 @@ def compute_table_name end 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) type = type.to_immutable_string diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index a77f50a8e9..474bbd2cb2 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -581,16 +581,18 @@ def _insert_record(values, returning) # :nodoc: im = Arel::InsertManager.new(arel_table) - if values.empty? - im.insert(connection.empty_insert_statement_value(primary_key)) - else - im.insert(values.transform_keys { |name| arel_table[name] }) - end + with_connection do |c| + if values.empty? + im.insert(c.empty_insert_statement_value(primary_key)) + else + im.insert(values.transform_keys { |name| arel_table[name] }) + end - connection.insert( - im, "#{self} Create", primary_key || false, primary_key_value, - returning: returning - ) + c.insert( + im, "#{self} Create", primary_key || false, primary_key_value, + returning: returning + ) + end end 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.wheres = constraints - connection.update(um, "#{self} Update") + with_connection do |c| + c.update(um, "#{self} Update") + end end def _delete_record(constraints) # :nodoc: @@ -623,7 +627,9 @@ def _delete_record(constraints) # :nodoc: dm = Arel::DeleteManager.new(arel_table) dm.wheres = constraints - connection.delete(dm, "#{self} Destroy") + with_connection do |c| + c.delete(dm, "#{self} Destroy") + end end private @@ -1069,7 +1075,7 @@ def toggle!(attribute) # end # def reload(options = nil) - self.class.connection.clear_query_cache + self.class.connection_pool.clear_query_cache fresh_object = if apply_scoping?(options) _find_record((options || {}).merge(all_queries: true)) diff --git a/activerecord/lib/active_record/query_cache.rb b/activerecord/lib/active_record/query_cache.rb index 3376d888d3..2e12787724 100644 --- a/activerecord/lib/active_record/query_cache.rb +++ b/activerecord/lib/active_record/query_cache.rb @@ -42,7 +42,7 @@ def self.complete(pools) end 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 diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index 50cedd445f..18a3f92c8e 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -59,7 +59,7 @@ def async_find_by_sql(sql, binds = [], preparable: nil, &block) end 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 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. 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 # Same as #count_by_sql but perform the query asynchronously and returns an ActiveRecord::Promise. 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 diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 717f28af26..2733a890bf 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -265,7 +265,7 @@ def find_or_create_by!(attributes, &block) def create_or_find_by(attributes, &block) transaction(requires_new: true) { create(attributes, &block) } rescue ActiveRecord::RecordNotUnique - if connection.transaction_open? + if lease_connection.transaction_open? where(attributes).lock.find_by!(attributes) else find_by!(attributes) @@ -278,7 +278,7 @@ def create_or_find_by(attributes, &block) def create_or_find_by!(attributes, &block) transaction(requires_new: true) { create!(attributes, &block) } rescue ActiveRecord::RecordNotUnique - if connection.transaction_open? + if lease_connection.transaction_open? where(attributes).lock.find_by!(attributes) else find_by!(attributes) @@ -468,28 +468,30 @@ def compute_cache_version(timestamp_column) # :nodoc: else collection = eager_loading? ? apply_join_dependency : self - column = connection.visitor.compile(table[timestamp_column]) - select_values = "COUNT(*) AS #{adapter_class.quote_column_name("size")}, MAX(%s) AS timestamp" + with_connection do |c| + 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? - query = collection.select("#{column} AS collection_cache_key_timestamp") - query._select!(table[Arel.star]) if distinct_value && collection.select_values.empty? - subquery_alias = "subquery_for_cache_key" - subquery_column = "#{subquery_alias}.collection_cache_key_timestamp" - arel = query.build_subquery(subquery_alias, select_values % subquery_column) - else - query = collection.unscope(:order) - query.select_values = [select_values % column] - arel = query.arel - end + if collection.has_limit_or_offset? + query = collection.select("#{column} AS collection_cache_key_timestamp") + query._select!(table[Arel.star]) if distinct_value && collection.select_values.empty? + subquery_alias = "subquery_for_cache_key" + subquery_column = "#{subquery_alias}.collection_cache_key_timestamp" + arel = query.build_subquery(subquery_alias, select_values % subquery_column) + else + query = collection.unscope(:order) + query.select_values = [select_values % column] + arel = query.arel + end - size, timestamp = connection.select_rows(arel, nil).first + size, timestamp = c.select_rows(arel, nil).first - if size - column_type = klass.type_for_attribute(timestamp_column) - timestamp = column_type.deserialize(timestamp) - else - size = 0 + if size + column_type = klass.type_for_attribute(timestamp_column) + timestamp = column_type.deserialize(timestamp) + else + size = 0 + end end end @@ -599,7 +601,9 @@ def update_all(updates) table[primary_key] end 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 def update(id = :all, attributes) # :nodoc: @@ -738,7 +742,9 @@ def delete_all end 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 # 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 def load_async - return load if !connection.async_enabled? + with_connection do |c| + return load if !c.async_enabled? - unless loaded? - result = exec_main_query(async: connection.current_transaction.closed?) + unless loaded? + result = exec_main_query(async: c.current_transaction.closed?) - if result.is_a?(Array) - @records = result - else - @future_result = result + if result.is_a?(Array) + @records = result + else + @future_result = result + end + @loaded = true end - @loaded = true end self @@ -852,8 +860,9 @@ def to_sql relation.to_sql end else - conn = klass.connection - conn.unprepared_statement { conn.to_sql(arel) } + klass.with_connection do |conn| + conn.unprepared_statement { conn.to_sql(arel) } + end end end @@ -938,7 +947,7 @@ def has_limit_or_offset? # :nodoc: end 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 class StrictLoadingScope # :nodoc: @@ -1062,13 +1071,15 @@ def exec_main_query(async: false) if where_clause.contradiction? [].freeze elsif eager_loading? - apply_join_dependency do |relation, join_dependency| - if relation.null_relation? - [].freeze - else - relation = join_dependency.apply_column_aliases(relation) - @_join_dependency = join_dependency - connection.select_all(relation.arel, "SQL", async: async) + with_connection do |c| + apply_join_dependency do |relation, join_dependency| + if relation.null_relation? + [].freeze + else + relation = join_dependency.apply_column_aliases(relation) + @_join_dependency = join_dependency + c.select_all(relation.arel, "SQL", async: async) + end end end else diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 378a655e4e..620f99826a 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -310,7 +310,9 @@ def pluck(*column_names) if where_clause.contradiction? ActiveRecord::Result.empty(async: @async) 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 result.then do |result| @@ -385,7 +387,9 @@ def ids ActiveRecord::Result.empty else 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 @@ -474,7 +478,9 @@ def execute_simple_calculation(operation, column_name, distinct) # :nodoc: ActiveRecord::Result.empty else 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 @@ -500,10 +506,10 @@ def execute_grouped_calculation(operation, column_name, distinct) # :nodoc: end 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| - 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) } 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.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| if association key_ids = calculated_data.collect { |row| row[group_aliases.first] } diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index cbb863429f..6fa99c6d94 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -374,7 +374,11 @@ def exists?(conditions = :none) relation = construct_relation_for_exists(conditions) 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 # 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 - klass.connection.distinct_relation_for_primary_key(relation) + klass.with_connection do |c| + c.distinct_relation_for_primary_key(relation) + end end end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index e031c40199..00425d93d3 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1653,7 +1653,7 @@ def build_arel(aliases = nil) arel.where(where_clause.ast) unless where_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.group(*arel_columns(group_values.uniq)) unless group_values.empty? diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index c280d895ce..3c6be4950a 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -8,7 +8,7 @@ module ActiveRecord # {#exec_query}[rdoc-ref:ConnectionAdapters::DatabaseStatements#exec_query] # 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 # => # # # # Get the column names of the result: diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index 3392a2609c..74dc1fac99 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -169,7 +169,7 @@ def sanitize_sql_array(ary) elsif statement.blank? statement else - statement % values.collect { |value| connection.quote_string(value.to_s) } + statement % values.collect { |value| lease_connection.quote_string(value.to_s) } end end @@ -196,13 +196,13 @@ def disallow_raw_sql!(args, permit: adapter_class.column_name_matcher) # :nodoc: def replace_bind_variables(statement, values) raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) bound = values.dup - c = connection + c = lease_connection statement.gsub(/\?/) do replace_bind_variable(bound.shift, c) end end - def replace_bind_variable(value, c = connection) + def replace_bind_variable(value, c = lease_connection) if ActiveRecord::Relation === value value.to_sql else @@ -224,7 +224,7 @@ def replace_named_bind_variables(statement, bind_vars) 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) values = value.map { |v| v.respond_to?(:id_for_database) ? v.id_for_database : v } if values.empty? diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb index aec6343a17..6c7359b77b 100644 --- a/activerecord/lib/active_record/statement_cache.rb +++ b/activerecord/lib/active_record/statement_cache.rb @@ -4,14 +4,14 @@ module ActiveRecord # 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: # - # cache = StatementCache.create(Book.connection) do |params| + # cache = StatementCache.create(ClothingItem.lease_connection) do |params| # Book.where(name: "my book").where("author_id > 3") # end # # The cached statement is executed by using the # {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 # {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 # block parameter. # - # cache = StatementCache.create(Book.connection) do |params| + # cache = StatementCache.create(ClothingItem.lease_connection) do |params| # Book.where(name: params.bind) # end # # 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 Substitute; end # :nodoc: diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 0a75f20b80..35192fc740 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -489,7 +489,7 @@ def load_seed # Dumps the schema cache in YAML format for the connection into the file # # ==== Examples - # ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.connection, "tmp/schema_dump.yaml") + # ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.lease_connection, "tmp/schema_dump.yaml") def dump_schema_cache(conn_or_pool, filename) conn_or_pool.schema_cache.dump_to(filename) end @@ -509,9 +509,9 @@ def with_temporary_pool_for_each(env: ActiveRecord::Tasks::DatabaseTasks.env, na 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| - yield pool.connection + pool.with_connection(&block) end end @@ -520,7 +520,7 @@ def migration_class # :nodoc: end def migration_connection # :nodoc: - migration_class.connection + migration_class.lease_connection end def migration_connection_pool # :nodoc: diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb index 64c1952970..ea581b69c7 100644 --- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb @@ -71,7 +71,7 @@ def structure_load(filename, extra_flags) attr_reader :db_config, :configuration_hash def connection - ActiveRecord::Base.connection + ActiveRecord::Base.lease_connection end def establish_connection(config = db_config) diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb index 5bd4f8da2f..40cd370f48 100644 --- a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb @@ -88,7 +88,7 @@ def structure_load(filename, extra_flags) attr_reader :db_config, :configuration_hash def connection - ActiveRecord::Base.connection + ActiveRecord::Base.lease_connection end def establish_connection(config = db_config) diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index d568c41307..b97e1968f2 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -66,7 +66,7 @@ def structure_load(filename, extra_flags) attr_reader :db_config, :root def connection - ActiveRecord::Base.connection + ActiveRecord::Base.lease_connection end def establish_connection(config = db_config) diff --git a/activerecord/lib/active_record/test_fixtures.rb b/activerecord/lib/active_record/test_fixtures.rb index 7a3a466231..18028b8d9a 100644 --- a/activerecord/lib/active_record/test_fixtures.rb +++ b/activerecord/lib/active_record/test_fixtures.rb @@ -157,7 +157,7 @@ def setup_transactional_fixtures @fixture_connection_pools = ActiveRecord::Base.connection_handler.connection_pool_list(:writing) @fixture_connection_pools.each do |pool| pool.pin_connection!(lock_threads) - pool.connection + pool.lease_connection end # 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) pool.pin_connection!(lock_threads) - pool.connection + pool.lease_connection @fixture_connection_pools << pool end end diff --git a/activerecord/lib/active_record/testing/query_assertions.rb b/activerecord/lib/active_record/testing/query_assertions.rb index f7cb0bff97..23ba780957 100644 --- a/activerecord/lib/active_record/testing/query_assertions.rb +++ b/activerecord/lib/active_record/testing/query_assertions.rb @@ -16,7 +16,7 @@ module QueryAssertions # assert_queries_count(1, include_schema: true) { Post.columns } # def assert_queries_count(count = nil, include_schema: false, &block) - ActiveRecord::Base.connection.materialize_transactions + ActiveRecord::Base.lease_connection.materialize_transactions counter = SQLCounter.new 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 } # 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 ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index be1ea2d873..a8b9ace2fa 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -75,7 +75,7 @@ def all_timestamp_attributes_in_model end 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 protected diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index 2a3178c462..102a909881 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -208,9 +208,9 @@ module Transactions # database error will occur because the savepoint has already been # automatically released. The following example demonstrates the problem: # - # Model.connection.transaction do # BEGIN - # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 - # Model.connection.create_table(...) # active_record_1 now automatically released + # Model.lease_connection.transaction do # BEGIN + # Model.lease_connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 + # Model.lease_connection.create_table(...) # active_record_1 now automatically released # end # RELEASE SAVEPOINT active_record_1 # # ^^^^ BOOM! database error! # end @@ -394,7 +394,7 @@ def rolledback!(force_restore_state: false, should_run_callbacks: true) # :nodoc # instance. def with_transaction_returning_status status = nil - connection = self.class.connection + connection = self.class.lease_connection ensure_finalize = !connection.transaction_open? 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 # callbacks can be called. 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 def has_transactional_callbacks? diff --git a/activerecord/lib/active_record/type_caster/connection.rb b/activerecord/lib/active_record/type_caster/connection.rb index 7af11e5256..0626a7f7cb 100644 --- a/activerecord/lib/active_record/type_caster/connection.rb +++ b/activerecord/lib/active_record/type_caster/connection.rb @@ -19,7 +19,7 @@ def type_for_attribute(attr_name) if schema_cache.data_source_exists?(table_name) column = schema_cache.columns_hash(table_name)[attr_name.to_s] if column - type = @klass.connection.lookup_cast_type_from_column(column) + type = @klass.lease_connection.lookup_cast_type_from_column(column) end end diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index 35df4e4eb2..b9d5861e45 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -114,12 +114,12 @@ def build_relation(klass, attribute, value) return relation.none! if bind.unboundable? 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] - klass.connection.case_sensitive_comparison(attr, bind) + klass.lease_connection.case_sensitive_comparison(attr, bind) else # 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 diff --git a/activerecord/lib/arel/nodes/node.rb b/activerecord/lib/arel/nodes/node.rb index 185b0aa3dc..5c50023e8f 100644 --- a/activerecord/lib/arel/nodes/node.rb +++ b/activerecord/lib/arel/nodes/node.rb @@ -147,7 +147,7 @@ def invert # Maybe we should just use `Table.engine`? :'( def to_sql(engine = Table.engine) collector = Arel::Collectors::SQLString.new - collector = engine.connection.visitor.accept self, collector + collector = engine.lease_connection.visitor.accept self, collector collector.value end diff --git a/activerecord/lib/arel/tree_manager.rb b/activerecord/lib/arel/tree_manager.rb index 7be35c697b..0ba1e8aa33 100644 --- a/activerecord/lib/arel/tree_manager.rb +++ b/activerecord/lib/arel/tree_manager.rb @@ -52,7 +52,7 @@ def to_dot def to_sql(engine = Table.engine) collector = Arel::Collectors::SQLString.new - collector = engine.connection.visitor.accept @ast, collector + collector = engine.lease_connection.visitor.accept @ast, collector collector.value end diff --git a/activerecord/test/activejob/destroy_association_async_test.rb b/activerecord/test/activejob/destroy_association_async_test.rb index 06edbf03af..d08520318c 100644 --- a/activerecord/test/activejob/destroy_association_async_test.rb +++ b/activerecord/test/activejob/destroy_association_async_test.rb @@ -72,7 +72,7 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase assert_equal 2, delete_sqls.count 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 ensure Sharded::Tag.delete_all @@ -185,7 +185,7 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase delete_sqls = sql.select { |sql| sql.start_with?("DELETE") } 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 Sharded::BlogPostDestroyAsync.delete_all Sharded::CommentDestroyAsync.delete_all @@ -307,7 +307,7 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase assert_equal 2, delete_sqls.count 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 ensure Sharded::CommentDestroyAsync.delete_all diff --git a/activerecord/test/cases/active_record_schema_test.rb b/activerecord/test/cases/active_record_schema_test.rb index 695e156c34..91c4a4ff7c 100644 --- a/activerecord/test/cases/active_record_schema_test.rb +++ b/activerecord/test/cases/active_record_schema_test.rb @@ -8,7 +8,7 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase setup do @original_verbose = ActiveRecord::Migration.verbose ActiveRecord::Migration.verbose = false - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @pool = ActiveRecord::Base.connection_pool @schema_migration = @pool.schema_migration @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) 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 ActiveRecord::Schema.define do 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) 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 ActiveRecord::Schema.define do create_table :has_timestamps diff --git a/activerecord/test/cases/active_record_test.rb b/activerecord/test/cases/active_record_test.rb index 1402c92477..d49621576d 100644 --- a/activerecord/test/cases/active_record_test.rb +++ b/activerecord/test/cases/active_record_test.rb @@ -8,13 +8,13 @@ class ActiveRecordTest < ActiveRecord::TestCase unless in_memory_db? test ".disconnect_all! closes all connections" do - ActiveRecord::Base.connection.connect! + ActiveRecord::Base.lease_connection.connect! assert_predicate ActiveRecord::Base, :connected? ActiveRecord.disconnect_all! assert_not_predicate ActiveRecord::Base, :connected? - ActiveRecord::Base.connection.connect! + ActiveRecord::Base.lease_connection.connect! assert_predicate ActiveRecord::Base, :connected? end end diff --git a/activerecord/test/cases/adapter_prevent_writes_test.rb b/activerecord/test/cases/adapter_prevent_writes_test.rb index 6d05d746c9..b1048588f4 100644 --- a/activerecord/test/cases/adapter_prevent_writes_test.rb +++ b/activerecord/test/cases/adapter_prevent_writes_test.rb @@ -10,7 +10,7 @@ module ActiveRecord class AdapterPreventWritesTest < ActiveRecord::TestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_preventing_writes_predicate @@ -79,7 +79,7 @@ def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes 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 @connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')") diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 3c6690f428..f6e6297dab 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -10,14 +10,14 @@ module ActiveRecord class AdapterTest < ActiveRecord::TestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.materialize_transactions end ## # PostgreSQL does not support null bytes in strings 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 b = Book.create(name: "my \x00 book") 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)) config = ARTest.test_configuration_hashes - ActiveRecord::Base.connection.execute( + ActiveRecord::Base.lease_connection.execute( "SELECT #{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") 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::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 ActiveRecord.disable_prepared_statements = original_prepared_statements 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 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 assert_not_nil error.cause @@ -257,7 +257,7 @@ def test_select_all_always_return_activerecord_result assert result.is_a?(ActiveRecord::Result) end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements def test_select_all_insert_update_delete_with_casted_binds binds = [Event.type_for_attribute("id").serialize(1)] bind_param = Arel::Nodes::BindParam.new(nil) @@ -329,7 +329,7 @@ class AdapterForeignKeyTest < ActiveRecord::TestCase fixtures :fk_test_has_pk def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end 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 def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_create_with_query_cache @@ -464,19 +464,19 @@ def test_truncate_tables_with_query_cache end # 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/subscriber" def test_reset_empty_table_with_custom_pk 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 end def test_reset_table_with_non_integer_pk Subscriber.delete_all - Subscriber.connection.reset_pk_sequence! "subscribers" + Subscriber.lease_connection.reset_pk_sequence! "subscribers" sub = Subscriber.new(name: "robert drake") sub.id = "bob drake" assert_nothing_raised { sub.save! } @@ -500,7 +500,7 @@ class AdapterConnectionTest < ActiveRecord::TestCase fixtures :posts, :authors, :author_addresses def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection assert_predicate @connection, :active? end @@ -620,7 +620,7 @@ def teardown # Quote string will not verify a broken connection (although it may # reconnect in some cases) - Post.connection.quote_string("") + Post.lease_connection.quote_string("") # Because the connection hasn't been verified since checkout, # and the query cannot safely be retried, the connection will be @@ -853,35 +853,35 @@ def threads(count, times) end end -if ActiveRecord::Base.connection.supports_advisory_locks? +if ActiveRecord::Base.lease_connection.supports_advisory_locks? class AdvisoryLocksEnabledTest < ActiveRecord::TestCase include ConnectionHelper 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| ActiveRecord::Base.establish_connection( 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( 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 -if ActiveRecord::Base.connection.savepoint_errors_invalidate_transactions? +if ActiveRecord::Base.lease_connection.savepoint_errors_invalidate_transactions? class InvalidateTransactionTest < ActiveRecord::TestCase def test_invalidates_transaction_on_rollback_error @invalidated = false - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.transaction do connection.send(:with_raw_connection) do diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/active_schema_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/active_schema_test.rb index e7025f2c0a..9e60a3e60d 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/active_schema_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/active_schema_test.rb @@ -7,8 +7,8 @@ class ActiveSchemaTest < ActiveRecord::AbstractMysqlTestCase include ConnectionHelper def setup - ActiveRecord::Base.connection.send(:default_row_format) - ActiveRecord::Base.connection.singleton_class.class_eval do + ActiveRecord::Base.lease_connection.send(:default_row_format) + ActiveRecord::Base.lease_connection.singleton_class.class_eval do alias_method :execute_without_stub, :execute def execute(sql, name = nil) ActiveSupport::Notifications.instrumenter.instrument( @@ -83,14 +83,14 @@ def test_add_index def test_index_in_create %w(SPATIAL FULLTEXT UNIQUE).each do |type| 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 end assert_match expected, actual end 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 end assert_match expected, actual @@ -100,7 +100,7 @@ def test_index_in_bulk_change %w(SPATIAL FULLTEXT UNIQUE).each do |type| expected = "ALTER TABLE `people` ADD #{type} INDEX `index_people_on_last_name` (`last_name`)" 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 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" 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 end end @@ -119,7 +119,7 @@ def test_drop_table end 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) else error = assert_raises(RuntimeError) { create_database(:matt) } @@ -149,31 +149,31 @@ def test_drop_table_with_specific_database def test_add_timestamps with_real_execute do - ActiveRecord::Base.connection.create_table :delete_me - ActiveRecord::Base.connection.add_timestamps :delete_me, null: true + ActiveRecord::Base.lease_connection.create_table :delete_me + ActiveRecord::Base.lease_connection.add_timestamps :delete_me, null: true assert column_exists?("delete_me", "updated_at", "datetime") assert column_exists?("delete_me", "created_at", "datetime") ensure - ActiveRecord::Base.connection.drop_table :delete_me rescue nil + ActiveRecord::Base.lease_connection.drop_table :delete_me rescue nil end end def test_remove_timestamps 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 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", "created_at", "datetime") ensure - ActiveRecord::Base.connection.drop_table :delete_me rescue nil + ActiveRecord::Base.lease_connection.drop_table :delete_me rescue nil end end 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/ - 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 end @@ -182,7 +182,7 @@ def test_indexes_in_create private 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 remove_method :execute alias_method :execute, :execute_without_stub @@ -190,13 +190,13 @@ def with_real_execute yield ensure - ActiveRecord::Base.connection.singleton_class.class_eval do + ActiveRecord::Base.lease_connection.singleton_class.class_eval do remove_method :execute alias_method :execute, :execute_with_stub end end def method_missing(...) - ActiveRecord::Base.connection.public_send(...) + ActiveRecord::Base.lease_connection.public_send(...) end end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/adapter_prevent_writes_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/adapter_prevent_writes_test.rb index def9061b91..0bf5f76ef4 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/adapter_prevent_writes_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/adapter_prevent_writes_test.rb @@ -7,7 +7,7 @@ class AdapterPreventWritesTest < ActiveRecord::AbstractMysqlTestCase include DdlHelper def setup - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection end def test_errors_when_an_insert_query_is_called_while_preventing_writes diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/auto_increment_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/auto_increment_test.rb index 24931178a3..997fa665c6 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/auto_increment_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/auto_increment_test.rb @@ -7,7 +7,7 @@ class AutoIncrementTest < ActiveRecord::AbstractMysqlTestCase include SchemaDumpingHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/charset_collation_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/charset_collation_test.rb index 17e5d97e0e..317212838d 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/charset_collation_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/charset_collation_test.rb @@ -7,7 +7,7 @@ class CharsetCollationTest < ActiveRecord::AbstractMysqlTestCase include SchemaDumpingHelper 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| t.string :string_ascii_bin, charset: "ascii", collation: "ascii_bin" t.text :text_ucs2_unicode_ci, charset: "ucs2", collation: "ucs2_unicode_ci" diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/connection_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/connection_test.rb index f06c970b81..7203efcde7 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/connection_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/connection_test.rb @@ -10,7 +10,7 @@ def setup super @subscriber = SQLSubscriber.new @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown @@ -37,7 +37,7 @@ def test_no_automatic_reconnection_after_timeout assert_not_predicate @connection, :active? ensure # 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 def test_successful_reconnection_after_timeout_with_manual_reconnect @@ -74,7 +74,7 @@ def test_active_after_disconnect def test_wait_timeout_as_string run_without_connection do |orig_connection| 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 end end @@ -82,7 +82,7 @@ def test_wait_timeout_as_string def test_wait_timeout_as_url run_without_connection do |orig_connection| 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 end end @@ -91,7 +91,7 @@ def test_character_set_connection_is_configured run_without_connection do |orig_connection| configuration_hash = orig_connection.except(:encoding, :collation) 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_results") @@ -107,8 +107,8 @@ def test_collation_connection_is_configured assert_equal "utf8mb4_unicode_ci", @connection.show_variable("collation_connection") assert_equal 1, @connection.query_value("SELECT 'こんにちは' = 'コンニチハ'") - assert_equal "utf8mb4_general_ci", ARUnit2Model.connection.show_variable("collation_connection") - assert_equal 0, ARUnit2Model.connection.query_value("SELECT 'こんにちは' = 'コンニチハ'") + assert_equal "utf8mb4_general_ci", ARUnit2Model.lease_connection.show_variable("collation_connection") + assert_equal 0, ARUnit2Model.lease_connection.query_value("SELECT 'こんにちは' = 'コンニチハ'") end def test_mysql_default_in_strict_mode @@ -119,7 +119,7 @@ def test_mysql_default_in_strict_mode def test_mysql_strict_mode_disabled run_without_connection do |orig_connection| 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 end end @@ -127,8 +127,8 @@ def test_mysql_strict_mode_disabled def test_mysql_strict_mode_specified_default run_without_connection do |orig_connection| ActiveRecord::Base.establish_connection(orig_connection.merge(strict: :default)) - global_sql_mode = ActiveRecord::Base.connection.select_value("SELECT @@GLOBAL.sql_mode") - session_sql_mode = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.sql_mode") + global_sql_mode = ActiveRecord::Base.lease_connection.select_value("SELECT @@GLOBAL.sql_mode") + session_sql_mode = ActiveRecord::Base.lease_connection.select_value("SELECT @@SESSION.sql_mode") assert_equal global_sql_mode, session_sql_mode end end @@ -136,7 +136,7 @@ def test_mysql_strict_mode_specified_default def test_mysql_sql_mode_variable_overrides_strict_mode run_without_connection do |orig_connection| 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 end end @@ -145,14 +145,14 @@ def test_mysql_sql_mode_variable_overrides_strict_mode def test_passing_arbitrary_flags_to_adapter run_without_connection do |orig_connection| 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 def test_passing_flags_by_array_to_adapter run_without_connection do |orig_connection| 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 @@ -160,7 +160,7 @@ def test_passing_flags_by_array_to_adapter def test_mysql_set_session_variable run_without_connection do |orig_connection| 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 end end @@ -168,14 +168,14 @@ def test_mysql_set_session_variable def test_mysql_set_session_variable_to_default run_without_connection do |orig_connection| 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" - session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" + global_mode = ActiveRecord::Base.lease_connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT" + session_mode = ActiveRecord::Base.lease_connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" assert_equal global_mode.rows, session_mode.rows end end def test_logs_name_show_variable - ActiveRecord::Base.connection.materialize_transactions + ActiveRecord::Base.lease_connection.materialize_transactions @subscriber.logged.clear @connection.show_variable "foo" assert_equal "SCHEMA", @subscriber.logged[0][1] diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/datetime_precision_quoting_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/datetime_precision_quoting_test.rb index 5f80d88f4e..9edcc1a2df 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/datetime_precision_quoting_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/datetime_precision_quoting_test.rb @@ -4,7 +4,7 @@ class DatetimePrecisionQuotingTest < ActiveRecord::AbstractMysqlTestCase setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end test "microsecond precision for MySQL gte 5.6.4" do diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/json_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/json_test.rb index 64a79d7fb8..2a30615e38 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/json_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/json_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "cases/json_shared_test_cases" -if ActiveRecord::Base.connection.supports_json? +if ActiveRecord::Base.lease_connection.supports_json? class JSONTest < ActiveRecord::AbstractMysqlTestCase include JSONSharedTestCases self.use_transactional_tests = false diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_boolean_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_boolean_test.rb index 9d5bdd493b..2447b9d92f 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_boolean_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_boolean_test.rb @@ -10,7 +10,7 @@ class BooleanType < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.clear_cache! @connection.create_table("mysql_booleans") do |t| t.boolean "archived" diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_enum_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_enum_test.rb index a1f454ced5..be61b26482 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_enum_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_enum_test.rb @@ -19,7 +19,7 @@ class EnumTest < ActiveRecord::Base end 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 :state, "TINYINT(1)" end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_explain_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_explain_test.rb index 6679f3fddc..41d9eaa947 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_explain_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/mysql_explain_test.rb @@ -66,6 +66,6 @@ def supports_analyze? end def conn - ActiveRecord::Base.connection + ActiveRecord::Base.lease_connection end end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/nested_deadlock_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/nested_deadlock_test.rb index 309fbbd030..86191f1d27 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/nested_deadlock_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/nested_deadlock_test.rb @@ -15,7 +15,7 @@ class Sample < ActiveRecord::Base @abort, Thread.abort_on_exception = Thread.abort_on_exception, false 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.create_table("samples", force: true) do |t| @@ -27,14 +27,14 @@ class Sample < ActiveRecord::Base teardown do 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.report_on_exception = @original_report_on_exception end test "deadlock correctly raises Deadlocked inside nested SavepointTransaction" do - connection = Sample.connection + connection = Sample.lease_connection assert_raises(ActiveRecord::Deadlocked) do barrier = Concurrent::CyclicBarrier.new(2) @@ -182,7 +182,7 @@ def make_parent_transaction_dirty end 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) flunk("current transaction is not a savepoint transaction") end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/quoting_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/quoting_test.rb index 4c1244288a..2386299b9a 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/quoting_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/quoting_test.rb @@ -5,7 +5,7 @@ class QuotingTest < ActiveRecord::AbstractMysqlTestCase def setup super - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection end def test_cast_bound_integer diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_migrations_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_migrations_test.rb index 6d796fc19e..39ff9819b1 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_migrations_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_migrations_test.rb @@ -59,7 +59,7 @@ def with_encoding_utf8mb4 end def connection - @connection ||= ActiveRecord::Base.connection + @connection ||= ActiveRecord::Base.lease_connection end def execute(sql) diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_test.rb index c7d1e92dce..4a011399ef 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/schema_test.rb @@ -10,7 +10,7 @@ class SchemaTest < ActiveRecord::AbstractMysqlTestCase fixtures :posts def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection db = Post.connection_pool.db_config.database table = Post.table_name @db_name = db @@ -108,7 +108,7 @@ def test_drop_temporary_table class MysqlAnsiQuotesTest < ActiveRecord::AbstractMysqlTestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute("SET SESSION sql_mode='ANSI_QUOTES'") end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/set_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/set_test.rb index 649dda5f97..5b8271623f 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/set_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/set_test.rb @@ -10,7 +10,7 @@ class SetTest < ActiveRecord::Base end 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')" end end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/sp_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/sp_test.rb index dc69227e8d..efe186f688 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/sp_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/sp_test.rb @@ -8,8 +8,8 @@ class StoredProcedureTest < ActiveRecord::AbstractMysqlTestCase fixtures :topics def setup - @connection = ActiveRecord::Base.connection - unless ActiveRecord::Base.connection.database_version >= "5.6.0" + @connection = ActiveRecord::Base.lease_connection + unless ActiveRecord::Base.lease_connection.database_version >= "5.6.0" skip("no stored procedure support") end end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/sql_types_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/sql_types_test.rb index 44a81249e0..fda13a68bf 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/sql_types_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/sql_types_test.rb @@ -11,6 +11,6 @@ def test_binary_types end 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 diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/table_options_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/table_options_test.rb index a82391f282..e8140a7a47 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/table_options_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/table_options_test.rb @@ -7,7 +7,7 @@ class TableOptionsTest < ActiveRecord::AbstractMysqlTestCase include SchemaDumpingHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown @@ -92,12 +92,12 @@ def setup def teardown ActiveRecord::Base.logger = @logger_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 end 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 diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/transaction_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/transaction_test.rb index 93852fec6a..1a6c04cdc3 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/transaction_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/transaction_test.rb @@ -15,7 +15,7 @@ class Sample < ActiveRecord::Base @abort, Thread.abort_on_exception = Thread.abort_on_exception, false 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.transaction do @@ -29,14 +29,14 @@ class Sample < ActiveRecord::Base end 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.report_on_exception = @original_report_on_exception end test "raises Deadlocked when a deadlock is encountered" do - connection = Sample.connection + connection = Sample.lease_connection assert_raises(ActiveRecord::Deadlocked) do barrier = Concurrent::CyclicBarrier.new(2) @@ -81,11 +81,11 @@ class Sample < ActiveRecord::Base begin Sample.transaction do 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) end ensure - Sample.connection.execute("SET innodb_lock_wait_timeout = DEFAULT") + Sample.lease_connection.execute("SET innodb_lock_wait_timeout = DEFAULT") latch2.count_down thread.join end @@ -93,7 +93,7 @@ class Sample < ActiveRecord::Base end 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 s = Sample.create!(value: 1) latch1 = Concurrent::CountDownLatch.new @@ -110,11 +110,11 @@ class Sample < ActiveRecord::Base begin Sample.transaction do latch1.wait - Sample.connection.execute("SET max_execution_time = 1") + Sample.lease_connection.execute("SET max_execution_time = 1") Sample.lock.find(s.id) end ensure - Sample.connection.execute("SET max_execution_time = DEFAULT") + Sample.lease_connection.execute("SET max_execution_time = DEFAULT") latch2.count_down thread.join end @@ -132,7 +132,7 @@ class Sample < ActiveRecord::Base Sample.lock.find(s.id) latch.count_down 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'") conn.execute("KILL QUERY #{pid}") end diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/unsigned_type_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/unsigned_type_test.rb index 305c8d7363..e22f5a9867 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/unsigned_type_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/unsigned_type_test.rb @@ -11,7 +11,7 @@ class UnsignedType < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("unsigned_types", force: true) do |t| t.integer :unsigned_integer, unsigned: true t.bigint :unsigned_bigint, unsigned: true diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/virtual_column_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/virtual_column_test.rb index 9ef8d71821..1213374481 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/virtual_column_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/virtual_column_test.rb @@ -3,7 +3,7 @@ require "cases/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 include SchemaDumpingHelper @@ -13,7 +13,7 @@ class VirtualColumn < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :virtual_columns, force: true do |t| t.string :name t.virtual :upper_name, type: :string, as: "UPPER(`name`)" diff --git a/activerecord/test/cases/adapters/abstract_mysql_adapter/warnings_test.rb b/activerecord/test/cases/adapters/abstract_mysql_adapter/warnings_test.rb index 95d2195083..996cbb44c1 100644 --- a/activerecord/test/cases/adapters/abstract_mysql_adapter/warnings_test.rb +++ b/activerecord/test/cases/adapters/abstract_mysql_adapter/warnings_test.rb @@ -5,7 +5,7 @@ class WarningsTest < ActiveRecord::AbstractMysqlTestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @original_db_warnings_action = :ignore end diff --git a/activerecord/test/cases/adapters/mysql2/check_constraint_quoting_test.rb b/activerecord/test/cases/adapters/mysql2/check_constraint_quoting_test.rb index a6e58a5602..9421657b05 100644 --- a/activerecord/test/cases/adapters/mysql2/check_constraint_quoting_test.rb +++ b/activerecord/test/cases/adapters/mysql2/check_constraint_quoting_test.rb @@ -3,12 +3,12 @@ require "cases/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 include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "trades", force: true do |t| t.string :name end @@ -25,7 +25,7 @@ def test_check_constraint_no_duplicate_expression_quoting assert_equal 1, check_constraints.size expression = check_constraints.first.expression - if ActiveRecord::Base.connection.mariadb? + if ActiveRecord::Base.lease_connection.mariadb? assert_equal "`name` <> 'forbidden_string'", expression else assert_equal "`name` <> _utf8mb4'forbidden_string'", expression diff --git a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb index 6cc9c23039..227187e766 100644 --- a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb @@ -7,7 +7,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase include DdlHelper def setup - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection @original_db_warnings_action = :ignore end @@ -265,7 +265,7 @@ def test_read_timeout_exception ActiveRecord::Base.establish_connection( db_config.configuration_hash.merge("read_timeout" => 1) ) - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection error = assert_raises(ActiveRecord::AdapterTimeout) do connection.execute("SELECT SLEEP(2)") diff --git a/activerecord/test/cases/adapters/mysql2/mysql2_rake_test.rb b/activerecord/test/cases/adapters/mysql2/mysql2_rake_test.rb index 2fd1cfd029..cba098b4ab 100644 --- a/activerecord/test/cases/adapters/mysql2/mysql2_rake_test.rb +++ b/activerecord/test/cases/adapters/mysql2/mysql2_rake_test.rb @@ -29,7 +29,7 @@ def test_establishes_connection_without_database mock.expect(:call, nil, [adapter: "mysql2", database: nil]) 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::Tasks::DatabaseTasks.create(db_config) 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 with_stubbed_connection_establish_connection do - ActiveRecord::Base.connection.stub( + ActiveRecord::Base.lease_connection.stub( :create_database, proc { raise ActiveRecord::DatabaseAlreadyExists } ) do @@ -90,7 +90,7 @@ def test_create_when_database_exists_outputs_info_to_stderr private def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end end @@ -139,7 +139,7 @@ def teardown def test_establishes_connection_to_mysql_database 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( ActiveRecord::Base, :establish_connection, @@ -169,7 +169,7 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout private def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end end @@ -186,7 +186,7 @@ def setup def test_establishes_connection_without_database 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 ActiveRecord::Tasks::DatabaseTasks.purge(db_config) end @@ -217,7 +217,7 @@ def test_recreates_database_with_the_given_options private def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end end @@ -232,7 +232,7 @@ def setup end def test_db_retrieves_charset - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :charset) do ActiveRecord::Tasks::DatabaseTasks.charset @configuration end @@ -250,7 +250,7 @@ def setup end def test_db_retrieves_collation - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :collation) do ActiveRecord::Tasks::DatabaseTasks.collation @configuration end @@ -313,7 +313,7 @@ def test_structure_dump_with_hash_extra_flags_for_the_correct_driver def test_structure_dump_with_ignore_tables 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 assert_called_with( Kernel, diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb index 07a83ad4a5..c9f6a5f7df 100644 --- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb @@ -4,7 +4,7 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase def setup - ActiveRecord::Base.connection.materialize_transactions + ActiveRecord::Base.lease_connection.materialize_transactions ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do def execute(sql, name = nil) sql end @@ -112,6 +112,6 @@ def test_remove_index_with_wrong_option private def method_missing(...) - ActiveRecord::Base.connection.public_send(...) + ActiveRecord::Base.lease_connection.public_send(...) end end diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index a1ac3f76ae..e894e511ec 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -12,7 +12,7 @@ class PgArray < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection enable_extension!("hstore", @connection) @@ -269,7 +269,7 @@ def test_quoting_non_standard_delimiters oid = ActiveRecord::ConnectionAdapters::PostgreSQL::OID comma_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(semicolon_delim.serialize(strings)) diff --git a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb index c8e728bbb6..9dbd78ac1a 100644 --- a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb @@ -11,7 +11,7 @@ class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase class PostgresqlBitString < ActiveRecord::Base; end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("postgresql_bit_strings", force: true) do |t| t.bit :a_bit, default: "00000011", limit: 8 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 end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements 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_varying: "F" } diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb index b0cc301c69..adcf12ca51 100644 --- a/activerecord/test/cases/adapters/postgresql/bytea_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb @@ -11,7 +11,7 @@ class ByteaDataType < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.transaction do @connection.create_table("bytea_data_type") do |t| t.binary "payload" @@ -87,7 +87,7 @@ def test_via_to_sql def test_via_to_sql_with_complicating_connection 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 escape_string_warning = off") end.join diff --git a/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb b/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb index 7b12b2c3b6..0c2bb5abfa 100644 --- a/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb +++ b/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb @@ -6,7 +6,7 @@ class PostgresqlCaseInsensitiveTest < ActiveRecord::PostgreSQLTestCase class Default < ActiveRecord::Base; end def test_case_insensitiveness - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection attr = Default.arel_table[:char1] comparison = connection.case_insensitive_comparison(attr, nil) diff --git a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb index 3842d1b65e..13e8c533c0 100644 --- a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb @@ -9,7 +9,7 @@ class PGChangeSchemaTest < ActiveRecord::PostgreSQLTestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection connection.create_table(:strings) do |t| t.string :somedate end diff --git a/activerecord/test/cases/adapters/postgresql/citext_test.rb b/activerecord/test/cases/adapters/postgresql/citext_test.rb index 241b2bf72e..c1511ce050 100644 --- a/activerecord/test/cases/adapters/postgresql/citext_test.rb +++ b/activerecord/test/cases/adapters/postgresql/citext_test.rb @@ -10,7 +10,7 @@ class Citext < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection enable_extension!("citext", @connection) diff --git a/activerecord/test/cases/adapters/postgresql/collation_test.rb b/activerecord/test/cases/adapters/postgresql/collation_test.rb index 7468f4c4f8..9aff9fd6d9 100644 --- a/activerecord/test/cases/adapters/postgresql/collation_test.rb +++ b/activerecord/test/cases/adapters/postgresql/collation_test.rb @@ -7,7 +7,7 @@ class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :postgresql_collations, force: true do |t| t.string :string_c, collation: "C" t.text :text_posix, collation: "POSIX" diff --git a/activerecord/test/cases/adapters/postgresql/composite_test.rb b/activerecord/test/cases/adapters/postgresql/composite_test.rb index 683066cdb3..1f6f649480 100644 --- a/activerecord/test/cases/adapters/postgresql/composite_test.rb +++ b/activerecord/test/cases/adapters/postgresql/composite_test.rb @@ -13,7 +13,7 @@ class PostgresqlComposite < ActiveRecord::Base def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.transaction do @connection.execute <<~SQL CREATE TYPE full_address AS diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index ced2dfa384..aa7adf4a36 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -13,7 +13,7 @@ class NonExistentTable < ActiveRecord::Base def setup super @subscriber = SQLSubscriber.new - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.materialize_transactions @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) end @@ -53,7 +53,7 @@ def test_connection_options NonExistentTable.establish_connection(params) # 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 ensure NonExistentTable.remove_connection @@ -126,7 +126,7 @@ def test_schema_names_logs_name assert_equal "SCHEMA", @subscriber.logged[0][1] end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements def test_statement_key_is_logged bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new) @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? ensure # 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 def test_set_session_variable_true run_without_connection do |orig_connection| 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 end end @@ -159,7 +159,7 @@ def test_set_session_variable_true def test_set_session_variable_false run_without_connection do |orig_connection| 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 end end @@ -181,7 +181,7 @@ def test_set_session_variable_default def test_set_session_timezone run_without_connection do |orig_connection| 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 diff --git a/activerecord/test/cases/adapters/postgresql/create_unlogged_tables_test.rb b/activerecord/test/cases/adapters/postgresql/create_unlogged_tables_test.rb index d7f7f07719..12d41c530e 100644 --- a/activerecord/test/cases/adapters/postgresql/create_unlogged_tables_test.rb +++ b/activerecord/test/cases/adapters/postgresql/create_unlogged_tables_test.rb @@ -19,7 +19,7 @@ class Thing < ActiveRecord::Base def setup @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 end diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index 6eebf5338a..c0d111de4b 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -17,7 +17,7 @@ class PostgresqlLtree < ActiveRecord::Base class PostgresqlDataTypeTest < ActiveRecord::PostgreSQLTestCase 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')") @first_time = PostgresqlTime.find(1) @@ -75,7 +75,7 @@ class PostgresqlInternalDataTypeTest < ActiveRecord::PostgreSQLTestCase include DdlHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_name_column_type diff --git a/activerecord/test/cases/adapters/postgresql/deferred_constraints_test.rb b/activerecord/test/cases/adapters/postgresql/deferred_constraints_test.rb index 079aa9edc3..a97a199c8a 100644 --- a/activerecord/test/cases/adapters/postgresql/deferred_constraints_test.rb +++ b/activerecord/test/cases/adapters/postgresql/deferred_constraints_test.rb @@ -5,7 +5,7 @@ class PostgresqlDeferredConstraintsTest < ActiveRecord::PostgreSQLTestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @fk = @connection.foreign_keys("authors").first.name @other_fk = @connection.foreign_keys("lessons_students").first.name end diff --git a/activerecord/test/cases/adapters/postgresql/domain_test.rb b/activerecord/test/cases/adapters/postgresql/domain_test.rb index eeaad94c27..0f740539f6 100644 --- a/activerecord/test/cases/adapters/postgresql/domain_test.rb +++ b/activerecord/test/cases/adapters/postgresql/domain_test.rb @@ -11,7 +11,7 @@ class PostgresqlDomain < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.transaction do @connection.execute "CREATE DOMAIN custom_money as numeric(8,2)" @connection.create_table("postgresql_domains") do |t| diff --git a/activerecord/test/cases/adapters/postgresql/enum_test.rb b/activerecord/test/cases/adapters/postgresql/enum_test.rb index 99dd568f15..6cea300bed 100644 --- a/activerecord/test/cases/adapters/postgresql/enum_test.rb +++ b/activerecord/test/cases/adapters/postgresql/enum_test.rb @@ -20,7 +20,7 @@ class PostgresqlEnum < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.transaction do @connection.create_enum("mood", ["sad", "ok", "happy"]) @connection.create_table("postgresql_enums") do |t| diff --git a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb index 6366c0ec72..8f3ade766a 100644 --- a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb +++ b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb @@ -26,7 +26,7 @@ def change def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @pool = ActiveRecord::Base.connection_pool @old_table_name_prefix = ActiveRecord::Base.table_name_prefix diff --git a/activerecord/test/cases/adapters/postgresql/foreign_table_test.rb b/activerecord/test/cases/adapters/postgresql/foreign_table_test.rb index 9a2e687671..a235dea110 100644 --- a/activerecord/test/cases/adapters/postgresql/foreign_table_test.rb +++ b/activerecord/test/cases/adapters/postgresql/foreign_table_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "models/professor" -if ActiveRecord::Base.connection.supports_foreign_tables? +if ActiveRecord::Base.lease_connection.supports_foreign_tables? class ForeignTableTest < ActiveRecord::TestCase self.use_transactional_tests = false @@ -18,7 +18,7 @@ class ForeignProfessorWithPk < ForeignProfessor def setup @professor = Professor.create(name: "Nicola") - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection enable_extension!("postgres_fdw", @connection) foreign_db_config = ARTest.test_configuration_hashes["arunit2"] @@ -52,7 +52,7 @@ def teardown def test_table_exists 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 def test_foreign_tables_are_valid_data_sources diff --git a/activerecord/test/cases/adapters/postgresql/full_text_test.rb b/activerecord/test/cases/adapters/postgresql/full_text_test.rb index 95dee3bf44..6ddec3980d 100644 --- a/activerecord/test/cases/adapters/postgresql/full_text_test.rb +++ b/activerecord/test/cases/adapters/postgresql/full_text_test.rb @@ -8,7 +8,7 @@ class PostgresqlFullTextTest < ActiveRecord::PostgreSQLTestCase class Tsvector < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("tsvectors") do |t| t.tsvector "text_vector" end diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index b3406b66a6..d82e1267e0 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -19,7 +19,7 @@ class PostgresqlPoint < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("postgresql_points") do |t| t.point :x t.point :y, default: [12.2, 13.3] @@ -167,7 +167,7 @@ class PostgresqlGeometricTest < ActiveRecord::PostgreSQLTestCase class PostgresqlGeometric < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("postgresql_geometrics") do |t| t.lseg :a_line_segment t.box :a_box @@ -247,10 +247,10 @@ class PostgreSQLGeometricLineTest < ActiveRecord::PostgreSQLTestCase class PostgresqlLine < ActiveRecord::Base; end setup do - unless ActiveRecord::Base.connection.database_version >= 90400 + unless ActiveRecord::Base.lease_connection.database_version >= 90400 skip("line type is not fully implemented") end - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("postgresql_lines") do |t| t.line :a_line end @@ -293,7 +293,7 @@ class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @table_name = :testings end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 5766d99184..1f95766dda 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -13,7 +13,7 @@ class Hstore < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection enable_extension!("hstore", @connection) diff --git a/activerecord/test/cases/adapters/postgresql/infinity_test.rb b/activerecord/test/cases/adapters/postgresql/infinity_test.rb index c02f2060af..5ec3d76ee1 100644 --- a/activerecord/test/cases/adapters/postgresql/infinity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/infinity_test.rb @@ -9,7 +9,7 @@ class PostgresqlInfinity < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table(:postgresql_infinities) do |t| t.float :float t.datetime :datetime diff --git a/activerecord/test/cases/adapters/postgresql/integer_test.rb b/activerecord/test/cases/adapters/postgresql/integer_test.rb index 3e45b057ff..ba1ab2fec9 100644 --- a/activerecord/test/cases/adapters/postgresql/integer_test.rb +++ b/activerecord/test/cases/adapters/postgresql/integer_test.rb @@ -8,7 +8,7 @@ class PgInteger < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.transaction do @connection.create_table "pg_integers", force: true do |t| diff --git a/activerecord/test/cases/adapters/postgresql/interval_test.rb b/activerecord/test/cases/adapters/postgresql/interval_test.rb index 619480e00c..3cb9fadb83 100644 --- a/activerecord/test/cases/adapters/postgresql/interval_test.rb +++ b/activerecord/test/cases/adapters/postgresql/interval_test.rb @@ -11,7 +11,7 @@ class IntervalDataType < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.transaction do @connection.create_table("interval_data_types") do |t| t.interval "maximum_term" diff --git a/activerecord/test/cases/adapters/postgresql/invertible_migration_test.rb b/activerecord/test/cases/adapters/postgresql/invertible_migration_test.rb index 457749c84d..ba432d9d18 100644 --- a/activerecord/test/cases/adapters/postgresql/invertible_migration_test.rb +++ b/activerecord/test/cases/adapters/postgresql/invertible_migration_test.rb @@ -50,7 +50,7 @@ def change end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end teardown do diff --git a/activerecord/test/cases/adapters/postgresql/ltree_test.rb b/activerecord/test/cases/adapters/postgresql/ltree_test.rb index 62c24fb2d0..f1639c7f43 100644 --- a/activerecord/test/cases/adapters/postgresql/ltree_test.rb +++ b/activerecord/test/cases/adapters/postgresql/ltree_test.rb @@ -10,7 +10,7 @@ class Ltree < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection enable_extension!("ltree", @connection) diff --git a/activerecord/test/cases/adapters/postgresql/money_test.rb b/activerecord/test/cases/adapters/postgresql/money_test.rb index 7e18dce1b9..5c4de69c25 100644 --- a/activerecord/test/cases/adapters/postgresql/money_test.rb +++ b/activerecord/test/cases/adapters/postgresql/money_test.rb @@ -11,7 +11,7 @@ class PostgresqlMoney < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute("set lc_monetary = 'C'") @connection.create_table("postgresql_moneys", force: true) do |t| t.money "wealth" diff --git a/activerecord/test/cases/adapters/postgresql/network_test.rb b/activerecord/test/cases/adapters/postgresql/network_test.rb index 8b62a52796..e6cdf46165 100644 --- a/activerecord/test/cases/adapters/postgresql/network_test.rb +++ b/activerecord/test/cases/adapters/postgresql/network_test.rb @@ -8,7 +8,7 @@ class PostgresqlNetworkTest < ActiveRecord::PostgreSQLTestCase class PostgresqlNetworkAddress < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("postgresql_network_addresses", force: true) do |t| t.inet "inet_address", default: "192.168.1.1" t.cidr "cidr_address", default: "192.168.1.0/24" diff --git a/activerecord/test/cases/adapters/postgresql/numbers_test.rb b/activerecord/test/cases/adapters/postgresql/numbers_test.rb index a1e4a69b07..785ae7988d 100644 --- a/activerecord/test/cases/adapters/postgresql/numbers_test.rb +++ b/activerecord/test/cases/adapters/postgresql/numbers_test.rb @@ -6,7 +6,7 @@ class PostgresqlNumberTest < ActiveRecord::PostgreSQLTestCase class PostgresqlNumber < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("postgresql_numbers", force: true) do |t| t.column "single", "REAL" t.column "double", "DOUBLE PRECISION" diff --git a/activerecord/test/cases/adapters/postgresql/optimizer_hints_test.rb b/activerecord/test/cases/adapters/postgresql/optimizer_hints_test.rb index 23a27b362b..b9ce87275d 100644 --- a/activerecord/test/cases/adapters/postgresql/optimizer_hints_test.rb +++ b/activerecord/test/cases/adapters/postgresql/optimizer_hints_test.rb @@ -8,7 +8,7 @@ class PostgresqlOptimizerHintsTest < ActiveRecord::PostgreSQLTestCase fixtures :posts def setup - enable_extension!("pg_hint_plan", ActiveRecord::Base.connection) + enable_extension!("pg_hint_plan", ActiveRecord::Base.lease_connection) end def test_optimizer_hints diff --git a/activerecord/test/cases/adapters/postgresql/partitions_test.rb b/activerecord/test/cases/adapters/postgresql/partitions_test.rb index 4015bc94f9..960bf298d8 100644 --- a/activerecord/test/cases/adapters/postgresql/partitions_test.rb +++ b/activerecord/test/cases/adapters/postgresql/partitions_test.rb @@ -4,7 +4,7 @@ class PostgreSQLPartitionsTest < ActiveRecord::PostgreSQLTestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown @@ -12,7 +12,7 @@ def teardown end def test_partitions_table_exists - skip unless ActiveRecord::Base.connection.database_version >= 100000 + skip unless ActiveRecord::Base.lease_connection.database_version >= 100000 @connection.create_table :partitioned_events, force: true, id: false, options: "partition by range (issued_at)" do |t| t.timestamp :issued_at diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_prevent_writes_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_prevent_writes_test.rb index 4df9528153..0bd69db7fa 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_prevent_writes_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_prevent_writes_test.rb @@ -11,7 +11,7 @@ class PostgreSQLAdapterPreventWritesTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_errors_when_an_insert_query_is_called_while_preventing_writes diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index 042e26a814..2524018128 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -14,7 +14,7 @@ class PostgreSQLAdapterTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @original_db_warnings_action = :ignore end @@ -477,7 +477,7 @@ def test_reload_type_map_for_newly_defined_types def test_only_reload_type_map_once_for_every_unrecognized_type reset_connection - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.select_all "SELECT 1" # eagerly initialize the connection silence_warnings do @@ -497,7 +497,7 @@ def test_only_reload_type_map_once_for_every_unrecognized_type def test_only_warn_on_first_encounter_of_unrecognized_oid reset_connection - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection warning = capture(:stderr) { connection.select_all "select 'pg_catalog.pg_class'::regclass" diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_rake_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_rake_test.rb index 323a4250f1..89b42968bd 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_rake_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_rake_test.rb @@ -26,7 +26,7 @@ def test_establishes_connection_to_postgresql_database mock.expect(:call, nil, [{ adapter: "postgresql", database: "postgres", schema_search_path: "public" }]) 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::Tasks::DatabaseTasks.create(db_config) end @@ -87,7 +87,7 @@ def test_establishes_connection_to_new_database mock.expect(:call, nil, [{ adapter: "postgresql", database: "postgres", schema_search_path: "public" }]) 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::Tasks::DatabaseTasks.create(db_config) end @@ -97,7 +97,7 @@ def test_establishes_connection_to_new_database end def test_db_create_with_error_prints_message - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do ActiveRecord::Base.stub(:establish_connection, -> * { raise Exception }) do assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration } assert_match "Couldn't create '#{@configuration['database']}' database. Please check your configuration.", $stderr.string @@ -115,7 +115,7 @@ def test_when_database_created_successfully_outputs_info_to_stdout def test_create_when_database_exists_outputs_info_to_stderr with_stubbed_connection_establish_connection do - ActiveRecord::Base.connection.stub( + ActiveRecord::Base.lease_connection.stub( :create_database, proc { raise ActiveRecord::DatabaseAlreadyExists } ) do @@ -128,7 +128,7 @@ def test_create_when_database_exists_outputs_info_to_stderr private def with_stubbed_connection_establish_connection(&block) - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do ActiveRecord::Base.stub(:establish_connection, nil, &block) end end @@ -150,7 +150,7 @@ def teardown end def test_establishes_connection_to_postgresql_database - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called_with( ActiveRecord::Base, :establish_connection, @@ -187,7 +187,7 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout private def with_stubbed_connection_establish_connection(&block) - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do ActiveRecord::Base.stub(:establish_connection, nil, &block) end end @@ -273,7 +273,7 @@ def test_establishes_connection private def with_stubbed_connection(&block) - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end @@ -290,7 +290,7 @@ def encoding; end end def test_db_retrieves_charset - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :encoding) do ActiveRecord::Tasks::DatabaseTasks.charset @configuration end @@ -308,7 +308,7 @@ def setup end def test_db_retrieves_collation - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :collation) do ActiveRecord::Tasks::DatabaseTasks.collation @configuration end @@ -407,7 +407,7 @@ def test_structure_dump_with_hash_extra_flags_for_the_correct_driver end def test_structure_dump_with_ignore_tables - 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 assert_called_with( Kernel, diff --git a/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb b/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb index f7478b50c3..8702f7738e 100644 --- a/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb +++ b/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb @@ -17,7 +17,7 @@ def teardown end def test_select_query_works_even_when_prepared_statements_are_disabled - assert_not Developer.connection.prepared_statements + assert_not Developer.lease_connection.prepared_statements david = developers(:david) diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb index 9f3d14dbdc..9dbbbcce87 100644 --- a/activerecord/test/cases/adapters/postgresql/quoting_test.rb +++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb @@ -7,7 +7,7 @@ module ConnectionAdapters class PostgreSQLAdapter class QuotingTest < ActiveRecord::PostgreSQLTestCase def setup - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection @raise_int_wider_than_64bit = ActiveRecord.raise_int_wider_than_64bit end diff --git a/activerecord/test/cases/adapters/postgresql/range_test.rb b/activerecord/test/cases/adapters/postgresql/range_test.rb index c0d1da4cd3..0d789d26fb 100644 --- a/activerecord/test/cases/adapters/postgresql/range_test.rb +++ b/activerecord/test/cases/adapters/postgresql/range_test.rb @@ -13,7 +13,7 @@ class PostgresqlRangeTest < ActiveRecord::PostgreSQLTestCase include InTimeZone def setup - @connection = PostgresqlRange.connection + @connection = PostgresqlRange.lease_connection @connection.transaction do @connection.execute <<~SQL CREATE TYPE floatrange AS RANGE ( diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb index c00dacc667..c815c7a4c0 100644 --- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb @@ -32,12 +32,12 @@ def execute(sql, name = nil) end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown reset_connection - if ActiveRecord::Base.connection.is_a?(MissingSuperuserPrivileges) + if ActiveRecord::Base.lease_connection.is_a?(MissingSuperuserPrivileges) raise "MissingSuperuserPrivileges patch was not removed" end end diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb index 199b1f392a..13db899bf4 100644 --- a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb +++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb @@ -4,7 +4,7 @@ class PostgresqlRenameTableTest < ActiveRecord::PostgreSQLTestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index fcb0aec81b..b344026af4 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -16,7 +16,7 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase USERS = ["rails_pg_schema_user1", "rails_pg_schema_user2"] def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute "SET search_path TO '$user',public" set_session_auth USERS.each do |u| @@ -63,7 +63,7 @@ def test_setting_auth_clears_stmt_cache end end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements def test_auth_with_bind assert_nothing_raised do set_session_auth diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 2c94f2aa30..87bf65cb65 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -81,7 +81,7 @@ def self.default_scope; where(deleted: false); end end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute "CREATE SCHEMA #{SCHEMA_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})" @connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{TABLE_NAME}.table\" (#{COLUMNS.join(',')})" @connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{CAPITALIZED_TABLE_NAME}\" (#{COLUMNS.join(',')})" @@ -148,9 +148,9 @@ def test_drop_schema_if_exists end def test_habtm_table_name_with_schema - ActiveRecord::Base.connection.drop_schema "music", if_exists: true - ActiveRecord::Base.connection.create_schema "music" - ActiveRecord::Base.connection.execute <<~SQL + ActiveRecord::Base.lease_connection.drop_schema "music", if_exists: true + ActiveRecord::Base.lease_connection.create_schema "music" + ActiveRecord::Base.lease_connection.execute <<~SQL CREATE TABLE music.albums (id serial primary key, deleted boolean default false); CREATE TABLE music.songs (id serial primary key); CREATE TABLE music.albums_songs (album_id integer, song_id integer); @@ -162,7 +162,7 @@ def test_habtm_table_name_with_schema assert_equal [album.id], Song.joins(:albums).pluck("albums.id") assert_equal [album.id], Song.joins(:albums).pluck("music.albums.id") ensure - ActiveRecord::Base.connection.drop_schema "music", if_exists: true + ActiveRecord::Base.lease_connection.drop_schema "music", if_exists: true end def test_drop_schema_with_nonexisting_schema @@ -181,7 +181,7 @@ def test_raise_wrapped_exception_on_bad_prepare end end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements def test_schema_change_with_prepared_stmt altered = false @connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)] @@ -549,7 +549,7 @@ class SchemaForeignKeyTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_schema("my_schema") end @@ -598,7 +598,7 @@ class SchemaIndexOpclassTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "trains" do |t| t.string :name t.string :position @@ -642,7 +642,7 @@ class SchemaIndexNullsOrderTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "trains" do |t| t.string :name t.text :description @@ -668,7 +668,7 @@ def test_non_default_order_with_nulls_is_dumped class DefaultsUsingMultipleSchemasAndDomainTest < ActiveRecord::PostgreSQLTestCase setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.drop_schema "schema_1", if_exists: true @connection.execute "CREATE SCHEMA schema_1" @connection.execute "CREATE DOMAIN schema_1.text AS text" @@ -724,7 +724,7 @@ class SchemaWithDotsTest < ActiveRecord::PostgreSQLTestCase include PGSchemaHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_schema "my.schema" end @@ -758,7 +758,7 @@ class SchemaWithDotsTest < ActiveRecord::PostgreSQLTestCase class SchemaJoinTablesTest < ActiveRecord::PostgreSQLTestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_schema("test_schema") end @@ -782,7 +782,7 @@ class SchemaIndexIncludeColumnsTest < ActiveRecord::PostgreSQLTestCase def test_schema_dumps_index_included_columns index_definition = dump_table_schema("companies").split(/\n/).grep(/t\.index.*company_include_index/).first.strip - if ActiveRecord::Base.connection.supports_index_include? + if ActiveRecord::Base.lease_connection.supports_index_include? assert_equal 't.index ["firm_id", "type"], name: "company_include_index", include: ["name", "account_id"]', index_definition else assert_equal 't.index ["firm_id", "type"], name: "company_include_index"', index_definition @@ -794,7 +794,7 @@ class SchemaIndexNullsNotDistinctTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "trains" do |t| t.string :name end diff --git a/activerecord/test/cases/adapters/postgresql/serial_test.rb b/activerecord/test/cases/adapters/postgresql/serial_test.rb index be1d550a6f..8551d17a04 100644 --- a/activerecord/test/cases/adapters/postgresql/serial_test.rb +++ b/activerecord/test/cases/adapters/postgresql/serial_test.rb @@ -9,7 +9,7 @@ class PostgresqlSerialTest < ActiveRecord::PostgreSQLTestCase class PostgresqlSerial < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "postgresql_serials", force: true do |t| t.serial :seq t.integer :serials_id, default: -> { "nextval('postgresql_serials_id_seq')" } @@ -51,7 +51,7 @@ class PostgresqlBigSerialTest < ActiveRecord::PostgreSQLTestCase class PostgresqlBigSerial < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "postgresql_big_serials", force: true do |t| t.bigserial :seq t.bigint :serials_id, default: -> { "nextval('postgresql_big_serials_id_seq')" } @@ -92,7 +92,7 @@ class CollidedSequenceNameTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :foo_bar, force: true do |t| t.serial :baz_id end @@ -127,7 +127,7 @@ class LongerSequenceNameDetectionTest < ActiveRecord::PostgreSQLTestCase def setup @table_name = "long_table_name_to_test_sequence_name_detection_for_serial_cols" - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table @table_name, force: true, _uses_legacy_table_name: true do |t| t.serial :seq t.bigserial :bigseq diff --git a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb index 9c3f303cd4..942a1197b3 100644 --- a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb +++ b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb @@ -47,7 +47,7 @@ def test_dealloc_does_not_raise_on_inactive_connection end def test_prepared_statements_do_not_get_stuck_on_query_interruption - pg_connection = ActiveRecord::Base.connection.connect!.instance_variable_get(:@raw_connection) + pg_connection = ActiveRecord::Base.lease_connection.connect!.instance_variable_get(:@raw_connection) pg_connection.stub(:get_last_result, -> { raise "random error" }) do assert_raises(RuntimeError) do Developer.where(name: "David").last diff --git a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb index d3e1ec909d..6987bcf6c7 100644 --- a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb +++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb @@ -10,7 +10,7 @@ class PostgresqlTimestampWithZone < ActiveRecord::Base; end self.use_transactional_tests = false setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute("INSERT INTO postgresql_timestamp_with_zones (id, time) VALUES (1, '2010-01-01 10:00:00-1')") end @@ -51,7 +51,7 @@ class PostgresqlTimestampWithZone < ActiveRecord::Base; end self.use_transactional_tests = false setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute("INSERT INTO postgresql_timestamp_with_zones (id, time) VALUES (1, '2010-01-01 10:00:00-1')") end @@ -79,7 +79,7 @@ class PostgresqlTimestampWithZone < ActiveRecord::Base; end setup do with_postgresql_datetime_type(:timestamptz) do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute("INSERT INTO postgresql_timestamp_with_zones (id, time) VALUES (1, '2010-01-01 10:00:00-1')") end end @@ -172,7 +172,7 @@ def test_adds_column_as_timestamp ActiveRecord::Migration.new.add_column :postgresql_timestamp_with_zones, :times, :datetime assert_equal({ "data_type" => "timestamp without time zone" }, - PostgresqlTimestampWithZone.connection.execute("select data_type from information_schema.columns where column_name = 'times'").to_a.first) + PostgresqlTimestampWithZone.lease_connection.execute("select data_type from information_schema.columns where column_name = 'times'").to_a.first) ensure $stdout = original end @@ -184,7 +184,7 @@ def test_adds_column_as_timestamptz_if_datetime_type_changed ActiveRecord::Migration.new.add_column :postgresql_timestamp_with_zones, :times, :datetime assert_equal({ "data_type" => "timestamp with time zone" }, - PostgresqlTimestampWithZone.connection.execute("select data_type from information_schema.columns where column_name = 'times'").to_a.first) + PostgresqlTimestampWithZone.lease_connection.execute("select data_type from information_schema.columns where column_name = 'times'").to_a.first) end ensure $stdout = original @@ -193,14 +193,14 @@ def test_adds_column_as_timestamptz_if_datetime_type_changed def test_adds_column_as_custom_type original, $stdout = $stdout, StringIO.new - PostgresqlTimestampWithZone.connection.execute("CREATE TYPE custom_time_format AS ENUM ('past', 'present', 'future');") + PostgresqlTimestampWithZone.lease_connection.execute("CREATE TYPE custom_time_format AS ENUM ('past', 'present', 'future');") ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES[:datetimes_as_enum] = { name: "custom_time_format" } with_postgresql_datetime_type(:datetimes_as_enum) do ActiveRecord::Migration.new.add_column :postgresql_timestamp_with_zones, :times, :datetime, precision: nil assert_equal({ "data_type" => "USER-DEFINED", "udt_name" => "custom_time_format" }, - PostgresqlTimestampWithZone.connection.execute("select data_type, udt_name from information_schema.columns where column_name = 'times'").to_a.first) + PostgresqlTimestampWithZone.lease_connection.execute("select data_type, udt_name from information_schema.columns where column_name = 'times'").to_a.first) end ensure ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES.delete(:datetimes_as_enum) diff --git a/activerecord/test/cases/adapters/postgresql/transaction_nested_test.rb b/activerecord/test/cases/adapters/postgresql/transaction_nested_test.rb index aef2d64d31..b2e0f27505 100644 --- a/activerecord/test/cases/adapters/postgresql/transaction_nested_test.rb +++ b/activerecord/test/cases/adapters/postgresql/transaction_nested_test.rb @@ -19,7 +19,7 @@ class Bit < ActiveRecord::Base @abort, Thread.abort_on_exception = Thread.abort_on_exception, false Thread.report_on_exception, @original_report_on_exception = false, Thread.report_on_exception - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.transaction do connection.drop_table "samples", if_exists: true @@ -37,8 +37,8 @@ class Bit < ActiveRecord::Base end teardown do - ActiveRecord::Base.connection.drop_table "samples", if_exists: true - ActiveRecord::Base.connection.drop_table "bits", if_exists: true + ActiveRecord::Base.lease_connection.drop_table "samples", if_exists: true + ActiveRecord::Base.lease_connection.drop_table "bits", if_exists: true Thread.abort_on_exception = @abort Thread.report_on_exception = @original_report_on_exception @@ -132,7 +132,7 @@ class Bit < ActiveRecord::Base s2 = Sample.create value: 2 thread = Thread.new do - connections.add Sample.connection + connections.add Sample.lease_connection Sample.transaction(requires_new: false) do make_parent_transaction_dirty Sample.transaction(requires_new: true) do @@ -145,7 +145,7 @@ class Bit < ActiveRecord::Base end begin - connections.add Sample.connection + connections.add Sample.lease_connection Sample.transaction(requires_new: false) do make_parent_transaction_dirty Sample.transaction(requires_new: true) do @@ -213,12 +213,12 @@ class Bit < ActiveRecord::Base private def with_warning_suppression - log_level = ActiveRecord::Base.connection.client_min_messages - ActiveRecord::Base.connection.client_min_messages = "error" + log_level = ActiveRecord::Base.lease_connection.client_min_messages + ActiveRecord::Base.lease_connection.client_min_messages = "error" yield ensure ActiveRecord::Base.connection_handler.clear_active_connections!(:all) - ActiveRecord::Base.connection.client_min_messages = log_level + ActiveRecord::Base.lease_connection.client_min_messages = log_level end # These tests are coordinating a controlled sequence of accesses to rows in `samples` table under serializable isolation. @@ -229,7 +229,7 @@ def make_parent_transaction_dirty end 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) flunk("current transaction is not a savepoint transaction") end diff --git a/activerecord/test/cases/adapters/postgresql/transaction_test.rb b/activerecord/test/cases/adapters/postgresql/transaction_test.rb index 3abe1a4f1c..92e4a1ee3a 100644 --- a/activerecord/test/cases/adapters/postgresql/transaction_test.rb +++ b/activerecord/test/cases/adapters/postgresql/transaction_test.rb @@ -16,7 +16,7 @@ class Sample < ActiveRecord::Base @abort, Thread.abort_on_exception = Thread.abort_on_exception, false Thread.report_on_exception, @original_report_on_exception = false, Thread.report_on_exception - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.transaction do connection.drop_table "samples", if_exists: true @@ -29,7 +29,7 @@ class Sample < ActiveRecord::Base end 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.report_on_exception = @original_report_on_exception @@ -74,7 +74,7 @@ class Sample < ActiveRecord::Base s2 = Sample.create value: 2 thread = Thread.new do - connections.add Sample.connection + connections.add Sample.lease_connection Sample.transaction do s1.lock! barrier.wait @@ -83,7 +83,7 @@ class Sample < ActiveRecord::Base end begin - connections.add Sample.connection + connections.add Sample.lease_connection Sample.transaction do s2.lock! barrier.wait @@ -114,11 +114,11 @@ class Sample < ActiveRecord::Base begin Sample.transaction do latch1.wait - Sample.connection.execute("SET lock_timeout = 1") + Sample.lease_connection.execute("SET lock_timeout = 1") Sample.lock.find(s.id) end ensure - Sample.connection.execute("SET lock_timeout = DEFAULT") + Sample.lease_connection.execute("SET lock_timeout = DEFAULT") latch2.count_down thread.join end @@ -142,11 +142,11 @@ class Sample < ActiveRecord::Base begin Sample.transaction do latch1.wait - Sample.connection.execute("SET statement_timeout = 1") + Sample.lease_connection.execute("SET statement_timeout = 1") Sample.lock.find(s.id) end ensure - Sample.connection.execute("SET statement_timeout = DEFAULT") + Sample.lease_connection.execute("SET statement_timeout = DEFAULT") latch2.count_down thread.join end @@ -163,7 +163,7 @@ class Sample < ActiveRecord::Base Sample.lock.find(s.id) latch.count_down sleep(0.5) - conn = Sample.connection + conn = Sample.lease_connection pid = conn.query_value("SELECT pid FROM pg_stat_activity WHERE query LIKE '% FOR UPDATE'") conn.execute("SELECT pg_cancel_backend(#{pid})") end @@ -184,7 +184,7 @@ class Sample < ActiveRecord::Base start_time = Time.now thread = Thread.new do Sample.transaction do - Sample.connection.execute("SELECT pg_sleep(10)") + Sample.lease_connection.execute("SELECT pg_sleep(10)") end rescue Exception => e e @@ -201,12 +201,12 @@ class Sample < ActiveRecord::Base private def with_warning_suppression - log_level = ActiveRecord::Base.connection.client_min_messages - ActiveRecord::Base.connection.client_min_messages = "error" + log_level = ActiveRecord::Base.lease_connection.client_min_messages + ActiveRecord::Base.lease_connection.client_min_messages = "error" yield ensure ActiveRecord::Base.connection_handler.clear_active_connections!(:all) - ActiveRecord::Base.connection.client_min_messages = log_level + ActiveRecord::Base.lease_connection.client_min_messages = log_level end end end diff --git a/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb b/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb index 8212ed4263..d62d4e0372 100644 --- a/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb +++ b/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb @@ -4,7 +4,7 @@ class PostgresqlTypeLookupTest < ActiveRecord::PostgreSQLTestCase setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end test "array delimiters are looked up correctly" do diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index b8ece66b19..9d4600ff27 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -5,7 +5,7 @@ module PostgresqlUUIDHelper def connection - @connection ||= ActiveRecord::Base.connection + @connection ||= ActiveRecord::Base.lease_connection end def drop_table(name) @@ -43,8 +43,8 @@ class UUIDType < ActiveRecord::Base drop_table "uuid_data_type" end - if ActiveRecord::Base.connection.respond_to?(:supports_pgcrypto_uuid?) && - ActiveRecord::Base.connection.supports_pgcrypto_uuid? + if ActiveRecord::Base.lease_connection.respond_to?(:supports_pgcrypto_uuid?) && + ActiveRecord::Base.lease_connection.supports_pgcrypto_uuid? def test_uuid_column_default connection.add_column :uuid_data_type, :thingy, :uuid, null: false, default: "gen_random_uuid()" UUIDType.reset_column_information diff --git a/activerecord/test/cases/adapters/postgresql/virtual_column_test.rb b/activerecord/test/cases/adapters/postgresql/virtual_column_test.rb index 9b51dd6600..215c35c9a1 100644 --- a/activerecord/test/cases/adapters/postgresql/virtual_column_test.rb +++ b/activerecord/test/cases/adapters/postgresql/virtual_column_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_virtual_columns? +if ActiveRecord::Base.lease_connection.supports_virtual_columns? class PostgresqlVirtualColumnTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper @@ -11,7 +11,7 @@ class VirtualColumn < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :virtual_columns, force: true do |t| t.string :name t.virtual :upper_name, type: :string, as: "UPPER(name)", stored: true diff --git a/activerecord/test/cases/adapters/postgresql/xml_test.rb b/activerecord/test/cases/adapters/postgresql/xml_test.rb index 81059351f9..544c15768b 100644 --- a/activerecord/test/cases/adapters/postgresql/xml_test.rb +++ b/activerecord/test/cases/adapters/postgresql/xml_test.rb @@ -10,7 +10,7 @@ class XmlDataType < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("xml_data_type") do |t| t.xml "payload" end diff --git a/activerecord/test/cases/adapters/sqlite3/collation_test.rb b/activerecord/test/cases/adapters/sqlite3/collation_test.rb index d938b5ff2f..adcd9d17bd 100644 --- a/activerecord/test/cases/adapters/sqlite3/collation_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/collation_test.rb @@ -7,7 +7,7 @@ class SQLite3CollationTest < ActiveRecord::SQLite3TestCase include SchemaDumpingHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :collation_table_sqlite3, force: true do |t| t.string :string_nocase, collation: "NOCASE" t.text :text_rtrim, collation: "RTRIM" diff --git a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb index fa53eb54fd..f41fe09bbc 100644 --- a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb @@ -6,7 +6,7 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase fixtures :customers def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_copy_table(from = "customers", to = "customers2", options = {}) diff --git a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb index e9f7d67035..fb6b912bd6 100644 --- a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb @@ -7,7 +7,7 @@ class SQLite3QuotingTest < ActiveRecord::SQLite3TestCase def setup super - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection end def test_quote_string diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_prevent_writes_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_prevent_writes_test.rb index afd9a63e92..31f307dd1c 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_prevent_writes_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_prevent_writes_test.rb @@ -11,7 +11,7 @@ class SQLite3AdapterPreventWritesTest < ActiveRecord::SQLite3TestCase self.use_transactional_tests = false def setup - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection end def test_errors_when_an_insert_query_is_called_while_preventing_writes diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index b702722665..42d853f512 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -48,7 +48,7 @@ def test_connect_with_url tf = Tempfile.open "whatever" url = "sqlite3:#{tf.path}" ActiveRecord::Base.establish_connection(url) - assert ActiveRecord::Base.connection + assert ActiveRecord::Base.lease_connection ensure tf.close tf.unlink @@ -59,7 +59,7 @@ def test_connect_memory_with_url original_connection = ActiveRecord::Base.remove_connection url = "sqlite3::memory:" ActiveRecord::Base.establish_connection(url) - assert ActiveRecord::Base.connection + assert ActiveRecord::Base.lease_connection ensure ActiveRecord::Base.establish_connection(original_connection) end @@ -74,7 +74,7 @@ def test_column_types owner = Owner.create!(name: "hello".encode("ascii-8bit")) owner.reload select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ", " - result = Owner.connection.exec_query <<~SQL + result = Owner.lease_connection.exec_query <<~SQL SELECT #{select} FROM #{Owner.table_name} WHERE #{Owner.primary_key} = #{owner.id} @@ -462,7 +462,7 @@ def test_exec_query_typecasts_bind_vals end def test_quote_binary_column_escapes_it - DualEncoding.connection.execute(<<~SQL) + DualEncoding.lease_connection.execute(<<~SQL) CREATE TABLE IF NOT EXISTS dual_encodings ( id integer PRIMARY KEY AUTOINCREMENT, name varchar(255), @@ -474,7 +474,7 @@ def test_quote_binary_column_escapes_it binary.save! assert_equal str, binary.data ensure - DualEncoding.connection.drop_table "dual_encodings", if_exists: true + DualEncoding.lease_connection.drop_table "dual_encodings", if_exists: true end def test_type_cast_should_not_mutate_encoding @@ -696,7 +696,7 @@ def test_compound_index end end - if ActiveRecord::Base.connection.supports_expression_index? + if ActiveRecord::Base.lease_connection.supports_expression_index? def test_expression_index with_example_table do @conn.add_index "ex", "max(id, number)", name: "expression" @@ -763,7 +763,7 @@ class BarcodeCustomPk < ActiveRecord::Base end def test_copy_table_with_existing_records_have_custom_primary_key - connection = BarcodeCustomPk.connection + connection = BarcodeCustomPk.lease_connection connection.create_table(:barcode_custom_pks, primary_key: "code", id: :string, limit: 42, force: true) do |t| t.text :other_attr end @@ -782,7 +782,7 @@ class BarcodeCpk < ActiveRecord::Base end def test_copy_table_with_composite_primary_keys - connection = BarcodeCpk.connection + connection = BarcodeCpk.lease_connection connection.create_table(:barcode_cpks, primary_key: ["region", "code"], force: true) do |t| t.string :region t.string :code @@ -804,7 +804,7 @@ def test_copy_table_with_composite_primary_keys end def test_custom_primary_key_in_create_table - connection = Barcode.connection + connection = Barcode.lease_connection connection.create_table :barcodes, id: false, force: true do |t| t.primary_key :id, :string end @@ -820,7 +820,7 @@ def test_custom_primary_key_in_create_table end def test_custom_primary_key_in_change_table - connection = Barcode.connection + connection = Barcode.lease_connection connection.create_table :barcodes, id: false, force: true do |t| t.integer :dummy end @@ -839,7 +839,7 @@ def test_custom_primary_key_in_change_table end def test_add_column_with_custom_primary_key - connection = Barcode.connection + connection = Barcode.lease_connection connection.create_table :barcodes, id: false, force: true do |t| t.integer :dummy end @@ -856,7 +856,7 @@ def test_add_column_with_custom_primary_key end def test_remove_column_preserves_index_options - connection = Barcode.connection + connection = Barcode.lease_connection connection.create_table :barcodes, force: true do |t| t.string :code t.string :region @@ -883,7 +883,7 @@ def test_remove_column_preserves_index_options end def test_auto_increment_preserved_on_table_changes - connection = Barcode.connection + connection = Barcode.lease_connection connection.create_table :barcodes, force: true do |t| t.string :code end diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite_rake_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite_rake_test.rb index 6906e5e68f..ca911be5a4 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite_rake_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite_rake_test.rb @@ -139,7 +139,7 @@ def setup end def test_db_retrieves_charset - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :encoding) do ActiveRecord::Tasks::DatabaseTasks.charset @configuration, "/rails/root" end @@ -192,7 +192,7 @@ def test_structure_dump def test_structure_dump_with_ignore_tables dbfile = @database 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::Tasks::DatabaseTasks.structure_dump(@configuration, filename, "/rails/root") end diff --git a/activerecord/test/cases/adapters/sqlite3/virtual_column_test.rb b/activerecord/test/cases/adapters/sqlite3/virtual_column_test.rb index 956a0870a0..f4c6d327d8 100644 --- a/activerecord/test/cases/adapters/sqlite3/virtual_column_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/virtual_column_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_virtual_columns? +if ActiveRecord::Base.lease_connection.supports_virtual_columns? class SQLite3VirtualColumnTest < ActiveRecord::SQLite3TestCase include SchemaDumpingHelper @@ -11,7 +11,7 @@ class VirtualColumn < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :virtual_columns, force: true do |t| t.string :name t.virtual :upper_name, type: :string, as: "UPPER(name)", stored: true diff --git a/activerecord/test/cases/adapters/trilogy/trilogy_adapter_test.rb b/activerecord/test/cases/adapters/trilogy/trilogy_adapter_test.rb index 88ab9063ca..b6a3d608f2 100644 --- a/activerecord/test/cases/adapters/trilogy/trilogy_adapter_test.rb +++ b/activerecord/test/cases/adapters/trilogy/trilogy_adapter_test.rb @@ -7,7 +7,7 @@ class TrilogyAdapterTest < ActiveRecord::TrilogyTestCase setup do - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection end test "connection_error" do @@ -343,7 +343,7 @@ class TrilogyAdapterTest < ActiveRecord::TrilogyTestCase ActiveRecord::Base.establish_connection( db_config.configuration_hash.merge("read_timeout" => 1) ) - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection error = assert_raises(ActiveRecord::AdapterTimeout) do connection.execute("SELECT SLEEP(2)") diff --git a/activerecord/test/cases/adapters/trilogy/trilogy_rake_test.rb b/activerecord/test/cases/adapters/trilogy/trilogy_rake_test.rb index 1658325300..272f1a6200 100644 --- a/activerecord/test/cases/adapters/trilogy/trilogy_rake_test.rb +++ b/activerecord/test/cases/adapters/trilogy/trilogy_rake_test.rb @@ -29,7 +29,7 @@ def test_establishes_connection_without_database mock.expect(:call, nil, [adapter: "trilogy", database: nil]) 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::Tasks::DatabaseTasks.create(db_config) 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 with_stubbed_connection_establish_connection do - ActiveRecord::Base.connection.stub( + ActiveRecord::Base.lease_connection.stub( :create_database, proc { raise ActiveRecord::DatabaseAlreadyExists } ) do @@ -90,7 +90,7 @@ def test_create_when_database_exists_outputs_info_to_stderr private def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end end @@ -139,7 +139,7 @@ def teardown def test_establishes_connection_to_mysql_database 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( ActiveRecord::Base, :establish_connection, @@ -169,7 +169,7 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout private def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end end @@ -186,7 +186,7 @@ def setup def test_establishes_connection_without_database 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 ActiveRecord::Tasks::DatabaseTasks.purge(db_config) end @@ -217,7 +217,7 @@ def test_recreates_database_with_the_given_options private def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection, &block) + ActiveRecord::Base.stub(:lease_connection, @connection, &block) end end end @@ -232,7 +232,7 @@ def setup end def test_db_retrieves_charset - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :charset) do ActiveRecord::Tasks::DatabaseTasks.charset @configuration end @@ -250,7 +250,7 @@ def setup end def test_db_retrieves_collation - ActiveRecord::Base.stub(:connection, @connection) do + ActiveRecord::Base.stub(:lease_connection, @connection) do assert_called(@connection, :collation) do ActiveRecord::Tasks::DatabaseTasks.collation @configuration end @@ -313,7 +313,7 @@ def test_structure_dump_with_hash_extra_flags_for_the_correct_driver def test_structure_dump_with_ignore_tables 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 assert_called_with( Kernel, diff --git a/activerecord/test/cases/annotate_test.rb b/activerecord/test/cases/annotate_test.rb index 9603b79a71..19d7b4ca1f 100644 --- a/activerecord/test/cases/annotate_test.rb +++ b/activerecord/test/cases/annotate_test.rb @@ -46,6 +46,6 @@ def test_annotate_is_sanitized private def regexp_escape_table_name(name) - Regexp.escape(Post.connection.quote_table_name(name)) + Regexp.escape(Post.lease_connection.quote_table_name(name)) end end diff --git a/activerecord/test/cases/arel/collectors/bind_test.rb b/activerecord/test/cases/arel/collectors/bind_test.rb index ffa9b15f66..8c193c6cc3 100644 --- a/activerecord/test/cases/arel/collectors/bind_test.rb +++ b/activerecord/test/cases/arel/collectors/bind_test.rb @@ -8,7 +8,7 @@ module Collectors class TestBind < Arel::Test def setup @conn = FakeRecord::Base.new - @visitor = Visitors::ToSql.new @conn.connection + @visitor = Visitors::ToSql.new @conn.lease_connection super end diff --git a/activerecord/test/cases/arel/collectors/composite_test.rb b/activerecord/test/cases/arel/collectors/composite_test.rb index 545637496f..fb910034d1 100644 --- a/activerecord/test/cases/arel/collectors/composite_test.rb +++ b/activerecord/test/cases/arel/collectors/composite_test.rb @@ -10,7 +10,7 @@ module Collectors class TestComposite < Arel::Test def setup @conn = FakeRecord::Base.new - @visitor = Visitors::ToSql.new @conn.connection + @visitor = Visitors::ToSql.new @conn.lease_connection super end diff --git a/activerecord/test/cases/arel/collectors/sql_string_test.rb b/activerecord/test/cases/arel/collectors/sql_string_test.rb index 443c7eb54b..d04c4fdfa6 100644 --- a/activerecord/test/cases/arel/collectors/sql_string_test.rb +++ b/activerecord/test/cases/arel/collectors/sql_string_test.rb @@ -7,7 +7,7 @@ module Collectors class TestSqlString < Arel::Test def setup @conn = FakeRecord::Base.new - @visitor = Visitors::ToSql.new @conn.connection + @visitor = Visitors::ToSql.new @conn.lease_connection super end diff --git a/activerecord/test/cases/arel/collectors/substitute_bind_collector_test.rb b/activerecord/test/cases/arel/collectors/substitute_bind_collector_test.rb index 255c8e79e9..298444d249 100644 --- a/activerecord/test/cases/arel/collectors/substitute_bind_collector_test.rb +++ b/activerecord/test/cases/arel/collectors/substitute_bind_collector_test.rb @@ -9,7 +9,7 @@ module Collectors class TestSubstituteBindCollector < Arel::Test def setup @conn = FakeRecord::Base.new - @visitor = Visitors::ToSql.new @conn.connection + @visitor = Visitors::ToSql.new @conn.lease_connection super end diff --git a/activerecord/test/cases/arel/insert_manager_test.rb b/activerecord/test/cases/arel/insert_manager_test.rb index e19a25b8a0..c4ea99d0c5 100644 --- a/activerecord/test/cases/arel/insert_manager_test.rb +++ b/activerecord/test/cases/arel/insert_manager_test.rb @@ -104,7 +104,7 @@ class InsertManagerTest < Arel::Spec manager.insert [[attribute, time]] _(manager.to_sql).must_be_like %{ - INSERT INTO "users" ("created_at") VALUES (#{Table.engine.connection.quote time}) + INSERT INTO "users" ("created_at") VALUES (#{Table.engine.lease_connection.quote time}) } end diff --git a/activerecord/test/cases/arel/nodes/equality_test.rb b/activerecord/test/cases/arel/nodes/equality_test.rb index ea9da07753..2260b04f8c 100644 --- a/activerecord/test/cases/arel/nodes/equality_test.rb +++ b/activerecord/test/cases/arel/nodes/equality_test.rb @@ -10,18 +10,18 @@ module Nodes describe "to_sql" do it "takes an engine" do engine = FakeRecord::Base.new - engine.connection.extend Module.new { + engine.lease_connection.extend Module.new { attr_accessor :quote_count def quote(*args) @quote_count += 1; super; end def quote_column_name(*args) @quote_count += 1; super; end def quote_table_name(*args) @quote_count += 1; super; end } - engine.connection.quote_count = 0 + engine.lease_connection.quote_count = 0 attr = Table.new(:users)[:id] test = attr.eq(10) test.to_sql engine - _(engine.connection.quote_count).must_equal 3 + _(engine.lease_connection.quote_count).must_equal 3 end end end diff --git a/activerecord/test/cases/arel/nodes/sql_literal_test.rb b/activerecord/test/cases/arel/nodes/sql_literal_test.rb index 51a9d8f931..5ee59ed3a8 100644 --- a/activerecord/test/cases/arel/nodes/sql_literal_test.rb +++ b/activerecord/test/cases/arel/nodes/sql_literal_test.rb @@ -7,7 +7,7 @@ module Arel module Nodes class SqlLiteralTest < Arel::Spec before do - @visitor = Visitors::ToSql.new Table.engine.connection + @visitor = Visitors::ToSql.new Table.engine.lease_connection end def compile(node) diff --git a/activerecord/test/cases/arel/select_manager_test.rb b/activerecord/test/cases/arel/select_manager_test.rb index 052673f8df..a07d0b9d69 100644 --- a/activerecord/test/cases/arel/select_manager_test.rb +++ b/activerecord/test/cases/arel/select_manager_test.rb @@ -964,15 +964,15 @@ def test_join_sources end it "handles database-specific statements" do - old_visitor = Table.engine.connection.visitor - Table.engine.connection.visitor = Visitors::PostgreSQL.new Table.engine.connection + old_visitor = Table.engine.lease_connection.visitor + Table.engine.lease_connection.visitor = Visitors::PostgreSQL.new Table.engine.lease_connection table = Table.new :users manager = Arel::SelectManager.new manager.from table manager.where table[:id].eq 10 manager.where table[:name].matches "foo%" _(manager.where_sql).must_be_like %{ WHERE "users"."id" = 10 AND "users"."name" ILIKE 'foo%' } - Table.engine.connection.visitor = old_visitor + Table.engine.lease_connection.visitor = old_visitor end it "returns nil when there are no wheres" do diff --git a/activerecord/test/cases/arel/support/fake_record.rb b/activerecord/test/cases/arel/support/fake_record.rb index 37af50aa89..5126d59b87 100644 --- a/activerecord/test/cases/arel/support/fake_record.rb +++ b/activerecord/test/cases/arel/support/fake_record.rb @@ -93,30 +93,32 @@ def cast_bound_value(thing) end class ConnectionPool - attr_reader :connection - def initialize @connection = Connection.new end + def lease_connection + @connection + end + def with_connection - yield connection + yield @connection end def table_exists?(name) - connection.tables.include? name.to_s + @connection.tables.include? name.to_s end def columns_hash - connection.columns_hash + @connection.columns_hash end def schema_cache - connection + @connection end def quote(thing) - connection.quote thing + @connection.quote thing end end @@ -127,8 +129,8 @@ def initialize @connection_pool = ConnectionPool.new end - def connection - connection_pool.connection + def lease_connection + connection_pool.lease_connection end end end diff --git a/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb b/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb index 36f9eb49a2..715320d2a3 100644 --- a/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb +++ b/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb @@ -40,7 +40,7 @@ class DummySubNode < DummySuperNode class DispatchContaminationTest < Arel::Spec before do - @connection = Table.engine.connection + @connection = Table.engine.lease_connection @table = Table.new(:users) end diff --git a/activerecord/test/cases/arel/visitors/mysql_test.rb b/activerecord/test/cases/arel/visitors/mysql_test.rb index c2ce5a4a98..861ee6e63d 100644 --- a/activerecord/test/cases/arel/visitors/mysql_test.rb +++ b/activerecord/test/cases/arel/visitors/mysql_test.rb @@ -6,7 +6,7 @@ module Arel module Visitors class MysqlTest < Arel::Spec before do - @visitor = MySQL.new Table.engine.connection + @visitor = MySQL.new Table.engine.lease_connection end def compile(node) diff --git a/activerecord/test/cases/arel/visitors/postgres_test.rb b/activerecord/test/cases/arel/visitors/postgres_test.rb index 2795540669..8717334cba 100644 --- a/activerecord/test/cases/arel/visitors/postgres_test.rb +++ b/activerecord/test/cases/arel/visitors/postgres_test.rb @@ -6,7 +6,7 @@ module Arel module Visitors class PostgresTest < Arel::Spec before do - @visitor = PostgreSQL.new Table.engine.connection + @visitor = PostgreSQL.new Table.engine.lease_connection @table = Table.new(:users) @attr = @table[:id] end diff --git a/activerecord/test/cases/arel/visitors/sqlite_test.rb b/activerecord/test/cases/arel/visitors/sqlite_test.rb index 6ec7cdc2a7..5a7923fad0 100644 --- a/activerecord/test/cases/arel/visitors/sqlite_test.rb +++ b/activerecord/test/cases/arel/visitors/sqlite_test.rb @@ -6,7 +6,7 @@ module Arel module Visitors class SqliteTest < Arel::Spec before do - @visitor = SQLite.new Table.engine.connection + @visitor = SQLite.new Table.engine.lease_connection end def compile(node) diff --git a/activerecord/test/cases/arel/visitors/to_sql_test.rb b/activerecord/test/cases/arel/visitors/to_sql_test.rb index 5bffa6b9f9..7f01ac5057 100644 --- a/activerecord/test/cases/arel/visitors/to_sql_test.rb +++ b/activerecord/test/cases/arel/visitors/to_sql_test.rb @@ -8,7 +8,7 @@ module Visitors describe "the to_sql visitor" do before do @conn = FakeRecord::Base.new - @visitor = ToSql.new @conn.connection + @visitor = ToSql.new @conn.lease_connection @table = Table.new(:users) @attr = @table[:id] end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index d672ab51fb..d83e94bcbf 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -270,7 +270,7 @@ def test_type_mismatch def test_raises_type_mismatch_with_namespaced_class assert_nil defined?(Region), "This test requires that there is no top-level Region class" - ActiveRecord::Base.connection.instance_eval do + ActiveRecord::Base.lease_connection.instance_eval do create_table(:admin_regions, force: true) { |t| t.string :name } add_column :admin_users, :region_id, :integer end @@ -285,7 +285,7 @@ def test_raises_type_mismatch_with_namespaced_class Admin.send :remove_const, "Region" if Admin.const_defined?("Region") Admin.send :remove_const, "RegionalUser" if Admin.const_defined?("RegionalUser") - ActiveRecord::Base.connection.instance_eval do + ActiveRecord::Base.lease_connection.instance_eval do remove_column :admin_users, :region_id if column_exists?(:admin_users, :region_id) drop_table :admin_regions, if_exists: true end @@ -460,7 +460,7 @@ def test_reloading_the_belonging_object def test_reload_the_belonging_object_with_query_cache odegy_account_id = accounts(:odegy_account).id - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.enable_query_cache! connection.clear_query_cache @@ -478,7 +478,7 @@ def test_reload_the_belonging_object_with_query_cache # This query is not cached anymore, so it should make a real SQL query assert_queries_count(1) { Account.find(odegy_account_id) } ensure - ActiveRecord::Base.connection.disable_query_cache! + ActiveRecord::Base.lease_connection.disable_query_cache! end def test_resetting_the_association diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb index 420a5a805b..d6811b9aaf 100644 --- a/activerecord/test/cases/associations/eager_singularization_test.rb +++ b/activerecord/test/cases/associations/eager_singularization_test.rb @@ -143,6 +143,6 @@ def test_eager_no_extra_singularization_has_many_through_has_many private def connection - ActiveRecord::Base.connection + ActiveRecord::Base.lease_connection end end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index d634cb5eef..e84fa8b7bc 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -497,7 +497,7 @@ def test_eager_association_loading_with_belongs_to_and_conditions_hash end def test_eager_association_loading_with_belongs_to_and_conditions_string_with_quoted_table_name - quoted_posts_id = Comment.connection.quote_table_name("posts") + "." + Comment.connection.quote_column_name("id") + quoted_posts_id = Comment.lease_connection.quote_table_name("posts") + "." + Comment.lease_connection.quote_column_name("id") assert_nothing_raised do Comment.includes(:post).references(:posts).where("#{quoted_posts_id} = ?", 4) end @@ -510,7 +510,7 @@ def test_eager_association_loading_with_belongs_to_and_order_string_with_unquote end def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name - quoted_posts_id = Comment.connection.quote_table_name("posts") + "." + Comment.connection.quote_column_name("id") + quoted_posts_id = Comment.lease_connection.quote_table_name("posts") + "." + Comment.lease_connection.quote_column_name("id") assert_nothing_raised do Comment.includes(:post).references(:posts).order(quoted_posts_id) end @@ -1697,7 +1697,7 @@ def test_preloading_has_many_through_with_custom_scope assert_equal 3, comments_collection.size end.last - c = Sharded::BlogPost.connection + c = Sharded::BlogPost.lease_connection quoted_blog_id = Regexp.escape(c.quote_table_name("sharded_comments.blog_id")) quoted_blog_post_id = Regexp.escape(c.quote_table_name("sharded_comments.blog_post_id")) assert_match(/WHERE #{quoted_blog_id} IN \(.+\) AND #{quoted_blog_post_id} IN \(.+\)/, sql) diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 6c335fa5ad..40b4b0e40f 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -129,7 +129,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings, :computers def setup_data_for_habtm_case - ActiveRecord::Base.connection.execute("delete from countries_treaties") + ActiveRecord::Base.lease_connection.execute("delete from countries_treaties") country = Country.new(name: "India") country.country_id = "c1" @@ -149,7 +149,7 @@ def test_marshal_dump def test_should_property_quote_string_primary_keys setup_data_for_habtm_case - con = ActiveRecord::Base.connection + con = ActiveRecord::Base.lease_connection sql = "select * from countries_treaties" record = con.select_rows(sql).last assert_equal "c1", record[0] @@ -435,7 +435,7 @@ def test_removing_associations_on_destroy assert_not_empty david.projects david.destroy assert_empty david.projects - assert_empty DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1") + assert_empty DeveloperWithBeforeDestroyRaise.lease_connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1") end def test_destroying @@ -449,7 +449,7 @@ def test_destroying david.projects.destroy(project) end - join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}") + join_records = Developer.lease_connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}") assert_empty join_records assert_equal 1, david.reload.projects.size @@ -465,7 +465,7 @@ def test_destroying_many david.projects.destroy(*projects) end - join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}") + join_records = Developer.lease_connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}") assert_empty join_records assert_equal 0, david.reload.projects.size @@ -481,7 +481,7 @@ def test_destroy_all david.projects.destroy_all end - join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}") + join_records = Developer.lease_connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}") assert_empty join_records assert_empty david.projects @@ -499,11 +499,11 @@ def test_destroy_associations_destroys_multiple_associations end end - join_records = Parrot.connection.select_all("SELECT * FROM parrots_pirates WHERE parrot_id = #{george.id}") + join_records = Parrot.lease_connection.select_all("SELECT * FROM parrots_pirates WHERE parrot_id = #{george.id}") assert_empty join_records assert_empty george.pirates.reload - join_records = Parrot.connection.select_all("SELECT * FROM parrots_treasures WHERE parrot_id = #{george.id}") + join_records = Parrot.lease_connection.select_all("SELECT * FROM parrots_treasures WHERE parrot_id = #{george.id}") assert_empty join_records assert_empty george.treasures.reload end @@ -659,7 +659,7 @@ def test_update_columns_after_push_without_duplicate_join_table_rows assert developer.save developer.projects << project developer.update_columns("name" => "Bruza") - assert_equal 1, Developer.connection.select_value(<<-end_sql).to_i + assert_equal 1, Developer.lease_connection.select_value(<<-end_sql).to_i SELECT count(*) FROM developers_projects WHERE project_id = #{project.id} AND developer_id = #{developer.id} diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 086917ee90..0cd1a8a326 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -925,7 +925,7 @@ def test_find_first_after_reload end def test_reload_with_query_cache - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.enable_query_cache! connection.clear_query_cache @@ -943,11 +943,11 @@ def test_reload_with_query_cache assert_equal 1, connection.query_cache.size ensure - ActiveRecord::Base.connection.disable_query_cache! + ActiveRecord::Base.lease_connection.disable_query_cache! end def test_reloading_unloaded_associations_with_query_cache - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.enable_query_cache! connection.clear_query_cache @@ -963,7 +963,7 @@ def test_reloading_unloaded_associations_with_query_cache assert_equal [client.name], firm.clients.reload.map(&:name) ensure - ActiveRecord::Base.connection.disable_query_cache! + ActiveRecord::Base.lease_connection.disable_query_cache! end def test_find_all_with_include_and_conditions @@ -1315,7 +1315,7 @@ def test_sharded_deleting_models blog_post.delete_comments.delete(comments_to_delete) end - c = Sharded::Comment.connection + c = Sharded::Comment.lease_connection blog_id = Regexp.escape(c.quote_table_name("sharded_comments.blog_id")) id = Regexp.escape(c.quote_table_name("sharded_comments.id")) diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 262d052ef6..f2c4468482 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -1618,7 +1618,7 @@ def test_post_has_many_tags_through_association_with_composite_query_constraints tag_ids = blog_post.tags.to_a.map(&:id) end.first - c = Sharded::Blog.connection + c = Sharded::Blog.lease_connection quoted_tags_blog_id = Regexp.escape(c.quote_table_name("sharded_tags.blog_id")) quoted_posts_tags_blog_id = Regexp.escape(c.quote_table_name("sharded_blog_posts_tags.blog_id")) assert_match(/.* ON.* #{quoted_tags_blog_id} = #{quoted_posts_tags_blog_id} .* WHERE/, sql) @@ -1636,7 +1636,7 @@ def test_tags_has_manu_posts_through_association_with_composite_query_constraint blog_post_ids = tag.blog_posts.to_a.map(&:id) end.first - c = Sharded::Blog.connection + c = Sharded::Blog.lease_connection quoted_blog_posts_blog_id = Regexp.escape(c.quote_table_name("sharded_blog_posts.blog_id")) quoted_posts_tags_blog_id = Regexp.escape(c.quote_table_name("sharded_blog_posts_tags.blog_id")) assert_match(/.* ON.* #{quoted_blog_posts_blog_id} = #{quoted_posts_tags_blog_id} .* WHERE/, sql) diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 93561050ed..fa8317fade 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -385,7 +385,7 @@ def test_reload_association def test_reload_association_with_query_cache odegy_id = companies(:odegy).id - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.enable_query_cache! connection.clear_query_cache @@ -402,7 +402,7 @@ def test_reload_association_with_query_cache # This query is not cached anymore, so it should make a real SQL query assert_queries_count(1) { Company.find(odegy_id) } ensure - ActiveRecord::Base.connection.disable_query_cache! + ActiveRecord::Base.lease_connection.disable_query_cache! end def test_reset_association diff --git a/activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb b/activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb index 5aeea253fa..983317e0f7 100644 --- a/activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb @@ -77,6 +77,6 @@ def test_disable_joins_through_with_enum_type assert_no_match(/INNER JOIN/, nj) end - assert_match(/#{Regexp.escape(Member.connection.quote_table_name('memberships.type'))}/, no_joins.first) + assert_match(/#{Regexp.escape(Member.lease_connection.quote_table_name('memberships.type'))}/, no_joins.first) end end diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index 629431f1fa..709ea5a4d6 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -171,7 +171,7 @@ def test_has_many_through_has_one_with_has_many_through_source_reflection end def test_has_many_through_has_one_with_has_many_through_source_reflection_preload - ActiveRecord::Base.connection.table_alias_length # preheat cache + ActiveRecord::Base.lease_connection.table_alias_length # preheat cache member = assert_queries_count(4) { Member.includes(:organization_member_details).first } groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy) diff --git a/activerecord/test/cases/associations/required_test.rb b/activerecord/test/cases/associations/required_test.rb index db7f945a36..07bda74978 100644 --- a/activerecord/test/cases/associations/required_test.rb +++ b/activerecord/test/cases/associations/required_test.rb @@ -12,7 +12,7 @@ class Child < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :parents, force: true @connection.create_table :children, force: true do |t| t.belongs_to :parent diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index af13e75b32..e285093cc6 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -166,8 +166,8 @@ def test_belongs_to_a_model_with_composite_primary_key_uses_composite_pk_in_sql comment.blog_post end.first - assert_match(/#{Regexp.escape(Sharded::BlogPost.connection.quote_table_name("sharded_blog_posts.blog_id"))} =/, sql) - assert_match(/#{Regexp.escape(Sharded::BlogPost.connection.quote_table_name("sharded_blog_posts.id"))} =/, sql) + assert_match(/#{Regexp.escape(Sharded::BlogPost.lease_connection.quote_table_name("sharded_blog_posts.blog_id"))} =/, sql) + assert_match(/#{Regexp.escape(Sharded::BlogPost.lease_connection.quote_table_name("sharded_blog_posts.id"))} =/, sql) end def test_querying_by_whole_associated_records_using_query_constraints @@ -246,7 +246,7 @@ def test_has_many_association_from_a_model_with_query_constraints_different_from comments = blog_post.comments.to_a end.first - assert_match(/WHERE .*#{Regexp.escape(Sharded::Comment.connection.quote_table_name("sharded_comments.blog_id"))} =/, sql) + assert_match(/WHERE .*#{Regexp.escape(Sharded::Comment.lease_connection.quote_table_name("sharded_comments.blog_id"))} =/, sql) assert_not_empty(comments) assert_equal(expected_comments.sort, comments.sort) end @@ -270,8 +270,8 @@ def test_model_with_composite_query_constraints_has_many_association_sql blog_post.comments.to_a end.first - assert_match(/#{Regexp.escape(Sharded::Comment.connection.quote_table_name("sharded_comments.blog_post_id"))} =/, sql) - assert_match(/#{Regexp.escape(Sharded::Comment.connection.quote_table_name("sharded_comments.blog_id"))} =/, sql) + assert_match(/#{Regexp.escape(Sharded::Comment.lease_connection.quote_table_name("sharded_comments.blog_post_id"))} =/, sql) + assert_match(/#{Regexp.escape(Sharded::Comment.lease_connection.quote_table_name("sharded_comments.blog_id"))} =/, sql) end def test_belongs_to_association_does_not_use_parent_query_constraints_if_not_configured_to @@ -1493,7 +1493,7 @@ def test_preloads_has_many_on_model_with_a_composite_primary_key_through_id_attr assert_equal 2, sql.size preload_sql = sql.last - c = Cpk::OrderAgreement.connection + c = Cpk::OrderAgreement.lease_connection order_id_column = Regexp.escape(c.quote_table_name("cpk_order_agreements.order_id")) order_id_constraint = /#{order_id_column} = (\?|(\d+)|\$\d)$/ expectation = /SELECT.*WHERE.* #{order_id_constraint}/ @@ -1515,7 +1515,7 @@ def test_preloads_belongs_to_a_composite_primary_key_model_through_id_attribute assert_equal 2, sql.size preload_sql = sql.last - c = Cpk::Order.connection + c = Cpk::Order.lease_connection order_id = Regexp.escape(c.quote_table_name("cpk_orders.id")) order_constraint = /#{order_id} = (\?|(\d+)|\$\d)$/ expectation = /SELECT.*WHERE.* #{order_constraint}/ diff --git a/activerecord/test/cases/asynchronous_queries_test.rb b/activerecord/test/cases/asynchronous_queries_test.rb index edf62db063..3d677cde0d 100644 --- a/activerecord/test/cases/asynchronous_queries_test.rb +++ b/activerecord/test/cases/asynchronous_queries_test.rb @@ -99,7 +99,7 @@ class AsynchronousQueriesTest < ActiveRecord::TestCase include AsynchronousQueriesSharedTests def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_async_select_all @@ -134,7 +134,7 @@ class AsynchronousQueriesWithTransactionalTest < ActiveRecord::TestCase include AsynchronousQueriesSharedTests def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.materialize_transactions end end diff --git a/activerecord/test/cases/attributes_test.rb b/activerecord/test/cases/attributes_test.rb index be1fda81c1..76a78f8c76 100644 --- a/activerecord/test/cases/attributes_test.rb +++ b/activerecord/test/cases/attributes_test.rb @@ -357,7 +357,7 @@ def deserialize(*) end test "attributes do not require a connection is established" do - assert_not_called(ActiveRecord::Base, :connection) do + assert_not_called(ActiveRecord::Base, :lease_connection) do Class.new(OverloadedType) do attribute :foo, :string end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index f17b10f925..860bcc2e9c 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -1318,7 +1318,7 @@ def test_when_new_record_a_child_marked_for_destruction_should_not_affect_other_ end def test_should_save_new_record_that_has_same_value_as_existing_record_marked_for_destruction_on_field_that_has_unique_index - Bird.connection.add_index :birds, :name, unique: true + Bird.lease_connection.add_index :birds, :name, unique: true 3.times { |i| @pirate.birds.create(name: "unique_birds_#{i}") } @@ -1328,7 +1328,7 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo assert_equal 3, @pirate.birds.reload.length ensure - Bird.connection.remove_index :birds, column: :name + Bird.lease_connection.remove_index :birds, column: :name end # Add and remove callbacks tests for association collections. @@ -1378,7 +1378,7 @@ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marke assert_empty @pirate.reload.parrots - join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}") + join_records = Pirate.lease_connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}") assert_empty join_records end diff --git a/activerecord/test/cases/base_prevent_writes_test.rb b/activerecord/test/cases/base_prevent_writes_test.rb index b97150579a..a92d4d87a6 100644 --- a/activerecord/test/cases/base_prevent_writes_test.rb +++ b/activerecord/test/cases/base_prevent_writes_test.rb @@ -59,7 +59,7 @@ class BasePreventWritesTest < ActiveRecord::TestCase ActiveRecord::Base.while_preventing_writes do assert_queries_count(2, include_schema: true) do Bird.transaction do - ActiveRecord::Base.connection.materialize_transactions + ActiveRecord::Base.lease_connection.materialize_transactions end end end @@ -68,8 +68,8 @@ class BasePreventWritesTest < ActiveRecord::TestCase test "preventing writes applies to all connections in block" do ActiveRecord::Base.while_preventing_writes do conn1_error = assert_raises ActiveRecord::ReadOnlyError do - assert_equal ActiveRecord::Base.connection, Bird.connection - assert_not_equal ARUnit2Model.connection, Bird.connection + assert_equal ActiveRecord::Base.lease_connection, Bird.lease_connection + assert_not_equal ARUnit2Model.lease_connection, Bird.lease_connection Bird.create!(name: "Bluejay") end @@ -78,8 +78,8 @@ class BasePreventWritesTest < ActiveRecord::TestCase ActiveRecord::Base.while_preventing_writes do conn2_error = assert_raises ActiveRecord::ReadOnlyError do - assert_not_equal ActiveRecord::Base.connection, Professor.connection - assert_equal ARUnit2Model.connection, Professor.connection + assert_not_equal ActiveRecord::Base.lease_connection, Professor.lease_connection + assert_equal ARUnit2Model.lease_connection, Professor.lease_connection Professor.create!(name: "Professor Bluejay") end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 041e4c6e97..b95deb8cba 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -138,7 +138,7 @@ def test_incomplete_schema_loading end def test_column_names_are_escaped - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection classname = conn.class.name[/[^:]*$/] badchar = { "SQLite3Adapter" => '"', @@ -691,7 +691,7 @@ def test_failed_comparison_of_unlike_class_records end def test_create_without_prepared_statement - topic = Topic.connection.unprepared_statement do + topic = Topic.lease_connection.unprepared_statement do Topic.create(title: "foo") end @@ -700,7 +700,7 @@ def test_create_without_prepared_statement def test_destroy_without_prepared_statement topic = Topic.create(title: "foo") - Topic.connection.unprepared_statement do + Topic.lease_connection.unprepared_statement do Topic.find(topic.id).destroy end @@ -1346,11 +1346,11 @@ def test_quoted_table_name_after_set_table_name klass.table_name = "foo" assert_equal "foo", klass.table_name - assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name + assert_equal klass.lease_connection.quote_table_name("foo"), klass.quoted_table_name klass.table_name = "bar" assert_equal "bar", klass.table_name - assert_equal klass.connection.quote_table_name("bar"), klass.quoted_table_name + assert_equal klass.lease_connection.quote_table_name("bar"), klass.quoted_table_name end def test_set_table_name_with_inheritance @@ -1451,7 +1451,7 @@ def test_find_on_abstract_base_class_doesnt_use_type_condition end def test_assert_queries_count - query = lambda { ActiveRecord::Base.connection.execute "select count(*) from developers" } + query = lambda { ActiveRecord::Base.lease_connection.execute "select count(*) from developers" } assert_queries_count(2) { 2.times { query.call } } assert_queries_count 1, &query assert_no_queries { assert true } @@ -1662,7 +1662,7 @@ def cast(value) if current_adapter?(:PostgreSQLAdapter) def test_column_types_on_queries_on_postgresql - result = ActiveRecord::Base.connection.exec_query("SELECT 1 AS test") + result = ActiveRecord::Base.lease_connection.exec_query("SELECT 1 AS test") assert_equal ActiveModel::Type::Integer, result.column_types["test"].class end end diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index ee5c6c5d13..f8df51b975 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -151,7 +151,7 @@ def test_find_in_batches_shouldnt_execute_query_unless_needed end def test_find_in_batches_should_quote_batch_order - c = Post.connection + c = Post.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("posts.id"))}/i) do Post.find_in_batches(batch_size: 1) do |batch| assert_kind_of Array, batch @@ -161,7 +161,7 @@ def test_find_in_batches_should_quote_batch_order end def test_find_in_batches_should_quote_batch_order_with_desc_order - c = Post.connection + c = Post.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("posts.id"))} DESC/) do Post.find_in_batches(batch_size: 1, order: :desc) do |batch| assert_kind_of Array, batch @@ -514,7 +514,7 @@ def test_in_batches_should_end_at_the_finish_option end def test_in_batches_executes_range_queries_when_unconstrained - c = Post.connection + c = Post.lease_connection quoted_posts_id = Regexp.escape(c.quote_table_name("posts.id")) assert_queries_match(/WHERE #{quoted_posts_id} > .+ AND #{quoted_posts_id} <= .+/i) do Post.in_batches(of: 2) { |relation| assert_kind_of Post, relation.first } @@ -522,7 +522,7 @@ def test_in_batches_executes_range_queries_when_unconstrained end def test_in_batches_executes_in_queries_when_unconstrained_and_opted_out_of_ranges - c = Post.connection + c = Post.lease_connection quoted_posts_id = Regexp.escape(c.quote_table_name("posts.id")) assert_queries_match(/#{quoted_posts_id} IN \(.+\)/i) do Post.in_batches(of: 2, use_ranges: false) { |relation| assert_kind_of Post, relation.first } @@ -530,7 +530,7 @@ def test_in_batches_executes_in_queries_when_unconstrained_and_opted_out_of_rang end def test_in_batches_executes_in_queries_when_constrained - c = Post.connection + c = Post.lease_connection quoted_posts_id = Regexp.escape(c.quote_table_name("posts.id")) assert_queries_match(/#{quoted_posts_id} IN \(.+\)/i) do Post.where("id < ?", 5).in_batches(of: 2) { |relation| assert_kind_of Post, relation.first } @@ -538,7 +538,7 @@ def test_in_batches_executes_in_queries_when_constrained end def test_in_batches_executes_range_queries_when_constrained_and_opted_in_into_ranges - c = Post.connection + c = Post.lease_connection quoted_posts_id = Regexp.escape(c.quote_table_name("posts.id")) assert_queries_match(/#{quoted_posts_id} > .+ AND #{quoted_posts_id} <= .+/i) do Post.where("id < ?", 5).in_batches(of: 2, use_ranges: true) { |relation| assert_kind_of Post, relation.first } @@ -546,7 +546,7 @@ def test_in_batches_executes_range_queries_when_constrained_and_opted_in_into_ra end def test_in_batches_no_subqueries_for_whole_tables_batching - c = Post.connection + c = Post.lease_connection quoted_posts_id = Regexp.escape(c.quote_table_name("posts.id")) assert_queries_match(/DELETE FROM #{Regexp.escape(c.quote_table_name("posts"))} WHERE #{quoted_posts_id} > .+ AND #{quoted_posts_id} <=/i) do Post.in_batches(of: 2).delete_all @@ -564,7 +564,7 @@ def test_in_batches_shouldnt_execute_query_unless_needed end def test_in_batches_should_quote_batch_order - c = Post.connection + c = Post.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name('posts'))}\.#{Regexp.escape(c.quote_column_name('id'))}/) do Post.in_batches(of: 1) do |relation| assert_kind_of ActiveRecord::Relation, relation @@ -574,7 +574,7 @@ def test_in_batches_should_quote_batch_order end def test_in_batches_should_quote_batch_order_with_desc_order - c = Post.connection + c = Post.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("posts.id"))} DESC/) do Post.in_batches(of: 1, order: :desc) do |relation| assert_kind_of ActiveRecord::Relation, relation @@ -584,7 +584,7 @@ def test_in_batches_should_quote_batch_order_with_desc_order end def test_in_batches_enumerator_should_quote_batch_order_with_desc_order - c = Post.connection + c = Post.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("posts.id"))} DESC/) do relation = Post.in_batches(of: 1, order: :desc).first assert_kind_of ActiveRecord::Relation, relation @@ -593,7 +593,7 @@ def test_in_batches_enumerator_should_quote_batch_order_with_desc_order end def test_in_batches_enumerator_each_record_should_quote_batch_order_with_desc_order - c = Post.connection + c = Post.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("posts.id"))} DESC/) do Post.in_batches(of: 1, order: :desc).each_record do |record| assert_kind_of Post, record diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 4bdb6c9f62..5bef888f69 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -6,7 +6,7 @@ require "models/author" require "models/post" -if ActiveRecord::Base.connection.prepared_statements +if ActiveRecord::Base.lease_connection.prepared_statements module ActiveRecord class BindParameterTest < ActiveRecord::TestCase fixtures :topics, :authors, :author_addresses, :posts @@ -25,7 +25,7 @@ def call(*args) def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @subscriber = LogListener.new @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) end diff --git a/activerecord/test/cases/cache_key_test.rb b/activerecord/test/cases/cache_key_test.rb index 4e4e0bbd80..00401f55aa 100644 --- a/activerecord/test/cases/cache_key_test.rb +++ b/activerecord/test/cases/cache_key_test.rb @@ -15,7 +15,7 @@ class CacheMeWithVersion < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table(:cache_mes, force: true) { |t| t.timestamps } @connection.create_table(:cache_me_with_versions, force: true) { |t| t.timestamps } end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 9cc5c24d65..cec0f5a3fb 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -227,7 +227,7 @@ def test_should_calculate_against_given_relation end def test_should_not_use_alias_for_grouped_field - assert_queries_match(/GROUP BY #{Regexp.escape(Account.connection.quote_table_name("accounts.firm_id"))}/i) do + assert_queries_match(/GROUP BY #{Regexp.escape(Account.lease_connection.quote_table_name("accounts.firm_id"))}/i) do c = Account.group(:firm_id).order("accounts_firm_id").sum(:credit_limit) assert_equal [1, 2, 6, 9], c.keys.compact end @@ -468,7 +468,7 @@ def test_should_group_by_fields_with_table_alias end def test_should_calculate_grouped_with_longer_field - field = "a" * Account.connection.max_identifier_length + field = "a" * Account.lease_connection.max_identifier_length Account.update_all("#{field} = credit_limit") @@ -1130,7 +1130,7 @@ def test_group_by_with_limit_and_offset end def test_group_by_with_quoted_count_and_order_by_alias - quoted_posts_id = Post.connection.quote_table_name("posts.id") + quoted_posts_id = Post.lease_connection.quote_table_name("posts.id") expected = { "SpecialPost" => 1, "StiPost" => 1, "Post" => 9 } actual = Post.group(:type).order("count_posts_id").count(quoted_posts_id) assert_equal expected, actual @@ -1390,7 +1390,7 @@ def test_having_with_strong_parameters def test_count_takes_attribute_type_precedence_over_database_type assert_called( - Account.connection, :select_all, + Account.lease_connection, :select_all, returns: ActiveRecord::Result.new(["count"], [["10"]]) ) do result = Account.count @@ -1401,7 +1401,7 @@ def test_count_takes_attribute_type_precedence_over_database_type def test_sum_takes_attribute_type_precedence_over_database_type assert_called( - Account.connection, :select_all, + Account.lease_connection, :select_all, returns: ActiveRecord::Result.new(["sum"], [[10.to_d]]) ) do result = Account.sum(:credit_limit) diff --git a/activerecord/test/cases/column_alias_test.rb b/activerecord/test/cases/column_alias_test.rb index 58d23c08da..17c2c83b35 100644 --- a/activerecord/test/cases/column_alias_test.rb +++ b/activerecord/test/cases/column_alias_test.rb @@ -7,7 +7,7 @@ class TestColumnAlias < ActiveRecord::TestCase fixtures :topics def test_column_alias - records = Topic.connection.select_all("SELECT id AS pk FROM topics") + records = Topic.lease_connection.select_all("SELECT id AS pk FROM topics") assert_equal ["pk"], records.columns end end diff --git a/activerecord/test/cases/comment_test.rb b/activerecord/test/cases/comment_test.rb index 3f3dc00963..1838c5f25a 100644 --- a/activerecord/test/cases/comment_test.rb +++ b/activerecord/test/cases/comment_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_comments? +if ActiveRecord::Base.lease_connection.supports_comments? class CommentTest < ActiveRecord::TestCase include SchemaDumpingHelper @@ -18,7 +18,7 @@ class PkCommented < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table("commenteds", comment: "A table with comment", force: true) do |t| t.string "name", comment: "Comment should help clarify the column purpose" diff --git a/activerecord/test/cases/connection_adapters/adapter_leasing_test.rb b/activerecord/test/cases/connection_adapters/adapter_leasing_test.rb index 797c146ab5..8e0261b473 100644 --- a/activerecord/test/cases/connection_adapters/adapter_leasing_test.rb +++ b/activerecord/test/cases/connection_adapters/adapter_leasing_test.rb @@ -46,14 +46,14 @@ def test_close @adapter.pool = pool # Make sure the pool marks the connection in use - assert_equal @adapter, pool.connection + assert_equal @adapter, pool.lease_connection assert_predicate @adapter, :in_use? # Close should put the adapter back in the pool @adapter.close assert_not_predicate @adapter, :in_use? - assert_equal @adapter, pool.connection + assert_equal @adapter, pool.lease_connection end end end diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index 5e479f952c..5605a79c16 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -150,7 +150,7 @@ def test_establish_connection_using_3_level_config_defaults_to_default_env_prima ActiveRecord::Base.establish_connection - assert_match "test/db/primary.sqlite3", ActiveRecord::Base.connection.pool.db_config.database + assert_match "test/db/primary.sqlite3", ActiveRecord::Base.lease_connection.pool.db_config.database ensure ActiveRecord::Base.configurations = @prev_configs ENV["RAILS_ENV"] = previous_env @@ -172,7 +172,7 @@ def test_establish_connection_using_2_level_config_defaults_to_default_env_prima ActiveRecord::Base.establish_connection - assert_match "test/db/primary.sqlite3", ActiveRecord::Base.connection.pool.db_config.database + assert_match "test/db/primary.sqlite3", ActiveRecord::Base.lease_connection.pool.db_config.database ensure ActiveRecord::Base.configurations = @prev_configs ENV["RAILS_ENV"] = previous_env @@ -187,7 +187,7 @@ def test_establish_connection_using_two_level_configurations @handler.establish_connection(:development) assert_not_nil pool = @handler.retrieve_connection_pool("development") - assert_not_predicate pool.connection, :preventing_writes? + assert_not_predicate pool.lease_connection, :preventing_writes? assert_equal "test/db/primary.sqlite3", pool.db_config.database ensure ActiveRecord::Base.configurations = @prev_configs @@ -203,7 +203,7 @@ def test_establish_connection_using_top_level_key_in_two_level_config @handler.establish_connection(:development_readonly) assert_not_nil pool = @handler.retrieve_connection_pool("development_readonly") - assert_not_predicate pool.connection, :preventing_writes? + assert_not_predicate pool.lease_connection, :preventing_writes? assert_equal "test/db/readonly.sqlite3", pool.db_config.database ensure ActiveRecord::Base.configurations = @prev_configs @@ -219,7 +219,7 @@ def test_establish_connection_with_string_owner_name @handler.establish_connection(:development_readonly, owner_name: "custom_connection") assert_not_nil pool = @handler.retrieve_connection_pool("custom_connection") - assert_not_predicate pool.connection, :preventing_writes? + assert_not_predicate pool.lease_connection, :preventing_writes? assert_equal "test/db/readonly.sqlite3", pool.db_config.database ensure ActiveRecord::Base.configurations = @prev_configs @@ -282,15 +282,15 @@ def test_connection_pools def test_a_class_using_custom_pool_and_switching_back_to_primary klass2 = Class.new(Base) { def self.name; "klass2"; end } - assert_same klass2.connection, ActiveRecord::Base.connection + assert_same klass2.lease_connection, ActiveRecord::Base.lease_connection pool = klass2.establish_connection(ActiveRecord::Base.connection_pool.db_config.configuration_hash) - assert_same klass2.connection, pool.connection - assert_not_same klass2.connection, ActiveRecord::Base.connection + assert_same klass2.lease_connection, pool.lease_connection + assert_not_same klass2.lease_connection, ActiveRecord::Base.lease_connection klass2.remove_connection - assert_same klass2.connection, ActiveRecord::Base.connection + assert_same klass2.lease_connection, ActiveRecord::Base.lease_connection end class ApplicationRecord < ActiveRecord::Base @@ -327,8 +327,8 @@ def test_connection_specification_name_should_fallback_to_parent def test_remove_connection_should_not_remove_parent klass2 = Class.new(Base) { def self.name; "klass2"; end } klass2.remove_connection - assert_not_nil ActiveRecord::Base.connection - assert_same klass2.connection, ActiveRecord::Base.connection + assert_not_nil ActiveRecord::Base.lease_connection + assert_same klass2.lease_connection, ActiveRecord::Base.lease_connection end def test_default_handlers_are_writing_and_reading @@ -338,7 +338,7 @@ def test_default_handlers_are_writing_and_reading if Process.respond_to?(:fork) def test_connection_pool_per_pid - object_id = ActiveRecord::Base.connection.object_id + object_id = ActiveRecord::Base.lease_connection.object_id rd, wr = IO.pipe rd.binmode @@ -346,7 +346,7 @@ def test_connection_pool_per_pid pid = fork { rd.close - wr.write Marshal.dump ActiveRecord::Base.connection.object_id + wr.write Marshal.dump ActiveRecord::Base.lease_connection.object_id wr.close exit! } @@ -359,8 +359,8 @@ def test_connection_pool_per_pid end def test_forked_child_doesnt_mangle_parent_connection - object_id = ActiveRecord::Base.connection.object_id - assert_predicate ActiveRecord::Base.connection, :active? + object_id = ActiveRecord::Base.lease_connection.object_id + assert_predicate ActiveRecord::Base.lease_connection, :active? rd, wr = IO.pipe rd.binmode @@ -369,7 +369,7 @@ def test_forked_child_doesnt_mangle_parent_connection pid = fork { rd.close wr.write Marshal.dump [ - ActiveRecord::Base.connection.object_id, + ActiveRecord::Base.lease_connection.object_id, ] wr.close @@ -383,27 +383,27 @@ def test_forked_child_doesnt_mangle_parent_connection assert_not_equal object_id, child_id rd.close - assert_equal 3, ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM people") + assert_equal 3, ActiveRecord::Base.lease_connection.select_value("SELECT COUNT(*) FROM people") end unless in_memory_db? def test_forked_child_recovers_from_disconnected_parent - object_id = ActiveRecord::Base.connection.object_id - assert_predicate ActiveRecord::Base.connection, :active? + object_id = ActiveRecord::Base.lease_connection.object_id + assert_predicate ActiveRecord::Base.lease_connection, :active? rd, wr = IO.pipe rd.binmode wr.binmode outer_pid = fork { - ActiveRecord::Base.connection.disconnect! + ActiveRecord::Base.lease_connection.disconnect! pid = fork { rd.close wr.write Marshal.dump [ - !!ActiveRecord::Base.connection.active?, - ActiveRecord::Base.connection.object_id, - ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM people"), + !!ActiveRecord::Base.lease_connection.active?, + ActiveRecord::Base.lease_connection.object_id, + ActiveRecord::Base.lease_connection.select_value("SELECT COUNT(*) FROM people"), ] wr.close @@ -425,7 +425,7 @@ def test_forked_child_recovers_from_disconnected_parent assert_equal 3, child_count # Outer connection is unaffected - assert_equal 6, ActiveRecord::Base.connection.select_value("SELECT 2 * COUNT(*) FROM people") + assert_equal 6, ActiveRecord::Base.lease_connection.select_value("SELECT 2 * COUNT(*) FROM people") end end diff --git a/activerecord/test/cases/connection_adapters/connection_handlers_multi_db_test.rb b/activerecord/test/cases/connection_adapters/connection_handlers_multi_db_test.rb index ae54da2271..7b95129fc9 100644 --- a/activerecord/test/cases/connection_adapters/connection_handlers_multi_db_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handlers_multi_db_test.rb @@ -37,30 +37,30 @@ def test_multiple_connections_works_in_a_threaded_environment # and won't be able to write to the second connection. SecondaryBase.connects_to database: { writing: { database: tf_writing.path, adapter: "sqlite3" }, secondary: { database: tf_reading.path, adapter: "sqlite3" } } - MultiConnectionTestModel.connection.execute("CREATE TABLE `multi_connection_test_models` (connection_role VARCHAR (255))") - MultiConnectionTestModel.connection.execute("INSERT INTO multi_connection_test_models VALUES ('writing')") + MultiConnectionTestModel.lease_connection.execute("CREATE TABLE `multi_connection_test_models` (connection_role VARCHAR (255))") + MultiConnectionTestModel.lease_connection.execute("INSERT INTO multi_connection_test_models VALUES ('writing')") ActiveRecord::Base.connected_to(role: :secondary) do - MultiConnectionTestModel.connection.execute("CREATE TABLE `multi_connection_test_models` (connection_role VARCHAR (255))") - MultiConnectionTestModel.connection.execute("INSERT INTO multi_connection_test_models VALUES ('reading')") + MultiConnectionTestModel.lease_connection.execute("CREATE TABLE `multi_connection_test_models` (connection_role VARCHAR (255))") + MultiConnectionTestModel.lease_connection.execute("INSERT INTO multi_connection_test_models VALUES ('reading')") end read_latch = Concurrent::CountDownLatch.new write_latch = Concurrent::CountDownLatch.new - MultiConnectionTestModel.connection + MultiConnectionTestModel.lease_connection thread = Thread.new do - MultiConnectionTestModel.connection + MultiConnectionTestModel.lease_connection write_latch.wait - assert_equal "writing", MultiConnectionTestModel.connection.select_value("SELECT connection_role from multi_connection_test_models") + assert_equal "writing", MultiConnectionTestModel.lease_connection.select_value("SELECT connection_role from multi_connection_test_models") read_latch.count_down end ActiveRecord::Base.connected_to(role: :secondary) do write_latch.count_down - assert_equal "reading", MultiConnectionTestModel.connection.select_value("SELECT connection_role from multi_connection_test_models") + assert_equal "reading", MultiConnectionTestModel.lease_connection.select_value("SELECT connection_role from multi_connection_test_models") read_latch.wait end @@ -78,7 +78,7 @@ def test_loading_relations_with_multi_db_connections SecondaryBase.connects_to database: { writing: { database: ":memory:", adapter: "sqlite3" }, secondary: { database: ":memory:", adapter: "sqlite3" } } relation = ActiveRecord::Base.connected_to(role: :secondary) do - MultiConnectionTestModel.connection.execute("CREATE TABLE `multi_connection_test_models` (connection_role VARCHAR (255))") + MultiConnectionTestModel.lease_connection.execute("CREATE TABLE `multi_connection_test_models` (connection_role VARCHAR (255))") MultiConnectionTestModel.create!(connection_role: "reading") MultiConnectionTestModel.where(connection_role: "reading") end @@ -130,14 +130,14 @@ def test_switching_connections_via_handler assert_equal :reading, ActiveRecord::Base.current_role assert ActiveRecord::Base.connected_to?(role: :reading) assert_not ActiveRecord::Base.connected_to?(role: :writing) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end ActiveRecord::Base.connected_to(role: :writing) do assert_equal :writing, ActiveRecord::Base.current_role assert ActiveRecord::Base.connected_to?(role: :writing) assert_not ActiveRecord::Base.connected_to?(role: :reading) - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end ensure ActiveRecord::Base.configurations = @prev_configs diff --git a/activerecord/test/cases/connection_adapters/connection_handlers_sharding_db_test.rb b/activerecord/test/cases/connection_adapters/connection_handlers_sharding_db_test.rb index 1e887c0d8b..100fd53486 100644 --- a/activerecord/test/cases/connection_adapters/connection_handlers_sharding_db_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handlers_sharding_db_test.rb @@ -128,7 +128,7 @@ def test_switching_connections_via_handler assert_not ActiveRecord::Base.connected_to?(role: :writing, shard: :default) assert_not ActiveRecord::Base.connected_to?(role: :writing, shard: :shard_one) assert_not ActiveRecord::Base.connected_to?(role: :reading, shard: :shard_one) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end ActiveRecord::Base.connected_to(role: :writing, shard: :default) do @@ -137,7 +137,7 @@ def test_switching_connections_via_handler assert_not ActiveRecord::Base.connected_to?(role: :reading, shard: :default) assert_not ActiveRecord::Base.connected_to?(role: :reading, shard: :shard_one) assert_not ActiveRecord::Base.connected_to?(role: :writing, shard: :shard_one) - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end ActiveRecord::Base.connected_to(role: :reading, shard: :shard_one) do @@ -146,7 +146,7 @@ def test_switching_connections_via_handler assert_not ActiveRecord::Base.connected_to?(role: :writing, shard: :shard_one) assert_not ActiveRecord::Base.connected_to?(role: :writing, shard: :default) assert_not ActiveRecord::Base.connected_to?(role: :reading, shard: :default) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end ActiveRecord::Base.connected_to(role: :writing, shard: :shard_one) do @@ -155,7 +155,7 @@ def test_switching_connections_via_handler assert_not ActiveRecord::Base.connected_to?(role: :reading, shard: :shard_one) assert_not ActiveRecord::Base.connected_to?(role: :reading, shard: :default) assert_not ActiveRecord::Base.connected_to?(role: :writing, shard: :default) - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end ensure ActiveRecord::Base.configurations = @prev_configs @@ -323,10 +323,10 @@ def test_same_shards_across_clusters SomeOtherBase.connects_to shards: { one: { writing: { database: ":memory:", adapter: "sqlite3" } } } ActiveRecord::Base.connected_to(role: :writing, shard: :one) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") ShardConnectionTestModel.create!(shard_key: "test_model_default") - ShardConnectionTestModelB.connection.execute("CREATE TABLE `shard_connection_test_model_bs` (shard_key VARCHAR (255))") + ShardConnectionTestModelB.lease_connection.execute("CREATE TABLE `shard_connection_test_model_bs` (shard_key VARCHAR (255))") ShardConnectionTestModelB.create!(shard_key: "test_model_b_default") assert_equal "test_model_default", ShardConnectionTestModel.where(shard_key: "test_model_default").first.shard_key @@ -342,7 +342,7 @@ def test_sharding_separation [:default, :one].each do |shard_name| ActiveRecord::Base.connected_to(role: :writing, shard: shard_name) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") end end @@ -378,27 +378,27 @@ def test_swapping_shards_globally_in_a_multi_threaded_environment [:default, :one].each do |shard_name| ActiveRecord::Base.connected_to(role: :writing, shard: shard_name) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModel.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}')") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}')") end end shard_one_latch = Concurrent::CountDownLatch.new shard_default_latch = Concurrent::CountDownLatch.new - ShardConnectionTestModel.connection + ShardConnectionTestModel.lease_connection thread = Thread.new do - ShardConnectionTestModel.connection + ShardConnectionTestModel.lease_connection shard_default_latch.wait - assert_equal "shard_key_default", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_default", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") shard_one_latch.count_down end ActiveRecord::Base.connected_to(role: :writing, shard: :one) do shard_default_latch.count_down - assert_equal "shard_key_one", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_one", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") shard_one_latch.wait end @@ -423,32 +423,32 @@ def test_swapping_shards_and_roles_in_a_multi_threaded_environment [:default, :one].each do |shard_name| ActiveRecord::Base.connected_to(role: :writing, shard: shard_name) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModel.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}')") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}')") end ActiveRecord::Base.connected_to(role: :secondary, shard: shard_name) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModel.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_secondary')") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_secondary')") end end shard_one_latch = Concurrent::CountDownLatch.new shard_default_latch = Concurrent::CountDownLatch.new - ShardConnectionTestModel.connection + ShardConnectionTestModel.lease_connection thread = Thread.new do - ShardConnectionTestModel.connection + ShardConnectionTestModel.lease_connection shard_default_latch.wait - assert_equal "shard_key_default", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_default", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") shard_one_latch.count_down end ActiveRecord::Base.connected_to(shard: :one, role: :secondary) do shard_default_latch.count_down - assert_equal "shard_key_one_secondary", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_one_secondary", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") shard_one_latch.wait end @@ -486,42 +486,42 @@ def test_swapping_granular_shards_and_roles_in_a_multi_threaded_environment [:default, :one].each do |shard_name| ActiveRecord::Base.connected_to(role: :writing, shard: shard_name) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModel.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}')") - ShardConnectionTestModelB.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModelB.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_b')") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}')") + ShardConnectionTestModelB.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModelB.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_b')") end ActiveRecord::Base.connected_to(role: :secondary, shard: shard_name) do - ShardConnectionTestModel.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModel.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_secondary')") - ShardConnectionTestModelB.connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") - ShardConnectionTestModelB.connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_secondary_b')") + ShardConnectionTestModel.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModel.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_secondary')") + ShardConnectionTestModelB.lease_connection.execute("CREATE TABLE `shard_connection_test_models` (shard_key VARCHAR (255))") + ShardConnectionTestModelB.lease_connection.execute("INSERT INTO `shard_connection_test_models` VALUES ('shard_key_#{shard_name}_secondary_b')") end end shard_one_latch = Concurrent::CountDownLatch.new shard_default_latch = Concurrent::CountDownLatch.new - ShardConnectionTestModel.connection + ShardConnectionTestModel.lease_connection thread = Thread.new do - ShardConnectionTestModel.connection + ShardConnectionTestModel.lease_connection shard_default_latch.wait - assert_equal "shard_key_default", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") - assert_equal "shard_key_default_b", ShardConnectionTestModelB.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_default", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_default_b", ShardConnectionTestModelB.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") shard_one_latch.count_down end SecondaryBase.connected_to(shard: :one, role: :secondary) do shard_default_latch.count_down - assert_equal "shard_key_one_secondary", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") - assert_equal "shard_key_default_b", ShardConnectionTestModelB.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_one_secondary", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_default_b", ShardConnectionTestModelB.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") SomeOtherBase.connected_to(shard: :one, role: :secondary) do - assert_equal "shard_key_one_secondary", ShardConnectionTestModel.connection.select_value("SELECT shard_key from shard_connection_test_models") - assert_equal "shard_key_one_secondary_b", ShardConnectionTestModelB.connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_one_secondary", ShardConnectionTestModel.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") + assert_equal "shard_key_one_secondary_b", ShardConnectionTestModelB.lease_connection.select_value("SELECT shard_key from shard_connection_test_models") end shard_one_latch.wait end diff --git a/activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb b/activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb index ed7b3b27ae..16ce98ec1e 100644 --- a/activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb @@ -385,44 +385,44 @@ def test_prevent_writes_can_be_changed_granularly # Switch everything to writing ActiveRecord::Base.connected_to(role: :writing) do - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? - assert_not_predicate PrimaryBase.connection, :preventing_writes? - assert_not_predicate SecondaryBase.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? + assert_not_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_not_predicate SecondaryBase.lease_connection, :preventing_writes? # Switch only primary to reading PrimaryBase.connected_to(role: :reading) do - assert_predicate PrimaryBase.connection, :preventing_writes? - assert_not_predicate SecondaryBase.connection, :preventing_writes? + assert_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_not_predicate SecondaryBase.lease_connection, :preventing_writes? # Switch global to reading ActiveRecord::Base.connected_to(role: :reading) do - assert_predicate PrimaryBase.connection, :preventing_writes? - assert_predicate SecondaryBase.connection, :preventing_writes? + assert_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_predicate SecondaryBase.lease_connection, :preventing_writes? # Switch only secondary to writing SecondaryBase.connected_to(role: :writing) do - assert_predicate PrimaryBase.connection, :preventing_writes? - assert_not_predicate SecondaryBase.connection, :preventing_writes? + assert_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_not_predicate SecondaryBase.lease_connection, :preventing_writes? end # Ensure restored to global reading - assert_predicate PrimaryBase.connection, :preventing_writes? - assert_predicate SecondaryBase.connection, :preventing_writes? + assert_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_predicate SecondaryBase.lease_connection, :preventing_writes? end # Switch everything to writing ActiveRecord::Base.connected_to(role: :writing) do - assert_not_predicate PrimaryBase.connection, :preventing_writes? - assert_not_predicate SecondaryBase.connection, :preventing_writes? + assert_not_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_not_predicate SecondaryBase.lease_connection, :preventing_writes? end - assert_predicate PrimaryBase.connection, :preventing_writes? - assert_not_predicate SecondaryBase.connection, :preventing_writes? + assert_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_not_predicate SecondaryBase.lease_connection, :preventing_writes? end # Ensure restored to global writing - assert_not_predicate PrimaryBase.connection, :preventing_writes? - assert_not_predicate SecondaryBase.connection, :preventing_writes? + assert_not_predicate PrimaryBase.lease_connection, :preventing_writes? + assert_not_predicate SecondaryBase.lease_connection, :preventing_writes? end ensure ActiveRecord::Base.configurations = @prev_configs @@ -441,17 +441,17 @@ def test_application_record_prevent_writes_can_be_changed # Switch everything to writing ActiveRecord::Base.connected_to(role: :writing) do - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? - assert_not_predicate ApplicationRecord.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? + assert_not_predicate ApplicationRecord.lease_connection, :preventing_writes? ApplicationRecord.connected_to(role: :reading) do - assert_predicate ApplicationRecord.connection, :preventing_writes? + assert_predicate ApplicationRecord.lease_connection, :preventing_writes? end # reading is fine bc it's looking up by AppRec but writing is not fine # bc its looking up by ARB in the stack ApplicationRecord.connected_to(role: :writing, prevent_writes: true) do - assert_predicate ApplicationRecord.connection, :preventing_writes? + assert_predicate ApplicationRecord.lease_connection, :preventing_writes? end end ensure diff --git a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb index 14a128499d..548c59bde7 100644 --- a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb @@ -10,7 +10,7 @@ class MysqlTypeLookupTest < ActiveRecord::TestCase include ConnectionHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown diff --git a/activerecord/test/cases/connection_adapters/schema_cache_test.rb b/activerecord/test/cases/connection_adapters/schema_cache_test.rb index ffc9167714..f816d9e9f8 100644 --- a/activerecord/test/cases/connection_adapters/schema_cache_test.rb +++ b/activerecord/test/cases/connection_adapters/schema_cache_test.rb @@ -9,7 +9,7 @@ class SchemaCacheTest < ActiveRecord::TestCase def setup @pool = ARUnit2Model.connection_pool - @connection = ARUnit2Model.connection + @connection = ARUnit2Model.lease_connection @cache = new_bound_reflection @check_schema_cache_dump_version_was = SchemaReflection.check_schema_cache_dump_version end @@ -372,7 +372,7 @@ def test_when_lazily_load_schema_cache_is_set_cache_is_lazily_populated_when_est old_config = ActiveRecord.lazily_load_schema_cache ActiveRecord.lazily_load_schema_cache = true ActiveRecord::Base.establish_connection(new_config) - ActiveRecord::Base.connection_pool.connection.verify! + ActiveRecord::Base.connection_pool.lease_connection.verify! assert File.exist?(tempfile) assert_not_nil ActiveRecord::Base.connection_pool.schema_reflection.instance_variable_get(:@cache) diff --git a/activerecord/test/cases/connection_adapters/type_lookup_test.rb b/activerecord/test/cases/connection_adapters/type_lookup_test.rb index fb1c3f2ddf..e7dde9d0bb 100644 --- a/activerecord/test/cases/connection_adapters/type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/type_lookup_test.rb @@ -7,7 +7,7 @@ module ConnectionAdapters class TypeLookupTest < ActiveRecord::TestCase unless current_adapter?(:PostgreSQLAdapter) # PostgreSQL does not use type strings for lookup setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_boolean_types diff --git a/activerecord/test/cases/connection_handling_test.rb b/activerecord/test/cases/connection_handling_test.rb index bd2314795b..22cf82f874 100644 --- a/activerecord/test/cases/connection_handling_test.rb +++ b/activerecord/test/cases/connection_handling_test.rb @@ -25,43 +25,43 @@ class ConnectionHandlingTest < ActiveRecord::TestCase conn = connection assert_predicate ActiveRecord::Base.connection_pool, :active_connection? 2.times do - assert_same connection, ActiveRecord::Base.connection + assert_same connection, ActiveRecord::Base.lease_connection end end assert_predicate ActiveRecord::Base.connection_pool, :active_connection? - assert_same conn, ActiveRecord::Base.connection + assert_same conn, ActiveRecord::Base.lease_connection end test "#with_connection use the already leased connection if available" do - leased_connection = ActiveRecord::Base.connection + leased_connection = ActiveRecord::Base.lease_connection assert_predicate ActiveRecord::Base.connection_pool, :active_connection? ActiveRecord::Base.with_connection do |connection| assert_same leased_connection, connection - assert_same ActiveRecord::Base.connection, connection + assert_same ActiveRecord::Base.lease_connection, connection end assert_predicate ActiveRecord::Base.connection_pool, :active_connection? - assert_same ActiveRecord::Base.connection, leased_connection + assert_same ActiveRecord::Base.lease_connection, leased_connection end test "#with_connection is reentrant" do - leased_connection = ActiveRecord::Base.connection + leased_connection = ActiveRecord::Base.lease_connection assert_predicate ActiveRecord::Base.connection_pool, :active_connection? ActiveRecord::Base.with_connection do |connection| assert_same leased_connection, connection - assert_same ActiveRecord::Base.connection, connection + assert_same ActiveRecord::Base.lease_connection, connection ActiveRecord::Base.with_connection do |connection2| assert_same leased_connection, connection2 - assert_same ActiveRecord::Base.connection, connection2 + assert_same ActiveRecord::Base.lease_connection, connection2 end end assert_predicate ActiveRecord::Base.connection_pool, :active_connection? - assert_same ActiveRecord::Base.connection, leased_connection + assert_same ActiveRecord::Base.lease_connection, leased_connection end end end diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb index 822bdeeec8..49aa925748 100644 --- a/activerecord/test/cases/connection_management_test.rb +++ b/activerecord/test/cases/connection_management_test.rb @@ -26,7 +26,7 @@ def setup @management = middleware(@app) # make sure we have an active connection - assert ActiveRecord::Base.connection + assert ActiveRecord::Base.lease_connection assert ActiveRecord::Base.connection_handler.active_connections?(:all) end @@ -75,7 +75,7 @@ def test_connections_not_closed_if_exception_inside_transaction end test "cancel asynchronous queries if an exception is raised" do - unless ActiveRecord::Base.connection.supports_concurrent_connections? + unless ActiveRecord::Base.lease_connection.supports_concurrent_connections? skip "This adapter doesn't support asynchronous queries" end @@ -83,7 +83,7 @@ def test_connections_not_closed_if_exception_inside_transaction attr_reader :future_result def call(env) - @future_result = ActiveRecord::Base.connection.select_all("SELECT * FROM does_not_exists", async: true) + @future_result = ActiveRecord::Base.lease_connection.select_all("SELECT * FROM does_not_exists", async: true) raise NotImplementedError end end.new diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 9108aec46b..71a00bc934 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -47,13 +47,13 @@ def teardown end def test_checkout_after_close - connection = pool.connection + connection = pool.lease_connection assert_predicate connection, :in_use? connection.close assert_not_predicate connection, :in_use? - assert_predicate pool.connection, :in_use? + assert_predicate pool.lease_connection, :in_use? end def test_released_connection_moves_between_threads @@ -77,7 +77,7 @@ def test_released_connection_moves_between_threads def test_with_connection assert_equal 0, active_connections(pool).size - main_thread = pool.connection + main_thread = pool.lease_connection assert_equal 1, active_connections(pool).size new_thread { @@ -90,7 +90,7 @@ def test_with_connection pool.with_connection do |conn| assert conn assert_equal 2, active_connections(pool).size - pool.connection # lease + pool.lease_connection end assert_equal 2, active_connections(pool).size @@ -116,7 +116,7 @@ def test_new_connection_no_query def test_active_connection_in_use assert_not_predicate pool, :active_connection? - main_thread = pool.connection + main_thread = pool.lease_connection assert_predicate pool, :active_connection? @@ -367,16 +367,16 @@ def test_remove_connection end def test_remove_connection_for_thread - conn = @pool.connection + conn = @pool.lease_connection @pool.remove conn - assert_not_equal(conn, @pool.connection) + assert_not_equal(conn, @pool.lease_connection) ensure conn.close if conn end def test_active_connection? assert_not_predicate @pool, :active_connection? - assert @pool.connection + assert @pool.lease_connection assert_predicate @pool, :active_connection? @pool.release_connection assert_not_predicate @pool, :active_connection? @@ -384,12 +384,12 @@ def test_active_connection? def test_checkout_behavior pool = ConnectionPool.new(@pool_config) - main_connection = pool.connection + main_connection = pool.lease_connection assert_not_nil main_connection threads = [] 4.times do |i| threads << new_thread(i) do - thread_connection = pool.connection + thread_connection = pool.lease_connection assert_not_nil thread_connection thread_connection.close end @@ -398,8 +398,8 @@ def test_checkout_behavior threads.each(&:join) new_thread do - assert pool.connection - pool.connection.close + assert pool.lease_connection + pool.lease_connection.close end.join end @@ -533,10 +533,10 @@ def test_checkout_fairness_by_group def test_automatic_reconnect_restores_after_disconnect pool = ConnectionPool.new(@pool_config) assert pool.automatic_reconnect - assert pool.connection + assert pool.lease_connection pool.disconnect! - assert pool.connection + assert pool.lease_connection end def test_automatic_reconnect_can_be_disabled @@ -545,7 +545,7 @@ def test_automatic_reconnect_can_be_disabled pool.automatic_reconnect = false assert_raises(ConnectionNotEstablished) do - pool.connection + pool.lease_connection end assert_raises(ConnectionNotEstablished) do @@ -554,7 +554,7 @@ def test_automatic_reconnect_can_be_disabled end def test_pool_sets_connection_visitor - assert @pool.connection.visitor.is_a?(Arel::Visitors::ToSql) + assert @pool.lease_connection.visitor.is_a?(Arel::Visitors::ToSql) end # make sure exceptions are thrown when establish_connection @@ -710,7 +710,7 @@ def test_bang_versions_of_disconnect_and_clear_reloadable_connections_if_unable_ assert_not_predicate @pool, :active_connection? # make a new connection for with_connection to clean up - @pool.connection + @pool.lease_connection end @pool.release_connection @@ -720,7 +720,7 @@ def test_bang_versions_of_disconnect_and_clear_reloadable_connections_if_unable_ assert_not_predicate @pool, :active_connection? # make a new connection for with_connection to clean up - @pool.connection + @pool.lease_connection end end @@ -728,7 +728,7 @@ def test_disconnect_and_clear_reloadable_connections_are_able_to_preempt_other_w skip_fiber_testing with_single_connection_pool do |pool| [:disconnect, :disconnect!, :clear_reloadable_connections, :clear_reloadable_connections!].each do |group_action_method| - conn = pool.connection # drain the only available connection + conn = pool.lease_connection # drain the only available connection second_thread_done = Concurrent::Event.new begin @@ -780,7 +780,7 @@ def test_disconnect_and_clear_reloadable_connections_are_able_to_preempt_other_w def test_clear_reloadable_connections_creates_new_connections_for_waiting_threads_if_necessary skip_fiber_testing with_single_connection_pool do |pool| - conn = pool.connection # drain the only available connection + conn = pool.lease_connection # drain the only available connection def conn.requires_reloading? # make sure it gets removed from the pool by clear_reloadable_connections true end @@ -852,11 +852,11 @@ def test_public_connections_access_threadsafe def test_role_and_shard_is_returned assert_equal :writing, @pool_config.role assert_equal :writing, @pool.role - assert_equal :writing, @pool.connection.role + assert_equal :writing, @pool.lease_connection.role assert_equal :default, @pool_config.shard assert_equal :default, @pool.shard - assert_equal :default, @pool.connection.shard + assert_equal :default, @pool.lease_connection.shard db_config = ActiveRecord::Base.connection_pool.db_config pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config, :reading, :shard_one) @@ -864,11 +864,11 @@ def test_role_and_shard_is_returned assert_equal :reading, pool_config.role assert_equal :reading, pool.role - assert_equal :reading, pool.connection.role + assert_equal :reading, pool.lease_connection.role assert_equal :shard_one, pool_config.shard assert_equal :shard_one, pool.shard - assert_equal :shard_one, pool.connection.shard + assert_equal :shard_one, pool.lease_connection.shard end def test_pin_connection_always_returns_the_same_connection @@ -877,7 +877,7 @@ def test_pin_connection_always_returns_the_same_connection pinned_connection = @pool.checkout assert_not_predicate @pool, :active_connection? - assert_same pinned_connection, @pool.connection + assert_same pinned_connection, @pool.lease_connection assert_predicate @pool, :active_connection? assert_same pinned_connection, @pool.checkout @@ -903,22 +903,22 @@ def test_pin_connection_connected? end def test_pin_connection_synchronize_the_connection - assert_equal ActiveSupport::Concurrency::NullLock, @pool.connection.lock + assert_equal ActiveSupport::Concurrency::NullLock, @pool.lease_connection.lock @pool.pin_connection!(true) - assert_not_equal ActiveSupport::Concurrency::NullLock, @pool.connection.lock + assert_not_equal ActiveSupport::Concurrency::NullLock, @pool.lease_connection.lock @pool.unpin_connection! - assert_equal ActiveSupport::Concurrency::NullLock, @pool.connection.lock + assert_equal ActiveSupport::Concurrency::NullLock, @pool.lease_connection.lock @pool.pin_connection!(false) - assert_equal ActiveSupport::Concurrency::NullLock, @pool.connection.lock + assert_equal ActiveSupport::Concurrency::NullLock, @pool.lease_connection.lock end def test_pin_connection_opens_a_transaction - assert_instance_of NullTransaction, @pool.connection.current_transaction + assert_instance_of NullTransaction, @pool.lease_connection.current_transaction @pool.pin_connection!(true) - assert_instance_of RealTransaction, @pool.connection.current_transaction + assert_instance_of RealTransaction, @pool.lease_connection.current_transaction @pool.unpin_connection! - assert_instance_of NullTransaction, @pool.connection.current_transaction + assert_instance_of NullTransaction, @pool.lease_connection.current_transaction end def test_unpin_connection_returns_whether_transaction_has_been_rolledback @@ -926,11 +926,11 @@ def test_unpin_connection_returns_whether_transaction_has_been_rolledback assert_equal true, @pool.unpin_connection! @pool.pin_connection!(true) - @pool.connection.commit_transaction + @pool.lease_connection.commit_transaction assert_equal false, @pool.unpin_connection! @pool.pin_connection!(true) - @pool.connection.rollback_transaction + @pool.lease_connection.rollback_transaction assert_equal false, @pool.unpin_connection! end diff --git a/activerecord/test/cases/core_test.rb b/activerecord/test/cases/core_test.rb index d6c86786b4..feb0fca260 100644 --- a/activerecord/test/cases/core_test.rb +++ b/activerecord/test/cases/core_test.rb @@ -167,7 +167,7 @@ def test_pretty_print_with_non_primary_key_id_attribute def test_find_by_cache_does_not_duplicate_entries Topic.initialize_find_by_cache - using_prepared_statements = Topic.connection.prepared_statements + using_prepared_statements = Topic.lease_connection.prepared_statements topic_find_by_cache = Topic.instance_variable_get("@find_by_statement_cache")[using_prepared_statements] assert_difference -> { topic_find_by_cache.size }, +1 do diff --git a/activerecord/test/cases/database_selector_test.rb b/activerecord/test/cases/database_selector_test.rb index 83b2160291..3876afe2d7 100644 --- a/activerecord/test/cases/database_selector_test.rb +++ b/activerecord/test/cases/database_selector_test.rb @@ -62,15 +62,15 @@ def test_can_write_while_reading_from_replicas_if_explicit called = true assert ActiveRecord::Base.connected_to?(role: :reading) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? ActiveRecord::Base.connected_to(role: :writing, prevent_writes: false) do assert ActiveRecord::Base.connected_to?(role: :writing) - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end assert ActiveRecord::Base.connected_to?(role: :reading) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end assert called end @@ -202,12 +202,12 @@ def test_preventing_writes_turns_off_for_primary_write write = false resolver.read do assert ActiveRecord::Base.connected_to?(role: :writing) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? read = true resolver.write do assert ActiveRecord::Base.connected_to?(role: :writing) - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? write = true end end @@ -227,7 +227,7 @@ def test_preventing_writes_works_in_a_threaded_environment resolver.read do inside_preventing.wait assert ActiveRecord::Base.connected_to?(role: :writing) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? finished_checking.set end end @@ -235,7 +235,7 @@ def test_preventing_writes_works_in_a_threaded_environment t2 = Thread.new do resolver.write do assert ActiveRecord::Base.connected_to?(role: :writing) - assert_not_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_not_predicate ActiveRecord::Base.lease_connection, :preventing_writes? inside_preventing.set finished_checking.wait end @@ -244,7 +244,7 @@ def test_preventing_writes_works_in_a_threaded_environment t3 = Thread.new do resolver.read do assert ActiveRecord::Base.connected_to?(role: :writing) - assert_predicate ActiveRecord::Base.connection, :preventing_writes? + assert_predicate ActiveRecord::Base.lease_connection, :preventing_writes? end end diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb index 119d48b85e..ee25c54528 100644 --- a/activerecord/test/cases/database_statements_test.rb +++ b/activerecord/test/cases/database_statements_test.rb @@ -4,7 +4,7 @@ class DatabaseStatementsTest < ActiveRecord::TestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end unless current_adapter?(:OracleAdapter) diff --git a/activerecord/test/cases/date_time_precision_test.rb b/activerecord/test/cases/date_time_precision_test.rb index a8c6cf4312..b6bb81c99f 100644 --- a/activerecord/test/cases/date_time_precision_test.rb +++ b/activerecord/test/cases/date_time_precision_test.rb @@ -12,7 +12,7 @@ class DateTimePrecisionTest < ActiveRecord::TestCase class Foo < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection Foo.reset_column_information end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index d0663ad312..5b5bd7c682 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -27,7 +27,7 @@ class DefaultNumbersTest < ActiveRecord::TestCase class DefaultNumber < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :default_numbers do |t| t.integer :positive_integer, default: 7 t.integer :negative_integer, default: -5 @@ -62,7 +62,7 @@ class DefaultStringsTest < ActiveRecord::TestCase class DefaultString < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :default_strings do |t| t.string :string_col, default: "Smith" t.string :string_col_with_quotes, default: "O'Connor" @@ -88,7 +88,7 @@ class DefaultBinaryTest < ActiveRecord::TestCase class DefaultBinary < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :default_binaries do |t| t.binary :varbinary_col, null: false, limit: 64, default: "varbinary_default" t.binary :varbinary_col_hex_looking, null: false, limit: 64, default: "0xDEADBEEF" @@ -100,7 +100,7 @@ def test_default_varbinary_string assert_equal "varbinary_default", DefaultBinary.new.varbinary_col end - if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) && !ActiveRecord::Base.connection.mariadb? + if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) && !ActiveRecord::Base.lease_connection.mariadb? def test_default_binary_string assert_equal "binary_default", DefaultBinary.new.binary_col end @@ -121,7 +121,7 @@ class DefaultTextTest < ActiveRecord::TestCase class DefaultText < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :default_texts do |t| t.text :text_col, default: "Smith" t.text :text_col_with_quotes, default: "O'Connor" @@ -149,7 +149,7 @@ class PostgresqlDefaultExpressionTest < ActiveRecord::TestCase test "schema dump includes default expression" do output = dump_table_schema("defaults") - if ActiveRecord::Base.connection.database_version >= 100000 + if ActiveRecord::Base.lease_connection.database_version >= 100000 assert_match %r/t\.date\s+"modified_date",\s+default: -> { "CURRENT_DATE" }/, output assert_match %r/t\.datetime\s+"modified_time",\s+default: -> { "CURRENT_TIMESTAMP" }/, output assert_match %r/t\.datetime\s+"modified_time_without_precision",\s+precision: nil,\s+default: -> { "CURRENT_TIMESTAMP" }/, output @@ -294,7 +294,7 @@ def test_mysql_not_null_defaults_strict def with_mysql_not_null_table klass = Class.new(ActiveRecord::Base) klass.table_name = "test_mysql_not_null_defaults" - klass.connection.create_table klass.table_name do |t| + klass.lease_connection.create_table klass.table_name do |t| t.integer :non_null_integer, null: false t.string :non_null_string, null: false t.text :non_null_text, null: false @@ -303,7 +303,7 @@ def with_mysql_not_null_table yield klass ensure - klass.connection.drop_table(klass.table_name) rescue nil + klass.lease_connection.drop_table(klass.table_name) rescue nil end end end diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index da1c8b6422..f7c4a9e423 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -608,14 +608,14 @@ def test_previous_changes class Testings < ActiveRecord::Base; end def test_field_named_field - ActiveRecord::Base.connection.create_table :testings do |t| + ActiveRecord::Base.lease_connection.create_table :testings do |t| t.string :field end assert_nothing_raised do Testings.new.attributes end ensure - ActiveRecord::Base.connection.drop_table :testings rescue nil + ActiveRecord::Base.lease_connection.drop_table :testings rescue nil ActiveRecord::Base.clear_cache! end diff --git a/activerecord/test/cases/disconnected_test.rb b/activerecord/test/cases/disconnected_test.rb index 3ba962b601..0757b56263 100644 --- a/activerecord/test/cases/disconnected_test.rb +++ b/activerecord/test/cases/disconnected_test.rb @@ -7,7 +7,7 @@ class TestRecord < ActiveRecord::Base class TestDisconnectedAdapter < ActiveRecord::TestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end teardown do diff --git a/activerecord/test/cases/encryption/helper.rb b/activerecord/test/cases/encryption/helper.rb index 1839bff03e..1c86ecdeda 100644 --- a/activerecord/test/cases/encryption/helper.rb +++ b/activerecord/test/cases/encryption/helper.rb @@ -78,7 +78,7 @@ def create_unencrypted_book_ignoring_case(name:) end # Skip type casting to simulate an upcase value. Not supported in AR without using private apis - EncryptedBookThatIgnoresCase.connection.execute <<~SQL + EncryptedBookThatIgnoresCase.lease_connection.execute <<~SQL UPDATE encrypted_books SET name = '#{name}' WHERE id = #{book.id}; SQL diff --git a/activerecord/test/cases/excluding_test.rb b/activerecord/test/cases/excluding_test.rb index bb161aa386..8f8b48800c 100644 --- a/activerecord/test/cases/excluding_test.rb +++ b/activerecord/test/cases/excluding_test.rb @@ -25,7 +25,7 @@ def test_result_set_does_not_include_collection_of_excluded_records def test_result_set_does_not_include_collection_of_excluded_records_from_a_query query = Post.where(id: @post) - assert_queries_match(/SELECT #{Regexp.escape Post.connection.quote_table_name("posts.id")} FROM/) do + assert_queries_match(/SELECT #{Regexp.escape Post.lease_connection.quote_table_name("posts.id")} FROM/) do records = Post.excluding(query).to_a assert_not_includes records, @post @@ -72,7 +72,7 @@ def test_result_set_through_association_does_not_include_collection_of_excluded_ def test_result_set_through_association_does_not_include_collection_of_excluded_records_from_a_relation relation = @post.comments - assert_queries_match(/SELECT #{Regexp.escape Comment.connection.quote_table_name("comments.id")} FROM/) do + assert_queries_match(/SELECT #{Regexp.escape Comment.lease_connection.quote_table_name("comments.id")} FROM/) do records = Comment.excluding(relation).to_a assert_not_empty records diff --git a/activerecord/test/cases/explain_subscriber_test.rb b/activerecord/test/cases/explain_subscriber_test.rb index a13c2e76f3..d7ec37fd42 100644 --- a/activerecord/test/cases/explain_subscriber_test.rb +++ b/activerecord/test/cases/explain_subscriber_test.rb @@ -4,7 +4,7 @@ require "active_record/explain_subscriber" require "active_record/explain_registry" -if ActiveRecord::Base.connection.supports_explain? +if ActiveRecord::Base.lease_connection.supports_explain? class ExplainSubscriberTest < ActiveRecord::TestCase SUBSCRIBER = ActiveRecord::ExplainSubscriber.new diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb index e168a00982..86b2f2f0e7 100644 --- a/activerecord/test/cases/explain_test.rb +++ b/activerecord/test/cases/explain_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "models/car" -if ActiveRecord::Base.connection.supports_explain? +if ActiveRecord::Base.lease_connection.supports_explain? class ExplainTest < ActiveRecord::TestCase fixtures :cars @@ -11,8 +11,8 @@ def base ActiveRecord::Base end - def connection - base.connection + def lease_connection + base.lease_connection end def test_relation_explain @@ -159,7 +159,7 @@ def stub_explain_for_query_plans(query_plans = ["query plan foo", "query plan ba # Minitest's `stub` method is unable to correctly replicate method arguments # signature, so we need to do a manual stubbing in this case. - metaclass = class << connection; self; end + metaclass = lease_connection.singleton_class explain_method = metaclass.instance_method(:explain) metaclass.define_method(:explain) do |_arel, _binds = [], _options = {}| explain_called += 1 @@ -167,8 +167,10 @@ def stub_explain_for_query_plans(query_plans = ["query plan foo", "query plan ba end yield ensure - metaclass.undef_method(:explain) - metaclass.define_method(:explain, explain_method) + if metaclass + metaclass.undef_method(:explain) + metaclass.define_method(:explain, explain_method) + end end def bind_param(name, value) @@ -176,8 +178,8 @@ def bind_param(name, value) end def expected_explain_clause - if connection.respond_to?(:build_explain_clause) - connection.build_explain_clause + if lease_connection.respond_to?(:build_explain_clause) + lease_connection.build_explain_clause else "EXPLAIN for:" end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 24a2afd150..5ac0013b28 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -275,7 +275,7 @@ def test_exists_passing_active_record_object_is_not_permitted end def test_exists_does_not_select_columns_without_alias - c = Topic.connection + c = Topic.lease_connection assert_queries_match(/SELECT 1 AS one FROM #{Regexp.escape(c.quote_table_name("topics"))}/i) do Topic.exists? end @@ -948,7 +948,7 @@ def test_model_class_responds_to_third_to_last_bang end def test_nth_to_last_with_order_uses_limit - c = Topic.connection + c = Topic.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("topics.id"))} DESC LIMIT/i) do Topic.second_to_last end @@ -1066,7 +1066,7 @@ def test_implicit_order_column_is_configurable assert_equal topics(:fifth), Topic.first assert_equal topics(:third), Topic.last - c = Topic.connection + c = Topic.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("topics.title"))} DESC, #{Regexp.escape(c.quote_table_name("topics.id"))} DESC LIMIT/i) { Topic.last } @@ -1078,7 +1078,7 @@ def test_implicit_order_set_to_primary_key old_implicit_order_column = Topic.implicit_order_column Topic.implicit_order_column = "id" - c = Topic.connection + c = Topic.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("topics.id"))} DESC LIMIT/i) { Topic.last } @@ -1090,7 +1090,7 @@ def test_implicit_order_for_model_without_primary_key old_implicit_order_column = NonPrimaryKey.implicit_order_column NonPrimaryKey.implicit_order_column = "created_at" - c = NonPrimaryKey.connection + c = NonPrimaryKey.lease_connection assert_queries_match(/ORDER BY #{Regexp.escape(c.quote_table_name("non_primary_keys.created_at"))} DESC LIMIT/i) { NonPrimaryKey.last } @@ -1099,7 +1099,7 @@ def test_implicit_order_for_model_without_primary_key end def test_implicit_order_column_reorders_query_constraints - c = ClothingItem.connection + c = ClothingItem.lease_connection ClothingItem.implicit_order_column = "color" quoted_type = Regexp.escape(c.quote_table_name("clothing_items.clothing_type")) quoted_color = Regexp.escape(c.quote_table_name("clothing_items.color")) @@ -1112,7 +1112,7 @@ def test_implicit_order_column_reorders_query_constraints end def test_implicit_order_column_prepends_query_constraints - c = ClothingItem.connection + c = ClothingItem.lease_connection ClothingItem.implicit_order_column = "description" quoted_type = Regexp.escape(c.quote_table_name("clothing_items.clothing_type")) quoted_color = Regexp.escape(c.quote_table_name("clothing_items.color")) @@ -1597,16 +1597,16 @@ def test_find_by_records end def test_select_value - assert_equal "37signals", Company.connection.select_value("SELECT name FROM companies WHERE id = 1") - assert_nil Company.connection.select_value("SELECT name FROM companies WHERE id = -1") + assert_equal "37signals", Company.lease_connection.select_value("SELECT name FROM companies WHERE id = 1") + assert_nil Company.lease_connection.select_value("SELECT name FROM companies WHERE id = -1") # make sure we didn't break count... assert_equal 0, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = 'Halliburton'") assert_equal 1, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = '37signals'") end def test_select_values - assert_equal ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "15"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map!(&:to_s) - assert_equal ["37signals", "Summit", "Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy", "Ex Nihilo Part Deux", "Apex", "RVshare"], Company.connection.select_values("SELECT name FROM companies ORDER BY id") + assert_equal ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "15"], Company.lease_connection.select_values("SELECT id FROM companies ORDER BY id").map!(&:to_s) + assert_equal ["37signals", "Summit", "Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy", "Ex Nihilo Part Deux", "Apex", "RVshare"], Company.lease_connection.select_values("SELECT name FROM companies ORDER BY id") end def test_select_rows @@ -1614,9 +1614,9 @@ def test_select_rows [["1", "1", nil, "37signals"], ["2", "1", "2", "Summit"], ["3", "1", "1", "Microsoft"]], - Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map { |i| i.map { |j| j.to_s unless j.nil? } }) + Company.lease_connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map { |i| i.map { |j| j.to_s unless j.nil? } }) assert_equal [["1", "37signals"], ["2", "Summit"], ["3", "Microsoft"]], - Company.connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map { |i| i.map { |j| j.to_s unless j.nil? } } + Company.lease_connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map { |i| i.map { |j| j.to_s unless j.nil? } } end def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct @@ -1824,7 +1824,7 @@ def test_finder_with_offset_string end test "#last for a model with composite query constraints" do - c = ClothingItem.connection + c = ClothingItem.lease_connection quoted_type = Regexp.escape(c.quote_table_name("clothing_items.clothing_type")) quoted_color = Regexp.escape(c.quote_table_name("clothing_items.color")) @@ -1834,7 +1834,7 @@ def test_finder_with_offset_string end test "#first for a model with composite query constraints" do - c = ClothingItem.connection + c = ClothingItem.lease_connection quoted_type = Regexp.escape(c.quote_table_name("clothing_items.clothing_type")) quoted_color = Regexp.escape(c.quote_table_name("clothing_items.color")) diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 39b67541b4..d6979ce533 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -100,9 +100,9 @@ def test_bulk_insert_multiple_table_with_a_multi_statement_query create_fixtures("bulbs", "movies", "computers") expected_sql = <<~EOS.chop - INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("bulbs")} .* - INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("movies")} .* - INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("computers")} .* + INSERT INTO #{ActiveRecord::Base.lease_connection.quote_table_name("bulbs")} .* + INSERT INTO #{ActiveRecord::Base.lease_connection.quote_table_name("movies")} .* + INSERT INTO #{ActiveRecord::Base.lease_connection.quote_table_name("computers")} .* EOS assert_equal 1, subscriber.events.size assert_match(/#{expected_sql}/, subscriber.events.first) @@ -123,7 +123,7 @@ def test_bulk_insert_with_a_multi_statement_query_raises_an_exception_when_any_i assert_no_difference "Aircraft.count" do assert_raises(ActiveRecord::NotNullViolation) do - ActiveRecord::Base.connection.insert_fixtures_set(fixtures) + ActiveRecord::Base.lease_connection.insert_fixtures_set(fixtures) end end end @@ -137,7 +137,7 @@ def test_bulk_insert_with_a_multi_statement_query_in_a_nested_transaction assert_difference "TrafficLight.count" do ActiveRecord::Base.transaction do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection assert_equal 1, conn.open_transactions conn.insert_fixtures_set(fixtures) assert_equal 1, conn.open_transactions @@ -148,7 +148,7 @@ def test_bulk_insert_with_a_multi_statement_query_in_a_nested_transaction if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) def test_bulk_insert_with_multi_statements_enabled - adapter_name = ActiveRecord::Base.connection.adapter_name + adapter_name = ActiveRecord::Base.lease_connection.adapter_name run_without_connection do |orig_connection| case adapter_name when "Trilogy" @@ -168,7 +168,7 @@ def test_bulk_insert_with_multi_statements_enabled } assert_nothing_raised do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.execute("SELECT 1; SELECT 2;") case adapter_name when "Trilogy" @@ -180,7 +180,7 @@ def test_bulk_insert_with_multi_statements_enabled assert_difference "TrafficLight.count" do ActiveRecord::Base.transaction do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection assert_equal 1, conn.open_transactions conn.insert_fixtures_set(fixtures) assert_equal 1, conn.open_transactions @@ -188,7 +188,7 @@ def test_bulk_insert_with_multi_statements_enabled end assert_nothing_raised do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.execute("SELECT 1; SELECT 2;") case adapter_name when "Trilogy" @@ -201,7 +201,7 @@ def test_bulk_insert_with_multi_statements_enabled end def test_bulk_insert_with_multi_statements_disabled - adapter_name = ActiveRecord::Base.connection.adapter_name + adapter_name = ActiveRecord::Base.lease_connection.adapter_name run_without_connection do |orig_connection| case adapter_name when "Trilogy" @@ -221,7 +221,7 @@ def test_bulk_insert_with_multi_statements_disabled } assert_raises(ActiveRecord::StatementInvalid) do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.execute("SELECT 1; SELECT 2;") case adapter_name when "Trilogy" @@ -232,12 +232,12 @@ def test_bulk_insert_with_multi_statements_disabled end assert_difference "TrafficLight.count" do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.insert_fixtures_set(fixtures) end assert_raises(ActiveRecord::StatementInvalid) do - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.execute("SELECT 1; SELECT 2;") case adapter_name when "Trilogy" @@ -250,7 +250,7 @@ def test_bulk_insert_with_multi_statements_disabled end def test_insert_fixtures_set_raises_an_error_when_max_allowed_packet_is_smaller_than_fixtures_set_size - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection mysql_margin = 2 packet_size = 1024 bytes_needed_to_have_a_1024_bytes_fixture = 906 @@ -267,7 +267,7 @@ def test_insert_fixtures_set_raises_an_error_when_max_allowed_packet_is_smaller_ end def test_insert_fixture_set_when_max_allowed_packet_is_bigger_than_fixtures_set_size - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection packet_size = 1024 fixtures = { "traffic_lights" => [ @@ -285,7 +285,7 @@ def test_insert_fixture_set_when_max_allowed_packet_is_bigger_than_fixtures_set_ def test_insert_fixtures_set_split_the_total_sql_into_two_chunks_smaller_than_max_allowed_packet subscriber = InsertQuerySubscriber.new subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection packet_size = 1024 fixtures = { "traffic_lights" => [ @@ -310,7 +310,7 @@ def test_insert_fixtures_set_split_the_total_sql_into_two_chunks_smaller_than_ma def test_insert_fixtures_set_concat_total_sql_into_a_single_packet_smaller_than_max_allowed_packet subscriber = InsertQuerySubscriber.new subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection packet_size = 1024 fixtures = { "traffic_lights" => [ @@ -337,7 +337,7 @@ def test_auto_value_on_primary_key { "name" => "first", "wheels_count" => 2 }, { "name" => "second", "wheels_count" => 3 } ] - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection assert_nothing_raised do conn.insert_fixtures_set({ "aircraft" => fixtures }, ["aircraft"]) end @@ -406,10 +406,10 @@ def test_nil_raises def test_inserts create_fixtures("topics") - first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'") + first_row = ActiveRecord::Base.lease_connection.select_one("SELECT * FROM topics WHERE author_name = 'David'") assert_equal("The First Topic", first_row["title"]) - second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'") + second_row = ActiveRecord::Base.lease_connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'") assert_nil(second_row["author_email_address"]) end @@ -417,7 +417,7 @@ def test_inserts_with_pre_and_suffix # Reset cache to make finds on the new table work ActiveRecord::FixtureSet.reset_cache - ActiveRecord::Base.connection.create_table :prefix_other_topics_suffix do |t| + ActiveRecord::Base.lease_connection.create_table :prefix_other_topics_suffix do |t| t.column :title, :string t.column :author_name, :string t.column :author_email_address, :string @@ -451,11 +451,11 @@ def self.name # class-level configuration helper. assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create" - first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'") + first_row = ActiveRecord::Base.lease_connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'") assert_not_nil first_row, "The prefix_other_topics_suffix table appears to be empty despite create_fixtures: the row with author_name = 'David' was not found" assert_equal("The First Topic", first_row["title"]) - second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'") + second_row = ActiveRecord::Base.lease_connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'") assert_nil(second_row["author_email_address"]) assert_equal :prefix_other_topics_suffix, topics.table_name.to_sym @@ -468,7 +468,7 @@ def self.name ActiveRecord::Base.table_name_prefix = old_prefix ActiveRecord::Base.table_name_suffix = old_suffix - ActiveRecord::Base.connection.drop_table :prefix_other_topics_suffix rescue nil + ActiveRecord::Base.lease_connection.drop_table :prefix_other_topics_suffix rescue nil end def test_insert_with_datetime @@ -663,7 +663,7 @@ def load_has_and_belongs_to_many end end -if Account.connection.respond_to?(:reset_pk_sequence!) +if Account.lease_connection.respond_to?(:reset_pk_sequence!) class FixturesResetPkSequenceTest < ActiveRecord::TestCase fixtures :accounts fixtures :companies @@ -678,7 +678,7 @@ def test_resets_to_min_pk_with_specified_pk_and_sequence @instances.each do |instance| model = instance.class model.delete_all - model.connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name) + model.lease_connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name) instance.save! assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed." @@ -689,7 +689,7 @@ def test_resets_to_min_pk_with_default_pk_and_sequence @instances.each do |instance| model = instance.class model.delete_all - model.connection.reset_pk_sequence!(model.table_name) + model.lease_connection.reset_pk_sequence!(model.table_name) instance.save! assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed." @@ -1051,8 +1051,8 @@ def connect!; end end.new pool = connection.pool = Class.new do - attr_reader :connection def initialize(connection); @connection = connection; end + def lease_connection; @connection; end def release_connection; end def pin_connection!(_); end def unpin_connection!; @connection.rollback_transaction; true; end @@ -1078,8 +1078,8 @@ def connect!; end end.new connection.pool = Class.new do - attr_reader :connection def initialize(connection); @connection = connection; end + def lease_connection; @connection; end def release_connection; end def pin_connection!(_); end def unpin_connection!; @connection.rollback_transaction; true; end @@ -1102,8 +1102,8 @@ def connect!; end end.new connection.pool = Class.new do - attr_reader :connection def initialize(connection); @connection = connection; end + def lease_connection; @connection; end def release_connection; end def pin_connection!(_); end def unpin_connection!; @connection.rollback_transaction; true; end @@ -1179,11 +1179,11 @@ def blank_teardown; end fixtures rand.to_s # bypass fixtures cache def test_no_rollback_in_teardown_unless_transaction_active - assert_equal 0, ActiveRecord::Base.connection.open_transactions + assert_equal 0, ActiveRecord::Base.lease_connection.open_transactions assert_raise(RuntimeError) { ar_setup_fixtures } - assert_equal 0, ActiveRecord::Base.connection.open_transactions + assert_equal 0, ActiveRecord::Base.lease_connection.open_transactions assert_nothing_raised { ar_teardown_fixtures } - assert_equal 0, ActiveRecord::Base.connection.open_transactions + assert_equal 0, ActiveRecord::Base.lease_connection.open_transactions end private @@ -1638,15 +1638,15 @@ def test_uses_writing_connection_for_fixtures def test_writing_and_reading_connections_are_the_same handler = ActiveRecord::Base.connection_handler - rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing).connection - ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading).connection + rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing).lease_connection + ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading).lease_connection assert_equal rw_conn, ro_conn teardown_shared_connection_pool - rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing).connection - ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading).connection + rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing).lease_connection + ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading).lease_connection assert_not_equal rw_conn, ro_conn end @@ -1658,15 +1658,15 @@ def test_writing_and_reading_connections_are_the_same_for_non_default_shards } handler = ActiveRecord::Base.connection_handler - rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing, shard: :two).connection - ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading, shard: :two).connection + rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing, shard: :two).lease_connection + ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading, shard: :two).lease_connection assert_equal rw_conn, ro_conn teardown_shared_connection_pool - rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing, shard: :two).connection - ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading, shard: :two).connection + rw_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :writing, shard: :two).lease_connection + ro_conn = handler.retrieve_connection_pool("ActiveRecord::Base", role: :reading, shard: :two).lease_connection assert_not_equal rw_conn, ro_conn end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 50276f79c7..c12e8dcf84 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -22,11 +22,15 @@ # Show backtraces for deprecated behavior for quicker cleanup. ActiveRecord.deprecator.debug = true +# ActiveRecord::Base.connection is only soft deprecated but we remove it +# in the test suite to ensure we're not using it internally. +ActiveRecord::ConnectionHandling.remove_method(:connection) + # Disable available locale checks to avoid warnings running the test suite. I18n.enforce_available_locales = false # Quote "type" if it's a reserved word for the current connection. -QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name("type") +QUOTED_TYPE = ActiveRecord::Base.lease_connection.quote_column_name("type") ActiveRecord.raise_on_assign_to_attr_readonly = true ActiveRecord.belongs_to_required_validates_foreign_key = false diff --git a/activerecord/test/cases/hot_compatibility_test.rb b/activerecord/test/cases/hot_compatibility_test.rb index 333dbd9d82..b22508c862 100644 --- a/activerecord/test/cases/hot_compatibility_test.rb +++ b/activerecord/test/cases/hot_compatibility_test.rb @@ -9,7 +9,7 @@ class HotCompatibilityTest < ActiveRecord::TestCase setup do @klass = Class.new(ActiveRecord::Base) do - connection.create_table :hot_compatibilities, force: true do |t| + lease_connection.create_table :hot_compatibilities, force: true do |t| t.string :foo t.string :bar end @@ -19,7 +19,7 @@ def self.name; "HotCompatibility"; end end teardown do - ActiveRecord::Base.connection.drop_table :hot_compatibilities + ActiveRecord::Base.lease_connection.drop_table :hot_compatibilities end test "insert after remove_column" do @@ -30,7 +30,7 @@ def self.name; "HotCompatibility"; end assert_equal 3, @klass.columns.length # remove one of them - @klass.connection.remove_column :hot_compatibilities, :bar + @klass.lease_connection.remove_column :hot_compatibilities, :bar # we still have 3 columns in the cache assert_equal 3, @klass.columns.length @@ -45,7 +45,7 @@ def self.name; "HotCompatibility"; end test "update after remove_column" do record = @klass.create! foo: "foo" assert_equal 3, @klass.columns.length - @klass.connection.remove_column :hot_compatibilities, :bar + @klass.lease_connection.remove_column :hot_compatibilities, :bar assert_equal 3, @klass.columns.length record.reload @@ -56,7 +56,7 @@ def self.name; "HotCompatibility"; end assert_equal "bar", record.foo end - if current_adapter?(:PostgreSQLAdapter) && ActiveRecord::Base.connection.prepared_statements + if current_adapter?(:PostgreSQLAdapter) && ActiveRecord::Base.lease_connection.prepared_statements test "cleans up after prepared statement failure in a transaction" do with_two_connections do |original_connection, ddl_connection| record = @klass.create! bar: "bar" @@ -66,7 +66,7 @@ def self.name; "HotCompatibility"; end record.reload end - assert_predicate get_prepared_statement_cache(@klass.connection), :any?, + assert_predicate get_prepared_statement_cache(@klass.lease_connection), :any?, "expected prepared statement cache to have something in it" # add a new column @@ -78,7 +78,7 @@ def self.name; "HotCompatibility"; end end end - assert_empty get_prepared_statement_cache(@klass.connection), + assert_empty get_prepared_statement_cache(@klass.lease_connection), "expected prepared statement cache to be empty but it wasn't" end end @@ -92,7 +92,7 @@ def self.name; "HotCompatibility"; end record.reload end - assert_predicate get_prepared_statement_cache(@klass.connection), :any?, + assert_predicate get_prepared_statement_cache(@klass.lease_connection), :any?, "expected prepared statement cache to have something in it" # add a new column @@ -108,7 +108,7 @@ def self.name; "HotCompatibility"; end end end - assert_empty get_prepared_statement_cache(@klass.connection), + assert_empty get_prepared_statement_cache(@klass.lease_connection), "expected prepared statement cache to be empty but it wasn't" end end diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 9ee1d2608f..91f5ab2dfa 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -195,7 +195,7 @@ def test_base_class_activerecord_error end def test_a_bad_type_column - Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')" + Company.lease_connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')" assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) } end @@ -477,7 +477,7 @@ def test_alt_eager_loading end def test_eager_load_belongs_to_primary_key_quoting - c = Account.connection + c = Account.lease_connection bind_param = Arel::Nodes::BindParam.new(nil) assert_queries_match(/#{Regexp.escape(c.quote_table_name("companies.id"))} = (?:#{Regexp.escape(bind_param.to_sql)}|1)/i) do Account.all.merge!(includes: :firm).find(1) @@ -544,7 +544,7 @@ def test_sti_type_from_attributes_disabled_in_non_sti_class def test_inheritance_new_with_subclass_as_default original_type = Company.columns_hash["type"].default - ActiveRecord::Base.connection.change_column_default :companies, :type, "Firm" + ActiveRecord::Base.lease_connection.change_column_default :companies, :type, "Firm" Company.reset_column_information firm = Company.new # without arguments @@ -563,7 +563,7 @@ def test_inheritance_new_with_subclass_as_default assert_equal "Client", firm.type assert_instance_of Client, firm ensure - ActiveRecord::Base.connection.change_column_default :companies, :type, original_type + ActiveRecord::Base.lease_connection.change_column_default :companies, :type, original_type Company.reset_column_information end end @@ -635,7 +635,7 @@ def test_sti_with_custom_type Empire.create! name: "an Empire" assert_equal [["a Startup", "omg_inheritance_attribute_mapping_test/startup"], - ["an Empire", "omg_inheritance_attribute_mapping_test/empire"]], ActiveRecord::Base.connection.select_rows("SELECT name, type FROM companies").sort + ["an Empire", "omg_inheritance_attribute_mapping_test/empire"]], ActiveRecord::Base.lease_connection.select_rows("SELECT name, type FROM companies").sort assert_equal [["a Startup", "InheritanceAttributeMappingTest::Startup"], ["an Empire", "InheritanceAttributeMappingTest::Empire"]], Company.all.map { |a| [a.name, a.type] }.sort @@ -644,7 +644,7 @@ def test_sti_with_custom_type startup.save! assert_equal [["a Startup", "omg_inheritance_attribute_mapping_test/empire"], - ["an Empire", "omg_inheritance_attribute_mapping_test/empire"]], ActiveRecord::Base.connection.select_rows("SELECT name, type FROM companies").sort + ["an Empire", "omg_inheritance_attribute_mapping_test/empire"]], ActiveRecord::Base.lease_connection.select_rows("SELECT name, type FROM companies").sort assert_equal [["a Startup", "InheritanceAttributeMappingTest::Empire"], ["an Empire", "InheritanceAttributeMappingTest::Empire"]], Company.all.map { |a| [a.name, a.type] }.sort @@ -654,7 +654,7 @@ def test_polymorphic_associations_custom_type startup = Startup.create! name: "a Startup" sponsor = Sponsor.create! sponsorable: startup - assert_equal ["omg_inheritance_attribute_mapping_test/company"], ActiveRecord::Base.connection.select_values("SELECT sponsorable_type FROM sponsors") + assert_equal ["omg_inheritance_attribute_mapping_test/company"], ActiveRecord::Base.lease_connection.select_values("SELECT sponsorable_type FROM sponsors") sponsor = Sponsor.find(sponsor.id) assert_equal startup, sponsor.sponsorable diff --git a/activerecord/test/cases/insert_all_test.rb b/activerecord/test/cases/insert_all_test.rb index 705a6a101b..32bc2837a1 100644 --- a/activerecord/test/cases/insert_all_test.rb +++ b/activerecord/test/cases/insert_all_test.rb @@ -235,7 +235,7 @@ def test_insert_all_and_upsert_all_finds_index_with_inverted_unique_by_columns skip unless supports_insert_conflict_target? columns = [:author_id, :name] - assert ActiveRecord::Base.connection.index_exists?(:books, columns) + assert ActiveRecord::Base.lease_connection.index_exists?(:books, columns) assert_difference "Book.count", +2 do Book.insert_all [{ name: "Remote", author_id: 1 }], unique_by: columns.reverse @@ -769,7 +769,7 @@ def test_upsert_all_with_unique_by_fails_cleanly_for_adapters_not_supporting_ins error = assert_raises ArgumentError do Book.upsert_all [{ name: "Rework", author_id: 1 }], unique_by: :isbn end - assert_match "#{ActiveRecord::Base.connection.class} does not support :unique_by", error.message + assert_match "#{ActiveRecord::Base.lease_connection.class} does not support :unique_by", error.message end private diff --git a/activerecord/test/cases/instrumentation_test.rb b/activerecord/test/cases/instrumentation_test.rb index ed383edec8..ae354b07ec 100644 --- a/activerecord/test/cases/instrumentation_test.rb +++ b/activerecord/test/cases/instrumentation_test.rb @@ -2,6 +2,7 @@ require "cases/helper" require "models/book" +require "models/clothing_item" module ActiveRecord class InstrumentationTest < ActiveRecord::TestCase @@ -142,13 +143,13 @@ def test_payload_row_count_on_raw_sql assert_equal 10, payload[:row_count] end end - ActiveRecord::Base.connection.execute("SELECT * FROM books WHERE name='row count book 3';") + ActiveRecord::Base.lease_connection.execute("SELECT * FROM books WHERE name='row count book 3';") ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end def test_payload_connection_with_query_cache_disabled - connection = Book.connection + connection = ClothingItem.lease_connection subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload| assert_equal connection, payload[:connection] end @@ -158,7 +159,7 @@ def test_payload_connection_with_query_cache_disabled end def test_payload_connection_with_query_cache_enabled - connection = Book.connection + connection = ClothingItem.lease_connection subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload| assert_equal connection, payload[:connection] end diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb index 11507518d0..2b64301fce 100644 --- a/activerecord/test/cases/invertible_migration_test.rb +++ b/activerecord/test/cases/invertible_migration_test.rb @@ -228,8 +228,8 @@ def change teardown do %w[horses new_horses].each do |table| - if ActiveRecord::Base.connection.table_exists?(table) - ActiveRecord::Base.connection.drop_table(table) + if ActiveRecord::Base.lease_connection.table_exists?(table) + ActiveRecord::Base.lease_connection.drop_table(table) end end ActiveRecord::Migration.verbose = @verbose_was @@ -356,7 +356,7 @@ def test_migrate_revert_change_column_default assert_equal "Sekitoba", Horse.new.name end - if ActiveRecord::Base.connection.supports_comments? + if ActiveRecord::Base.lease_connection.supports_comments? def test_migrate_revert_change_column_comment migration1 = ChangeColumnComment1.new migration1.migrate(:up) @@ -374,7 +374,7 @@ def test_migrate_revert_change_column_comment end def test_migrate_revert_change_table_comment - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection migration1 = ChangeTableComment1.new migration1.migrate(:up) assert_equal "Sekitoba", connection.table_comment("horses") @@ -390,32 +390,33 @@ def test_migrate_revert_change_table_comment if current_adapter?(:PostgreSQLAdapter) def test_migrate_enable_and_disable_extension + connection = Horse.lease_connection migration1 = InvertibleMigration.new migration2 = DisableExtension1.new migration3 = DisableExtension2.new - assert_equal true, Horse.connection.extension_available?("hstore") + assert_equal true, connection.extension_available?("hstore") migration1.migrate(:up) migration2.migrate(:up) - assert_equal true, Horse.connection.extension_enabled?("hstore") + assert_equal true, connection.extension_enabled?("hstore") migration3.migrate(:up) - assert_equal false, Horse.connection.extension_enabled?("hstore") + assert_equal false, connection.extension_enabled?("hstore") migration3.migrate(:down) - assert_equal true, Horse.connection.extension_enabled?("hstore") + assert_equal true, connection.extension_enabled?("hstore") migration2.migrate(:down) - assert_equal false, Horse.connection.extension_enabled?("hstore") + assert_equal false, connection.extension_enabled?("hstore") ensure - enable_extension!("hstore", ActiveRecord::Base.connection) + enable_extension!("hstore", ActiveRecord::Base.lease_connection) end end def test_revert_order block = Proc.new { |t| t.string :name } - recorder = ActiveRecord::Migration::CommandRecorder.new(ActiveRecord::Base.connection) + recorder = ActiveRecord::Migration::CommandRecorder.new(ActiveRecord::Base.lease_connection) recorder.instance_eval do create_table("apples", &block) revert do @@ -439,24 +440,24 @@ def test_revert_order def test_legacy_up LegacyMigration.migrate :up - assert ActiveRecord::Base.connection.table_exists?("horses"), "horses should exist" + assert ActiveRecord::Base.lease_connection.table_exists?("horses"), "horses should exist" end def test_legacy_down LegacyMigration.migrate :up LegacyMigration.migrate :down - assert_not ActiveRecord::Base.connection.table_exists?("horses"), "horses should not exist" + assert_not ActiveRecord::Base.lease_connection.table_exists?("horses"), "horses should not exist" end def test_up LegacyMigration.up - assert ActiveRecord::Base.connection.table_exists?("horses"), "horses should exist" + assert ActiveRecord::Base.lease_connection.table_exists?("horses"), "horses should exist" end def test_down LegacyMigration.up LegacyMigration.down - assert_not ActiveRecord::Base.connection.table_exists?("horses"), "horses should not exist" + assert_not ActiveRecord::Base.lease_connection.table_exists?("horses"), "horses should not exist" end def test_migrate_down_with_table_name_prefix @@ -465,7 +466,7 @@ def test_migrate_down_with_table_name_prefix migration = InvertibleMigration.new migration.migrate(:up) assert_nothing_raised { migration.migrate(:down) } - assert_not ActiveRecord::Base.connection.table_exists?("p_horses_s"), "p_horses_s should not exist" + assert_not ActiveRecord::Base.lease_connection.table_exists?("p_horses_s"), "p_horses_s should not exist" ensure ActiveRecord::Base.table_name_prefix = ActiveRecord::Base.table_name_suffix = "" end @@ -484,7 +485,7 @@ def test_migrate_revert_add_index_with_name RevertNamedIndexMigration2.new.migrate(:up) RevertNamedIndexMigration2.new.migrate(:down) - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection assert connection.index_exists?(:horses, :content), "index on content should exist" assert_not connection.index_exists?(:horses, :content, name: "horses_index_named"), @@ -496,7 +497,7 @@ def test_migrate_revert_add_index_without_name_on_expression InvertibleMigration.new.migrate(:up) RevertNonNamedExpressionIndexMigration.new.migrate(:up) - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection assert connection.index_exists?(:horses, [:remind_at, :place_id]), "index on remind_at and place_id should exist" @@ -519,7 +520,7 @@ def test_up_only assert_equal 0, horse2.oldie # created after migration UpOnlyMigration.new.migrate(:down) # should be no error - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection assert_not connection.column_exists?(:horses, :oldie) Horse.reset_column_information end diff --git a/activerecord/test/cases/json_shared_test_cases.rb b/activerecord/test/cases/json_shared_test_cases.rb index 17f08a6b31..ec3ce55e90 100644 --- a/activerecord/test/cases/json_shared_test_cases.rb +++ b/activerecord/test/cases/json_shared_test_cases.rb @@ -13,7 +13,7 @@ class JsonDataType < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown @@ -276,7 +276,7 @@ def klass end def assert_type_match(type, sql_type) - native_type = ActiveRecord::Base.connection.native_database_types[type][:name] + native_type = ActiveRecord::Base.lease_connection.native_database_types[type][:name] assert_match %r(\A#{native_type}\b), sql_type end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 39996f0a8b..f597ed525f 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -293,7 +293,7 @@ def test_lock_without_default_sets_version_to_zero end def test_touch_existing_lock_without_default_should_work_with_null_in_the_database - ActiveRecord::Base.connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") + ActiveRecord::Base.lease_connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") t1 = LockWithoutDefault.last assert_equal 0, t1.lock_version @@ -322,7 +322,7 @@ def test_touch_stale_object_with_lock_without_default end def test_lock_without_default_should_work_with_null_in_the_database - ActiveRecord::Base.connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") + ActiveRecord::Base.lease_connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") t1 = LockWithoutDefault.last t2 = LockWithoutDefault.find(t1.id) @@ -344,7 +344,7 @@ def test_lock_without_default_should_work_with_null_in_the_database end def test_update_with_lock_version_without_default_should_work_on_dirty_value_before_type_cast - ActiveRecord::Base.connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") + ActiveRecord::Base.lease_connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") t1 = LockWithoutDefault.last assert_equal 0, t1.lock_version @@ -361,7 +361,7 @@ def test_update_with_lock_version_without_default_should_work_on_dirty_value_bef end def test_destroy_with_lock_version_without_default_should_work_on_dirty_value_before_type_cast - ActiveRecord::Base.connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") + ActiveRecord::Base.lease_connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") t1 = LockWithoutDefault.last assert_equal 0, t1.lock_version @@ -411,7 +411,7 @@ def test_lock_with_custom_column_without_default_sets_version_to_zero end def test_lock_with_custom_column_without_default_should_work_with_null_in_the_database - ActiveRecord::Base.connection.execute("INSERT INTO lock_without_defaults_cust(title) VALUES('title1')") + ActiveRecord::Base.lease_connection.execute("INSERT INTO lock_without_defaults_cust(title) VALUES('title1')") t1 = LockWithCustomColumnWithoutDefault.last t2 = LockWithCustomColumnWithoutDefault.find(t1.id) @@ -550,7 +550,7 @@ def test_removing_has_and_belongs_to_many_associations_upon_destroy assert_not_empty p.treasures p.destroy assert_empty p.treasures - assert_empty RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1") + assert_empty RichPerson.lease_connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1") end def test_yaml_dumping_with_lock_column @@ -613,7 +613,7 @@ def test_destroy_dependents end def test_destroy_existing_object_with_locking_column_value_null_in_the_database - ActiveRecord::Base.connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") + ActiveRecord::Base.lease_connection.execute("INSERT INTO lock_without_defaults(title) VALUES('title1')") t1 = LockWithoutDefault.last assert_equal 0, t1.lock_version @@ -639,12 +639,12 @@ def test_destroy_stale_object private def add_counter_column_to(model, col = "test_count") - model.connection.add_column model.table_name, col, :integer, null: false, default: 0 + model.lease_connection.add_column model.table_name, col, :integer, null: false, default: 0 model.reset_column_information end def remove_counter_column_from(model, col = :test_count) - model.connection.remove_column model.table_name, col + model.lease_connection.remove_column model.table_name, col model.reset_column_information end @@ -747,10 +747,10 @@ def test_with_lock_rolls_back_transaction def test_with_lock_configures_transaction person = Person.find 1 Person.transaction do - outer_transaction = Person.connection.transaction_manager.current_transaction + outer_transaction = Person.lease_connection.transaction_manager.current_transaction assert_equal true, outer_transaction.joinable? person.with_lock(requires_new: true, joinable: false) do - current_transaction = Person.connection.transaction_manager.current_transaction + current_transaction = Person.lease_connection.transaction_manager.current_transaction assert_not_equal outer_transaction, current_transaction assert_equal false, current_transaction.joinable? end @@ -770,7 +770,7 @@ def test_lock_sending_custom_lock_statement def test_with_lock_sets_isolation person = Person.find 1 person.with_lock(isolation: :read_uncommitted) do - current_transaction = Person.connection.transaction_manager.current_transaction + current_transaction = Person.lease_connection.transaction_manager.current_transaction assert_equal :read_uncommitted, current_transaction.isolation_level end end diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index 70523cd725..122a8f472b 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -44,7 +44,7 @@ def debug(progname = nil, &block) def setup @old_logger = ActiveRecord::Base.logger Developer.primary_key - ActiveRecord::Base.connection.materialize_transactions + ActiveRecord::Base.lease_connection.materialize_transactions super ActiveRecord::LogSubscriber.attach_to(:active_record) end @@ -247,7 +247,7 @@ def test_cached_queries_doesnt_log_when_level_is_not_debug assert_equal 0, @logger.logged(:debug).size end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements def test_where_in_binds_logging_include_attribute_names Developer.where(id: [1, 2, 3, 4, 5]).load wait diff --git a/activerecord/test/cases/marshal_serialization_test.rb b/activerecord/test/cases/marshal_serialization_test.rb index 897907401a..c72f0efb3d 100644 --- a/activerecord/test/cases/marshal_serialization_test.rb +++ b/activerecord/test/cases/marshal_serialization_test.rb @@ -100,7 +100,7 @@ def marshal_fixture(file_name) def marshal_fixture_path(file_name) File.expand_path( - "support/marshal_compatibility_fixtures/#{ActiveRecord::Base.connection.adapter_name}/#{file_name}.dump", + "support/marshal_compatibility_fixtures/#{ActiveRecord::Base.lease_connection.adapter_name}/#{file_name}.dump", TEST_ROOT ) end diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index 87e7ace873..bc9e529f3b 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -9,7 +9,7 @@ class ChangeSchemaTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @table_name = :testings end @@ -368,45 +368,45 @@ def test_keeping_default_and_notnull_constraints_on_change person_klass = Class.new(ActiveRecord::Base) person_klass.table_name = "testings" - person_klass.connection.add_column "testings", "wealth", :integer, null: false, default: 99 + person_klass.lease_connection.add_column "testings", "wealth", :integer, null: false, default: 99 person_klass.reset_column_information assert_equal 99, person_klass.column_defaults["wealth"] assert_equal false, person_klass.columns_hash["wealth"].null # Oracle needs primary key value from sequence if current_adapter?(:OracleAdapter) - assert_nothing_raised { person_klass.connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')") } + assert_nothing_raised { person_klass.lease_connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')") } else - assert_nothing_raised { person_klass.connection.execute("insert into testings (title) values ('tester')") } + assert_nothing_raised { person_klass.lease_connection.execute("insert into testings (title) values ('tester')") } end # change column default to see that column doesn't lose its not null definition - person_klass.connection.change_column_default "testings", "wealth", 100 + person_klass.lease_connection.change_column_default "testings", "wealth", 100 person_klass.reset_column_information assert_equal 100, person_klass.column_defaults["wealth"] assert_equal false, person_klass.columns_hash["wealth"].null # rename column to see that column doesn't lose its not null and/or default definition - person_klass.connection.rename_column "testings", "wealth", "money" + person_klass.lease_connection.rename_column "testings", "wealth", "money" person_klass.reset_column_information assert_nil person_klass.columns_hash["wealth"] assert_equal 100, person_klass.column_defaults["money"] assert_equal false, person_klass.columns_hash["money"].null # change column - person_klass.connection.change_column "testings", "money", :integer, null: false, default: 1000 + person_klass.lease_connection.change_column "testings", "money", :integer, null: false, default: 1000 person_klass.reset_column_information assert_equal 1000, person_klass.column_defaults["money"] assert_equal false, person_klass.columns_hash["money"].null # change column, make it nullable and clear default - person_klass.connection.change_column "testings", "money", :integer, null: true, default: nil + person_klass.lease_connection.change_column "testings", "money", :integer, null: true, default: nil person_klass.reset_column_information assert_nil person_klass.columns_hash["money"].default assert_equal true, person_klass.columns_hash["money"].null # change_column_null, make it not nullable and set null values to a default value - person_klass.connection.execute("UPDATE testings SET money = NULL") - person_klass.connection.change_column_null "testings", "money", false, 2000 + person_klass.lease_connection.execute("UPDATE testings SET money = NULL") + person_klass.lease_connection.change_column_null "testings", "money", false, 2000 person_klass.reset_column_information assert_nil person_klass.columns_hash["money"].default assert_equal false, person_klass.columns_hash["money"].null @@ -500,12 +500,12 @@ def testing_table_with_only_foo_attribute end end - if ActiveRecord::Base.connection.supports_foreign_keys? + if ActiveRecord::Base.lease_connection.supports_foreign_keys? class ChangeSchemaWithDependentObjectsTest < ActiveRecord::TestCase self.use_transactional_tests = false setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :trains @connection.create_table(:wagons) { |t| t.references :train } @connection.add_foreign_key :wagons, :trains diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb index 89fac58780..6d8512f6d5 100644 --- a/activerecord/test/cases/migration/change_table_test.rb +++ b/activerecord/test/cases/migration/change_table_test.rb @@ -14,7 +14,7 @@ def setup end def with_change_table - yield ActiveRecord::Base.connection.update_table_definition(:delete_me, @connection) + yield ActiveRecord::Base.lease_connection.update_table_definition(:delete_me, @connection) end if Minitest::Mock.instance_method(:expect).parameters.map(&:first).include?(:keyrest) diff --git a/activerecord/test/cases/migration/check_constraint_test.rb b/activerecord/test/cases/migration/check_constraint_test.rb index d4169f43ec..5294902d76 100644 --- a/activerecord/test/cases/migration/check_constraint_test.rb +++ b/activerecord/test/cases/migration/check_constraint_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_check_constraints? +if ActiveRecord::Base.lease_connection.supports_check_constraints? module ActiveRecord class Migration class CheckConstraintTest < ActiveRecord::TestCase @@ -13,7 +13,7 @@ class Trade < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "trades", force: true do |t| t.integer :price t.integer :quantity @@ -165,7 +165,7 @@ def test_added_check_constraint_ensures_valid_values end end - if ActiveRecord::Base.connection.supports_validate_constraints? + if ActiveRecord::Base.lease_connection.supports_validate_constraints? def test_not_valid_check_constraint Trade.create(quantity: -1) @@ -315,7 +315,7 @@ module ActiveRecord class Migration class NoForeignKeySupportTest < ActiveRecord::TestCase setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_add_check_constraint_should_be_noop diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb index 5bec98860a..db64710d3a 100644 --- a/activerecord/test/cases/migration/column_positioning_test.rb +++ b/activerecord/test/cases/migration/column_positioning_test.rb @@ -11,7 +11,7 @@ class ColumnPositioningTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection connection.create_table :testings, id: false do |t| t.column :first, :integer diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb index 57661a68d9..e8a35fa5c6 100644 --- a/activerecord/test/cases/migration/command_recorder_test.rb +++ b/activerecord/test/cases/migration/command_recorder_test.rb @@ -6,7 +6,7 @@ module ActiveRecord class Migration class CommandRecorderTest < ActiveRecord::TestCase def setup - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection @recorder = CommandRecorder.new(connection) end @@ -113,7 +113,7 @@ def test_invert_change_table end end - if ActiveRecord::Base.connection.supports_bulk_alter? + if ActiveRecord::Base.lease_connection.supports_bulk_alter? def test_bulk_invert_change_table block = Proc.new do |t| t.string :name @@ -225,7 +225,7 @@ def test_invert_change_column_default_with_from_and_to_with_boolean assert_equal [:change_column_default, [:table, :column, from: false, to: true]], change end - if ActiveRecord::Base.connection.supports_comments? + if ActiveRecord::Base.lease_connection.supports_comments? def test_invert_change_column_comment assert_raises(ActiveRecord::IrreversibleMigration) do @recorder.inverse_of :change_column_comment, [:table, :column, "comment"] diff --git a/activerecord/test/cases/migration/compatibility_test.rb b/activerecord/test/cases/migration/compatibility_test.rb index e702f3a5f3..76db6af884 100644 --- a/activerecord/test/cases/migration/compatibility_test.rb +++ b/activerecord/test/cases/migration/compatibility_test.rb @@ -15,7 +15,7 @@ class TestModel < ActiveRecord::Base def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @pool = ActiveRecord::Base.connection_pool @schema_migration = @pool.schema_migration @internal_metadata = @pool.internal_metadata @@ -114,7 +114,7 @@ def migrate(x) assert connection.column_exists?(:testings, :updated_at, null: true) end - if ActiveRecord::Base.connection.supports_bulk_alter? + if ActiveRecord::Base.lease_connection.supports_bulk_alter? def test_timestamps_have_null_constraints_if_not_present_in_migration_of_change_table_with_bulk migration = Class.new(ActiveRecord::Migration[4.2]) { def migrate(x) @@ -176,7 +176,7 @@ def migrate(x) assert connection.column_exists?(:testings, :updated_at, null: false, **precision_implicit_default) end - if ActiveRecord::Base.connection.supports_bulk_alter? + if ActiveRecord::Base.lease_connection.supports_bulk_alter? def test_timestamps_doesnt_set_precision_on_change_table_with_bulk migration = Class.new(ActiveRecord::Migration[5.2]) { def migrate(x) @@ -227,7 +227,7 @@ def change end end - if ActiveRecord::Base.connection.supports_comments? + if ActiveRecord::Base.lease_connection.supports_comments? def test_change_column_comment_can_be_reverted migration = Class.new(ActiveRecord::Migration[5.2]) { def migrate(x) @@ -620,7 +620,7 @@ def migrate(x) ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate - foreign_keys = Testing.connection.foreign_keys("sub_testings") + foreign_keys = Testing.lease_connection.foreign_keys("sub_testings") assert_equal 1, foreign_keys.size assert_equal :immediate, foreign_keys.first.deferrable ensure @@ -828,7 +828,7 @@ class BaseCompatibilityTest < ActiveRecord::TestCase attr_reader :connection def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @pool = ActiveRecord::Base.connection_pool @schema_migration = @pool.schema_migration @internal_metadata = @pool.internal_metadata @@ -917,7 +917,7 @@ module LegacyPolymorphicReferenceIndexTestCases attr_reader :connection def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @pool = ActiveRecord::Base.connection_pool @schema_migration = @pool.schema_migration @internal_metadata = @pool.internal_metadata diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb index 489db47867..bac268f671 100644 --- a/activerecord/test/cases/migration/create_join_table_test.rb +++ b/activerecord/test/cases/migration/create_join_table_test.rb @@ -9,7 +9,7 @@ class CreateJoinTableTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end teardown do diff --git a/activerecord/test/cases/migration/exclusion_constraint_test.rb b/activerecord/test/cases/migration/exclusion_constraint_test.rb index ab0a202317..ac40aafdf8 100644 --- a/activerecord/test/cases/migration/exclusion_constraint_test.rb +++ b/activerecord/test/cases/migration/exclusion_constraint_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_exclusion_constraints? +if ActiveRecord::Base.lease_connection.supports_exclusion_constraints? module ActiveRecord class Migration class ExclusionConstraintTest < ActiveRecord::TestCase @@ -13,7 +13,7 @@ class Invoice < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "invoices", force: true do |t| t.date :start_date t.date :end_date @@ -162,7 +162,7 @@ def test_added_deferrable_initially_immediate_exclusion_constraint assert_nothing_raised do Invoice.transaction(requires_new: true) do - Invoice.connection.set_constraints(:deferred, "invoices_date_overlap") + Invoice.lease_connection.set_constraints(:deferred, "invoices_date_overlap") Invoice.create!(start_date: "2020-12-31", end_date: "2021-01-01") invoice.update!(end_date: "2020-12-31") diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index f7002ef20a..05c479cf93 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -3,12 +3,12 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_foreign_keys? +if ActiveRecord::Base.lease_connection.supports_foreign_keys? module ActiveRecord class Migration class ForeignKeyInCreateTest < ActiveRecord::TestCase def test_foreign_keys - foreign_keys = ActiveRecord::Base.connection.foreign_keys("fk_test_has_fk") + foreign_keys = ActiveRecord::Base.lease_connection.foreign_keys("fk_test_has_fk") assert_equal 1, foreign_keys.size fk = foreign_keys.first @@ -45,7 +45,7 @@ def change end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @migration = CreateRocketsMigration.new silence_stream($stdout) { @migration.migrate(:up) } Rocket.reset_table_name @@ -177,7 +177,7 @@ class Astronaut < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "rockets", force: true do |t| t.string :name end @@ -433,7 +433,7 @@ def test_remove_foreign_key_by_the_select_one_on_the_same_table @connection.foreign_keys("astronauts").map { |fk| [fk.from_table, fk.to_table, fk.column] } end - if ActiveRecord::Base.connection.supports_validate_constraints? + if ActiveRecord::Base.lease_connection.supports_validate_constraints? def test_add_invalid_foreign_key @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false @@ -517,7 +517,7 @@ def test_add_invalid_foreign_key end end - if ActiveRecord::Base.connection.supports_deferrable_constraints? + if ActiveRecord::Base.lease_connection.supports_deferrable_constraints? def test_deferrable_foreign_key @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", deferrable: :immediate @@ -759,11 +759,11 @@ def test_add_foreign_key_with_if_not_exists_not_set end if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - if ActiveRecord::Base.connection.mariadb? + if ActiveRecord::Base.lease_connection.mariadb? assert_match(/Duplicate key on write or update/, error.message) - elsif ActiveRecord::Base.connection.database_version < "5.6" + elsif ActiveRecord::Base.lease_connection.database_version < "5.6" assert_match(/Can't create table/, error.message) - elsif ActiveRecord::Base.connection.database_version < "8.0" + elsif ActiveRecord::Base.lease_connection.database_version < "8.0" assert_match(/Can't write; duplicate key in table/, error.message) else assert_match(/Duplicate foreign key constraint name/, error.message) @@ -800,7 +800,7 @@ class CompositeForeignKeyTest < ActiveRecord::TestCase include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :rockets, primary_key: [:tenant_id, :id], force: true do |t| t.integer :tenant_id t.integer :id diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb index da8bdc472a..2ea8db5b04 100644 --- a/activerecord/test/cases/migration/helper.rb +++ b/activerecord/test/cases/migration/helper.rb @@ -18,7 +18,7 @@ class TestModel < ActiveRecord::Base def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection connection.create_table :test_models do |t| t.timestamps null: true end diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb index 0b56300612..8fb23d38c6 100644 --- a/activerecord/test/cases/migration/index_test.rb +++ b/activerecord/test/cases/migration/index_test.rb @@ -9,7 +9,7 @@ class IndexTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @table_name = :testings connection.create_table table_name do |t| diff --git a/activerecord/test/cases/migration/references_foreign_key_test.rb b/activerecord/test/cases/migration/references_foreign_key_test.rb index 8d7c846cbc..b61738353a 100644 --- a/activerecord/test/cases/migration/references_foreign_key_test.rb +++ b/activerecord/test/cases/migration/references_foreign_key_test.rb @@ -2,12 +2,12 @@ require "cases/helper" -if ActiveRecord::Base.connection.supports_foreign_keys? +if ActiveRecord::Base.lease_connection.supports_foreign_keys? module ActiveRecord class Migration class ReferencesForeignKeyInCreateTest < ActiveRecord::TestCase setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table(:testing_parents, force: true) end @@ -63,7 +63,7 @@ class ReferencesForeignKeyInCreateTest < ActiveRecord::TestCase fks.map { |fk| [fk.from_table, fk.to_table, fk.column] }) end - if ActiveRecord::Base.connection.supports_deferrable_constraints? + if ActiveRecord::Base.lease_connection.supports_deferrable_constraints? test "deferrable: false option can be passed" do @connection.create_table :testings do |t| t.references :testing_parent, foreign_key: { deferrable: false } @@ -112,7 +112,7 @@ module ActiveRecord class Migration class ReferencesForeignKeyTest < ActiveRecord::TestCase setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table(:testing_parents, force: true) end diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb index c7539ee24a..0c53a1a274 100644 --- a/activerecord/test/cases/migration/references_index_test.rb +++ b/activerecord/test/cases/migration/references_index_test.rb @@ -9,7 +9,7 @@ class ReferencesIndexTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @table_name = :testings end diff --git a/activerecord/test/cases/migration/schema_definitions_test.rb b/activerecord/test/cases/migration/schema_definitions_test.rb index 57ee9fabdb..1d692face5 100644 --- a/activerecord/test/cases/migration/schema_definitions_test.rb +++ b/activerecord/test/cases/migration/schema_definitions_test.rb @@ -8,7 +8,7 @@ class SchemaDefinitionsTest < ActiveRecord::TestCase attr_reader :connection def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_build_create_table_definition_with_block diff --git a/activerecord/test/cases/migration/unique_constraint_test.rb b/activerecord/test/cases/migration/unique_constraint_test.rb index 624a856273..8ba5e148fd 100644 --- a/activerecord/test/cases/migration/unique_constraint_test.rb +++ b/activerecord/test/cases/migration/unique_constraint_test.rb @@ -3,7 +3,7 @@ require "cases/helper" require "support/schema_dumping_helper" -if ActiveRecord::Base.connection.supports_unique_constraints? +if ActiveRecord::Base.lease_connection.supports_unique_constraints? module ActiveRecord class Migration class UniqueConstraintTest < ActiveRecord::TestCase @@ -13,7 +13,7 @@ class Section < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table "sections", force: true do |t| t.integer "position", null: false end @@ -137,7 +137,7 @@ def test_added_deferrable_initially_immediate_unique_constraint assert_nothing_raised do Section.transaction(requires_new: true) do - Section.connection.exec_query("SET CONSTRAINTS unique_section_position DEFERRED") + Section.lease_connection.exec_query("SET CONSTRAINTS unique_section_position DEFERRED") Section.create!(position: 1) section.update!(position: 2) diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index d6b5f85263..b468f7acd3 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -40,7 +40,7 @@ class MigrationTest < ActiveRecord::TestCase def setup super %w(reminders people_reminders prefix_reminders_suffix p_things_s).each do |table| - Reminder.connection.drop_table(table) rescue nil + Reminder.lease_connection.drop_table(table) rescue nil end Reminder.reset_column_information @verbose_was, ActiveRecord::Migration.verbose = ActiveRecord::Migration.verbose, false @@ -58,23 +58,23 @@ def setup @schema_migration.delete_all_versions %w(things awesome_things prefix_things_suffix p_awesome_things_s).each do |table| - Thing.connection.drop_table(table) rescue nil + Thing.lease_connection.drop_table(table) rescue nil end Thing.reset_column_information %w(reminders people_reminders prefix_reminders_suffix).each do |table| - Reminder.connection.drop_table(table) rescue nil + Reminder.lease_connection.drop_table(table) rescue nil end Reminder.reset_table_name Reminder.reset_column_information %w(last_name key bio age height wealth birthday favorite_day moment_of_truth male administrator funny).each do |column| - Person.connection.remove_column("people", column) rescue nil + Person.lease_connection.remove_column("people", column) rescue nil end - Person.connection.remove_column("people", "first_name") rescue nil - Person.connection.remove_column("people", "middle_name") rescue nil - Person.connection.add_column("people", "first_name", :string) + Person.lease_connection.remove_column("people", "first_name") rescue nil + Person.lease_connection.remove_column("people", "middle_name") rescue nil + Person.lease_connection.add_column("people", "first_name", :string) Person.reset_column_information ActiveRecord::Migration.verbose = @verbose_was @@ -153,7 +153,7 @@ def test_migration_version end def test_create_table_raises_if_already_exists - connection = Person.connection + connection = Person.lease_connection connection.create_table :testings, force: true do |t| t.string :foo end @@ -168,7 +168,7 @@ def test_create_table_raises_if_already_exists end def test_create_table_with_if_not_exists_true - connection = Person.connection + connection = Person.lease_connection connection.create_table :testings, force: true do |t| t.string :foo end @@ -183,7 +183,7 @@ def test_create_table_with_if_not_exists_true end def test_create_table_raises_for_long_table_names - connection = Person.connection + connection = Person.lease_connection name_limit = connection.table_name_length long_name = "a" * (name_limit + 1) short_name = "a" * name_limit @@ -200,7 +200,7 @@ def test_create_table_raises_for_long_table_names end def test_create_table_with_indexes_and_if_not_exists_true - connection = Person.connection + connection = Person.lease_connection connection.create_table :testings, force: true do |t| t.references :people t.string :foo @@ -219,15 +219,15 @@ def test_create_table_with_indexes_and_if_not_exists_true def test_create_table_with_force_true_does_not_drop_nonexisting_table # using a copy as we need the drop_table method to # continue to work for the ensure block of the test - temp_conn = Person.connection.dup + temp_conn = Person.lease_connection.dup - assert_not_equal temp_conn, Person.connection + assert_not_equal temp_conn, Person.lease_connection temp_conn.create_table :testings2, force: true do |t| t.column :foo, :string end ensure - Person.connection.drop_table :testings2, if_exists: true + Person.lease_connection.drop_table :testings2, if_exists: true end def test_remove_column_with_if_not_exists_not_set @@ -270,7 +270,7 @@ def migrate(x) end if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - if ActiveRecord::Base.connection.mariadb? + if ActiveRecord::Base.lease_connection.mariadb? assert_match(/Can't DROP COLUMN `last_name`; check that it exists/, error.message) else assert_match(/check that column\/key exists/, error.message) @@ -344,7 +344,7 @@ def migrate(x) ensure Person.reset_column_information if Person.column_names.include?("last_name") - Person.connection.remove_column("people", "last_name") + Person.lease_connection.remove_column("people", "last_name") end end @@ -372,7 +372,7 @@ def migrate(x) ensure Person.reset_column_information if Person.column_names.include?("last_name") - Person.connection.remove_column("people", "last_name") + Person.lease_connection.remove_column("people", "last_name") end end @@ -402,7 +402,7 @@ def migrate(x) ensure Person.reset_column_information if Person.column_names.include?("last_name") - Person.connection.remove_column("people", "last_name") + Person.lease_connection.remove_column("people", "last_name") end end @@ -430,13 +430,13 @@ def migrate(x) ensure Person.reset_column_information if Person.column_names.include?("last_name") - Person.connection.remove_column("people", "last_name") + Person.lease_connection.remove_column("people", "last_name") end end def test_migration_instance_has_connection migration = Class.new(ActiveRecord::Migration::Current).new - assert_equal ActiveRecord::Base.connection, migration.connection + assert_equal ActiveRecord::Base.lease_connection, migration.connection end def test_method_missing_delegates_to_connection @@ -452,7 +452,7 @@ def create_table; "hi mom!"; end end def test_add_table_with_decimals - Person.connection.drop_table :big_numbers rescue nil + Person.lease_connection.drop_table :big_numbers rescue nil assert_not_predicate BigNumber, :table_exists? GiveMeBigNumbers.up @@ -565,7 +565,7 @@ def test_instance_based_migration_down assert migration.went_down, "have not gone down" end - if ActiveRecord::Base.connection.supports_ddl_transactions? + if ActiveRecord::Base.lease_connection.supports_ddl_transactions? def test_migrator_one_up_with_exception_and_rollback assert_no_column Person, :last_name @@ -630,7 +630,7 @@ def migrate(x) ensure Person.reset_column_information if Person.column_names.include?("last_name") - Person.connection.remove_column("people", "last_name") + Person.lease_connection.remove_column("people", "last_name") end end end @@ -742,18 +742,18 @@ def test_inserting_a_new_entry_into_internal_metadata def test_updating_an_existing_entry_into_internal_metadata @internal_metadata[:version] = "foo" - updated_at = @internal_metadata.send(:select_entry, @pool.connection, :version)["updated_at"] + updated_at = @internal_metadata.send(:select_entry, @pool.lease_connection, :version)["updated_at"] assert_equal "foo", @internal_metadata[:version] # same version doesn't update timestamps @internal_metadata[:version] = "foo" assert_equal "foo", @internal_metadata[:version] - assert_equal updated_at, @internal_metadata.send(:select_entry, @pool.connection, :version)["updated_at"] + assert_equal updated_at, @internal_metadata.send(:select_entry, @pool.lease_connection, :version)["updated_at"] # updated version updates timestamps @internal_metadata[:version] = "not_foo" assert_equal "not_foo", @internal_metadata[:version] - assert_not_equal updated_at, @internal_metadata.send(:select_entry, @pool.connection, :version)["updated_at"] + assert_not_equal updated_at, @internal_metadata.send(:select_entry, @pool.lease_connection, :version)["updated_at"] ensure @internal_metadata.delete_all_entries end @@ -880,134 +880,134 @@ def test_add_drop_table_with_prefix_and_suffix def test_create_table_with_binary_column assert_nothing_raised { - Person.connection.create_table :binary_testings do |t| + Person.lease_connection.create_table :binary_testings do |t| t.column "data", :binary, null: false end } - columns = Person.connection.columns(:binary_testings) + columns = Person.lease_connection.columns(:binary_testings) data_column = columns.detect { |c| c.name == "data" } assert_nil data_column.default ensure - Person.connection.drop_table :binary_testings, if_exists: true + Person.lease_connection.drop_table :binary_testings, if_exists: true end unless mysql_enforcing_gtid_consistency? def test_create_table_with_query - Person.connection.create_table :table_from_query_testings, as: "SELECT id FROM people WHERE id = 1" + Person.lease_connection.create_table :table_from_query_testings, as: "SELECT id FROM people WHERE id = 1" - columns = Person.connection.columns(:table_from_query_testings) - assert_equal [1], Person.connection.select_values("SELECT * FROM table_from_query_testings") + columns = Person.lease_connection.columns(:table_from_query_testings) + assert_equal [1], Person.lease_connection.select_values("SELECT * FROM table_from_query_testings") assert_equal 1, columns.length assert_equal "id", columns.first.name ensure - Person.connection.drop_table :table_from_query_testings rescue nil + Person.lease_connection.drop_table :table_from_query_testings rescue nil end def test_create_table_with_query_from_relation - Person.connection.create_table :table_from_query_testings, as: Person.select(:id).where(id: 1) + Person.lease_connection.create_table :table_from_query_testings, as: Person.select(:id).where(id: 1) - columns = Person.connection.columns(:table_from_query_testings) - assert_equal [1], Person.connection.select_values("SELECT * FROM table_from_query_testings") + columns = Person.lease_connection.columns(:table_from_query_testings) + assert_equal [1], Person.lease_connection.select_values("SELECT * FROM table_from_query_testings") assert_equal 1, columns.length assert_equal "id", columns.first.name ensure - Person.connection.drop_table :table_from_query_testings rescue nil + Person.lease_connection.drop_table :table_from_query_testings rescue nil end end if current_adapter?(:SQLite3Adapter) def test_allows_sqlite3_rollback_on_invalid_column_type - Person.connection.create_table :something, force: true do |t| + Person.lease_connection.create_table :something, force: true do |t| t.column :number, :integer t.column :name, :string t.column :foo, :bar end - assert Person.connection.column_exists?(:something, :foo) - assert_nothing_raised { Person.connection.remove_column :something, :foo, :bar } - assert_not Person.connection.column_exists?(:something, :foo) - assert Person.connection.column_exists?(:something, :name) - assert Person.connection.column_exists?(:something, :number) + assert Person.lease_connection.column_exists?(:something, :foo) + assert_nothing_raised { Person.lease_connection.remove_column :something, :foo, :bar } + assert_not Person.lease_connection.column_exists?(:something, :foo) + assert Person.lease_connection.column_exists?(:something, :name) + assert Person.lease_connection.column_exists?(:something, :number) ensure - Person.connection.drop_table :something, if_exists: true + Person.lease_connection.drop_table :something, if_exists: true end end def test_decimal_scale_without_precision_should_raise e = assert_raise(ArgumentError) do - Person.connection.create_table :test_decimal_scales, force: true do |t| + Person.lease_connection.create_table :test_decimal_scales, force: true do |t| t.decimal :scaleonly, scale: 10 end end assert_equal "Error adding decimal column: precision cannot be empty if scale is specified", e.message ensure - Person.connection.drop_table :test_decimal_scales, if_exists: true + Person.lease_connection.drop_table :test_decimal_scales, if_exists: true end if current_adapter?(:Mysql2Adapter, :TrilogyAdapter, :PostgreSQLAdapter) def test_out_of_range_integer_limit_should_raise e = assert_raise(ArgumentError) do - Person.connection.create_table :test_integer_limits, force: true do |t| + Person.lease_connection.create_table :test_integer_limits, force: true do |t| t.column :bigone, :integer, limit: 10 end end assert_includes e.message, "No integer type has byte size 10" ensure - Person.connection.drop_table :test_integer_limits, if_exists: true + Person.lease_connection.drop_table :test_integer_limits, if_exists: true end def test_out_of_range_text_limit_should_raise e = assert_raise(ArgumentError) do - Person.connection.create_table :test_text_limits, force: true do |t| + Person.lease_connection.create_table :test_text_limits, force: true do |t| t.text :bigtext, limit: 0xfffffffff end end assert_includes e.message, "No text type has byte size #{0xfffffffff}" ensure - Person.connection.drop_table :test_text_limits, if_exists: true + Person.lease_connection.drop_table :test_text_limits, if_exists: true end def test_out_of_range_binary_limit_should_raise e = assert_raise(ArgumentError) do - Person.connection.create_table :test_binary_limits, force: true do |t| + Person.lease_connection.create_table :test_binary_limits, force: true do |t| t.binary :bigbinary, limit: 0xfffffffff end end assert_includes e.message, "No binary type has byte size #{0xfffffffff}" ensure - Person.connection.drop_table :test_binary_limits, if_exists: true + Person.lease_connection.drop_table :test_binary_limits, if_exists: true end end if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) def test_invalid_text_size_should_raise e = assert_raise(ArgumentError) do - Person.connection.create_table :test_text_sizes, force: true do |t| + Person.lease_connection.create_table :test_text_sizes, force: true do |t| t.text :bigtext, size: 0xfffffffff end end assert_equal "#{0xfffffffff} is invalid :size value. Only :tiny, :medium, and :long are allowed.", e.message ensure - Person.connection.drop_table :test_text_sizes, if_exists: true + Person.lease_connection.drop_table :test_text_sizes, if_exists: true end end - if ActiveRecord::Base.connection.supports_advisory_locks? + if ActiveRecord::Base.lease_connection.supports_advisory_locks? def test_migrator_generates_valid_lock_id migration = Class.new(ActiveRecord::Migration::Current).new migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata, 100) lock_id = migrator.send(:generate_migrator_advisory_lock_id) - assert ActiveRecord::Base.connection.get_advisory_lock(lock_id), + assert ActiveRecord::Base.lease_connection.get_advisory_lock(lock_id), "the Migrator should have generated a valid lock id, but it didn't" - assert ActiveRecord::Base.connection.release_advisory_lock(lock_id), + assert ActiveRecord::Base.lease_connection.release_advisory_lock(lock_id), "the Migrator should have generated a valid lock id, but it didn't" end @@ -1019,7 +1019,7 @@ def test_generate_migrator_advisory_lock_id lock_id = migrator.send(:generate_migrator_advisory_lock_id) - current_database = ActiveRecord::Base.connection.current_database + current_database = ActiveRecord::Base.lease_connection.current_database salt = ActiveRecord::Migrator::MIGRATOR_SALT expected_id = Zlib.crc32(current_database) * salt @@ -1088,7 +1088,7 @@ def migrate(x) AND query LIKE '%#{lock_id}%' SQL - assert_no_changes -> { ActiveRecord::Base.connection.exec_query(query).rows.flatten } do + assert_no_changes -> { ActiveRecord::Base.lease_connection.exec_query(query).rows.flatten } do migrator.migrate end end @@ -1102,7 +1102,7 @@ def test_with_advisory_lock_raises_the_right_error_when_it_fails_to_release_lock e = assert_raises(ActiveRecord::ConcurrentMigrationError) do silence_stream($stderr) do migrator.send(:with_advisory_lock) do - ActiveRecord::Base.connection.release_advisory_lock(lock_id) + ActiveRecord::Base.lease_connection.release_advisory_lock(lock_id) end end end @@ -1153,7 +1153,7 @@ def env_name(pool) class ReservedWordsMigrationTest < ActiveRecord::TestCase def test_drop_index_from_table_named_values - connection = Person.connection + connection = Person.lease_connection connection.create_table :values, force: true do |t| t.integer :value end @@ -1169,7 +1169,7 @@ def test_drop_index_from_table_named_values class ExplicitlyNamedIndexMigrationTest < ActiveRecord::TestCase def test_drop_index_by_name - connection = Person.connection + connection = Person.lease_connection connection.create_table :values, force: true do |t| t.integer :value end @@ -1186,7 +1186,7 @@ def test_drop_index_by_name class IndexForTableWithSchemaMigrationTest < ActiveRecord::TestCase if current_adapter?(:PostgreSQLAdapter) def test_add_and_remove_index - connection = Person.connection + connection = Person.lease_connection connection.create_schema("my_schema") connection.create_table("my_schema.values", force: true) do |t| t.integer :value @@ -1203,21 +1203,21 @@ def test_add_and_remove_index end end -if ActiveRecord::Base.connection.supports_bulk_alter? +if ActiveRecord::Base.lease_connection.supports_bulk_alter? class BulkAlterTableMigrationsTest < ActiveRecord::TestCase def setup - @connection = Person.connection + @connection = Person.lease_connection @connection.create_table(:delete_me, force: true) { |t| } Person.reset_column_information Person.reset_sequence_name end teardown do - Person.connection.drop_table(:delete_me) rescue nil + Person.lease_connection.drop_table(:delete_me) rescue nil end def test_adding_multiple_columns - classname = ActiveRecord::Base.connection.class.name[/[^:]*$/] + classname = ActiveRecord::Base.lease_connection.class.name[/[^:]*$/] expected_query_count = { "Mysql2Adapter" => 1, "TrilogyAdapter" => 1, @@ -1320,7 +1320,7 @@ def test_adding_indexes t.integer :age end - classname = ActiveRecord::Base.connection.class.name[/[^:]*$/] + classname = ActiveRecord::Base.lease_connection.class.name[/[^:]*$/] expected_query_count = { "Mysql2Adapter" => 1, # mysql2 supports creating two indexes using one statement "TrilogyAdapter" => 1, # trilogy supports creating two indexes using one statement @@ -1354,7 +1354,7 @@ def test_removing_index assert index(:index_delete_me_on_name) - classname = ActiveRecord::Base.connection.class.name[/[^:]*$/] + classname = ActiveRecord::Base.lease_connection.class.name[/[^:]*$/] expected_query_count = { "Mysql2Adapter" => 1, # mysql2 supports dropping and creating two indexes using one statement "TrilogyAdapter" => 1, # trilogy supports dropping and creating two indexes using one statement @@ -1385,7 +1385,7 @@ def test_changing_columns assert_not column(:name).default assert_equal :date, column(:birthdate).type - classname = ActiveRecord::Base.connection.class.name[/[^:]*$/] + classname = ActiveRecord::Base.lease_connection.class.name[/[^:]*$/] expected_query_count = { "Mysql2Adapter" => 3, # one query for columns, one query for primary key, one query to do the bulk change "TrilogyAdapter" => 3, # one query for columns, one query for primary key, one query to do the bulk change @@ -1416,7 +1416,7 @@ def test_changing_column_null_with_default assert_not column(:name).default assert_equal :date, column(:birthdate).type - classname = ActiveRecord::Base.connection.class.name[/[^:]*$/] + classname = ActiveRecord::Base.lease_connection.class.name[/[^:]*$/] expected_query_count = { "Mysql2Adapter" => 7, # four queries to retrieve schema info, one for bulk change, one for UPDATE, one for NOT NULL "TrilogyAdapter" => 7, # four queries to retrieve schema info, one for bulk change, one for UPDATE, one for NOT NULL @@ -1452,13 +1452,13 @@ def test_default_functions_on_columns if current_adapter?(:PostgreSQLAdapter) assert_equal "gen_random_uuid()", column(:name).default_function - Person.connection.execute("INSERT INTO delete_me DEFAULT VALUES") + Person.lease_connection.execute("INSERT INTO delete_me DEFAULT VALUES") else assert_equal "uuid()", column(:name).default_function - Person.connection.execute("INSERT INTO delete_me () VALUES ()") + Person.lease_connection.execute("INSERT INTO delete_me () VALUES ()") end - person_data = Person.connection.select_one("SELECT * FROM delete_me ORDER BY id DESC") + person_data = Person.lease_connection.select_one("SELECT * FROM delete_me ORDER BY id DESC") assert_match(/\A(.+)-(.+)-(.+)-(.+)\Z/, person_data.fetch("name")) end end @@ -1487,7 +1487,7 @@ def test_changing_index assert index(:username_index) assert_not index(:username_index).unique - classname = ActiveRecord::Base.connection.class.name[/[^:]*$/] + classname = ActiveRecord::Base.lease_connection.class.name[/[^:]*$/] expected_query_count = { "Mysql2Adapter" => 1, # mysql2 supports dropping and creating two indexes using one statement "TrilogyAdapter" => 1, # trilogy supports dropping and creating two indexes using one statement @@ -1512,7 +1512,7 @@ def with_bulk_change_table(&block) # Reset columns/indexes cache as we're changing the table @columns = @indexes = nil - Person.connection.change_table(:delete_me, bulk: true, &block) + Person.lease_connection.change_table(:delete_me, bulk: true, &block) end def column(name) @@ -1520,7 +1520,7 @@ def column(name) end def columns - @columns ||= Person.connection.columns("delete_me") + @columns ||= Person.lease_connection.columns("delete_me") end def index(name) @@ -1528,7 +1528,7 @@ def index(name) end def indexes - @indexes ||= Person.connection.indexes("delete_me") + @indexes ||= Person.lease_connection.indexes("delete_me") end end # AlterTableMigrationsTest @@ -1536,7 +1536,7 @@ class RevertBulkAlterTableMigrationsTest < ActiveRecord::TestCase self.use_transactional_tests = false def setup - @connection = Person.connection + @connection = Person.lease_connection Person.reset_column_information Person.reset_sequence_name end diff --git a/activerecord/test/cases/multi_db_migrator_test.rb b/activerecord/test/cases/multi_db_migrator_test.rb index 07e1c60390..83d7d8c293 100644 --- a/activerecord/test/cases/multi_db_migrator_test.rb +++ b/activerecord/test/cases/multi_db_migrator_test.rb @@ -157,18 +157,18 @@ def test_migrator_db_has_no_schema_migrations_table migrator = migrator.new(@path_a, @schema_migration_a, @internal_metadata_a) @schema_migration_a.drop_table - assert_not @pool_a.connection.table_exists?("schema_migrations") + assert_not @pool_a.lease_connection.table_exists?("schema_migrations") migrator.migrate(1) - assert @pool_a.connection.table_exists?("schema_migrations") + assert @pool_a.lease_connection.table_exists?("schema_migrations") migrator.rollback _, migrator = migrator_class(3) migrator = migrator.new(@path_b, @schema_migration_b, @internal_metadata_b) @schema_migration_b.drop_table - assert_not @pool_b.connection.table_exists?("schema_migrations") + assert_not @pool_b.lease_connection.table_exists?("schema_migrations") migrator.migrate(1) - assert @pool_b.connection.table_exists?("schema_migrations") + assert @pool_b.lease_connection.table_exists?("schema_migrations") migrator.rollback end @@ -197,7 +197,7 @@ def test_migrator_forward end def test_internal_metadata_stores_environment - current_env = ActiveRecord::Base.connection.pool.db_config.env_name + current_env = ActiveRecord::Base.lease_connection.pool.db_config.env_name migrations_path = MIGRATIONS_ROOT + "/valid" migrator = ActiveRecord::MigrationContext.new(migrations_path, @schema_migration_b, @internal_metadata_b) diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index 3bfe0a52f8..17e8ee59f8 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -15,20 +15,20 @@ def setup end def test_connected - assert_not_nil Entrant.connection - assert_not_nil Course.connection + assert_not_nil Entrant.lease_connection + assert_not_nil Course.lease_connection end def test_proper_connection - assert_not_equal(Entrant.connection, Course.connection) - assert_equal(Entrant.connection, Entrant.retrieve_connection) - assert_equal(Course.connection, Course.retrieve_connection) - assert_equal(ActiveRecord::Base.connection, Entrant.connection) + assert_not_equal(Entrant.lease_connection, Course.lease_connection) + assert_equal(Entrant.lease_connection, Entrant.retrieve_connection) + assert_equal(Course.lease_connection, Course.retrieve_connection) + assert_equal(ActiveRecord::Base.lease_connection, Entrant.lease_connection) end def test_swapping_the_connection old_spec_name, Course.connection_specification_name = Course.connection_specification_name, "ActiveRecord::Base" - assert_equal(Entrant.connection, Course.connection) + assert_equal(Entrant.lease_connection, Course.lease_connection) ensure Course.connection_specification_name = old_spec_name end @@ -58,12 +58,12 @@ def test_associations end def test_course_connection_should_survive_reloads - assert Course.connection + assert Course.lease_connection assert Object.send(:remove_const, :Course) assert load("models/course.rb") - assert Course.connection + assert Course.lease_connection end def test_transactions_across_databases @@ -92,14 +92,14 @@ def test_transactions_across_databases end def test_connection - assert_same Entrant.connection, Bird.connection - assert_not_same Entrant.connection, Course.connection + assert_same Entrant.lease_connection, Bird.lease_connection + assert_not_same Entrant.lease_connection, Course.lease_connection end unless in_memory_db? def test_count_on_custom_connection - assert_equal ARUnit2Model.connection, College.connection - assert_not_equal ActiveRecord::Base.connection, College.connection + assert_equal ARUnit2Model.lease_connection, College.lease_connection + assert_not_equal ActiveRecord::Base.lease_connection, College.lease_connection assert_equal 1, College.count end @@ -115,12 +115,12 @@ def test_exception_contains_connection_pool Course.where(wrong_column: "wrong").first! end - assert_equal Course.connection.pool, error.connection_pool + assert_equal Course.lease_connection.pool, error.connection_pool end def test_exception_contains_correct_pool - course_conn = Course.connection - entrant_conn = Entrant.connection + course_conn = Course.lease_connection + entrant_conn = Entrant.lease_connection assert_not_equal course_conn, entrant_conn diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 8d8ed0ffe5..eadd49e1b4 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -744,7 +744,7 @@ def test_update_sti_subclass_type def test_becomes_default_sti_subclass original_type = Topic.columns_hash["type"].default - ActiveRecord::Base.connection.change_column_default :topics, :type, "Reply" + ActiveRecord::Base.lease_connection.change_column_default :topics, :type, "Reply" Topic.reset_column_information reply = topics(:second) @@ -754,7 +754,7 @@ def test_becomes_default_sti_subclass assert_instance_of Topic, topic ensure - ActiveRecord::Base.connection.change_column_default :topics, :type, original_type + ActiveRecord::Base.lease_connection.change_column_default :topics, :type, original_type Topic.reset_column_information end @@ -1463,9 +1463,9 @@ def test_find_via_reload end def test_reload_via_querycache - ActiveRecord::Base.connection.enable_query_cache! - ActiveRecord::Base.connection.clear_query_cache - assert ActiveRecord::Base.connection.query_cache_enabled, "cache should be on" + ActiveRecord::Base.lease_connection.enable_query_cache! + ActiveRecord::Base.lease_connection.clear_query_cache + assert ActiveRecord::Base.lease_connection.query_cache_enabled, "cache should be on" parrot = Parrot.create(name: "Shane") # populate the cache with the SELECT result @@ -1473,7 +1473,7 @@ def test_reload_via_querycache assert_equal parrot.id, found_parrot.id # Manually update the 'name' attribute in the DB directly - assert_equal 1, ActiveRecord::Base.connection.query_cache.size + assert_equal 1, ActiveRecord::Base.lease_connection.query_cache.size ActiveRecord::Base.uncached do found_parrot.name = "Mary" found_parrot.save @@ -1486,7 +1486,7 @@ def test_reload_via_querycache found_parrot = Parrot.find(parrot.id) assert_equal "Mary", found_parrot.name ensure - ActiveRecord::Base.connection.disable_query_cache! + ActiveRecord::Base.lease_connection.disable_query_cache! end def test_save_touch_false @@ -1508,7 +1508,7 @@ def test_reset_column_information_resets_children child_class = Class.new(Topic) child_class.new # force schema to load - ActiveRecord::Base.connection.add_column(:topics, :foo, :string) + ActiveRecord::Base.lease_connection.add_column(:topics, :foo, :string) Topic.reset_column_information # this should redefine attribute methods @@ -1518,7 +1518,7 @@ def test_reset_column_information_resets_children assert child_class.instance_methods.include?(:foo_changed?) assert_equal "bar", child_class.new(foo: :bar).foo ensure - ActiveRecord::Base.connection.remove_column(:topics, :foo) + ActiveRecord::Base.lease_connection.remove_column(:topics, :foo) Topic.reset_column_information end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 1aff31e65e..6b93af89c3 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -33,10 +33,10 @@ def test_pooled_connection_checkin_two def test_pooled_connection_remove ActiveRecord::Base.establish_connection(@connection.merge(pool: 2, checkout_timeout: 0.5)) - old_connection = ActiveRecord::Base.connection + old_connection = ActiveRecord::Base.lease_connection extra_connection = ActiveRecord::Base.connection_pool.checkout ActiveRecord::Base.connection_pool.remove(extra_connection) - assert_equal ActiveRecord::Base.connection.object_id, old_connection.object_id + assert_equal ActiveRecord::Base.lease_connection.object_id, old_connection.object_id end private @@ -65,7 +65,7 @@ def checkout_checkin_connections_loop(pool_size, loops) conn = ActiveRecord::Base.connection_pool.checkout ActiveRecord::Base.connection_pool.checkin conn @connection_count += 1 - ActiveRecord::Base.connection.data_sources + ActiveRecord::Base.lease_connection.data_sources rescue ActiveRecord::ConnectionTimeoutError @timed_out += 1 end diff --git a/activerecord/test/cases/prepared_statement_status_test.rb b/activerecord/test/cases/prepared_statement_status_test.rb index 595eb2f88c..75dabe9735 100644 --- a/activerecord/test/cases/prepared_statement_status_test.rb +++ b/activerecord/test/cases/prepared_statement_status_test.rb @@ -7,8 +7,8 @@ module ActiveRecord class PreparedStatementStatusTest < ActiveRecord::TestCase def test_prepared_statement_status_is_thread_and_instance_specific - course_conn = Course.connection - entrant_conn = Entrant.connection + course_conn = Course.lease_connection + entrant_conn = Entrant.lease_connection inside = Concurrent::Event.new preventing = Concurrent::Event.new @@ -16,7 +16,7 @@ def test_prepared_statement_status_is_thread_and_instance_specific assert_not_same course_conn, entrant_conn - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements t1 = Thread.new do course_conn.unprepared_statement do inside.set diff --git a/activerecord/test/cases/primary_class_test.rb b/activerecord/test/cases/primary_class_test.rb index ed153ad5a6..4351585700 100644 --- a/activerecord/test/cases/primary_class_test.rb +++ b/activerecord/test/cases/primary_class_test.rb @@ -108,7 +108,7 @@ def test_application_record_shares_a_connection_with_active_record_by_default assert_predicate ApplicationRecord, :primary_class? assert_predicate ApplicationRecord, :application_record_class? - assert_equal ActiveRecord::Base.connection, ApplicationRecord.connection + assert_equal ActiveRecord::Base.lease_connection, ApplicationRecord.lease_connection ensure ApplicationRecord.remove_connection ActiveRecord.application_record_class = nil @@ -124,7 +124,7 @@ def test_application_record_shares_a_connection_with_the_primary_abstract_class_ assert_predicate PrimaryClassTest::PrimaryAppRecord, :primary_class? assert_predicate PrimaryClassTest::PrimaryAppRecord, :application_record_class? assert_predicate PrimaryClassTest::PrimaryAppRecord, :abstract_class? - assert_equal ActiveRecord::Base.connection, PrimaryClassTest::PrimaryAppRecord.connection + assert_equal ActiveRecord::Base.lease_connection, PrimaryClassTest::PrimaryAppRecord.lease_connection ensure PrimaryClassTest::PrimaryAppRecord.remove_connection ActiveRecord.application_record_class = nil diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index 1a4727c136..b11a9dde24 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -221,9 +221,9 @@ def test_primary_key_returns_nil_if_it_does_not_exist def test_quoted_primary_key_after_set_primary_key k = Class.new(ActiveRecord::Base) k.table_name = "bar" - assert_equal k.connection.quote_column_name("id"), k.quoted_primary_key + assert_equal k.lease_connection.quote_column_name("id"), k.quoted_primary_key k.primary_key = "foo" - assert_equal k.connection.quote_column_name("foo"), k.quoted_primary_key + assert_equal k.lease_connection.quote_column_name("foo"), k.quoted_primary_key end def test_auto_detect_primary_key_from_schema @@ -291,7 +291,7 @@ class AutoIncrement < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown @@ -328,7 +328,7 @@ class Barcode < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table(:barcodes, primary_key: "code", id: :string, limit: 42, force: true) end @@ -371,7 +371,7 @@ class CompositePrimaryKeyTest < ActiveRecord::TestCase def setup ActiveRecord::Base.schema_cache.clear! - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table(:uber_barcodes, primary_key: ["region", "code"], force: true) do |t| t.string :region t.integer :code @@ -502,7 +502,7 @@ class PrimaryKeyIntegerNilDefaultTest < ActiveRecord::TestCase include SchemaDumpingHelper def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def teardown @@ -533,7 +533,7 @@ class Widget < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @pk_type = current_adapter?(:PostgreSQLAdapter) ? :serial : :integer end diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index 9535b13d1f..f002df1c7c 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -35,8 +35,8 @@ def sql(event) end def teardown - Task.connection.clear_query_cache - ActiveRecord::Base.connection.disable_query_cache! + Task.lease_connection.clear_query_cache + ActiveRecord::Base.lease_connection.disable_query_cache! super end @@ -45,10 +45,10 @@ def test_execute_clear_cache mw = middleware { |env| Post.first - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect - Post.connection.execute("SELECT 1") - query_cache = ActiveRecord::Base.connection.query_cache + Post.lease_connection.execute("SELECT 1") + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 0, query_cache.size, query_cache.inspect } mw.call({}) @@ -61,10 +61,10 @@ def test_exec_query_clear_cache mw = middleware { |env| Post.first - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect - Post.connection.exec_query("SELECT 1") - query_cache = ActiveRecord::Base.connection.query_cache + Post.lease_connection.exec_query("SELECT 1") + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 0, query_cache.size, query_cache.inspect } mw.call({}) @@ -77,13 +77,13 @@ def test_writes_should_always_clear_cache mw = middleware { |env| Post.first - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect - Post.connection.uncached do + Post.lease_connection.uncached do # should clear the cache Post.create!(title: "a new post", body: "and a body") end - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 0, query_cache.size, query_cache.inspect } mw.call({}) @@ -96,12 +96,12 @@ def test_reads_dont_clear_disabled_cache mw = middleware { |env| Post.first - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect - Post.connection.uncached do + Post.lease_connection.uncached do Post.count # shouldn't clear the cache end - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect } mw.call({}) @@ -115,7 +115,7 @@ def test_exceptional_middleware_clears_and_disables_cache_on_error mw = middleware { |env| Task.find 1 Task.find 1 - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect raise "lol borked" } @@ -132,7 +132,7 @@ def test_query_cache_is_applied_to_all_connections mw = middleware { |env| ActiveRecord::Base.connection_handler.connection_pool_list(:all).each do |pool| - assert_predicate pool.connection, :query_cache_enabled + assert_predicate pool.lease_connection, :query_cache_enabled end } @@ -218,7 +218,7 @@ def test_query_cache_across_threads assert_cache :off, conn end - assert_not_predicate ActiveRecord::Base.connection, :nil? + assert_not_predicate ActiveRecord::Base.lease_connection, :nil? assert_cache :off middleware { @@ -227,7 +227,7 @@ def test_query_cache_across_threads Task.find 1 assert_cache :dirty - thread_1_connection = ActiveRecord::Base.connection + thread_1_connection = ActiveRecord::Base.lease_connection ActiveRecord::Base.connection_handler.clear_active_connections!(:all) assert_cache :off, thread_1_connection @@ -236,7 +236,7 @@ def test_query_cache_across_threads thread_2_connection = nil thread = Thread.new { - thread_2_connection = ActiveRecord::Base.connection + thread_2_connection = ActiveRecord::Base.lease_connection assert_equal thread_2_connection, thread_1_connection assert_cache :off @@ -256,7 +256,7 @@ def test_query_cache_across_threads started.wait - thread_1_connection = ActiveRecord::Base.connection + thread_1_connection = ActiveRecord::Base.lease_connection assert_not_equal thread_1_connection, thread_2_connection assert_cache :dirty, thread_2_connection checked.set @@ -287,7 +287,7 @@ def test_middleware_caches mw = middleware { |env| Task.find 1 Task.find 1 - query_cache = ActiveRecord::Base.connection.query_cache + query_cache = ActiveRecord::Base.lease_connection.query_cache assert_equal 1, query_cache.size, query_cache.inspect [200, {}, nil] } @@ -308,7 +308,7 @@ def test_cache_passing_a_relation post = Post.first Post.cache do query = post.categories.select(:post_id) - assert Post.connection.select_all(query).is_a?(ActiveRecord::Result) + assert Post.lease_connection.select_all(query).is_a?(ActiveRecord::Result) end end @@ -352,7 +352,7 @@ def test_exists_queries_with_cache def test_select_all_with_cache Post.cache do assert_queries_count(1) do - 2.times { Post.connection.select_all(Post.all) } + 2.times { Post.lease_connection.select_all(Post.all) } end end end @@ -360,7 +360,7 @@ def test_select_all_with_cache def test_select_one_with_cache Post.cache do assert_queries_count(1) do - 2.times { Post.connection.select_one(Post.all) } + 2.times { Post.lease_connection.select_one(Post.all) } end end end @@ -368,7 +368,7 @@ def test_select_one_with_cache def test_select_value_with_cache Post.cache do assert_queries_count(1) do - 2.times { Post.connection.select_value(Post.all) } + 2.times { Post.lease_connection.select_value(Post.all) } end end end @@ -376,7 +376,7 @@ def test_select_value_with_cache def test_select_values_with_cache Post.cache do assert_queries_count(1) do - 2.times { Post.connection.select_values(Post.all) } + 2.times { Post.lease_connection.select_values(Post.all) } end end end @@ -384,7 +384,7 @@ def test_select_values_with_cache def test_select_rows_with_cache Post.cache do assert_queries_count(1) do - 2.times { Post.connection.select_rows(Post.all) } + 2.times { Post.lease_connection.select_rows(Post.all) } end end end @@ -404,7 +404,7 @@ def test_cache_notifications_can_be_overridden logger = ShouldNotHaveExceptionsLogger.new subscriber = ActiveSupport::Notifications.subscribe "sql.active_record", logger - connection = ActiveRecord::Base.connection.dup + connection = ActiveRecord::Base.lease_connection.dup def connection.cache_notification_info(sql, name, binds) super.merge(neat: true) @@ -461,7 +461,7 @@ def test_cache_is_flat def test_cache_does_not_wrap_results_in_arrays Task.cache do - assert_equal 2, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") + assert_equal 2, Task.lease_connection.select_value("SELECT count(*) AS count_all FROM tasks") end end @@ -500,7 +500,7 @@ def test_cache_is_available_when_using_a_not_connected_connection end def test_query_cache_executes_new_queries_within_block - ActiveRecord::Base.connection.enable_query_cache! + ActiveRecord::Base.lease_connection.enable_query_cache! # Warm up the cache by running the query assert_queries_count(1) do @@ -512,7 +512,7 @@ def test_query_cache_executes_new_queries_within_block assert_equal 0, Post.where(title: "test").to_a.count end - ActiveRecord::Base.connection.uncached do + ActiveRecord::Base.lease_connection.uncached do # Check that new query is executed, avoiding the cache assert_queries_count(1) do assert_equal 0, Post.where(title: "test").to_a.count @@ -521,7 +521,7 @@ def test_query_cache_executes_new_queries_within_block end def test_query_cache_doesnt_leak_cached_results_of_rolled_back_queries - ActiveRecord::Base.connection.enable_query_cache! + ActiveRecord::Base.lease_connection.enable_query_cache! post = Post.first Post.transaction do @@ -532,7 +532,7 @@ def test_query_cache_doesnt_leak_cached_results_of_rolled_back_queries assert_equal 0, Post.where(title: "rollback").to_a.count - ActiveRecord::Base.connection.uncached do + ActiveRecord::Base.lease_connection.uncached do assert_equal 0, Post.where(title: "rollback").to_a.count end @@ -547,7 +547,7 @@ def test_query_cache_doesnt_leak_cached_results_of_rolled_back_queries assert_equal 0, Post.where(title: "rollback").to_a.count - ActiveRecord::Base.connection.uncached do + ActiveRecord::Base.lease_connection.uncached do assert_equal 0, Post.where(title: "rollback").to_a.count end end @@ -558,7 +558,7 @@ def test_query_cached_even_when_types_are_reset Task.find(1) # Preload the type cache again (so we don't have those queries issued during our assertions) - Task.connection.send(:reload_type_map) if Task.connection.respond_to?(:reload_type_map, true) + Task.lease_connection.send(:reload_type_map) if Task.lease_connection.respond_to?(:reload_type_map, true) # Clear places where type information is cached Task.reset_column_information @@ -587,9 +587,9 @@ def test_query_cache_is_enabled_on_connections_established_after_middleware_runs assert_not ActiveRecord::Base.connection_handler.active_connections?(:all) # Double check they are cleared middleware { - assert_predicate ActiveRecord::Base.connection, :query_cache_enabled + assert_predicate ActiveRecord::Base.lease_connection, :query_cache_enabled }.call({}) - assert_not_predicate ActiveRecord::Base.connection, :query_cache_enabled + assert_not_predicate ActiveRecord::Base.lease_connection, :query_cache_enabled end def test_query_caching_is_local_to_the_current_thread @@ -597,11 +597,11 @@ def test_query_caching_is_local_to_the_current_thread middleware { assert ActiveRecord::Base.connection_pool.query_cache_enabled - assert ActiveRecord::Base.connection.query_cache_enabled + assert ActiveRecord::Base.lease_connection.query_cache_enabled Thread.new { assert_not ActiveRecord::Base.connection_pool.query_cache_enabled - assert_not ActiveRecord::Base.connection.query_cache_enabled + assert_not ActiveRecord::Base.lease_connection.query_cache_enabled ActiveRecord::Base.connection_handler.clear_active_connections!(:all) }.join @@ -612,7 +612,7 @@ def test_query_cache_is_enabled_on_all_connection_pools middleware { ActiveRecord::Base.connection_handler.connection_pool_list(:all).each do |pool| assert pool.query_cache_enabled - assert pool.connection.query_cache_enabled + assert pool.lease_connection.query_cache_enabled end }.call({}) end @@ -656,7 +656,7 @@ def test_clear_query_cache_is_called_on_all_connections begin assert_cache :off - ActiveRecord::Base.connection.enable_query_cache! + ActiveRecord::Base.lease_connection.enable_query_cache! assert_cache :clean thread_a = Thread.new do @@ -677,7 +677,7 @@ def test_clear_query_cache_is_called_on_all_connections begin assert_cache :off - ActiveRecord::Base.connection.enable_query_cache! + ActiveRecord::Base.lease_connection.enable_query_cache! assert_cache :clean Post.first @@ -708,7 +708,7 @@ def test_clear_query_cache_is_called_on_all_connections private def with_temporary_connection_pool(&block) - pool_config = ActiveRecord::Base.connection.pool.pool_config + pool_config = ActiveRecord::Base.lease_connection.pool.pool_config new_pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(pool_config) pool_config.stub(:pool, new_pool, &block) @@ -720,7 +720,7 @@ def middleware(&app) lambda { |env| executor.wrap { app.call(env) } } end - def assert_cache(state, connection = ActiveRecord::Base.connection) + def assert_cache(state, connection = ActiveRecord::Base.lease_connection) case state when :off assert_not connection.query_cache_enabled, "cache should be off" @@ -759,7 +759,7 @@ def hash end def setup - ActiveRecord::Base.connection.create_table("json_objs", force: true) do |t| + ActiveRecord::Base.lease_connection.create_table("json_objs", force: true) do |t| if current_adapter?(:PostgreSQLAdapter) t.jsonb "payload" else @@ -767,7 +767,7 @@ def setup end end - ActiveRecord::Base.connection.enable_query_cache! + ActiveRecord::Base.lease_connection.enable_query_cache! end def test_query_cache_handles_mutated_binds @@ -781,8 +781,8 @@ def test_query_cache_handles_mutated_binds end def teardown - ActiveRecord::Base.connection.disable_query_cache! - ActiveRecord::Base.connection.drop_table("json_objs", if_exists: true) + ActiveRecord::Base.lease_connection.disable_query_cache! + ActiveRecord::Base.lease_connection.drop_table("json_objs", if_exists: true) end end @@ -800,16 +800,16 @@ class YAMLObj < ActiveRecord::Base def setup @use_yaml_unsafe_load_was = ActiveRecord.use_yaml_unsafe_load - ActiveRecord::Base.connection.create_table("yaml_objs", force: true) do |t| + ActiveRecord::Base.lease_connection.create_table("yaml_objs", force: true) do |t| t.text "payload" end - ActiveRecord::Base.connection.enable_query_cache! + ActiveRecord::Base.lease_connection.enable_query_cache! end def teardown - ActiveRecord::Base.connection.disable_query_cache! - ActiveRecord::Base.connection.drop_table("yaml_objs", if_exists: true) + ActiveRecord::Base.lease_connection.disable_query_cache! + ActiveRecord::Base.lease_connection.drop_table("yaml_objs", if_exists: true) ActiveRecord.use_yaml_unsafe_load = @use_yaml_unsafe_load_was end @@ -844,7 +844,7 @@ class QueryCacheExpiryTest < ActiveRecord::TestCase fixtures :tasks, :posts, :categories, :categories_posts def teardown - Task.connection.clear_query_cache + Task.lease_connection.clear_query_cache end def test_cache_gets_cleared_after_migration @@ -852,44 +852,44 @@ def test_cache_gets_cleared_after_migration Post.find(1) # change the column definition - Post.connection.change_column :posts, :title, :string, limit: 80 + Post.lease_connection.change_column :posts, :title, :string, limit: 80 assert_nothing_raised { Post.find(1) } # restore the old definition - Post.connection.change_column :posts, :title, :string + Post.lease_connection.change_column :posts, :title, :string end def test_find - assert_called(Task.connection.query_cache, :clear, times: 1) do - assert_not Task.connection.query_cache_enabled + assert_called(Task.lease_connection.query_cache, :clear, times: 1) do + assert_not Task.lease_connection.query_cache_enabled Task.cache do - assert Task.connection.query_cache_enabled + assert Task.lease_connection.query_cache_enabled Task.find(1) Task.uncached do - assert_not Task.connection.query_cache_enabled + assert_not Task.lease_connection.query_cache_enabled Task.find(1) end - assert Task.connection.query_cache_enabled + assert Task.lease_connection.query_cache_enabled end - assert_not Task.connection.query_cache_enabled + assert_not Task.lease_connection.query_cache_enabled end end def test_enable_disable - assert_called(Task.connection.query_cache, :clear, times: 1) do + assert_called(Task.lease_connection.query_cache, :clear, times: 1) do Task.cache { } end - assert_called(Task.connection.query_cache, :clear, times: 1) do + assert_called(Task.lease_connection.query_cache, :clear, times: 1) do Task.cache { Task.cache { } } end end def test_update Task.cache do - assert_called(Task.connection.query_cache, :clear, times: 1) do + assert_called(Task.lease_connection.query_cache, :clear, times: 1) do task = Task.find(1) task.starting = Time.now.utc task.save! @@ -899,7 +899,7 @@ def test_update def test_destroy Task.cache do - assert_called(Task.connection.query_cache, :clear, times: 1) do + assert_called(Task.lease_connection.query_cache, :clear, times: 1) do Task.find(1).destroy end end @@ -907,7 +907,7 @@ def test_destroy def test_insert Task.cache do - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.create! end end @@ -917,11 +917,11 @@ def test_insert_all skip unless supports_insert_on_duplicate_skip? Task.cache do - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.insert({ starting: Time.now }) end - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.insert_all([{ starting: Time.now }]) end end @@ -929,11 +929,11 @@ def test_insert_all def test_insert_all_bang Task.cache do - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.insert!({ starting: Time.now }) end - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.insert_all!([{ starting: Time.now }]) end end @@ -943,11 +943,11 @@ def test_upsert_all skip unless supports_insert_on_duplicate_update? Task.cache do - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.upsert({ starting: Time.now }) end - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do Task.upsert_all([{ starting: Time.now }]) end end @@ -955,7 +955,7 @@ def test_upsert_all def test_cache_is_expired_by_habtm_update ActiveRecord::Base.cache do - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do c = Category.first p = Post.first p.categories << c @@ -965,7 +965,7 @@ def test_cache_is_expired_by_habtm_update def test_cache_is_expired_by_habtm_delete ActiveRecord::Base.cache do - assert_called(ActiveRecord::Base.connection.query_cache, :clear, times: 1) do + assert_called(ActiveRecord::Base.lease_connection.query_cache, :clear, times: 1) do p = Post.find(1) assert_predicate p.categories, :any? p.categories.delete_all @@ -977,7 +977,7 @@ def test_query_cache_lru_eviction store = ActiveRecord::ConnectionAdapters::QueryCache::Store.new(2) store.enabled = true - connection = Post.connection + connection = Post.lease_connection old_store, connection.query_cache = connection.query_cache, store begin Post.cache do @@ -1006,10 +1006,10 @@ def test_query_cache_lru_eviction end test "threads use the same connection" do - @connection_1 = ActiveRecord::Base.connection.object_id + @connection_1 = ActiveRecord::Base.lease_connection.object_id thread_a = Thread.new do - @connection_2 = ActiveRecord::Base.connection.object_id + @connection_2 = ActiveRecord::Base.lease_connection.object_id end thread_a.join diff --git a/activerecord/test/cases/query_logs_test.rb b/activerecord/test/cases/query_logs_test.rb index 4ae1bb5740..95b2bf296b 100644 --- a/activerecord/test/cases/query_logs_test.rb +++ b/activerecord/test/cases/query_logs_test.rb @@ -59,7 +59,7 @@ def test_basic_commenting ActiveRecord::QueryLogs.tags = [ :application ] assert_queries_match(%r{select id from posts /\*application:active_record\*/$}) do - ActiveRecord::Base.connection.execute "select id from posts" + ActiveRecord::Base.lease_connection.execute "select id from posts" end end @@ -68,7 +68,7 @@ def test_add_comments_to_beginning_of_query ActiveRecord::QueryLogs.prepend_comment = true assert_queries_match(%r{/\*application:active_record\*/ select id from posts$}) do - ActiveRecord::Base.connection.execute "select id from posts" + ActiveRecord::Base.lease_connection.execute "select id from posts" end end @@ -120,11 +120,11 @@ def test_retrieves_comment_from_cache_when_enabled_and_set ActiveRecord::QueryLogs.tags = [ { query_counter: -> { i += 1 } } ] assert_queries_match("SELECT 1 /*query_counter:1*/") do - ActiveRecord::Base.connection.execute "SELECT 1" + ActiveRecord::Base.lease_connection.execute "SELECT 1" end assert_queries_match("SELECT 1 /*query_counter:1*/") do - ActiveRecord::Base.connection.execute "SELECT 1" + ActiveRecord::Base.lease_connection.execute "SELECT 1" end end @@ -134,13 +134,13 @@ def test_resets_cache_on_context_update ActiveRecord::QueryLogs.tags = [ temporary_tag: ->(context) { context[:temporary] } ] assert_queries_match("SELECT 1 /*temporary_tag:value*/") do - ActiveRecord::Base.connection.execute "SELECT 1" + ActiveRecord::Base.lease_connection.execute "SELECT 1" end ActiveSupport::ExecutionContext[:temporary] = "new_value" assert_queries_match("SELECT 1 /*temporary_tag:new_value*/") do - ActiveRecord::Base.connection.execute "SELECT 1" + ActiveRecord::Base.lease_connection.execute "SELECT 1" end end @@ -157,7 +157,7 @@ def test_default_tag_behavior end def test_connection_is_passed_to_tagging_proc - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection ActiveRecord::QueryLogs.tags = [ same_connection: ->(context) { context[:connection] == connection } ] assert_queries_match("SELECT 1 /*same_connection:true*/") do @@ -171,14 +171,14 @@ def test_connection_does_not_override_already_existing_connection_in_context ActiveRecord::QueryLogs.tags = [ fake_connection: ->(context) { context[:connection] == fake_connection } ] assert_queries_match("SELECT 1 /*fake_connection:true*/") do - ActiveRecord::Base.connection.execute "SELECT 1" + ActiveRecord::Base.lease_connection.execute "SELECT 1" end end def test_empty_comments_are_not_added ActiveRecord::QueryLogs.tags = [ empty: -> { nil } ] assert_queries_match(%r{select id from posts$}) do - ActiveRecord::Base.connection.execute "select id from posts" + ActiveRecord::Base.lease_connection.execute "select id from posts" end end @@ -247,7 +247,7 @@ def test_sqlcommenter_format_value_string_coercible def test_invalid_encoding_query ActiveRecord::QueryLogs.tags = [ :application ] assert_nothing_raised do - ActiveRecord::Base.connection.execute "select 1 as '\xFF'" + ActiveRecord::Base.lease_connection.execute "select 1 as '\xFF'" end end end diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb index 62fbd5dc41..a00c50f8ea 100644 --- a/activerecord/test/cases/quoting_test.rb +++ b/activerecord/test/cases/quoting_test.rb @@ -202,7 +202,7 @@ def test_quote_duration class TypeCastingTest < ActiveRecord::TestCase def setup - @conn = ActiveRecord::Base.connection + @conn = ActiveRecord::Base.lease_connection end def test_type_cast_symbol @@ -250,7 +250,7 @@ def test_type_cast_duration_should_raise_error class QuoteBooleanTest < ActiveRecord::TestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_quote_returns_frozen_string diff --git a/activerecord/test/cases/relation/delete_all_test.rb b/activerecord/test/cases/relation/delete_all_test.rb index fca1652514..14d73abfb8 100644 --- a/activerecord/test/cases/relation/delete_all_test.rb +++ b/activerecord/test/cases/relation/delete_all_test.rb @@ -83,9 +83,9 @@ def test_delete_all_with_joins_and_where_part_is_hash end if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - assert_no_match %r/SELECT DISTINCT #{Regexp.escape(Pet.connection.quote_table_name("pets.pet_id"))}/, sqls.last + assert_no_match %r/SELECT DISTINCT #{Regexp.escape(Pet.lease_connection.quote_table_name("pets.pet_id"))}/, sqls.last else - assert_match %r/SELECT #{Regexp.escape(Pet.connection.quote_table_name("pets.pet_id"))}/, sqls.last + assert_match %r/SELECT #{Regexp.escape(Pet.lease_connection.quote_table_name("pets.pet_id"))}/, sqls.last end end diff --git a/activerecord/test/cases/relation/load_async_test.rb b/activerecord/test/cases/relation/load_async_test.rb index af867cf3c1..5be5b02568 100644 --- a/activerecord/test/cases/relation/load_async_test.rb +++ b/activerecord/test/cases/relation/load_async_test.rb @@ -9,7 +9,7 @@ module ActiveRecord module WaitForAsyncTestHelper private - def wait_for_async_query(connection = ActiveRecord::Base.connection, timeout: 5) + def wait_for_async_query(connection = ActiveRecord::Base.lease_connection, timeout: 5) return unless connection.async_enabled? executor = connection.pool.async_executor @@ -124,9 +124,9 @@ def test_notification_forwarding wait_for_async_query assert_equal expected_records, deferred_posts.to_a - assert_equal Post.connection.supports_concurrent_connections?, status[:async] + assert_equal Post.lease_connection.supports_concurrent_connections?, status[:async] assert_equal Thread.current.object_id, status[:thread_id] - if Post.connection.supports_concurrent_connections? + if Post.lease_connection.supports_concurrent_connections? assert_instance_of Float, status[:lock_wait] else assert_nil status[:lock_wait] @@ -151,7 +151,7 @@ def test_simple_query wait_for_async_query assert_equal expected_records, deferred_posts.to_a - assert_equal Post.connection.supports_concurrent_connections?, status[:async] + assert_equal Post.lease_connection.supports_concurrent_connections?, status[:async] ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end @@ -199,7 +199,7 @@ def test_eager_loading_query assert_queries_count(0) do deferred_posts.each(&:comments) end - assert_equal Post.connection.supports_concurrent_connections?, status[:async] + assert_equal Post.lease_connection.supports_concurrent_connections?, status[:async] ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end @@ -286,7 +286,7 @@ def test_simple_query deferred_posts = Post.where(author_id: 1).load_async assert_equal expected_records, deferred_posts.to_a - assert_not_equal Post.connection.supports_concurrent_connections?, status[:async] + assert_not_equal Post.lease_connection.supports_concurrent_connections?, status[:async] ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end @@ -326,7 +326,7 @@ def test_eager_loading_query deferred_posts.each(&:comments) end - assert_predicate Post.connection, :supports_concurrent_connections? + assert_predicate Post.lease_connection, :supports_concurrent_connections? assert_not status[:async], "Expected status[:async] to be false with NullExecutor" ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber @@ -429,7 +429,7 @@ def test_simple_query wait_for_async_query assert_equal expected_records, deferred_posts.to_a - assert_equal Post.connection.supports_concurrent_connections?, status[:async] + assert_equal Post.lease_connection.supports_concurrent_connections?, status[:async] ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end @@ -468,7 +468,7 @@ def test_eager_loading_query assert_queries_count(0) do deferred_posts.each(&:comments) end - assert_equal Post.connection.supports_concurrent_connections?, status[:async] + assert_equal Post.lease_connection.supports_concurrent_connections?, status[:async] ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end @@ -577,8 +577,8 @@ def test_simple_query assert_equal expected_records, deferred_posts.to_a assert_equal expected_dogs, deferred_dogs.to_a - assert_equal Post.connection.async_enabled?, status[:async] - assert_equal OtherDog.connection.async_enabled?, dog_status[:async] + assert_equal Post.lease_connection.async_enabled?, status[:async] + assert_equal OtherDog.lease_connection.async_enabled?, dog_status[:async] ensure ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end diff --git a/activerecord/test/cases/relation/merging_test.rb b/activerecord/test/cases/relation/merging_test.rb index 3bb8f5211c..3d348fa326 100644 --- a/activerecord/test/cases/relation/merging_test.rb +++ b/activerecord/test/cases/relation/merging_test.rb @@ -139,14 +139,14 @@ def test_merge_doesnt_duplicate_same_clauses non_mary_and_bob = Author.where.not(id: [mary, bob]) - author_id = Author.connection.quote_table_name("authors.id") + author_id = Author.lease_connection.quote_table_name("authors.id") assert_queries_match(/WHERE #{Regexp.escape(author_id)} NOT IN \((\?|\W?\w?\d), \g<1>\)\z/) do assert_equal [david], non_mary_and_bob.merge(non_mary_and_bob) end only_david = Author.where("#{author_id} IN (?)", david) - matcher = if Author.connection.prepared_statements + matcher = if Author.lease_connection.prepared_statements if current_adapter?(:PostgreSQLAdapter) /WHERE \(#{Regexp.escape(author_id)} IN \(\$1\)\)\z/ else @@ -364,7 +364,7 @@ class MergingDifferentRelationsTest < ActiveRecord::TestCase assert_equal dev.ratings, [rating_1] end - if ActiveRecord::Base.connection.supports_common_table_expressions? + if ActiveRecord::Base.lease_connection.supports_common_table_expressions? test "merging relation with common table expression" do posts_with_tags = Post.with(posts_with_tags: Post.where("tags_count > 0")).from("posts_with_tags AS posts") posts_with_comments = Post.where("legacy_comments_count > 0") diff --git a/activerecord/test/cases/relation/predicate_builder_test.rb b/activerecord/test/cases/relation/predicate_builder_test.rb index 13900cd155..4b9ae99625 100644 --- a/activerecord/test/cases/relation/predicate_builder_test.rb +++ b/activerecord/test/cases/relation/predicate_builder_test.rb @@ -39,7 +39,7 @@ def test_does_not_mutate private def topic_title - Topic.connection.quote_table_name("topics.title") + Topic.lease_connection.quote_table_name("topics.title") end end end diff --git a/activerecord/test/cases/relation/update_all_test.rb b/activerecord/test/cases/relation/update_all_test.rb index ec4539f9e4..d41108b1c4 100644 --- a/activerecord/test/cases/relation/update_all_test.rb +++ b/activerecord/test/cases/relation/update_all_test.rb @@ -69,9 +69,9 @@ def test_update_all_with_joins end if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - assert_no_match %r/SELECT DISTINCT #{Regexp.escape(Pet.connection.quote_table_name("pets.pet_id"))}/, sqls.last + assert_no_match %r/SELECT DISTINCT #{Regexp.escape(Pet.lease_connection.quote_table_name("pets.pet_id"))}/, sqls.last else - assert_match %r/SELECT #{Regexp.escape(Pet.connection.quote_table_name("pets.pet_id"))}/, sqls.last + assert_match %r/SELECT #{Regexp.escape(Pet.lease_connection.quote_table_name("pets.pet_id"))}/, sqls.last end end diff --git a/activerecord/test/cases/relation/with_test.rb b/activerecord/test/cases/relation/with_test.rb index 514a1d6def..f6eccee3ed 100644 --- a/activerecord/test/cases/relation/with_test.rb +++ b/activerecord/test/cases/relation/with_test.rb @@ -15,7 +15,7 @@ class WithTest < ActiveRecord::TestCase POSTS_WITH_TAGS_AND_COMMENTS = (POSTS_WITH_COMMENTS & POSTS_WITH_TAGS).sort.freeze POSTS_WITH_TAGS_AND_MULTIPLE_COMMENTS = (POSTS_WITH_MULTIPLE_COMMENTS & POSTS_WITH_TAGS).sort.freeze - if ActiveRecord::Base.connection.supports_common_table_expressions? + if ActiveRecord::Base.lease_connection.supports_common_table_expressions? def test_with_when_hash_is_passed_as_an_argument relation = Post .with(posts_with_comments: Post.where("legacy_comments_count > 0")) diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index 9313e319ff..2614271605 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -291,7 +291,7 @@ def test_respond_to_for_non_selected_element def test_select_quotes_when_using_from_clause skip_if_sqlite3_version_includes_quoting_bug - quoted_join = ActiveRecord::Base.connection.quote_table_name("join") + quoted_join = ActiveRecord::Base.lease_connection.quote_table_name("join") selected = Post.select(:join).from(Post.select("id as #{quoted_join}")).map(&:join) assert_equal Post.pluck(:id).sort, selected.sort end @@ -373,7 +373,7 @@ def test_relation_with_optimizer_hints_filters_sql_comment_delimiters end def test_does_not_duplicate_optimizer_hints_on_merge - escaped_table = Post.connection.quote_table_name("posts") + escaped_table = Post.lease_connection.quote_table_name("posts") expected = "SELECT /*+ OMGHINT */ #{escaped_table}.* FROM #{escaped_table}" query = Post.optimizer_hints("OMGHINT").merge(Post.optimizer_hints("OMGHINT")).to_sql assert_equal expected, query @@ -457,7 +457,7 @@ def skip_if_sqlite3_version_includes_quoting_bug def sqlite3_version_includes_quoting_bug? if current_adapter?(:SQLite3Adapter) - selected_quoted_column_names = ActiveRecord::Base.connection.exec_query( + selected_quoted_column_names = ActiveRecord::Base.lease_connection.exec_query( 'SELECT "join" FROM (SELECT id AS "join" FROM posts) subquery' ).columns ["join"] != selected_quoted_column_names diff --git a/activerecord/test/cases/reserved_word_test.rb b/activerecord/test/cases/reserved_word_test.rb index e32605fd11..cd3977242a 100644 --- a/activerecord/test/cases/reserved_word_test.rb +++ b/activerecord/test/cases/reserved_word_test.rb @@ -28,7 +28,7 @@ class Distinct < ActiveRecord::Base end def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :select, force: true @connection.create_table :distinct, force: true @connection.create_table :distinct_select, id: false, force: true do |t| diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index e470ccb37b..41d00cd6df 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -11,25 +11,25 @@ def setup end def test_sanitize_sql_array_handles_string_interpolation - quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi") + quoted_bambi = ActiveRecord::Base.lease_connection.quote_string("Bambi") assert_equal "name='#{quoted_bambi}'", Binary.sanitize_sql_array(["name='%s'", "Bambi"]) assert_equal "name='#{quoted_bambi}'", Binary.sanitize_sql_array(["name='%s'", "Bambi".mb_chars]) - quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote_string("Bambi\nand\nThumper") + quoted_bambi_and_thumper = ActiveRecord::Base.lease_connection.quote_string("Bambi\nand\nThumper") assert_equal "name='#{quoted_bambi_and_thumper}'", Binary.sanitize_sql_array(["name='%s'", "Bambi\nand\nThumper"]) assert_equal "name='#{quoted_bambi_and_thumper}'", Binary.sanitize_sql_array(["name='%s'", "Bambi\nand\nThumper".mb_chars]) end def test_sanitize_sql_array_handles_bind_variables - quoted_bambi = ActiveRecord::Base.connection.quote("Bambi") + quoted_bambi = ActiveRecord::Base.lease_connection.quote("Bambi") assert_equal "name=#{quoted_bambi}", Binary.sanitize_sql_array(["name=?", "Bambi"]) assert_equal "name=#{quoted_bambi}", Binary.sanitize_sql_array(["name=?", "Bambi".mb_chars]) - quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper") + quoted_bambi_and_thumper = ActiveRecord::Base.lease_connection.quote("Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi_and_thumper}", Binary.sanitize_sql_array(["name=?", "Bambi\nand\nThumper"]) assert_equal "name=#{quoted_bambi_and_thumper}", Binary.sanitize_sql_array(["name=?", "Bambi\nand\nThumper".mb_chars]) end def test_sanitize_sql_array_handles_named_bind_variables - quoted_bambi = ActiveRecord::Base.connection.quote("Bambi") + quoted_bambi = ActiveRecord::Base.lease_connection.quote("Bambi") assert_equal "name=#{quoted_bambi}", Binary.sanitize_sql_array(["name=:name", name: "Bambi"]) if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) assert_equal "name=#{quoted_bambi} AND id='1'", Binary.sanitize_sql_array(["name=:name AND id=:id", name: "Bambi", id: 1]) @@ -37,7 +37,7 @@ def test_sanitize_sql_array_handles_named_bind_variables assert_equal "name=#{quoted_bambi} AND id=1", Binary.sanitize_sql_array(["name=:name AND id=:id", name: "Bambi", id: 1]) end - quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper") + quoted_bambi_and_thumper = ActiveRecord::Base.lease_connection.quote("Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi_and_thumper}", Binary.sanitize_sql_array(["name=:name", name: "Bambi\nand\nThumper"]) assert_equal "name=#{quoted_bambi_and_thumper} AND name2=#{quoted_bambi_and_thumper}", Binary.sanitize_sql_array(["name=:name AND name2=:name", name: "Bambi\nand\nThumper"]) end @@ -91,7 +91,7 @@ def self.search_as_method(term) } end - query = if searchable_post.connection.prepared_statements + query = if searchable_post.lease_connection.prepared_statements if current_adapter?(:PostgreSQLAdapter) /title LIKE \$1/ else @@ -158,7 +158,7 @@ def each(&b) end def test_bind_enumerable - quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')}) + quoted_abc = %(#{ActiveRecord::Base.lease_connection.quote('a')},#{ActiveRecord::Base.lease_connection.quote('b')},#{ActiveRecord::Base.lease_connection.quote('c')}) if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) assert_equal "'1','2','3'", bind("?", [1, 2, 3]) @@ -190,14 +190,14 @@ def test_bind_enumerable end def test_bind_empty_enumerable - quoted_nil = ActiveRecord::Base.connection.quote(nil) + quoted_nil = ActiveRecord::Base.lease_connection.quote(nil) assert_equal quoted_nil, bind("?", []) assert_equal " in (#{quoted_nil})", bind(" in (?)", []) assert_equal "foo in (#{quoted_nil})", bind("foo in (?)", []) end def test_bind_range - quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')}) + quoted_abc = %(#{ActiveRecord::Base.lease_connection.quote('a')},#{ActiveRecord::Base.lease_connection.quote('b')},#{ActiveRecord::Base.lease_connection.quote('c')}) if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) assert_equal "'0'", bind("?", 0..0) assert_equal "'1','2','3'", bind("?", 1..3) @@ -209,19 +209,19 @@ def test_bind_range end def test_bind_empty_range - quoted_nil = ActiveRecord::Base.connection.quote(nil) + quoted_nil = ActiveRecord::Base.lease_connection.quote(nil) assert_equal quoted_nil, bind("?", 0...0) assert_equal quoted_nil, bind("?", "a"..."a") end def test_bind_empty_string - quoted_empty = ActiveRecord::Base.connection.quote("") + quoted_empty = ActiveRecord::Base.lease_connection.quote("") assert_equal quoted_empty, bind("?", "") end def test_bind_chars - quoted_bambi = ActiveRecord::Base.connection.quote("Bambi") - quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper") + quoted_bambi = ActiveRecord::Base.lease_connection.quote("Bambi") + quoted_bambi_and_thumper = ActiveRecord::Base.lease_connection.quote("Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi}", bind("name=?", "Bambi") assert_equal "name=#{quoted_bambi_and_thumper}", bind("name=?", "Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi}", bind("name=?", "Bambi".mb_chars) @@ -231,7 +231,7 @@ def test_bind_chars def test_named_bind_with_postgresql_type_casts l = Proc.new { bind(":a::integer '2009-01-01'::date", a: "10") } assert_nothing_raised(&l) - assert_equal "#{ActiveRecord::Base.connection.quote('10')}::integer '2009-01-01'::date", l.call + assert_equal "#{ActiveRecord::Base.lease_connection.quote('10')}::integer '2009-01-01'::date", l.call end def test_named_bind_with_literal_colons diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 9eb0031409..fb62350f19 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -20,7 +20,7 @@ def standard_dump def test_dump_schema_information_with_empty_versions @schema_migration.delete_all_versions - schema_info = ActiveRecord::Base.connection.dump_schema_information + schema_info = ActiveRecord::Base.lease_connection.dump_schema_information assert_no_match(/INSERT INTO/, schema_info) end @@ -30,9 +30,9 @@ def test_dump_schema_information_outputs_lexically_reverse_ordered_versions_rega @schema_migration.create_version(v) end - schema_info = ActiveRecord::Base.connection.dump_schema_information + schema_info = ActiveRecord::Base.lease_connection.dump_schema_information expected = <<~STR - INSERT INTO #{ActiveRecord::Base.connection.quote_table_name("schema_migrations")} (version) VALUES + INSERT INTO #{ActiveRecord::Base.lease_connection.quote_table_name("schema_migrations")} (version) VALUES ('20100301010101'), ('20100201010101'), ('20100101010101'); @@ -170,12 +170,12 @@ def test_schema_dump_with_regexp_ignored_table def test_schema_dumps_index_columns_in_right_order index_definition = dump_table_schema("companies").split(/\n/).grep(/t\.index.*company_index/).first.strip if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - if ActiveRecord::Base.connection.supports_index_sort_order? + if ActiveRecord::Base.lease_connection.supports_index_sort_order? assert_equal 't.index ["firm_id", "type", "rating"], name: "company_index", length: { type: 10 }, order: { rating: :desc }', index_definition else assert_equal 't.index ["firm_id", "type", "rating"], name: "company_index", length: { type: 10 }', index_definition end - elsif ActiveRecord::Base.connection.supports_index_sort_order? + elsif ActiveRecord::Base.lease_connection.supports_index_sort_order? assert_equal 't.index ["firm_id", "type", "rating"], name: "company_index", order: { rating: :desc }', index_definition else assert_equal 't.index ["firm_id", "type", "rating"], name: "company_index"', index_definition @@ -184,7 +184,7 @@ def test_schema_dumps_index_columns_in_right_order def test_schema_dumps_partial_indices index_definition = dump_table_schema("companies").split(/\n/).grep(/t\.index.*company_partial_index/).first.strip - if ActiveRecord::Base.connection.supports_partial_index? + if ActiveRecord::Base.lease_connection.supports_partial_index? assert_equal 't.index ["firm_id", "type"], name: "company_partial_index", where: "(rating > 10)"', index_definition else assert_equal 't.index ["firm_id", "type"], name: "company_partial_index"', index_definition @@ -202,7 +202,7 @@ def test_schema_dumps_nulls_not_distinct def test_schema_dumps_index_sort_order index_definition = dump_table_schema("companies").split(/\n/).grep(/t\.index.*_name_and_rating/).first.strip - if ActiveRecord::Base.connection.supports_index_sort_order? + if ActiveRecord::Base.lease_connection.supports_index_sort_order? assert_equal 't.index ["name", "rating"], name: "index_companies_on_name_and_rating", order: :desc', index_definition else assert_equal 't.index ["name", "rating"], name: "index_companies_on_name_and_rating"', index_definition @@ -218,7 +218,7 @@ def test_schema_dumps_index_length end end - if ActiveRecord::Base.connection.supports_check_constraints? + if ActiveRecord::Base.lease_connection.supports_check_constraints? def test_schema_dumps_check_constraints constraint_definition = dump_table_schema("products").split(/\n/).grep(/t.check_constraint.*products_price_check/).first.strip if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) @@ -229,7 +229,7 @@ def test_schema_dumps_check_constraints end end - if ActiveRecord::Base.connection.supports_exclusion_constraints? + if ActiveRecord::Base.lease_connection.supports_exclusion_constraints? def test_schema_dumps_exclusion_constraints output = dump_table_schema("test_exclusion_constraints") constraint_definitions = output.split(/\n/).grep(/test_exclusion_constraints_.*_overlap/) @@ -241,7 +241,7 @@ def test_schema_dumps_exclusion_constraints end end - if ActiveRecord::Base.connection.supports_unique_constraints? + if ActiveRecord::Base.lease_connection.supports_unique_constraints? def test_schema_dumps_unique_constraints output = dump_table_schema("test_unique_constraints") constraint_definitions = output.split(/\n/).grep(/t\.unique_constraint/) @@ -293,7 +293,7 @@ def test_schema_dump_aliased_types assert_match %r{t\.decimal\s+"numeric_number"}, output end - if ActiveRecord::Base.connection.supports_expression_index? + if ActiveRecord::Base.lease_connection.supports_expression_index? def test_schema_dump_expression_indices index_definition = dump_table_schema("companies").split(/\n/).grep(/t\.index.*company_expression_index/).first.strip index_definition.sub!(/, name: "company_expression_index"\z/, "") @@ -389,7 +389,7 @@ def test_schema_dump_oid_type end def test_schema_dump_includes_extensions - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.stub(:extensions, ["hstore"]) do output = dump_all_table_schema(/./) @@ -405,7 +405,7 @@ def test_schema_dump_includes_extensions end def test_schema_dump_includes_extensions_in_alphabetic_order - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.stub(:extensions, ["hstore", "uuid-ossp", "xml2"]) do output = dump_all_table_schema(/./) @@ -444,7 +444,7 @@ def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_ assert_match %r{create_table "string_key_objects", id: false}, output end - if ActiveRecord::Base.connection.supports_foreign_keys? + if ActiveRecord::Base.lease_connection.supports_foreign_keys? def test_foreign_keys_are_dumped_at_the_bottom_to_circumvent_dependency_issues output = standard_dump assert_match(/^\s+add_foreign_key "fk_test_has_fk"[^\n]+\n\s+add_foreign_key "lessons_students"/, output) @@ -506,7 +506,7 @@ def test_schema_dump_with_table_name_prefix_and_suffix assert_no_match %r{create_table "schema_migrations"}, output assert_no_match %r{create_table "ar_internal_metadata"}, output - if ActiveRecord::Base.connection.supports_foreign_keys? + if ActiveRecord::Base.lease_connection.supports_foreign_keys? assert_no_match %r{add_foreign_key "foo_.+_bar"}, output assert_no_match %r{add_foreign_key "[^"]+", "foo_.+_bar"}, output end @@ -533,7 +533,7 @@ def test_schema_dump_with_table_name_prefix_and_suffix_regexp_escape assert_no_match %r{create_table "schema_migrations"}, output assert_no_match %r{create_table "ar_internal_metadata"}, output - if ActiveRecord::Base.connection.supports_foreign_keys? + if ActiveRecord::Base.lease_connection.supports_foreign_keys? assert_no_match %r{add_foreign_key "foo\$.+\$bar"}, output assert_no_match %r{add_foreign_key "[^"]+", "foo\$.+\$bar"}, output end @@ -888,7 +888,7 @@ class SchemaDumperDefaultsTest < ActiveRecord::TestCase include SchemaDumpingHelper setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.create_table :dump_defaults, force: true do |t| t.string :string_with_default, default: "Hello!" t.date :date_with_default, default: "2014-06-05" diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb index 4ab62ed86c..f67bc83f31 100644 --- a/activerecord/test/cases/scoping/default_scoping_test.rb +++ b/activerecord/test/cases/scoping/default_scoping_test.rb @@ -705,8 +705,8 @@ def test_sti_conditions_are_not_carried_in_default_scope end def test_with_abstract_class_scope_should_be_executed_in_correct_context - vegetarian_pattern = /#{Regexp.escape(Lion.connection.quote_table_name("lions.is_vegetarian"))}/i - gender_pattern = /#{Regexp.escape(Lion.connection.quote_table_name("lions.gender"))}/i + vegetarian_pattern = /#{Regexp.escape(Lion.lease_connection.quote_table_name("lions.is_vegetarian"))}/i + gender_pattern = /#{Regexp.escape(Lion.lease_connection.quote_table_name("lions.gender"))}/i assert_match vegetarian_pattern, Lion.all.to_sql assert_match gender_pattern, Lion.female.to_sql @@ -721,7 +721,7 @@ def test_default_scoping_with_threads 2.times do Thread.new { assert_includes DeveloperOrderedBySalary.all.to_sql, "salary DESC" - DeveloperOrderedBySalary.connection.close + DeveloperOrderedBySalary.lease_connection.close }.join end end @@ -738,13 +738,13 @@ def test_default_scope_is_threadsafe threads << Thread.new do Thread.current[:default_scope_delay] = -> { barrier_1.wait; barrier_2.wait } assert_equal 1, ThreadsafeDeveloper.all.to_a.count - ThreadsafeDeveloper.connection.close + ThreadsafeDeveloper.lease_connection.close end threads << Thread.new do Thread.current[:default_scope_delay] = -> { barrier_2.wait } barrier_1.wait assert_equal 1, ThreadsafeDeveloper.all.to_a.count - ThreadsafeDeveloper.connection.close + ThreadsafeDeveloper.lease_connection.close end threads.each(&:join) ensure diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index 5cf8fe2732..f5a1a6163a 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -133,7 +133,7 @@ def test_json_read_legacy_null # Force a row to have a JSON "null" instead of a database NULL (this is how # null values are saved on 4.1 and before) - id = Topic.connection.insert "INSERT INTO topics (content) VALUES('null')" + id = Topic.lease_connection.insert "INSERT INTO topics (content) VALUES('null')" t = Topic.find(id) assert_nil t.content @@ -143,7 +143,7 @@ def test_json_read_db_null Topic.serialize :content, coder: JSON # Force a row to have a database NULL instead of a JSON "null" - id = Topic.connection.insert "INSERT INTO topics (content) VALUES(NULL)" + id = Topic.lease_connection.insert "INSERT INTO topics (content) VALUES(NULL)" t = Topic.find(id) assert_nil t.content diff --git a/activerecord/test/cases/statement_cache_test.rb b/activerecord/test/cases/statement_cache_test.rb index cf071a049a..7262833cd7 100644 --- a/activerecord/test/cases/statement_cache_test.rb +++ b/activerecord/test/cases/statement_cache_test.rb @@ -6,24 +6,25 @@ require "models/molecule" require "models/numeric_data" require "models/electron" +require "models/clothing_item" module ActiveRecord class StatementCacheTest < ActiveRecord::TestCase def setup - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection end def test_statement_cache Book.create(name: "my book") Book.create(name: "my other book") - cache = StatementCache.create(Book.connection) do |params| + cache = StatementCache.create(ClothingItem.lease_connection) do |params| Book.where(name: params.bind) end - b = cache.execute([ "my book" ], Book.connection) + b = cache.execute([ "my book" ], ClothingItem.lease_connection) assert_equal "my book", b[0].name - b = cache.execute([ "my other book" ], Book.connection) + b = cache.execute([ "my other book" ], ClothingItem.lease_connection) assert_equal "my other book", b[0].name end @@ -31,13 +32,13 @@ def test_statement_cache_id b1 = Book.create(name: "my book") b2 = Book.create(name: "my other book") - cache = StatementCache.create(Book.connection) do |params| + cache = StatementCache.create(ClothingItem.lease_connection) do |params| Book.where(id: params.bind) end - b = cache.execute([ b1.id ], Book.connection) + b = cache.execute([ b1.id ], ClothingItem.lease_connection) assert_equal b1.name, b[0].name - b = cache.execute([ b2.id ], Book.connection) + b = cache.execute([ b2.id ], ClothingItem.lease_connection) assert_equal b2.name, b[0].name end @@ -52,18 +53,18 @@ def test_find_or_create_by end def test_statement_cache_with_simple_statement - cache = ActiveRecord::StatementCache.create(Book.connection) do |params| + cache = ActiveRecord::StatementCache.create(ClothingItem.lease_connection) do |params| Book.where(name: "my book").where("author_id > 3") end Book.create(name: "my book", author_id: 4) - books = cache.execute([], Book.connection) + books = cache.execute([], ClothingItem.lease_connection) assert_equal "my book", books[0].name end def test_statement_cache_with_complex_statement - cache = ActiveRecord::StatementCache.create(Book.connection) do |params| + cache = ActiveRecord::StatementCache.create(ClothingItem.lease_connection) do |params| Liquid.joins(molecules: :electrons).where("molecules.name" => "dioxane", "electrons.name" => "lepton") end @@ -71,7 +72,7 @@ def test_statement_cache_with_complex_statement molecule = salty.molecules.create(name: "dioxane") molecule.electrons.create(name: "lepton") - liquids = cache.execute([], Book.connection) + liquids = cache.execute([], ClothingItem.lease_connection) assert_equal "salty", liquids[0].name end @@ -81,7 +82,7 @@ def test_statement_cache_with_strictly_cast_attribute end def test_statement_cache_values_differ - cache = ActiveRecord::StatementCache.create(Book.connection) do |params| + cache = ActiveRecord::StatementCache.create(ClothingItem.lease_connection) do |params| Book.where(name: "my book") end @@ -89,13 +90,13 @@ def test_statement_cache_values_differ Book.create(name: "my book") end - first_books = cache.execute([], Book.connection) + first_books = cache.execute([], ClothingItem.lease_connection) 3.times do Book.create(name: "my book") end - additional_books = cache.execute([], Book.connection) + additional_books = cache.execute([], ClothingItem.lease_connection) assert_not_equal first_books, additional_books end @@ -104,7 +105,7 @@ def test_unprepared_statements_dont_share_a_cache_with_prepared_statements Book.create(name: "my other book") book = Book.find_by(name: "my book") - other_book = Book.connection.unprepared_statement do + other_book = Book.lease_connection.unprepared_statement do Book.find_by(name: "my other book") end diff --git a/activerecord/test/cases/statement_invalid_test.rb b/activerecord/test/cases/statement_invalid_test.rb index 9045a3c682..b3316ddfa9 100644 --- a/activerecord/test/cases/statement_invalid_test.rb +++ b/activerecord/test/cases/statement_invalid_test.rb @@ -20,8 +20,8 @@ def error_number test "message contains no sql" do sql = Book.where(author_id: 96, cover: "hard").to_sql error = assert_raises(ActiveRecord::StatementInvalid) do - Book.connection.send(:log, sql, Book.name) do - Book.connection.send(:with_raw_connection) do + Book.lease_connection.send(:log, sql, Book.name) do + Book.lease_connection.send(:with_raw_connection) do raise MockDatabaseError end end @@ -33,8 +33,8 @@ def error_number sql = Book.where(author_id: 96, cover: "hard").to_sql binds = [Minitest::Mock.new, Minitest::Mock.new] error = assert_raises(ActiveRecord::StatementInvalid) do - Book.connection.send(:log, sql, Book.name, binds) do - Book.connection.send(:with_raw_connection) do + Book.lease_connection.send(:log, sql, Book.name, binds) do + Book.lease_connection.send(:with_raw_connection) do raise MockDatabaseError end end diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb index c30455aee8..b4cdc91ab1 100644 --- a/activerecord/test/cases/store_test.rb +++ b/activerecord/test/cases/store_test.rb @@ -164,7 +164,7 @@ class StoreTest < ActiveRecord::TestCase end test "saved changes tracking for accessors with json column" do - if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) && ActiveRecord::Base.connection.mariadb? + if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) && ActiveRecord::Base.lease_connection.mariadb? skip "MariaDB doesn't support JSON store_accessor" end @john.enable_friend_requests = true diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb index 9a9c669b1c..003ac83cd2 100644 --- a/activerecord/test/cases/tasks/database_tasks_test.rb +++ b/activerecord/test/cases/tasks/database_tasks_test.rb @@ -290,7 +290,7 @@ def test_dump_schema_cache ActiveRecord::Tasks::DatabaseTasks.stub(:db_dir, dir) do path = File.join(dir, "schema_cache.yml") assert_not File.file?(path) - ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.connection, path) + ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.lease_connection, path) assert File.file?(path) end end @@ -1131,11 +1131,11 @@ class DatabaseTasksMigrationTestCase < ActiveRecord::TestCase # Use a memory db here to avoid having to rollback at the end setup do migrations_path = [MIGRATIONS_ROOT, folder_name].join("/") - file = ActiveRecord::Base.connection.raw_connection.filename + file = ActiveRecord::Base.lease_connection.raw_connection.filename @conn = ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:", migrations_paths: migrations_path source_db = SQLite3::Database.new file - dest_db = ActiveRecord::Base.connection.raw_connection + dest_db = ActiveRecord::Base.lease_connection.raw_connection backup = SQLite3::Backup.new(dest_db, "main", source_db, "main") backup.step(-1) backup.finish diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb index 23c1bfe6c1..7d9669f1f8 100644 --- a/activerecord/test/cases/test_case.rb +++ b/activerecord/test/cases/test_case.rb @@ -170,13 +170,13 @@ def with_db_warnings_action(action, warnings_to_ignore = []) ActiveRecord.db_warnings_action = action ActiveRecord.db_warnings_ignore = warnings_to_ignore - ActiveRecord::Base.connection.disconnect! # Disconnect from the db so that we reconfigure the connection + ActiveRecord::Base.lease_connection.disconnect! # Disconnect from the db so that we reconfigure the connection yield ensure ActiveRecord.db_warnings_action = @original_db_warnings_action ActiveRecord.db_warnings_ignore = original_db_warnings_ignore - ActiveRecord::Base.connection.disconnect! + ActiveRecord::Base.lease_connection.disconnect! end def reset_callbacks(klass, kind) diff --git a/activerecord/test/cases/time_precision_test.rb b/activerecord/test/cases/time_precision_test.rb index 8e7298dd33..7ffec3397f 100644 --- a/activerecord/test/cases/time_precision_test.rb +++ b/activerecord/test/cases/time_precision_test.rb @@ -11,7 +11,7 @@ class TimePrecisionTest < ActiveRecord::TestCase class Foo < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection Foo.reset_column_information end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index ab3c9c43da..95d08a1cd8 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -588,7 +588,7 @@ class TimestampAttributePost < ActiveRecord::Base end def test_do_not_write_timestamps_on_save_if_they_are_not_attributes - with_example_table ActiveRecord::Base.connection, "timestamp_attribute_posts", "id integer primary key" do + with_example_table ActiveRecord::Base.lease_connection, "timestamp_attribute_posts", "id integer primary key" do post = TimestampAttributePost.new(id: 1) post.save! # should not try to assign and persist created_at, updated_at assert_nil post.created_at @@ -597,13 +597,13 @@ def test_do_not_write_timestamps_on_save_if_they_are_not_attributes end def test_index_is_created_for_both_timestamps - ActiveRecord::Base.connection.create_table(:foos, force: true) do |t| + ActiveRecord::Base.lease_connection.create_table(:foos, force: true) do |t| t.timestamps null: true, index: true end - indexes = ActiveRecord::Base.connection.indexes("foos") + indexes = ActiveRecord::Base.lease_connection.indexes("foos") assert_equal ["created_at", "updated_at"], indexes.flat_map(&:columns).sort ensure - ActiveRecord::Base.connection.drop_table(:foos) + ActiveRecord::Base.lease_connection.drop_table(:foos) end end diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 9b21c3b8c5..86f4b6e08b 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -100,13 +100,13 @@ def setup def test_before_commit_exception_should_pop_transaction_stack @first.before_commit_block { raise "better pop this txn from the stack!" } - original_txn = @first.class.connection.current_transaction + original_txn = @first.class.lease_connection.current_transaction begin @first.save! fail rescue - assert_equal original_txn, @first.class.connection.current_transaction + assert_equal original_txn, @first.class.lease_connection.current_transaction end end @@ -314,7 +314,7 @@ def test_call_after_rollback_when_commit_fails assert_raises RuntimeError do @first.transaction do - tx = @first.class.connection.transaction_manager.current_transaction + tx = @first.class.lease_connection.transaction_manager.current_transaction def tx.commit raise end diff --git a/activerecord/test/cases/transaction_instrumentation_test.rb b/activerecord/test/cases/transaction_instrumentation_test.rb index 69633a47db..f9ffdc9e3f 100644 --- a/activerecord/test/cases/transaction_instrumentation_test.rb +++ b/activerecord/test/cases/transaction_instrumentation_test.rb @@ -233,8 +233,8 @@ def test_reconnecting_after_materialized_transaction_starts_new_event events << event end Topic.transaction do - Topic.connection.materialize_transactions - Topic.connection.reconnect!(restore_transactions: true) + Topic.lease_connection.materialize_transactions + Topic.lease_connection.reconnect!(restore_transactions: true) end assert_equal 2, events.count @@ -305,7 +305,7 @@ def test_transaction_instrumentation_on_failed_commit error = Class.new(StandardError) assert_raises error do - ActiveRecord::Base.connection.stub(:commit_db_transaction, -> (*) { raise error }) do + ActiveRecord::Base.lease_connection.stub(:commit_db_transaction, -> (*) { raise error }) do ActiveRecord::Base.transaction do topic.update(title: "Ruby on Rails") end @@ -329,7 +329,7 @@ def test_transaction_instrumentation_on_failed_rollback error = Class.new(StandardError) assert_raises error do - ActiveRecord::Base.connection.stub(:rollback_db_transaction, -> (*) { raise error }) do + ActiveRecord::Base.lease_connection.stub(:rollback_db_transaction, -> (*) { raise error }) do ActiveRecord::Base.transaction do topic.update(title: "Ruby on Rails") raise ActiveRecord::Rollback @@ -351,7 +351,7 @@ def test_transaction_instrumentation_on_failed_rollback_when_unmaterialized error = Class.new(StandardError) assert_raises error do # Stubbing this method simulates an error that occurs when the transaction is still unmaterilized. - Topic.connection.transaction_manager.stub(:rollback_transaction, -> (*) { raise error }) do + Topic.lease_connection.transaction_manager.stub(:rollback_transaction, -> (*) { raise error }) do Topic.transaction do raise ActiveRecord::Rollback end diff --git a/activerecord/test/cases/transaction_isolation_test.rb b/activerecord/test/cases/transaction_isolation_test.rb index 7aaeb677ac..bfe36a70e5 100644 --- a/activerecord/test/cases/transaction_isolation_test.rb +++ b/activerecord/test/cases/transaction_isolation_test.rb @@ -3,7 +3,7 @@ require "cases/helper" class TransactionIsolationUnsupportedTest < ActiveRecord::TestCase - unless ActiveRecord::Base.connection.supports_transaction_isolation? && !current_adapter?(:SQLite3Adapter) + unless ActiveRecord::Base.lease_connection.supports_transaction_isolation? && !current_adapter?(:SQLite3Adapter) self.use_transactional_tests = false class Tag < ActiveRecord::Base @@ -11,14 +11,14 @@ class Tag < ActiveRecord::Base test "setting the isolation level raises an error" do assert_raises(ActiveRecord::TransactionIsolationError) do - Tag.transaction(isolation: :serializable) { Tag.connection.materialize_transactions } + Tag.transaction(isolation: :serializable) { Tag.lease_connection.materialize_transactions } end end end end class TransactionIsolationTest < ActiveRecord::TestCase - if ActiveRecord::Base.connection.supports_transaction_isolation? && !current_adapter?(:SQLite3Adapter) + if ActiveRecord::Base.lease_connection.supports_transaction_isolation? && !current_adapter?(:SQLite3Adapter) self.use_transactional_tests = false class Tag < ActiveRecord::Base @@ -38,7 +38,7 @@ class Tag2 < ActiveRecord::Base # It is impossible to properly test read uncommitted. The SQL standard only # specifies what must not happen at a certain level, not what must happen. At # the read uncommitted level, there is nothing that must not happen. - if ActiveRecord::Base.connection.transaction_isolation_levels.include?(:read_uncommitted) + if ActiveRecord::Base.lease_connection.transaction_isolation_levels.include?(:read_uncommitted) test "read uncommitted" do Tag.transaction(isolation: :read_uncommitted) do assert_equal 0, Tag.count @@ -63,7 +63,7 @@ class Tag2 < ActiveRecord::Base end # We are testing that a nonrepeatable read does not happen - if ActiveRecord::Base.connection.transaction_isolation_levels.include?(:repeatable_read) + if ActiveRecord::Base.lease_connection.transaction_isolation_levels.include?(:repeatable_read) test "repeatable read" do tag = Tag.create(name: "jon") diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index a5efefdfb2..3b0b756167 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -43,9 +43,9 @@ def test_transaction_does_not_apply_default_scope def test_rollback_dirty_changes_even_with_raise_during_rollback_removes_from_pool topic = topics(:fifth) - connection = Topic.connection + connection = Topic.lease_connection - Topic.connection.class_eval do + Topic.lease_connection.class_eval do alias :real_exec_rollback_db_transaction :exec_rollback_db_transaction define_method(:exec_rollback_db_transaction) do raise @@ -66,7 +66,7 @@ def test_rollback_dirty_changes_even_with_raise_during_rollback_removes_from_poo def test_rollback_dirty_changes_even_with_raise_during_rollback_doesnt_commit_transaction topic = topics(:fifth) - Topic.connection.class_eval do + Topic.lease_connection.class_eval do alias :real_exec_rollback_db_transaction :exec_rollback_db_transaction define_method(:exec_rollback_db_transaction) do raise @@ -90,10 +90,10 @@ def test_rollback_dirty_changes_even_with_raise_during_rollback_doesnt_commit_tr end def test_connection_removed_from_pool_when_commit_raises_and_rollback_raises - connection = Topic.connection + connection = Topic.lease_connection # Update commit_transaction to raise the first time it is called. - Topic.connection.transaction_manager.class_eval do + Topic.lease_connection.transaction_manager.class_eval do alias :real_commit_transaction :commit_transaction define_method(:commit_transaction) do raise "commit failed" @@ -101,7 +101,7 @@ def test_connection_removed_from_pool_when_commit_raises_and_rollback_raises end # Update rollback_transaction to raise. - Topic.connection.transaction_manager.class_eval do + Topic.lease_connection.transaction_manager.class_eval do alias :real_rollback_transaction :rollback_transaction define_method(:rollback_transaction) do |*_args| raise "rollback failed" @@ -124,12 +124,12 @@ def test_connection_removed_from_pool_when_commit_raises_and_rollback_raises end def test_connection_removed_from_pool_when_begin_raises_after_successfully_beginning_a_transaction - connection = Topic.connection + connection = Topic.lease_connection # Disable lazy transactions so that we will begin a transaction before attempting to write. connection.disable_lazy_transactions! # Update begin_db_transaction to successfully begin a transaction, then raise. - Topic.connection.class_eval do + Topic.lease_connection.class_eval do alias :real_begin_db_transaction :begin_db_transaction define_method(:begin_db_transaction) do |*_args| raise "begin failed" @@ -151,7 +151,7 @@ def test_connection_removed_from_pool_when_thread_killed_in_begin_after_successf queue = Queue.new connection = nil thread = Thread.new do - connection = Topic.connection + connection = Topic.lease_connection # Disable lazy transactions so that we will begin a transaction before attempting to write. connection.disable_lazy_transactions! @@ -299,7 +299,7 @@ def test_add_to_null_transaction def test_successful_with_return_outside_inner_transaction committed = false - Topic.connection.class_eval do + Topic.lease_connection.class_eval do alias :real_commit_db_transaction :commit_db_transaction define_method(:commit_db_transaction) do committed = true @@ -315,7 +315,7 @@ def test_successful_with_return_outside_inner_transaction assert_predicate Topic.find(1), :approved?, "First should have been approved" assert_not_predicate Topic.find(2), :approved?, "Second should have been unapproved" ensure - Topic.connection.class_eval do + Topic.lease_connection.class_eval do remove_method :commit_db_transaction alias :commit_db_transaction :real_commit_db_transaction rescue nil end @@ -393,7 +393,7 @@ def test_return_from_transaction_commits def test_number_of_transactions_in_commit num = nil - Topic.connection.class_eval do + Topic.lease_connection.class_eval do alias :real_commit_db_transaction :commit_db_transaction define_method(:commit_db_transaction) do num = transaction_manager.open_transactions @@ -408,7 +408,7 @@ def test_number_of_transactions_in_commit assert_equal 0, num ensure - Topic.connection.class_eval do + Topic.lease_connection.class_eval do remove_method :commit_db_transaction alias :commit_db_transaction :real_commit_db_transaction rescue nil end @@ -735,7 +735,7 @@ def test_force_savepoint_in_nested_transaction assert_predicate @first.reload, :approved? assert_not_predicate @second.reload, :approved? - end if Topic.connection.supports_savepoints? + end if Topic.lease_connection.supports_savepoints? def test_force_savepoint_on_instance @first.transaction do @@ -756,7 +756,7 @@ def test_force_savepoint_on_instance assert_predicate @first.reload, :approved? assert_not_predicate @second.reload, :approved? - end if Topic.connection.supports_savepoints? + end if Topic.lease_connection.supports_savepoints? def test_no_savepoint_in_nested_transaction_without_force Topic.transaction do @@ -777,7 +777,7 @@ def test_no_savepoint_in_nested_transaction_without_force assert_not_predicate @first.reload, :approved? assert_not_predicate @second.reload, :approved? - end if Topic.connection.supports_savepoints? + end if Topic.lease_connection.supports_savepoints? def test_many_savepoints Topic.transaction do @@ -821,36 +821,36 @@ def test_many_savepoints assert_equal "One", @one assert_equal "Two", @two assert_equal "Three", @three - end if Topic.connection.supports_savepoints? + end if Topic.lease_connection.supports_savepoints? def test_using_named_savepoints Topic.transaction do @first.approved = true @first.save! - Topic.connection.create_savepoint("first") + Topic.lease_connection.create_savepoint("first") @first.approved = false @first.save! - Topic.connection.rollback_to_savepoint("first") + Topic.lease_connection.rollback_to_savepoint("first") assert_predicate @first.reload, :approved? @first.approved = false @first.save! - Topic.connection.release_savepoint("first") + Topic.lease_connection.release_savepoint("first") assert_not_predicate @first.reload, :approved? end - end if Topic.connection.supports_savepoints? + end if Topic.lease_connection.supports_savepoints? def test_releasing_named_savepoints Topic.transaction do - Topic.connection.materialize_transactions + Topic.lease_connection.materialize_transactions - Topic.connection.create_savepoint("another") - Topic.connection.release_savepoint("another") + Topic.lease_connection.create_savepoint("another") + Topic.lease_connection.release_savepoint("another") # The savepoint is now gone and we can't remove it again. assert_raises(ActiveRecord::StatementInvalid) do - Topic.connection.release_savepoint("another") + Topic.lease_connection.release_savepoint("another") end end end @@ -859,33 +859,33 @@ def test_savepoints_name Topic.transaction do Topic.delete_all # Dirty the transaction to force a savepoint below - assert_nil Topic.connection.current_savepoint_name - assert_nil Topic.connection.current_transaction.savepoint_name + assert_nil Topic.lease_connection.current_savepoint_name + assert_nil Topic.lease_connection.current_transaction.savepoint_name Topic.transaction(requires_new: true) do Topic.delete_all # Dirty the transaction to force a savepoint below - assert_equal "active_record_1", Topic.connection.current_savepoint_name - assert_equal "active_record_1", Topic.connection.current_transaction.savepoint_name + assert_equal "active_record_1", Topic.lease_connection.current_savepoint_name + assert_equal "active_record_1", Topic.lease_connection.current_transaction.savepoint_name Topic.transaction(requires_new: true) do - assert_equal "active_record_2", Topic.connection.current_savepoint_name - assert_equal "active_record_2", Topic.connection.current_transaction.savepoint_name + assert_equal "active_record_2", Topic.lease_connection.current_savepoint_name + assert_equal "active_record_2", Topic.lease_connection.current_transaction.savepoint_name end - assert_equal "active_record_1", Topic.connection.current_savepoint_name - assert_equal "active_record_1", Topic.connection.current_transaction.savepoint_name + assert_equal "active_record_1", Topic.lease_connection.current_savepoint_name + assert_equal "active_record_1", Topic.lease_connection.current_transaction.savepoint_name end end end def test_rollback_when_commit_raises - assert_called(Topic.connection, :begin_db_transaction) do - Topic.connection.stub(:commit_db_transaction, -> { raise("OH NOES") }) do - assert_called(Topic.connection, :rollback_db_transaction) do + assert_called(Topic.lease_connection, :begin_db_transaction) do + Topic.lease_connection.stub(:commit_db_transaction, -> { raise("OH NOES") }) do + assert_called(Topic.lease_connection, :rollback_db_transaction) do e = assert_raise RuntimeError do Topic.transaction do - Topic.connection.materialize_transactions + Topic.lease_connection.materialize_transactions end end assert_equal "OH NOES", e.message @@ -1177,27 +1177,27 @@ def test_sqlite_add_column_in_transaction assert_nothing_raised do Topic.reset_column_information - Topic.connection.add_column("topics", "stuff", :string) + Topic.lease_connection.add_column("topics", "stuff", :string) assert_includes Topic.column_names, "stuff" Topic.reset_column_information - Topic.connection.remove_column("topics", "stuff") + Topic.lease_connection.remove_column("topics", "stuff") assert_not_includes Topic.column_names, "stuff" end - if Topic.connection.supports_ddl_transactions? + if Topic.lease_connection.supports_ddl_transactions? assert_nothing_raised do - Topic.transaction { Topic.connection.add_column("topics", "stuff", :string) } + Topic.transaction { Topic.lease_connection.add_column("topics", "stuff", :string) } end else Topic.transaction do - assert_raise(ActiveRecord::StatementInvalid) { Topic.connection.add_column("topics", "stuff", :string) } + assert_raise(ActiveRecord::StatementInvalid) { Topic.lease_connection.add_column("topics", "stuff", :string) } raise ActiveRecord::Rollback end end ensure begin - Topic.connection.remove_column("topics", "stuff") + Topic.lease_connection.remove_column("topics", "stuff") rescue ensure Topic.reset_column_information @@ -1205,7 +1205,7 @@ def test_sqlite_add_column_in_transaction end def test_transactions_state_from_rollback - connection = Topic.connection + connection = Topic.lease_connection transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction assert_predicate transaction, :open? @@ -1219,7 +1219,7 @@ def test_transactions_state_from_rollback end def test_transactions_state_from_commit - connection = Topic.connection + connection = Topic.lease_connection transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction assert_predicate transaction, :open? @@ -1233,7 +1233,7 @@ def test_transactions_state_from_commit end def test_mark_transaction_state_as_committed - connection = Topic.connection + connection = Topic.lease_connection transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction transaction.rollback @@ -1242,7 +1242,7 @@ def test_mark_transaction_state_as_committed end def test_mark_transaction_state_as_rolledback - connection = Topic.connection + connection = Topic.lease_connection transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction transaction.commit @@ -1251,7 +1251,7 @@ def test_mark_transaction_state_as_rolledback end def test_mark_transaction_state_as_nil - connection = Topic.connection + connection = Topic.lease_connection transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction transaction.commit @@ -1260,7 +1260,7 @@ def test_mark_transaction_state_as_nil end def test_transaction_rollback_with_primarykeyless_tables - connection = ActiveRecord::Base.connection + connection = ActiveRecord::Base.lease_connection connection.create_table(:transaction_without_primary_keys, force: true, id: false) do |t| t.integer :thing_id end @@ -1328,7 +1328,7 @@ def test_nested_transactions_skip_excess_savepoints end def test_nested_transactions_after_disable_lazy_transactions - Topic.connection.disable_lazy_transactions! + Topic.lease_connection.disable_lazy_transactions! actual_queries = capture_sql(include_schema: true) do # RealTransaction (begin..commit) @@ -1363,7 +1363,7 @@ def test_nested_transactions_after_disable_lazy_transactions end end - if ActiveRecord::Base.connection.prepared_statements + if ActiveRecord::Base.lease_connection.prepared_statements def test_prepared_statement_materializes_transaction Topic.first @@ -1391,12 +1391,12 @@ def test_raising_does_not_materialize_transaction def test_accessing_raw_connection_materializes_transaction assert_queries_match(/BEGIN|COMMIT/i, include_schema: true) do - Topic.transaction { Topic.connection.raw_connection } + Topic.transaction { Topic.lease_connection.raw_connection } end end def test_accessing_raw_connection_disables_lazy_transactions - Topic.connection.raw_connection + Topic.lease_connection.raw_connection assert_queries_match(/BEGIN|COMMIT/i, include_schema: true) do Topic.transaction { } @@ -1416,7 +1416,7 @@ def test_checking_in_connection_reenables_lazy_transactions def test_transactions_can_be_manually_materialized assert_queries_match(/BEGIN|COMMIT/i, include_schema: true) do Topic.transaction do - Topic.connection.materialize_transactions + Topic.lease_connection.materialize_transactions end end end @@ -1470,10 +1470,10 @@ def test_no_automatic_savepoint_for_inner_transaction assert_not_predicate @first.reload, :approved? end -end if Topic.connection.supports_savepoints? +end if Topic.lease_connection.supports_savepoints? class ConcurrentTransactionTest < ActiveRecord::TestCase - if ActiveRecord::Base.connection.supports_transaction_isolation? && !current_adapter?(:SQLite3Adapter) + if ActiveRecord::Base.lease_connection.supports_transaction_isolation? && !current_adapter?(:SQLite3Adapter) self.use_transactional_tests = false fixtures :topics, :developers @@ -1489,7 +1489,7 @@ def test_transaction_per_thread topic.approved = !topic.approved? assert topic.save! end - Topic.connection.close + Topic.lease_connection.close end end @@ -1524,7 +1524,7 @@ def test_transaction_isolation__read_committed dev = Developer.find(1) assert_equal original_salary, dev.salary end - Developer.connection.close + Developer.lease_connection.close end end @@ -1537,7 +1537,7 @@ def test_transaction_isolation__read_committed assert_equal original_salary, Developer.find(1).salary end end - Developer.connection.close + Developer.lease_connection.close end threads.each(&:join) diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index 5494a5fa4b..14a4d63f57 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -9,7 +9,7 @@ class TestUnconnectedAdapter < ActiveRecord::TestCase self.use_transactional_tests = false def setup - @underlying = ActiveRecord::Base.connection + @underlying = ActiveRecord::Base.lease_connection @connection_name = ActiveRecord::Base.remove_connection # Clear out connection info from other pids (like a fork parent) too diff --git a/activerecord/test/cases/unsafe_raw_sql_test.rb b/activerecord/test/cases/unsafe_raw_sql_test.rb index 8367fb9ba9..b0f0291928 100644 --- a/activerecord/test/cases/unsafe_raw_sql_test.rb +++ b/activerecord/test/cases/unsafe_raw_sql_test.rb @@ -74,7 +74,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "order: allows quoted table and column names" do ids_expected = Post.order(Arel.sql("title")).pluck(:id) - quoted_title = Post.connection.quote_table_name("posts.title") + quoted_title = Post.lease_connection.quote_table_name("posts.title") ids = Post.order(quoted_title).pluck(:id) assert_equal ids_expected, ids @@ -172,7 +172,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase "Mysql2" => "utf8mb4_bin", "Trilogy" => "utf8mb4_bin", "SQLite" => "binary" - }[ActiveRecord::Base.connection.adapter_name] + }[ActiveRecord::Base.lease_connection.adapter_name] ids_expected = Post.order(Arel.sql(%Q'author_id, title COLLATE "#{collation_name}" DESC')).pluck(:id) @@ -256,7 +256,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "pluck: allows quoted table and column names" do titles_expected = Post.pluck(Arel.sql("title")) - quoted_title = Post.connection.quote_table_name("posts.title") + quoted_title = Post.lease_connection.quote_table_name("posts.title") titles = Post.pluck(quoted_title) assert_equal titles_expected, titles diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 6e5e8ccd33..5c4bccda56 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -638,7 +638,7 @@ class UniquenessValidationWithIndexTest < ActiveRecord::TestCase self.use_transactional_tests = false def setup - @connection = Topic.connection + @connection = Topic.lease_connection @connection.schema_cache.clear! Topic.delete_all Event.delete_all diff --git a/activerecord/test/cases/view_test.rb b/activerecord/test/cases/view_test.rb index 64562d5607..1219f740a0 100644 --- a/activerecord/test/cases/view_test.rb +++ b/activerecord/test/cases/view_test.rb @@ -19,7 +19,7 @@ class Ebook < ActiveRecord::Base def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection create_view "ebooks'", <<~SQL SELECT id, name, cover, status FROM books WHERE format = 'ebook' SQL @@ -85,7 +85,7 @@ def quote_table_name(name) end end -if ActiveRecord::Base.connection.supports_views? +if ActiveRecord::Base.lease_connection.supports_views? class ViewWithPrimaryKeyTest < ActiveRecord::TestCase include ViewBehavior @@ -108,7 +108,7 @@ class ViewWithoutPrimaryKeyTest < ActiveRecord::TestCase class Paperback < ActiveRecord::Base; end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute <<~SQL CREATE VIEW paperbacks AS SELECT name, status FROM books WHERE format = 'paperback' @@ -169,7 +169,7 @@ class PrintedBook < ActiveRecord::Base end setup do - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @connection.execute <<~SQL CREATE VIEW printed_books AS SELECT id, name, status, format FROM books WHERE format = 'paperback' @@ -212,9 +212,9 @@ def test_update_record_to_fail_view_conditions end end # end of `if current_adapter?(:Mysql2Adapter, :TrilogyAdapter, :PostgreSQLAdapter, :SQLServerAdapter)` end -end # end of `if ActiveRecord::Base.connection.supports_views?` +end # end of `if ActiveRecord::Base.lease_connection.supports_views?` -if ActiveRecord::Base.connection.supports_materialized_views? +if ActiveRecord::Base.lease_connection.supports_materialized_views? class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase include ViewBehavior diff --git a/activerecord/test/models/bird.rb b/activerecord/test/models/bird.rb index 20af7c6122..cb9497e49b 100644 --- a/activerecord/test/models/bird.rb +++ b/activerecord/test/models/bird.rb @@ -8,7 +8,7 @@ class Bird < ActiveRecord::Base before_save do # force materialize_transactions - self.class.connection.materialize_transactions + self.class.lease_connection.materialize_transactions end attr_accessor :cancel_save_from_callback diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb index d5f6f00691..e286916eb6 100644 --- a/activerecord/test/models/contact.rb +++ b/activerecord/test/models/contact.rb @@ -5,8 +5,8 @@ def self.extended(base) base.class_eval do establish_connection(adapter: "fake") - connection.data_sources = [table_name] - connection.primary_keys = { + lease_connection.data_sources = [table_name] + lease_connection.primary_keys = { table_name => "id" } @@ -27,7 +27,7 @@ def self.extended(base) # mock out self.columns so no pesky db is needed for these tests def column(name, sql_type = nil, options = {}) - connection.merge_column(table_name, name, sql_type, options) + lease_connection.merge_column(table_name, name, sql_type, options) end end diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb index dabeeaec3b..171d529899 100644 --- a/activerecord/test/models/parrot.rb +++ b/activerecord/test/models/parrot.rb @@ -22,8 +22,10 @@ def increment_updated_count end def self.delete_all(*) - connection.delete("DELETE FROM parrots_pirates") - connection.delete("DELETE FROM parrots_treasures") + with_connection do |c| + c.delete("DELETE FROM parrots_pirates") + c.delete("DELETE FROM parrots_treasures") + end super end end diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 9bb5a90f79..05638a7c34 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -341,8 +341,8 @@ def adapter_class Post.adapter_class end - def connection - Post.connection + def lease_connection + Post.lease_connection end def table_name diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb index a233af926a..13d64b061d 100644 --- a/activerecord/test/schema/postgresql_specific_schema.rb +++ b/activerecord/test/schema/postgresql_specific_schema.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true ActiveRecord::Schema.define do - ActiveRecord::TestCase.enable_extension!("uuid-ossp", ActiveRecord::Base.connection) - ActiveRecord::TestCase.enable_extension!("pgcrypto", ActiveRecord::Base.connection) if ActiveRecord::Base.connection.supports_pgcrypto_uuid? + ActiveRecord::TestCase.enable_extension!("uuid-ossp", ActiveRecord::Base.lease_connection) + ActiveRecord::TestCase.enable_extension!("pgcrypto", ActiveRecord::Base.lease_connection) if ActiveRecord::Base.lease_connection.supports_pgcrypto_uuid? uuid_default = connection.supports_pgcrypto_uuid? ? {} : { default: "uuid_generate_v4()" } diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 8c44978076..27dcd40253 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -1486,13 +1486,13 @@ end end -if ActiveRecord::Base.connection.supports_insert_returning? && !ActiveRecord::TestCase.current_adapter?(:SQLite3Adapter) - ActiveRecord::Base.connection.create_table :pk_autopopulated_by_a_trigger_records, force: true, id: false do |t| +if ActiveRecord::Base.lease_connection.supports_insert_returning? && !ActiveRecord::TestCase.current_adapter?(:SQLite3Adapter) + ActiveRecord::Base.lease_connection.create_table :pk_autopopulated_by_a_trigger_records, force: true, id: false do |t| t.integer :id, null: false end if ActiveRecord::TestCase.current_adapter?(:PostgreSQLAdapter) - ActiveRecord::Base.connection.execute( + ActiveRecord::Base.lease_connection.execute( <<-SQL CREATE OR REPLACE FUNCTION populate_column() RETURNS TRIGGER AS $$ @@ -1512,7 +1512,7 @@ SQL ) elsif ActiveRecord::TestCase.current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - ActiveRecord::Base.connection.execute( + ActiveRecord::Base.lease_connection.execute( <<-SQL CREATE TRIGGER before_insert_trigger BEFORE INSERT ON pk_autopopulated_by_a_trigger_records @@ -1523,22 +1523,22 @@ end end -Course.connection.create_table :courses, force: true do |t| +Course.lease_connection.create_table :courses, force: true do |t| t.column :name, :string, null: false t.column :college_id, :integer, index: true end -College.connection.create_table :colleges, force: true do |t| +College.lease_connection.create_table :colleges, force: true do |t| t.column :name, :string, null: false end -Professor.connection.create_table :professors, force: true do |t| +Professor.lease_connection.create_table :professors, force: true do |t| t.column :name, :string, null: false end -Professor.connection.create_table :courses_professors, id: false, force: true do |t| +Professor.lease_connection.create_table :courses_professors, id: false, force: true do |t| t.references :course t.references :professor end -OtherDog.connection.create_table :dogs, force: true +OtherDog.lease_connection.create_table :dogs, force: true diff --git a/activerecord/test/support/adapter_helper.rb b/activerecord/test/support/adapter_helper.rb index 1628b9d8da..7af07ebee0 100644 --- a/activerecord/test/support/adapter_helper.rb +++ b/activerecord/test/support/adapter_helper.rb @@ -4,7 +4,7 @@ module AdapterHelper def current_adapter?(*types) types.any? do |type| ActiveRecord::ConnectionAdapters.const_defined?(type) && - ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type)) + ActiveRecord::Base.lease_connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type)) end end @@ -14,14 +14,14 @@ def in_memory_db? end def mysql_enforcing_gtid_consistency? - current_adapter?(:Mysql2Adapter, :TrilogyAdapter) && "ON" == ActiveRecord::Base.connection.show_variable("enforce_gtid_consistency") + current_adapter?(:Mysql2Adapter, :TrilogyAdapter) && "ON" == ActiveRecord::Base.lease_connection.show_variable("enforce_gtid_consistency") end def supports_default_expression? if current_adapter?(:PostgreSQLAdapter) true elsif current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection (conn.mariadb? && conn.database_version >= "10.2.1") || (!conn.mariadb? && conn.database_version >= "8.0.13") end @@ -29,7 +29,7 @@ def supports_default_expression? def supports_non_unique_constraint_name? if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.mariadb? else false @@ -38,7 +38,7 @@ def supports_non_unique_constraint_name? def supports_text_column_with_default? if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) - conn = ActiveRecord::Base.connection + conn = ActiveRecord::Base.lease_connection conn.mariadb? && conn.database_version >= "10.2.1" else true @@ -62,7 +62,7 @@ def supports_text_column_with_default? supports_virtual_columns? ].each do |method_name| define_method method_name do - ActiveRecord::Base.connection.public_send(method_name) + ActiveRecord::Base.lease_connection.public_send(method_name) end end diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb index 614b9b80f5..e986909604 100644 --- a/activerecord/test/support/connection.rb +++ b/activerecord/test/support/connection.rb @@ -32,7 +32,7 @@ def self.connect ActiveRecord::Base.establish_connection :arunit ARUnit2Model.establish_connection :arunit2 - arunit_adapter = ActiveRecord::Base.connection.pool.db_config.adapter + arunit_adapter = ActiveRecord::Base.lease_connection.pool.db_config.adapter unless connection_name.include?(arunit_adapter) raise ArgumentError, "The connection name did not match the adapter name. Connection name is '#{connection_name}' and the adapter name is '#{arunit_adapter}'." diff --git a/activerecord/test/support/load_schema_helper.rb b/activerecord/test/support/load_schema_helper.rb index f3ec1f9eff..a35fbba53e 100644 --- a/activerecord/test/support/load_schema_helper.rb +++ b/activerecord/test/support/load_schema_helper.rb @@ -6,7 +6,7 @@ def load_schema original_stdout = $stdout $stdout = StringIO.new - adapter_name = ActiveRecord::Base.connection.adapter_name.downcase + adapter_name = ActiveRecord::Base.lease_connection.adapter_name.downcase adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb" load SCHEMA_ROOT + "/schema.rb" diff --git a/activerecord/test/support/schema_dumping_helper.rb b/activerecord/test/support/schema_dumping_helper.rb index e1e602f166..cd95d2ce61 100644 --- a/activerecord/test/support/schema_dumping_helper.rb +++ b/activerecord/test/support/schema_dumping_helper.rb @@ -4,7 +4,9 @@ module SchemaDumpingHelper def dump_table_schema(*tables) pool = ActiveRecord::Base.connection_pool old_ignore_tables = ActiveRecord::SchemaDumper.ignore_tables - ActiveRecord::SchemaDumper.ignore_tables = pool.connection.data_sources - tables + pool.with_connection do |connection| + ActiveRecord::SchemaDumper.ignore_tables = connection.data_sources - tables + end output, = capture_io do ActiveRecord::SchemaDumper.dump(pool) diff --git a/activestorage/test/migrations_test.rb b/activestorage/test/migrations_test.rb index eb2dc9b62f..7e4ad4bdee 100644 --- a/activestorage/test/migrations_test.rb +++ b/activestorage/test/migrations_test.rb @@ -8,7 +8,7 @@ class ActiveStorage::MigrationsTest < ActiveSupport::TestCase @original_verbose = ActiveRecord::Migration.verbose ActiveRecord::Migration.verbose = false - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Base.lease_connection @original_options = Rails.configuration.generators.options.deep_dup end diff --git a/activestorage/test/models/attachment_test.rb b/activestorage/test/models/attachment_test.rb index c891d33108..ca37d15549 100644 --- a/activestorage/test/models/attachment_test.rb +++ b/activestorage/test/models/attachment_test.rb @@ -174,11 +174,11 @@ def assert_blob_identified_before_owner_validated(owner, blob, content_type) end def assert_blob_identified_outside_transaction(blob, &block) - baseline_transaction_depth = ActiveRecord::Base.connection.open_transactions + baseline_transaction_depth = ActiveRecord::Base.lease_connection.open_transactions max_transaction_depth = -1 track_transaction_depth = ->(*) do - max_transaction_depth = [ActiveRecord::Base.connection.open_transactions, max_transaction_depth].max + max_transaction_depth = [ActiveRecord::Base.lease_connection.open_transactions, max_transaction_depth].max end blob.stub(:identify_without_saving, track_transaction_depth, &block) diff --git a/railties/lib/rails/commands/dbconsole/dbconsole_command.rb b/railties/lib/rails/commands/dbconsole/dbconsole_command.rb index e3e7a32455..8ec6499ce7 100644 --- a/railties/lib/rails/commands/dbconsole/dbconsole_command.rb +++ b/railties/lib/rails/commands/dbconsole/dbconsole_command.rb @@ -67,7 +67,7 @@ def find_cmd_and_exec(commands, *args) # :doc: Rails::DBConsole#find_cmd_and_exec is deprecated and will be removed in Rails 7.2. Please use find_cmd_and_exec on the connection adapter class instead. MSG - ActiveRecord::Base.connection.find_cmd_and_exec(commands, *args) + ActiveRecord::Base.lease_connection.find_cmd_and_exec(commands, *args) end end diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 7df0c0f0a3..6846cdc629 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -72,7 +72,7 @@ def dangerous_name?(name) def valid_type?(type) DEFAULT_TYPES.include?(type.to_s) || !defined?(ActiveRecord::Base) || - ActiveRecord::Base.connection.valid_type?(type) + ActiveRecord::Base.lease_connection.valid_type?(type) end def valid_index_type?(index_type) diff --git a/railties/test/application/bin_setup_test.rb b/railties/test/application/bin_setup_test.rb index 89ce2337ce..26f6f019a4 100644 --- a/railties/test/application/bin_setup_test.rb +++ b/railties/test/application/bin_setup_test.rb @@ -13,7 +13,7 @@ def test_bin_setup Dir.chdir(app_path) do rails "generate", "model", "article" - list_tables = lambda { rails("runner", "p ActiveRecord::Base.connection.tables").strip } + list_tables = lambda { rails("runner", "p ActiveRecord::Base.lease_connection.tables").strip } File.write("log/test.log", "zomg!") assert_equal "[]", list_tables.call diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index fdcfac69ef..968e9d5c26 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -2926,9 +2926,9 @@ class Post < ActiveRecord::Base assert_equal false, ActiveRecord::ConnectionAdapters::SQLite3Adapter.strict_strings_by_default - Post.connection.create_table :posts + Post.lease_connection.create_table :posts assert_nothing_raised do - Post.connection.add_index :posts, :non_existent + Post.lease_connection.add_index :posts, :non_existent end end @@ -2963,9 +2963,9 @@ class Post < ActiveRecord::Base assert_equal true, ActiveRecord::ConnectionAdapters::SQLite3Adapter.strict_strings_by_default - Post.connection.create_table :posts + Post.lease_connection.create_table :posts error = assert_raises(StandardError) do - Post.connection.add_index :posts, :non_existent + Post.lease_connection.add_index :posts, :non_existent end assert_match(/no such column: non_existent/, error.message) end @@ -4751,8 +4751,8 @@ class Foo < ApplicationRecord app "development" - assert_equal "potato", ActiveRecord::Base.connection.pool.db_config.adapter - assert_equal "SQLite", ActiveRecord::Base.connection.adapter_name + assert_equal "potato", ActiveRecord::Base.lease_connection.pool.db_config.adapter + assert_equal "SQLite", ActiveRecord::Base.lease_connection.adapter_name end private diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index bd55f5263e..a079a390c2 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -109,7 +109,7 @@ def setup class Post < ActiveRecord::Base end CODE - system "#{app_path}/bin/rails runner 'Post.connection.create_table :posts'" + system "#{app_path}/bin/rails runner 'Post.lease_connection.create_table :posts'" @primary, @replica = PTY.open end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 8b5c9007bb..28f9d9b190 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -238,7 +238,7 @@ def show assert ActiveRecord::Base.schema_cache.data_sources("posts") end ensure - ActiveRecord::Base.connection.drop_table("posts", if_exists: true) # force drop posts table for test. + ActiveRecord::Base.lease_connection.drop_table("posts", if_exists: true) # force drop posts table for test. end test "expire schema cache dump" do @@ -273,7 +273,7 @@ def show app("development") assert_raises ActiveRecord::ConnectionNotEstablished do - ActiveRecord::Base.connection.execute("SELECT 1") + ActiveRecord::Base.lease_connection.execute("SELECT 1") end _, error = capture_io do @@ -318,7 +318,7 @@ def show assert ActiveRecord::Base.connection_pool.schema_reflection.data_sources(:__unused__, "posts") assert_raises ActiveRecord::ConnectionNotEstablished do - ActiveRecord::Base.connection.execute("SELECT 1") + ActiveRecord::Base.lease_connection.execute("SELECT 1") end end end @@ -345,7 +345,7 @@ def show orig_database_url = ENV.delete("DATABASE_URL") orig_rails_env, Rails.env = Rails.env, "development" ActiveRecord::Base.establish_connection - assert ActiveRecord::Base.connection + assert ActiveRecord::Base.lease_connection assert_match(/#{ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, name: "primary").database}/, ActiveRecord::Base.connection_db_config.database) db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, name: "primary") assert_match(/#{db_config.database}/, ActiveRecord::Base.connection_db_config.database) @@ -362,7 +362,7 @@ def show database_url_db_name = "db/database_url_db.sqlite3" ENV["DATABASE_URL"] = "sqlite3:#{database_url_db_name}" ActiveRecord::Base.establish_connection - assert ActiveRecord::Base.connection + assert ActiveRecord::Base.lease_connection assert_match(/#{database_url_db_name}/, ActiveRecord::Base.connection_db_config.database) ensure ActiveRecord::Base.remove_connection @@ -372,7 +372,7 @@ def show test "connections checked out during initialization are returned to the pool" do app_file "config/initializers/active_record.rb", <<-RUBY - ActiveRecord::Base.connection + ActiveRecord::Base.lease_connection RUBY app("development") assert_not_predicate ActiveRecord::Base.connection_pool, :active_connection? diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index d23e54b012..360b550698 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -494,10 +494,10 @@ def test_initialize_can_be_called_at_any_time class OmgController < ActionController::Metal ActiveSupport.run_load_hooks(:action_controller, self) def show - if ActiveRecord::Base.connection.query_cache_enabled + if ActiveRecord::Base.lease_connection.query_cache_enabled self.response_body = ["Query cache is enabled."] else - self.response_body = ["Expected ActiveRecord::Base.connection.query_cache_enabled to be true"] + self.response_body = ["Expected ActiveRecord::Base.lease_connection.query_cache_enabled to be true"] end end end @@ -527,10 +527,10 @@ def show class OmgController < ActionController::Metal ActiveSupport.run_load_hooks(:action_controller, self) def show - if ActiveRecord::Base.connection.query_cache_enabled + if ActiveRecord::Base.lease_connection.query_cache_enabled self.response_body = ["Query cache is enabled."] else - self.response_body = ["Expected ActiveRecord::Base.connection.query_cache_enabled to be true"] + self.response_body = ["Expected ActiveRecord::Base.lease_connection.query_cache_enabled to be true"] end end end diff --git a/railties/test/application/query_logs_test.rb b/railties/test/application/query_logs_test.rb index 604f0d5f3f..add764ebba 100644 --- a/railties/test/application/query_logs_test.rb +++ b/railties/test/application/query_logs_test.rb @@ -31,7 +31,7 @@ def dynamic_content app_file "app/controllers/name_spaced/users_controller.rb", <<-RUBY class NameSpaced::UsersController < ApplicationController def index - render inline: ActiveRecord::QueryLogs.call("", ActiveRecord::Base.connection) + render inline: ActiveRecord::QueryLogs.call("", ActiveRecord::Base.lease_connection) end end RUBY @@ -39,7 +39,7 @@ def index app_file "app/jobs/user_job.rb", <<-RUBY class UserJob < ActiveJob::Base def perform - ActiveRecord::QueryLogs.call("", ActiveRecord::Base.connection) + ActiveRecord::QueryLogs.call("", ActiveRecord::Base.lease_connection) end def dynamic_content @@ -89,8 +89,8 @@ def app test "controller and job tags are defined by default" do add_to_config "config.active_record.query_log_tags_enabled = true" app_file "config/initializers/active_record.rb", <<-RUBY - raise "Expected prepared_statements to be enabled" unless ActiveRecord::Base.connection.prepared_statements - ActiveRecord::Base.connection.execute("SELECT 1") + raise "Expected prepared_statements to be enabled" unless ActiveRecord::Base.lease_connection.prepared_statements + ActiveRecord::Base.lease_connection.execute("SELECT 1") RUBY boot_app diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index fbbb334a33..a55a8a3920 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -284,18 +284,18 @@ def with_bad_permissions require "#{app_path}/config/environment" Book.create!(title: "Remote") assert_equal 1, Book.count - schema_migrations = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") - internal_metadata = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + schema_migrations = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + internal_metadata = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") rails "db:truncate_all" assert_equal( schema_migrations, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") ) assert_equal( internal_metadata, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") ) assert_equal 0, Book.count end @@ -309,23 +309,23 @@ def with_bad_permissions require "#{app_path}/config/environment" Book.create!(title: "Remote") assert_equal 1, Book.count - schema_migrations = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") - internal_metadata = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") - books = ActiveRecord::Base.connection.execute("SELECT * from \"books\"") + schema_migrations = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + internal_metadata = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + books = ActiveRecord::Base.lease_connection.execute("SELECT * from \"books\"") output = rails("db:truncate_all", allow_failure: true) assert_match(/ActiveRecord::ProtectedEnvironmentError/, output) assert_equal( schema_migrations, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") ) assert_equal( internal_metadata, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") ) assert_equal 1, Book.count - assert_equal(books, ActiveRecord::Base.connection.execute("SELECT * from \"books\"")) + assert_equal(books, ActiveRecord::Base.lease_connection.execute("SELECT * from \"books\"")) end end end @@ -471,7 +471,7 @@ def db_schema_cache_dump rails "db:drop", "db:create" rails "runner", <<~RUBY - ActiveRecord::Base.connection.create_table(:books) do |t| + ActiveRecord::Base.lease_connection.create_table(:books) do |t| t.integer :pages t.virtual :pages_plus_1, type: :integer, as: "pages + 1", stored: true end @@ -533,7 +533,7 @@ def db_fixtures_load(expected_database) end test "db:schema:load does not purge the existing database" do - rails "runner", "ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }" + rails "runner", "ActiveRecord::Base.lease_connection.create_table(:posts) {|t| t.string :title }" app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: 20140423102712) do @@ -541,7 +541,7 @@ def db_fixtures_load(expected_database) end RUBY - list_tables = lambda { rails("runner", "p ActiveRecord::Base.connection.tables").strip } + list_tables = lambda { rails("runner", "p ActiveRecord::Base.lease_connection.tables").strip } assert_equal '["posts"]', list_tables[] rails "db:schema:load" @@ -575,10 +575,10 @@ def db_fixtures_load(expected_database) rails "db:schema:load" - tables = rails("runner", "p ActiveRecord::Base.connection.tables").strip + tables = rails("runner", "p ActiveRecord::Base.lease_connection.tables").strip assert_match(/"geese"/, tables) - columns = rails("runner", "p ActiveRecord::Base.connection.columns('geese').map(&:name)").strip + columns = rails("runner", "p ActiveRecord::Base.lease_connection.columns('geese').map(&:name)").strip assert_equal '["gooseid", "name"]', columns end @@ -658,8 +658,8 @@ def db_fixtures_load(expected_database) require "#{app_path}/config/environment" Book.create!(title: "Remote") assert_equal 1, Book.count - schema_migrations = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") - internal_metadata = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + schema_migrations = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + internal_metadata = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") app_file "db/seeds.rb", <<-RUBY Book.create!(title: "Rework") @@ -670,11 +670,11 @@ def db_fixtures_load(expected_database) assert_equal( schema_migrations, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") ) assert_equal( internal_metadata, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") ) assert_equal 2, Book.count assert_not_predicate Book.where(title: "Remote"), :exists? @@ -691,9 +691,9 @@ def db_fixtures_load(expected_database) require "#{app_path}/config/environment" Book.create!(title: "Remote") assert_equal 1, Book.count - schema_migrations = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") - internal_metadata = ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") - books = ActiveRecord::Base.connection.execute("SELECT * from \"books\"") + schema_migrations = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + internal_metadata = ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + books = ActiveRecord::Base.lease_connection.execute("SELECT * from \"books\"") app_file "db/seeds.rb", <<-RUBY Book.create!(title: "Rework") @@ -704,14 +704,14 @@ def db_fixtures_load(expected_database) assert_equal( schema_migrations, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.schema_migrations_table_name}\"") ) assert_equal( internal_metadata, - ActiveRecord::Base.connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") + ActiveRecord::Base.lease_connection.execute("SELECT * from \"#{ActiveRecord::Base.internal_metadata_table_name}\"") ) assert_equal 1, Book.count - assert_equal(books, ActiveRecord::Base.connection.execute("SELECT * from \"books\"")) + assert_equal(books, ActiveRecord::Base.lease_connection.execute("SELECT * from \"books\"")) assert_not_predicate Book.where(title: "Rework"), :exists? end end @@ -736,7 +736,7 @@ def db_fixtures_load(expected_database) assert_match(/create_table "books"/, schema) assert_match(/create_table "recipes"/, schema) - tables = rails("runner", "p ActiveRecord::Base.connection.tables.sort").strip + tables = rails("runner", "p ActiveRecord::Base.lease_connection.tables.sort").strip assert_equal('["ar_internal_metadata", "books", "recipes", "schema_migrations"]', tables) test_environment = lambda { rails("runner", "-e", "test", "puts ActiveRecord::Base.connection_pool.internal_metadata[:environment]").strip } @@ -754,7 +754,7 @@ def db_fixtures_load(expected_database) output = rails("db:prepare") assert_no_match(/CreateBooks: migrated/, output) - tables = rails("runner", "p ActiveRecord::Base.connection.tables.sort").strip + tables = rails("runner", "p ActiveRecord::Base.lease_connection.tables.sort").strip assert_equal('["ar_internal_metadata", "books", "schema_migrations"]', tables) end @@ -778,7 +778,7 @@ def db_fixtures_load(expected_database) Dir.chdir(app_path) do db_name = use_postgresql rails "db:drop", "db:create" - rails "runner", "ActiveRecord::Base.connection.drop_database(:#{db_name}_test)" + rails "runner", "ActiveRecord::Base.lease_connection.drop_database(:#{db_name}_test)" output = rails("db:prepare") assert_match(%r{Created database '#{db_name}_test'}, output) diff --git a/railties/test/application/rake/multi_dbs_test.rb b/railties/test/application/rake/multi_dbs_test.rb index 0635a69232..a97df2b57c 100644 --- a/railties/test/application/rake/multi_dbs_test.rb +++ b/railties/test/application/rake/multi_dbs_test.rb @@ -108,8 +108,8 @@ def db_migrate_and_schema_dump_and_load(schema_format = "ruby") rails "db:schema:load" - ar_tables = lambda { rails("runner", "p ActiveRecord::Base.connection.tables").strip } - animals_tables = lambda { rails("runner", "p AnimalsBase.connection.tables").strip } + ar_tables = lambda { rails("runner", "p ActiveRecord::Base.lease_connection.tables").strip } + animals_tables = lambda { rails("runner", "p AnimalsBase.lease_connection.tables").strip } assert_equal '["schema_migrations", "ar_internal_metadata", "books"]', ar_tables[] assert_equal '["schema_migrations", "ar_internal_metadata", "dogs"]', animals_tables[] @@ -148,8 +148,8 @@ def db_migrate_and_schema_dump_and_load_one_database(database, schema_format) rails "db:schema:load:#{database}" - ar_tables = lambda { rails("runner", "p ActiveRecord::Base.connection.tables").strip } - animals_tables = lambda { rails("runner", "p AnimalsBase.connection.tables").strip } + ar_tables = lambda { rails("runner", "p ActiveRecord::Base.lease_connection.tables").strip } + animals_tables = lambda { rails("runner", "p AnimalsBase.lease_connection.tables").strip } if database == "primary" assert_equal '["schema_migrations", "ar_internal_metadata", "books"]', ar_tables[] @@ -211,8 +211,8 @@ def db_test_prepare_name(name, schema_format) output = rails("db:test:prepare:#{name}", "--trace") assert_match(/Execute db:test:load_schema:#{name}/, output) - ar_tables = lambda { rails("runner", "-e", "test", "p ActiveRecord::Base.connection.tables").strip } - animals_tables = lambda { rails("runner", "-e", "test", "p AnimalsBase.connection.tables").strip } + ar_tables = lambda { rails("runner", "-e", "test", "p ActiveRecord::Base.lease_connection.tables").strip } + animals_tables = lambda { rails("runner", "-e", "test", "p AnimalsBase.lease_connection.tables").strip } if name == "primary" assert_equal ["schema_migrations", "ar_internal_metadata", "books"].sort, JSON.parse(ar_tables[]).sort @@ -937,7 +937,7 @@ class TwoMigration < ActiveRecord::Migration::Current assert_match(/Created database/, output) assert_equal 1, Dog.count ensure - Dog.connection.disconnect! + Dog.lease_connection.disconnect! rails "db:drop" rescue nil end end @@ -959,7 +959,7 @@ class TwoMigration < ActiveRecord::Migration::Current assert_equal 1, Dog.count ensure - Dog.connection.disconnect! + Dog.lease_connection.disconnect! rails "db:drop" rescue nil end end @@ -973,7 +973,7 @@ class TwoMigration < ActiveRecord::Migration::Current db_migrate_and_schema_dump_and_load app_file "db/seeds.rb", <<-RUBY - print Book.connection.pool.db_config.database + print Book.lease_connection.pool.db_config.database RUBY output = rails("db:seed") @@ -1261,7 +1261,7 @@ class TwoMigration < ActiveRecord::Migration::Current YAML Dir.chdir(app_path) do - animals_db_exists = lambda { rails("runner", "puts !!(AnimalsBase.connection rescue false)").strip } + animals_db_exists = lambda { rails("runner", "puts !!(AnimalsBase.lease_connection rescue false)").strip } generate_models_for_animals diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index 91dc5b7154..30f92fbe98 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -277,12 +277,12 @@ class UserTest < ActiveSupport::TestCase app_file "lib/tasks/hooks.rake", <<-RUBY task :before_hook do - has_user_table = ActiveRecord::Base.connection.table_exists?('users') + has_user_table = ActiveRecord::Base.lease_connection.table_exists?('users') puts "before: " + has_user_table.to_s end task :after_hook do - has_user_table = ActiveRecord::Base.connection.table_exists?('users') + has_user_table = ActiveRecord::Base.lease_connection.table_exists?('users') puts "after: " + has_user_table.to_s end diff --git a/railties/test/json_params_parsing_test.rb b/railties/test/json_params_parsing_test.rb index 65ad9673ff..12f778366c 100644 --- a/railties/test/json_params_parsing_test.rb +++ b/railties/test/json_params_parsing_test.rb @@ -35,7 +35,7 @@ def self.name; "Foo"; end assert_nil app.call(make_env("t" => data)) end ensure - klass.connection.drop_table("foos") + klass.lease_connection.drop_table("foos") end private