Skip to content

Commit 004f64c

Browse files
authored
Add {:unsafe_fragment, ...} support to RETURNING clause (#722)
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 004f64c

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed

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

lib/ecto/adapters/tds/connection.ex

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,9 @@ if Code.ensure_loaded?(Tds) do
10271027

10281028
defp returning([], _verb), do: []
10291029

1030+
defp returning({:unsafe_fragment, fragment}, _verb),
1031+
do: [" OUTPUT ", fragment]
1032+
10301033
defp returning(returning, verb) when is_list(returning) do
10311034
[" OUTPUT ", Enum.map_intersperse(returning, ", ", &[verb, ?., quote_name(&1)])]
10321035
end

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)