从存储过程中检索结果的惯用方法是什么?

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年9月18日 01:47:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/46267073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定