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 ;(
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.