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

将自定义类型数组插入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 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?