Commit Graph

21047 Commits

Author SHA1 Message Date
Rafael França
0c93edd244
Merge pull request #42940 from SkipKayhil/engine-migration-newline
Move comment after newline in installed migrations
2021-08-05 23:30:06 -04:00
Rafael Mendonça França
c91a8135c7
Allow using a different socket to test mysql 2021-08-05 14:27:30 -04:00
Ryuta Kamizono
ac45e1d396
Merge pull request #42948 from yahonda/diag79936
Address "NameError: Rails couldn't find a valid model for Club association"
2021-08-05 13:31:01 +09:00
Yasuo Honda
945aa87466 Address "NameError: Rails couldn't find a valid model for Club association"
This commit addresses CI failure of Active Record isolation tests.
https://buildkite.com/rails/rails/builds/79936

Follow up #41392

* Steps to reproduce
```ruby
$ cd activerecord
$ bin/test test/cases/associations/belongs_to_associations_test.rb test/cases/associations/has_many_associations_test.rb test/cases/associations/has_many_through_disable_joins_associations_test.rb test/cases/associations/has_one_associations_test.rb test/cases/connection_adapters/schema_cache_test.rb test/cases/inheritance_test.rb test/cases/migration_test.rb test/cases/store_test.rb test/cases/strict_loading_test.rb
```

Since the entire output is too long, here is the minimum case fixed by
this commit.

```ruby
$ cd activerecord
$ bin/test test/cases/associations/belongs_to_associations_test.rb:38
Using sqlite3
Run options: --seed 34180

E

Error:
BelongsToAssociationsTest#test_belongs_to:
NameError: Rails couldn't find a valid model for Club association. Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass.
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:431:in `rescue in compute_class'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:422:in `compute_class'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:372:in `klass'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:722:in `association_primary_key'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/reflection.rb:727:in `join_primary_key'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_row.rb:150:in `block in resolve_sti_reflections'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_row.rb:138:in `each_value'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_row.rb:138:in `resolve_sti_reflections'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_row.rb:92:in `fill_row_model_attributes'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_row.rb:70:in `initialize'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_rows.rb:36:in `new'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_rows.rb:36:in `block in build_table_rows_from'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_rows.rb:35:in `each'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_rows.rb:35:in `map'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_rows.rb:35:in `build_table_rows_from'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixture_set/table_rows.rb:18:in `initialize'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:692:in `new'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:692:in `table_rows'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:633:in `block (2 levels) in insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:632:in `each'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:632:in `block in insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:629:in `each'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:629:in `insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:615:in `read_and_insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:567:in `create_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/test_fixtures.rb:268:in `load_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/test_fixtures.rb:122:in `setup_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/test_fixtures.rb:10:in `before_setup'

bin/test test/cases/associations/belongs_to_associations_test.rb:38

Finished in 0.083668s, 11.9520 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
$
```
2021-08-05 12:40:19 +09:00
Kasper Timm Hansen
845280a8f8
Merge branch 'main' into structurally-compatible 2021-08-04 17:23:07 +02:00
Kasper Timm Hansen
cd469fdbb3
Merge pull request #41392 from kddnewton/raise-error-belongs-to-custom-primary-key
Raise error on invalid fixture primary key
2021-08-04 17:20:29 +02:00
Kasper Timm Hansen
14540a50a0
Merge pull request #42061 from kddnewton/ar-in-order-of
Add `ActiveRecord::QueryMethods#in_order_of`.
2021-08-04 17:17:07 +02:00
Hartley McGuire
43f756778f Move comment after newline in installed migrations
When an engine's migration is installed in a rails application, a
comment is inserted after any magic comments indicating the migration's
source. However, the current implementation does not take into
account whether there is an empty line after magic comments, and the
generated migration will not pass rubocop's
Layout/EmptyLineAfterMagicComment even if the engine's migration did.
This commit changes the implementation to insert the new comment after
a newline occuring after magic comments, if it exists.

Example Engine Migration:
```ruby
# frozen_string_literal: true
# coding: ISO-8859-15

class CurrenciesHaveSymbols < ActiveRecord::Migration::Current
end
```

Before change:
```ruby
# frozen_string_literal: true
# coding: ISO-8859-15
# This migration comes from bukkits (originally 1)

class CurrenciesHaveSymbols < ActiveRecord::Migration::Current
end
```

