postgresql - pkey 上的 Ecto 唯一约束错误

标签 postgresql phoenix-framework ecto 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

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

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

作为额外引用,这是我的架构,包括变更集

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

这是迁移

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

最佳答案

我找到了发生这种情况的原因。

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

this answer有关.我之前用 Postico 手动插入了一些数据,其中必须明确包含 id。 pkey 序列在那一点上没有更新,后来导致设置了重复的 id。

关于postgresql - pkey 上的 Ecto 唯一约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475815/

相关文章:

sql - 如何在 postgres 中应用调度程序?

elixir - 如何仅从ecto模型获取字段?

sql - 在 Postgres 中,如何从给定的 TIMESTAMP WITH TIME ZONE 列中提取月份(根据特定时区)?

postgresql - Azure 数据工厂 - 从 Ubuntu 上的 PostgreSQL DB 复制数据

elixir - 在 Phoenix 中创建和使用 Elixir 助手模块

elixir - 向对象添加虚拟字段

postgresql - ecto jsonb 数组和 map 转换问题

elixir - 如何在 Ecto 模型中使用 uuid

postgresql - 如何在 docker-compose up 上注册一个 Postgres 容器主机?

elixir - 为什么在布局中调用时 "Mix.env()"在生产中会变为 nil?