【发布时间】:2021-09-02 18:27:11
【问题描述】:
我正在使用本地托管的 postgres 数据库来测试对生产中的 postgres 数据库的查询。生产数据库有一个info 类型为jsonb 的字段;当使用 gorm 的AutoMigrate 时,我试图在本地模仿这个模式。我定义的模型如下:
import "github.com/jinzhu/gorm/dialects/postgres"
type Event struct {
...
Info postgres.Jsonb
...
}
但是当我查询 JSON 属性时,例如stmt.Where("info->>'attr' = value"),我收到以下错误:
...
Message:"operator does not exist: bytea ->> unknown", Detail:"", Hint:"No operator matches the given name and argument type(s). You might need to add explicit type casts.",
...
但是,此查询在生产环境中有效。似乎Info 字段被存储为bytea 而不是jsonb。我知道我可以做到stmt.Where("encode(info, "escape")::jsonb->>'attr' = value"),但我更愿意(如果可能的话)更接近地模拟生产环境,而不是更改查询以支持这些单元测试。
我已经尝试在模型中使用类型标签(例如gorm:"type=jsonb"),并按照建议here 定义我自己的JSON 类型来实现估值器、扫描仪和GormDataTypeInterface。这些方法都没有将类型自动迁移为jsonb。
有什么方法可以确保AutoMigrate 创建一个jsonb 类型的表?谢谢!
【问题讨论】:
标签: postgresql go-gorm