Skip to content

Commit

Permalink
improvement: fix some error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
zachdaniel committed Oct 5, 2023
1 parent ce26211 commit 0f854eb
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 2 deletions.
49 changes: 49 additions & 0 deletions lib/data_layer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,55 @@ defmodule AshSqlite.DataLayer do
)
end

defp handle_raised_error(
%Exqlite.Error{
message: "FOREIGN KEY constraint failed"
},
stacktrace,
context,
resource
) do
handle_raised_error(
Ash.Error.Changes.InvalidChanges.exception(
fields: Ash.Resource.Info.primary_key(resource),
message: "referenced something that does not exist"
),
stacktrace,
context,
resource
)
end

defp handle_raised_error(
%Exqlite.Error{
message: "UNIQUE constraint failed: " <> fields
},
stacktrace,
context,
resource
) do
fields
|> String.split(", ")
|> Enum.map(fn field ->
field |> String.split(".", trim: true) |> Enum.drop(1) |> Enum.at(0)
end)
|> Enum.map(fn field ->
Ash.Resource.Info.attribute(resource, field)
end)
|> Enum.reject(&is_nil/1)
|> Enum.map(fn %{name: name} ->
Ash.Error.Changes.InvalidAttribute.exception(
field: name,
message: "has already been taken"
)
end)
|> handle_raised_error(
stacktrace,
context,
resource
)
end

defp handle_raised_error(error, stacktrace, _ecto_changeset, _resource) do
{:error, Ash.Error.to_ash_error(error, stacktrace)}
end
Expand Down
42 changes: 40 additions & 2 deletions lib/expr.ex
Original file line number Diff line number Diff line change
Expand Up @@ -624,10 +624,48 @@ defmodule AshSqlite.Expr do
)

:|| ->
raise "|| operator not supported by AshSqlite"
do_dynamic_expr(
query,
%Fragment{
embedded?: pred_embedded?,
arguments: [
raw: "(CASE WHEN (",
casted_expr: left_expr,
raw: " == FALSE OR ",
casted_expr: left_expr,
raw: " IS NULL) THEN ",
casted_expr: right_expr,
raw: " ELSE ",
casted_expr: left_expr,
raw: "END)"
]
},
bindings,
embedded?,
type
)

:&& ->
raise "&& operator not supported by AshSqlite"
do_dynamic_expr(
query,
%Fragment{
embedded?: pred_embedded?,
arguments: [
raw: "(CASE WHEN (",
casted_expr: left_expr,
raw: " == FALSE OR ",
casted_expr: left_expr,
raw: " IS NULL) THEN ",
casted_expr: left_expr,
raw: " ELSE ",
casted_expr: right_expr,
raw: "END)"
]
},
bindings,
embedded?,
type
)

other ->
raise "Operator not implemented #{other}"
Expand Down

0 comments on commit 0f854eb

Please sign in to comment.