【问题标题】:How to avoid that 0 (zero) int turns into Postgres "null" value and violates "not null" constraint?如何避免 0(零)int 变成 Postgres“null”值并违反“not null”约束?
【发布时间】:2019-04-14 19:24:34
【问题描述】:

在 Go 中,我将 JSON 解组/解码为一个 ID 字段为 int 类型的结构。然后我尝试使用 go-pg 将这个结构插入 PostgreSQL 数据库,并将 ID 列作为主键(它有一个非空约束)。第一个条目的 ID 为 0。在 Postgres 文档中,它指出 0 可以作为主键的值。但是,我不断收到一条错误消息:

“ERROR #23502 “number”列中的空值违反了非空约束”。

0 解组为 int 值时,它看起来变成了 Go“零值”。然后将其作为 null 值插入 Postgres。任何关于如何避免这种情况的提示将不胜感激。

type Account struct {
   Number int `sql:"type:smallint, pk"`
   Name string
}

[...]

account := Account{}
err := json.NewDecoder(r.Body).Decode(&account)

[...]

insertErr := pgLayer.db.Insert(&account)
if insertErr != nil {
   log.Printf("Error while inserting new item")
   return "n/a", insertErr
}

【问题讨论】:

  • 你试过sql:"smallint,pk,notnull" 吗?

标签: postgresql go sql-null


【解决方案1】:

虽然 go-pg 不是很明显,但您可以使用结构标记 sql:",notnull" 来显示 Go 空值(""0[] 等)是允许的,不应被视为SQLNULL.

你可以在Features list看到它。

在您的情况下,我会将其更改为:

type Account struct {
   Number int `sql:"type:smallint,pk,notnull"`
   Name string
}

【讨论】:

    【解决方案2】:

    我认为解决您的问题的最简单方法是将您的 ID 列设为 SERIAL 类型,并让 Postgres 为您处理设置和自动递增值。如果您在插入后直接需要应用程序中的值,您可以随时使用RETURNING psql 子句,如下所示:

    INSERT INTO shows(
        user_id, name, description, created, modified
    ) VALUES(
        :user_id, :name, :created, :modified
    ) RETURNING id;
    

    并在您的代码中捕获响应。

    【讨论】:

      猜你喜欢
      • 2017-03-01
      • 1970-01-01
      • 2020-10-02
      • 2014-11-27
      • 2018-03-20
      • 2023-03-30
      • 2021-06-10
      • 2021-03-24
      • 1970-01-01
      相关资源
      最近更新 更多