Return unique constraint errors for custom primary keys
wmartins opened this issue · 6 comments
Hi there! I've been using Etso for a while now and it's a great solution to get an Ecto based project up and running in no time.
One thing that I'm missing is to be able to get the error that happens when trying to insert a duplicate entry. In other words, I get a changeset that is invalid, however, the errors
property is empty. The impact is that I'm unable to show this error information on a form.
I've been dabbling a litte with the implementation in order to check if it's possible, and here are my findings.
First, the empty error is justified by the following line:
etso/lib/etso/adapter/behaviour/schema.ex
Line 24 in f25bdea
If I change that to this:
diff --git a/lib/etso/adapter/behaviour/schema.ex b/lib/etso/adapter/behaviour/schema.ex
index 6fe3992..fd8f7e1 100644
--- a/lib/etso/adapter/behaviour/schema.ex
+++ b/lib/etso/adapter/behaviour/schema.ex
@@ -21,7 +21,7 @@ defmodule Etso.Adapter.Behaviour.Schema do
ets_field_names = TableStructure.field_names(schema)
ets_changes = TableStructure.fields_to_tuple(ets_field_names, fields)
ets_result = :ets.insert_new(ets_table, ets_changes)
- if ets_result, do: {:ok, []}, else: {:invalid, []}
+ if ets_result, do: {:ok, []}, else: {:invalid, [unique: "primary_key"]}
end
def update(%{repo: repo}, %{schema: schema}, fields, filters, [], _) do
Now I start to receive the error:
@primary_key{:key, :string, autogenerate: false}
def changeset(schema, params \\ %{}) do
schema
|> unique_constraint(:key, name: :primary_key)
end
%{
key: [
{"has already been taken",
[constraint: :unique, constraint_name: "primary_key"]}
]
}
What are your thoughts on that, is that something you wish to support?
Thanks. Apologies I have been busy recently. Will investigate this.
Documentation for insert_new agrees with your proposed change. I shall raise a new release shorty. Thank you!!
You don't need to apologize @evadne :).
I'll be happy to test it when this new release is available. Thank you for the time to look into it!
@wmartins FYI: Change is live @ feature/gh-7-unique-constraint-error
. Will release new version when ready :>
Looking good @evadne, here's my application before and after those changes:
Before: not showing field validation error
After: showing field validation error
Released 0.1.5 with thanks ❤️