将自定义类型数组插入 postgres

cat*_*t-t 5 postgresql go pq

我正在尝试插入一行,其中有一列是自定义类型 ( ) 的数组ingredient。我的桌子是:

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[],
    // ...
);
Run Code Online (Sandbox Code Playgroud)

使用原始 sql,我可以通过以下方式插入一行:

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

但我正在努力与库一起做到这一点pq。我创建了一个pq.Array界面:

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"},
    },
)
Run Code Online (Sandbox Code Playgroud)

但 pg 不断抛出错误:

  Error insertingpq: malformed array literal: "ARRAY[ROW('flour','3','cups')]::ingredient[]"
Run Code Online (Sandbox Code Playgroud)

我返回的是错误的吗driver.Value

mko*_*iva 3

您可以使用此处概述的方法: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"}}))
Run Code Online (Sandbox Code Playgroud)

或者,如果表中有记录并查询它,您可能会看到其文字形式的成分数组,您可以在插入期间模仿它。

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[])`

// ...
Run Code Online (Sandbox Code Playgroud)