postgresql - 将自定义类型数组插入 postgres

标签 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[],
    // ...
);

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

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

但我正在努力使用 pq 库来做到这一点。我创建了一个 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"},
    },
)

但是 pg 一直报错:

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

我是否返回了不正确的 driver.Value

最佳答案

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

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

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

// ...

关于postgresql - 将自定义类型数组插入 postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47621459/

相关文章:

postgresql - 如何从 Dapper(使用 Npgsql)调用具有混合大小写名称的存储过程?

python - 如何在 PostgreSQL 中将长整数 NUMERIC 转换为位字符串?

go - 控制鼠标和键盘的Golang?

xml - 解码 XML 以构造并转换为 slice

sql - 向 postgres 查询添加查询参数时出错

postgresql - PostgreSQL和Golang之间的数据类型

PostgreSQL 更改返回的行顺序

ruby-on-rails - 如果记录有两个条件返回 true else false,如何获取 Rails 4?

sql - 当不涉及并发线程时如何修复 "database is locked"?戈兰、sqlite3

postgresql - 无法从 db.QueryRow() 推断出错误