【发布时间】: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