wmnnd
Ecto unique_constraint for primary key
Hi there,
I’m trying to capture constraint exceptions when a user attempts to create a database record with a primary key that already exists.
My Ecto struct has its primary key defined like this: @primary_key { :uuid, :binary_id, autogenerate: true }
I tried applying a unique_constraing in my changeset with unique_constraint(changeset, :uuid) but would still get an exception that said:
** (Ecto.ConstraintError) constraint error when attempting to insert struct:
* unique: PRIMARY
If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and define the proper
constraint name. The changeset defined the following constraints:
* unique: %TABLE_NAME_uuid_index
Only after I added name: :PRIMARY as an additional opts argument to unique_constraint/3, everything went fine: unique_constraint(changeset, :uuid, name: :PRIMARY)
Now why is it that I have to specify :PRIMARY as the name of the constraint? Where does that name come from?
I could not find anything about that in the Ecto docs.
Marked As Solved
josevalim
PRIMARY is the name of the constraint Postgres gives to primary keys. By default we inflect a name based on a unique index, so you need to be explicitly in the case of primary key matches.
Last Post!
wmnnd
Thanks for the explanation, that’s already what I suspected. I’m using MariaDB but it seems to use the same naming convention.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex










