사용자 정의 유형 (ingredient
)의 배열 인 열이있는 행을 삽입하려고합니다. 내 테이블은 다음과 같습니다 원시 SQL을 사용하여사용자 정의 유형의 배열을 포스트 그레스에 삽입
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[],
// ...
);
, 나는하여 행을 삽입 할 수 있습니다
INSERT INTO recipes (name, ingredients) VALUES ('some_name', ARRAY[ROW('aa', 'bb', 'cc'), ROW('xx', 'yy', 'zz')]::ingredient[] );
하지만 난 pq
lib 디렉토리로 이동이 작업을 수행하기 위해 고군분투하고있다. 나는 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"},
},
)
을하지만 페이지 오류 던지는 유지 :
Error insertingpq: malformed array literal: "ARRAY[ROW('flour','3','cups')]::ingredient[]"
내가 잘못된 driver.Value
을 반환 오전?
'driver.Value'에서 변환을 생략하고 쿼리에 추가하려고 했습니까? 예 : '$ 2 :: ingredients []'. – mkopriva
위와 동일한 오류가 발생했습니다. –