Skip to content

PostgreSQL wire: Go (pgx v5)

# host
postgres.internal
warehouse.internal
# port
5432
5432 (PostgreSQL wire)
# user / password / database
PostgreSQL values
MachWarehouse values
Terminal window
go mod tidy
DATABASE_URL=postgresql://app:...@warehouse.internal:5432/demo go run .

Library: github.com/jackc/pgx/v5 v5.11.0 (Go 1.27).

The program as it is kept and tested in the Mach Database Warehouse repository; highlighted lines read the connection setting.

go.mod
module example.com/machwarehouse/postgres-go
go 1.27
require github.com/jackc/pgx/v5 v5.11.0
main.go
// Command postgres-go aggregates over the PostgreSQL wire with pgx. Plain pgx code.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5"
)
func main() {
ctx := context.Background()
conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
rows, err := conn.Query(ctx, "SELECT country, count(*) AS events, sum(revenue)::text AS revenue FROM events GROUP BY country ORDER BY sum(revenue) DESC")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var country, revenue string
var events int64
if err := rows.Scan(&country, &events, &revenue); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\t%d\t%s\n", country, events, revenue)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}