带有 JSONB 和非 JSONB 列的查询表

问题描述

我有一张看起来像这样的表格:

CREATE TABLE users (
    id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),forename character varying(50) NULL,surname character varying(50) NULL,date_of_birth date NULL,email character varying(255) UNIQUE DEFAULT NULL,settings JSONB
);

我有一个结构:

type User struct {
    ID            uuid.UUID  `json:"id" db:"id"`
    Forename      string     `json:"forename" db:"forename"`
    Surname       string     `json:"surname" db:"surname"`
    DateOfBirth   time.Time  `json:"dateOfBirth" db:"date_of_birth"`
    Email         string     `json:"email" db:"email"`
    Children      *[]Child   `json:"children" db:"children"`
}

type Child struct {
    Forename      string     `json:"forename" db:"forename"`
    Surname       string     `json:"surname" db:"surname"`
    DateOfBirth   time.Time  `json:"dateOfBirth" db:"date_of_birth"`
}

我的所有查询都使用 SQLX,但在涉及 JSONB 列时插入和检索数据有困难。

如果我想获取用户:

rows,err := dB.Conn.Queryx(query,id)
if err != nil {
    return nil,err
}

user := &User{}

for rows.Next() {
    err := rows.StructScan(&user)
    if err != nil {
        return nil,err
    }
}

我从 StructScan 中收到以下错误

sql: Scan error on column index 5,name "children": unsupported Scan,storing driver.Value type []uint8 into type *[]Child

我已经为似乎没有帮助的结构实现了如下接口:

func (c *Child) Scan(val interface{}) error {
    switch v := val.(type) {
    case []byte:
        json.Unmarshal(v,&c)
        return nil
    case string:
        json.Unmarshal([]byte(v),&c)
        return nil
    default:
        return errors.New(fmt.Sprintf("Unsupported type: %T",v))
    }
}

func (c *Child) Value() (driver.Value,error) {
    return json.Marshal(c)
}

对于使用 SQLX NamedQuery 的插入,我还得到以下内容:

sql: converting argument $5 type: unsupported type []Child,a slice of struct"

使用结构从 PostgreSQL 数据库插入和检索结构的最简单方法是什么。

N.B 我可以在使用 map[string]interface{} 时让它工作,但我真的需要正确的类型结构

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)