postgresql - 如何避免 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
}
解决方案
虽然这不是很明显,go-pg
但您可以使用 struct 标记sql:",notnull"
来显示允许使用 Go 空值(""
、0
等[]
)并且不应将其视为 SQL NULL
。
您可以在功能列表中看到它。
在您的情况下,我会将其更改为:
type Account struct {
Number int `sql:"type:smallint,pk,notnull"`
Name string
}
推荐阅读
- java - Java Thread which waits for new objects in collection
- vue.js - 将数组数据传递给组件并制作
- altair - Having both X and Y axes' Scales in Altair respond to a selection interval
- google-places-api - Google Places Api autocomplete does not return any Postal Code for Germany (address_components)
- configuration - 在简单的控制台应用程序(Core 3.1)中从 appsetting.json 检索连接字符串
- google-apps-script - 如何为我的 Google Web App 创建弹出式授权
- laravel-livewire - 在 livewire 中使用两种形式
- python - 从 excel 行中读取逗号分隔的数字 - python pandas
- php - 更改 ini 文件时 XDebug 配置设置不会更改
- android - MPAndroidChart - 有没有办法只显示最高和最低标签?