将自定义类型数组插入 postgres
Inserting array of custom types into postgres
我正在尝试插入一行,其中有一列是自定义类型的数组 (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')]::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 (, )
`
_, 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
?
看来你的数据库设计很复杂,没有考虑到 SQL 的长处(和短处)。
我可以建议您根据食谱将配料拆分成自己的 table。然后找出一个完整的食谱是JOIN
操作。
正在创建数据库:
CREATE TABLE ingredients (
recipe_id uuid,
name text,
quantity int,
unit text
);
CREATE TABLE recipes (
recipe_id uuid PRIMARY KEY,
name text
);
插入菜谱并查询读出:
INSERT INTO recipes VALUES (
'5d1cb631-37bd-46cc-a278-4c8558ed8964', 'cake1'
);
INSERT INTO ingredients (recipe_id, name, quantity, unit) VALUES
('5d1cb631-37bd-46cc-a278-4c8558ed8964', 'flour', 3, 'cups'),
('5d1cb631-37bd-46cc-a278-4c8558ed8964', 'water', 1, 'cups')
;
SELECT r.name, i.name, i.quantity, i.unit
FROM ingredients AS i
INNER JOIN recipes AS r
ON r.recipe_id=i.recipe_id;
SQL小提琴 link: http://sqlfiddle.com/#!17/262ad/14
您可以使用此处概述的方法: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 (, ::ingredient[])`
db.Exec(stmt, "some_name", pq.Array([]*Ingredient{{"flour", "3", "cups"}}))
或者如果您在 table 中有记录并查询它,您可能会看到其 文字 形式的成分数组,您可以在插入。
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 (, ::ingredient[])`
// ...
我正在尝试插入一行,其中有一列是自定义类型的数组 (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')]::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 (, )
`
_, 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
?
看来你的数据库设计很复杂,没有考虑到 SQL 的长处(和短处)。
我可以建议您根据食谱将配料拆分成自己的 table。然后找出一个完整的食谱是JOIN
操作。
正在创建数据库:
CREATE TABLE ingredients (
recipe_id uuid,
name text,
quantity int,
unit text
);
CREATE TABLE recipes (
recipe_id uuid PRIMARY KEY,
name text
);
插入菜谱并查询读出:
INSERT INTO recipes VALUES (
'5d1cb631-37bd-46cc-a278-4c8558ed8964', 'cake1'
);
INSERT INTO ingredients (recipe_id, name, quantity, unit) VALUES
('5d1cb631-37bd-46cc-a278-4c8558ed8964', 'flour', 3, 'cups'),
('5d1cb631-37bd-46cc-a278-4c8558ed8964', 'water', 1, 'cups')
;
SELECT r.name, i.name, i.quantity, i.unit
FROM ingredients AS i
INNER JOIN recipes AS r
ON r.recipe_id=i.recipe_id;
SQL小提琴 link: http://sqlfiddle.com/#!17/262ad/14
您可以使用此处概述的方法: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 (, ::ingredient[])`
db.Exec(stmt, "some_name", pq.Array([]*Ingredient{{"flour", "3", "cups"}}))
或者如果您在 table 中有记录并查询它,您可能会看到其 文字 形式的成分数组,您可以在插入。
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 (, ::ingredient[])`
// ...