pkey上的Ecto唯一约束错误

Kat*_*ine 6 postgresql ecto phoenix-framework postgrex

尝试插入新房间时,我开始收到以下错误消息

** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * unique: rooms_pkey

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: rooms_name_index
Run Code Online (Sandbox Code Playgroud)

主键不应该自动递增吗?什么会突然发生这个错误?插入是作为multi的一部分完成的,相关部分是:

|> Multi.insert(:room, Room.changeset(%Room{}, %{name: "service-user-care-team:" <> Integer.to_string(user.id)}))
Run Code Online (Sandbox Code Playgroud)

有关其他参考,请参阅我的架构,包括更改集

schema "rooms" do
  field :name, :string
  many_to_many :users, App.User, join_through: "user_rooms", on_delete: :delete_all
  has_many :messages, App.Message

  timestamps()
end

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, [:name])
  |> validate_required([:name])
  |> unique_constraint(:name)
end
Run Code Online (Sandbox Code Playgroud)

这是迁移

defmodule App.Repo.Migrations.CreateRoom do
  use Ecto.Migration

  def change do
    create table(:rooms) do
      add :name, :string, null: false

      timestamps()
    end

    create unique_index(:rooms, [:name])
 end
end
Run Code Online (Sandbox Code Playgroud)

Kat*_*ine 5

我找到了为什么会发生这种情况。

我忘记在原始描述中包含的一个重要说明是,这是在开发环境中工作时发生的。

与这个答案有关。我之前使用 Postico 手动插入了一些数据,其中必须明确包含 id。此时 pkey 序列尚未更新,这导致后来设置了重复的 id。