Commit Graph

23779 Commits

Author SHA1 Message Date
Rafael Mendonça França a8a848d76e
Don't enable automatically_invert_plural_associations by default
This can cause a lot of issues that are hard to detect.

It is better to make this opt-in for people that want to use it.

In Rails 8 we can revisit if we want to enable this config by default.
2024-05-23 19:15:01 +00:00
Rafael Mendonça França 43e4916483
Merge pull request #51891 from flavorjones/flavorjones-update-sqlite3-test-messages
update sqlite3 adapter tests to accept error messages from v3.46.0
2024-05-23 12:26:05 -04:00
Rafael Mendonça França 7ee34d9efb
Enable Rails minitest plugin in our rake tasks 2024-05-23 16:16:37 +00:00
Florin Oltean 372d327b91 Make pretty_print behave more similar to inspect. 2024-05-23 18:11:13 +02:00
Mike Dalessio b2660d6f45
update sqlite3 adapter tests to accept error messages from v3.46.0
Upstream sqlite updated the error messages to be more descriptive
starting in v3.46.0. Where the error message might look like this in
earlier versions:

    no such column: non_existent

in 3.46.0 it looks like:

    no such column: "non_existent" - should this be a string literal in single-quotes?

The tests have been updated to accept either style of message.

The sqlite3-ruby gem will release a version with this vendored version
shortly, see https://github.com/sparklemotion/sqlite3-ruby/pull/536
2024-05-23 11:50:52 -04:00
zzak d4150ab5cb
Revert "Merge pull request #51184 from ConfusedVorlon/document_after_commit_deduplication"
This reverts commit 2abee307fe, reversing
changes made to e34a0eec38.

A warning on each method is excessive and the warning should already be covered under the guide:
https://edgeguides.rubyonrails.org/active_record_callbacks.html#transaction-callbacks
2024-05-23 20:09:09 +09:00
Joshua Young 0516eafda2 [Fix #51720] Infer association klass as top level if model has same demodularized name 2024-05-23 08:04:57 +09:00
eileencodes bd04126e79
Fix typo 2024-05-21 19:06:44 -04:00
eileencodes 227c590d02
Add test and fix changelog for `schema_cache_ignored_table?` 2024-05-21 15:37:38 -04:00
eileencodes e815c6663a
Make public method for `schema_cache_ignored_tables?`
Previously we only provided a method to set the ignored schema cache
tables, but there was no way to ask if a table was ignored by the schema
cache. Applications may want to implement their own schema cache, or at
least run this check. Rather than forcing them to implement an internal
method, this adds a way to ask whether a table is ignored by the schema
cache code.

Usage:

```ruby
ActiveRecord.schema_cache_ignored_tables = ["developers"]
ActiveRecord.schema_cache_ignored_tables?("developers")
```
2024-05-21 14:42:25 -04:00
Xavier Noria 1b534a4d10 ActiveRecord -> Active Record 2024-05-21 14:24:28 +02:00
fatkodima 0318c34cb3 Fix non-partial inserts for models with composite identity primary keys 2024-05-18 12:08:33 +03:00
Yasuo Honda b708a1b9dd Address `Layout/IndentationWidth` cop offenses
This commit addresses RuboCop offenses reported at
https://buildkite.com/rails/rails/builds/107320#018f8835-b770-4068-9b97-0aec28c7ddb3

- Offenses are addressed by RuboCop auto correction as follows
```
$ bundle exec rubocop -a activerecord/test/cases/connection_adapters/type_lookup_test.rb
Inspecting 1 file
C

Offenses:

activerecord/test/cases/connection_adapters/type_lookup_test.rb:91:9: C: [Corrected] Layout/IndentationWidth: Use 2 (not 3) spaces for indentation.
           %w{decimal(2) decimal(2,0) numeric(2) numeric(2,0) number(2) number(2,0)}.each do |type|
        ^^^
activerecord/test/cases/connection_adapters/type_lookup_test.rb:92:11: C: [Corrected] Layout/IndentationWidth: Use 2 (not 3) spaces for indentation.
             cast_type = @connection.send(:type_map).lookup(type)
          ^^^
activerecord/test/cases/connection_adapters/type_lookup_test.rb:94:14: C: [Corrected] Layout/IndentationConsistency: Inconsistent indentation detected.
             assert_equal :decimal, cast_type.type
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
activerecord/test/cases/connection_adapters/type_lookup_test.rb:95:14: C: [Corrected] Layout/IndentationConsistency: Inconsistent indentation detected.
             assert_equal 2, cast_type.cast(2.1)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 4 offenses detected, 4 offenses corrected
$
```

Follow up #51826
2024-05-18 07:49:08 +09:00
Rafael Mendonça França d0ce794e2d
Merge pull request #51442 from rosa/skip-deprecation-warning-for-invalid-reflections
Emit deprecation warning about inverse_of inference only for valid reflections
2024-05-17 16:38:06 -04:00
Rafael Mendonça França 59eb4f49a0
Merge pull request #51826 from Shopify/remove-oracle-sqlserver-from-tests
Remove oracle sqlserver from tests
2024-05-17 16:18:30 -04:00
Joé Dupuis 478874ae1b
Add `active_record.postgresql_adapter_decode_dates`
to toggle automatic decoding of dates column with the
PostgresqlAdapter.

PR #51483 is a breaking change and should have been gated behind a
config.
2024-05-15 18:38:08 +00:00
Andrew Novoselac de7bf12e46 Remove support for SQLServerAdapter, OracleAdapter and JBDC adapters in tests
As of rails/rails@8eae753 we are no longer supporting these and do not need to test them.
2024-05-14 14:56:16 -04:00
Rafael Mendonça França 52b417bca6
This will be released in 7.2, not 8 2024-05-14 18:05:40 +00:00
Carlos Antonio da Silva 0be846c893
Merge pull request #51758 from taketo1113/fix-changed-cidr2
PostgreSQL Cidr#change? raise an error of NoMethodError: undefined method `prefix' for nil, when creating a record with an empty value of inet/cidr column.
2024-05-14 09:59:51 -03:00
Ryuta Kamizono 1b6b1a9cb9
Merge pull request #51788 from fatkodima/batch_enumerator-destroy_all-returns-rows-number
Change `BatchEnumerator#destroy_all` to return the total number of affected rows
2024-05-14 21:13:55 +09:00
Jean Boussier 4ca838b899 Eliminate `lease_connection` call in `cached_find_by`
Fix: https://github.com/rails/rails/issues/51811
2024-05-14 15:12:12 +09:00
Jean Boussier db4dba78c9 Only serialize associations that were loaded
Fix: https://github.com/rails/rails/issues/51807

`association_cached?` only means the Association object was
created, not that the records were loaded.

Co-Authored-By: benk-gc <bkyriakou@gocardless.com>
2024-05-14 09:37:23 +09:00
Taketo Takashima c395b99f11 Fix PostgreSQL Cidr#change?: NoMethodError: undefined method `prefix` for nil 2024-05-14 08:43:51 +09:00
fatkodima 94af7c181a Change `BatchEnumerator#destroy_all` to return the total number of affected rows 2024-05-13 22:54:25 +03:00
Ryuta Kamizono 36885949a9
Merge pull request #51787 from fatkodima/fix-touch_all-with-aliased-attribute-for-update
Fix `ActiveRecord::Relation#touch_all` with custom attribute aliased as attribute for update
2024-05-14 03:55:58 +09:00
Andrew Novoselac 5b91084f20 Remove support for oracle, sqlserver and JRuby specific database adapters from the new and db:system:change commands. The supported options are sqlite3, mysql, postgresql and trilogy. 2024-05-13 14:07:47 -04:00
Rafael Mendonça França bf59d363fb
Clean CHANGELOG for 8.0 2024-05-13 16:55:52 +00:00
Rafael Mendonça França 37fd0e7fe4
Development of Rails 8.0 starts now
🎉
2024-05-13 16:45:20 +00:00
Yasuo Honda d2cf718093
Merge pull request #51806 from yahonda/follow_up_51571
Use `foreign_key` option for destroy_async test models
2024-05-13 22:18:31 +09:00
Yasuo Honda 9a77052dee Use `foreign_key` option for destroy_async test models
This pull request replaces the deprecated `query_constraints:` option with `foreign_key` for destroy_async test models.
Follow up #51571

- This commit addresses these two warnings below:

```
% bin/test test/activejob/destroy_association_async_test.rb
Using sqlite3
DEPRECATION WARNING: Setting `query_constraints:` option on `Cpk::BookDestroyAsync.has_many :chapters` is deprecated. To maintain current behavior, use the `foreign_key` option instead. (called from new at /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:19)
/Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:19:in `new'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:19:in `create'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/associations/builder/association.rb:50:in `create_reflection'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/associations/builder/association.rb:32:in `build'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/associations.rb:1531:in `has_many'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/models/cpk/book_destroy_async.rb:7:in `<class:BookDestroyAsync>'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/models/cpk/book_destroy_async.rb:4:in `<module:Cpk>'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/models/cpk/book_destroy_async.rb:3:in `<top (required)>'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `require'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `block (2 levels) in replace_require'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/activejob/destroy_association_async_test.rb:27:in `<top (required)>'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `require'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `block (2 levels) in replace_require'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:61:in `block in load_tests'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:60:in `each'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:60:in `load_tests'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:52:in `run'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/support/tools.rb:37:in `<top (required)>'
  bin/test:11:in `require_relative'
  bin/test:11:in `<main>'
DEPRECATION WARNING: Setting `query_constraints:` option on `Cpk::ChapterDestroyAsync.belongs_to :book` is deprecated. To maintain current behavior, use the `foreign_key` option instead. (called from new at /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:19)
/Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:19:in `new'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:19:in `create'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/associations/builder/association.rb:50:in `create_reflection'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/associations/builder/association.rb:32:in `build'
  /Users/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/associations.rb:1910:in `belongs_to'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/models/cpk/chapter_destroy_async.rb:8:in `<class:ChapterDestroyAsync>'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/models/cpk/chapter_destroy_async.rb:4:in `<module:Cpk>'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/models/cpk/chapter_destroy_async.rb:3:in `<top (required)>'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `require'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `block (2 levels) in replace_require'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/activejob/destroy_association_async_test.rb:28:in `<top (required)>'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `require'
  /Users/yahonda/.rbenv/versions/3.3.1/lib/ruby/3.3.0/bundled_gems.rb:74:in `block (2 levels) in replace_require'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:61:in `block in load_tests'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:60:in `each'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:60:in `load_tests'
  /Users/yahonda/src/github.com/rails/rails/railties/lib/rails/test_unit/runner.rb:52:in `run'
  /Users/yahonda/src/github.com/rails/rails/activerecord/test/support/tools.rb:37:in `<top (required)>'
  bin/test:11:in `require_relative'
  bin/test:11:in `<main>'
Run options: --seed 24461

....................

Finished in 0.199597s, 100.2019 runs/s, 370.7471 assertions/s.
20 runs, 74 assertions, 0 failures, 0 errors, 0 skips
%
```
2024-05-13 21:55:43 +09:00
Jean Boussier ed2c15b524 Move `ActiveRecord::Base.insert` in `Relation`
Ref: https://github.com/rails/rails/pull/50396

As well as related methods.
2024-05-13 15:52:02 +09:00
Jean Boussier 8f419e482b Move `ActiveRecord::Base.destroy` in `Relation`
Ref: https://github.com/rails/rails/pull/50396
2024-05-13 15:52:02 +09:00
Jean Boussier 5e1d07dff4 Move `ActiveRecord::Base.delete` in `Relation`
Ref: https://github.com/rails/rails/pull/50396
2024-05-13 15:52:02 +09:00
Jean Boussier 135af7ba28
Merge pull request #51803 from akhilgkrishnan/fix-batch-test
Fix: batch test assertion order
2024-05-13 15:21:37 +09:00
Akhil G Krishnan 75bdf05d87 Fix: batch test assertion order
Co-authored-by: Chedli Bourguiba <chaadow@users.noreply.github.com>
2024-05-13 08:10:51 +05:30
Jean Boussier c08c2efda2 Refactor `ActiveRecord::TokenFor` to not rely on relation delegation
Ref: https://github.com/rails/rails/pull/50396
Ref: https://github.com/rails/rails/pull/51776

`ActiveRecord::Relation` automatically delegates missing methods
to the model class wrapped in a `scoping { }` block.

This is to support scoping in user defined class methods. The problem
however is that it's very error prone for the framework, because we
can mistakenly call model methods from inside `Relation` and not
realized we're applying a global scope.

In the best case scenario it's just a waste of performance, but
it can also lead to bugs like https://github.com/rails/rails/issues/51775

I'm planning to restrict this automatic delegation to methods defined
in childs of `ActiveRecord::Base` only: https://github.com/rails/rails/pull/50396
but for this to work we must first refactor any Rails code that rely on it.
2024-05-13 11:28:15 +09:00
Jean Boussier c6d0ef5974 Refactor `ActiveRecord::SignedId` to not rely on relation delegation
Ref: https://github.com/rails/rails/pull/50396
Ref: https://github.com/rails/rails/pull/51776

`ActiveRecord::Relation` automatically delegates missing methods
to the model class wrapped in a `scoping { }` block.

This is to support scoping in user defined class methods. The problem
however is that it's very error prone for the framework, because we
can mistakenly call model methods from inside `Relation` and not
realized we're applying a global scope.

In the best case scenario it's just a waste of performance, but
it can also lead to bugs like https://github.com/rails/rails/issues/51775

I'm planning to restrict this automatic delegation to methods defined
in childs of `ActiveRecord::Base` only: https://github.com/rails/rails/pull/50396
but for this to work we must first refactor any Rails code that rely on it.
2024-05-13 11:07:01 +09:00
fatkodima e057037c72 Support `touch_all` in batches 2024-05-13 09:23:57 +09:00
Sampat Badhe a44fbb11a3
Correct typo in activerecord changelog [ci skip]
Correct typo in activerecord changelog for -https://github.com/rails/rails/pull/50662
2024-05-12 10:43:00 +05:30
fatkodima 47f25b268a Add support for `:if_not_exists` and `:force` options to `create_schema` 2024-05-11 16:40:20 +03:00
fatkodima 5dcc35b6e1 Fix `ActiveRecord::Relation#touch_all` with custom attribute aliased as attribute for update 2024-05-11 14:14:44 +03:00
Jean Boussier 4bd4fcc85d Fix `.with_connection` to not set current scope
Fix: https://github.com/rails/rails/issues/51775

This us us being bitten by https://github.com/rails/rails/pull/50396
once more. We should really make this delegation much stricter.
2024-05-10 10:02:05 +02:00
lulalala 1c26a39f15 Fix test
It seems now attribute being base should always be part of the key
2024-05-09 23:45:29 +08:00
lulalala 0a36c36dd8 Add index_errors: :nested_attributes_order mode
which respects reject_if and is in nested_attributes order.

When in default index_errors:true mode,
fix #24390 and return index based on full association order.
2024-05-09 20:03:53 +08:00
Nikita Vasilevsky 9cadf61835
Warn about changing `query_constraints:` behavior
This commit adds a deprecation warning for the `query_constraints:`
association option. This option will change behavior in the future versions
of Rails and applications are encouraged to switch to `foreign_key:` to preserve the
current behavior.
2024-05-08 20:08:09 +00:00
Carlos Antonio da Silva 59064f88d8 Remove extraneous array wrapping
We're already conditioning `reflection_fk` based on whether it's an
`Array` or not, so no need to wrap it in this `Array()` call since in
this block it is sure to be an `Array`.

Ref.: d7980c6b10
2024-05-07 09:54:05 -03:00
Jean Boussier 06968f81b3 Reduce allocations in BelongsToAssociation#replace_keys
Using the same benchmark as in https://github.com/rails/rails/pull/51726

`replace_keys` always allocate a multiple arrays to support composite
primary keys, even though most primary keys likely aren't composite.

And even when they are, we can avoid needless allocations by not using
`Array#zip`.

This reduce allocations by 18% (8k) on that benchmark.

Before:

```
Total allocated: 4.88 MB (44495 objects)
Total retained: 4.16 MB (32043 objects)

allocated memory by file
-----------------------------------
...
 320.00 kB  activerecord/lib/active_record/associations/belongs_to_association.rb

allocated objects by file
-----------------------------------
...
      8000  activerecord/lib/active_record/associations/belongs_to_association.rb
```

After:

```
Total allocated: 4.56 MB (36495 objects)
Total retained: 4.16 MB (32041 objects)
```

NB: `belongs_to_association` doesn't show up in top files anymore
2024-05-07 12:43:17 +02:00
Jean Boussier bac70c3775
Merge pull request #51752 from Shopify/result-duplicated-column
Simplify `ActiveRecord::Result#hash_rows`
2024-05-07 12:07:01 +02:00
Jean Boussier 9652207c6b Simplify `ActiveRecord::Result#hash_rows`
Last big refactor was in https://github.com/rails/rails/pull/37614.
Somewhat extracted from https://github.com/rails/rails/pull/51744.

The concern about columns with the same name didn't make much sense
to me because in both code paths, the last one wins, so we can simplify
the whole methods.

Additionally by implementing `columns_index`, we have a decent template
always available.
2024-05-07 11:45:38 +02:00
David Heinemeier Hansson e8e077dd16
Add ENV["SKIP_TEST_DATABASE_TRUNCATE"] flag to speed up multi-process test runs (#51686) 2024-05-06 17:04:01 -07:00
maniSHarma7575 fd94a129d1 [FIX] Sqlite3 Should create db for missing parent directories as well 2024-05-06 16:04:20 +02:00
Jean Boussier 743763b860 Avoid allocating a column_type Hash when unnecessary
Only the Postgres provide these types, so no point allocating
a hash every time for other adapters.
2024-05-06 12:46:18 +02:00
Rafael Mendonça França 9ddb9e2f2d
Fix documentation
This method still returns string keys.
2024-05-03 17:06:06 +00:00
Jean Boussier d9a54e41ab Use symbols as keys for `_reflections`
Using a simple benchmark such as:

```ruby
Post.transaction do
  100.times do
    post = Post.create!(author_id: 42, title: "A" * 50, body: "a" * 400, tags: "blah blah blah", published_at: Time.now, comments_count: 20)
    20.times do
      post.comments.create!(author_id: 42, body: "a" * 120, tags: "blah blah blah", published_at: Time.now)
    end
  end
end

posts = Post.includes(:comments).to_a
```

This allocate `43,077` objects, and out of these `2,200` are caused by association
names being stored as strings internally:

```
Allocated String Report
-----------------------------------
  80.00 kB    2000  "post"
              2000  activerecord/lib/active_record/reflection.rb:123

   8.00 kB     200  "comments"
               200  activerecord/lib/active_record/reflection.rb:123
```

This is because many API accept either symbol or string, and blindly
call `to_s` on it. We could avoid this with sprinkling the code with
`Symbol == association ? association.name : association.to_s`, but it's
ugly.

This issue may be entirely solved in a future Ruby version, but
it will take years: https://bugs.ruby-lang.org/issues/20350

By using symbols, we both save allocations, and marginally speed up
lookups and comparisons, reducing this particular benchmark allocations
by 5%.

It's a bit unclear why these were ever made strings. Historically
symbols were immortal and using them for user supplied data could lead
to DOS vulnerability, so this may have been why, but it's not longer
a concern since Ruby 2.2.
2024-05-03 14:43:33 +02:00
Jean Boussier fa048105d1 Eliminate missed `lease_connection` calls
Followup: https://github.com/rails/rails/pull/51353
Fix: https://github.com/rails/rails/issues/51722

Not too sure what happened, but I somehow missed quite a number
of `lease_connection` calls inside Active Record.
2024-05-03 13:32:33 +02:00
Jean Boussier 087260d0fc
Merge pull request #51713 from Shopify/stale-state-casting
Don't cast `stale_state` to String
2024-05-02 16:59:02 +02:00
Jean Boussier 8ba2b7f92f
Merge pull request #51409 from fatkodima/fix-destroy_async-job-for-cpk
Fix `destroy_async` job for owners with composite primary keys
2024-05-02 16:57:50 +02:00
Jean Boussier 2cadcb2718 Don't cast `stale_state` to String
I'm looking at reducing the allocations and memory footprint
of Active Record models, and based on a small benchmark I saw
a lot of numeric strings being created from `stale_state`.

I tracked this cast all the way down to 1c07b84df9
but unfortunately the commit message doesn't explain why it was added.

I can't think of a reason why this would be needed.

The benchmark is essentially just: `Post.includes(:comments).to_a` with
`100` posts and `20` comments each.

```
Total allocated: 4.69 MB (45077 objects)
Total retained: 3.84 MB (29623 objects)

retained objects by location
-----------------------------------
...
      2000  activerecord/lib/active_record/associations/belongs_to_association.rb:152

retained memory by location
-----------------------------------
...
  80.00 kB  activerecord/lib/active_record/associations/belongs_to_association.rb:152
```

NB: This break the final assertion of the Rails 6.1 Marshal backward compatibility
test, but I think it's an acceptable tradeoff.
2024-05-02 14:36:34 +02:00
Ryuta Kamizono 2c79c87a19 WithChain does not exist in the codebase 2024-05-02 21:11:02 +09:00
nisusam e0b7136b3e Fix typo from Changelog [ci skip] 2024-05-02 17:23:21 +05:30
Claire fc26e44181 Add support for recursive CTE in Active Record
```ruby
Post.with_recursive(
  post_and_replies: [
    Post.where(id: 42),
    Post.joins('JOIN post_and_replies ON posts.in_reply_to_id = post_and_replies.id'),
  ]
)
```

Generates the following SQL:

```sql
WITH RECURSIVE "post_and_replies" AS (
  (SELECT "posts".* FROM "posts" WHERE "posts"."id" = 42)
  UNION ALL
  (SELECT "posts".* FROM "posts" JOIN post_and_replies ON posts.in_reply_to_id = post_and_replies.id)
)
SELECT "posts".* FROM "posts"
```
2024-05-02 12:32:27 +02:00
Cody Cutrer 5c5e8d2fd6 Pass validate(_check)_constraint through change_table 2024-05-01 15:33:37 -06:00
fatkodima 702638291c
Fix tests without assertions in the framework 2024-04-30 23:29:30 +00:00
Rafael Mendonça França 3e68225b72
Merge pull request #51685 from fffx/record_not_saved_doc
[Fix #51672] Update RDoc comments for  ActiveRecord::RecordNotSaved [ci skip]
2024-04-30 19:08:07 -03:00
Fangxing 541681b2d9 Update Doc for ActiveRecord::RecordNotSaved to be consistent 2024-04-30 23:32:14 +03:00
Jean Boussier 6a38d3ac6c
Merge pull request #51483 from JoeDupuis/add-date-text-decoder-postgresql-adapter
Add a Date decoder to the pg adapter
2024-04-30 13:32:07 +02:00
Ryuta Kamizono f963d4a7f2
Merge pull request #50487 from nubinary/fix/unneccesary-readonly-attributes-to-a
Remove unnecessary to_a conversion for readonly_attributes method call
2024-04-30 19:50:17 +09:00
Joé Dupuis 2c88c80fc7
Add a Date decoder to the pg adapter to type cast dates
at the connection level

Fix #51448

Type cast columns of type `date` to ruby `Date` when running a raw
query through `ActiveRecord::Base.connection.select_all`.
2024-04-29 19:16:18 -07:00
JP Rosevear 127808841b Remove unnecessary to_a conversion for readonly_attributes method call 2024-04-29 07:44:00 -04:00
fatkodima 74275accb8 Raise when a block is passed to `ActiveRecord::Relation#with` 2024-04-29 14:34:09 +03:00
fatkodima 0fbf30d328 Fix count queries on `includes+references` for models with composite primary keys 2024-04-24 14:14:37 +03:00
Yasuo Honda 3e156142bf
Merge pull request #51633 from taketo1113/fix-changed-cidr
Fix PostgreSQL `Cidr#change?` to compare with address prefix
2024-04-24 11:47:14 +09:00
André Guimarães Sakata f6cace4f83 Use Ruby's official documentation 2024-04-23 17:57:56 -03:00
Rafael Mendonça França ec4558ae9f
Merge pull request #50837 from fatkodima/fix-rename_table-for-indexes-7-0
Ensure pre-7.1 migrations use legacy index names when using `rename_table`
2024-04-23 14:06:31 -03:00
Taketo Takashima acc277b135 Fix PostgreSQL Cidr#change? when changed address prefix. Fix #51582
Update activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb

Co-authored-by: Yasuo Honda <yasuo.honda@gmail.com>

Updated to keep the argument order

Added note to remove `changed?` method when `IPAddr#==` compares `IPAddr#prefix`
2024-04-24 00:11:49 +09:00
Adrianna Chang 33a50ce65d
Join association built from string join should not retry 2024-04-23 09:07:29 -04:00
fatkodima 2c66b2a458 Ensure pre-7.1 migrations use legacy index names when using `rename_table` 2024-04-23 02:53:28 +03:00
Jean Boussier 0385029c9d SerializedAttributeTest: use decorate_attribute
Followup: https://github.com/rails/rails/pull/51608
2024-04-22 12:35:16 +02:00
Joshua Young 7861476d4f Encourage `#lease_connection` over `#connection` on AR model `#inspect` without connection 2024-04-21 20:43:45 +10:00
Rafael Mendonça França 339035c11e
Copy edit documentation 2024-04-19 20:16:53 +00:00
Rafael Mendonça França 5e4f2d3fd1
Merge pull request #50856 from Dmoment/docs-autosave-validations
Document autosave validation behavior for ActiveRecord associations [ci skip]
2024-04-19 17:10:42 -03:00
Rafael Mendonça França 4d1f4edcba
Refactor code to make it more clear
Extract the conditional to a method that explains what it needs to do.

Also avoid calling `present?`.
2024-04-19 19:17:01 +00:00
Jean Boussier 1083a9ca2c
Merge pull request #51609 from ClearlyClaire/fixes/arel-select-union-wrapping
Arel: only wrap SELECT statements in UNION if they involve ORDER BY, LIMIT or OFFSET
2024-04-19 16:19:05 +02:00
Claire 96bc0549b4 Arel: only wrap SELECT statements in UNION if they involve ORDER BY, LIMIT or OFFSET
This change was not compatible with the SQLite3 adapter, so revert it, except for
the specific cases where this actually fixed an issue.
2024-04-19 12:48:13 +02:00
Jean Boussier d5c88d68c3 Fix some more ignored block warnings
Ref: https://bugs.ruby-lang.org/issues/15554

A couple are harmless, but another couple found actual problems
in the test suite where we passed blocks to `assert_*` methods that
didn't expect one.
2024-04-19 10:23:42 +02:00
Reid Lynch 715276071f
Strict loading using `:n_plus_one_only` does not eagerly load child associations.
Before:

    ```ruby
    person = Person.find(1)
    person.strict_loading!(mode: :n_plus_one_only)
    person.posts.first
    # SELECT * FROM posts WHERE person_id = 1; -- non-deterministic order
    ```

    After:

    ```ruby
    person = Person.find(1)
    person.strict_loading!(mode: :n_plus_one_only)
    person.posts.first # this is 1+1, not N+1
    # SELECT * FROM posts WHERE person_id = 1 ORDER BY id LIMIT 1;
    ```

    Strict loading in `:n_plus_one_only` mode is designed to prevent performance issues when
    deeply traversing associations. It allows `Person.find(1).posts`, but _not_
    `Person.find(1).posts.map(&:category)`. With this change, child associations are no
    longer eagerly loaded, to match intended behavior and to prevent non-deterministic
    order issues caused by calling methods like `first` or `last`.
    Fixes #49473.
2024-04-19 00:05:13 +00:00
Rafael Mendonça França d60a23457c
Revert "Don't silently execute statements on migrations when they can't be reversed"
This reverts commit 5b04d448ab.

This is breaking more than it is fixing. We need to find a better way to
handle this.
2024-04-19 00:03:53 +00:00
Rafael Mendonça França aaa8e9fc30
Remove unused variable assignment in test 2024-04-18 23:10:17 +00:00
Rafael Mendonça França 5b04d448ab
Don't silently execute statements on migrations when they can't be reversed
Fixes #51570.
2024-04-18 23:00:57 +00:00
Rafael Mendonça França fd3a7a2dd2
Merge pull request #49774 from stevepolitodesign/sp-disable-inheritance
Improve STI documentation
2024-04-18 17:37:30 -03:00
Rafael Mendonça França c06888d8c3
Merge pull request #50826 from hexdevs/ta/document-in-order-of-with-enum
[docs] Add more examples to `#in_order_of` [ci-skip]
2024-04-18 14:46:40 -03:00
Mike Dalessio fd1c635d2f Allow sqlite3 to float to version 2 2024-04-18 11:34:24 +02:00
Jean Boussier 65cb5f80f1 TestCase#create_fixtures no longer takes a block 2024-04-17 14:29:18 +02:00
Jean Boussier b8460800aa
Merge pull request #51476 from marvinthepa/no_anonymous_block_parameter
Fix "no anonymous block parameter" in ruby 3.1
2024-04-16 23:58:24 +02:00
Mike Dalessio a8c55910b7
test: fix flaky schema dump test to prefer YAML to Marshal
Testing against upstream sqlite3 which returns frozen strings
demonstrates that Rails can't guarantee that the schema dumps will be
byte-for-byte reproducible when they're in Marshal format.
2024-04-16 17:26:09 -04:00
Ryuta Kamizono 778039b896
Merge pull request #51567 from kamipo/fix_remove_prefix_and_suffix
Fix `remove_prefix_and_suffix` in `ActiveRecord::SchemaDumper`
2024-04-15 05:13:22 +09:00
Ryuta Kamizono fe7eb07cf5 Fix `remove_prefix_and_suffix` in `ActiveRecord::SchemaDumper`
Accidentally `remove_prefix_and_suffix` in `ActiveRecord::SchemaDumper`
has broken due to table name prefix and suffix options is assigned to
unused `version` argument in `SchemaDumper#initialize` added in #51162.
2024-04-15 04:57:41 +09:00
fatkodima 31e62ff55e Fix SQL query example in `ActiveRecord::Base#ids` docs [skip ci] 2024-04-14 12:02:01 +03:00
fatkodima 82c02ef4d0 Allow `ActiveRecord::Base#pluck` to accept hash values 2024-04-13 21:39:36 +03:00
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 50515fb45f, 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 6dd1929b04.

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