我有一个postgres表:
CREATE TABLE public.foo
(
id uuid NOT NULL DEFAULT gen_random_uuid(),
foo timestamp with time zone[],
bar timestamp with time zone
)
然后我查询此表并将结果扫描为以下值:
var res []myResStruct
rows, err := db.Query(`sql goes here`, ¶ms)
if err != nil {
log.Printf("err querying: %v\n", err)
panic(err)
}
defer rows.Close()
for rows.Next() {
var (
id uuid.UUID
foo []uint8
bar time.Time
)
if err := rows.Scan(&id, &foo, &bar); err != nil {
log.Printf("err scanning: %v\n", err)
panic(err)
}
// note: I hate this, but golang's sql driver doesn't support \
// arrays of timestamps?
s := string(foo)
s = strings.Replace(s, "{", "", -1)
s = strings.Replace(s, "}", "", -1)
s = strings.Replace(s, "\"", "", -1)
z := strings.Split(s, ",")
var tmpFoo []time.Time
for _, v := range z {
t, _ := time.Parse("2006-01-02 15:04:05-07", v)
tmpFoo = append(tmpFoo, t)
}
// note @adam-hanna: is there a way to know the length of results \
// so I can create a slice of proper length?
res = append(res, &myResStruct{
id: id,
foo: tmpFoo,
bar: bar,
})
}
if err := rows.Err(); err != nil {
log.Printf("rows.Error(): %v\n", err)
panic(err)
}
为什么我必须使用[]uint8
foo
,但我可以time.Time
使用bar
?有没有更好的办法?仅供参考 - 我使用lib/pq。