Commit Graph

23780 Commits

Author SHA1 Message Date
Jean Boussier
92591ebd54
Merge pull request #51429 from fatkodima/fix-pg-include-indexes-with-keywords
Fix PostgreSQL `include` indexes with keyword column names
2024-04-12 23:00:00 +02:00
Yasuo Honda
7d17add290
Merge pull request #51550 from wynksaiddestroy/fix-custom-type-attribute-example
Avoid name collision with builtin postgresql money type in custom type example [ci skip]
2024-04-12 13:56:30 +09:00
Ngan Pham
39c7d9b1b1
Fix query_logs_test.rb 2024-04-11 16:36:14 -07:00
Ngan Pham
9186dfe2d0
Allow string keys for SQLCommenter 2024-04-11 12:47:11 -07:00
Fabian Winkler
46c9012196 Rename MoneyType to PriceType 2024-04-11 21:16:10 +02:00
Claire
85c7530a57 Arel: wrap SELECT statements in parentheses when generating SQL for UNION
This commit fixes generated SQL for `UNION` and `UNION ALL` involving `LIMIT`
or `ORDER BY` by wrapping `SELECT` statements appearing in an `UNION` or
`UNION ALL` in parentheses.
2024-04-11 17:55:41 +02:00
Jean Boussier
93df871020
Merge pull request #51540 from vahe/lazily_load_schema_cache-docs-cmment-cleanup
Remove misleading comment related to lazily_load_schema_cache and use_schema_cache_dump
2024-04-11 08:46:44 +02:00
Yasuo Honda
81cbca7569
Merge pull request #51531 from fatkodima/fix-sqlite-copy-virtual-columns
Fix copying virtual columns when altering a table in sqlite3
2024-04-11 08:18:52 +09:00
Vahe Khachikyan
9be9a8183d
Remove misleading comment related to lazily_load_schema_cache and use_schema_cache_dump 2024-04-10 13:19:37 -04:00
fatkodima
041de49399 Remove usage of OpenStruct 2024-04-09 21:35:08 +03:00
fatkodima
a457b121a0 Fix copying virtual columns when altering a table in sqlite3 2024-04-09 20:47:37 +03:00
Carlos Antonio da Silva
8feeab2338 Add missing ostruct require on AR test suite
Similar to 50515fb45f36dfad067adbdda9fee41fcb326ca9, make sure we
require `ostruct` where we use `OpenStruct`, to get the build back to
green, while we work to remove its usage on tests. (see #51510.)

Sample error:

```
Error:
ActiveRecord::Encryption::ConfigurableTest#test_installing_autofiltered_parameters_will_add_the_encrypted_attribute_as_a_filter_parameter_using_the_dot_notation:
NameError: uninitialized constant ActiveRecord::Encryption::ConfigurableTest::OpenStruct
    test/cases/encryption/configurable_test.rb:45:in `block in <class:ConfigurableTest>'
```
2024-04-09 13:56:02 -03:00
Nikita Vasilevsky
ac6217d6fa
Ensure association's foreign_key: and query_constraints: options behave the same 2024-04-09 14:52:17 +00:00
Eileen M. Uchitelle
6f32c7b2e9
Merge pull request #51513 from fatkodima/create_table-force-and-if_not_exists
Raise when both `:force` and `:if_not_exists` provided to `create_table`
2024-04-09 10:14:30 -04:00
fatkodima
e8bf57894e Raise when both :force and :if_not_exists provided to create_table
Co-authored-by: Allison Phillips <aly@thanx.com>
2024-04-08 23:46:48 +03:00
Carlos Antonio da Silva
8ad19d9865 Minor tweaks / improvements to recent changelog/api docs [ci skip] 2024-04-08 14:48:44 -03:00
Petrik
79f0c6504d Fix small typo's in ActiveRecord Changelog [ci-skip] 2024-04-08 15:58:14 +02:00
Jean Boussier
3700aa90e3 Fix a typo in activerecord/CHANGELOG.md 2024-04-08 12:19:29 +02:00
Martin Sander
f2addb58a5 Fix "no anonymous block parameter" in ruby 3.1
Also change another anonymous block to a named block as requested by
skipkayhil, although it does not trigger the same error as the method
does not contain any keyword arguments.
2024-04-06 21:30:09 +02:00
fatkodima
bb779f929f Counter cache columns are not marked as readonly [skip ci] 2024-04-06 12:39:08 +03:00
Ben Sheldon [he/him]
2182419d81
Allow IN with subselect to be preparable 2024-04-04 21:36:39 -07:00
fatkodima
6369e92fbb Add queries count to template rendering instrumentation 2024-04-04 18:25:06 +03:00
Jean Boussier
58158c0f8c
Merge pull request #51478 from kmcphillips/mysql-parse-version-error
Raise named exception in `AbstractMysqlAdapter` when DB reports an invalid version
2024-04-04 17:15:45 +02:00
Jean Boussier
bfcc13ab7c Arel: make Or nodes "Nary" like And
Fix: https://github.com/rails/rails/issues/51386

This significantly reduce the depth of the tree for large `OR`
conditions. I was initially a bit on the fence about that fix,
but given that `And` is already implemented this way, I see no
reasons not to do the same.

Amusingly, the reported repro script now makes SQLite fail:

```ruby
SQLite3::SQLException: Expression tree is too large (maximum depth 1000)
```
2024-04-04 14:59:56 +02:00
Kevin McPhillips
d9995cc00c
Add test for MariaDB 5.5.5- prefix in db version parsing regex. 2024-04-03 16:38:33 -04:00
Kevin McPhillips
869d802c48
Raise a descriptive error if the MySQL adapter fails to parse the version string. 2024-04-03 16:38:33 -04:00
Jean Boussier
c2df237414 Allow to register transaction callbacks outside of a record
Ref: https://github.com/rails/rails/pull/26103
Ref: https://github.com/rails/rails/pull/51426

A fairly common mistake with Rails is to enqueue a job from inside a
transaction, and a record as argumemnt, which then lead to a RecordNotFound
error when picked up by the queue.

This is even one of the arguments advanced for job runners backed by the
database such as `solid_queue`, `delayed_job` or `good_job`. But relying
on this is undesirable iin my opinion as it makes the Active Job abstraction
leaky, and if in the future you need to migrate to another backend or even
just move the queue to a separate database, you may experience a lot of race
conditions of the sort.

But more generally, being able to defer work to after the current transaction
has been a missing feature of Active Record. Right now the only way to do it
is from a model callback, and this forces moving things in Active Record
models that sometimes are better done elsewhere. Even as a self-proclaimed
"service object skeptic", I often wanted this capability over the last decade,
and I'm sure it got asked or desired by many more people.

Also there's some 3rd party gems adding this capability using monkey patches.
It's not a reason to upstream the capability, but it's a proof that there is
demand for it.

Implementation wise, this proof of concept shows that it's not really hard to
implement, even with nested multi-db transactions support.

Co-Authored-By: Cristian Bica <cristian.bica@gmail.com>
2024-04-03 14:26:10 +02:00
Jean Boussier
eac95d531d Fix the ActionRecord typo 2024-04-03 09:32:41 +02:00
fatkodima
e79455f3d4 Add the ability to ignore counter cache columns while they are backfilling 2024-04-02 13:59:46 +03:00
Jean Boussier
d6ec8dbc48 Suggest inverse_of: nil instead of false
Followup: https://github.com/rails/rails/pull/50883
Ref: https://github.com/rails/rails/pull/50284#issuecomment-2027722175
2024-03-30 09:53:38 +01:00
Rosa Gutierrez
6758b86b84 Emit deprecation warning about inverse_of inference only for valid reflections
That is, if the reflection found is not valid, we don't want to emit the warning
because it's misleading. It says the inverse association could have been automatically
inferred but wasn't because `automatically_invert_plural_associations` is disabled.
However, this is not true, because later on, when we check whether the reflection
is valid, we see it's not, and end up returning `nil`.
2024-03-28 21:04:07 +01:00
Feng Ce
c1c07b096b Remove delegate_missing_to in FutureResult class and add test cases. 2024-03-27 17:58:12 +08:00
fatkodima
16d635768c Fix PostgreSQL include indexes with keyword column names 2024-03-27 11:30:15 +02:00
Andrew Novoselac
cd5fe84fbe Add tests guarding against regressions identified in rails/rails@640e3981
We had to revert rails/rails@6dd1929 due to some regressions it caused. Here are some tests that would prevent those regressions in the future. See previous commits for more detail.
2024-03-26 12:32:13 -04:00
Jean Boussier
12dbb80635
Merge pull request #51425 from andrewn617/revert-eliminate-lease-connection-in-type-caster-connection
Revert eliminate lease connection in type caster connection
2024-03-26 16:55:00 +01:00
Andrew Novoselac
42fede57bd Use with_connection instead of lease_connection in TypeCaster::Connection 2024-03-26 10:13:49 -04:00
Andrew Novoselac
640e3981ca Revert "Eliminate lease_connection call in TypeCaster::Connection"
This reverts commit 6dd1929b04de42cdff1264bb5618c7f6abe77a9c.

This introduced a change in behaviour since type_for_attribute is aware of custom types but lookup_cast_type does not.

Additionally, since we no longer to use the table and column info to get attributes, this introduced an issue where attribute types were not be correctly found for some queries, where we were joining a table that has a different name than the name of the reflection for that association.
2024-03-26 10:08:40 -04:00
Adrianna Chang
eabcff22a8
Retry known idempotent SELECT queries on connection-related exceptions
This commit makes two types of queries retry-able by opting into our `allow_retry` flag:
1) SELECT queries we construct by walking the Arel tree via `#to_sql_and_binds`. We use a
new `retryable` attribute on collector classes, which defaults to true for most node types,
but will be set to false for non-idempotent node types (functions, SQL literals, etc). The
`retryable` value is returned from  `#to_sql_and_binds` and used by `#select_all` and
passed down the call stack, eventually reaching the adapter's `#internal_exec_query` method.

Internally-generated SQL literals are marked as retryable via a new `retryable` attribute on
`Arel::Nodes::SqlLiteral`.

2) `#find` and `#find_by` queries with known attributes. We set `allow_retry: true` in `#cached_find_by`,
and pass this down to `#find_by_sql` and `#_query_by_sql`.

