首页 > 解决方案 > 如何避免 0(零)int 变成 Postgres“null”值并违反“not null”约束?

问题描述

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

“错误 #23502 “数字”列中的空值违反了非空约束”。

当它被解组为 int 值时,它看起来像0变成了一个 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
}

标签: postgresqlgosql-null

解决方案


虽然这不是很明显,go-pg但您可以使用 struct 标记sql:",notnull"来显示允许使用 Go 空值(""0[])并且不应将其视为 SQL NULL

您可以在功能列表中看到它。

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

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

推荐阅读