hello everyone,
i am encountering a weird behaviour here
my migration for id
and nick_name
field in user column is as follows
in file 1
defmodule MyModule.Repo.Migrations.AddInitialSchema do
use Ecto.Migration
def up do
execute """
CREATE TABLE IF NOT EXISTS `users` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
end
end
in file 2
defmodule MyModule.Repo.Migrations.UpdateColumnNickNameToUnqiueConstrainInUser do
use Ecto.Migration
def up do
execute """
ALTER TABLE users ADD UNIQUE(nick_name);
"""
end
end
and my mysql users table look like this(only showing two field which is revelant)
+---------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| nick_name | varchar(255) | YES | UNI | NULL | |
+---------------------------+--------------+------+-----+---------+----------------+
my changeset function is like this
def changeset(user, params) do
cast(user, params, [
:id,
:nick_name,
])
|> unique_constraint(:nick_name,
name: :nick_name,
match: :suffix,
message: "nick_name_already_taken"
)
|> unique_constraint(:id,
name: :id,
match: :suffix,
message: "id_already_taken"
)
my three consecutive inset is as follows
user1 = %User{
id: 1,
nick_name: "n1",
}
user2 = %User{
id: 2,
nick_name: "n1",
}
user3 = %User{
id: 1,
nick_name: "n2",
}
data = User.changeset(user, params)
IamService.Repo.insert(data)
now
when i am inserting user1
it is getting successfully inserted in the databases
after that when i inserting user2
i am getting error:
errors: [
nick_name: {"nick_name_already_taken",
[constraint: :unique, constraint_name: "nick_name"]}
],
which is fine it is expected
but when i am inserting user3 i am getting the below error,
** (Ecto.ConstraintError) constraint error when attempting to insert struct:
* PRIMARY (unique_constraint)
If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `unique_constraint/3` on your changeset with the constraint
`:name` as an option.
The changeset defined the following constraints:
* id (unique_constraint)
* nick_name (unique_constraint)
(ecto 3.4.4) lib/ecto/repo/schema.ex:700: anonymous fn/4 in Ecto.Repo.Schema.constraints_to_errors/3
(elixir 1.11.4) lib/enum.ex:1411: Enum."-map/2-lists^map/1-0-"/2
(ecto 3.4.4) lib/ecto/repo/schema.ex:685: Ecto.Repo.Schema.constraints_to_errors/3
(ecto 3.4.4) lib/ecto/repo/schema.ex:666: Ecto.Repo.Schema.apply/4
(ecto 3.4.4) lib/ecto/repo/schema.ex:263: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4
seems to that the unique_constraint(:id,… is not getting applied
help me out, what is going wrong??