Commit Graph

23066 Commits

Author SHA1 Message Date
Ryuta Kamizono 1b0ee9f3f6
Merge pull request #49149 from deepakmahakale/release_notes_7_1/merge_rewhere_deprecated
[skip ci] rewhere argument on #merge deprecated
2023-09-05 19:53:04 +09:00
Deepak Mahakale ba7def2e53 [skip ci] rewhere argument on #merge deprecated 2023-09-05 16:09:05 +05:30
Ryuta Kamizono cf10924421
Merge pull request #49146 from kamipo/generating_token_only_once
Generate secure token only once regardless of `on: :initialize` or `on: :create`
2023-09-05 19:24:26 +09:00
Ryuta Kamizono a10e7a9dc5 Fix test_generating_token_on_initialize_does_not_affect_reading_from_the_column 2023-09-05 18:31:05 +09:00
Ryuta Kamizono 2a73ef8d3b Fix a test added in #48912 to work on a model with `on: :initialize`
Since default behavior is still `on: :create`.
2023-09-05 18:25:19 +09:00
Ryuta Kamizono 4f2fa59734 Don't modify existing test model in a test case
It will affect to other tests.
2023-09-05 18:12:33 +09:00
Ryuta Kamizono 2df70ddb96 Generate secure token only once regardless of `on: :initialize` or `on: :create`
Follow-up to #47420.

Whereas the original behavior (`on: :create`) is invoked only once
before a record is persisted, the new behavior (`on: :initialize`) is
invoked not only new record but also persisted records.

It should be invoked only once for new record consistently.
2023-09-05 17:43:41 +09:00
Ryuta Kamizono 2fbb25b771
Merge pull request #49133 from fatkodima/fix-has_secure_token-when-not-selected-column
Fix `has_secure_token on: :initialize` when column is not selected
2023-09-05 15:25:16 +09:00
Ryuta Kamizono ca374bd9a3
Merge pull request #49136 from fatkodima/fix-counter-caches-var-modification
Fix in-place modification of shared `_counter_cache_columns` class attribute
2023-09-05 15:07:52 +09:00
fatkodima 2933e16528 Fix in-place modification of shared `_counter_cache_columns` class attribute 2023-09-04 19:32:48 +03:00
fatkodima 72e3a3c9c1 Fix `assert_deprecated` related warnings in ActiveRecord tests 2023-09-04 16:25:20 +03:00
fatkodima 32f43176bb Fix `has_secure_token on: :initialize` when column is not selected 2023-09-04 15:55:57 +03:00
Ryuta Kamizono 8271186d01 Merge pull request #48095 from ippachi/triple-dot-range-unscope
Fix unscope not working when where by tripe dot range
2023-09-04 17:16:25 +09:00
Ryuta Kamizono 532188cbf4
Merge pull request #45498 from HParker/deprecate-rewhere-on-merge
Deprecate passing `rewhere` to `merge`
2023-09-04 16:03:42 +09:00
Ryuta Kamizono 9084a9045f Add original author's credit for #49100 [ci-skip]
Since #41730 is the original work for the enum attribute validation.
2023-09-04 13:46:15 +09:00
Hartley McGuire db1a3537c7
Remove $global mistakenly left in test
This was accidentally left in when this change was [submitted][1] to
main. This was already addressed in the backport commit but this
addresses it for main.

