There is a table with a UNIQUE INDEX on the field “documento”. If I try to duplicate a record on this table, I get the following error from Ash:
{:error,
%Ash.Error.Unknown{
errors: [
%Ash.Error.Unknown.UnknownError{
error: "** (Ecto.ConstraintError) constraint error when attempting to insert struct:\n\n * \"pessoas_documento_index\" (unique_constraint)\n\nIf you would like to stop this constraint violation from raising an\nexception and instead add it as an error to your changeset, please\ncall `unique_constraint/3` on your changeset with the constraint\n`:name` as an option.\n\nThe changeset defined the following constraints:\n\n * \"pessoas_pkey\" (unique_constraint)\n",
field: nil,
changeset: nil,
query: nil,
error_context: [],
vars: [],
path: [],
stacktrace: #Stacktrace<>,
class: :unknown
}
],
...
I’d like to properly catch this specific error (unique constraint) and act accordingly.
The main reason for that is that I have to “try” to insert a record on the table. If it does not exist, it should be inserted. If it already exists, I have to retrieve it. I can’t SELECT before INSERT because of race condition.