Ignore invalid PRIMARY KEY values in ActiveRecord::Persistence.delete
method
#49738
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When some invalid primary key values are passed to
ActiveRecord::Persistence.delete
method, ActiveRecord still perform aDELETE
query even if it is not needed. For example,So people usually add conditions around the call like
User.delete(ids) if ids.compact.any?
orUser.delete(id) if id
or just forget these conditions and unneeded queries are ran. But we can remove this burden from the user. Recent real-world example https://github.com/rails/solid_cache/blob/9be6755a2d8c8fd1c294912e1fbf6bbb69410c61/app/models/solid_cache/entry.rb#L64-L66But, can
NULL
be a valid value and can we actually ignore it? I checked, and it turns out that primary keys cannot beNULL
- ANSI standard says so, PostgreSQL, MySQL, SQL Server and Oracle Server conform to that. There is an exception from SQLite. In the docs it says that it allowsNULL
s due to some historical reasons, unless some conditions are met (one of them is explicitNOT NULL
or table is created inSTRICT
mode, read the docs from the link for the details). But in rails, we explicitly set itNOT NULL
rails/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
Line 77 in ad1e443
strict
mode (#45346). So, I think it is safe to ignorenil
s as values provided to#delete
.