@@ -2668,7 +2668,15 @@ defmodule AshPostgres.DataLayer do
26682668 ) do
26692669 case Ecto.Adapters.Postgres.Connection . to_constraints ( error , [ ] ) do
26702670 [ ] ->
2671- { :error , Ash.Error . to_ash_error ( error , stacktrace ) }
2671+ constraints = maybe_foreign_key_violation_constraints ( error )
2672+ if constraints != [ ] do
2673+ { :error ,
2674+ changeset
2675+ |> constraints_to_errors ( :delete , constraints , resource , error )
2676+ |> Ash.Error . to_ash_error ( ) }
2677+ else
2678+ { :error , Ash.Error . to_ash_error ( error , stacktrace ) }
2679+ end
26722680
26732681 constraints ->
26742682 { :error ,
@@ -2682,6 +2690,20 @@ defmodule AshPostgres.DataLayer do
26822690 { :error , Ash.Error . to_ash_error ( error , stacktrace ) }
26832691 end
26842692
2693+ defp maybe_foreign_key_violation_constraints ( % Postgrex.Error { postgres: postgres } )
2694+ when is_map ( postgres ) do
2695+ code = postgres [ :code ] || postgres [ "code" ]
2696+ constraint = postgres [ :constraint ] || postgres [ "constraint" ]
2697+
2698+ if code in [ "23503" , 23503 , :foreign_key_violation ] and is_binary ( constraint ) do
2699+ [ { :foreign_key , constraint } ]
2700+ else
2701+ [ ]
2702+ end
2703+ end
2704+
2705+ defp maybe_foreign_key_violation_constraints ( _ ) , do: [ ]
2706+
26852707 defp constraints_to_errors (
26862708 % { constraints: user_constraints } = changeset ,
26872709 action ,
0 commit comments