rails/activerecord
eileencodes adb64db43d
Only remove connection for an existing pool if the config is different
Previously Rails would always remove the connection if it found a
matching class in the pool manager. Therefore if
`ActiveRecord::Base.establish_connection` was called with the same
config, each time it was called it would be clobbered, even though the
config hasn't changed and the existing connection is prefectly fine. As
far as I can tell from conversations and reading the history this
functionality was added for ActiveRecord tests to be able to clobber the
connection and use a new config, then re-establish the old connection.
Essentially outside Rake tasks and AR tests, this functionality doesn't
have a ton of value.

On top of not adding a ton of value, this has resulted in a few bugs. In
Rails 6.0 I made it so that if you established a connection on
`ApplicationRecord` Rails would treat that connection the same as
`ActiveRecord::Base.` The reason for this is that the Railtie
establishes a connection on boot to the first database, but then if
you're using multiple databases you're calling `connects_to` in your
`ApplicationRecord` or primary abstract class which essentially doubles
your connections to the same database. To avoid opening 2 connections to
the same database, Rails treats them the same.

However, because we have this code that removes existing connections,
when an application boots, `ApplicationRecord` will clobber the
connection that the Railtie established even though the connection
configs are the same.

This removal of the connection caused bugs in migrations that load up a
model connected to `ApplicationRecord` (ex `Post.first`) and then calls
`execute("SELECT 1")` (obviously a simplified example). When `execute`
runs the connection is different from the one opened to run the
migration and essentially it is lost when the `remove_connection` code
is called.

To fix this I've updated the code to only remove the connection if the
database config is different. Ultimately I'd like to remove this code
altogether but to do that we first need to stop using
`Base.establish_connection` in the rake tasks and tests. This will fix
the major bugs until I come up with a solution for the areas that
currently need to call `establish_connection` on Base.

The added benefit of this change is that if your app is calling
`establish_connection` multiple times with the same config, it is now
3x faster than the previous implementation because we can return the
found pool instead of setting it up again. To benchmark this I
duplicated the `establish_connection` method to use the new behavior
with a new name.

Benchmark script:

```ruby
require "active_record"
require "logger"
require "benchmark/ips"

config_hash = { "development" => { "primary" => { "adapter" => "mysql2", "username" => "rails", "database" => "activerecord_unittest"}}}
ActiveRecord::Base.configurations = config_hash

db_config = ActiveRecord::Base.configurations.configs_for(env_name: "development", name: "primary")

p "Same model same config"
ActiveRecord::Base.connected_to(role: :writing, prevent_writes: true) do
  Benchmark.ips do |x|
    x.report "establish_connection with remove" do
      ActiveRecord::Base.establish_connection(db_config)
    end

    x.report "establish_connection without remove" do
      ActiveRecord::Base.establish_connection_no_remove(db_config)
    end

    x.compare!
  end
end
```

Benchmark results:

```
Warming up --------------------------------------
establish_connection with remove
                         4.677k i/100ms
establish_connection without remove
                        19.501k i/100ms
Calculating -------------------------------------
establish_connection with remove
                         41.252k (±11.3%) i/s -    205.788k in   5.075525s
establish_connection without remove
                        179.205k (± 6.9%) i/s -    897.046k in   5.029742s

Comparison:
establish_connection without remove:   179205.1 i/s
establish_connection with remove:    41252.3 i/s - 4.34x  (± 0.00) slower
```

Other changes:

1) sqlite3 now disconnects and reconnects the connection when `purge` is
called. This is necessary now that a new connection isn't created
everyt time `establish_connection` is called. Without this change to
purge the new database is left in an inaccessible state causing a
readonly error from the sqlite3 client. This wasn't happening in mysql
or postgres because they were already reconnecting the db connection.
2) I added `remove_connection` to tests that use `ApplicationRecord`.
This is required because `ApplicationRecord` or any class that is a
`primary_abstract_class` will be treated the same as
`ActiveRecord::Base`. This is fine in applications because they are
shared connections, but in the AR test environment, we don't want those
connnections to stick around (we want AR::Base back).
3) In the async tests I removed 2 calls to `establish_connection`. These
were causing sqlite3 tests to leak the state of async_executor because
it's stored on the connection. I'm not sure why these were calling
`establish_connection` but it's not necessary and was leaking state when
now that we are no longer removing the connection.

Fixes: #41855
Fixes: #41876
Fixes: #42873
Fixes: #43004
2022-06-29 11:25:17 -04:00
..
bin Active Record bin/test command runs only its own adapter tests 2021-09-07 21:34:56 +09:00
examples
lib Only remove connection for an existing pool if the config is different 2022-06-29 11:25:17 -04:00
test Only remove connection for an existing pool if the config is different 2022-06-29 11:25:17 -04:00
.gitignore
activerecord.gemspec Fix gemspec 2021-11-15 21:06:21 +00:00
CHANGELOG.md Only remove connection for an existing pool if the config is different 2022-06-29 11:25:17 -04:00
MIT-LICENSE Bump license years to 2022 [ci-skip] 2022-01-01 15:22:15 +09:00
Rakefile dropdb if activerecord_unittest / activerecord_unittest2 exists 2022-05-30 20:12:35 +09:00
README.rdoc Start Rails 7.1 development 2021-12-07 15:52:30 +00:00
RUNNING_UNIT_TESTS.rdoc Update activerecord/RUNNING_UNIT_TESTS.rdoc 2021-04-01 15:02:15 +02:00

= Active Record -- Object-relational mapping in Rails

Active Record connects classes to relational database tables to establish an
almost zero-configuration persistence layer for applications. The library
provides a base class that, when subclassed, sets up a mapping between the new
class and an existing table in the database. In the context of an application,
these classes are commonly referred to as *models*. Models can also be
connected to other models; this is done by defining *associations*.

