PostgreSQL
suggest changePostgreSQL is a widely used open source relational database. In Go, most projects talk to it through pgx, a pure Go driver and toolkit.
You can use pgx in two ways:
- The native pgx API (
pgx.Conn,pgxpool.Pool). It's faster and supports PostgreSQL features thatdatabase/sqlcan't express: arrays,COPY, batches,LISTEN/NOTIFY, detailed error fields. - As a
database/sqldriver (github.com/jackc/pgx/v5/stdlib). Use it when code or libraries expect*sql.DB. See SQL for the generaldatabase/sqlAPI.
The older lib/pq driver still works, but pgx is more actively developed and has more features, so it's the usual choice for new code.
The examples use pgx v5:
go get github.com/jackc/pgx/v5
Connecting
Use pgxpool.New for a connection pool. It's safe for concurrent use by many goroutines, so create one at startup and share it.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
ctx := context.Background()
// e.g. postgres://user:password@localhost:5432/dbname?sslmode=disable
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// pgxpool.New doesn't connect; Ping does.
if err := pool.Ping(ctx); err != nil {
log.Fatal(err)
}
var version string
err = pool.QueryRow(ctx, "SELECT current_setting('server_version')").Scan(&version)
if err != nil {
log.Fatal(err)
}
fmt.Println("PostgreSQL version:", version)
}
PostgreSQL version: 16.2
The connection string can be a URL or a key/value string:
postgres://app:secret@localhost:5432/shop?sslmode=disable
host=localhost port=5432 user=app password=secret dbname=shop sslmode=disable
pgx also reads the standard libpq environment variables (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGSSLMODE) and ~/.pgpass, so pgxpool.New(ctx, "") works if those are set.
sslmode defaults to prefer: pgx tries TLS and falls back to a plain connection. In production use sslmode=verify-full so the server certificate is checked.
For a short script you can use a single connection: conn, err := pgx.Connect(ctx, url) followed by defer conn.Close(ctx). A *pgx.Conn is not safe for concurrent use. In servers, use the pool.
Create, insert, query
PostgreSQL uses numbered placeholders $1, $2, ... instead of ?. Every pgx method takes a context.Context first.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const schema = `
DROP TABLE IF EXISTS books;
CREATE TABLE books (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
year int
);`
type Book struct {
ID int64
Title string
Author string
Year *int32 // NULL-able column
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// Without arguments, Exec can run several statements at once.
if _, err := pool.Exec(ctx, schema); err != nil {
log.Fatal(err)
}
// Placeholders are $1, $2, ... RETURNING gives back the generated id.
var id int64
err = pool.QueryRow(ctx,
"INSERT INTO books (title, author, year) VALUES ($1, $2, $3) RETURNING id",
"The Go Programming Language", "Donovan, Kernighan", 2015,
).Scan(&id)
if err != nil {
log.Fatal(err)
}
fmt.Println("inserted id:", id)
tag, err := pool.Exec(ctx,
"INSERT INTO books (title, author, year) VALUES ($1, $2, $3), ($4, $5, $6)",
"Learning Go", "Jon Bodner", 2024,
"Untitled draft", "Anonymous", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("rows affected:", tag.RowsAffected())
// Query + manual Scan loop.
rows, err := pool.Query(ctx, "SELECT id, title, year FROM books ORDER BY id")
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var id int64
var title string
var year *int32
if err := rows.Scan(&id, &title, &year); err != nil {
log.Fatal(err)
}
if year == nil {
fmt.Printf("%d %q (no year)\n", id, title)
} else {
fmt.Printf("%d %q %d\n", id, title, *year)
}
}
// Always check rows.Err() after the loop.
if err := rows.Err(); err != nil {
log.Fatal(err)
}
// CollectRows + RowToStructByName maps columns to struct fields.
rows, _ = pool.Query(ctx, "SELECT * FROM books WHERE year > $1 ORDER BY year", 2000)
books, err := pgx.CollectRows(rows, pgx.RowToStructByName[Book])
if err != nil {
log.Fatal(err)
}
for _, b := range books {
fmt.Printf("%d: %s by %s (%d)\n", b.ID, b.Title, b.Author, *b.Year)
}
// No row found is reported as pgx.ErrNoRows.
var title string
err = pool.QueryRow(ctx, "SELECT title FROM books WHERE id = $1", 999).Scan(&title)
if errors.Is(err, pgx.ErrNoRows) {
fmt.Println("book 999 not found")
}
}
inserted id: 1
rows affected: 2
1 "The Go Programming Language" 2015
2 "Learning Go" 2024
3 "Untitled draft" (no year)
1: The Go Programming Language by Donovan, Kernighan (2015)
2: Learning Go by Jon Bodner (2024)
book 999 not found
Notes:
Execreturns apgconn.CommandTag.RowsAffected()tells you how many rows anINSERT,UPDATEorDELETEtouched.- PostgreSQL has no
LastInsertId. UseRETURNING id(orRETURNING *) andScanthe result. - A pointer (
*int32) scans SQLNULLasnil. A plainint32would makeScanreturn an error forNULL. pgx.RowToStructByNamematches column names to struct fields case-insensitively. Use adb:"column_name"tag when names differ, ordb:"-"to skip a field. The query must return a column for every field;pgx.RowToStructByNameLaxallows missing columns.- Passing several statements to
Execonly works without arguments. With arguments, pgx uses the extended protocol, which allows one statement per call.
Errors from Query are deferred: if the query fails, rows.Next() returns false and the error comes from rows.Err() or from CollectRows. That's why the examples can write rows, _ := pool.Query(...) before CollectRows.
Collecting rows
Writing rows.Next() / Scan loops gets tedious. pgx has generic helpers:
| Function | Returns |
|---|---|
pgx.CollectRows(rows, fn) |
[]T with all rows |
pgx.CollectOneRow(rows, fn) |
first row as T, pgx.ErrNoRows if none |
pgx.CollectExactlyOneRow(rows, fn) |
T, error if zero rows or more than one |
pgx.ForEachRow(rows, scans, fn) |
calls fn after scanning each row |
The row function fn decides how a row becomes a T:
pgx.RowTo[T]for a single columnpgx.RowToStructByName[T]/pgx.RowToStructByPos[T]for structspgx.RowToAddrOfStructByName[T]to get[]*Tpgx.RowToMapformap[string]any
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/jackc/pgx/v5"
)
type Product struct {
ID int `db:"id"`
Name string `db:"name"`
PriceCents int64 `db:"price_cents"`
CreatedAt time.Time `db:"created_at"`
}
func main() {
ctx := context.Background()
conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
_, err = conn.Exec(ctx, `
DROP TABLE IF EXISTS products;
CREATE TABLE products (
id serial PRIMARY KEY,
name text NOT NULL,
price_cents bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
)`)
if err != nil {
log.Fatal(err)
}
// pgx.NamedArgs rewrites @name placeholders into $1, $2, ...
rows, _ := conn.Query(ctx, `
INSERT INTO products (name, price_cents) VALUES (@name, @price)
RETURNING *`,
pgx.NamedArgs{"name": "Keyboard", "price": 4999})
p, err := pgx.CollectOneRow(rows, pgx.RowToStructByName[Product])
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d %s %d\n", p.ID, p.Name, p.PriceCents)
conn.Exec(ctx, `INSERT INTO products (name, price_cents) VALUES ('Mouse', 1999), ('Cable', 599)`)
// RowTo[T] for a single column, RowToMap for dynamic queries.
rows, _ = conn.Query(ctx, "SELECT name FROM products ORDER BY price_cents")
names, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
log.Fatal(err)
}
fmt.Println(names)
rows, _ = conn.Query(ctx, "SELECT name, price_cents FROM products WHERE id = 2")
m, err := pgx.CollectExactlyOneRow(rows, pgx.RowToMap)
if err != nil {
log.Fatal(err)
}
fmt.Println(m)
// CollectOneRow returns pgx.ErrNoRows when there's nothing.
rows, _ = conn.Query(ctx, "SELECT * FROM products WHERE id = 42")
_, err = pgx.CollectOneRow(rows, pgx.RowToStructByName[Product])
fmt.Println(err)
}
1 Keyboard 4999
[Cable Mouse Keyboard]
map[name:Mouse price_cents:1999]
no rows in result set
pgx.NamedArgs lets you write @name instead of $1, which is easier to read for queries with many parameters.
PostgreSQL types
pgx maps PostgreSQL types to Go types directly:
| PostgreSQL | Go |
|---|---|
int2, int4, int8 |
int16, int32, int64, int |
float4, float8 |
float32, float64 |
text, varchar |
string |
bool |
bool |
bytea |
[]byte |
timestamptz, timestamp, date |
time.Time |
uuid |
[16]byte, string, pgtype.UUID |
text[], int8[], ... |
[]string, []int64, ... |
json, jsonb |
any value; encoded/decoded with encoding/json |
numeric |
pgtype.Numeric, string, float64 |
For NULL use a pointer or a pgtype type (pgtype.Text, pgtype.Int8, pgtype.Timestamptz, ...) which have a Valid field. sql.NullString and friends work too.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
)
type Meta struct {
Pages int `json:"pages"`
Publisher string `json:"publisher"`
Formats []string `json:"formats"`
}
func main() {
ctx := context.Background()
// A single connection instead of a pool; fine for scripts and tools.
conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
_, err = conn.Exec(ctx, `
DROP TABLE IF EXISTS items;
CREATE TABLE items (
id serial PRIMARY KEY,
name text NOT NULL,
tags text[] NOT NULL DEFAULT '{}',
meta jsonb,
price numeric(10,2),
note text,
created_at timestamptz NOT NULL DEFAULT now()
)`)
if err != nil {
log.Fatal(err)
}
// Go slices map to Postgres arrays, structs/maps are encoded as JSON
// for json/jsonb columns, nil becomes NULL.
meta := Meta{Pages: 380, Publisher: "Addison-Wesley", Formats: []string{"paper", "ebook"}}
_, err = conn.Exec(ctx,
`INSERT INTO items (name, tags, meta, price, note) VALUES ($1, $2, $3, $4, $5)`,
"gopl", []string{"go", "programming"}, meta, "34.99", nil)
if err != nil {
log.Fatal(err)
}
var (
name string
tags []string
m Meta
price pgtype.Numeric
note pgtype.Text
created time.Time
)
err = conn.QueryRow(ctx,
`SELECT name, tags, meta, price, note, created_at FROM items WHERE name = $1`,
"gopl").Scan(&name, &tags, &m, &price, ¬e, &created)
if err != nil {
log.Fatal(err)
}
f, _ := price.Float64Value()
fmt.Println("name: ", name)
fmt.Println("tags: ", tags, len(tags))
fmt.Printf("meta: %+v\n", m)
fmt.Println("price: ", f.Float64)
fmt.Println("note: ", note.String, "valid:", note.Valid)
fmt.Println("created:", created.Location(), time.Since(created) < time.Minute)
// = ANY($1) lets you pass a slice instead of building IN (...) by hand.
var count int
err = conn.QueryRow(ctx,
`SELECT count(*) FROM items WHERE $1 = ANY(tags) OR name = ANY($2)`,
"go", []string{"a", "b"}).Scan(&count)
if err != nil {
log.Fatal(err)
}
fmt.Println("matching:", count)
// Query a single JSON field with ->> (returns text).
var publisher string
err = conn.QueryRow(ctx, `SELECT meta->>'publisher' FROM items WHERE meta @> $1`,
`{"formats": ["ebook"]}`).Scan(&publisher)
if err != nil {
log.Fatal(err)
}
fmt.Println("publisher:", publisher)
}
name: gopl
tags: [go programming] 2
meta: {Pages:380 Publisher:Addison-Wesley Formats:[paper ebook]}
price: 34.99
note: valid: false
created: Local true
matching: 1
publisher: Addison-Wesley
Things to note:
- Arrays round-trip as Go slices.
$1 = ANY(tags)tests membership.name = ANY($2)with a slice argument replacesIN (...)and avoids building SQL strings with a variable number of placeholders. - A struct passed for a
jsonbcolumn is marshalled withencoding/json, and scanningjsonbinto a struct unmarshals it. numericis an arbitrary precision decimal. Don't usefloat64for money. Usepgtype.Numeric, a decimal library such as shopspring/decimal with pgx-shopspring-decimal, or store integer cents in abigint.timestamptzvalues are returned in the local time zone of the Go process (time.Local). They represent the same instant either way. Call.UTC()if you want UTC.
Transactions
pgx.BeginFunc runs a function inside a transaction. It commits if the function returns nil and rolls back if it returns an error or panics.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrInsufficientFunds = errors.New("insufficient funds")
func transfer(ctx context.Context, pool *pgxpool.Pool, from, to string, amount int) error {
// BeginFunc commits if the function returns nil, rolls back otherwise.
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
var balance int
// FOR UPDATE locks the row until the transaction ends.
err := tx.QueryRow(ctx,
"SELECT balance FROM accounts WHERE name = $1 FOR UPDATE", from).Scan(&balance)
if err != nil {
return err
}
if balance < amount {
return ErrInsufficientFunds
}
_, err = tx.Exec(ctx,
"UPDATE accounts SET balance = balance - $1 WHERE name = $2", amount, from)
if err != nil {
return err
}
_, err = tx.Exec(ctx,
"UPDATE accounts SET balance = balance + $1 WHERE name = $2", amount, to)
return err
})
}
// The explicit form: Begin, defer Rollback, Commit.
func resetAll(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
// Rollback after a successful Commit is a no-op, so deferring it is safe.
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, "UPDATE accounts SET balance = 0"); err != nil {
return err
}
if _, err := tx.Exec(ctx, "DELETE FROM no_such_table"); err != nil {
return err // the deferred Rollback undoes the UPDATE
}
return tx.Commit(ctx)
}
func printBalances(ctx context.Context, pool *pgxpool.Pool) {
rows, _ := pool.Query(ctx, "SELECT name, balance FROM accounts ORDER BY name")
var name string
var balance int
_, err := pgx.ForEachRow(rows, []any{&name, &balance}, func() error {
fmt.Printf(" %s: %d\n", name, balance)
return nil
})
if err != nil {
log.Fatal(err)
}
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
_, err = pool.Exec(ctx, `
DROP TABLE IF EXISTS accounts;
CREATE TABLE accounts (name text PRIMARY KEY, balance int NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES ('alice', 100), ('bob', 50);`)
if err != nil {
log.Fatal(err)
}
fmt.Println("transfer 30:", transfer(ctx, pool, "alice", "bob", 30))
fmt.Println("transfer 500:", transfer(ctx, pool, "alice", "bob", 500))
printBalances(ctx, pool)
fmt.Println("resetAll:", resetAll(ctx, pool))
printBalances(ctx, pool)
}
transfer 30: <nil>
transfer 500: insufficient funds
alice: 70
bob: 80
resetAll: ERROR: relation "no_such_table" does not exist (SQLSTATE 42P01)
alice: 70
bob: 80
tx.Rollback after a successful Commit does nothing and returns pgx.ErrTxClosed, which is why defer tx.Rollback(ctx) right after Begin is the standard pattern.
Use pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable}) for a different isolation level, or AccessMode: pgx.ReadOnly for a read-only transaction. Under Serializable be prepared to retry transactions that fail with SQLSTATE 40001 (serialization failure).
Calling Begin on a pgx.Tx creates a nested transaction implemented with a SAVEPOINT.
Handling errors
Server errors are returned as *pgconn.PgError. It carries the SQLSTATE code plus details like the violated constraint. The github.com/jackc/pgerrcode package has named constants for the codes.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func main() {
ctx := context.Background()
conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
_, err = conn.Exec(ctx, `
DROP TABLE IF EXISTS users;
CREATE TABLE users (id serial PRIMARY KEY, email text UNIQUE NOT NULL, age int CHECK (age >= 0))`)
if err != nil {
log.Fatal(err)
}
insert := func(email string, age int) error {
_, err := conn.Exec(ctx, "INSERT INTO users (email, age) VALUES ($1, $2)", email, age)
return err
}
fmt.Println(insert("ann@example.com", 30))
for _, err := range []error{insert("ann@example.com", 31), insert("bo@example.com", -1)} {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
fmt.Println("code: ", pgErr.Code)
fmt.Println("message: ", pgErr.Message)
fmt.Println("detail: ", pgErr.Detail)
fmt.Println("constraint:", pgErr.ConstraintName)
switch pgErr.Code {
case pgerrcode.UniqueViolation:
fmt.Println("=> email already registered")
case pgerrcode.CheckViolation:
fmt.Println("=> invalid value")
}
}
}
}
<nil>
code: 23505
message: duplicate key value violates unique constraint "users_email_key"
detail: Key (email)=(ann@example.com) already exists.
constraint: users_email_key
=> email already registered
code: 23514
message: new row for relation "users" violates check constraint "users_age_check"
detail: Failing row contains (3, bo@example.com, -1).
constraint: users_age_check
=> invalid value
Common codes:
| Code | pgerrcode constant | Meaning |
|---|---|---|
23505 |
UniqueViolation |
duplicate key |
23503 |
ForeignKeyViolation |
referenced row missing, or still referenced |
23502 |
NotNullViolation |
NULL in a NOT NULL column |
23514 |
CheckViolation |
CHECK constraint failed |
40001 |
SerializationFailure |
retry the transaction |
40P01 |
DeadlockDetected |
retry the transaction |
57014 |
QueryCanceled |
statement_timeout or cancel |
Mapping UniqueViolation to a "already exists" error is usually better than checking with a SELECT first, which is racy.
Pool configuration and timeouts
Use pgxpool.ParseConfig to tune the pool before creating it:
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
ctx := context.Background()
cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
cfg.MaxConns = 10
cfg.MinConns = 1
cfg.MaxConnLifetime = time.Hour
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.ConnConfig.RuntimeParams["application_name"] = "pgdemo"
// Runs once for every new connection.
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, "SET statement_timeout = '30s'")
return err
}
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
var app, timeout string
err = pool.QueryRow(ctx,
"SELECT current_setting('application_name'), current_setting('statement_timeout')").
Scan(&app, &timeout)
if err != nil {
log.Fatal(err)
}
fmt.Println("application_name:", app, "statement_timeout:", timeout)
// Every call takes a context; cancelling it cancels the query on the server.
qctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
defer cancel()
_, err = pool.Exec(qctx, "SELECT pg_sleep(5)")
fmt.Println("timed out:", errors.Is(err, context.DeadlineExceeded), pgconn.Timeout(err))
}
application_name: pgdemo statement_timeout: 30s
timed out: true true
MaxConnsdefaults to the larger of 4 and the number of CPUs. Keep the total across all instances of your app below the server'smax_connections(100 by default).AfterConnectruns on every new connection. Use it for session settings, the same way you'd use DSN pragmas with SQLite.- Cancelling the context of a running query sends a cancel request to the server, so the query stops there too, not just in Go. Give request handlers a deadline and pass
r.Context()into queries.
Batches and bulk loading
Each Exec or Query is a network round trip. When you have many small statements, a pgx.Batch sends them all at once. For loading a lot of rows, CopyFrom uses PostgreSQL's COPY protocol, which is much faster than individual INSERTs.
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)
_, err = conn.Exec(ctx, `
DROP TABLE IF EXISTS events;
CREATE TABLE events (id bigserial PRIMARY KEY, kind text NOT NULL, user_id int NOT NULL)`)
if err != nil {
log.Fatal(err)
}
// Batch: queue many statements, send them in one network round trip.
batch := &pgx.Batch{}
batch.Queue("INSERT INTO events (kind, user_id) VALUES ($1, $2)", "login", 1)
batch.Queue("INSERT INTO events (kind, user_id) VALUES ($1, $2)", "view", 1)
batch.Queue("SELECT count(*) FROM events").QueryRow(func(row pgx.Row) error {
var n int
err := row.Scan(&n)
fmt.Println("count inside batch:", n)
return err
})
if err := conn.SendBatch(ctx, batch).Close(); err != nil {
log.Fatal(err)
}
// CopyFrom uses the COPY protocol: the fastest way to bulk load rows.
rows := make([][]any, 0, 10000)
for i := range 10000 {
rows = append(rows, []any{"click", i % 100})
}
n, err := conn.CopyFrom(ctx,
pgx.Identifier{"events"},
[]string{"kind", "user_id"},
pgx.CopyFromRows(rows))
if err != nil {
log.Fatal(err)
}
fmt.Println("copied:", n)
var total int
conn.QueryRow(ctx, "SELECT count(*) FROM events").Scan(&total)
fmt.Println("total:", total)
}
count inside batch: 2
copied: 10000
total: 10002
CopyFrom doesn't support ON CONFLICT or RETURNING. A common trick is to COPY into a temporary table and then run INSERT ... SELECT ... ON CONFLICT from it. Use pgx.CopyFromSlice to generate rows on the fly instead of building [][]any in memory.
LISTEN and NOTIFY
PostgreSQL has a built-in publish/subscribe mechanism. A session runs LISTEN channel, and any other session sends a message with NOTIFY channel, 'payload' or pg_notify(channel, payload). Notifications sent inside a transaction are delivered when it commits.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// LISTEN needs a dedicated connection; take one out of the pool.
conn, err := pool.Acquire(ctx)
if err != nil {
log.Fatal(err)
}
defer conn.Release()
if _, err := conn.Exec(ctx, "LISTEN jobs"); err != nil {
log.Fatal(err)
}
// Any other session can notify, here a pooled connection.
go func() {
for i := 1; i <= 3; i++ {
// pg_notify works with parameters; NOTIFY jobs, '...' does not.
_, err := pool.Exec(ctx, "SELECT pg_notify('jobs', $1)", fmt.Sprintf("job-%d", i))
if err != nil {
log.Println(err)
}
}
}()
for range 3 {
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
n, err := conn.Conn().WaitForNotification(waitCtx)
cancel()
if err != nil {
log.Fatal(err)
}
fmt.Printf("channel=%s payload=%s\n", n.Channel, n.Payload)
}
}
channel=jobs payload=job-1
channel=jobs payload=job-2
channel=jobs payload=job-3
A listener holds its connection for as long as it listens, so acquire it from the pool once and keep it, or open a separate pgx.Connect connection. Payloads are limited to 8000 bytes; send an id and let the listener load the data.
Using database/sql
If you need a *sql.DB (for example for a migration tool or an ORM that takes one), import github.com/jackc/pgx/v5/stdlib. It registers the driver name "pgx".
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
func main() {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.Exec(`DROP TABLE IF EXISTS notes;
CREATE TABLE notes (id serial PRIMARY KEY, body text, starred bool)`)
if err != nil {
log.Fatal(err)
}
var id int
err = db.QueryRow("INSERT INTO notes (body, starred) VALUES ($1, $2) RETURNING id",
"buy milk", nil).Scan(&id)
if err != nil {
log.Fatal(err)
}
var body string
var starred sql.NullBool
err = db.QueryRow("SELECT body, starred FROM notes WHERE id = $1", id).Scan(&body, &starred)
if err != nil {
log.Fatal(err)
}
fmt.Println(id, body, starred.Valid)
}
1 buy milk false
Everything from the SQL chapter applies. Placeholders are still $1, $2. To get the native pgx connection from a *sql.Conn, use conn.Raw and stdlib.Conn. To wrap an existing pool, use stdlib.OpenDBFromPool(pool).
Beyond hand-written queries
- sqlc generates type-safe Go code from SQL queries and supports pgx v5 directly. It's a popular choice that keeps you writing plain SQL.
- goose, golang-migrate and tern manage schema migrations.
- For tests, run a throwaway PostgreSQL in Docker, e.g. with testcontainers-go, and point
DATABASE_URLat it.
Summary
- Use pgx v5. Create one
pgxpool.Pooland share it. Usepgx/v5/stdlibonly when you need*sql.DB. - Placeholders are
$1,$2. UseRETURNINGinstead ofLastInsertId. - Use
pgx.CollectRowswithRowToStructByNameto avoid manual scan loops; checkpgx.ErrNoRows. - Use pointers or
pgtypetypes for nullable columns. Slices map to arrays, structs tojsonb. - Use
pgx.BeginFuncorBegin+defer tx.Rollback(ctx)+Commit. - Inspect
*pgconn.PgErrorcodes for constraint violations. - Use
Batchto cut round trips,CopyFromfor bulk loads, contexts for timeouts.