【问题标题】:Gorm Jsonb type stored as byteaGorm Jsonb 类型存储为 bytea
【发布时间】: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


    【解决方案1】:

    我遇到了同样的问题,类型 JsonB 自动迁移到 bytea。我通过添加标签gorm:"type:jsonb" 解决了这个问题。您的问题中也提到了它,但是您使用的是gorm:"type=jsonb",这是不正确的。

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 1970-01-01
      • 2015-06-06
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多