Commit Graph

18015 Commits

Author SHA1 Message Date
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: 013745151be062aa4d0fc1f2a008a7303fdb6e04
- removed: 93034ad7fea7e00562103a7cd0acfab19bbfadf9

`activejob/lib/active_job/log_subscriber.rb`
- added: b314ab555e0d85e6efb41be94fb5f3a157bb12fe
- removed: 5ab2034730feacfc2caee418f8c0b55191d27427

`activemodel/lib/active_model/errors.rb`
- added: cf7fac7e29bb2816412c949fdaed3d61a923eb23
- removed: 9de6457ab0767ebab7f2c8bc583420fda072e2bd

`activerecord/lib/active_record/core.rb`
- added: b3bfa361c503e107aff4dee5edf79bd7fd3d3725
- removed: e1066f450d1a99c9a0b4d786b202e2ca82a4c3b3

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

`activesupport/lib/active_support/duration.rb`
- added: 75924c4517c8f87712d3f59c11f10152ed57b9d8
- removed: a91ea1d51048342d13fc73f9b09ce4cfd086bb34

`railties/lib/rails/commands/server/server_command.rb`
- added: f2173648938b418d120f5a68d8f3862d8ae9dace
- removed: 553b86fc751c751db504bcbe2d033eb2bb5b6a0b

