/
CHANGELOG.md
1920 lines (1265 loc) · 66.1 KB
/
CHANGELOG.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
* Support decrypting data encrypted non-deterministically with a SHA1 hash digest.
This adds a new Active Record encryption option to support decrypting data encrypted
non-deterministically with a SHA1 hash digest:
```
Rails.application.config.active_record.encryption.support_sha1_for_non_deterministic_encryption = true
```
The new option addresses a problem when upgrading from 7.0 to 7.1. Due to a bug in how Active Record
Encryption was getting initialized, the key provider used for non-deterministic encryption were using
SHA-1 as its digest class, instead of the one configured globally by Rails via
`Rails.application.config.active_support.key_generator_hash_digest_class`.
*Cadu Ribeiro and Jorge Manrubia*
* Apply scope to association subqueries. (belongs_to/has_one/has_many)
Given: `has_many :welcome_posts, -> { where(title: "welcome") }`
Before:
```ruby
Author.where(welcome_posts: Post.all)
#=> SELECT (...) WHERE "authors"."id" IN (SELECT "posts"."author_id" FROM "posts")
```
Later:
```ruby
Author.where(welcome_posts: Post.all)
#=> SELECT (...) WHERE "authors"."id" IN (SELECT "posts"."author_id" FROM "posts" WHERE "posts"."title" = 'welcome')
```
*Lázaro Nixon*
* Added PostgreSQL migration commands for enum rename, add value, and rename value.
`rename_enum` and `rename_enum_value` are reversible. Due to Postgres
limitation, `add_enum_value` is not reversible since you cannot delete enum
values. As an alternative you should drop and recreate the enum entirely.
```ruby
rename_enum :article_status, to: :article_state
```
```ruby
add_enum_value :article_state, "archived" # will be at the end of existing values
add_enum_value :article_state, "in review", before: "published"
add_enum_value :article_state, "approved", after: "in review"
```
```ruby
rename_enum_value :article_state, from: "archived", to: "deleted"
```
*Ray Faddis*
* Allow composite primary key to be derived from schema
Booting an application with a schema that contains composite primary keys
will not issue warning and won't `nil`ify the `ActiveRecord::Base#primary_key` value anymore.
Given a `travel_routes` table definition and a `TravelRoute` model like:
```ruby
create_table :travel_routes, primary_key: [:origin, :destination], force: true do |t|
t.string :origin
t.string :destination
end
class TravelRoute < ActiveRecord::Base; end
```
The `TravelRoute.primary_key` value will be automatically derived to `["origin", "destination"]`
*Nikita Vasilevsky*
* Include the `connection_pool` with exceptions raised from an adapter.
The `connection_pool` provides added context such as the connection used
that led to the exception as well as which role and shard.
*Luan Vieira*
* Support multiple column ordering for `find_each`, `find_in_batches` and `in_batches`.
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
```
*Takuya Kurimoto*
* Fix where on association with has_one/has_many polymorphic relations.
Before:
```ruby
Treasure.where(price_estimates: PriceEstimate.all)
#=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates")
```
Later:
```ruby
Treasure.where(price_estimates: PriceEstimate.all)
#=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates" WHERE "price_estimates"."estimate_of_type" = 'Treasure')
```
*Lázaro Nixon*
* Assign auto populated columns on Active Record record creation.
Changes record creation logic to allow for the `auto_increment` column to be assigned
immediately after creation regardless of it's relation to the model's primary key.
The PostgreSQL adapter benefits the most from the change allowing for any number of auto-populated
columns to be assigned on the object immediately after row insertion utilizing the `RETURNING` statement.
*Nikita Vasilevsky*
* Use the first key in the `shards` hash from `connected_to` for the `default_shard`.
Some applications may not want to use `:default` as a shard name in their connection model. Unfortunately Active Record expects there to be a `:default` shard because it must assume a shard to get the right connection from the pool manager. Rather than force applications to manually set this, `connects_to` can infer the default shard name from the hash of shards and will now assume that the first shard is your default.
For example if your model looked like this:
```ruby
class ShardRecord < ApplicationRecord
self.abstract_class = true
connects_to shards: {
shard_one: { writing: :shard_one },
shard_two: { writing: :shard_two }
}
```
Then the `default_shard` for this class would be set to `shard_one`.
Fixes: #45390
*Eileen M. Uchitelle*
* Fix mutation detection for serialized attributes backed by binary columns.
*Jean Boussier*
* Add `ActiveRecord.disconnect_all!` method to immediately close all connections from all pools.
*Jean Boussier*
* Discard connections which may have been left in a transaction.
There are cases where, due to an error, `within_new_transaction` may unexpectedly leave a connection in an open transaction. In these cases the connection may be reused, and the following may occur:
- Writes appear to fail when they actually succeed.
- Writes appear to succeed when they actually fail.
- Reads return stale or uncommitted data.
Previously, the following case was detected:
- An error is encountered during the transaction, then another error is encountered while attempting to roll it back.
Now, the following additional cases are detected:
- An error is encountered just after successfully beginning a transaction.
- An error is encountered while committing a transaction, then another error is encountered while attempting to roll it back.
- An error is encountered while rolling back a transaction.
*Nick Dower*
* Active Record query cache now evicts least recently used entries
By default it only keeps the `100` most recently used queries.
The cache size can be configured via `database.yml`
```yaml
development:
adapter: mysql2
query_cache: 200
```
It can also be entirely disabled:
```yaml
development:
adapter: mysql2
query_cache: false
```
*Jean Boussier*
* Deprecate `check_pending!` in favor of `check_pending_migrations!`.
`check_pending!` will only check for pending migrations on the current database connection or the one passed in. This has been deprecated in favor of `check_pending_migrations!` which will find all pending migrations for the database configurations in a given environment.
*Eileen M. Uchitelle*
* Make `increment_counter`/`decrement_counter` accept an amount argument
```ruby
Post.increment_counter(:comments_count, 5, by: 3)
```
*fatkodima*
* Add support for `Array#intersect?` to `ActiveRecord::Relation`.
`Array#intersect?` is only available on Ruby 3.1 or later.
This allows the Rubocop `Style/ArrayIntersect` cop to work with `ActiveRecord::Relation` objects.
*John Harry Kelly*
* The deferrable foreign key can be passed to `t.references`.
*Hiroyuki Ishii*
* Deprecate `deferrable: true` option of `add_foreign_key`.
`deferrable: true` is deprecated in favor of `deferrable: :immediate`, and
will be removed in Rails 7.2.
Because `deferrable: true` and `deferrable: :deferred` are hard to understand.
Both true and :deferred are truthy values.
This behavior is the same as the deferrable option of the add_unique_key method, added in #46192.
*Hiroyuki Ishii*
* `AbstractAdapter#execute` and `#exec_query` now clear the query cache
If you need to perform a read only SQL query without clearing the query
cache, use `AbstractAdapter#select_all`.
*Jean Boussier*
* Make `.joins` / `.left_outer_joins` work with CTEs.
For example:
```ruby
Post
.with(commented_posts: Comment.select(:post_id).distinct)
.joins(:commented_posts)
#=> WITH (...) SELECT ... INNER JOIN commented_posts on posts.id = commented_posts.post_id
```
*Vladimir Dementyev*
* Add a load hook for `ActiveRecord::ConnectionAdapters::Mysql2Adapter`
(named `active_record_mysql2adapter`) to allow for overriding aspects of the
`ActiveRecord::ConnectionAdapters::Mysql2Adapter` class. This makes `Mysql2Adapter`
consistent with `PostgreSQLAdapter` and `SQLite3Adapter` that already have load hooks.
*fatkodima*
* Introduce adapter for Trilogy database client
Trilogy is a MySQL-compatible database client. Rails applications can use Trilogy
by configuring their `config/database.yml`:
```yaml
development:
adapter: trilogy
database: blog_development
pool: 5
```
Or by using the `DATABASE_URL` environment variable:
```ruby
ENV['DATABASE_URL'] # => "trilogy://localhost/blog_development?pool=5"
```
*Adrianna Chang*
* `after_commit` callbacks defined on models now execute in the correct order.
```ruby
class User < ActiveRecord::Base
after_commit { puts("this gets called first") }
after_commit { puts("this gets called second") }
end
```
Previously, the callbacks executed in the reverse order. To opt in to the new behaviour:
```ruby
config.active_record.run_after_transaction_callbacks_in_order_defined = true
```
This is the default for new apps.
*Alex Ghiculescu*
* Infer `foreign_key` when `inverse_of` is present on `has_one` and `has_many` associations.
```ruby
has_many :citations, foreign_key: "book1_id", inverse_of: :book
```
can be simplified to
```ruby
has_many :citations, inverse_of: :book
```
and the foreign_key will be read from the corresponding `belongs_to` association.
*Daniel Whitney*
* Limit max length of auto generated index names
Auto generated index names are now limited to 62 bytes, which fits within
the default index name length limits for MySQL, Postgres and SQLite.
Any index name over the limit will fallback to the new short format.
Before (too long):
```
index_testings_on_foo_and_bar_and_first_name_and_last_name_and_administrator
```
After (short format):
```
idx_on_foo_bar_first_name_last_name_administrator_5939248142
```
The short format includes a hash to ensure the name is unique database-wide.
*Mike Coutermarsh*
* Introduce a more stable and optimized Marshal serializer for Active Record models.
Can be enabled with `config.active_record.marshalling_format_version = 7.1`.
*Jean Boussier*
* Allow specifying where clauses with column-tuple syntax.
Querying through `#where` now accepts a new tuple-syntax which accepts, as
a key, an array of columns and, as a value, an array of corresponding tuples.
The key specifies a list of columns, while the value is an array of
ordered-tuples that conform to the column list.
For instance:
```ruby
# Cpk::Book => Cpk::Book(author_id: integer, number: integer, title: string, revision: integer)
# Cpk::Book.primary_key => ["author_id", "number"]
book = Cpk::Book.create!(author_id: 1, number: 1)
Cpk::Book.where(Cpk::Book.primary_key => [[1, 2]]) # => [book]
# Topic => Topic(id: integer, title: string, author_name: string...)
Topic.where([:title, :author_name] => [["The Alchemist", "Paul Coelho"], ["Harry Potter", "J.K Rowling"]])
```
*Paarth Madan*
* Allow warning codes to be ignore when reporting SQL warnings.
Active Record config that can ignore warning codes
```ruby
# Configure allowlist of warnings that should always be ignored
config.active_record.db_warnings_ignore = [
"1062", # MySQL Error 1062: Duplicate entry
]
```
This is supported for the MySQL and PostgreSQL adapters.
*Nick Borromeo*
* Introduce `:active_record_fixtures` lazy load hook.
Hooks defined with this name will be run whenever `TestFixtures` is included
in a class.
```ruby
ActiveSupport.on_load(:active_record_fixtures) do
self.fixture_paths << "test/fixtures"
end
klass = Class.new
klass.include(ActiveRecord::TestFixtures)
klass.fixture_paths # => ["test/fixtures"]
```
*Andrew Novoselac*
* Introduce `TestFixtures#fixture_paths`.
Multiple fixture paths can now be specified using the `#fixture_paths` accessor.
Apps will continue to have `test/fixtures` as their one fixture path by default,
but additional fixture paths can be specified.
```ruby
ActiveSupport::TestCase.fixture_paths << "component1/test/fixtures"
ActiveSupport::TestCase.fixture_paths << "component2/test/fixtures"
```
`TestFixtures#fixture_path` is now deprecated.
*Andrew Novoselac*
* Adds support for deferrable exclude constraints in PostgreSQL.
By default, exclude constraints in PostgreSQL are checked after each statement.
This works for most use cases, but becomes a major limitation when replacing
records with overlapping ranges by using multiple statements.
```ruby
exclusion_constraint :users, "daterange(valid_from, valid_to) WITH &&", deferrable: :immediate
```
Passing `deferrable: :immediate` checks constraint after each statement,
but allows manually deferring the check using `SET CONSTRAINTS ALL DEFERRED`
within a transaction. This will cause the excludes to be checked after the transaction.
It's also possible to change the default behavior from an immediate check
(after the statement), to a deferred check (after the transaction):
```ruby
exclusion_constraint :users, "daterange(valid_from, valid_to) WITH &&", deferrable: :deferred
```
*Hiroyuki Ishii*
* Respect `foreign_type` option to `delegated_type` for `{role}_class` method.
Usage of `delegated_type` with non-conventional `{role}_type` column names can now be specified with `foreign_type` option.
This option is the same as `foreign_type` as forwarded to the underlying `belongs_to` association that `delegated_type` wraps.
*Jason Karns*
* Add support for unique constraints (PostgreSQL-only).
```ruby
add_unique_key :sections, [:position], deferrable: :deferred, name: "unique_section_position"
remove_unique_key :sections, name: "unique_section_position"
```
See PostgreSQL's [Unique Constraints](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS) documentation for more on unique constraints.
By default, unique constraints in PostgreSQL are checked after each statement.
This works for most use cases, but becomes a major limitation when replacing
records with unique column by using multiple statements.
An example of swapping unique columns between records.
```ruby
# position is unique column
old_item = Item.create!(position: 1)
new_item = Item.create!(position: 2)
Item.transaction do
old_item.update!(position: 2)
new_item.update!(position: 1)
end
```
Using the default behavior, the transaction would fail when executing the
first `UPDATE` statement.
By passing the `:deferrable` option to the `add_unique_key` statement in
migrations, it's possible to defer this check.
```ruby
add_unique_key :items, [:position], deferrable: :immediate
```
Passing `deferrable: :immediate` does not change the behaviour of the previous example,
but allows manually deferring the check using `SET CONSTRAINTS ALL DEFERRED` within a transaction.
This will cause the unique constraints to be checked after the transaction.
It's also possible to adjust the default behavior from an immediate
check (after the statement), to a deferred check (after the transaction):
```ruby
add_unique_key :items, [:position], deferrable: :deferred
```
If you want to change an existing unique index to deferrable, you can use :using_index
to create deferrable unique constraints.
```ruby
add_unique_key :items, deferrable: :deferred, using_index: "index_items_on_position"
```
*Hiroyuki Ishii*
* Remove deprecated `Tasks::DatabaseTasks.schema_file_type`.
*Rafael Mendonça França*
* Remove deprecated `config.active_record.partial_writes`.
*Rafael Mendonça França*
* Remove deprecated `ActiveRecord::Base` config accessors.
*Rafael Mendonça França*
* Remove the `:include_replicas` argument from `configs_for`. Use `:include_hidden` argument instead.
*Eileen M. Uchitelle*
* Allow applications to lookup a config via a custom hash key.
If you have registered a custom config or want to find configs where the hash matches a specific key, now you can pass `config_key` to `configs_for`. For example if you have a `db_config` with the key `vitess` you can look up a database configuration hash by matching that key.
```ruby
ActiveRecord::Base.configurations.configs_for(env_name: "development", name: "primary", config_key: :vitess)
ActiveRecord::Base.configurations.configs_for(env_name: "development", config_key: :vitess)
```
*Eileen M. Uchitelle*
* Allow applications to register a custom database configuration handler.
Adds a mechanism for registering a custom handler for cases where you want database configurations to respond to custom methods. This is useful for non-Rails database adapters or tools like Vitess that you may want to configure differently from a standard `HashConfig` or `UrlConfig`.
Given the following database YAML we want the `animals` db to create a `CustomConfig` object instead while the `primary` database will be a `UrlConfig`:
```yaml
development:
primary:
url: postgres://localhost/primary
animals:
url: postgres://localhost/animals
custom_config:
sharded: 1
```
To register a custom handler first make a class that has your custom methods:
```ruby
class CustomConfig < ActiveRecord::DatabaseConfigurations::UrlConfig
def sharded?
custom_config.fetch("sharded", false)
end
private
def custom_config
configuration_hash.fetch(:custom_config)
end
end
```
Then register the config in an initializer:
```ruby
ActiveRecord::DatabaseConfigurations.register_db_config_handler do |env_name, name, url, config|
next unless config.key?(:custom_config)
CustomConfig.new(env_name, name, url, config)
end
```
When the application is booted, configuration hashes with the `:custom_config` key will be `CustomConfig` objects and respond to `sharded?`. Applications must handle the condition in which Active Record should use their custom handler.
*Eileen M. Uchitelle and John Crepezzi*
* `ActiveRecord::Base.serialize` no longer uses YAML by default.
YAML isn't particularly performant and can lead to security issues
if not used carefully.
Unfortunately there isn't really any good serializers in Ruby's stdlib
to replace it.
The obvious choice would be JSON, which is a fine format for this use case,
however the JSON serializer in Ruby's stdlib isn't strict enough, as it fallback
to casting unknown types to strings, which could lead to corrupted data.
Some third party JSON libraries like `Oj` have a suitable strict mode.
So it's preferable that users choose a serializer based on their own constraints.
The original default can be restored by setting `config.active_record.default_column_serializer = YAML`.
*Jean Boussier*
* `ActiveRecord::Base.serialize` signature changed.
Rather than a single positional argument that accepts two possible
types of values, `serialize` now accepts two distinct keyword arguments.
Before:
```ruby
serialize :content, JSON
serialize :backtrace, Array
```
After:
```ruby
serialize :content, coder: JSON
serialize :backtrace, type: Array
```
*Jean Boussier*
* YAML columns use `YAML.safe_dump` is available.
As of `psych 5.1.0`, `YAML.safe_dump` can now apply the same permitted
types restrictions than `YAML.safe_load`.
It's preferable to ensure the payload only use allowed types when we first
try to serialize it, otherwise you may end up with invalid records in the
database.
*Jean Boussier*
* `ActiveRecord::QueryLogs` better handle broken encoding.
It's not uncommon when building queries with BLOB fields to contain
binary data. Unless the call carefully encode the string in ASCII-8BIT
it generally end up being encoded in `UTF-8`, and `QueryLogs` would
end up failing on it.
`ActiveRecord::QueryLogs` no longer depend on the query to be properly encoded.
*Jean Boussier*
* Fix a bug where `ActiveRecord::Generators::ModelGenerator` would not respect create_table_migration template overrides.
```
rails g model create_books title:string content:text
```
will now read from the create_table_migration.rb.tt template in the following locations in order:
```
lib/templates/active_record/model/create_table_migration.rb
lib/templates/active_record/migration/create_table_migration.rb
```
*Spencer Neste*
* `ActiveRecord::Relation#explain` now accepts options.
For databases and adapters which support them (currently PostgreSQL
and MySQL), options can be passed to `explain` to provide more
detailed query plan analysis:
```ruby
Customer.where(id: 1).joins(:orders).explain(:analyze, :verbose)
```
*Reid Lynch*
* Multiple `Arel::Nodes::SqlLiteral` nodes can now be added together to
form `Arel::Nodes::Fragments` nodes. This allows joining several pieces
of SQL.
*Matthew Draper*, *Ole Friis*
* `ActiveRecord::Base#signed_id` raises if called on a new record.
Previously it would return an ID that was not usable, since it was based on `id = nil`.
*Alex Ghiculescu*
* Allow SQL warnings to be reported.
Active Record configs can be set to enable SQL warning reporting.
```ruby
# Configure action to take when SQL query produces warning
config.active_record.db_warnings_action = :raise
# Configure allowlist of warnings that should always be ignored
config.active_record.db_warnings_ignore = [
/Invalid utf8mb4 character string/,
"An exact warning message",
]
```
This is supported for the MySQL and PostgreSQL adapters.
*Adrianna Chang*, *Paarth Madan*
* Add `#regroup` query method as a short-hand for `.unscope(:group).group(fields)`
Example:
```ruby
Post.group(:title).regroup(:author)
# SELECT `posts`.`*` FROM `posts` GROUP BY `posts`.`author`
```
*Danielius Visockas*
* PostgreSQL adapter method `enable_extension` now allows parameter to be `[schema_name.]<extension_name>`
if the extension must be installed on another schema.
Example: `enable_extension('heroku_ext.hstore')`
*Leonardo Luarte*
* Add `:include` option to `add_index`.
Add support for including non-key columns in indexes for PostgreSQL
with the `INCLUDE` parameter.
```ruby
add_index(:users, :email, include: [:id, :created_at])
```
will result in:
```sql
CREATE INDEX index_users_on_email USING btree (email) INCLUDE (id, created_at)
```
*Steve Abrams*
* `ActiveRecord::Relation`’s `#any?`, `#none?`, and `#one?` methods take an optional pattern
argument, more closely matching their `Enumerable` equivalents.
*George Claghorn*
* Add `ActiveRecord::Base::normalizes` to declare attribute normalizations.
A normalization is applied when the attribute is assigned or updated, and
the normalized value will be persisted to the database. The normalization
is also applied to the corresponding keyword argument of finder methods.
This allows a record to be created and later queried using unnormalized
values. For example:
```ruby
class User < ActiveRecord::Base
normalizes :email, with: -> email { email.strip.downcase }
end
user = User.create(email: " CRUISE-CONTROL@EXAMPLE.COM\n")
user.email # => "cruise-control@example.com"
user = User.find_by(email: "\tCRUISE-CONTROL@EXAMPLE.COM ")
user.email # => "cruise-control@example.com"
user.email_before_type_cast # => "cruise-control@example.com"
User.exists?(email: "\tCRUISE-CONTROL@EXAMPLE.COM ") # => true
User.exists?(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]) # => false
```
*Jonathan Hefner*
* Hide changes to before_committed! callback behaviour behind flag.
In #46525, behavior around before_committed! callbacks was changed so that callbacks
would run on every enrolled record in a transaction, not just the first copy of a record.
This change in behavior is now controlled by a configuration option,
`config.active_record.before_committed_on_all_records`. It will be enabled by default on Rails 7.1.
*Adrianna Chang*
* The `namespaced_controller` Query Log tag now matches the `controller` format
For example, a request processed by `NameSpaced::UsersController` will now log as:
```
:controller # "users"
:namespaced_controller # "name_spaced/users"
```
*Alex Ghiculescu*
* Return only unique ids from ActiveRecord::Calculations#ids
Updated ActiveRecord::Calculations#ids to only return the unique ids of the base model
when using eager_load, preload and includes.
```ruby
Post.find_by(id: 1).comments.count
# => 5
Post.includes(:comments).where(id: 1).pluck(:id)
# => [1, 1, 1, 1, 1]
Post.includes(:comments).where(id: 1).ids
# => [1]
```
*Joshua Young*
* Stop using `LOWER()` for case-insensitive queries on `citext` columns
Previously, `LOWER()` was added for e.g. uniqueness validations with
`case_sensitive: false`.
It wasn't mentioned in the documentation that the index without `LOWER()`
wouldn't be used in this case.
*Phil Pirozhkov*
* Extract `#sync_timezone_changes` method in AbstractMysqlAdapter to enable subclasses
to sync database timezone changes without overriding `#raw_execute`.
*Adrianna Chang*, *Paarth Madan*
* Do not write additional new lines when dumping sql migration versions
This change updates the `insert_versions_sql` function so that the database insert string containing the current database migration versions does not end with two additional new lines.
*Misha Schwartz*
* Fix `composed_of` value freezing and duplication.
Previously composite values exhibited two confusing behaviors:
- When reading a compositve value it'd _NOT_ be frozen, allowing it to get out of sync with its underlying database
columns.
- When writing a compositve value the argument would be frozen, potentially confusing the caller.
Currently, composite values instantiated based on database columns are frozen (addressing the first issue) and
assigned compositve values are duplicated and the duplicate is frozen (addressing the second issue).
*Greg Navis*
* Fix redundant updates to the column insensitivity cache
Fixed redundant queries checking column capability for insensitive
comparison.
*Phil Pirozhkov*
* Allow disabling methods generated by `ActiveRecord.enum`.
*Alfred Dominic*
* Avoid validating `belongs_to` association if it has not changed.
Previously, when updating a record, Active Record will perform an extra query to check for the presence of
`belongs_to` associations (if the presence is configured to be mandatory), even if that attribute hasn't changed.
Currently, only `belongs_to`-related columns are checked for presence. It is possible to have orphaned records with
this approach. To avoid this problem, you need to use a foreign key.
This behavior can be controlled by configuration:
```ruby
config.active_record.belongs_to_required_validates_foreign_key = false
```
and will be disabled by default with `config.load_defaults 7.1`.
*fatkodima*
* `has_one` and `belongs_to` associations now define a `reset_association` method
on the owner model (where `association` is the name of the association). This
method unloads the cached associate record, if any, and causes the next access
to query it from the database.
*George Claghorn*
* Allow per attribute setting of YAML permitted classes (safe load) and unsafe load.
*Carlos Palhares*
* Add a build persistence method
Provides a wrapper for `new`, to provide feature parity with `create`s
ability to create multiple records from an array of hashes, using the
same notation as the `build` method on associations.
*Sean Denny*
* Raise on assignment to readonly attributes
```ruby
class Post < ActiveRecord::Base
attr_readonly :content
end
Post.create!(content: "cannot be updated")
post.content # "cannot be updated"
post.content = "something else" # => ActiveRecord::ReadonlyAttributeError
```
Previously, assignment would succeed but silently not write to the database.
This behavior can be controlled by configuration:
```ruby
config.active_record.raise_on_assign_to_attr_readonly = true
```
and will be enabled by default with `config.load_defaults 7.1`.
*Alex Ghiculescu*, *Hartley McGuire*
* Allow unscoping of preload and eager_load associations
Added the ability to unscope preload and eager_load associations just like
includes, joins, etc. See ActiveRecord::QueryMethods::VALID_UNSCOPING_VALUES
for the full list of supported unscopable scopes.
```ruby
query.unscope(:eager_load, :preload).group(:id).select(:id)
```
*David Morehouse*
* Add automatic filtering of encrypted attributes on inspect
This feature is enabled by default but can be disabled with
```ruby
config.active_record.encryption.add_to_filter_parameters = false
```
*Hartley McGuire*
* Clear locking column on #dup
This change fixes not to duplicate locking_column like id and timestamps.
```
car = Car.create!
car.touch
car.lock_version #=> 1
car.dup.lock_version #=> 0
```
*Shouichi Kamiya*, *Seonggi Yang*, *Ryohei UEDA*
* Invalidate transaction as early as possible
After rescuing a `TransactionRollbackError` exception Rails invalidates transactions earlier in the flow
allowing the framework to skip issuing the `ROLLBACK` statement in more cases.
Only affects adapters that have `savepoint_errors_invalidate_transactions?` configured as `true`,
which at this point is only applicable to the `mysql2` adapter.
*Nikita Vasilevsky*
* Allow configuring columns list to be used in SQL queries issued by an `ActiveRecord::Base` object
It is now possible to configure columns list that will be used to build an SQL query clauses when
updating, deleting or reloading an `ActiveRecord::Base` object
```ruby
class Developer < ActiveRecord::Base
query_constraints :company_id, :id
end
developer = Developer.first.update(name: "Bob")
# => UPDATE "developers" SET "name" = 'Bob' WHERE "developers"."company_id" = 1 AND "developers"."id" = 1
```
*Nikita Vasilevsky*
* Adds `validate` to foreign keys and check constraints in schema.rb
Previously, `schema.rb` would not record if `validate: false` had been used when adding a foreign key or check
constraint, so restoring a database from the schema could result in foreign keys or check constraints being
incorrectly validated.
*Tommy Graves*
* Adapter `#execute` methods now accept an `allow_retry` option. When set to `true`, the SQL statement will be
retried, up to the database's configured `connection_retries` value, upon encountering connection-related errors.
*Adrianna Chang*
* Only trigger `after_commit :destroy` callbacks when a database row is deleted.
This prevents `after_commit :destroy` callbacks from being triggered again
when `destroy` is called multiple times on the same record.
*Ben Sheldon*
* Fix `ciphertext_for` for yet-to-be-encrypted values.
Previously, `ciphertext_for` returned the cleartext of values that had not
yet been encrypted, such as with an unpersisted record:
```ruby
Post.encrypts :body
post = Post.create!(body: "Hello")
post.ciphertext_for(:body)
# => "{\"p\":\"abc..."
post.body = "World"
post.ciphertext_for(:body)
# => "World"
```
Now, `ciphertext_for` will always return the ciphertext of encrypted
attributes:
```ruby
Post.encrypts :body
post = Post.create!(body: "Hello")
post.ciphertext_for(:body)
# => "{\"p\":\"abc..."
post.body = "World"
post.ciphertext_for(:body)
# => "{\"p\":\"xyz..."
```
*Jonathan Hefner*