duangutian1426 2017-12-03 18:01
浏览 742
已采纳

将自定义类型数组插入postgres

I'm trying to insert a row with a column that is an array of a custom type (ingredient). My tables are:

CREATE TYPE ingredient AS (
    name text,
    quantity text,
    unit text
);

CREATE TABLE IF NOT EXISTS recipes (
    recipe_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    name text,
    ingredients ingredient[],
    // ...
);

Using raw sql, I can insert a row by:

INSERT INTO recipes (name, ingredients) VALUES ('some_name', ARRAY[ROW('aa', 'bb', 'cc'), ROW('xx', 'yy', 'zz')]::ingredient[] );

But I'm struggling to do this in go with the pq lib. I've created a pq.Array interface:

type Ingredient struct {
    Name string
    Quantity string
    Unit string
}

type Ingredients []*Ingredient

func (ings *Ingredients) ConvertValue(v interface{}) (driver.Value, error) {
    return "something", nil
}
func (ings *Ingredients) Value() (driver.Value, error) {
    val := `ARRAY[]`
    for i, ing := range ings {
        if i != 0 {
            val += ","
        }
        val += fmt.Printf(`ROW('%v','%v','%v')`, ing.Name, ing.Quantity, ing.Unit)
    }
    val += `::ingredient[]`
    return val, nil
}


// and then trying to insert via:
stmt := `INSERT INTO recipes (
        name,
        ingredients
    )
    VALUES ($1, $2)
`
_, err := db.Exec(stmt,
    "some_name",
    &Ingredients{
        &Ingredient{"flour", "3", "cups"},
    },
)

But pg keeps throwing the error:

  Error insertingpq: malformed array literal: "ARRAY[ROW('flour','3','cups')]::ingredient[]"

Am I returning an incorrect driver.Value?

  • 写回答

2条回答 默认 最新

  • dongyu9263 2017-12-03 19:51
    关注

    You can either use this approach outlined here: https://github.com/lib/pq/issues/544

    type Ingredient struct {
        Name string
        Quantity string
        Unit string
    }
    
    func (i *Ingredient) Value() (driver.Value, error) {
        return fmt.Sprintf("('%s','%s','%s')", i.Name, i.Quantity, i.Unit), nil
    }
    
    stmt := `INSERT INTO recipes (name, ingredients) VALUES ($1, $2::ingredient[])`
    
    db.Exec(stmt, "some_name", pq.Array([]*Ingredient{{"flour", "3", "cups"}}))
    

    Or if you have records in the table and you query it, you will probably see the ingredient array in its literal form, which you can than mimic during insert.

    func (ings *Ingredients) Value() (driver.Value, error) {
        val := `{`
        for i, ing := range ings {
            if i != 0 {
                val += ","
            }
            val += fmt.Sprintf(`"('%s','%s','%s')"`, ing.Name, ing.Quantity, ing.Unit)
        }
        val += `}`
        return val, nil
    }
    
    // e.g. `{"('flour','3','cups')"}`
    
    stmt := `INSERT INTO recipes (name, ingredients) VALUES ($1, $2::ingredient[])`
    
    // ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。