Skip to content

Commit

Permalink
fix: properly support expr errors in bulk create
Browse files Browse the repository at this point in the history
  • Loading branch information
zachdaniel committed Dec 12, 2024
1 parent 5d9f0fc commit 877ad28
Showing 1 changed file with 32 additions and 29 deletions.
61 changes: 32 additions & 29 deletions lib/data_layer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1551,7 +1551,7 @@ defmodule AshPostgres.DataLayer do

true ->
{:ok, Ecto.Query.exclude(root_query, :order_by),
root_query.__ash_bindings__.expression_accumulator, false}
Map.get(root_query, :__ash_bindings__).expression_accumulator, false}
end

case root_query_result do
Expand Down Expand Up @@ -1966,7 +1966,7 @@ defmodule AshPostgres.DataLayer do

fields_to_upsert =
upsert_fields --
Keyword.keys(Enum.at(changesets, 0).atomics) -- keys
(Keyword.keys(Enum.at(changesets, 0).atomics) -- keys)

fields_to_upsert
|> Enum.uniq()
Expand Down Expand Up @@ -2184,33 +2184,6 @@ defmodule AshPostgres.DataLayer do
)
end

defp handle_raised_error(
%Postgrex.Error{} = error,
stacktrace,
{:bulk_create, fake_changeset},
_resource
) do
case Ecto.Adapters.Postgres.Connection.to_constraints(error, []) do
[] ->
{:error, Ash.Error.to_ash_error(error, stacktrace)}

constraints ->
{:error,
fake_changeset
|> constraints_to_errors(:insert, constraints)
|> Ash.Error.to_ash_error()}
end
end

defp handle_raised_error(%Ecto.Query.CastError{} = e, stacktrace, context, resource) do
handle_raised_error(
Ash.Error.Query.InvalidFilterValue.exception(value: e.value, context: context),
stacktrace,
context,
resource
)
end

defp handle_raised_error(
%Postgrex.Error{
postgres: %{
Expand Down Expand Up @@ -2254,6 +2227,33 @@ defmodule AshPostgres.DataLayer do
{:error, :no_rollback, Ash.Error.from_json(exception, input)}
end

defp handle_raised_error(
%Postgrex.Error{} = error,
stacktrace,
{:bulk_create, fake_changeset},
_resource
) do
case Ecto.Adapters.Postgres.Connection.to_constraints(error, []) do
[] ->
{:error, Ash.Error.to_ash_error(error, stacktrace)}

constraints ->
{:error,
fake_changeset
|> constraints_to_errors(:insert, constraints)
|> Ash.Error.to_ash_error()}
end
end

defp handle_raised_error(%Ecto.Query.CastError{} = e, stacktrace, context, resource) do
handle_raised_error(
Ash.Error.Query.InvalidFilterValue.exception(value: e.value, context: context),
stacktrace,
context,
resource
)
end

defp handle_raised_error(
%Postgrex.Error{} = error,
stacktrace,
Expand Down Expand Up @@ -2657,6 +2657,9 @@ defmodule AshPostgres.DataLayer do
{:ok, [result]} ->
{:ok, result}

{:error, :no_rollback, error} ->
{:error, :no_rollback, error}

{:error, error} ->
{:error, error}
end
Expand Down

0 comments on commit 877ad28

Please sign in to comment.