After change:
```ruby
# frozen_string_literal: true
# coding: ISO-8859-15

# This migration comes from bukkits (originally 1)
class CurrenciesHaveSymbols < ActiveRecord::Migration::Current
end
```
2021-08-04 00:52:53 -04:00
Washington Botelho
7ab3390dfb
Better description for ensuring_owner_was prop
Co-authored-by: Kasper Timm Hansen <kaspth@gmail.com>
2021-08-02 22:15:40 -03:00
Kevin Newton
459ca2258c
Add ActiveRecord::QueryMethods#in_order_of.
This allows you to specify an explicit order that you'd like records
returned in based on a SQL expression. By default, this will be accomplished
using a case statement, as in:

```ruby
Post.in_order_of(:id, [3, 5, 1])
```

will generate the SQL:

```sql
SELECT "posts".* FROM "posts" ORDER BY CASE "posts"."id" WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASC
```

However, because this functionality is built into MySQL in the form of the
`FIELD` function, that connection adapter will generate the following SQL
instead:

```sql
SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESC
```

*Kevin Newton*
2021-08-02 16:11:36 -04:00
Kevin Newton
d31071a5a2
Add ActiveRecord::Relation#structurally_compatible?. 2021-08-02 16:10:40 -04:00
Washington Botelho
668fbc62fb
ensuring_owner_was enabled only with dependent 2021-08-02 10:19:33 -03:00
Jacopo
d5b6e5dabe Fix eager_loading? when ordering with Symbol
`eager_loading?` is triggered correctly when using `order` with symbols.

```ruby
scope = Post.includes(:comments).order(:"comments.label")
=> true
```
2021-07-30 10:19:07 +02:00
Rafael Mendonça França
18707ab17f
Standardize nodoc comments 2021-07-29 21:18:07 +00:00
eileencodes
b31c2fd017
Fix typo in docs
It's marshal not marchal.
2021-07-29 12:10:43 -04:00
Jacopo
d7c0b4542c Remove offensive wording from active record
Remove "This shit is nasty" offensive wording from active record.
2021-07-28 21:25:50 +02:00
Rafael França
4ae0390c10
Merge pull request #42894 from jonathanhefner/fix-incomplete-nodoc
Fix incomplete :nodoc: directives [ci-skip]
2021-07-28 13:39:46 -04:00
Jonathan Hefner
d766c672ec Apply :nodoc: to all DatabaseStatements overrides [ci-skip] 2021-07-28 12:30:51 -05:00
Jonathan Hefner
11c2c0ef2f Fix incomplete :nodoc: directives [ci-skip] 2021-07-28 10:30:06 -05:00
eileencodes
311d0babfb
Remove "stupid" from active record
The language in the docs is clearer without saying MySQL is stupid. The
test doesn't need stupid in the value to be used - an incorrect value is
incorrect.
2021-07-28 11:09:10 -04:00
Jean Boussier
796aba1678
Merge pull request #40822 from fatkodima/fix-mysql-column-default
Fix retrieving default value for text column for MariaDB
2021-07-27 23:30:26 +02:00
George Claghorn
3fa7dce079 Remove outdated comment in ActiveRecord::Associations::AssociationScope#add_constraints [ci skip]
This comment was correct when it was added in 65843e1. In that commit, ActiveRecord::AssociationScope#scope applies the nearest association's scope, and #add_constraints skips it.

c8d8899 made the comment incorrect. It modified #scope not to apply the nearest association's scope and #add_constraints to apply scopes for the entire association chain.
2021-07-24 17:55:01 -04:00
Ryuta Kamizono
5d78c54a46
Merge pull request #42829 from yahonda/diag79471
Address FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations error
2021-07-21 18:05:10 +09:00
Yasuo Honda
d481d08449 Address FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations
Managed to reproduce CI failure at https://buildkite.com/rails/rails/builds/79496#0c03f856-9be1-4ca0-88c9-e1df21ae0a07

This commitaddresses the following errors by loading :author_addresses fixture because
`:authors` has a foreign key to `:author_addresses`.

* sqlite3 adapter
```ruby
$ bin/test test/cases/adapters/sqlite3/explain_test.rb test/cases/fixtures_test.rb -n "/^(?:SQLite3ExplainTest#(?:test_explain_with_eager_loading)|FixturesWithForeignKeyViolationsTest#(?:test_does_not_raise_if_no_fk_violations))$/" --seed 2529
Using sqlite3
Run options: -n "/^(?:SQLite3ExplainTest#(?:test_explain_with_eager_loading)|FixturesWithForeignKeyViolationsTest#(?:test_does_not_raise_if_no_fk_violations))$/" --seed 2529

.E

Error:
FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations:
RuntimeError: Foreign key violations found in your fixture data. Ensure you aren't referring to labels that don't exist on associations.
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:641:in `block in insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:629:in `each'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:629:in `insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:615:in `read_and_insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:567:in `create_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:844:in `block (2 levels) in test_does_not_raise_if_no_fk_violations'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/testing/assertions.rb:34:in `assert_nothing_raised'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:843:in `block in test_does_not_raise_if_no_fk_violations'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:857:in `with_verify_foreign_keys_for_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:842:in `test_does_not_raise_if_no_fk_violations'

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

