Skip to content

Commit b2151d4

Browse files
improvement: add postgres_reference_expr callback (#438)
Custom types can use this to transform bare attribute expressions into boolean expressions for filters.
1 parent 14374ad commit b2151d4

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/sql_implementation.ex

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,33 @@ defmodule AshPostgres.SqlImplementation do
153153
{:ok, Ecto.Query.dynamic(fragment("(? <=> ?)", ^arg1, ^arg2)), acc}
154154
end
155155

156+
def expr(
157+
query,
158+
%Ash.Query.Ref{
159+
attribute: %Ash.Resource.Attribute{
160+
type: attr_type,
161+
constraints: constraints,
162+
},
163+
bare?: true
164+
} = ref,
165+
bindings,
166+
embedded?,
167+
acc,
168+
type
169+
) do
170+
if function_exported?(attr_type, :postgres_reference_expr, 3) do
171+
non_bare_ref = %Ash.Query.Ref{ ref | bare?: nil }
172+
{expr, acc} = AshSql.Expr.dynamic_expr(query, non_bare_ref, bindings, embedded?, type, acc)
173+
174+
case attr_type.postgres_reference_expr(attr_type, constraints, expr) do
175+
{:ok, bare_expr} -> {:ok, bare_expr, acc}
176+
:error -> :error
177+
end
178+
else
179+
:error
180+
end
181+
end
182+
156183
def expr(
157184
_query,
158185
_expr,

lib/type.ex

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,21 @@ defmodule AshPostgres.Type do
88
@callback value_to_postgres_default(Ash.Type.t(), Ash.Type.constraints(), term) ::
99
{:ok, String.t()} | :error
1010

11+
@callback postgres_reference_expr(Ash.Type.t(), Ash.Type.constraints(), term) ::
12+
{:ok, term} | :error
13+
14+
@optional_callbacks value_to_postgres_default: 3,
15+
postgres_reference_expr: 3
16+
1117
defmacro __using__(_) do
1218
quote do
1319
@behaviour AshPostgres.Type
20+
1421
def value_to_postgres_default(_, _, _), do: :error
22+
def postgres_reference_expr(_, _, _), do: :error
1523

16-
defoverridable value_to_postgres_default: 3
24+
defoverridable value_to_postgres_default: 3,
25+
postgres_reference_expr: 3
1726
end
1827
end
1928
end

0 commit comments

Comments
 (0)