Skip to content

Commit a2d1d7c

Browse files
authored
test: add failing test for cond/if calculation in query filters (#766)
cond/if expressions used in query filters produce a DBConnection.EncodeError because the THEN clause literals in the generated CASE WHEN are not type-cast (e.g. THEN 3) when the expression appears in a WHERE clause, while they ARE properly cast (e.g. THEN 3::bigint) in a SELECT clause. The root cause is in ash_sql's expr.ex: when embedded? is true (which it is for cond/if expression nodes), the literal handler at default_dynamic_expr/6 skips type casting entirely, so the Fragment parameters end up as {value, :any}. Postgrex then cannot infer the correct encoding from context and defaults to text, causing the binary vs integer mismatch.
1 parent b456c85 commit a2d1d7c

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

test/calculation_test.exs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1100,6 +1100,31 @@ defmodule AshPostgres.CalculationTest do
11001100
assert full_name == "name"
11011101
end
11021102

1103+
test "cond/if calculation can be used in query filters" do
1104+
post =
1105+
Post
1106+
|> Ash.Changeset.for_create(:create, %{title: "match", score: 75})
1107+
|> Ash.create!()
1108+
1109+
# Loading the cond-based calculation works fine
1110+
post = Ash.load!(post, :score_category)
1111+
assert post.score_category == 2
1112+
1113+
# Filtering by a cond-based calculation should also work.
1114+
# This currently fails with DBConnection.EncodeError because the THEN
1115+
# clause literals in the generated CASE WHEN are not type-cast when the
1116+
# expression appears in a WHERE clause (they ARE cast in SELECT).
1117+
assert [_] =
1118+
Post
1119+
|> Ash.Query.filter(score_category == 2)
1120+
|> Ash.read!()
1121+
1122+
assert [] =
1123+
Post
1124+
|> Ash.Query.filter(score_category == 3)
1125+
|> Ash.read!()
1126+
end
1127+
11031128
test "calculation with fragment and cond returning integer doesn't cause Postgrex encoding error" do
11041129
Post
11051130
|> Ash.Changeset.for_create(:create, %{title: "hello ash lovers"})

test/support/resources/post.ex

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,6 +1124,20 @@ defmodule AshPostgres.Test.Post do
11241124

11251125
calculate(:c_times_p, :integer, expr(count_of_comments * count_of_linked_posts))
11261126

1127+
1128+
calculate(
1129+
:score_category,
1130+
:integer,
1131+
expr(
1132+
cond do
1133+
score > 100 -> 3
1134+
score > 50 -> 2
1135+
score > 0 -> 1
1136+
true -> 0
1137+
end
1138+
)
1139+
)
1140+
11271141
calculate(
11281142
:literal_map_in_expr,
11291143
:map,

0 commit comments

Comments
 (0)