Finished in 0.045767s, 43.6991 runs/s, 174.7966 assertions/s.
2 runs, 8 assertions, 0 failures, 1 errors, 0 skips
$
```

* postgresql adapter

```ruby
$ ARCONN=postgresql bin/test test/cases/adapters/postgresql/explain_test.rb test/cases/fixtures_test.rb -n "/^(?:PostgreSQLExplainTest#(?:test_explain_with_eager_loading)|FixturesWithForeignKeyViolationsTest#(?:test_does_not_raise_if_no_fk_violations))$/" --seed 16926
Using postgresql
Run options: -n "/^(?:PostgreSQLExplainTest#(?:test_explain_with_eager_loading)|FixturesWithForeignKeyViolationsTest#(?:test_does_not_raise_if_no_fk_violations))$/" --seed 16926

.E

Error:
FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations:
RuntimeError: Foreign key violations found in your fixture data. Ensure you aren't referring to labels that don't exist on associations.
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:641:in `block in insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:629:in `each'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:629:in `insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:615:in `read_and_insert'
    /home/yahonda/src/github.com/rails/rails/activerecord/lib/active_record/fixtures.rb:567:in `create_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:844:in `block (2 levels) in test_does_not_raise_if_no_fk_violations'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/testing/assertions.rb:34:in `assert_nothing_raised'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:843:in `block in test_does_not_raise_if_no_fk_violations'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:857:in `with_verify_foreign_keys_for_fixtures'
    /home/yahonda/src/github.com/rails/rails/activerecord/test/cases/fixtures_test.rb:842:in `test_does_not_raise_if_no_fk_violations'

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

Finished in 0.121193s, 16.5027 runs/s, 49.5080 assertions/s.
2 runs, 6 assertions, 0 failures, 1 errors, 0 skips
$
```

* It does not reproduce with mysql2 adapter because MySQL does not have
  features to validate existing foreign keys, but added
  :author_addresses in Mysql2ExplainTest for consistency.

Follow up #42674
2021-07-21 16:54:35 +09:00
Jean Boussier
48f4c88214 Fix changelog entry for active_record.partial_inserts 2021-07-21 09:12:36 +02:00
Ryuta Kamizono
e50b0e3ab3 Fixup CHANGELOGs [ci skip] 2021-07-21 10:08:08 +09:00
Ryuta Kamizono
a206aecedf chore: Use e.g. which is the more used spelling
```
% git grep -i '\be\.g\.' | wc -l
290
```
2021-07-21 09:17:54 +09:00
Eileen M. Uchitelle
fad8d8a0f3
Merge pull request #42803 from gregschmit/gns/fix-migrate-status-order
db:migrate:status: Sort migration ID as integer for consistency.
2021-07-20 08:29:10 -04:00
George Claghorn
fc3acf2e8d Add change tracking methods for belongs_to associations
Permit checking whether a belongs_to association has been pointed to a new target record in the previous save and whether it will point to a new target record in the next save.

    post.category # => #<Category id: 1, name: "Ruby">

    post.category = Category.second   # => #<Category id: 2, name: "Programming">
    post.category_changed?            # => true
    post.category_previously_changed? # => false

    post.save!

    post.category_changed?            # => false
    post.category_previously_changed? # => true
2021-07-19 14:39:13 -04:00
Santiago Bartesaghi
60d99db356 Fix minor typo [ci skip] 2021-07-19 12:01:29 -03:00
eileencodes
10ca60a16b
Add option to disable schema dumb per-database
Dumping the schema is on by default for all databases in an application. To turn it off for a
specific database use the `schema_dump` option:

```yaml
  # config/database.yml

  production:
  schema_dump: false
```

Co-authored-by: Luis Vasconcellos <vasconcelloslf@gmail.com>
2021-07-19 07:58:49 -04:00
Gregory N. Schmit
78955b925a
Sort migration ID as int in db:migrate:status for consistency. 2021-07-16 13:10:31 -05:00
Jacopo
8ab892e7b1 Fix eager_loading? when ordering with Hash syntax
`eager_loading?` is triggered correctly when using `order` with
hash syntax on an outer table.

before:
```ruby
Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
=> raises ActiveRecord::StatementInvalid
```

