Skip to content

Commit 7da2cbc

Browse files
committed
Add {:unsafe_fragment, ...} support to RETURNING clause
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
1 parent e3430b2 commit 7da2cbc

2 files changed

Lines changed: 7 additions & 0 deletions

File tree

lib/ecto/adapters/postgres/connection.ex

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,6 +1204,9 @@ if Code.ensure_loaded?(Postgrex) do
12041204
defp returning([]),
12051205
do: []
12061206

1207+
defp returning({:unsafe_fragment, fragment}),
1208+
do: [" RETURNING ", fragment]
1209+
12071210
defp returning(returning),
12081211
do: [" RETURNING " | quote_names(returning)]
12091212

test/ecto/adapters/postgres_test.exs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1877,6 +1877,10 @@ defmodule Ecto.Adapters.PostgresTest do
18771877

18781878
query = insert("prefix", "schema", [], [[]], {:raise, [], []}, [])
18791879
assert query == ~s{INSERT INTO "prefix"."schema" VALUES (DEFAULT)}
1880+
1881+
# With unsafe_fragment in returning
1882+
query = insert(nil, "schema", [:x, :y], [[:x, :y]], {:raise, [], []}, {:unsafe_fragment, ~s{"id", ("x" = "y") AS "was_equal"}})
1883+
assert query == ~s{INSERT INTO "schema" ("x","y") VALUES ($1,$2) RETURNING "id", ("x" = "y") AS "was_equal"}
18801884
end
18811885

18821886
test "insert with on conflict" do

0 commit comments

Comments
 (0)