【问题标题】:Ecto.Repo.insert! with "on_conflict: :nothing" raising a Postgresql "syntax error at or near "ON""Ecto.Repo.insert!使用“on_conflict::nothing”引发 Postgresql“在“ON”处或附近出现语法错误”
【发布时间】:2020-04-18 15:40:44
【问题描述】:

我对 Elixir 和 Phoenix 完全陌生,目前正在阅读“Programming Phoenix”一书。

我已经到了第 7 章,我有一个名为 categories 的数据库表,其中有一列 namename 上的 DB 级唯一性约束。

如果我在一个名为“Hello”的类别已经存在时运行以下行,我会得到一个Ecto.ConstraintError,正如预期的那样:

> Rumbl.Repo.insert!(%Rumbl.Multimedia.Category{name: "Hello"})
[debug] QUERY ERROR db=3.2ms queue=4.9ms idle=9982.9ms
INSERT INTO "categories" ("name","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["Hello", ~N[2020-04-18 07:05:04], ~N[2020-04-18 07:05:04]]
** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * categories_name_index (unique_constraint)

现在,这本书告诉我,我可以在对insert! 的调用中添加选项on_conflict: :nothing,这样可以防止出现错误。但实际发生的是我得到一个 postgres 语法错误:

> Rumbl.Repo.insert!(%Rumbl.Multimedia.Category{name: "Hello"}, on_conflict: :nothing)
** (Postgrex.Error) ERROR 42601 (syntax_error) syntax error at or near "ON"

    query: INSERT INTO "categories" ("name","inserted_at","updated_at") VALUES ($1,$2,$3) ON CONFLICT DO NOTHING RETURNING "id"
    (ecto_sql) lib/ecto/adapters/sql.ex:612: Ecto.Adapters.SQL.raise_sql_call_error/1
    (ecto) lib/ecto/repo/schema.ex:657: Ecto.Repo.Schema.apply/4
    (ecto) lib/ecto/repo/schema.ex:263: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4
    (ecto) lib/ecto/repo/schema.ex:164: Ecto.Repo.Schema.insert!/4
[debug] QUERY ERROR db=0.0ms queue=0.8ms idle=9038.9ms
INSERT INTO "categories" ("name","inserted_at","updated_at") VALUES ($1,$2,$3) ON CONFLICT DO NOTHING RETURNING "id" ["Hello", ~N[2020-04-18 07:05:13], ~N[2020-04-18 07:05:13]]

版本号:

  • 灵药 1.9.4
  • 凤凰1.4.10
  • Ecto 3.4.2
  • Postgres 12.1

【问题讨论】:

    标签: postgresql elixir ecto phoenix


    【解决方案1】:

    原来我弄错了我的 postgres 版本是 12.1,这实际上是我的 psql 客户端的安装版本,而不是运行 9.4 的 postgres 服务器ON CONFLICT是9.5添加的,所以解决办法是升级我的postgres服务器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 2020-12-26
      • 2020-02-05
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 2021-12-13
      • 2021-12-24
      相关资源
      最近更新 更多