Active Record relies heavily on naming in that it uses class and association
names to establish mappings between respective database tables and foreign key
columns. Although these mappings can be defined explicitly, it's recommended
to follow naming conventions, especially when getting started with the
library.

You can read more about Active Record in the {Active Record Basics}[https://edgeguides.rubyonrails.org/active_record_basics.html] guide.

A short rundown of some of the major features:

* Automated mapping between classes and tables, attributes and columns.

   class Product < ActiveRecord::Base
   end

  {Learn more}[link:classes/ActiveRecord/Base.html]

The Product class is automatically mapped to the table named "products",
which might look like this:

   CREATE TABLE products (
     id bigint NOT NULL auto_increment,
     name varchar(255),
     PRIMARY KEY  (id)
   );

This would also define the following accessors: <tt>Product#name</tt> and
<tt>Product#name=(new_name)</tt>.


* Associations between objects defined by simple class methods.

   class Firm < ActiveRecord::Base
     has_many   :clients
     has_one    :account
     belongs_to :conglomerate
   end

  {Learn more}[link:classes/ActiveRecord/Associations/ClassMethods.html]


* Aggregations of value objects.

   class Account < ActiveRecord::Base
     composed_of :balance, class_name: 'Money',
                 mapping: %w(balance amount)
     composed_of :address,
                 mapping: [%w(address_street street), %w(address_city city)]
   end

  {Learn more}[link:classes/ActiveRecord/Aggregations/ClassMethods.html]


* Validation rules that can differ for new or existing objects.

    class Account < ActiveRecord::Base
      validates :subdomain, :name, :email_address, :password, presence: true
      validates :subdomain, uniqueness: true
      validates :terms_of_service, acceptance: true, on: :create
      validates :password, :email_address, confirmation: true, on: :create
    end

  {Learn more}[link:classes/ActiveRecord/Validations.html]


* Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.).

   class Person < ActiveRecord::Base
     before_destroy :invalidate_payment_plan
     # the `invalidate_payment_plan` method gets called just before Person#destroy
   end

  {Learn more}[link:classes/ActiveRecord/Callbacks.html]


* Inheritance hierarchies.

   class Company < ActiveRecord::Base; end
   class Firm < Company; end
   class Client < Company; end
   class PriorityClient < Client; end

  {Learn more}[link:classes/ActiveRecord/Base.html]


* Transactions.

    # Database transaction
    Account.transaction do
      david.withdrawal(100)
      mary.deposit(100)
    end

  {Learn more}[link:classes/ActiveRecord/Transactions/ClassMethods.html]


* Reflections on columns, associations, and aggregations.

    reflection = Firm.reflect_on_association(:clients)
    reflection.klass # => Client (class)
    Firm.columns # Returns an array of column descriptors for the firms table

  {Learn more}[link:classes/ActiveRecord/Reflection/ClassMethods.html]


* Database abstraction through simple adapters.

    # connect to SQLite3
    ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3')

    # connect to MySQL with authentication
    ActiveRecord::Base.establish_connection(
      adapter:  'mysql2',
      host:     'localhost',
      username: 'me',
      password: 'secret',
      database: 'activerecord'
    )

  {Learn more}[link:classes/ActiveRecord/Base.html] and read about the built-in support for
  MySQL[link:classes/ActiveRecord/ConnectionAdapters/Mysql2Adapter.html],
  PostgreSQL[link:classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html], and
  SQLite3[link:classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html].


* Logging support for Log4r[https://github.com/colbygk/log4r] and Logger[https://ruby-doc.org/stdlib/libdoc/logger/rdoc/].

    ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
    ActiveRecord::Base.logger = Log4r::Logger.new('Application Log')


* Database agnostic schema management with Migrations.

    class AddSystemSettings < ActiveRecord::Migration[7.1]
      def up
        create_table :system_settings do |t|
          t.string  :name
          t.string  :label
          t.text    :value
          t.string  :type
          t.integer :position
        end

        SystemSetting.create name: 'notice', label: 'Use notice?', value: 1
      end

      def down
        drop_table :system_settings
      end
    end

  {Learn more}[link:classes/ActiveRecord/Migration.html]


== Philosophy

Active Record is an implementation of the object-relational mapping (ORM)
pattern[https://www.martinfowler.com/eaaCatalog/activeRecord.html] by the same
name described by Martin Fowler:

  "An object that wraps a row in a database table or view,
  encapsulates the database access, and adds domain logic on that data."

Active Record attempts to provide a coherent wrapper as a solution for the inconvenience that is
object-relational mapping. The prime directive for this mapping has been to minimize
the amount of code needed to build a real-world domain model. This is made possible
by relying on a number of conventions that make it easy for Active Record to infer
complex relations and structures from a minimal amount of explicit direction.

Convention over Configuration:
* No XML files!
* Lots of reflection and run-time extension
* Magic is not inherently a bad word

Admit the Database:
* Lets you drop down to SQL for odd cases and performance
* Doesn't attempt to duplicate or replace data definitions


== Download and installation

The latest version of Active Record can be installed with RubyGems:

  $ gem install activerecord

Source code can be downloaded as part of the Rails project on GitHub:

* https://github.com/rails/rails/tree/main/activerecord


== License

Active Record is released under the MIT license:

* https://opensource.org/licenses/MIT


== Support

API documentation is at:

* https://api.rubyonrails.org

Bug reports for the Ruby on Rails project can be filed here:

* https://github.com/rails/rails/issues

Feature requests should be discussed on the rails-core mailing list here:

* https://discuss.rubyonrails.org/c/rubyonrails-core