after:
```ruby
Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
=> true
```

Co-authored-by: Eugene Kenny <elkenny@gmail.com>
2021-07-15 14:26:31 +02:00
Daniel Colson
d30c85cebd
Fix bug with TypeMap default values
https://github.com/rails/rails/pull/42773 introduced a regression where
looking up an unregistered type on a TypeMap with a parent (like
[mysql2 TYPE_MAP_WITH_BOOLEAN](88ec15b850/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb (L618))
would cause a `LocalJumpError`

This commit fixes the error by forwarding the default block when
fetching from the parent TypeMap.

Co-authored-by: Chris Bloom <chrisbloom7@gmail.com>
2021-07-14 13:26:37 -04:00
Eileen M. Uchitelle
7127105cca
Merge pull request #42778 from dark-panda/fix-42699-move-forced-encoding-to-encryptor
Move forced encoding on deterministic encryption to the default encryptor
2021-07-14 12:40:50 -04:00
John Hawthorn
7f8eccc3f1
Merge pull request #42654 from dinahshi/preloader-from-available
Add `available_records` argument to Associations::Preloader
2021-07-14 07:09:32 -07:00
Kevin Newton
006eb25ccd
Raise error on invalid fixture primary key
When you're using a custom primary key on a belongs_to and you're trying to load that value through the association shorthand in a fixture, you end up getting the primary key of the table and not the primary key specified in the join. This makes sense to keep as the behavior because it's super fast (just hashing the name of the fixture), but it's still surprising so we should want the developer that it's not possible to do what they want.
2021-07-14 08:54:38 -04:00
Dinah Shi
2a3f1757dd Add available_records argument to Associations::Preloader
Sometimes when we are preloading associations on records, we already have
the association objects loaded in-memory. But the Preloader will go to the
database to fetch them anyways because there is no way to tell it about
these loaded objects. This PR adds a new `available_records` argument to
supply the Preloader with a set of in-memory records that it can use to
fill associations without making a database query.

`available_records` is an array of ActiveRecord::Base objects. Mixed
models are supported. Preloader will use these records to try to fill the
requested associations before querying the database. This can save database
queries by reusing in-memory objects.

The optimization is only applied to single associations (i.e. :belongs_to,
:has_one) as we must query the database to do an exhaustive lookup for
collections (i.e. :has_many). It also requires the query to have no scopes
as scopes can filter associations even if they are already in memory.

```ruby
comment = Comment.last
post = Post.find_by(id: comment.post_id)
all_authors = Author.all.to_a

Preloader.new([comment], [:post, :author]).call

Preloader.new([comment], [:post, :author], available_records: [post, all_authors]).call
```

Co-Authored-By: John Hawthorn <john@hawthorn.email>
2021-07-14 08:44:03 -04:00
J Smith
35e88cd6d9 Move forced encoding on deterministic encryption to the default encryptor 2021-07-13 16:02:38 -03:00
Jean Boussier
cf7db80fe1 Refactor ActiveRecord::Type::TypeMap
A good part of the complexity was to support the HashLookupTypeMap
subclass that's only used by the Postgres adapter.

In the end they have a similar-ish interface but this inheritance
doesn't help much.

Worse, adapters using `TypeMap` doesn't need extra arguments. By
skipping this unused feature, we can drastically reduce the memory
footprint, as this feature imposed a 320B per entry overhead.
2021-07-13 17:37:08 +02:00
Jean Boussier
88ec15b850
Merge pull request #42773 from Shopify/static-typemaps
Define adapter type maps statically when possible
2021-07-13 15:56:55 +02:00
Jean Boussier
d79fb96360 Define adapter type maps statically when possible
Each type map can use a non trivial amount of memory (over 10KiB
in our app).

Currently each connection build its own type map from scratch, but
except for postgresql which has extension types, all connections
end up with the same maps.

So the more connections you have the more memory it wastes.

By defining the type map statically for MySQL and SQLite3 connections
we save some memory, share caches, and allow that memory to be handled
by Copy on Write for forking setups.
2021-07-13 14:21:03 +02:00
alkeshghorpade
a6ce872ec6 [ci-skip] typo fix in activerecord changelog 2021-07-13 17:01:11 +05:30
Jean Boussier
91082730cc Disable Active Record partial_inserts by default in Rails 7.0
Ref: https://github.com/rails/rails/pull/42355

The justification for `partial_inserts` back in 2012
(144e8691cbfb8bba77f18cfe68d5e7fd48887f5e) was:

> This is more efficient, and also means that it will be safe to remove
> database columns without getting subsequent errors in running app processes
> (so long as the code in those processes doesn't contain any references to the
> removed column).

But since then `ignored_columns` is a much more reliable way to safely remove a
column, and I doubt the reduced query size really help much.

Additionally, `partial_inserts` prevent removing the default value of a column
in a safe way.
2021-07-13 11:02:12 +02:00
Zachary Scott
bd720c9791
Merge pull request #42760 from ghiculescu/patch-4
Add CHANGELOG for #42674
2021-07-13 15:02:43 +09:00
Alex Ghiculescu
647f4bd17f Add docs for attr_readonly
From https://github.com/rails/rails/pull/42705#issuecomment-878415276 - explicitly call out that assigning attributes works, but is ignored by saves.

Co-authored-by: Petrik de Heus <petrik@deheus.net>
2021-07-12 12:56:25 -05:00
Ryuta Kamizono
e06706201a
Merge pull request #42765 from p8/activerecord/fix-reflection-warning-message
Fix spelling in compute_class warning
2021-07-13 02:52:31 +09:00
Petrik
a2fca818c7 Fix spelling in compute_class warning 2021-07-12 19:38:28 +02:00
eileencodes
eb50860fe9
Revert "Merge pull request #40445 from robertomiranda/destroy_all-in_batcches"
This reverts commit 1cdee90d385399083596c22343cc46f51283aca3, reversing
changes made to c3a1bfe187d594ed2c2348cc0ae6c5c894368b8e.

We are reverting this because it caused a change in behavior and we need
to discuss how to address that behavior change and find a work around
that doesn't break existing applications.
2021-07-12 13:15:13 -04:00
Alex Ghiculescu
32ff2c2bf3
Add CHANGELOG for #42674
Fixes https://github.com/rails/rails/pull/42674#issuecomment-877714992

cc @zzak
2021-07-12 10:23:58 -05:00
Jean Boussier
317547e0e7
Merge pull request #42729 from Shopify/fix-has-many-inversing-remove
Fix clearing the inverse relation when has_many_inversing is enabled
2021-07-08 12:18:14 +02:00
Jean Boussier
6d7235dd20 Fix clearing the inverse relation when has_many_inversing is enabled
https://github.com/rails/rails/pull/42601 fixed clearing the inverse relation,
but it didn't account for collection associations.

For these, just assigning `nil` isn't possible because we need the record to
remove it from the collection.

So this PR introduce an explicit method for this purpose rather than
reuse `inversed_from(nil)`.
2021-07-08 11:25:32 +02:00
Jean Boussier
197fb159ec
Merge pull request #42666 from justin808/patch-1
Improve logging of schema cache at startup.
2021-07-08 10:02:41 +02:00
Justin Gordon
9f9c1bf79e Improve logging of schema cache at startup.
This allows verification if the schema cache was used at startup.
2021-07-07 21:33:00 -10:00
Alex Ghiculescu
47467fe33d Verify foreign keys after loading fixtures
When writing fixtures, it's currently possible to define associations that don't exist, even if a foreign key exists. For example:

```yml
george:
  name: "Curious George"
  pirate: redbeard

blackbeard:
  name: "Blackbeard"
 ```

When the fixtures are created, `parrots(:george).pirate` will be nil, but it's not immediately clear why. This can make it hard to debug tests and can give false confidence in passing ones.

This can happen because Rails [disables referential integrity](f263530bf7/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb (L407)) when inserting fixtures. This makes the fixtures algorithm much simpler - it can just create the fixtures in alphabetical order and assume that the other side of a foreign key constraint will *eventually* be added.

Ideally we would check foreign keys once all fixtures have been loaded, so that we can be sure that the foreign key constraints were met. This PR introduces that. To enable it:

```ruby
config.active_record.verify_foreign_keys_for_fixtures = true
```

I'm proposing we enable this in 7.0 for new apps and have added it to new framework defaults. When run against our app, it found 3 fixture files with unmet FK constraints - turns out all those fixtures weren't being used and were safe to delete.
2021-07-07 15:41:05 -05:00
Jonathan del Strother
0c25a0baee
Micro-optimize ActiveRecord::Core#hash
Avoids calling _read_attribute("id") more than necessary

```ruby
require "active_record"
require "benchmark/ips"

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database:  ":memory:")
ActiveRecord::Base.connection.create_table :users do |t|
  t.text :name
end

class User < ActiveRecord::Base
  # This is the current implementation from ActiveRecord::Core
  def hash
    if id
      self.class.hash ^ id.hash
    else
      super
    end
  end
end
class UserFastHash < ActiveRecord::Base
  self.table_name = "users"
  def hash
    if i = id
      self.class.hash ^ i.hash
    else
      super
    end
  end
end

1_000.times { |i| User.create(name: "test #{i}") }
slow_users = User.take(1000)
fast_users = UserFastHash.take(1000)

Benchmark.ips do |x|
  x.report("slowhash") {
    hash = {}
    slow_users.each { |u| hash[u] = 1 }
  }
  x.report("fasthash") {
    hash = {}
    fast_users.each { |u| hash[u] = 1 }
  }
  x.compare!
end
```

```
Warming up --------------------------------------
            slowhash   129.000  i/100ms
            fasthash   177.000  i/100ms
Calculating -------------------------------------
            slowhash      1.307k (± 0.7%) i/s -      6.579k in   5.033141s
            fasthash      1.764k (± 2.4%) i/s -      8.850k in   5.021749s

Comparison:
            fasthash:     1763.5 i/s
            slowhash:     1307.2 i/s - 1.35x  (± 0.00) slower
```
2021-07-07 19:07:22 +01:00
Roberto Miranda
7834a783b8
destroy_all_in_batches is off by default for newly generated Rails apps.
Following up https://github.com/rails/rails/pull/42673#issuecomment-874744582
2021-07-06 19:43:44 +01:00
Jordan
385c4a0771
Fix link to incorrect method in API docs 2021-07-06 10:21:32 +01:00
Ryuta Kamizono
32bac31cc0 Spell checking if record and association_name are provided for AssociationNotFoundError 2021-07-05 17:29:54 +09:00
Petrik
0409ed57ac Clean up checks to see if DidYouMean is defined
As of Ruby 2.7 DidYouMean is included as a default gem, so there is no
need to check if DidYouMean is defined in the test suite. We still need
to check if the DidYouMean modules are defined in the actual code, as
someone might run Rails with DidYouMean disabled by using the
`--disable-did_you_mean` flag. This is ussually done for performance
reasons.

This commit also includes some of the changes made by Yuki in:
https://github.com/rails/rails/pull/39555
These changes include replacing Jaro with the more accurate
SpellChecker, and using DidYouMean::Correctable for simplere
corrections.

The DidYouMean::SpellChecker does have a treshold for corrections.
If there is not enough similarity it might not return a suggestion.
To stop the tests from failing some test data had to be changed.

For example, `non_existent` does not meet the treshold for `hello`, but
`ello` does:

DidYouMean::SpellChecker.new(dictionary: %w[hello]).correct('non_existent')
=> []
DidYouMean::SpellChecker.new(dictionary: %w[hello]).correct('ello')
=> ["hello"]

The treshold makes sense for spelling errors. But maybe we should add a
different SpellChecker that helps to get a suggestion even if there is
little overlap. For example for when a model only has 2 attributes
(title and body), it's helpful to get a suggestion for `name`

Co-Authored-By: Yuki Nishijima <yk.nishijima@gmail.com>
2021-07-04 13:43:50 +02:00
Jean Boussier
ccb66572b1
Merge pull request #42601 from mdemare/has_one_cache
Clear cached has_one association after removing belongs_to association
2021-07-03 08:58:54 +02:00
Ryuta Kamizono
d7fce6c996 Fix odd closing parenthesis by enabling the Layout/ClosingParenthesisIndentation cop 2021-07-02 18:01:50 +09:00
Ryuta Kamizono
db767c332a Fix CI failure caused by error_highlight gem
Since https://github.com/ruby/ruby/pull/4586, error.message includes the
line of code that raised.

https://bugs.ruby-lang.org/issues/17930
2021-07-02 17:44:10 +09:00
Michiel de Mare
484303d698 Clear cached has_one association after setting belongs_to association to nil
Given an author that "has one" post, and setting the post's author to nil,
the author will still have a cached association to the post. Updating any
attribute of the author would erroneously restore the post's author. This
commit resets the association, preventing that behavior.
2021-07-01 22:38:54 +02:00
Abhay Nikam
5cf6898efb Fixes changelog entry after addition of #41722 2021-07-01 18:17:32 +05:30
eileencodes
ce7ff88a50
Fix changelog
Conflict left incorrect entry in changelog.
2021-07-01 08:38:16 -04:00
Eileen M. Uchitelle
6ecf1065da
Merge pull request #41722 from dbussink/openssl-constants
Always use OpenSSL constants for Digest operations
2021-07-01 07:49:39 -04:00
eileencodes
22cef24b6e
Fix migrations with the same timestamps in multiple databases
In #42604 we added functionality that would sort the migrations by
timestamp so that if there were 2 migrations in 2 databases that were
dependent on one another they would be run in timestamp order rather
than in cluster order.

While debugging another issue I realized that if the timestamps are the
same that only one of the migrations will get run. This fixes the issue
by collecting all the db configs for a version so that we get the entire
list.

Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>
2021-06-30 09:28:16 -04:00
Dirkjan Bussink
0523532a3c
Always use OpenSSL constants for Digest operations
As also previously discussed in
https://github.com/rails/rails/pull/40770#issuecomment-748347066, this
moves the usage of Digest constants to always use the OpenSSL version of
those Digest implementations.
2021-06-30 13:57:54 +02:00
Alex Kitchens
c3fe14c239
Merge pull request #42625 from intrip/36027-create-or-find-by-docs
Adjust docs of create_or_find_by
2021-06-29 15:44:46 -05:00
Eileen M. Uchitelle
b09c110aaf
Merge pull request #42198 from zetlanddk/remove-dangling-migrations
Handle duplicate migration names in multi db
2021-06-29 15:59:23 -04:00
John Hawthorn
fb3c5a15a3 Fix explain test on sqlite 3.36.0
Explain output changed in 3.36.0

https://www.sqlite.org/releaselog/3_36_0.html

Co-authored-by: Dinah Shi <dinahshi@github.com>
2021-06-29 10:34:22 -07:00
Jean Boussier
8be6e7af27
Merge pull request #42444 from OuYangJinTing/fix-ar-sanitization
Improve disallow_raw_sql error msg and fix typo
2021-06-29 14:18:24 +02:00
Jacopo
562972caa8 Adjust docs of create_or_find_by
- Mention explicitly in the docs that `create_of_find_by` requires a DB
constraint.

Closes #36027

Co-authored-by: Eileen M. Uchitelle <eileencodes@users.noreply.github.com>
2021-06-29 11:04:10 +02:00
Guillermo Iguaran
1cdee90d38
Merge pull request #40445 from robertomiranda/destroy_all-in_batcches
ActiveRecord::Relation#destroy_all perform its work in batches
2021-06-28 22:49:30 -07:00
Roberto Miranda
4e25cedf7f ActiveRecord::Relation#destroy_all perform its work in batches
💇‍♀️

Fix specs

Update activerecord/lib/active_record/relation.rb

Co-authored-by: Eugene Kenny <elkenny@gmail.com>

Update activerecord/lib/active_record/relation.rb

Co-authored-by: Viktar Basharymau <6alliapumob@gmail.com>

Use class attribute instead of mattr_accessor

Add destroy all test case around value returned

add Rails.application.config.active_record.destroy_all_in_batches too new defaults framework

Reset Active Record Relation

Document ActiveRecord::Relation#destroy_all

Add changelog entry and update docs

💇‍♀️

Update method signature and argument docs

Apply suggestions from code review

Co-authored-by: Viktar Basharymau <6alliapumob@gmail.com>
Co-authored-by: Alberto Almagro <albertoalmagro@gmail.com>
2021-06-28 21:37:24 +01:00
Roberto Miranda
06b026f024 Fix migration compatibility for default precision value on datetime columns (Round 2)
add test cases on default precision from 4.2 to 6.1

Fix compatibility on rails 6.0

Fix compatibility from 5.2 to 4.2
2021-06-28 21:27:43 +01:00
Zachary Scott
0ffdf6dfe7
Merge pull request #42615 from zzak/zzak/42572
Add CHANGELOG for #42572
2021-06-28 19:54:52 +09:00
Zachary Scott
6caaec74bb Add CHANGELOG for #42572 2021-06-28 19:40:07 +09:00
OuYangJinTing
d01ab84b41 [AR] Fix typo of disallow_raw_sql! exception msg 2021-06-28 10:22:30 +08:00
Roberto Miranda
63c2efaa16 Add support for if_exists/if_not_exists on remove_foreign_key/add_foreign_key
Applications can set their migrations to ignore exceptions raised when adding a foreign key that already exists or when removing a foreign key that does not exist.

Add test cases

💇‍♀️
2021-06-27 18:55:17 +01:00
alkeshghorpade
e4cb51d8ff typo fix in error raised 2021-06-26 23:26:59 +05:30
Guillermo Iguaran
de737ea267
Merge pull request #42606 from robertomiranda/r/test-compatibility
Fix migration compatibility for default precision value on datetime columns
2021-06-25 17:32:33 -07:00
Samuel Cochran
8478b26485
Prevent polluting ENV with postgres vars 2021-06-26 08:27:53 +10:00
Roberto Miranda
365acb675d Add test case for add_column on rails 5.0 migrations 2021-06-25 17:47:25 +01:00
Roberto Miranda
9e3320ad26 Fix migrations compatibility for default precision value on datetime columns 2021-06-25 17:47:15 +01:00
Roberto Miranda
9b9d9c7bf9 Test default precision against 6.1 2021-06-25 17:47:02 +01:00
Eileen M. Uchitelle
32488129e9
Merge pull request #42604 from eileencodes/fix-migration-ordering-bug
Fix migration ordering across databases
2021-06-25 12:35:37 -04:00
Eileen M. Uchitelle
246bac42a0
Merge pull request #42605 from Tonkpils/tonkpils/revert-disable-automatic-write-protection
Revert "Disable automatic write protection on replicas"
2021-06-25 12:05:17 -04:00
Guillermo Iguaran
5a26648c3c
Merge pull request #42297 from robertomiranda/r/default-precision-datime
Set precision 6 by default for datetime columns
2021-06-25 08:59:14 -07:00
eileencodes
45eb0f3bec
Fix migration ordering across databases
Previously if there were 2 migrations in one db and 1 migration in the
other db all the migrations for db one would run and then all migrations
for db two would run. If a migration in one database depended on a
migration in another database then it could fail. This is probably
pretty rare, however in a multi-db application that's moving tables from
one db to another, running them out of order could result in a migration
error.

In this this change we collect all the versions for each migration and
the corresponding db_config so we can run them in the order they are
created rather than per-db.

Closes #41664
Related #41538

Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>
Co-authored-by: Kiril Dokh <dsounded@gmail.com>
2021-06-25 11:54:00 -04:00
Leo Correa
69bc201929
Revert "Disable automatic write protection on replicas"
This reverts commit 951deecc52f191ca85bd5c0416b382f4852c6f72.

This change prevents applications from testing replicas and would
require explicitly setting `prevent_writes` when connecting to reading
roles in `connected_to`. For now we'll revert this until there's a
longer term fix in place
2021-06-25 11:35:51 -04:00
Jean Boussier
99913f6a5e Report async queries lock wait duration
This duration is very important to figure wether the `load_async`
actually improved something.
2021-06-25 13:59:47 +02:00
Roberto Miranda
c2a6f618d2 Set precision 6 by default for datetime
💇‍♀️

Set precision 6 by detauls for datime columns when using sqlite3_adapter

 Set precision 6 by detauls for datime columns when using postgresql_adapter

Update activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb

Co-authored-by: Zachary Scott <zzakscott@gmail.com>

Update tests precision

Add datetime precision by using the migration compatibility layer

Add default precision when adding new column for a table

Fix compatibility tests

Add changelog entry

Update postgres test cases

Custom type does not support precision

Typo ⌨️

Fix specific mysql2 schema

💇‍♀️
2021-06-25 09:23:01 +01:00
Rafael França
b56e6afcfd
Merge pull request #42591 from dinahshi/strict-loading-mode-ivar
Convert strict_loading_mode from class attr to ivar
2021-06-24 16:55:53 -04:00
Eileen M. Uchitelle
3c4d2172b8
Merge pull request #42590 from eileencodes/fix-disable-joins-with-sti-type
Fix disable joins with sti type
2021-06-24 15:50:13 -04:00
eileencodes
207747ec2d
Fix disable_joins when using an enum STI type
When a model has an STI enum type, the type wasn't properly applied when
disable joins was set to true. In this case we need to apply the scope
from the association in `add_constraints` so that `type` is included in
the query. Otherwise in a `has_one :through` with `type` all records
will be returned because we're not filtering on type.

Long term I think this might be in the wrong place and that we want to
do this in a new definition of `target_scope` but that's a future
refactoring that needs to be done.
2021-06-24 14:30:00 -04:00
John Hawthorn
18b0135e18
Merge pull request #42553 from jhawthorn/preload_instance_scope
Support preloads on instance dependent associations
2021-06-24 10:25:47 -07:00
Dinah Shi
cec55aafb9 Convert strict_loading_mode from class attr to ivar
Strict loading mode `:n_plus_one_only` is only
supported on single records, not associations or
models. Using an ivar instead of class_attribute
ensures that this cannot be set globally. This
fixes a bug where setting `strict_loading_mode`
caused errors to be silent when
`strict_loading_by_default` is true.

Fixes #42576

Co-Authored-By: John Hawthorn <john@hawthorn.email>
2021-06-24 11:54:40 -04:00
eileencodes
25f2341968
Move find_target to more correct place for disable joins
Instead of redefining this in has_one_association we can define this in
singular association and reuse the existing `find_target` method.
2021-06-24 10:08:04 -04:00