I have written an example of Go code which is sends query to postgres and send result to the pager:
package main
import (
"fmt"
"database/sql"
_ "github.com/lib/pq"
"log"
"os/exec"
"strings"
"os"
)
func main() {
connstr := "user=postgres dbname=postgres sslmode=disable"
db, err := sql.Open("postgres", connstr)
if err != nil { log.Fatal(err) }
rows, err := db.Query("SELECT schemaname, relname, seq_scan FROM pg_stat_all_tables ORDER BY 1 LIMIT 10")
if err != nil { log.Fatal(err) }
defer rows.Close()
var buf string
for rows.Next() {
var s, r string
var ss int
if err := rows.Scan(&s, &r, &ss); err != nil { log.Fatal(err) }
buf = fmt.Sprintf("%s %s %d\n", buf + s, r, ss)
}
cmd := exec.Command("less")
cmd.Stdin = strings.NewReader(buf)
cmd.Stdout = os.Stdout
err = cmd.Run()
if err != nil { log.Fatal(err) }
}
But the following line:
buf = fmt.Sprintf("%s %s %d\n", buf + s, r, ss)
looks rude for me and I'm not sure this is a right way. Is there way to achieve result in more elegant way? May be it's possible with some kind of buffers and io.Readers?
UPD. When I asked this question a few year ago, I was a Golang newbie. Now, with current experience I see no problems with this code and the question should be closed.