Add {:unsafe_fragment, ...} support to RETURNING clause#722
Open
henryzhan013 wants to merge 1 commit intoelixir-ecto:masterfrom
Open
Add {:unsafe_fragment, ...} support to RETURNING clause#722henryzhan013 wants to merge 1 commit intoelixir-ecto:masterfrom
henryzhan013 wants to merge 1 commit intoelixir-ecto:masterfrom
Conversation
This adds support for raw SQL fragments in the RETURNING clause, matching the existing pattern used by conflict_target. This enables use cases like returning computed expressions: RETURNING id, (price = EXCLUDED.price) AS was_skipped
Member
|
Can you please add this to Also please send a PR to elixir-ecto/ecto itself that updates the docs! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
This lets you pass raw SQL fragments to the
RETURNINGclause, just like you already can withconflict_target.Why
PostgreSQL supports expressions in
RETURNING— things like:But Ecto only accepts column names for
:returning, which all get quoted as identifiers. If you try passing a string with an expression, it becomes"(price != EXCLUDED.price) AS was_updated"which is invalid.I ran into this working on
ash_postgreswhere we need to detect whether an upsert actually updated a row or was skipped due to conflict conditions. Right now that requires an extra query. With this change, we can do it in one shot by returning a computed expression.Changes
One new function clause in
returning/1:This is the same pattern
conflict_target/1already uses (line 284), so there's precedent for it. Existing code using lists of column names works exactly as before.