将Golang JSON存储到Postgresql中

moe*_*sef 13 sql postgresql json struct go

我想将某个结构存储到我的数据库中,其中包含一个JSON字段.

type Comp struct {
    CompId               int64           `db:"comp_id" json:"comp_id"`
    StartDate            time.Time       `db:"start_date" json:"start_date"`
    EndDate              time.Time       `db:"end_date" json:"end_date"`
    WeeklySchedule       json.RawMessage `db:"weekly_schedule" json:"weekly_schedule"`
}
Run Code Online (Sandbox Code Playgroud)

该表的架构是:

CREATE TABLE IF NOT EXISTS Tr.Comp(
    comp_id                 SERIAL,
    start_date              timestamp NOT NULL,
    end_date                timestamp NOT NULL,
    weekly_schedule         json NOT NULL,
    PRIMARY KEY (comp_id)
);
Run Code Online (Sandbox Code Playgroud)

我在我的项目中使用sqlx和lib/pq驱动程序,以下将不会执行.相反,恐慌说有一个零指针.DB是一个全局*sqlx.DB结构

    tx := DB.MustBegin()

    compFixture := Comp{
        StartDate:            time.Now(),
        EndDate:              time.Now().AddDate(1, 0, 0),
        WeeklySchedule:       json.RawMessage([]byte("{}")),
    }
    _, err = tx.NamedExec(
        `INSERT INTO 
            Tr.Comp(comp_id, 
                start_date, end_date, weekly_schedule) 
            VALUES (DEFAULT, 
                :start_date, :end_date, :weekly_schedule)  
            RETURNING comp_id;`, compFixture)
    if err != nil {
        t.Fatal("Error creating fixture.", err)
    }
Run Code Online (Sandbox Code Playgroud)

当我weekly_schedule从架构和夹具中删除东西运行正常.但由于某种原因,当该字段被包括在内时,程序会出现恐慌.有关如何weekly_schedule在我的数据库模式和Go结构中定义字段的任何想法?

jma*_*ney 10

sqlx有一个类型JSONText,可以满足github.com/jmoiron/sqlx/types您的需求

JSONText的doc


moe*_*sef 6

我不知道这个解决方案有多干净,但我最终创建了自己的数据类型JSONRaw。DB 驱动程序将其视为 a []btye,但在 Go 代码中仍然可以将其视为 json.RawMessage。

type JSONRaw json.RawMessage

func (j JSONRaw) Value() (driver.Value, error) {
    byteArr := []byte(j)

    return driver.Value(byteArr), nil
}

func (j *JSONRaw) Scan(src interface{}) error {
    asBytes, ok := src.([]byte)
    if !ok {
        return error(errors.New("Scan source was not []bytes"))
    }
    err := json.Unmarshal(asBytes, &j)
    if err != nil {
        return error(errors.New("Scan could not unmarshal to []string"))
    }

    return nil
}

func (m *JSONRaw) MarshalJSON() ([]byte, error) {
    return *m, nil
}

func (m *JSONRaw) UnmarshalJSON(data []byte) error {
    if m == nil {
        return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
    }
    *m = append((*m)[0:0], data...)
    return nil
}
Run Code Online (Sandbox Code Playgroud)

这是库的MarshalJSON复制粘贴重新实现。UnmarshalJSONencoding/json