Postgres的无效SQL类型(映射) [英] invalid sql type (map) for postgres

查看:141
本文介绍了Postgres的无效SQL类型(映射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用gorm将嵌套结构保存到postgres中,但是我的map[string]*InnerStruct类型遇到了一些问题.

I'm trying to save a nested struct into postgres using gorm, but I'm hitting some issues with my map[string]*InnerStruct type.

我想将地图类型以JSONB的形式存储在postgres中,所以我已经定义了一个Scanner/Valuer,就像在类似的

I want to store my map type as JSONB in postgres, so I've defined a Scanner/Valuer like so as suggested in similar questions:

type SomeMapType map[string]*InnerStruct

type StoreStruct struct {
    gorm.Model
    Id               string `gorm:"type:uuid;primary_key"`
    AccountID        string
    SomeMapType      SomeMapType `gorm:"column:cache,type:jsonb"`
}

var _ driver.Valuer = SomeMapType{}
var _ sql.Scanner = &SomeMapType{}

func (smt SomeMapType) Value() (driver.Value, error) {
    return json.Marshal(smt)
}

func (smt *SomeMapType) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }

    return json.Unmarshal(b, &smt)
}

但是当我尝试像这样创建表时:

but when I try to create a table like so:

err := db.
        CreateTable(StoreStruct{}).
        Table(tableName).Error)

发生恐慌: panic: invalid sql type SomeMapType (map) for postgres [recovered]

似乎在调用我的Valuer/Scanner实现之前就发生了这种情况.

It looks like this happens even before my Valuer/Scanner implementations are called.

难道无法在要使用gorm保存到DB的结构上存储map字段吗?
我相信我已经看过一些似乎可以在map[string]interface{}上运行的示例,所以我不确定为什么我的情况有所不同?

Is it just not possible to store a map field on a struct you want to save to a DB with gorm?
I believe I've seen examples that seem to be working with map[string]interface{} so I'm not sure why my scenario is different?

推荐答案

我的问题不包括SQL类型标记注释.

My problem was not including the SQL type tag annotation.

进行以下更改可以解决我的问题:

Making the changes below fixed my issue:

type StoreStruct struct {
    gorm.Model
    Id               string `gorm:"type:uuid;primary_key"`
    AccountID        string
    SomeMapType      SomeMapType `gorm:"column:cache" sql:"type:jsonb"`
}

这篇关于Postgres的无效SQL类型(映射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