英文:
What is the idiomatic way to retrieve results from a stored procedure?
问题
DROP函数mytest();
CREATE OR REPLACE FUNCTION mytest()
RETURNS TABLE(name text, age int)
AS
$$
SELECT name, age FROM names
$$
LANGUAGE sql;
我看到的大多数存储过程的示例返回一个具有单个列的单行,可以与QueryRow一起使用。在这里,我将表用作输出。上面的代码返回4行:
mytest
(bob,12)
(fred,18)
(james,22)
(bill,27)
(4 rows)
在Go中,处理元组的惯用方式是什么:
rows, err := db.Query("SELECT mytest()")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var items string
if err = rows.Scan(&items); err != nil {
panic(err)
}
log.Println(items) // items是一个字符串...现在怎么办?
}
if err = rows.Err(); err != nil {
panic(err)
}
// 打印一些元组:
(bob,12)
(fred,18)
(james,22)
(bill,27)
也许有一个专门处理这个的包,但我还没有找到它 ;(
英文:
DROP function mytest();
CREATE OR REPLACE FUNCTION mytest()
RETURNS TABLE(name text, age int)
AS
$$
SELECT name, age FROM names
$$
LANGUAGE sql;
Most of the examples I've seen with a stored procedure return a single row with a single column and can be used with QueryRow. Here I am using a table as the output. This above returns 4 rows:
mytest
------------
(bob,12)
(fred,18)
(james,22)
(bill,27)
(4 rows)
In Go, what is the idiomatic way to deal with the tuples:
rows, err := db.Query("SELECT mytest()")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var items string
if err = rows.Scan(&items); err != nil {
panic(err)
}
log.Println(items) // items is a string...now what?
}
if err = rows.Err(); err != nil {
panic(err)
}
// prints some tuples:
(bob,12)
(fred,18)
(james,22)
(bill,27)
Maybe there's a package for this but I haven't found it ;(
答案1
得分: -1
你可以尝试使用一个 PostgreSQL 的类型安全的 ORM,比如 src-d/go-kallax
,它可以处理元组。
你可以在这篇博客文章中了解到 kallax 的介绍。
> - kallax 的首要目标是为数据访问层提供类型安全性。
-
kallax 的另一个目标是确保所有的模型首先都是 Go 结构体,而不需要使用特定于数据库的类型,比如 sql.NullInt64。同时,它还提供了对所有基本 Go 类型的数组和切片以及所有 JSON 和数组操作符的支持。
英文:
Instead of a Query, you could try a PostgreSQL typesafe1 ORM , like src-d/go-kallax
, which deals with tuples.
You can see kalax presented in this blog post
> - the first priority of kallax is to provide type safety to the data access layer.
-
Another goal of kallax is to make sure all models are, first and foremost, Go structs without having to use database-specific types such as, for example, sql.NullInt64. Support for arrays and slices of all basic Go types and all JSON and arrays operators is provided as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论