[1]: 57a9e25f8e
2023-09-02 12:27:50 -04:00
Sean Doyle e85a3ec624
Change `has_secure_token` default to `on: :initialize`
Follow-up to [#47420][]

With the changes made in [#47420][], `has_secure_token` declarations can
be configured to execute in an `after_initialize` callback. This commit
proposed a new Rails 7.1 default: generate all `has_secure_token` values
when their corresponding models are initialized.

To preserve pre-7.1 behavior, applications can set
`config.active_record.generate_secure_token_on = :create`.

By default, generate the value when the model is initialized:

```ruby
class User < ApplicationRecord
  has_secure_token
end

record = User.new
record.token # => "fwZcXX6SkJBJRogzMdciS7wf"
```

With `config.active_record.generate_secure_token_on = :create`, generate
the value when the model is created:

```ruby
 # config/application.rb
config.active_record.generate_secure_token_on = :create

 # app/models/user.rb
class User < ApplicationRecord
  has_secure_token on: :create
end

record = User.new
record.token # => nil
record.save!
record.token # => "fwZcXX6SkJBJRogzMdciS7wf"
```

[#47420]: https://github.com/rails/rails/pull/47420

Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
2023-09-01 20:17:22 +00:00
Eileen M. Uchitelle 3bc64016af
Merge pull request #49112 from gmcgibbon/cpk_id_docs
Composite Primary Key id method docs
2023-09-01 15:58:54 -04:00
Эдем 7c65a4b83b
Make enums validatable without raising error (#49100)
* Make enums validatable without raising error

* Trigger fail CI

Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
2023-09-01 15:31:12 -04:00
Gannon McGibbon 5ae1c5a812 [skip ci] Document id_value method
Adds documention for ActiveRecord::ModelSchema#id_value as a utility
when using composite primary keys.
2023-09-01 14:15:02 -05:00
Gannon McGibbon 362134b462 [skip ci] Document composite primary key behaviour
Adds documentation to exaplain composite key behaviour in
ActiveRecord::AttributeMethods::PrimaryKey for
methods #id, #id=, #id?, #id_before_type_cast, #id_was, #id_in_database.
2023-09-01 14:14:43 -05:00
Rafael Mendonça França cdbc9b78cb
Merge pull request #49090 from skipkayhil/hm-change-column-precision-6
Fix change_column not setting precision for sqlite
2023-09-01 14:21:53 -04:00
Jean Boussier 9fd3d03dab
Merge pull request #49105 from Earlopain/ar-normalizes-where
Document `where` support for AR `normalizes`
2023-09-01 19:02:14 +02:00
Hartley McGuire 57a9e25f8e
Fix change_column not setting precision for sqlite
There were a few 6.1 migration compatibility fixes in [previous][1]
[commits][2]. Most importantly, those commits reorganized some of the
compatibility tests to ensure that the tests would run against every
Migration version. To continue the effort of improving test coverage for
Migration compatibility, this commit converts tests for create_table and
change_column setting the correct precision on datetime columns.

While the create_table tests all pass, the change_column test did not
pass for 7.0 versioned Migrations on sqlite. This was due to the sqlite
adapter not using new_column_definition to set the options on the new
column (new_column_definition is where precision: 6 gets set if no
precision is specified). This happens because columns can't be modified
in place in sqlite and instead the whole table must be recreated and the
data copied. Before this commit, change_column would use the options
of the existing column as a base and merge in the exact options (and
type) passed to change_column.

This commit changes the change_column method to replace the existing
column without using the existing options. This ensures that precision:
6 is set consistently across adapters when change_column is used to
create a datetime column.

[1]: c2f838e80c
[2]: 9b07b2d6ca
2023-09-01 16:57:19 +00:00
Nikita Vasilevsky 0aa4cc4bbc
[skip ci] Document using `FinderMethods.find` on composite primary key models 2023-09-01 16:15:41 +00:00
Earlopain 830957e213
Document `where` support for AR `normalizes`
Also some other small changelog tweak:
* Add normalize_value_for to the activerecord changelog
* Fix a wrong method reference in the 7.1 release notes
2023-09-01 18:13:23 +02:00
Nikita Vasilevsky 0df4df4d15
Add CHANGELOG entries for `ActiveModel::Conversion#to_key` changes
`8a5cf4cf4415ae1cdad7feecfb27149c151b0b10` made changes to `to_key` in order
to support composite identifiers. This commit adds CHANGELOG entries for those.
2023-09-01 15:41:05 +00:00
Jean Boussier 9a1d465438 Fix `ActiveRecord.disconnect_all!` to not disable reconnect on pools
Followup: https://github.com/rails/rails/pull/47856
2023-09-01 16:59:17 +02:00
Filinto Romain 14a34c7223 fix class_name STI 2023-09-01 10:55:28 +02:00
eileencodes 6297e60d3b
Fix alias_attribute deprecation warning and message
I noticed this test was throwing a warning for `alias_attribute
:id_value, :id` defined by Rails. Since this test messes with primary
keys I decided to fix it by making custom classes for each of the
tests that need to change the PK.

While debugging these tests I noticed the deprecation wasn't formatted
correctly so I fixed that while in there.
2023-08-31 15:36:37 -04:00
Eileen M. Uchitelle 411bfa2734
Merge pull request #49088 from eileencodes/derive-foreign-key-query-constraints
Allow Active Record to derive the association query constraints
2023-08-31 12:08:05 -04:00
eileencodes a332dd9323
Allow Active Record to derive the association query constraints
Active Record already has the ability to guess the foreign key. With
query constraints we can use the information from the owner class and
that foreign key to infer what the query constraints should be for an
association. This change improves the ergonomics of the query
constraints feature by making it so that you only have to define the
query constraints on the top level model and skip defining it on the
association. There are a few caveats to this as of this PR:

- If the query constraints on the parent are greater than 2, Rails can't
derive the association constraints
- If the query constraints on the parent don't include the primary key,
Rails can't derive the association constraints.
- If the association has an explicit `foreign_key` or
`query_constraints` option set, Active Record won't infer the key.
- I have not implemented support for CPK yet as it's more complex and
maybe not possible since we don't know which key to split on and use
for the foreign association.

Prior to this change you would need to do the following to use query
constraints:

```ruby
class Post
  query_constraints :blog_id, :id

  has_many :comments, query_constraints: [:blog_id, :blog_post_id]
end

class Comment
  query_constraints :blog_id, :id

  belongs_to :blog, query_constraints: [:blog_id, :blog_post_id]
end
```

After this change, the associations don't require you to set the query
constraints, Active Record will generate `[:blog_id, :blog_post_id]`
foreign key itself.

```ruby
class Post
  query_constraints :blog_id, :id

  has_many :comments
end

class Comment
  query_constraints :blog_id, :id

  belongs_to :blog
end
```
2023-08-31 11:12:59 -04:00
Jean Boussier a7fdc1cdb4 Optimize ActiveRecord::LogSubscriber#query_source_location
`Kernel#caller` has linear performance based on how deep the
stack is. While this is a development only feature, it can end
up being quite slow.

Ruby 3.2 introduced `Thread.each_caller_location`, which lazily
yield `Backtrace::Location` objects.

Ref: https://bugs.ruby-lang.org/issues/16663

This is perfect for this use case as we are searching for the
closest frame that matches a pattern, saving us from collecting
the entire backtrace.
2023-08-31 11:56:55 +02:00
emily.qiu 3af0c0108d Allow KILL queries on read-only connections for mysql 2023-08-30 14:58:56 -05:00
Ian Candy eae26caec3 Clarify deprecation warning for alias_attribute
We ran into a few cases at GitHub where we were using alias_attribute
incorrectly and the new behavior either didn't warn or raised an unclear
deprecation warning. This attempts to add clarity to the deprecation reason
when you try to alias something that isn't actually an attribute.

Previously, trying to alias a generated attribute method, such as `attribute_in_database`, would
still hit `define_proxy_call`, because we were only checking the owner of the target method.

In the future, we should probably raise if you try to use alias_attribute for a non-attribute.

Note that we don't raise the warning for abstract classes, because the attribute may be implemented
by a child class. We could potentially figure out a way to raise in these cases as well, but this
hopefully is good enough for now.

Finally, I also updated the way we're setting `local_alias_attributes` when `alias_attribute` is
first called. This was causing problems since we now use `alias_attribute` early in the
`load_schema!` call for some models: https://buildkite.com/rails/rails/builds/98910
2023-08-30 13:19:58 -04:00
HParker 451053eca5 Add changelog entry for batching using loaded relations
This backfills a changelog entry for PR #48876. This is potentially something Rails users
should be aware of as in very specific situations it can be a change in behavior
2023-08-28 17:29:52 -07:00
Greg Molnar c775fa4db5 upsert should accept update_only parameter like upsert_all does 2023-08-28 16:59:24 +00:00
paulreece 4026aba1f1 This branch fixes the issues raised in #48862. By adding the key and it's values to self.references_values as Rails does when building a where clause, it prevents unneccessary aliasing from taking place and allows a User to successfully use a table_alias in their select query using a Hash. 2023-08-25 17:53:59 -04:00
Étienne Barrié 0810752188 Use Object#with 2023-08-25 17:06:14 +02:00
Étienne Barrié 7e11402e72 Fix test leak 2023-08-25 17:01:22 +02:00
fatkodima df12ca09a0 Do not write to debug.log in activerecord tests on CI 2023-08-24 22:37:07 +03:00
fatkodima 46bd163ee6 Fix slow ActiveRecord::QueryCache test 2023-08-24 22:37:07 +03:00
Rafael Mendonça França d70707d9af
Merge pull request #49020 from Shopify/allow-redefining-to-param-delimiter
Allow redefining `to_param` delimiter using `param_delimiter`
2023-08-23 18:11:14 -04:00
Rafael Mendonça França 59542e86c4
Merge pull request #49019 from adrianna-chang-shopify/ac-deprecate-read-attribute-id-pk
Deprecate `read_attribute(:id)` returning the primary key
2023-08-23 18:02:36 -04:00
Rafael Mendonça França c70ac1d9eb
Merge pull request #49012 from skipkayhil/hm-migration-table-def-methods
Ensure all migration versions use TableDefinition
2023-08-23 17:59:41 -04:00
Nikita Vasilevsky 564a3d6d97
Support composite primary key in `AR::Base#to_param` 2023-08-23 21:53:47 +00:00
Adrianna Chang ac83311bae
Deprecate `read_attribute(:id)` returning the primary key
This commit deprecates `read_attribute(:id)` returning the primary key
if the model's primary key is not the id column. Starting in Rails 7.2,
`read_attribute(:id)` will always return the value of the id column.

This commit also changes `read_attribute(:id)` for composite primary
key models to return the value of the id column, not the composite
primary key.
2023-08-23 16:36:32 -04:00
Rafael Mendonça França 3a680cd647
Merge pull request #49015 from Shopify/update-changelong-about-undefine-attribute-methods
Add new behavior of `undefine_attribute_methods` to CHANGELOG
2023-08-23 14:38:39 -04:00
Nikita Vasilevsky e50fce0fa9
Add new behavior of `undefine_attribute_methods` to CHANGELOG
In `1818beb3a3ea5fdb498095d4885f8a7e512f24ca` Rails changed the target
where alias attribute methods are defined. It lead to
`undefine_attribute_methods` to clean alias attribute methods along with
the attribute methods. It was an intended behavior change but it wasn't
properly documented and tested. This commit clarifies the new behavior
in the Active Model changelog along with covering the behavior with tests.
2023-08-23 14:41:10 +00:00
Adrianna Chang a5f64bf29d
Merge pull request #49004 from andrewn617/improve-base-class-documentation
Improve the documentation for ActiveRecord::Inheritance#base_class
2023-08-23 09:36:12 -04:00
Andrew Novoselac 46279956cf Improve the documentation for ActiveRecord::Inheritance#base_class 2023-08-23 09:19:40 -04:00
Jean Boussier be2c6320f1
Merge pull request #48996 from Shopify/check-for-parent-being-an-owner-of-the-target-method
Allow parent being the owner of an alias attribute method
2023-08-23 14:33:00 +02:00
Nikita Vasilevsky 0c99588919
Allow parent being the owner of an alias attribute method
When an abstract class inherited from an Active Record model
defines an alias attribute Rails should expect the original methods
of the aliased attribute to be defined in the parent class and avoid
raising deprecation warning.
2023-08-23 11:35:45 +00:00
Hartley McGuire c793cdc665
Ensure all migration versions use TableDefinition
This is similar to a [previous commit][1] which ensures that versioned
migrations always call `super` in `compatible_table_definition`. In this
case, these methods are being pulled up to `Current` so that all
subclasses will use a `TableDefinition` class and future developers do
not have to remember to add all of these methods to new versioned
classes when a new one is created.

[1]: 16f8bd7944
2023-08-23 02:03:31 -04:00
Hartley McGuire 9b07b2d6ca
Fix 6.1 change_table setting datetime precision
While working on #48969, I found that some of the Compatibility test
cases were not working correctly. The tests removed in this commit were
never running the `change_table` migration and so were not actually
testing that `change_table` works correctly. The issue is that the two
migrations created in these tests both have `nil` versions, and so the
Migrator only runs the first one.

This commit refactors the tests so that its easier to test the behavior
of each Migration class version (and I think the rest of the tests
should be updated to use this strategy as well). Additionally, since the
tests are fixed it exposed that `t.change` in a `change_table` is not
behaving as expected so that is fixed as well.
2023-08-22 14:01:52 -04:00
Rafael Mendonça França ed5af00459
Merge pull request #48998 from Shopify/to_key-supports-composite-primary-key
Support composite identifiers in `to_key`
2023-08-22 13:53:19 -04:00
Nikita Vasilevsky 8a5cf4cf44
Support composite identifiers in `to_key`
This commit adds support for composite identifiers in `to_key`.
Rails 7.1 adds support for composite primary key which means that
composite primary key models' `#id` method returns an `Array` and
`to_key` needs to avoid double-wrapping the value.
2023-08-22 16:13:23 +00:00
Jean Boussier 5f6c404853
Merge pull request #48983 from JoeDupuis/fix-regression-on-strict-has-one-through
Fix regression blocking creation of some strict association
2023-08-22 17:20:56 +02:00
Hartley McGuire c2f838e80c
Fix 6.1 change_column setting datetime precision
This is already the case for add_column and create_table, but
change_column was missed
2023-08-21 19:10:14 -04:00
Rafael Mendonça França ccee593fed
Merge pull request #48930 from adrianna-chang-shopify/ac-id-value
Use `alias_attribute` to provide `id_value` alias for `id` attribute
2023-08-21 14:33:39 -04:00
Adrianna Chang e90b11e77e
Use alias_attribute to provide #id_value alias for #id
This allows access to the raw id column value on records for which an
id column exists but is not the primary key. This is common amongst
models with composite primary keys.
2023-08-21 14:12:53 -04:00
Rafael Mendonça França 6beb3482cd
Merge pull request #48991 from andrewn617/fix-alias-attribute-on-superclass
Fix defect where aliased attribute methods on abstract classes were not being defined
2023-08-21 13:55:46 -04:00
Andrew Novoselac 211146b845 Fix defect where aliased attribute methods on abstract classes were being not defined
rails/rails@a88f47d fixed an issue where subclasses were regenerating aliased attribute methods defined on parent classes. Part of the solution was to call #generate_alias_attributes recursively on a class's superclass to generate all the alias attributes in the inheritance hierarchy. However, the implementation relies on #base_class to determine if we should call #generate_alias_attributes on the superclass. Since all models that inherit from abstract classes are base classes, this means that #generate_alias_attributes will never be called on abstract classes, meaning no method will be generated for any alias attributes defined on them.

To fix this issue, we should always call #generate_alias_attributes on the superclass unless the superclass is ActiveRecord::Base.
2023-08-21 13:32:26 -04:00
Joé Dupuis 4b3571803b Fix regression blocking creation of some strict association
PR #48606 introduced a regression preventing the creation of a chain
of models using a has_one through association when strict_loading is
activated.

The association relies on the initial stale_state being `nil`
to skip loading the target.
755c13f167/activerecord/lib/active_record/associations/association.rb (L175)

PR #48606 initializes the stale_state to `[nil]`
https://github.com/rails/rails/pull/48606/files#diff-39c3da3c5f3fbff01b0a32d3b7ec613fda6bc6225fdbe2629134d91babe37786R84-R86

This change converts the `[nil]` state back to `nil`.
2023-08-21 10:32:08 -07:00
Rafael Mendonça França 77080d5e17
Initialize @has_query_constraints to false in the inherited hook
`has_query_constraints?` is a class method so doing it in init_internals
would not define the right variable.
2023-08-21 15:58:58 +00:00
Guillermo Iguaran 4ec3a986d5
Merge pull request #48959 from skipkayhil/hm-clean-filters-requires
Remove uneeded requires of core_ext/string/filters
2023-08-18 16:03:44 -07:00
Rafael Mendonça França ce36426c98
Initialize the variable in the init_internals method
This will avoid that the conditional assignment is executed every time
has_query_constraints? is called.
2023-08-18 22:13:14 +00:00
eileencodes 3b5a4a56fb
Fix uninitialized ivar 2023-08-18 13:30:51 -04:00
eileencodes 784ca88173
Add method for accessing only query constraints
I'm working on an enhancement to query constraints that will require me
to know when we have query constraints but not a composite key.
Currently if you have a composite key it will be included in the query
constraints list. There's not a way to differentiate between the two
which means that we're forced into setting the query constraints on the
associations for the primary key.

This change adds a `has_query_constraints?` method so we can check the
class for query constraints. The options still work as well but we can
be sure we're always picking up the query constraints when they're
present.
2023-08-18 13:21:06 -04:00
Eileen M. Uchitelle ac5f9dec53
Merge pull request #48947 from eileencodes/use-IN-sql-over-OR-with-query-constraints
Use IN sql instead of OR sql for query constraints
2023-08-17 15:34:31 -04:00
eileencodes 0bbf4e86cb
Use IN sql intead of OR sql for query constraints
We originally implemented this project to use OR queries instead of IN
because it seemed like there was no way to do that without a row
constructor. While working on implementing this feature in our vitess
gem I noticed that we can actually get the queries we wanted, and the
new code is more performant than generating an OR.

SQL Before:

```sql
SELECT "sharded_comments".*
FROM "sharded_comments"
WHERE ("sharded_comments"."blog_id" = 969142904
AND ("sharded_comments"."blog_post_id" = 357271355
OR "sharded_comments"."blog_post_id" = 756811794)
OR "sharded_comments"."blog_id" = 308674288
AND "sharded_comments"."blog_post_id" = 1055755181)
```

SQL After:

```sql
SELECT "sharded_comments".*
FROM "sharded_comments"
WHERE "sharded_comments"."blog_id"
IN (969142904, 308674288)
AND "sharded_comments"."blog_post_id"
IN (357271355, 756811794, 1055755181)
```

Using one of the tests that utilizes this code path, I benchmarked the
queries. The new implementation is faster:

Before:

```
Warming up --------------------------------------
             queries   147.000  i/100ms
Calculating -------------------------------------
             queries      1.486k (± 3.2%) i/s -      7.497k in   5.050742s
```

After:

```
Warming up --------------------------------------
             queries   179.000  i/100ms
Calculating -------------------------------------
             queries      1.747k (± 4.5%) i/s -      8.771k in   5.031424s
```

We can probably improve this more but I think this query is more in line
with what we want and expect while also being more performant (without
having to build a new row constructor in arel).
2023-08-17 15:04:32 -04:00
Eileen M. Uchitelle b56f938b5f
Merge pull request #48964 from sinsoku/fix-method-name
Fix method name to `check_all_pending!`
2023-08-17 10:04:41 -04:00
Eileen M. Uchitelle 8abfcd752a
Merge pull request #48913 from ipc103/fix-parent-deprecation-warning
Allow parent to define alias method override
2023-08-17 09:46:26 -04:00
Takumi Shotoku 0e41e2cd8e
Fix method name to `check_all_pending!`
The method added in 03379d1f59 is `check_all_pending!`, not
`check_pending_migrations!`.
2023-08-17 16:51:39 +09:00
Ian Candy a88f47d012 Only define attribute methods for class
Because we're using a class_attribute to track all of the attribute_aliases,
each subclass was regenerating the parent class methods, causing some unexpected
deprecation messages.

Instead, we can use a class instance variable to track the attributes aliased locally
in that particular subclass. We then walk up the chain and re-define the attribute methods
if they haven't been defined yet.
2023-08-16 18:23:02 -04:00
Hartley McGuire ff6e885d59
Remove uneeded requires of core_ext/string/filters
`actionpack/lib/action_dispatch/routing.rb`
- added: 013745151b
- removed: 93034ad7fe

`activejob/lib/active_job/log_subscriber.rb`
- added: b314ab555e
- removed: 5ab2034730

`activemodel/lib/active_model/errors.rb`
- added: cf7fac7e29
- removed: 9de6457ab0

`activerecord/lib/active_record/core.rb`
- added: b3bfa361c5
- removed: e1066f450d

`activesupport/lib/active_support/core_ext/module/introspection.rb`
- added: 358ac36edf
- removed: 167b4153ca

`activesupport/lib/active_support/duration.rb`
- added: 75924c4517
- removed: a91ea1d510

`railties/lib/rails/commands/server/server_command.rb`
- added: f217364893
- removed: 553b86fc75

`railties/lib/rails/command/base.rb`
- added: 6813edc7d9
- removed: b617a561d8
2023-08-16 17:39:25 -04:00
Rafael Mendonça França b6669e5605
Merge pull request #48927 from paulreece/remove_table_alias_writer
This removes the writer method for table_alias from Arel::Table.
2023-08-11 15:34:18 -04:00
paulreece 6b56de4183 This removes the writer method for table_alias from Arel::Table. Since arel_table is a private API of the framework, no one should be modifying it. 2023-08-10 20:20:13 -04:00
zzak 81fa9136f8
Merge pull request #48924 from skipkayhil/hm-docs-fix-plusses
Fix code blocks using + instead of <tt> [ci skip]
2023-08-11 08:04:19 +09:00
Hartley McGuire bac6d8c079
Fix code blocks using + instead of <tt>
Pluses cannot be used to create code blocks when the content includes a
space.

Found using a regular expression:

```bash
$ rg '#\s[^+]*\+[^+]*\s[^+]*\S\+'
```
2023-08-10 13:05:05 -04:00
Eileen M. Uchitelle 22fa76c125
Merge pull request #48911 from jhbabon/fix/schema-cache-settings
Ensure schema_cache_dump settings are propagated to SchemaReflection class
2023-08-10 10:57:57 -04:00
Nikita Vasilevsky 594f539324
Use `ActiveRecord.deprecator` for the alias attribute deprecation 2023-08-09 20:51:23 +00:00
Eileen M. Uchitelle 8ec27a4529
Merge pull request #43386 from rdimartino/dirty_store
Fix tracking previous changes for ActiveRecord::Store accessors with underlying JSON data column
2023-08-09 12:32:16 -04:00
Juan Hernández Babón d5984f4d80 Ensure schema_cache_dump settings are propagated to SchemaReflection class 2023-08-09 14:11:44 +02:00
Robert DiMartino eceaa38e06
Fix tracking previous changes for ActiveRecord::Store accessors with underlying JSON data column 2023-08-07 22:26:45 -04:00
Rafael Mendonça França 6cc4dc287d
Run mariadb using docker compose on devcontainer 2023-08-05 02:47:43 +00:00
Rafael Mendonça França 451dec7968
Run postgresql using docker compose on devcontainer
This will make easier to make sure the service is running when the
development container is started.

Before after the first time the container was created, if it was
restarted you needed to run the boot.sh script manually to start the
service.
2023-08-05 02:47:42 +00:00
Rafael Mendonça França bd8d717712
Merge pull request #48880 from akhilgkrishnan/added-missing-factory-method-test
Added missing test for Arel factory methods
2023-08-04 16:03:04 -04:00
Rafael Mendonça França 40c616c635
Make sure nested base errors are translatable
If the user defined a translation to a nested error on base we should
look it up in the same way we do for the other attributes.

If no translation is set, we fallback to the name of the association.

Fixes #48884.
2023-08-04 19:55:57 +00:00
John Hawthorn 3cb00edea5
Merge pull request #48879 from jhawthorn/get-rid-of-trilogy-errors-merge
Get rid of trilogy errors merge
2023-08-03 23:17:19 -07:00
Akhil G Krishnan af2839f9a9 Added missing test for Arel factory methods 2023-08-04 09:50:39 +05:30
Rafael Mendonça França 191ae490ed
Make trilogy tests pass on MariaDB
* `supports_json?` always return false on mariadb so the test needs to
stub.
* to_a(as: :hash) is not supported on trilogy. And we should be dealing
with ActiveRecord::Result objects anyway.
2023-08-04 03:33:13 +00:00
Rafael Mendonça França 83e61ca513
Make sure all PostgreSQL tests pass when nulls not distinct isn't supported by the database 2023-08-04 02:49:58 +00:00
Rafael Mendonça França e6521dcb2b
No need for local variable for relation 2023-08-04 02:23:03 +00:00
Rafael Mendonça França c1817e468b
Extract private method to batch on unloaded relation
This will make the in_batches differences between loaded and unloaded
relations.
2023-08-04 02:21:43 +00:00
Rafael Mendonça França 94efd65fdf
Extract private method to implement batch on loaded relation
Isolate the behavior so it is clear what in `in_batches` is reposible
for this logic.
2023-08-04 02:10:41 +00:00
Rafael Mendonça França cfa5857914
Add unit test for Arel::FactoryMethods.coalesce
Method was added in e5190acacd
but there was no unit test for it.
2023-08-04 01:55:04 +00:00
Rafael Mendonça França 2e3df04fcb
Merge pull request #48873 from drnic/arel-cast-function
Adds Arel::FactoryMethods#cast(node, type)
2023-08-03 21:52:00 -04:00
John Hawthorn 08d58e77ed Merge remote-tracking branch 'Shopify/get-rid-of-trilogy-errors' 2023-08-03 16:06:02 -07:00
Rafael Mendonça França b4a594d307
Test the node instead of the result of the SQL
The result of the SQL is not the same on all databases, so writing a
test that would pass in all cases would mean conditionals here.

Since we already testing if the SQL results of a As node is correct in
the visitor tests, we only need to check if the As node attributes are
correct here.
2023-08-03 21:20:54 +00:00
Rafael Mendonça França fbaba19e2d
Merge PR #48608 2023-08-03 19:29:30 +00:00
Eileen M. Uchitelle db6159ce62
Merge pull request #48861 from paulreece/correct_missing_and_associated_behavior
Fixes #47909 when using order or unscope
2023-08-03 11:26:37 -04:00
Aidan Haran db3578a20e Removed hard coded special case for sqlite3_mem 2023-08-03 10:52:29 +01:00
Jean Boussier 147a715790
Merge pull request #48876 from HParker/warn-and-reduce-queries-on-loaded-relations
Use already loaded relation when batching if possible
2023-08-03 09:57:56 +02:00
Dr Nic Williams 32bdff49fe Adds Arel::FactoryMethods#cast(node, type)
For example:
  product_table = Product.arel_table
  product_table.cast(product_table[:position], "integer")

Produces SQL:
  CAST(position as integer)
2023-08-03 17:50:18 +10:00
HParker db92fb7b70 Use already loaded relation when batching if possible
If you have already loaded the relation when using in_batches, you
would reload each batch from the database.  Since we already have the
records available, we can avoid these queries and return the records
as-if the query was run.
2023-08-03 00:07:34 -07:00
Rafael Mendonça França e3f590e2ab
Add regression test for https://github.com/rails/rails/pull/48413#issuecomment-1638486195 2023-08-02 20:18:38 +00:00
zzak f5f9446478
Add autosave tests for association with error
Pulled from #48413

"Fix autosave associations with validations added on `:base` of the associated objects"

Co-authored-by: fatkodima <fatkodima123@gmail.com>
2023-08-02 19:53:54 +00:00
zzak b2c53f8f9f
Revert "Merge pull request #48413 from fatkodima/fix-autosave-association-with-validation-on-save"
This reverts commit 655278edeb, reversing
changes made to 43852db088.
2023-08-02 19:53:53 +00:00
paulreece 4aa339cbbe This fix corrects the logic in both the associated and missing methods. If the reflection.options hash has a key/value pair for :class_name it will use the association. This fixes 48651 which was not returning the correct value when using an enum association and querying for a record that had one key of the enum but was missing another. This also fixes 44964 where ActiveRecord was not properly aliasing self-referencing relations. If the reflection.options doesn’t contain the key/value pair then it will use the reflection.table_name. This fixes 47909 in which a user was trying to find records that were either missing a relation or were missing a relation that was ordered or unscoped or were missing a relation that was using extends in the query which resulted in an ActiveRecord Exception. It also allows for using extends in any of these capacities. 2023-08-02 11:47:13 -04:00
Rafael Mendonça França 834aa41242
Merge PR #48740 2023-08-01 23:05:45 +00:00
Rafael Mendonça França a2e6f952ed
Merge pull request #48808 from zzak/revert-create-association-breaking-changes
Revert singular association breaking changes
2023-08-01 19:01:36 -04:00
Akhil G Krishnan f171101f17 Fixed few typos in tests and guide
reverted the unwanted change

fixed the alignment

review changes updated
2023-08-01 23:31:17 +05:30
Eileen M. Uchitelle 98e12fc6d6
Merge pull request #48852 from f3ndot/issue-37779-escape-literal-colons-2
Allow escaping of literal colons in `ActionRecord::Sanitization#replace_named_bind_variables`
2023-08-01 10:38:04 -04:00
Jean Boussier 35a614c227
Merge pull request #48793 from Shopify/define-attributes-initializer
Never connect to the database in define_attribute_methods initializer
2023-08-01 08:45:24 +02:00
Eileen M. Uchitelle 05d93c7fa1
Merge pull request #48844 from Shopify/use-call-args-for-define-proxy-method-namespace
Use `call_args` in the `define_proxy_method` namespace.
2023-07-31 09:11:46 -04:00
Jean Boussier 828563d5f4
Merge pull request #48838 from jhbabon/fix-schema-version-check 2023-07-30 18:19:32 +02:00
Justin Bull 694376f15e Allow use of backslashes to escape literal colons
Despite the inconvenience of double-backslashing, the backslash was chosen
because it's a very common char to use in escaping across multiple programming
languages. A developer, without looking at documentation, may intuitively try
to use it to achieve the desired results in this scenario.

Fixes #37779
2023-07-30 07:55:02 -04:00
zzak a599ea8c80
Add test covering SchemaCache members are sorted
Follow up to #48824
2023-07-30 08:40:47 +09:00
Nikita Vasilevsky 5dbc7b424e
Use `call_args` in the `define_proxy_method` namespace.
`define_proxy_call` accepts `call_args` as an argument which impacts
method body generation but it doesn't use `call_args` in the `namespace`
generation which leads to the same cached method to be reused even if
`call_args` differ.

It has never been an issue since `define_proxy_call` was only used to
generate Active Record attribute methods and we were always passing
the same `call_args` per method name.

However, since https://github.com/rails/rails/pull/48533 we are using
`define_proxy_call` to generate alias attribute methods where `call_args`
differ for the same method name which leads to the same cached method
being reused in wrong places.

This commit fixes the issue by making sure `call_args` are being
considered when generating the `namespace` for the method.
2023-07-28 19:28:55 +00:00
Juan Hernández Babón c4c28846e0 Use connection.schema_version inside ActiveRecord::SchemaCache
AbstractAdapter#schema_version uses migration_context.current_version by
default, but some adapters might redefine this method to use a custom
schema version number. This fix ensures that generated schema cache
files use this method and that it is also used when validating a file's
version.
2023-07-28 16:47:57 +02:00
Eileen M. Uchitelle 40a9d9bea1
Merge pull request #48738 from paulreece/enum_join_missing_fix
Restores functionality to the missing method when using enums and fixes #48651
2023-07-27 14:18:53 -04:00
paulreece 7aed2ca84a This fix corrects the logic in both the associated and missing methods. If the @scope.values has more than one key it will use associated in the WHERE IS NOT NULL SQL clause. This fixes 48651 which was not returning the correct value when using an enum association and querying for a record that had one key of the enum but was missing another. This also fixes 44964 where ActiveRecord was not properly aliasing self-referencing relations. If the @scope.values has only one key it will use reflection.table_name in the WHERE IS NOT NULL SQL clause. This fixes 47909 in which a user was trying to find records that were simply missing a relation which resulted in an ActiveRecord Exception. 2023-07-27 12:19:52 -04:00
Jean Boussier 3c7f48b8b9 Sort SchemaCache members when dumping it
Ref: https://github.com/rails/rails/issues/42717

This allow to result to be consistent, allowing to use its digest
for cache keys and such.
2023-07-27 10:29:56 +02:00
Nikita Vasilevsky 6798b43bef
Return `false` early when a non-AR object passed to `FinderMethods#include?`
This PR fixes a bug introduced in https://github.com/rails/rails/pull/48761
which leads to a `NoMethodError` when a non Active Record object passed
to `include?` or `member?` since only Active Record objects
respond to `composite_primary_key?`.
2023-07-26 18:05:50 +00:00
zzak 2e0c302df3
Revert "Merge pull request #46386 from lazaronixon/fix-has-one-create-record"
This reverts commit d2cb5b7469, reversing
changes made to 348e609da3.
2023-07-26 14:52:31 +09:00
zzak 09c1a85ab7
Revert "Merge pull request #48416 from Shopify/fix-has-one-deletion"
This reverts commit 6be41aded8, reversing
changes made to 55c3066da3.
2023-07-26 14:51:17 +09:00
Adrianna Chang 7981988fa0
Fix #previously_new_record? on destroyed records
Ref: #48794

`#previously_new_record?` should return false for records that are
created and then destroyed.
2023-07-25 15:49:49 -04:00
Eileen M. Uchitelle 06e8bb5b4c
Merge pull request #48795 from Shopify/tweak-alias-attribute-deprecation-message
Tweak `alias_attribute` deprecation message
2023-07-25 10:51:13 -04:00
Nikita Vasilevsky 408b1b95d4
Tweak `alias_attribute` deprecation message 2023-07-25 13:53:55 +00:00
Xavier Noria b70571c3c0
Update activerecord/lib/active_record/errors.rb
Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
2023-07-24 19:31:38 +02:00
Jean Boussier 5f3eb2195b
Merge pull request #48773 from nirvdrum/thread-safe-quoted-names
Make ActiveRecord's quoted name caches thread-safe on JRuby/TruffleRuby
2023-07-24 18:17:50 +02:00
Kevin Menard 68d572a5d1 Make ActiveRecord's quoted name caches thread-safe. 2023-07-24 12:04:10 -04:00
Nikita Vasilevsky 686336f579
Do not use `alias_attribute` to alias an association
Using `alias_attribute` to alias an association is not an indented
use case. This commit removes `alias_attribute` calls to alias an
association along with the relevant tests. However, it doesn't mean
that the commit brakes any current behaviors.
2023-07-24 14:45:09 +00:00
Jean Boussier de765e37c1 Never connect to the database in define_attribute_methods initializer
Followup: https://github.com/rails/rails/pull/48743

After careful consideration, unless users have a schema cache dump loaded
and `check_schema_cache_dump_version = false`, we have no choice but
to arbitrate between resiliency and performance.

If we define attribute methods during boot, we allow them to be shared
between forked workers, and prevent the first requests to be slower.

However, by doing so we'd trigger a connection to the datase, which
if it's unresponsive could lead to workers not being able to restart
triggering a cascading failure.

Previously Rails used to be in some sort of middle-ground where
it would define attribute methods during boot if for some reason
it was already connected to the database at this point.

But this is now deemed undesirable, as an application initializer
inadvertantly establishing the database connection woudl lead to
a readically different behavior.
2023-07-24 16:37:50 +02:00
Xavier Noria 4dd55e8d81
Update activerecord/lib/active_record/errors.rb
Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
2023-07-21 18:35:39 +02:00
Xavier Noria 7970c8af12 Improve the docs of ActiveRecord::TransactionRollbackError 2023-07-21 18:06:07 +02:00
Jean Boussier 3ee73bff39
Merge pull request #48533 from Shopify/delay-alias-attribute-defition
Call proxy methods from `alias_attribute` generated methods
2023-07-21 14:08:30 +02:00
Xavier Noria 5a36344334 Fixes the documentation of with_transaction_returning_status
This method was refactored in d916c62, but the documentation was not updated.
2023-07-21 13:07:55 +02:00
John Hawthorn 4c7f792371
Merge pull request #48766 from ywenc/ywenc/add-other-to-method
Call `other.value_for_database` in ActiveRecord::Relation::QueryAttribute == check
2023-07-19 17:38:17 -07:00
ywenc 7941511e48
Fix `StatementCache::Substitute` with serialized type (#48765)
* Don't call value_for_database if StatementCache::Substitute

Test type.dump with string

Co-authored-by: jhawthorn <jhawthorn@github.com>

* Update query_attribute.rb

Co-authored-by: jhawthorn <jhawthorn@github.com>

* Use double quotes

---------

Co-authored-by: jhawthorn <jhawthorn@github.com>
2023-07-19 17:37:51 -07:00
ywenc 8358008bb9 Call other.value_for_database in == check
Co-authored-by: jhawthorn <jhawthorn@github.com>
2023-07-19 17:40:35 -04:00
Matthew Draper 3a8b9baa51
Merge pull request #47503 from fatkodima/no-sleeping-on-duel
Rewrite `PessimisticLockingTest#test_no_locks_no_wait` to avoid costly sleeping
2023-07-20 02:26:59 +09:30
Jean Boussier 47d0f4ec0f Add a missing word in a comment 2023-07-19 17:32:29 +02:00
Eileen M. Uchitelle 5faf31bd6b
Merge pull request #48761 from adrianna-chang-shopify/ac-fix-include-method-cpk
Support `include?` and `member?` on composite primary key relations
2023-07-19 10:39:42 -04:00
Adrianna Chang 15f91c5963
Support include? and member? on composite primary key relations
`include` and `member?` delegate to `exists?` with the record's primary
key to determine if an unloaded relation contains a given record. If
the primary key is composite, `exists?` belives we are passing
where-style conditions and fails.

This commit fixes the issue by turning the record's composite primary key
into a hash of column / value pairs that `exists?` can accept.
2023-07-19 09:16:30 -04:00
Gregory Jones 4837bcaeef
Merge branch 'main' into postgres-index-nulls-not-distinct 2023-07-18 15:05:24 -04:00
Sean Doyle 7d63864486 Specify when to generate `has_secure_token`
The callback when the value is generated. When called with `on:
:initialize`, the value is generated in an `after_initialize` callback,
otherwise the value will be used in a `before_` callback. It will
default to `:create`.
2023-07-18 14:48:30 -04:00
Jean Boussier 835eb8a213
Merge pull request #48743 from Shopify/ar-define-attr-methods-init
Cleanup `define_attribute_methods` initializer
2023-07-18 10:21:50 +02:00
Nikita Vasilevsky 1818beb3a3
Call proxy methods from `alias_attribute` generated methods
This commit changes bodies of methods generated by `alias_attribute`
along with generating these methods lazily.

Previously the body of the `alias_attribute :new_title, :title` was
`def new_title; title; end`. This commit changes it to
`def new_title; attribute("title"); end`.

This allows for `alias_attribute` to be used to alias attributes named
with a reserved names like `id`:
```ruby
  class Topic < ActiveRecord::Base
    self.primary_key = :title
    alias_attribute :id_value, :id
  end

  Topic.new.id_value # => 1
```
2023-07-17 22:22:28 +00:00