These changes ensure that queries we know are safe to retry can be retried automatically.
2024-03-26 09:25:55 -04:00
fatkodima
e9b6185234
Merge pull request #51417 from akhilgkrishnan/test-typo-fix
Fix typo: belong_to -> belongs_to
2024-03-26 11:37:38 +02:00
Joshua Young
31ba84d5cd
Ensure binary encoding check is performed with the correct context in #encrypt_as_text (#51423) 2024-03-25 22:26:35 -07:00
Joshua Young
fc9ccbd89c
Fix ActiveRecord::Encryption::Errors::Encoding incorrectly raises for not-encrypted binary encoded values (#51412) 2024-03-25 18:05:54 -07:00
Yaroslav Kurbatov
3bd2d686c7
Ensure all association options are added to the list unconditionally
Some association options, e.g. `through`, were only added to
`.valid_options` list only if they were provided. It means that
sometimes ArgumentError's message would not mention all the
possible options.
2024-03-26 00:03:45 +03:00
Akhil G Krishnan
155dada1eb Fix Typo: belong_to updated to belongs_to 2024-03-25 21:25:09 +05:30
Carlos Antonio da Silva
61a3e61e77 Minor text / error message tweaks, fixes, and punctuation
Improve a few sentences and add punctuation to some recent changelog &
guide entries.

[ci skip]
2024-03-25 10:21:08 -03:00
Nikita Vasilevsky
3df4d6927d Add CHANGELOG entries for association composite primary and foreign keys 2024-03-25 08:38:56 -04:00
Jean Boussier
246b3b609b
Merge pull request #50883 from Shopify/infer-inverse-of-deprecation
Put plural inverse association inference behind a configuration flag
2024-03-25 12:25:21 +01:00
Rony Vieira
2f64b9d1ef Fix typo on ActiveRecord::Associations::ClassMethods doc 2024-03-25 11:36:50 +01:00
Jean Boussier
7a8e58bcb3 Put plural inverse association inference behind a configuration flag
Ref: https://github.com/rails/rails/pull/50284

While having the inverse association configured it generally positive
as it avoid some extra queries etc, infering it may break legecy code,
as evidenced by how it broke `ActiveStorage::Blob` in https://github.com/rails/rails/pull/50800

As such we can't just enable this behavior immediately, we need to provide
and upgrade path for users.
2024-03-25 10:24:21 +01:00
Jean Boussier
4db9f51259
Merge pull request #51349 from Shopify/connection-optional-deprecation
Add `config.active_record.permanent_connection_checkout` setting
2024-03-25 08:34:56 +01:00
fatkodima
26fccf44c0 Fix destroy_async job for owners with composite primary keys 2024-03-25 01:52:54 +02:00
fatkodima
fa2aea8108 Wrap by parentheses custom complex sql literals in update_all 2024-03-24 21:08:22 +02:00
Jean Boussier
fdde675b88 Implement with_connection(prevent_permanent_checkout: true) option
When `.connection` is called inside a `.with_connection` block
it cause the lease to become permanent (or sticky). This is to
ensure that legacy code that may hold onto this connection
won't cause thread safety issues.

However if you autidted the code that calls `.connection` and
know for sure it won't hold into the returned connection,
you can wrap it with `with_connection(prevent_permanent_checkout: true)`
to prevent the lease from becoming permanent and ensure the connection
is released at the end of the block.
2024-03-21 12:19:15 +01:00
Jean Boussier
dd8fd52c07 Add config.active_record.permanent_connection_checkout setting
Controls whether `ActiveRecord::Base.connection` raises an error, emits a deprecation warning, or neither.

`ActiveRecord::Base.connection` checkouts a database connection from the pool and keep it leased until the end of
the request or job. This behavior can be undesirable in environments that use many more threads or fibers than there
is available connections.

This configuration can be used to track down and eliminate code that calls `ActiveRecord::Base.connection` and
migrate it to use `ActiveRecord::Base.with_connection` instead.

The default behavior remains unchanged, and there is currently no plans to change the default.
2024-03-21 12:19:15 +01:00
Jean Boussier
9f01421d7d Eliminate remaining use of lease_connection in Arel::TreeManager 2024-03-20 20:03:39 +01:00
Jean Boussier
7c68c5210c
Merge pull request #51353 from Shopify/get-rid-lease-connection
Eliminate remaining uses of `lease_connection` inside Active Record
2024-03-19 18:03:37 +01:00
Jean Boussier
f8d8183eca Eliminate lease_connection call in Integration 2024-03-19 15:44:52 +01:00
Jean Boussier
5bc1724535 Eliminate lease_connection call in Transactions 2024-03-19 15:44:52 +01:00
Jean Boussier
ae77151fe0 Eliminate lease_connection call in Arel 2024-03-19 15:33:27 +01:00
Jean Boussier
6dd1929b04 Eliminate lease_connection call in TypeCaster::Connection 2024-03-19 14:52:56 +01:00
Eileen M. Uchitelle
27942bc382
Merge pull request #50347 from iamradioactive/fix_derived_foreign_key
Fix derived foreign key to return correctly when association id is part of query constraints
2024-03-19 09:14:19 -04:00
Jean Boussier
7082d343c8 Eliminate lease_connection call in UniquenessValidator 2024-03-19 14:04:27 +01:00
Jean Boussier
97755b8f8d Eliminate lease_connection call in JoinAssociation 2024-03-19 14:00:19 +01:00
Max Prokopiev
6aec2ca232 Extract check for VALUES/row_alias syntax
The change to upserts (https://github.com/rails/rails/pull/51274) is causing
an issue with Vitess, since it doesn't support the `row_alias` syntax added
in MySQL 8.0.19.

There is an ongoing work (https://github.com/vitessio/vitess/pull/15510)
to add that support and it is likely to be included into Vitess v20,
but in the meantime it would be nice to have an ability to control that
behavior in the existing apps.
2024-03-19 11:52:18 +01:00
Jean Boussier
0f3465c03a
Merge pull request #51346 from ghiculescu/_active_record_fixture
Fix clash with methods named `fixture` in test cases
2024-03-19 08:09:07 +01:00
Alex
461ac5943c Fix clash with methods named fixture in test cases
Fix: https://github.com/rails/rails/pull/51213#issuecomment-2003349504
2024-03-19 10:40:13 +10:00
Rafael Mendonça França
2fa7d52863
Merge pull request #51345 from Shopify/allow-association-primary-key-to-be-an-array
Allow `primary_key:` association option to be composite
2024-03-18 13:32:38 -07:00
Rafael Mendonça França
e6f92f17aa
Merge pull request #51334 from Shopify/allow-setting-assoc-foreign-key-as-an-array
Allow association `foreign_key` to be an Array
2024-03-18 13:31:33 -07:00
Gannon McGibbon
a56cf01e5a
Merge pull request #51335 from gmcgibbon/connection_ensure_active
Don't query adapter in ensure blocks when connection is closed
2024-03-18 15:19:48 -05:00
Nikita Vasilevsky
cc4f368390
Allow primary_key: association option to be composite
Association's `primary_key` can be composite when derived from associated class
`primary_key` or `query_constraints`. But we don't allow setting it explicitly
even though Rails is already capable of supporting it.

This commit allows `primary_key` association option to be an array.
2024-03-18 18:40:14 +00:00
Carlos Antonio da Silva
f404a949ce Fix AR changelog reference to new config [ci skip] 2024-03-18 13:09:43 -03:00
Gannon McGibbon
548bb830ab Don't query adapter in ensure blocks when connection is closed
Trilogy closes its connection when it encounters a timeout. Active
Record doesn't always account for this, and can query the adapter in
ensure blocks of certain adapter methods. Instead, we need to preface
these queries with active checks to make sure we don't swallow the
timeout and raise an adapter error instead.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
2024-03-15 20:05:35 -05:00
Nikita Vasilevsky
a94d02fbd2
Allow association foreign_key to be an Array
Currently the only way to setup a composite foreign key is to use `query_constraints`.
With our intention to decouple `query_constraints` from `foreign_key` we need to allow
`foreign_key` to be an Array to preserve the current behavior achieved with `query_constraints`.
2024-03-15 19:40:57 +00:00
Jean Boussier
89adf24a57
Merge pull request #51325 from gabriel-amaral/old-upsert-for-on-duplicate-raw-sql
Do not try to alias on key update when raw SQL is supplied
2024-03-14 16:26:00 +01:00
Gabriel Amaral
ee483b68b3 Do not try to alias on key update when raw SQL is supplied 2024-03-14 13:20:00 +00:00
Jean Boussier
3771f7ea58 Stablize ConnectionPoolTests#test_idle_timeout_configuration
It flakes a lot on my machine because the timeouts are identical.
2024-03-14 09:54:43 +01:00
Rosa Gutierrez
4a0b2a0b5b Memoize key_provider from key or deterministic key_provider if any
The memoization of Scheme#key_provider was removed completely in
https://github.com/rails/rails/pull/51019 because it prevented
overriding the `key_provider` via `with_encryption_context`. However,
this also made our tests for the HEY app about 5 times slower. We traced
this down to all attributes where we either provide a key or declare them
as deterministic and have to derive a key to instantiate the provider
every time we load them. This might happen hundreds of times per test,
and ultimately, we call
```
ActiveSupport::KeyGenerator#generate_key
```
and
```
OpenSSL::KDF.pbkdf2_hmac
```
hundreds of times. This adds significant overhead per test.

In reality, what's overridden bv `with_encryption_context` is the value
used as default provider, that is, `ActiveRecord::Encryption.key_provider`.
This is only used in `Scheme#key_provider` if the scheme doesn't already have
either a `key_provider` passed directly, or a `key`, or is `deterministic`.
The `key_provider` passed directly is already memoized simply by having it
stored as is. Let's memoize the other two, in order, so we save all those
extra calls to derive the same keys again and again.
2024-03-13 22:41:10 +01:00
Sean Doyle
c2ca7594dc ActiveRecord::Migration.verbose documentation [ci skip]
Follow-up to [#51258][]

Re-write `ActiveRecord::Migration.verbose` documentation to incorporate
[review feedback][] from [#51258][].

[#51258]: https://github.com/rails/rails/pull/51258
[review feedback]: https://github.com/rails/rails/pull/51258#discussion_r1519637097
2024-03-11 09:44:59 -04:00
Vipul A M
bf96dcfa0d
Merge pull request #51258 from seanpdoyle/migration-verbose-class-attribute
Emphasize mention of `Migration.verbose` [ci skip]
2024-03-10 13:30:23 -04:00
Yasuo Honda
52353c8bf5 MySQL 8.0.19 introduces aliases in the VALUES and SET clauses of INSERT INTO ... ON DUPLICATE KEY UPDATE statement
This commit addresses the following errors against MySQL 8.0.18 or lower version of MySQL 8.0.

- Steps to reproduce

```ruby
git clone https://github.com/rails/rails
cd rails
git clone https://github.com/rails/buildkite-config .buildkite/
RUBY_IMAGE=ruby:3.3 docker-compose -f .buildkite/docker-compose.yml build base &&
  CI=1 MYSQL_IMAGE=mysql:8.0.18 docker-compose -f .buildkite/docker-compose.yml run mysqldb runner activerecord 'rake db:mysql:rebuild test:mysql2'
```

- Actual behavior

```ruby
... snip ...
Error:
InsertAllTest#test_upsert_all_implicitly_sets_timestamps_on_create_when_model_record_timestamps_is_false_but_overridden:
ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `ships_values` ON DUPLICATE KEY UPDATE updated_at=(CASE WHEN (`ships`.`name`<' at line 1
    /usr/local/bundle/gems/mysql2-0.5.6/lib/mysql2/client.rb:151:in `_query'
    /usr/local/bundle/gems/mysql2-0.5.6/lib/mysql2/client.rb:151:in `block in query'
    /usr/local/bundle/gems/mysql2-0.5.6/lib/mysql2/client.rb:150:in `handle_interrupt'
    /usr/local/bundle/gems/mysql2-0.5.6/lib/mysql2/client.rb:150:in `query'
    lib/active_record/connection_adapters/mysql2/database_statements.rb:104:in `block (2 levels) in raw_execute'
    lib/active_record/connection_adapters/abstract_adapter.rb:997:in `block in with_raw_connection'
    /rails/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb:23:in `handle_interrupt'
    /rails/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb:23:in `block in synchronize'
    /rails/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb:19:in `handle_interrupt'
    /rails/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb:19:in `synchronize'
    lib/active_record/connection_adapters/abstract_adapter.rb:969:in `with_raw_connection'
    lib/active_record/connection_adapters/mysql2/database_statements.rb:102:in `block in raw_execute'
    /rails/activesupport/lib/active_support/notifications/instrumenter.rb:58:in `instrument'
    lib/active_record/connection_adapters/abstract_adapter.rb:1112:in `log'
    lib/active_record/connection_adapters/mysql2/database_statements.rb:101:in `raw_execute'
    lib/active_record/connection_adapters/abstract_mysql_adapter.rb:237:in `execute_and_free'
    lib/active_record/connection_adapters/mysql2/database_statements.rb:23:in `internal_exec_query'
    lib/active_record/connection_adapters/abstract/database_statements.rb:171:in `exec_insert_all'
    lib/active_record/connection_adapters/abstract/query_cache.rb:26:in `exec_insert_all'
    lib/active_record/insert_all.rb:55:in `execute'
    lib/active_record/insert_all.rb:13:in `block in execute'
    lib/active_record/connection_adapters/abstract/connection_pool.rb:384:in `with_connection'
    lib/active_record/connection_handling.rb:270:in `with_connection'
    lib/active_record/insert_all.rb:12:in `execute'
    lib/active_record/persistence.rb:363:in `upsert_all'
    test/cases/insert_all_test.rb:561:in `block in test_upsert_all_implicitly_sets_timestamps_on_create_when_model_record_timestamps_is_false_but_overridden'
    test/cases/insert_all_test.rb:809:in `with_record_timestamps'
    test/cases/insert_all_test.rb:560:in `test_upsert_all_implicitly_sets_timestamps_on_create_when_model_record_timestamps_is_false_but_overridden'

bin/rails test /rails/activerecord/test/cases/insert_all_test.rb:557

E
... snip ...
8856 runs, 25842 assertions, 1 failures, 52 errors, 41 skips
```

Follow up #51274

Refer to these release notes, WL and commits for MySQL 8.0.19 and 8.0.20.

- MySQL 8.0.19 supports aliases in the VALUES and SET clauses of INSERT INTO ... ON DUPLICATE KEY UPDATE statement
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-19.html

> MySQL now supports aliases in the VALUES and SET clauses of INSERT INTO ... ON DUPLICATE KEY UPDATE statement
> for the row to be inserted and its columns. Consider a statement such as this one:

https://dev.mysql.com/worklog/task/?id=6312
c39355e9e6

- MySQL 8.0.20 deprecates the old `VALUES()` syntax in INSERT ... ON DUPLICATE KEY UPDATE statements

https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-20.html
> The use of VALUES() to access new row values in INSERT ... ON DUPLICATE KEY UPDATE statements
> is now deprecated, and is subject to removal in a future MySQL release.
> Instead, you should use aliases for the new row and its columns as implemented in MySQL 8.0.19 and later.

https://dev.mysql.com/worklog/task/?id=13325
6f3b9df50b
2024-03-09 00:03:39 +09:00
fatkodima
3c61c3d4f8 Fix flaky upsert test 2024-03-08 01:56:08 +02:00
fatkodima
0e7826e10e Fix upsert warning for MySQL 2024-03-07 15:35:14 +02:00
Sean Doyle
0faae8af77 Emphasize mention of Migration.verbose [ci skip]
The API documentation for `ActiveRecord::Migration` mentions controlling
the level of log output through a `.verbose` class attribute. The line
isn't wrapped in `<tt>`, `+`, or backticks, so isn't emphasized as if it
were code.

This commit visually emphasizes that line so that it's more obviously
code.
2024-03-06 17:12:55 -05:00
Carlos Antonio da Silva
2fa3294618
Merge pull request #51263 from buncis/update-delegate-type-doc
[ci skip] update delegated type doc to make it less confusing and in sync with rails guide
2024-03-06 13:22:44 -03:00
buncis
1c54153dc6
update docs to make it less confusing and in sync with rails guide 2024-03-06 20:31:34 +07:00
Yasuo Honda
3a7d96c485 Add missing :author_addresses in OrderTest
This commit addresses this CI failure https://buildkite.com/rails/rails-nightly/builds/247#018e0bea-7a88-45eb-94fa-be4155aeeeca/1164-1173

- Error without this commit
```ruby
$ bin/test test/cases/relation/order_test.rb test/cases/fixtures_test.rb -n "/^(?:OrderTest#(?:test_order_desc)|FixturesWithForeignKeyViolationsTest#(?:test_does_not_raise_if_no_fk_violations))$/" --seed 31115
Using sqlite3
Run options: -n "/^(?:OrderTest#(?:test_order_desc)|FixturesWithForeignKeyViolationsTest#(?:test_does_not_raise_if_no_fk_violations))$/" --seed 31115

.E

Error:
FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations:
RuntimeError: Foreign key violations found in your fixture data. Ensure you aren't referring to labels that don't exist on associations. Error from database:

Foreign key violations found: authors, authors, authors
    lib/active_record/fixtures.rb:704:in `rescue in check_all_foreign_keys_valid!'
    lib/active_record/fixtures.rb:701:in `check_all_foreign_keys_valid!'
    lib/active_record/fixtures.rb:688:in `block (2 levels) in insert'
    lib/active_record/connection_adapters/abstract/connection_pool.rb:384:in `with_connection'
    lib/active_record/fixtures.rb:685:in `block in insert'
    lib/active_record/fixtures.rb:676:in `each'
    lib/active_record/fixtures.rb:676:in `insert'
    lib/active_record/fixtures.rb:662:in `read_and_insert'
    lib/active_record/fixtures.rb:607:in `create_fixtures'
    test/cases/fixtures_test.rb:893:in `block (2 levels) in test_does_not_raise_if_no_fk_violations'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/testing/assertions.rb:49:in `assert_nothing_raised'
    test/cases/fixtures_test.rb:892:in `block in test_does_not_raise_if_no_fk_violations'
    test/cases/fixtures_test.rb:906:in `with_verify_foreign_keys_for_fixtures'
    test/cases/fixtures_test.rb:891:in `test_does_not_raise_if_no_fk_violations'

bin/test test/cases/fixtures_test.rb:884

Finished in 0.084771s, 23.5930 runs/s, 94.3720 assertions/s.
2 runs, 8 assertions, 0 failures, 1 errors, 0 skips
$
```

Refer to #43873 that has the same reason why it gets error.
2024-03-05 14:23:20 +09:00
Yasuo Honda
a556be5ddc Use ActiveRecord::Base.lease_connection for uncached dirties tests
This commit addresses these errors since #51192 renames `.connection` into `.lease_connection`

Follow up #51204

```ruby
$ cd activerecord
$ bin/test test/cases/query_cache_test.rb -n /uncached_dirties/
Using sqlite3
Run options: -n /uncached_dirties/ --seed 57207

E

Error:
QueryCacheTest#test_query_cache_uncached_dirties:
NoMethodError: undefined method `connection' for class ActiveRecord::Base
    lib/active_record/dynamic_matchers.rb:22:in `method_missing'
    test/cases/query_cache_test.rb:712:in `block (2 levels) in test_query_cache_uncached_dirties'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/testing/assertions.rb:241:in `assert_no_changes'
    test/cases/query_cache_test.rb:712:in `block in test_query_cache_uncached_dirties'
    test/cases/query_cache_test.rb:771:in `block (2 levels) in middleware'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/execution_wrapper.rb:91:in `wrap'
    test/cases/query_cache_test.rb:771:in `block in middleware'
    test/cases/query_cache_test.rb:720:in `test_query_cache_uncached_dirties'

bin/test test/cases/query_cache_test.rb:709

E

Error:
QueryCacheTest#test_query_cache_connection_uncached_dirties:
NoMethodError: undefined method `connection' for class ActiveRecord::Base
    lib/active_record/dynamic_matchers.rb:22:in `method_missing'
    test/cases/query_cache_test.rb:726:in `block (2 levels) in test_query_cache_connection_uncached_dirties'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/testing/assertions.rb:241:in `assert_no_changes'
    test/cases/query_cache_test.rb:726:in `block in test_query_cache_connection_uncached_dirties'
    test/cases/query_cache_test.rb:771:in `block (2 levels) in middleware'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/execution_wrapper.rb:91:in `wrap'
    test/cases/query_cache_test.rb:771:in `block in middleware'
    test/cases/query_cache_test.rb:734:in `test_query_cache_connection_uncached_dirties'

bin/test test/cases/query_cache_test.rb:723

E

Error:
QueryCacheTest#test_query_cache_uncached_dirties_disabled_with_nested_cache:
NoMethodError: undefined method `connection' for class ActiveRecord::Base
    lib/active_record/dynamic_matchers.rb:22:in `method_missing'
    test/cases/query_cache_test.rb:740:in `block (2 levels) in test_query_cache_uncached_dirties_disabled_with_nested_cache'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/testing/assertions.rb:194:in `assert_changes'
    test/cases/query_cache_test.rb:740:in `block in test_query_cache_uncached_dirties_disabled_with_nested_cache'
    test/cases/query_cache_test.rb:771:in `block (2 levels) in middleware'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/execution_wrapper.rb:91:in `wrap'
    test/cases/query_cache_test.rb:771:in `block in middleware'
    test/cases/query_cache_test.rb:757:in `test_query_cache_uncached_dirties_disabled_with_nested_cache'

bin/test test/cases/query_cache_test.rb:737

Finished in 0.134429s, 22.3166 runs/s, 0.0000 assertions/s.
3 runs, 0 assertions, 0 failures, 3 errors, 0 skips
$
```
2024-03-03 23:37:54 +09:00
Donal McBreen
5d528ba0c8
Add dirties option to uncached (#51204)
This adds a `dirties` option to `ActiveRecord::Base.uncached` and
`ActiveRecord::ConnectionAdapters::ConnectionPool#uncached`.

Setting `dirties` to `false`, means database writes to the connection
pool will not mark any query caches as dirty.

The option defaults to `true` which retains the existing behaviour and
clears query caches on all connection pools used by the current thread.

Co-authored-by: Jeremy Daer <jeremy@rubyonrails.org>
2024-03-02 19:01:24 -08:00
Jean Boussier
ec7deca7ee Refactor InsertAll not to permanently lease a connection
Extracted from: https://github.com/rails/rails/pull/50793
2024-03-01 15:33:45 +01:00
Jean Boussier
2bf0d68de6 Fix a typo in ConnectionPoool#connection deprecation (again) 2024-03-01 15:32:58 +01:00
Jean Boussier
f657842090 Fix a typo in ConnectionPoool#connection deprecation 2024-03-01 15:28:00 +01:00
Jean Boussier
7263da542b 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
2024-03-01 14:32:55 +01:00
Jean Boussier
38e8609ded Make .connection always return a permanently leased connection
Ref: https://github.com/rails/rails/pull/51083

The introduction of `ActiveRecord::Base.with_connection` somewhat broke
some expectations, namely that calling `.connection` would cause the
connection to be permenently leased, hence that future calls to it
would return the same connection, with all it's possible environmental
changes.

So any call to `.connection`, even inside `.with_connection` should
cause the lease to be sticky, and persist beyond the `with_connection`
block.

Also rename `.connection` into `.lease_connection`, as to make it
more explicit.
2024-03-01 11:37:06 +01:00
Jean Boussier
1d0b396f40 Clear all threads query cache when a connection is pinned
Ref: https://github.com/Shopify/maintenance_tasks/pull/983#issuecomment-1969407080
Ref: https://github.com/rails/rails/pull/51151

Now that query caches are owned by the pool, and assigned on connections
during checkout, when running multithreaded code inside transactional
tests (typically system tests), the two threads uses the same connection
but not the same cache.

So it's important that we do clear the caches for all threads when
a connection is pinned.
2024-02-29 09:21:18 +01:00
Jean Boussier
ef947f9932 Expose a generic fixture accessor for fixture names that may conflict with Minitest
```ruby
assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
assert_equal "Ruby on Rails", fixture(:web_sites, :rubyonrails).name
```

This was brought to me by someone with a `Metadata` model. The fixtures
accessor being `metadata` which conflicts with the `metadata` method
recently added in `Minitest`.
2024-02-28 16:09:23 +01:00
Joshua Young
f42d9cbc32 [Fix #51164] Model.query_constraints with single non-primary-key column raises incorrect error 2024-02-28 14:19:10 +10:00
Rafael Mendonça França
649e99bf92
Merge pull request #51206 from fatkodima/fix-indexes-for-nonexisting-table
Fix `indexes` method for non-existing MySQL tables
2024-02-27 16:29:49 -05:00
fatkodima
8510efa841 Fix indexes method for non-existing MySQL tables 2024-02-27 13:39:01 +02:00
Jean Boussier
0016280f4f Don't require an active connection for table and column quoting
Extracted from: https://github.com/rails/rails/pull/50793

Right now quoting table or column names requires a leased Adapter
instance, even though none of the implementations actually requires
an active connection.

The idea here is to move these methods to the class so that the quoting
can be done without leasing a connection or even needing the connection
to ever have been established.

I also checked `activerecord-sqlserver-adapter` and `oracle-enhanced`
gems, and neither need an active connection.
2024-02-27 11:19:00 +01:00
Carlos Antonio da Silva
c402ec7872 Add punctuation on some newly added API docs [ci skip] 2024-02-26 13:32:39 -03:00
Jean Boussier
6e74098b8c Fix Migrator.current_version to instantiate SchemaMigration correctly
This was missed in https://github.com/rails/rails/pull/51162
2024-02-26 12:49:31 +01:00
Vipul A M
2abee307fe
Merge pull request #51184 from ConfusedVorlon/document_after_commit_deduplication
[ci skip] Add warning about deduplication of after_xxx_commit shortcuts
2024-02-25 16:30:11 -05:00
Lex Cao
48036fee0d Fix typo 2024-02-25 23:11:40 +08:00
Rob Jonson
79fa0e3b2d Add warning about deduplication of after_xxx_commit shortcuts 2024-02-24 19:40:13 +00:00
fatkodima
5db70c979e Fix flaky multi_db_migrator_test.rb test 2024-02-24 02:38:31 +02:00
Jean Boussier
2cbedfdb2e Refactor FixtureSet to deal with connection pools
Extracted from: https://github.com/rails/rails/pull/50793

Allow to check the cache without checking out a connection.
2024-02-23 11:25:33 +01:00
Jean Boussier
932e029ad7
ConnectionPool: handle schema_reflection being re-assigned
This fixes a regression recently introduced that a schema_reflection
assignment from taking effect.
2024-02-22 21:13:04 +00:00
Jean Boussier
a918394974 Refactor InternalMetadata, MigrationContext to belong to the pool
Extracted from: https://github.com/rails/rails/pull/50793

Similar to the recent refactoring of schema caches, rather than to directly
hold a connection, they now hold a pool and checkout a connection when needed.
2024-02-22 12:46:41 +01:00
Rafael Mendonça França
939742d69e
Merge pull request #50901 from joshuay03/fix-autosave-has-one-setting-fk-when-unchanged
[Fix #50897] Autosaving `has_one` sets foreign key attribute when unchanged
2024-02-21 15:21:23 -05:00
Rafael Mendonça França
3e42d79c99
Merge pull request #51078 from saleh-alhaddad/support_join_types_in_where_associated
Fix override existing join types in the query in the `where.associated` method
2024-02-21 15:10:24 -05:00
saleh-alhaddad
3400aac7f9
Fix an issue in the where.associated method 2024-02-21 18:12:15 +00:00
mylesboone
278d6574cf
ActiveRecord::Relation#order supports hash like ActiveRecord::Relation#where (#50000)
* relation#order supports hash like relation#where

This allows for an ActiveRecord::Relation to take a hash such as
`Topic.includes(:posts).order(posts: { created_at: :desc })`

* use is_a? to support subclasses of each

Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
2024-02-21 12:43:15 -05:00
Jean Boussier
684131a4f0
Merge pull request #51139 from Shopify/relation-bound-sql-literal
Relation#where build BoundSqlLiteral rather than eagerly interpolate
2024-02-21 16:49:45 +01:00
Carlos Antonio da Silva
baad391196 Remove unused intermediate variable
It was necessary to return properly with the previous deprecation code,
which was removed in eccc6061f4f3abdfdeb9a363987a898418d9498f.
2024-02-21 09:31:27 -03:00
Jean Boussier
8e6a5deca6 Relation#where build BoundSqlLiteral rather than eagerly interpolate
Ref: https://github.com/rails/rails/pull/50793

To make not caching connection checkout viable, we need to reduced
the amount of places where we need a connection.

Once big source of this is query/relation building, where in many
cases it eagerly quote and interpolation bound values in SQL fragments.

Doing this requires an active connection because both MySQL and Postgres
may quote values differently based on the connection settings.

Instead of eagerly doing all this, we can instead just insert these
as bound values in the Arel AST. For adapters with prepared statements
this is better anyway as it will avoid leaking statements, and for those
that don't support it, it will simply delay the quoting to just
before the query is executed.

However, the `%` API (`where("title = %s", something)`) can't realistically
be fixed this way, but I don't see much value in it and it probably should
be deprecated and removed.
2024-02-21 13:22:55 +01:00
Jean Boussier
1af361b30b Don't forcefully clear temporarily disabled query caches
Followup: https://github.com/rails/rails/pull/50938

The behavior changed to always clear the query cache as soon
as it's disabled, on the assumption that once queries have been
performed without it, all bets are off.

However that isn't quite true, we can apply the same clearing
logic than when it's enabled. If you perform read only queries
without the cache, there is no reason to clear it.
2024-02-21 11:47:54 +01:00
Jean Boussier
e88dba8f0b clear_query_caches_for_current_thread: avoid pinning all connections
Ref: https://github.com/rails/rails/pull/51083#discussion_r1496720821

Now that the pool is owned by the pool, we can clear it without
hacing to checkout a connection.
2024-02-21 10:26:28 +01:00
Joshua Young
a518b5a9d9 [Fix #50897] Autosaving has_one sets foreign key attribute when unchanged 2024-02-21 18:07:44 +10:00
Rafael Mendonça França
842ca2137f
Merge pull request #51047 from johnpitchko/add-query-docs-to-delegated-type
Add query docs for delegated type [ci skip]
2024-02-20 18:22:49 -05:00
Rafael Mendonça França
eccc6061f4
Remove deprecated behavior that would rollback a transaction block when exited using return, break or throw. 2024-02-20 21:56:51 +00:00
Rafael Mendonça França
c313d91613
Remove deprecated support to pass rewhere to ActiveRecord::Relation#merge 2024-02-20 21:56:13 +00:00
Rafael Mendonça França
c09956a3ad
Remove deprecated support to pass deferrable: true to add_foreign_key 2024-02-20 21:55:04 +00:00
Rafael Mendonça França
95b48d8a3b
Remove deprecated support to quote ActiveSupport::Duration 2024-02-20 21:54:57 +00:00
Rafael Mendonça França
240e9dac0a
Remove deprecated #quote_bound_value 2024-02-20 21:53:43 +00:00
Rafael Mendonça França
465fbd78f4
Remove deprecated ActiveRecord::ConnectionAdapters::ConnectionPool#connection_klass 2024-02-20 21:53:41 +00:00
Rafael Mendonça França
64cbcd7a8c
Remove deprecated support to apply some methods in the Connection Handle to the connections pools for the current role when the role arguments isn't provided 2024-02-20 21:53:38 +00:00
Rafael Mendonça França
9489c14b7b
Remove deprecated #all_connection_pools 2024-02-20 21:53:17 +00:00
Rafael Mendonça França
7ddf423329
Remove deprecated ActiveRecord::ConnectionAdapters::SchemaCache#data_sources 2024-02-20 21:53:13 +00:00
Rafael Mendonça França
5667de1aca
Remove deprecated ActiveRecord::ConnectionAdapters::SchemaCache.load_from 2024-02-20 21:52:11 +00:00
Rafael Mendonça França
9391f0a0e8
Remove deprecated #all_foreign_keys_valid? from database adapters 2024-02-20 21:51:31 +00:00
Rafael Mendonça França
8069cc83e8
Remove deprecated support to passing coder and class as second argument to serialize 2024-02-20 21:51:30 +00:00
Rafael Mendonça França
39997a0f04
Remove deprecated support to ActiveRecord::Base#read_attribute(:id) to return the custom primary key value 2024-02-20 21:51:29 +00:00
Rafael Mendonça França
f40a697e0f
Remove deprecated TestFixtures.fixture_path 2024-02-20 21:51:26 +00:00
Rafael Mendonça França
4bf2c4cea1
Remove deprecated behavior to support referring to a singular association by its plural name 2024-02-20 21:50:36 +00:00
Rafael Mendonça França
9ef79385d9
Remove deprecated support to passing SchemaMigration and InternalMetadata classes as arguments to ActiveRecord::MigrationContext. 2024-02-20 21:50:05 +00:00
Rafael Mendonça França
02f66fe3e2
Remove deprecated ActiveRecord::Migration.check_pending method 2024-02-20 21:50:04 +00:00
Rafael Mendonça França
e509a0edb5
Remove deprecated methods on ActiveRecord::LogSubscriber 2024-02-20 21:50:03 +00:00
Rafael Mendonça França
2fb186dabb
Remove deprecated support to define explain in the connection adapter with 2 arguments 2024-02-20 21:50:02 +00:00
Rafael Mendonça França
dca35bbd77
Remove deprecated ActiveRecord::ActiveJobRequiredError 2024-02-20 21:50:01 +00:00
Rafael Mendonça França
5515fa49a2
Remove deprecated methods in ActiveRecord::Base 2024-02-20 21:50:00 +00:00
Rafael Mendonça França
7a08a86d21
Remove deprecated name argument from ActiveRecord::Base.remove_connection 2024-02-20 21:49:59 +00:00
Rafael Mendonça França
94d24f4504
[R] Remove deprecated support to call alias_attribute with non-existent attribute names 2024-02-20 21:49:56 +00:00
Rafael Mendonça França
2af68b257f
Remove deprecated Rails.application.config.active_record.suppress_multiple_database_warning 2024-02-20 21:39:06 +00:00
Rafael Mendonça França
6ca6aba66c
Merge pull request #51118 from fatkodima/missing-connection_pool-in-errors-assignments
Pass `connection_pool` to more database-related exceptions raisings
2024-02-20 16:02:49 -05:00
Carlos Antonio da Silva
0b1a0c4937
Merge pull request #51133 from johnpitchko/fix-delegated-type-example
Fix delegated type example [ci skip]
2024-02-20 13:49:07 -03:00
Jean Boussier
da9cf15f42 Refactor BindParameterTest
Ref: https://github.com/rails/rails/pull/51139

Makes it more clear that the expected behavior really is.
2024-02-20 15:06:18 +01:00
John Pitchko
c419435b0e
Fix delegated type example
Must specify `account` parameter because of the association defined in `Entry`.
2024-02-19 21:46:14 -07:00
John Pitchko
4c9a1e0d93
Add query docs for delegated type
Lint

Update activerecord/lib/active_record/delegated_type.rb

Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
2024-02-19 14:12:16 -07:00
fatkodima
6dfe92b23f Pass connection_pool to more database-related exceptions raisings 2024-02-18 01:05:40 +02:00
Jean Boussier
057563a888
Merge pull request #51038 from fatkodima/debug-ci
Rewrite connection reaper test with timeout
2024-02-17 21:32:03 +01:00
fatkodima
4880ec66b9 Rewrite connection reaper test with timeout 2024-02-17 20:55:56 +02:00
Klemen Nagode
89addc7a6e
Prevent extra newlines after table generation block in shema.rb (#48731)
* Prevent extra newlines after table generation block in shema.rb file when there are no foreign keys or indexes.  This will produce valid code without linting issues (issue: Trailing whitespace detected)

* fix linting issues

* fix linting

Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
2024-02-16 14:27:44 -05:00
Donal McBreen
50e322962b
Add MessagePackMessageSerializer for binary data (#51102) 2024-02-16 09:07:25 -08:00
Jean Boussier
50daadaa71 Update test suite for compatibility with Ruby 3.4-dev
https://bugs.ruby-lang.org/issues/19117 and https://bugs.ruby-lang.org/issues/16495
slightly change how backtrace are rendered which makes a few tests fail.
2024-02-16 11:55:44 +01:00
Donal McBreen
7d4a39cc6f
Support encrypting binary columns (#50920)
* Support encrypting binary columns

ActiveRecord Encryption doesn't prevent you from encrypting binary
columns but it doesn't have proper support for it either.

When the data is fed through encrypt/decrypt it is converted to a
String. This means that the the encryption layer is not transparent
to binary data - which should be passed as Type::Binary::Data.

As a result the data is not properly escaped in the SQL queries or
deserialized correctly after decryption.

However it just happens to work fine for MySQL and SQLite because the
MessageSerializer doesn't use any characters that need to be encoded.
However if you try to use a custom serializer that does then it breaks.

PostgreSQL on the other hand does not work - because the Bytea type
is passed a String rather than a Type::Binary::Data to deserialize, it
attempts to unescape the data and either mangles it or raises an error
if it contains null bytes.

The commit fixes the issue, by reserializing the data after
encryption and decryption. For text data that's a no-op, but for binary
data we'll convert it back to a Type::Binary::Data.

* Extract decrypt_as_text/encrypt_as_text

* Handle serialized binary data in encrypted columns

Calling `serialize` is not always possible, because the column type
might not expect to be serializing a String, for example when declared
as serialzed or store attribute.

With binary data the encryptor was passed an
`ActiveModel::Type::Binary::Data`` and returned a `String``. In order to
remain transparent we need to turn the data back into a
`ActiveModel::Type::Binary::Data` before passing it on.

We'll also rename `serialize`` to `text_to_database_type` to be a bit
more descriptive.
2024-02-15 08:45:56 -08:00
Jean Boussier
1af13c645a Refactor SchemaCache to hold a ConnectionPool
Another refactoring in relation to https://github.com/rails/rails/pull/50793

But it makes sense even without it.

Rather than each connection to have its own `BoundSchemaReflection`,
we can instead have `BoundSchemaReflection` hold a `ConnectionPool`,
from which it can checkout a connection to perform queries when needed.

If the current thread already leased a connection, it will be used.

This simplifies the interface quite a bit.
2024-02-15 13:56:32 +01:00
Jean Boussier
85330030b3 ActiveRecord::TestCase: reap all leaked connection on teardown
Some tests do leak connections, which cause some other tests to stall
for a very long time when they call `clear_all_connections`.

Each leaked connection takes 5 seconds to be cleared because of the
checkout timeout.

So on teardown to inspect all pools to make sure nothing was leaked
and if some connections were leaked we cleanup the state.
2024-02-15 13:31:34 +01:00
Rafael Mendonça França
e2c522b4b2
Merge pull request #51016 from javierav/optimistic-locking-doc
Document that lock_version column is integer
2024-02-14 18:55:48 -05:00
Rafael Mendonça França
6095b55230
Merge pull request #49655 from Shopify/fix-cpk-update-all-with-join-subquery
Fix `update_all/delete_all` on CPK model relation with join subquery
2024-02-14 18:08:53 -05:00
Rafael Mendonça França
f91cb4f81f
Deprecated ENV["SCHEMA_CACHE"] in favor of schema_cache_path in the databse configuration
The config in the yaml allows for more complex configuration.
2024-02-14 22:02:29 +00:00
Rafael Mendonça França
83f4441901
Fix deprecation message
The message was partially duplicated because
`deprecation_warning` was being called instead of `warn`
2024-02-14 22:02:13 +00:00
Rafael Mendonça França
67e4376a99
Remove unused methods from SchemaReflection 2024-02-14 22:02:11 +00:00
Rafael Mendonça França
cac604a992
Remove eager loading of schema cache dump
This will be eager loaded by the define_attribute_methods initializer
now that the schema cache can be automatically loaded for all
connection if the file is present on disk after #48716.
2024-02-14 22:02:10 +00:00
Eugene Kenny
bc31f5e556 Add missing super in prune_thread_cache method 2024-02-14 16:37:02 +00:00
Jean Boussier
17b0c0ce14 Improve ConnectionHandlingTest
As pointed by Carlos on the PR.
2024-02-14 14:42:26 +01:00
Jean Boussier
e7217c0d23 Remove a forgotten :nodoc: 2024-02-14 14:27:27 +01:00
Jean Boussier
22f41a1b40 Add ActiveRecord::Base.with_connection as a shortcut
Extracted from https://github.com/rails/rails/pull/50793

The leased connection is yielded, and for the duration of the block,
any call to `ActiveRecord::Base.connection` will yield that same connection.

This is useful to perform a few database operations without causing a
connection to be leased for the entire duration of the request or job.
2024-02-14 14:07:04 +01:00
Jean Boussier
bbf0b1f33b Refactor some Active Record tests
Mostly extracted from: https://github.com/rails/rails/pull/50793

- Use `#adapter_name` instead of `#class::ADAPTER_NAME`
- Avoid monkey patching some connection instances
- Ignore SCHEMA queries in some asssertions
2024-02-14 12:57:29 +01:00
Jean Boussier
94fc536007 Prune dead thread from connection pool caches on reap
Otherwise they could linger around and leak memory if a user
checkout connections from short lived fibers or threads.

The undocumented `connection_cache_key` hook point is eliminated
because it was essentially add to allow the connection pool to
be fiber based rather than thread based, which is now supported
out of the box.
2024-02-14 10:57:16 +01:00
Jean Boussier
85742ce529 Refactor QueryCache to be owned by the pool
Ref: https://github.com/rails/rails/pull/50793

If we want to stop caching the checked out connections,
then we must persist the cache in the pool, and assign it
to the connection when it's checked out.

The pool become responsible for managing the cache lifecycle.

This also open the door to sharing the cache between multiple
connections, which is valuable for read replicas, etc.

This change only really make sense if we go through with no
longer caching checked out connections. Otherwise it's just
extra complexity.
2024-02-14 10:57:16 +01:00
Jason Nochlin
fc9ed119c7
Deprecate config.active_record.warn_on_records_fetched_greater_than (#51007)
* Deprecate config.active_record.warn_on_records_fetched_greater_than

* Review changes

Co-authored-by: Rafael Mendonça França <rafael@franca.dev>

---------

Co-authored-by: Jason Nochlin <hundredwatt@users.noreply.github.com>
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
2024-02-13 18:20:55 -05:00
John Hawthorn
c730877c49
Merge pull request #51019 from jhawthorn/key-provider
Remove memoization to accept `key_provider` overridden by `with_encryption_context`
2024-02-13 13:10:38 -08:00
eileencodes
847953dbaa
Raise error for Trilogy when prepared_statements is true
Trilogy doesn't currently support prepared statements. The error that
applications would see is a `StatementInvalid` error. This doesn't quite point
you to the fact this isn't supported. So raise a more appropriate error
pointing to what to change.
2024-02-13 14:47:43 -05:00
Yasuo Honda
6e7ef7d61c
Merge pull request #51037 from fatkodima/fix-deprecated-enum-syntax-tests
Fix deprecated `enum` syntax in tests
2024-02-13 21:37:23 +09:00
Petrik de Heus
a42ca9cf14
Merge pull request #51049 from sobstel/main
[DOCS] Warn against uniqueness validator when create_or_find_by is used [ci-skip]
2024-02-13 07:45:59 +01:00
Przemek Sobstel
a42eda12da doc: Warn against having uniqueness validator when create_or_find_by is used
Co-authored-by: Petrik de Heus <petrik@deheus.net>
2024-02-13 07:23:58 +01:00
Yasuo Honda
e4f1c8758c
Merge pull request #50962 from joshuay03/update-has-one-create-test-descriptions
Update some create `has_one` failure test descriptions
2024-02-13 10:07:04 +09:00
maximerety
d997c554b3
[Fix #50604] Restore compatibility of ARE configs with eager loading mode
Configure ActiveRecord::Encryption (ARE) on ActiveRecord::Base (AR)
loading, so that ARE configs are ready before AR models start using
`encrypts` to declare encrypted attributes.

This means that you can add ARE configurations in initializers, as long
as you don't trigger the loading of ActiveRecord::Base or your AR models
in prior initializers.
2024-02-12 17:57:56 +01:00
Nikita Vasilevsky
19a1680c17
Fix update_all/delete_all on CPK model relation with join subquery 2024-02-12 16:35:59 +00:00
Jean Boussier
a8d6d477c7
Merge pull request #50999 from Shopify/refactor-transactional-fixtures
Decouple transactional fixtures and active connections
2024-02-12 09:54:39 +01:00
Javier Aranda
a60039b8dc
Document that lock_version column is integer 2024-02-11 18:19:21 +01:00
Joshua Young
e61234dac7 Update create has_one failure test descriptions 2024-02-11 19:42:23 +10:00
fatkodima
93884c66d5 Fix deprecated enum syntax in tests 2024-02-10 12:42:54 +02:00
Hartley McGuire
8c5425197c
Deprecate defining enums with keywords args
Enums have historically been defined using keyword arguments:

```ruby
class Function > ApplicationRecord
  enum color: [:red, :blue],
       type: [:instance, :class],
       _scopes: false
```

This has the advantage of being able to define multiple enums at once
with the same options. However, it also has a downside that enum options
must be prefixed with an underscore to separate them from the enum
definitions (to enable models to have enums with the same name as an
option).

In Rails 7, a new syntax was [introduced][1] to instead define enums with
positional arguments:

```ruby
class Function > ApplicationRecord
  enum :color, [:red, :blue], scopes: false
  enum :type, [:instance, :class], scopes: false
```

This new syntax eliminates the need to prefix options with an underscore,
and the docs were updated to recommend this new syntax.

However, both versions of the API have been supported since, and it has
started to cause some problems:

The first issue is that the available options have drifted. In Rails
7.1, an option was added to make assigning an invalid enum value use
validation errors instead of runtime errors. However, the equivalent
underscored prefix option was not added for the original enum syntax

Articles have been created that describe the new option in Rails 7.1,
but the examples in the articles use un-prefixed options with the old
syntax. This confusion has also lead to issues opened asking why that
incorrect syntax is not working.

Additionally, the presence of underscored options is just generally
confusing because it tends to imply an option is for internal use.

This commit aims to fix all of these issues by deprecating the old enum
syntax. With only one way to define enums, options cannot drift and
there will be less confusion around how enums should be defined.

[1]: 0618d2d84a501aea93c898aec504ff9a0e09d6f2
2024-02-10 00:20:45 +00:00
Andrei Makarov
b55b5584d8
Add class name to enum validation exception message
Unify enum without column exception message

Update enum_test for new exception message
2024-02-09 22:57:52 +00:00
Jean Boussier
1dcb411429 Decouple transactional fixtures and active connections
Ref: https://github.com/rails/rails/pull/50793

Transactional fixtures are currently tightly coupled with the pool
active connection. It assumes calling `pool.connection` will memoize
the checked out connection and leverage that to start a transaction
on it and ensure all subsequent accesses will get the same connection.

To allow to remove checkout caching (or make it optional), we first
must decouple transactional fixtures to not rely on it.

The idea is to behave similarly, but store the connection in
the pool as a special "pinned" connection, and not as the regular
active connection.

This allows to always return the same pinned connection,
but without necessarily assigning it as the active connection.

Additionally, this pinning impact all threads and fibers, so
that all threads have a consistent view of the database state.
2024-02-09 12:59:40 +01:00
Jean Boussier
29fe34486d Make various minor fixes to the Active Record test suite
Extracted from: https://github.com/rails/rails/pull/50999

- Make fixtures setup and teardown methods private.
- Don't run adapter thread safety tests with sqlite3_mem
- Make foreign_key_tests more resilient to leaked state
- Use `exit!` in fork to avoid `at_exit` side effects.
- Disable transactional fixtures in tests that do a lot of low level
  assertions on connections or connection pools.
2024-02-09 10:01:45 +01:00
Jean Boussier
bfcfede66a
Merge pull request #50983 from fatkodima/fix-counter-caches-for-cpk
Fix counter caches to work for models with composite primary keys
2024-02-09 08:16:51 +01:00
John Hawthorn
48856482c8 Remove memoization of key provider
This is necessary to allow key_provider to be changed dynamically using
with_encryption_context.

Co-authored-by: Kyle Stevens <kstevens715@gmail.com>
2024-02-08 14:47:25 -08:00
Adrianna Chang
06b7e345af
Add active_record.config.validate_migration_timestamps config option.
When set, an `ActiveRecord::InvalidMigrationTimestampError` will be raised if the timestamp
prefix for a migration is more than a day ahead of the timestamp associated with the current time.
This is done to prevent forward-dating of migration files, which can impact migration generation
and other migration commands.

It is turned off by default, but will be turned on for applications starting in Rails 7.2.
2024-02-08 12:14:26 -05:00
fatkodima
ea3804835c Fix counter caches to work for models with composite primary keys 2024-02-08 18:59:39 +02:00
Jean Boussier
257c6306b5
Merge pull request #51012 from Shopify/fix-thread-safety-in-mysql-adapters
Properly synchronize `Mysql2Adapter#active?` and `TrilogyAdapter#active?`
2024-02-08 15:10:16 +01:00
Jean Boussier
6f3b46b02d Properly synchronize Mysql2Adapter#active? and TrilogyAdapter#active?
As well as `disconnect!` and `verify!`.

This generally isn't a big problem as connections must not be shared between
threads, but is required when running transactional tests or system tests
and could lead to a SEGV.
2024-02-08 15:01:26 +01:00
Jean Boussier
26de25d7ee Gracefully handle transactional fixtures leaks
Extracted from: https://github.com/rails/rails/pull/50999

Some tests may use the connections in ways that cause the fixtures
transaction to be committed or rolled back. The typical case being
doing schema change query in MySQL, which automatically commits the
transaction. But ther eare more subtle cases.

The general idea here is to ensure our transaction is correctly
rolling back during teardown. If it fails, then we assume something
might have mutated some of the inserted fixtures, so we invalidate
the cache to ensure the next test will reset them.

This issue is particularly common in Active Record's own test suite
since transaction fixtures are enabled by default but we have
many tests create tables and such.

We could treat this case as an error, but since we can gracefully
recover from it, I don't think it's worth it.
2024-02-08 11:28:42 +01:00
Jean Boussier
bab4aa7cb2
Merge pull request #51001 from Shopify/fixtures-cache-key
Share already loaded fixtures across test classes
2024-02-07 19:10:38 +01:00
Jean Boussier
6ad3d0ed77 Share already loaded fixtures across test classes
`self.class` is a fairly narrow cache key, so it doesn't hit that much,
but more importantly, since nothing clears that cache, on large test
suites it keeps growing extremely large.

Using the list of fixtures as a cache key doesn't strictly solve
the growth issue, but most classes actually load all fixtures so
this should shrink the cache size considerably.
2024-02-07 17:45:32 +01:00
Jean Boussier
f7eb822856 Fix a reace condition in FutureResult#instrument
We must wait until the event is fully recorded before adding
it to the list, otherwise it might be flushed while incomplete.
2024-02-07 16:06:45 +01:00
Petrik
35bd5e0f55 Document ActiveRecord alias_attribute [ci-skip]
This documents how `alias_attribute` works, including for queries.
2024-02-07 10:47:07 +01:00
Jean Boussier
3e7ba58439 Delete EncryptionPerformanceTest
On my machine, running the whole Active Record test suite takes
`88` seconds, and `40` of these are spent in encryption tests.

Some of them also happen to flake because of random blips.

I appreciate the care that has been put into ensuring the overhead
of encrption was reasonable, but I don't think these tests justify
their cost.
2024-02-06 18:05:31 +01:00
Jean Boussier
d0d7425854 Speedup ConnectionPoolTests
Most of the time was spent waiting on the default 5 seconds
checkout timeout.

Reducing in for just these tests saves about 1 minute of run time
but more importantly saves me from trying to figure out if my
refactoring introduced a deadlock of some sort.

Before: `real	1m4.448s`

After: `real	0m6.395s`
2024-02-06 17:32:44 +01:00
Jean Boussier
b324c221e2 SQLite3AdapterTest: Stop leaking files in fixtures directory 2024-02-06 16:59:04 +01:00
fatkodima
a87668a238 Support :source_location tag option for query log tags 2024-02-06 00:52:57 +02:00
fatkodima
7c6b1f5de1
Merge pull request #50933 from 1060ki/update_docs_for_mysql_algorithm
[ci skip] [docs] Updated docs to indicate that mysql supports the algorithm
2024-02-02 12:02:52 +02:00
Tomoki Ichikawa
e07aecca93
[ci skip] [docs] Updated docs to indicate that mysql supports the algorithm 2024-02-02 10:38:18 +09:00
Carlos Antonio da Silva
e09e61af0d
Merge pull request #50936 from sato11/query-constraints-typo
Correct error in the document for `query_constraints` [ci-skip]
2024-02-01 13:44:43 -03:00
Junichi Sato
4dc86683a4
Correct error in the document for query_constraints [ci-skip]
The context of this example suggests what it really wants to
point to is `query_constraints` instead of `query_by`.

Also apply fixed-width font to the reference to the methods correctly.
2024-02-01 20:27:55 +09:00
Jean Boussier
6e2c2dbb7d Refactor QueryCacheTest
In preparation of an upcoming query cache refactor.

The main changes is to not test the clear caused by `cached { }`
and what's inside the block.
2024-02-01 11:07:22 +01:00
Thiago Araujo
4335bc9c31 simplify in_order_of documentation 2024-01-31 09:11:36 -07:00
Rafael Mendonça França
b16b5168af
Merge pull request #50922 from fatkodima/fix-loading-schema-cache-database_tasks-false
Fix loading schema cache when all databases have disabled database tasks
2024-01-30 19:19:54 -05:00
Tristan Starck
b0b481a7c4
Fix teardown callbacks (#50915)
* Switch ActiveSupport::TestCase teardown and setup callbacks to run in setup and teardown minitest lifecycle hooks.

Minitest provides `setup` and `teardown` lifecycle hooks to run code in. In general it is best practice to when defining your own test case class, to use `Minitest::TestCase.setup` and `Minitest::TestCase.teardown` instead of `before_setup` and `after_teardown`.

Per Minitest's Documentation on Lifecycle Hooks: https://docs.ruby-lang.org/en/2.1.0/MiniTest/Unit/LifecycleHooks.html
> before_setup()
> Runs before every test, before setup. This hook is meant for libraries to extend minitest. It is not meant to be used by test developers.

> after_teardown()
> Runs after every test, after teardown. This hook is meant for libraries to extend minitest. It is not meant to be used by test developers.

Since the `setup` and `teardown` ActiveSupport::TestCase callbacks are in essence user code, it makes sense to run during their corresponding Minitest Lifecycle hooks.

* Ensure test fixutres are torndown on errors in superclass after_teardown code.

By not adding wrapping the `teardown_fixtures` code, its possible that super raises an error and prevents the existing database transaction from rolling back.
`super` in general should only be calling `Minitest::Testcase.after_teardown` however, if another library were to override `Minitest::Testcase.after_teardown`, like the popular gem [rspec-mocks](https://github.com/rspec/rspec-mocks/blob/main/lib/rspec/mocks/minitest_integration.rb#L23) does, it causes all subsequent tests to retain any changes that were made to the database in the original test that errors.

* Remove unnecessary setup and teardown methods in tests

* update activesupport Changelog

* Fix linter issues in CHANGELOG

* fix tests with improper setup and teardown method definitions

* Fix final CHANGELOG lint

* Revert "Fix final CHANGELOG lint"

This reverts commit f30682eb629780862ccc63e1d3210dfe035e997e.

* Revert "fix tests with improper setup and teardown method definitions"

This reverts commit 1d5b88c8739695a4eed5c46924c9ffc6010353f5.

* Revert "Fix linter issues in CHANGELOG"

This reverts commit 60e89bd189cbcdf50d7e923a90ec5ebe1578a6e9.

* Revert "update activesupport Changelog"

This reverts commit 0f19bc324fec7a793cc34dcfede27017b5a24e46.

* Revert "Remove unnecessary setup and teardown methods in tests"

This reverts commit e5673f179ac01c814ab44017b97e7638aad6e775.

* Revert "Switch ActiveSupport::TestCase teardown and setup callbacks to run in setup and teardown minitest lifecycle hooks."

This reverts commit d08d92d86131d8643a275397d9b0c15995730a14.

* Rescue Minitest::Assertion errors in ActiveSupport::TestCase.teardown callback code to ensure all other after_teardown methods are called.

* Fix name of test class

* remove unused MyError class

* Fix module to not be in global namespace

Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
2024-01-30 19:05:18 -05:00
fatkodima
b8585b3b3a Fix loading schema cache when all databases have disabled database tasks 2024-01-30 13:49:05 +02:00
Jean Boussier
ad81c30859 More efficiently reset inspect implementation
Not that `inspect` is anywhere close to be a hostspot, but just
to not allow a less defficient pattern.

Instead of allocating an UnboundMethod and bind_call it, we can
directly replace the method.
2024-01-30 08:34:22 +01:00
Donal McBreen
8c3d4f2b24
Allow encryption without compression
Add a `compress` option to ActiveRecord::Encryption::Encryptor, which
defaults to `true`. When set to `false`, the encryptor will never
compress the data.

This is useful for cases where the data is already compressed.

This can be used with the `encryptor` option in the model:

```ruby
class Record < ApplicationRecord
  encrypts :field, encryptor: ActiveRecord::Encryption::Encryptor.new(compress: false)
end
```
2024-01-29 18:50:46 +00:00
Rafael Mendonça França
de645c6794
Change HashConfig documentation to be markdown 2024-01-29 18:18:16 +00:00
Rafael Mendonça França
4d1d7d3d1b
Unify the logic to determine the default schema cache path for a database configuration
When the application has more than one database configuration, only
the primary was being loaded by default on boot time. All the other
connection pools were loading the schema cache lazily.

This logic can be found in:

351a8d9bc9/activerecord/lib/active_record/connection_adapters/pool_config.rb (L13)
351a8d9bc9/activerecord/lib/active_record/railtie.rb (L149-L178)

The lazy code path wasn't using the same logic to determine the name
of the default schema cache file that the Railties uses, so it
was loading the schema cache of the primary config to all the other
configs. If no table name coincided nothing bad would happen, but if
table names coincided, the schema would be completly wrong in all
non-primary connections.
2024-01-29 18:18:15 +00:00
Rafael Mendonça França
1cf7025b4d
Allow passing a DatabaseConfig object to cache_dump_filename 2024-01-29 18:18:13 +00:00
Rafael Mendonça França
e3efad939d
Fix documentation for DatabaseConfigurations::HashConfig#initialize 2024-01-29 18:18:00 +00:00
Rafael Mendonça França
e7073e4c95
Merge pull request #50887 from marvin-bitterlich/marvin.bitterlich/result-set
Add row_count field to sql.active_record notification
2024-01-29 13:02:16 -05:00
Marvin Bitterlich
e9a2288c13
Add row_count field to sql.active_record notification
This field returns the amount of rows returned by the query that emitted the notification.    
This metric is useful in cases where one wants to detect queries with big result sets.
2024-01-27 00:12:19 +00:00
Daniel Colson
adfdbf8c29
Clean up trilogy error translation
This commit makes a few changes to our trilogy error translation:

* https://github.com/trilogy-libraries/trilogy/pull/118 introduced
  `Trilogy::EOFError` which we can use instead of matching on
  `TRILOGY_CLOSED_CONNECTION`.
* https://github.com/trilogy-libraries/trilogy/pull/15 introduced
  `Trilogy::ConnectionClosed`, which inherits from `IOError` for
  backwards compatibility. As far as I can tell that's the only
  `IOError` trilogy can raise, so this commit rescues the
  trilogy-specific error instead.
* As far as I can tell Trilogy does not raise `SocketError`, so don't
  bother translating that
* Don't treat TRILOGY_UNEXPECTED_PACKET as a connection error. If we get
  this, it's probably a bug in trilogy that we should fix. I'd like to
  eventually get rid of TRILOGY_INVALID_SEQUENCE_ID too, but we're
  currently relying on it in a few tests (related to trilogy missing
  caching_sha2_password auth support, if I recall correctly)

I'm kinda hoping we'll eventually be able to simplify this to something
like:

```rb
if exception.is_a?(Trilogy::ConnectionError)
  ConnectionFailed.new(message, connection_pool: @pool)
else
  super
end
```

but we'd need more changes to trilogy before that is possible.
2024-01-26 12:59:10 -05:00
Daniel Colson
c616fe29be
Move server shutdown translation to abstract mysql
1053 is the server shutdown error code. We see these fairly often at
GitHub when, for example, shutting down Vitess vtage processes for
maintenance. Translating the error to `ConnectionFailed` allows us to
treat these as retryable connection error, so we can reconnect and hit a
new vtage process.

This is all true regardless of whether the adapter is trilogy or mysql2
or whatever, so this commit moves the translation out into the abstract
mysql adapter.
2024-01-25 12:31:46 -05:00
Jean Boussier
808b052572
Merge pull request #50845 from Shopify/fix-composite-primary-key-association-eager-load
Fix eager loading of composite primary key associations
2024-01-25 16:47:30 +01:00
Jean Boussier
6ee0041ed2 Refactor Module#delegate inside ActiveSupport::Delegation
This allow to support some extra private features without exposing
them in `Module#delegate`.
2024-01-25 11:51:00 +01:00
Nikita Vasilevsky
605d910194
Fix eager loading of composite primary key associations
Co-Authored-By: Christine Belan <christine.belan@shopify.com>
2024-01-24 17:25:03 +00:00
Petrik de Heus
c7551d08fc
Merge pull request #50836 from p8/activerecord/fix-query-logs-rdoc
Specify RDoc method name for accessors defined on singleton_class [ci-skip]
2024-01-24 13:03:43 +01:00
Aaron Patterson
84130af8b5
Don't mutate row arrays that come back from the database adapter
In SQLite3-Ruby version 2.0, I would like to make row arrays frozen. I
tested the change, and it only breaks this test, so I'm changing the
test. I don't think we should be mutating the objects that the database
adapter returns
2024-01-23 16:33:04 -08:00
Daniel Colson
6616770ec9
Translate Trilogy syscall errors as conn failed
At GitHub we get a fair number of Trilogy `ETIMEDOUT` errors (for known
reasons that we might be able to improve somewhat, but I doubt we'll
make them go away entirely). These are very much retryable network
errors, so it'd be handy if these `ETIMEDOUT` errors were translated to
`ConnectionFailed` instead of `StatementInvalid`, making them
`retryable_connection_error`s.

ed2bc92b82/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb (L1077)

We're already translating `ECONNRESET` (via matching on the error
message) and `EPIPE` to `ConnectionFailed`. Rather than adding another
case, this commit treats all of the Trilogy `SystemCallError` subclasses
as `ConnectionFailed`.

This requires bumping trilogy 2.7 so we can get
https://github.com/trilogy-libraries/trilogy/pull/143
2024-01-23 16:20:02 -05:00
Deepak Chauhan
83033a4af5 [ci skip] fixed rubocop spacing issue 2024-01-24 01:16:09 +05:30
Deepak Chauhan
35b3940432 Document autosave validation behavior 2024-01-24 00:53:01 +05:30
Petrik
db6eb7b72c Specify singleton method name for accessors defined on singleton_class [ci-skip]
RDoc can't extract the name of accessors defined with
`singleton_class.attr_accessor`, resulting in methods called `unknown`
in RDoc.
2024-01-22 12:34:07 +01:00
Petrik de Heus
fe81d667a7
Merge pull request #50789 from p8/docs/relative-includes
Use relative includes of README's in documentation [ci-skip]
2024-01-21 18:30:07 +01:00
Sean Doyle
68013b30d2 Infer :inverse_of for has_many ..., through:
Closes [#49574][]

Issue #49574 outlines how an Active Record join model accessed through a
`has_many ..., through:` association is unable to infer an appropriate
`:inverse_of` association by pluralizing a predictably pluralizable
class name.

This commit resolves that issue by also checking a model's reflections
for a pluralized inverse name in addition to whatever's provided through
the `:as` option or inferred in the singular.

The issue shares a code sample:

```ruby
ActiveRecord::Schema.define do
  create_table "listings", force: :cascade do |t|
    t.bigint "list_id", null: false
    t.bigint "pin_id", null: false
  end

  create_table "lists", force: :cascade do |t|
  end

  create_table "pins", force: :cascade do |t|
  end
end

class Pin < ActiveRecord::Base
  has_many :listings
end

class List < ActiveRecord::Base
  has_many :listings
  has_many :pins, through: :listings
end

class Listing < ActiveRecord::Base
  belongs_to :list
  belongs_to :pin
end

class BugTest < Minitest::Test
  def test_association_stuff
    list = List.create!
    pin = list.pins.new

    pin.save!

    assert_equal [pin], list.reload.pins
    assert_equal 1, list.reload.pins.count
  end
end
```

Unfortunately, there isn't a one-to-one mapping in the test suite's
`test/model` directory for this type of structure. The most similar
associations were between the `Book`, `Subscription`, and `Subscriber`.
For the sake of ease, this commit wraps the test block in a new
`skipping_validations_for` helper method to ignore validations declared
on the `Subscription` join table model.

[#49574]: https://github.com/rails/rails/issues/49574
2024-01-21 10:25:46 -05:00
Jean Boussier
9f52c45b18
Merge pull request #50308 from fatkodima/refactor-loaded-batches
Small refactoring of batching over loaded relation
2024-01-21 09:13:43 +01:00
Thiago Araujo
178b5da09a Add more examples to #in_order_of [ci-skip]
Adds more examples to `#in_order_of`:
- what happens when dealing with `enum` +columns+
- what happens when passing `nil` as a +value+ for nullable columns
2024-01-20 17:10:13 -07:00
Jean Boussier
2ddbca3e6a
Merge pull request #50809 from Shopify/freeze-cached-strings
Freeze and dedup `quote_column_name` and `quote_table_name` caches
2024-01-19 15:23:55 +01:00
Jean Boussier
9d4a44d049 Freeze and dedup quote_column_name and quote_table_name caches
Avoid corrupting the cache by mutating the return value, and also
sligthly reduce memory usage when the quoting format often return
an unmodified string.
2024-01-19 12:42:02 +01:00
Joshua Young
1eab83a0a8 [Fix #50803] Consistently raise an ArgumentError when passing an invalid argument to a nested attributes association writer 2024-01-19 20:34:33 +10:00
Nikita Vasilevsky
24570678d6
[Tests only] Expand trigger populated PK test case to run against more DBs 2024-01-18 17:28:12 +00:00
Eileen M. Uchitelle
33aa383c20
Merge pull request #50783 from Shopify/append-pk-to-returning-columns-if-returning-is-empty
Always request `primary_key` in `RETURNING` if no other columns requested
2024-01-18 11:45:40 -05:00
Petrik
8565f45100 Use relative includes of README's in documentation [ci-skip]
The Rails documentation uses the `:include:` directive to inline the
README of the framework into the main documentation page. As the
README's aren't in the root directory from where SDoc is run we need to
add the framework path to the include:

    # :include: activesupport/README.md

This results in a warning when installing the gems as generating the rdoc for the gem is run from the gem/framework root:

    Couldn't find file to include 'activesupport/README.rdoc' from lib/active_support.rb

The `:include:` RDoc directive supports includes relative to the current
file as well:

    # :include: ../README.md

This makes sure it works for the Rails API docs and the separate gems.

Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
2024-01-18 10:39:15 +01:00
fatkodima
63ad11ab20 Fix async queries to work with query cache and other cached async queries 2024-01-17 21:32:14 +02:00
Nikita Vasilevsky
c2c861f98a
Always request primary_key in RETURNING if no other columns requested
Prior 7.1 Rails always included `primary_key` in `RETURNING` clause on
record creation. This was changed in 7.1 to include more auto-populated
columns if such columns exist. This change lead to situations where
no columns were requested in `RETURNING` clause, even the `primary_key`.

This change brings back the old behavior of always requesting the
`primary_key` in `RETURNING` clause if no other columns are requested.
2024-01-17 18:19:40 +00:00
Yash Kapadia
0702c24e7b Fix single quote escapes on default generated MySQL columns
MySQL 5.7.5+ supports generated columns, which can be used to create a column that is computed from an expression. This commit fixes the escaping of the default value for such expressions if a single quote is included.

See the following for more: https://dev.mysql.com/blog-archive/generated-columns-in-mysql-5-7-5/
2024-01-17 07:12:27 -05:00
Hartley McGuire
327f28b65f
Fix t.references validating options on Rails < 7.1
Option validation was [added][1] for 7.1+ Migration classes, and a
compatibility layer was added to ensure that previous Migration versions
do not have their options validated. However, the `t.references` method
was missing in the compatibility layer which results in pre 7.1
Migrations validating options passed to `t.references`.

This commit fixes the issue by adding t.references to the compatibility
layer.

See also a [similar fix][2] for `add_reference`

[1]: e6da3ebd6c65af23d134a9e01145f26600912008
[2]: 71b4e223018d180b7c96915c0df1c28afbf7cc53
2024-01-16 17:21:22 -05:00
Rafael Porras Lucena
a88ee05fe0
Fix calculation of SQL runtime 2024-01-16 16:16:41 +01:00
Jean Boussier
946e46ebcc Modernize method missing implementations
`...` is both simpler an more correct since the keyword argument
separation.
2024-01-16 13:17:45 +01:00
Hartley McGuire
71b4e22301
Fix add_reference options validated on < 7.1
Option validation was [added][1] for 7.1+ Migration classes, and
a compatibility layer was added to ensure that previous Migration
versions do not have their options validated. However, the add_reference
method was missing in the compatibility layer which results in pre 7.1
Migrations validating options passed to add_reference.

This commit fixes the issue by adding add_reference to the compatibility
layer. In addition to adding add_reference to the "no validation"
compatibility test, the test is refactored to run against each previous
migration version to ensure that they all behave consistently.

[1]: e6da3ebd6c65af23d134a9e01145f26600912008
2024-01-15 20:52:49 +00:00
Rafael Mendonça França
af2bbd5f66
Merge pull request #46383 from dmytro-savochkin/fix-activerecord-reload-association-cache
Ensure `reload` sets correct owner for each association (ActiveRecord::Persistence)
2024-01-15 15:48:25 -05:00
JP Rosevear
b3fecab5c0
Merge branch 'main' into feature/delegated-type-types-introspection 2024-01-15 12:46:59 -05:00
Jean Boussier
2cd568a5da Handle alternative base classes in define_attribute_methods
Ref: d429bfb3b6 (r136670440)
2024-01-15 17:20:56 +01:00
Jean Boussier
63631e2d5b Make schema_dump, query_cache, replica and database_tasks configurable via DATABASE_URL
Fix: https://github.com/rails/rails/pull/50745

I went a bit farther and handled all the boolean configs, not just `schema_cache`.

Co-Authored-By: Mike Coutermarsh <coutermarsh.mike@gmail.com>
2024-01-15 15:51:31 +01:00