Skip to content

Commit

Permalink
improvement: add postgres_reference_expr callback (#438)
Browse files Browse the repository at this point in the history
Custom types can use this to transform bare attribute expressions into
boolean expressions for filters.
  • Loading branch information
stevebrambilla authored Dec 5, 2024
1 parent 14374ad commit b2151d4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
27 changes: 27 additions & 0 deletions lib/sql_implementation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,33 @@ defmodule AshPostgres.SqlImplementation do
{:ok, Ecto.Query.dynamic(fragment("(? <=> ?)", ^arg1, ^arg2)), acc}
end

def expr(
query,
%Ash.Query.Ref{
attribute: %Ash.Resource.Attribute{
type: attr_type,
constraints: constraints,
},
bare?: true
} = ref,
bindings,
embedded?,
acc,
type
) do
if function_exported?(attr_type, :postgres_reference_expr, 3) do
non_bare_ref = %Ash.Query.Ref{ ref | bare?: nil }
{expr, acc} = AshSql.Expr.dynamic_expr(query, non_bare_ref, bindings, embedded?, type, acc)

case attr_type.postgres_reference_expr(attr_type, constraints, expr) do
{:ok, bare_expr} -> {:ok, bare_expr, acc}
:error -> :error
end
else
:error
end
end

def expr(
_query,
_expr,
Expand Down
11 changes: 10 additions & 1 deletion lib/type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,21 @@ defmodule AshPostgres.Type do
@callback value_to_postgres_default(Ash.Type.t(), Ash.Type.constraints(), term) ::
{:ok, String.t()} | :error

@callback postgres_reference_expr(Ash.Type.t(), Ash.Type.constraints(), term) ::
{:ok, term} | :error

@optional_callbacks value_to_postgres_default: 3,
postgres_reference_expr: 3

defmacro __using__(_) do
quote do
@behaviour AshPostgres.Type

def value_to_postgres_default(_, _, _), do: :error
def postgres_reference_expr(_, _, _), do: :error

defoverridable value_to_postgres_default: 3
defoverridable value_to_postgres_default: 3,
postgres_reference_expr: 3
end
end
end

0 comments on commit b2151d4

Please sign in to comment.