`railties/lib/rails/command/base.rb`
- added: 6813edc7d926965e5644cd8befaf229a35b9d8ca
- removed: b617a561d865a65cfc140caa0e3c4af4350bfcef
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
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
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
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
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
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
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
zzak
b2c53f8f9f
Revert "Merge pull request #48413 from fatkodima/fix-autosave-association-with-validation-on-save"
This reverts commit 655278edeb82ec5f081313abf9c9f59c8be76b22, reversing
changes made to 43852db0883ccb151ab4b1d7776ce056485671f5.
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
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
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
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 d2cb5b7469bd5412fe175517b163a706f260a567, reversing
changes made to 348e609da369c4a32cdcab51a78edcd0ad2942c1.
2023-07-26 14:52:31 +09:00
zzak
09c1a85ab7
Revert "Merge pull request #48416 from Shopify/fix-has-one-deletion"
This reverts commit 6be41aded8c067b2b4af3b05193e551f126fb0e3, reversing
changes made to 55c3066da325703ff7a9524dbdc479b860db3970.
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
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
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
Jorge Manrubia
e6d59cdebb
Fix queries for deterministically encrypted attributed for data migrated from 7.0. (#48676)
#48530 introduced a problem for the system that extends AR queries involving deterministically encrypted attributes. The problem is that this option added the same "previous scheme" for all the attributes, when the only intended ones were the "non deterministic" ones. A side effect of this is that, when encrypting query param values, it was using the wrong encryption scheme.

Fixes https://github.com/rails/rails/issues/48204#issuecomment-1623301440
2023-07-17 19:38:54 +02:00
Jean Boussier
7e07fde9a3 Cleanup define_attribute_methods initializer
Followup: https://github.com/rails/rails/pull/48716

`model.connection_pool.schema_reflection` is never falsy, so that `if`
was pointless.

Instead we more properly check if the schema cache contains that table.

I also added some more comments to explain why the initializer tries
so hard not to touch the database.
2023-07-17 16:45:22 +02:00
Jean Boussier
13cff7e197
Merge pull request #48716 from Shopify/schema-reflection
Refactor Active Record Schema Cache to not hold a connection
2023-07-17 12:14:46 +02:00
Jonathan Hefner
04fede8cb7 Fix comment syntax [ci-skip] 2023-07-16 15:19:31 -05:00
Nick Dower
b563cabc60 Discard connection in ensure, not rescue
Partially Fixes #48164. Followup to #48200.

`within_new_transaction` currently discards connections if an error
is raised which may have left the connection in a transaction. This change
updates that logic to discard connections in an `ensure` block to handle
cases where an error is not raised, for instance if the thread is killed.
2023-07-15 10:05:56 +02:00
Matthew Draper
b36f9186b0 Refactor Active Record Schema Cache to not hold a connection
A big problem with the current `SchemaCache` implementation is that it holds
a reference to a connection, and uses it to lazily query the schema when the
information is missing.

This cause issues in multi-threaded contexts because all the connections
of a pool share the same schema, so they are constantly setting themselves
as the connection the schema cache should use, and you can end up in
situation where Thread#1 query the schema cache, which end up using the
connection currently attributed to Thread#2.

For a very long time this worked more or less by accident, because all
connection adapters would have an internal Monitor.

However in https://github.com/rails/rails/pull/46519 we got rid of this
synchronization, revealing the pre-existing issue. Previously it would
work™,  but still wasn't ideal because of unexpected the connection
sharing between threads.

The idea here is to refactor the schema cache so that it doesn't hold a
reference onto any connection.

And instead of a `SchemaCache`, connections now have access to a
`SchemaReflection`. Now the connection that needs a schema information
is always provided as an argument, so that in case of a miss, it can be
used to populate the cache.

That should fix the database thread safety issues that were witnessed.

However note that at this stage, the underlying `SchemaCache` isn't
synchronized, so in case of a race condition, the same schema query
can be performed more than once. It could make sense to add synchronization
in a followup.

This refactoring also open the door to query the cache without a connection,
making it easier to eagerly define model attribute methods on boot without
establishing a connection to the database.

Co-Authored-By: Jean Boussier <jean.boussier@gmail.com>
Co-Authored-By: zzak <zzakscott@gmail.com>
2023-07-13 12:34:13 +02:00
Jacopo
186474f273 Fix counter_cache create/concat with overlapping counter_cache_column
Fix when multiple `belongs_to` maps to the same counter_cache column.
In such situation `inverse_which_updates_counter_cache` may find the
wrong relation which leads into an invalid increment of the
counter_cache.

This is done by releying on the `inverse_of` property of the relation
as well as comparing the models the association points two.

Note however that this second check doesn't work for polymorphic
associations.

Fixes #41250

Co-Authored-By: Jean Boussier <jean.boussier@gmail.com>
2023-07-13 12:06:08 +02:00
Jean Boussier
29205d7928 Eagerly cast serialized query attributes
Fix: https://github.com/rails/rails/issues/48652
Ref: https://github.com/rails/rails/pull/46048
Ref: https://github.com/rails/rails/issues/46044
Ref: https://github.com/rails/rails/pull/34303
Ref: https://github.com/rails/rails/pull/39160
Close: https://github.com/rails/rails/pull/48705

This deep_dup was introduced to prevent the value stored in the query
cache to be later mutated.

The problem is that `ActiveRecord::Base#dup` will return a copy
of the record but with the primary key set to nil. One could
argue that `#dup` shouldn't behave this way, but I think this ship
has sailed (or has it?).

My initial fix was to instead always call `type.cast` eagerly so that we'd dup
serialized types in a more correct way. However there is a test
that explictly ensure this doesn't happen: https://github.com/rails/rails/pull/39160

The reason isn't 100% clear to me, but if I get it correctly, it's to avoid
a potentially costly operation upfront.

So instead we only eagerly cast serialized attributes only, so protect against
future mutations.

Mutable types are still deep duped.
2023-07-13 11:44:33 +02:00
Eileen M. Uchitelle
a8e653fdd0
Merge pull request #48724 from gmcgibbon/improve_cpk_validation_check
Improve cpk validation check
2023-07-12 18:12:01 -04:00
Gannon McGibbon
410fc35055 Remove unused suppress_composite_primary_key on HABTM join model class
This method appears to be dead code. Since it was intended to be
private, it should be safe to remove without deprecation.
2023-07-12 16:12:13 -05:00
Gannon McGibbon
ab0451132c Improve CPK error message
A developer may not always want to specify query constraints. If, for
example they would like to use a non-composite primary key in an
asscoaition, they need to use primary_key/foreign_key options instead.

Co-authored-by: Nikita Vasilevsky <nikita.vasilevsky@shopify.com>
2023-07-12 16:02:46 -05:00
Gannon McGibbon
c18d1293b3 Allow assocaition primary keys to be derived with query contraints
Support assignment of belongs_to associations with query constraints.
This improves errors messages for composite key mismatches, and some
edge cases with query constraint lists.

Co-authored-by: Nikita Vasilevsky <nikita.vasilevsky@shopify.com>
2023-07-12 16:02:45 -05:00
Gannon McGibbon
b2c0f3e5c1 Validate composite key length when owner record class has composite key
Catches more bugs in CPK assocaitions by validating the shape of keys on
both ends of the association.

Co-authored-by: Nikita Vasilevsky <nikita.vasilevsky@shopify.com>
2023-07-12 15:40:15 -05:00
Petrik de Heus
f768944bdf
Merge branch 'main' into activerecord/aes256gm-inspect 2023-07-11 21:10:42 +02:00
eileencodes
95f7feaf74
Remove connected? check from db_runtime payload
The check for `Base.connected?` was added in
4ecdf24bde.
At the time this change was made, we were calling
`Base.connection.reset_runtime` so it made sense to check if the
database was connected. Since
dd61a817de
we have stored that information in a thread instead, negating the need
to check `Base.connected?`.

The problem with checking `Base.connected?` is that in a multi-db
application this will return `false` for any model running a query not
inheriting from `Base`, leaving the `db_runtime` payload `nil`. Since
the information we need is stored in a thread rather than on the
connection directly we can remove the `Base.connected?` check.

Fixes #48687
2023-07-10 11:21:59 -04:00
Eileen M. Uchitelle
56c784d808
Merge pull request #48690 from adrianna-chang-shopify/ac-merge-target-list-cpk-fix
Prevent `#merge_target_lists` from clearing id column on composite primary key records
2023-07-10 09:06:07 -04:00
Jean Boussier
5fbaa524b9 Active Record commit transaction on return, break and throw
Fix: https://github.com/rails/rails/issues/45017
Ref: https://github.com/rails/rails/pull/29333
Ref: https://github.com/ruby/timeout/pull/30

Historically only raised errors would trigger a rollback, but in Ruby `2.3`, the `timeout` library
started using `throw` to interupt execution which had the adverse effect of committing open transactions.

To solve this, in Active Record 6.1 the behavior was changed to instead rollback the transaction as it was safer
than to potentially commit an incomplete transaction.

Using `return`, `break` or `throw` inside a `transaction` block was essentially deprecated from Rails 6.1 onwards.

However with the release of `timeout 0.4.0`, `Timeout.timeout` now raises an error again, and Active Record is able
to return to its original, less surprising, behavior.
2023-07-10 10:37:42 +02:00
Adrianna Chang
c5abbbae59
Prevent #merge_target_lists from clearing id column on CPK records
Previously, when merging persisted and in-memory records, we were using
`record[name]` to get the value of the attribute. For records with a
composite primary key, the full CPK would be returned, which was
incompatible with `#_write_attribute`: we'd attempt to assign an Array
to the `id` column, which would result in the column being set to nil.

When dealing with a record with a composite primary key, we need to
write each part of the primary key individually via `#_write_attribute`.
2023-07-07 16:52:37 -04:00
eileencodes
b69fa80b66
Deprecate name argument in remove_connection
The `name` argument is not useful as `remove_connection` should be called
on the class that established the connection. Allowing `name` to be
passed here doesn't match how any of the other methods behave on the
connection classes. While this behavior has been around for a long time,
I'm not sure anyone is using this as it's not documented when to use
name, nor are there any tests.
2023-07-06 15:55:35 -04:00
Petrik
7dd38cfa16 Don't show secrets for Active Record's Cipher::Aes256Gcm#inspect.
If anyone calls a cypher in the console it will show the secret of the
encryptor.

By overriding the `inspect` method to only show the class name we can
avoid accidentally outputting sensitive information.

Before:

```ruby
ActiveRecord::Encryption::Cipher::Aes256Gcm.new(secret).inspect
"#<ActiveRecord::Encryption::Cipher::Aes256Gcm:0x0000000104888038 ... @secret=\"\\xAF\\bFh]LV}q\\nl\\xB2U\\xB3 ... >"
```

After:

```ruby
ActiveRecord::Encryption::Cipher::Aes256Gcm(secret).inspect
"#<ActiveRecord::Encryption::Cipher::Aes256Gcm:0x0000000104888038>"
```
2023-07-06 21:41:27 +02:00
Eileen M. Uchitelle
fc1886757d
Merge pull request #48674 from gmcgibbon/hmt_singular_fix
Fix has_one through singular building with inverse.
2023-07-06 09:09:28 -04:00
Ryuta Kamizono
e552fca4a6
Merge pull request #48657 from alpaca-tc/fix-association-with-has-many-inversing
Fix de-duplication of unsaved records for `ActiveRecord::Associations::CollectionProxy#<<`
2023-07-06 14:37:07 +09:00
Gannon McGibbon
68e0dd2c83 Fix has_one through singular building with inverse.
Allows building of records from an association with a has_one through a
singular association with inverse. For belongs_to through associations,
linking the foreign key to the primary key model isn't needed.
For has_one, we cannot build records due to the association not being mutable.
2023-07-05 23:22:51 -05:00
alpaca-tc
d413d36de2 Fix de-duplication of unsaved records for ActiveRecord::Associations::CollectionProxy#<<
The existing process was attempting to detect duplicates by storing added records in `Set.new`.
When a record is added to `Set.new`, the identity is calculated using `ActiveRecord::Core#hash`, but this value changes before and after saving, so duplicates were not detected before and after saving even for the same object.

This PR fixed the problem by using the `#object_id` of the record to detect duplicates.
Note that when storing a new object obtained by `ActiveRecord::Base.find` etc., duplicates are not eliminated because the `#object_id` is different. This is the same behavior as the current `ActiveRecord::Associations::CollectionProxy#<<`.
2023-07-06 09:51:55 +09:00
Gannon McGibbon
3fc9ade23b Make has_many through singular associations build CPK records
Adds support for building records in has_many through has_one
composite primary key associations.

Also updates query constraints on associations affected by rails/rails#48564.
2023-07-05 12:04:47 -05:00
Eileen M. Uchitelle
d1a79da376
Merge pull request #48606 from gmcgibbon/stale_state_cpk
Support stale state detections in CPK through associations
2023-07-05 11:07:21 -04:00
eileencodes
5cf5a2af13
Fix parallel testing (issue #48547)
Fixes 2 bugs in parallel testing.

The first bug was related to changes made in #45450 which meant that we were
no longer replacing the connection in parallel testing because the
config object is equal (we simply merge a new db name but the object id
of the config stays the same). This bug only manifested in mysql and
sqlite3 interestingly. It would fail on the internal metadata tables
because they were missing in the schema version check.

To fix this I introduced a `clobber: true` kwarg onto the connection
handler that allows us to bypass the functionality that won't make a new
connection if the config is the same. This is an easy way to fall back
to the old behavior from before this change. I only added `clobber`
to the `reconstruct_from_schema` call because we need to actually
replace the connection for these. It's not safe to add everywhere since
we don't always want to replace the connection.

After implementing this fix I was still seeing failures in the mysql
demo app I made due to the fact that `purge` was not re-establishing the
connection to a config that had a database defined. Neither sqlite3 or
postgresql were missing this.

I added a test for mysql2 so we don't have regressions in the future. I
think this was missed because sqlite3 only demonstrates the bug if it
was never successful on that worker and postgresql was fine.

Fixes #48547
2023-07-05 10:50:54 -04:00
alpaca-tc
4c245bfd12 Fix a bug that prevented #pretty_print from displaying records unsaved in collection association.
The change in PR #43302 introduced a bug where unsaved records are not displayed in pretty_print.
The following code will not show unsaved records until this PR is merged.

```ruby
post = Post.create!
post.comments.build

pp(post.comments) #=> expected "[#<Post:0x000000014c0b48a0 ...>]", got "[]"
```

Fixed to call `#load_target` before display as well as `#inspect`.
2023-07-05 12:08:40 +09:00
Gannon McGibbon
755c13f167 Support stale state detections in CPK through associations
Stale states need to be tracked as arrays to properly check through
associations with composite primary keys.
2023-07-04 02:14:02 -05:00
zzak
a234669d63
Disable database prepared statements when query logs are enabled
Fixes #48398

Prepared Statements and Query Logs are incompatible features due to query logs making every query unique.

Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
2023-07-03 16:59:44 +09:00
Guillermo Iguaran
b790387597
Merge pull request #48616 from p8/activerecord/document-dirty
Document `ActiveRecord::Dirty` module in the API docs
2023-06-30 13:07:13 -07:00
Rafael Mendonça França
b2a99eee2b
Merge pull request #48506 from Shopify/rwstauner/fixture-set
Autoload ActiveRecord::FixtureSet
2023-06-30 13:32:43 -04:00
Petrik
4b3920ac9e Document ActiveRecord::AttributeMethods::Dirty module in the API docs
Currently it is a bit unclear which dirty methods can be called on
Active Record models. You have to know that methods from ActiveModel::Dirty
are included.

It also unclear if methods can be invoked in the form of
`saved_change_to_name?` unless you read the documentation of the
`saved_change_to_attribute?` method.

By adding an introduction to the module we can show which methods are
defined specifically for Active Record, and how to call them, very
similar to the ActiveModel::Dirty introduction.
Linking to ActiveModel::Dirty makes it's also easier to find methods
defined there.
2023-06-30 11:02:16 +02:00
Rafael Mendonça França
e366af5bf5
Revert "Merge pull request #48487 from lazaronixon/scope-subqueries"
This reverts commit 6264c1de762cbd7fda6eddc825d6de3027ed5e42, reversing
changes made to 6c80bcdd20eb0c71d53511b16a932bbed4f7da1f.

Reason: Still discussion about the feature. We want to make it opt-in
but we need to better understand why people would want to opt-in to
this behavior.
2023-06-29 15:25:53 +00:00
Yasuo Honda
b214c07558
Merge pull request #48594 from fatkodima/fix-pg-partial-index-on-keyword-column
Accept keyword-like named columns for PostgreSQL partial indexes
2023-06-29 23:15:26 +09:00
Gregory Jones
575a2e0ea7 Add index existence tests for nulls_not_distinct 2023-06-29 01:56:45 -04:00
Gregory Jones
10bad051a8 Support NULLS NOT DISTINCT in Postgres 15+ 2023-06-28 23:24:57 -04:00
Randy Stauner
9b8524c291
Autoload ActiveRecord::FixtureSet
When eager_load is enabled and something (like the frozen_record gem)
tries to load yaml files that use `ActiveRecord::FixtureSet.identify(...)`
we'll get an uninitialized constant error.

Move requires for constants in the ActiveRecord::FixtureSet namespace
to below the creation of the class to avoid circular requires.
See ActiveSupport::Deprecation for a similar instance of this:
7dd67dc285/activesupport/lib/active_support/deprecation.rb (L35-L54)
2023-06-28 16:49:46 -07:00
Gannon McGibbon
e6af9f55e6
Merge pull request #48564 from gmcgibbon/use_id_pk_cpk_book
Use id in composite primary key of cpk book and fix related bugs
2023-06-27 13:02:20 -05:00
fatkodima
0288c5cae0 Accept keyword-like named columns for PostgreSQL partial indexes 2023-06-27 19:35:04 +03:00
Gannon McGibbon
abb6b207c0 Use _read_attribute to properly query id?
Support primary key dirty tracking when ID is a composite
primary key with an id column.

Introduces `ActiveRecord::AttributeMethods::Query#_query_attribute`
to bypass id reader.
2023-06-26 15:33:30 -05:00
Gannon McGibbon
16a5bdc511 Use _read_attribute in ids method
Support calculating IDs for collection proxies
using composite id column values instead of the id reader.
2023-06-26 15:33:30 -05:00
Gannon McGibbon
8a33758e51 Use _read_attribute in [association]_ids writer
Supports id primary key assignment in [association]_ids writer
for composite primary keys.
2023-06-26 15:33:30 -05:00
Matthew Hirst
00ebbbd746
This allows Rails projects with multiple databases to specify which database they would like the migrations to be copied to. 2023-06-26 19:27:47 +02:00
Rafael Mendonça França
5d81a7e6f8
Merge pull request #48507 from szymonlipka/fix-empty-string-range
Fix empty string saving for ranges
2023-06-26 12:05:06 -04:00
Rafael Mendonça França
587cc9b8ef
Merge pull request #47827 from shouichi/remove-class-cache
Remove ActiveRecord::FixtureSet::ClassCache
2023-06-26 12:04:09 -04:00
Jorge Manrubia
4f365720d1
Fix Active Record encryption not picking up encryption settings with eager-loading (#48577)
This deals with a problem where, when eager-loading is enabled, Active Record fails to pick up settings affecting encryption schemes.

The solution here is to resolve encryption schemes lazily, when the attribute type is used.

Follow-up from https://github.com/rails/rails/pull/48530

Closes https://github.com/rails/rails/issues/48204#issuecomment-1607127334
2023-06-26 13:25:38 +02:00
Jorge Manrubia
c8d26bb647
Add a encryption option to support previous data encrypted non-deterministically with a SHA1 hash digest (#48530)
* Make sure active record encryption configuration happens after initializers have run

Co-authored-by: Cadu Ribeiro <mail@cadu.dev>

* Add a new option to support previous data encrypted non-deterministically with a hash digest of SHA1

There is currently a problem with Active Record encryption for users updating from 7.0 to 7.1 Before
#44873, data encrypted with non-deterministic encryption was always using SHA-1. The reason is that
`ActiveSupport::KeyGenerator.hash_digest_class` is set in an after_initialize block in the railtie config,
but encryption config was running before that, so it was effectively using the previous default SHA1. That
means that existing users are using SHA256 for non deterministic encryption, and SHA1 for deterministic
encryption.

This adds a new option `use_sha1_digest_for_non_deterministic_data` that
users can enable to support for SHA1 and SHA256 when decrypting existing data.

* Set a default value of true for `support_sha1_for_non_deterministic_encryption` and proper initializer values.

We want to enable the flag existing versions (< 7.1), and we want it to be false moving by
default moving forward.

* Make sure the system to auto-filter params supports different initialization orders

This reworks the system to auto-filter params so that it works when encrypted
attributes are declared before the encryption configuration logic runs.

Co-authored-by: Cadu Ribeiro <mail@cadu.dev>

---------

Co-authored-by: Cadu Ribeiro <mail@cadu.dev>
2023-06-25 10:16:22 +02:00
Gannon McGibbon
1ba823d662
Merge pull request #48552 from gmcgibbon/fix_cpk_hmt
Add support for unpersisted CPK has_one/has_many through associations
2023-06-23 14:42:20 -05:00
zzak
dd89f600f7
🔗 Remove RDoc auto-link from Rails module everywhere 2023-06-23 10:49:30 +09:00
Gannon McGibbon
699a3725ad Add support for unpersisted CPK has_one/has_many through associations
Fixes loading of has_one and has_many associations with composite
primary key though associations that have unpersisted owner records.
2023-06-21 17:15:04 -05:00
Gannon McGibbon
622485ae4b Add support for nullifying CPK has_one associations
Composite primary key records need to conditionally unset multiple
column attributes from the associated record in order to properly
support dependent: nullify.
2023-06-21 11:08:06 -05:00
Szymon Lipka
ca170d8161 Fix empty string range saving 2023-06-21 09:23:41 +02:00
Guillermo Iguaran
119b4b2af1 Fix the name of delegated method for the records to Array#intersect?
The right method name is Array#intersect?

This adds a test case to avoid this mistake in the future.
2023-06-20 22:22:58 -07:00
Alex Ghiculescu
657600c4d6 Revert "Revert "Merge pull request #48527 from ghiculescu/active-record-enum-id"" 2023-06-21 08:56:13 +10:00
Guillermo Iguaran
6499ccbd09
Merge pull request #48534 from skipkayhil/hm-revert-48527
Revert "Merge pull request #48527 from ghiculescu/active-record-enum-id"
2023-06-20 15:41:12 -07:00
Aaron Patterson
6264c1de76
Merge pull request #48487 from lazaronixon/scope-subqueries
Apply scope to association subqueries
2023-06-20 15:07:29 -07:00
Hartley McGuire
96a86cb630
Revert "Merge pull request #48527 from ghiculescu/active-record-enum-id"
This reverts commit 8b36095881435e996db16604c52737e144b6bff3, reversing
changes made to e05245db878077097d666f7667c0f9057f767583.

Railties tests have been failing since this change. The issue is that
calling `primary_key` as the model is loaded requires either a
connection to the database or a populated schema cache. This becomes an
issue when an app loads models that do not have underlying tables, as
shown in the failing Railties tests.

When eager loading an app using `rails/all`,
`ActionMailbox::InboundEmail` will be loaded whether or not `rails g
action_mailbox:install` has been run. This means the `primary_key` for
`InboundEmail` will not be in the schema cache and a database connection
will be required to boot the app.
2023-06-20 17:44:36 -04:00
zzak
9cdc347342
Fixup AR::FixtureSet docs
* Improve the spacing of various paragraphs
* Link to AS::TestCase.fixture_paths= API
* Add a note about needing to require "rails/test_help" to get fixture_paths
* Expanded briefly on YAML default map unordering property
* Improve heading weight consistency
* Unlink several RDoc autolinked things
2023-06-20 15:47:13 +09:00
zzak
4a63d94a24
Fix AR::TestFixtures.fixture_paths= docs
This removes the deprecated .fixture_path and .fixture_path= methods
from public documentation, and creates a class method for the getter and
setters.

Interestingly because these methods were always `class_attribute` based,
which RDoc doesn't parse, they weren't technically "public"
documentation.
2023-06-20 15:47:07 +09:00
Alex
a22b942fb3 Disallow id as an enum value in Active Record
Fixes https://github.com/rails/rails/issues/48524

The test case in the issue breaks because `value.respond_to?(:id)` returns true [here](51f2e2f80b/activerecord/lib/active_record/relation/predicate_builder.rb (L58)). This effectively adds a default scope to queries where it shouldn't.

There might be a way to fix this in Active Record but I'd be surprised if nothing else breaks from defining `id` instance and class methods. I think it is simpler to not allow it as a value since it really should be treated as a reserved method.
2023-06-20 11:22:30 +10:00
Gannon McGibbon
51f2e2f80b
Merge pull request #48519 from adrianna-chang-shopify/ac-tweak-fixture-path-deprecations
Fix deprecation warning messages for `ActiveSupport::TestFixtures`
2023-06-19 17:32:13 -05:00
Adrianna Chang
0da4b8f315
Fix deprecation warning messages for test fixtures
Minor fixes to the deprecation messages around TestFixtures.fixture_path,
TestFixtures.fixture_path=, and TestFixtures#fixture_path to clarify
which method is deprecated and which should be used instead.
2023-06-19 10:09:52 -04:00
Nixon
8d520e0359 Apply scope to association subqueries 2023-06-16 15:48:24 -03:00
Eileen M. Uchitelle
f97e867a22
Merge pull request #48490 from gmcgibbon/eager_load_cpk
Eager load composite primary keys models
2023-06-16 14:09:38 -04:00
Eileen M. Uchitelle
2f833a64ae
Merge pull request #48489 from gmcgibbon/_read_attribute_has_one_autosave
Use _read_attribute when autosaving has_one associations
2023-06-16 14:09:04 -04:00
Adrianna Chang
4b6fb72199
Bugfix: Ensure has_one associations saved when part of CPK has changed
If a has_one association uses a composite primary key, and part of the
composite primary key changes on the owner, these changes need to be
reflected on the belonging object's foreign key.

This was not working previously, because `#_record_changed?` was not
equipped to handle composite primary key associations, so we were not
recognizing that the belonging object's foreign key needed to be updated
when the owner's primary key changed.
2023-06-15 17:44:04 -04:00
Gannon McGibbon
c18a95e38e Add support for eager loading cpk has_many/has_one relations
Correctly assigns eagerly loaded associations to composite primary key models.
2023-06-15 16:31:29 -05:00
Gannon McGibbon
4d04775920 Use _read_attribute when autosaving has_one associations
In models with composite primary keys, the #id accessor will return an
array, where we actually want the id column value.
2023-06-15 15:52:09 -05:00
Gannon McGibbon
145d2568fd Add support for eager loading cpk belongs_to relations
Correctly assigns eagerly loaded associations to composite primary key
models.
2023-06-15 15:17:53 -05:00
Eileen M. Uchitelle
8a4543d739
Merge pull request #48484 from adrianna-chang-shopify/ac-composite-primary-key-associations-inverse
Fix setting inverses for composite primary key associations
2023-06-15 14:03:18 -04:00
Adrianna Chang
4e53fd0aad
Fix setting inverses for composite primary key associations
Checking whether a record has a foreign key for a composite primary key
association requires us to check whether all parts of the foreign key
are present. Otherwise, the inverse association will not be set.
2023-06-15 13:30:19 -04:00
Ray Faddis
ce6047f84f Adding PG enum rename, add value, and rename value migration helpers 2023-06-15 10:03:23 -04:00
Nikita Vasilevsky
892e4ae24c
Fix destroy_all for has_many :through associations that points to a CPK model 2023-06-14 17:48:13 +00:00
ippachi
ed680483db
Fix unscope not working when where by tripe dot range
Fix #48094
2023-06-14 01:15:08 +09:00
Varun Sharma
2a8475c6d1 Remove unnecessary splat operator 2023-06-13 19:51:25 +05:30
Eileen M. Uchitelle
a14c5f07e1
Merge pull request #48436 from gmcgibbon/cpk_malformed_key
Add better TypeError when assigning CPK
2023-06-12 12:40:16 -04:00
Eileen M. Uchitelle
716baea69f
Merge pull request #48440 from fatkodima/fix-batching-using-cpk
Fix ActiveRecord batching over composite primary keys
2023-06-12 09:24:09 -04:00
a5-stable
6538d65b04 wrap Arel.sql to avoid error 2023-06-12 00:43:35 +09:00
Varun Sharma
f0712f39d4 Do not revalidate encrypted attribute with current encrypted_type 2023-06-11 19:39:14 +05:30
fatkodima
14cfad3137 Fix ActiveRecord batching over composite primary keys 2023-06-10 18:20:25 +03:00
Gannon McGibbon
13b495bfd0 Add better TypeError when assigning CPK
Raises a more readable error when assigning a singular ID to a
model with a composite primary key.
2023-06-09 13:16:14 -05:00
Jenny Shen
b202d5be99
Handle ER_DBACCESS_DENIED_ERROR code in mysql2 adapter
During the process of adding adapter tests to test the different types of connection errors,
the ER_DBACCESS_DENIED_ERROR code was discovered to be not handled. It is the same as
ER_ACCESS_DENIED_ERROR except that a database has been given.

https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html#error_er_dbaccess_denied_error

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
2023-06-09 10:26:36 -04:00
Jean Boussier
ec1aa50a89 Revert "Merge pull request #48406 from rails/revert-46790-singular-association-refactor"
This reverts commit f6f2b2d53f244138df58c8b5659d132fcf0d1832, reversing
changes made to 3e01b26a16857c83ba0507e1533f02bda4a5d516.
2023-06-07 10:02:59 +02:00
Yasuo Honda
655278edeb
Merge pull request #48413 from fatkodima/fix-autosave-association-with-validation-on-save
Fix autosave associations with validations added on `:base` of the associated objects
2023-06-07 11:14:05 +09:00
fatkodima
d01c4a7045 Fix autosave associations with validations added on :base of the associated objects 2023-06-07 02:07:53 +03:00
Nikita Vasilevsky
257f0124fc
Allow composite primary key to be derived from schema
This commit stops issuing the
"Active Record does not support composite primary key" warning
and allows `ActiveRecord::Base#primary_key` to be derived as an `Array`
2023-06-06 14:39:04 +00:00
Eileen M. Uchitelle
e7be1e76bc
Merge pull request #48400 from adrianna-chang-shopify/ac-scope-for-create-on-cpk
Fix `#scope_for_create` for belongs_to associations with CPK
2023-06-06 09:04:22 -04:00
Jean Boussier
7f1c93bd19
Revert "Small refactor on build singular association" 2023-06-06 14:33:01 +02:00
Matthew Draper
3e01b26a16 Merge pull request #48295 from luanzeba/connection_attr_reader
Store `connection_pool` in database-related exceptions
2023-06-06 20:33:55 +09:30
Adrianna Chang
e684588e53
Fix #scope_for_create for belongs_to associations with CPK
`#scope_for_create` for singular associations removes the primary key
from the scope so that we don't assign PK columns when building an
association.

However, removing the primary key from the scope doesn't currently
handle composite primary keys. This commit fixes that.
2023-06-05 17:06:12 -04:00
Eileen M. Uchitelle
768ebf9985
Merge pull request #48385 from adrianna-chang-shopify/ac-autosave-belongs-to-destroy
Fix destroying belongs_to associations for CPK
2023-06-05 13:33:01 -04:00
takuyaK
9452b59506 Support batching using composite primary keys and multiple column ordering
When find_each/find_in_batches/in_batches are performed on a table with composite primary keys, ascending or descending order can be selected for each key.

    ```ruby
    Person.find_each(order: [:desc, :asc]) do |person|
      person.party_all_night!
    end
    ```
2023-06-05 21:59:38 +09:00
Rafael Mendonça França
fb919dac93
Merge pull request #47647 from fatkodima/remove_unique_key-by-options
Consider options when removing UNIQUE KEYs
2023-06-02 16:56:01 -04:00
Adrianna Chang
be231a7f22
Fix destroying belongs_to associations for CPK
This commit handles destroying CPK associations when autosave is set
and the parent association is marked for destruction. It does so
by ensuring that all parts of the foreign key (the parent's CPK)
are set to nil before destroying the parent record.
2023-06-02 15:39:33 -04:00
Gannon McGibbon
87c2ad0a81 Fix has_one autosaving for CPK associations
Adds support for autosaving has_one associations with composite primary keys.
2023-06-02 11:20:53 -05:00
Luan Vieira
7d4c88dde3
Store connection_pool in DB exceptions
Anytime an exception is raised from an adapter we now provide a
`connection_pool` along for the application to further debug what went
wrong. This is an important feature when running a multi-database Rails
application.

We chose to provide the `connection_pool` as it has relevant context
like connection, role and shard. We wanted to avoid providing the
`connection` directly as it might accidentally be used after it's
returned to the pool and been handed to another thread.
The `ConnectionAdapters::PoolConfig` would also have been a reasonable
option except it's `:nodoc:`.
2023-06-02 10:44:28 -04:00
Eileen M. Uchitelle
254f1d8ded
Merge pull request #48357 from gmcgibbon/belongs_to_cpk
Add composite primary key validity check on belongs_to associations.
2023-06-02 08:25:16 -04:00
Gannon McGibbon
f9a8f9c976 Add composite primary key validity check to associations.
Raise ActiveRecord::CompositePrimaryKeyMismatchError when a belongs_to,
has_one, or has_many foreign key and primary key don't have the same length.
2023-06-02 01:32:59 -05:00
Nixon
aa41938e3a Fix polymorphic association subquery 2023-06-02 02:50:23 -03:00
Yasuo Honda
95af5fce71
Merge pull request #45783 from shhavel/fix/anonymous_pg_columns_of_different_type_from_json
[AR] Fix result with anonymous PG columns of different type from json
2023-06-02 08:33:08 +09:00
eileencodes
2c39149e99
Revert deprecation message for prepared statements
While we had hoped to turn prepared statements on for Rails 7.2, the bug
that's preventing us from doing that is still present. See #43005.

Until this bug is fixed we should not be encouraging applications
running mysql to change the `prepared_statements` in the config to
`true`. In addition to this bug being present, Trilogy does not yet
support `prepared_statements` (although work is in progress).

It will be better to implement this deprecation when mysql2 and trilogy
can both handle `prepared_statements` without major bugs.
2023-06-01 16:11:55 -04:00
Nikita Vasilevsky
c92933265e
Assign auto populated columns on Active Record object creation
This commit extends Active Record creation logic to allow for a database
auto-populated attributes to be assigned on object creation.

Given a `Post` model represented by the following schema:
```ruby
create_table :posts, id: false do |t|
  t.integer :sequential_number, auto_increment: true
  t.string :title, primary_key: true
  t.string :ruby_on_rails, default: -> { "concat('R', 'o', 'R')" }
end
```
where `title` is being used as a primary key, the table has an
integer `sequential_number` column populated by a sequence and
`ruby_on_rails` column has a default function - creation of
`Post` records should populate the `sequential_number` and
`ruby_on_rails` attributes:

```ruby
new_post = Post.create(title: 'My first post')
new_post.sequential_number # => 1
new_post.ruby_on_rails # => 'RoR'
```

* At this moment MySQL and SQLite adapters are limited to only one
column being populated and the column must be the `auto_increment`
while PostgreSQL adapter supports any number of auto-populated
columns through `RETURNING` statement.
2023-06-01 14:39:12 +00:00
eileencodes
7d60710559
Add role to connection payload
It doesn't make sense to include shard if we're also not going to
include role.
2023-05-31 15:59:21 -04:00
Eileen M. Uchitelle
ced5e77936
Merge pull request #48353 from eileencodes/set-default-shard-from-connects_to-hash
Set default_shard from connects_to hash
2023-05-31 15:29:57 -04:00
eileencodes
0d41bfd3cc
Set default_shard from connects_to hash
If an application is using sharding, they may not want to use `default`
as the `default_shard`. Unfortunately Rails expects there to be a shard
named `default` for certain actions internally. This leads to some
errors on boot and the application is left manually setting
`default_shard=` in their model or updating their shards in
`connects_to` to name `shard_one` to `default`. Neither are a great
solution, especially if Rails can do this for you. Changes to Active
Record are:

* Simplify `connects_to` by merging `database` into `shards` kwarg so we
can do a single loop through provided options.
* Set the `self.default_shard` to the first keys in the shards kwarg.
* Add a test for this behavior
* Update existing test that wasn't testing this to use `default`. I
could have left this test but it really messes with connections in the
other tests and since this isn't testing shard behavior specifically, I
updated it to use `default` as the default shard name.

This is a slight change in behavior from existing applications but
arguably this is fixing a bug because without this an application won't
boot. I originally thought that this would require a huge refactoring to
fix but realized that it makes a lot of sense to take the first shard as
they default. They should all have the same schema so we can assume it's
fine to take the first one.

Fixes: #45390
2023-05-31 12:52:12 -04:00
fatkodima
c3b0878f2e Preserve timestamp when setting an ActiveSupport::TimeWithZone value to timestamptz attribute 2023-05-31 00:35:29 +03:00
fatkodima
1c469c5a74 Consider options when removing UNIQUE KEYs 2023-05-30 15:15:26 +03:00
Jean Boussier
ae02cd6539
Merge pull request #48322 from fatkodima/fix-locking-with-counter-caches
Fix decrementing counter caches for parent records using optimistic locking
2023-05-30 09:45:56 +02:00
zzak
dd9f3ff64a
Fix headings for AR::QueryMethods#where
* Use capital case for headings
* Escape String, Hash, Array, Module from RDoc autolinking
2023-05-30 13:45:46 +09:00
zzak
8a3e5d2448
Fixed-width font fixes for AR::QueryMethods 2023-05-30 13:44:54 +09:00
zzak
bc7a727c6d
Remove AR::Associations::Preloader from public API doc
This removes the following previously internal API:

* AR::Associations::Preloader
* AR::Associations::Preloader::Association
* AR::Associations::Preloader::Association::LoaderQuery
* AR::Associations::Preloader::Association::LoaderRecords

Because there was a `:nodoc:` on both Preloader and Preloader::Association,
the assumption is that everything underthat is also private.

However, RDoc did not do the right thing.
2023-05-30 10:55:31 +09:00
zzak
8bcea6b07a
Link to the first method in the public instance methods list for AR::Associations 2023-05-30 10:54:56 +09:00
zzak
cfed245164
Link to AR::QueryMethods#includes for associations option in AR::Associations::Preloader.new 2023-05-30 10:52:16 +09:00
zzak
0677321b2a
Unlink Callbacks heading from AR::AutosaveAssociation 2023-05-30 10:51:01 +09:00
fatkodima
a7dc348406 Fix decrementing counter caches for parent records using optimistic locking 2023-05-30 02:17:37 +03:00
zzak
e0ae39b33f
💅 Several fixes to AR::DatabaseConfigurations docs
* Fix RDoc autolinks where it makes sense
* Fixed-width font for database_tasks option
* Remove duplicate "Also aliased as blank?"
* Link to AR::DatabaseConfigurations from config classes
* Link to AR::Base.configurations from DatabaseConfigurations
* Move options doc to initializer
2023-05-29 19:10:02 +09:00
zzak
3b1f1580ab
Trick RDoc to pickup ActiveRecord::Core#values_at 2023-05-29 10:36:27 +09:00
Guillermo Iguaran
c49bd00a4a
Merge pull request #48303 from ryanhertz/transaction-after-commit
fix after_commit callback when record is destroyed twice
2023-05-26 11:00:57 -07:00
fatkodima
4e0079f09a Preserve existing column default functions when altering table in SQLite 2023-05-26 14:09:52 +03:00
Rafael Mendonça França
54ec908a2d
Merge pull request #47940 from fatkodima/fix-alias-where-missing
Remove table alias added when using `where.missing` or `where.associated`
2023-05-25 23:04:37 -04:00
Ryan Hertz
e8ae4ecd5c
fix after_commit callback when record is destroyed twice
When `destroy` is called twice on a persisted record inside a
transaction, the after_commit callbacks fail to run. The second
time `destroy` is called, `@_trigger_destroy_callback` is set to false
because the record has already been deleted, even though the
transaction hasn't completed yet, and the after_commit callbacks haven't
had a chance to run from the first `destroy`.
2023-05-25 14:58:02 -07:00
eileencodes
6bd812326c
Fix deprecation message for connection pool methods
This deprecation was added in main as of 7.1 so the message shouldn't
mention 7.1, it should mention the next version of Rails.
2023-05-25 08:54:01 -04:00
Aaron Patterson
2dbc7dbac8
Merge pull request #48261 from 97jaz/arel-cte-node
Adds Arel::Nodes::Cte for use in WITH expressions
2023-05-24 16:53:29 -07:00
Rafael Mendonça França
8f9fb1e042
Merge pull request #47181 from spencerneste/model_generator_custom_migration_template
Model Generator Source Paths Should Allow for Customization
2023-05-24 19:28:05 -04:00
Jon Zeppieri
355b65ddb4 Adds Arel::Nodes::Cte for use in WITH expressions
SelectManager#with currently accepts As and TableAlias nodes.
Neither of these support materialization hints for the query
planner. Both Postgres and SQLite support such hints.

This commit adds a Cte node that does support materialization
hints. It continues to support As and TableAlias nodes by
translating them into Cte nodes.
2023-05-24 19:19:21 -04:00
Rafael Mendonça França
b070c4d610
Simplify the implementation to register the correct source_path for the migration template 2023-05-24 22:54:12 +00:00
zzak
073269c9b9
Merge pull request #48288 from zzak/rdoc-fixed-width-namespaces
Use short-form fixed-width RDoc form for namespaces
2023-05-25 07:14:47 +09:00
Spencer Neste
a8fe415f85
Model Generator Source Paths Should Allow for Customization
Co-authored-by: Joshua Flanagan <joshuaflanagan@gmail.com>
2023-05-24 22:13:45 +00:00
zzak
38bef29064
Replace all occurrences of '<tt>(\w+::\w+::\w+)</tt>' with '+$1+'
E.g.:

* <tt>Rails::Command::NotesCommand</tt> -> +Rails::Command::NotesCommand+

Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
2023-05-25 06:56:17 +09:00
zzak
e3c73fd183
Replace all occurrences of '<tt>(\w+::\w+)</tt>' with '+$1+'
E.g.:

* <tt>ActiveRecord::Base</tt> -> +ActiveRecord::Base+

Co-authored-by: Hartley McGuire <skipkayhil@gmail.com>
Co-authored-by: Petrik de Heus <petrik@deheus.net>
2023-05-25 06:52:32 +09:00
Chris Salzberg
908f1c9bbc Automatically add test/fixtures in engines to fixture_paths
Introduces a new engine initializer, `add_fixture_paths`, which
automatically adds a `test/fixtures` folder under the engine root to
`fixture_paths` if such a folder exists.
2023-05-24 17:01:25 +09:00
Hartley McGuire
2ba2090eac
Fix NameError in Mysql2::DatabaseStatements
The recent [refactor][1] to the MySQL DatabaseStatements classes renamed
Mysql::DatabaseStatements to Mysql2::DatabaseStatements. That commit
also updated most of the references to the top level Mysql2 to be
explicit since Ruby will now assume they refer to
ActiveRecord::ConnectionAdapters::Mysql2. However, Mysql2::Error was not
updated, and that rescue will currently raise:

```
NameError: uninitialized constant ActiveRecord::ConnectionAdapters::Mysql2::Error
```

if the execute raises any error.

To fix this, Mysql2 must be changed to explicitly refer to the top level
namespace.

[1]: 93b5fc1f95e04b6a51f3e8dd2c885ba9ddd139a6
2023-05-23 13:42:32 -04:00
Jean Boussier
108617eb74 Fix change_in_place? for binary serialized columns
Followup: https://github.com/rails/rails/pull/40383
Fix: https://github.com/rails/rails/issues/48255
Fix: https://github.com/rails/rails/pull/48262

If the serialized attribute is backed by a binary column, we must ensure
that both the `raw_old_value` and the `raw_new_value` are casted to
`Binary::Data`.

Additionally, `Binary::Data` must cast it's backing string in
`Encoding::BINARY` otherwise comparison of strings containing bytes
outside the ASCII range will fail.
2023-05-22 13:01:42 +02:00
Jean Boussier
a3587cd6f9
Merge pull request #48271 from piecehealth/fix_ar_conn_verify
Rescue Exception while the connection pool 'checkout_and_verify'
2023-05-22 11:54:03 +02:00
Jean Boussier
785f65680b TrilogyAdapter: translate Trilogy::TimeoutError in AdapterTimeout
Prior to this patch it would translate it to `InvalidStatement` which
is the catch all and is hard to work with.
2023-05-22 10:05:11 +02:00
Kang Zhang
3b814f9866 Rescue Exception while the connection pool 'checkout_and_verify' 2023-05-22 14:23:58 +08:00
Hartley McGuire
2d98df02f9
Fixup links for CollectionProxy docs
Add some link and code blocks, and correct some docs referring to
methods on ActiveRecord::Base that are not.
2023-05-19 18:49:55 -04:00
Jean Boussier
f1b15971a5 Implement ActiveRecord.disconnect_all! to close all connections
This is basically a multi-db aware version of `ActiveRecord::Base.connection.disconnect!`.
It also avoid connecting to the database if we weren't already.

This can be useful to reset state after `establish_connection` has been used.
2023-05-19 13:19:31 +02:00
Yasuo Honda
a6bfa6c6e3
Merge pull request #48237 from a5-stable/fix-precision-maximum-for-mysql
fix a comment on `add_column` regarding the maximum value of precision in MySQL
2023-05-18 08:58:17 +09:00
a5-stable
ac1184d637 fix precision explanation for mysql 2023-05-17 01:26:03 +09:00
a5-stable
271562d82c call eq when begin and end are the same 2023-05-16 23:37:49 +09:00
zzak
9d2c6597cb
Use RDoc syntax for :uuid argument (re #47949) 2023-05-16 18:27:14 +09:00
Eileen M. Uchitelle
91481b180f
Merge pull request #48037 from fatkodima/index-include-as-strings
Return `INCLUDE` columns in PostgreSQL indexes as strings
2023-05-15 14:49:51 -04:00