database/sql & pgx: Connections, Prepared Statements, Transactions, Repository Pattern
"DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines." —
database/sqlpackage source, typeDBdoc comment (Go 1.27)
Summary: How a Go service talks to PostgreSQL correctly: database/sql and its pool, drivers (pgx stdlib, lib/pq, go-sql-driver/mysql), queries and scanning, NULLs, placeholders, prepared statements and pgx's statement cache, transactions with the defer-Rollback pattern and retries, the pgx v5 native API (pgxpool, CollectRows, batches, COPY, LISTEN/NOTIFY), error inspection by SQLSTATE, timeouts, and a repository layer that keeps all of this out of your domain code. Focus: sql.Open is lazy and *sql.DB is a pool; the four pool knobs; QueryContext/QueryRowContext/ExecContext; rows.Next/Scan/Err/Close; sql.ErrNoRows; sql.NullString, sql.Null[T] and pointers; $1 vs ?; Stmt and implicit per-connection prepare; pgx QueryExecMode; BeginTx, isolation levels, Commit/Rollback; ctx cancellation; pgconn.PgError and SQLSTATE 40001/23505/57014; pgxpool.Config; PgBouncer transaction mode; repositories, sqlc, ORMs and migrations; testing and observability. Learning goal: Open one pool per database at startup and size it on purpose, write queries that cannot leak connections or swallow errors, run every multi-statement change in one transaction that rolls back on any exit and retries on serialization failure, choose between database/sql and native pgx with reasons, and read a production error (SQLSTATE 40001, context deadline exceeded, prepared statement "stmtcache_..." does not exist) and know what to change.
This page owns the Go side of relational access: the database/sql package, the pgx driver and toolkit, and the Go code patterns built on them. It does not re-teach the database theory. Pool sizing against max_connections and poolers in general are in Connection Pooling; what a transaction guarantees is in ACID & Transactions; which anomaly each level allows is in Isolation Levels; lazy loading and N+1 across ORMs in ORM Pitfalls; migration strategy (expand/contract, zero downtime) in Schema Migrations; the server itself in PostgreSQL Fundamentals. Context, deadlines and how pgx reacts to cancellation are in context; interfaces and fakes for tests in Mocking with Interfaces & DI; the repository as a DDD building block in Repositories; writing events in the same transaction in Outbox Pattern; a full HTTP service around a repository in A REST API in Go.
Facts below were checked against the Go 1.27 standard-library source (database/sql, database/sql/driver), the go.dev "Accessing relational databases" guides, the Go 1.8, 1.10, 1.13, 1.15, 1.17 and 1.22 release notes and api/go1.N.txt files, the pgx v5.8.0 source at its tag (doc.go, conn.go, rows.go, named_args.go, batch.go, copy_from.go, tx.go, tracer.go, pgxpool, stdlib, pgconn) plus the current pgx CHANGELOG up to 5.13.0, the pgx wiki, the PostgreSQL current docs (isolation, PREPARE, COPY, LISTEN/NOTIFY, client settings, error codes, protocol), PgBouncer's config, features and changelog pages, and the READMEs of lib/pq, go-sql-driver/mysql, sqlc, golang-migrate, goose, tern, bun, squirrel, goqu, otelsql, otelpgx, pgxmock, sqlmock and dockertest. The snippets declare go 1.24 and pin github.com/jackc/pgx/v5 v5.8.0, the last pgx release whose go.mod says 1.24 (5.9.0 and later require Go 1.25). That pin is for this module only: pgx 5.12.0 fixed an SQL injection in simple-protocol batches and an authentication bypass, so production code on Go 1.25+ should use the latest 5.x. Snippets were compiled, vetted and tested with -race on Go 1.27.4 (macOS). PostgreSQL is not installed on the build machine, so the tests use a small fake database/sql driver and pgx code paths that need no server; labs that need a server are marked "expected, not run".
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why a pool, why a driver interface | Why it exists |
| History, version by version | Where it comes from |
| A bad repository and its fix | Go |
| sql.Open lazy, DB is a pool, Ping | Opening a database |
| SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTime | Pool knobs |
| Drivers: pgx stdlib, lib/pq legacy, go-sql-driver/mysql | Drivers |
| QueryContext/QueryRowContext/ExecContext and rows.Next/Scan/Err/Close | Querying |
| sql.ErrNoRows | No rows |
| NULL handling: sql.NullString, sql.Null[T] 1.22, pointers | NULLs |
| placeholders $1 vs ? and SQL injection | Placeholders |
| prepared statements, Stmt, implicit per-connection prepare | Prepared statements |
pgx statement cache modes (QueryExecMode) | pgx statement cache |
| transactions, BeginTx, isolation levels, Commit/Rollback, defer Rollback pattern | Transactions |
| retries on serialization failure 40001 | Retrying a transaction |
| context cancellation behaviour, pgx cancel request | Cancellation |
| pgx v5 native API: pgx.Conn, pgxpool.Pool | Native pgx |
| CollectRows, RowToStructByName, named args | Collecting rows |
| batch, CopyFrom, COPY, unnest, bulk insert | Batches and bulk |
| LISTEN/NOTIFY | LISTEN/NOTIFY |
| pgtype, custom types, AfterConnect | Types |
| pgxpool config, MaxConns, health check, connection string/DSN | pgxpool config |
| timeouts: statement_timeout, lock_timeout | Timeouts |
| error inspection: pgconn.PgError, SQLSTATE | Errors |
| PgBouncer transaction mode and prepared statements | PgBouncer |
| repository pattern, interface per aggregate | Repository pattern |
| tx propagation via context or UnitOfWork | Sharing a transaction |
| sqlc for typed queries, squirrel/goqu builders, GORM/ent/bun trade-offs | sqlc, builders, ORMs |
| migrations: golang-migrate, goose, atlas, tern | Migrations |
| N+1 in Go | N+1 |
| testing: fake driver, pgx mock, real DB, dockertest/testcontainers pointer | Testing |
| observability: otelsql, pgx tracer, pool stats | Observability |
| Internals and exact error texts | Mechanics |
| Bugs and fixes | Solving the classic problems |
| What to use when | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it | Lab |
| Eloquent and PDO next to Go | For PHP/Laravel developers |
Everything in one minute
The database/sql objects. Each row is unpacked in the concept catalogue.
| Type | What it is | Lifetime | Concurrency-safe | Holds a connection |
|---|---|---|---|---|
*sql.DB | A pool of connections plus a driver | Whole process; open once | Yes | Borrows one per call |
*sql.Conn | One pinned connection | Until Close | Not for concurrent statements | Yes, until Close |
*sql.Tx | One transaction | Until Commit or Rollback | No | Yes, the whole time |
*sql.Stmt | A prepared statement | Until Close | Yes | Prepared lazily on each connection used |
*sql.Rows | A result cursor | Until Close or the last Next | No | Yes, until closed |
*sql.Row | Result of QueryRowContext | Until Scan | No | Released by Scan |
The calls you use every day.
| Call | Returns | Use for | Must do afterwards |
|---|---|---|---|
db.QueryContext(ctx, q, args...) | *sql.Rows, error | Many rows | defer rows.Close(), loop Next, check rows.Err() |
db.QueryRowContext(ctx, q, args...) | *sql.Row | Zero or one row | .Scan(...); sql.ErrNoRows when empty |
db.ExecContext(ctx, q, args...) | sql.Result, error | INSERT/UPDATE/DELETE/DDL | RowsAffected() if it matters |
db.BeginTx(ctx, opts) | *sql.Tx, error | Several statements, one unit | defer tx.Rollback(), then tx.Commit() |
db.PrepareContext(ctx, q) | *sql.Stmt, error | One hot statement reused | stmt.Close() on shutdown |
db.PingContext(ctx) | error | Startup and readiness checks | Nothing |
The same work in pgx v5 native.
database/sql | pgx v5 | Difference |
|---|---|---|
sql.Open("pgx", dsn) | pgxpool.New(ctx, dsn) | Both lazy; pgxpool returns "without waiting for any connections" |
db.QueryContext + loop | pool.Query + pgx.CollectRows(rows, pgx.RowToStructByName[T]) | Collect closes rows and checks errors |
sql.NullString | *string or pgtype.Text | pgx maps NULL to nil pointers |
?/$1 only | $1 or @name with pgx.NamedArgs | Named args rewritten client-side |
tx.Commit() | tx.Commit(ctx) | pgx methods take ctx |
| not available | pool.SendBatch, pool.CopyFrom, conn.WaitForNotification | PostgreSQL-only features |
sql.ErrNoRows | pgx.ErrNoRows | Wraps sql.ErrNoRows since pgx 5.7.0 |
The errors you will read in logs.
| Text | Meaning | What to do |
|---|---|---|
sql: no rows in result set | sql.ErrNoRows from Row.Scan | Map to a domain "not found" |
sql: transaction has already been committed or rolled back | sql.ErrTxDone | Expected from a deferred Rollback; a bug anywhere else |
context deadline exceeded | Your ctx expired (waiting for a conn or running the query) | Check pool wait stats and query time |
ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) | Serialization failure under Repeatable Read or Serializable | Retry the whole transaction |
ERROR: duplicate key value violates unique constraint "users_email_key" (SQLSTATE 23505) | Unique violation | Map the constraint to a 409 |
ERROR: canceling statement due to statement timeout (SQLSTATE 57014) | statement_timeout fired | Fix the query or raise the limit for that job |
ERROR: prepared statement "stmtcache_..." does not exist (SQLSTATE 26000) | Statement cache behind a transaction-mode pooler | See PgBouncer |
sql: Scan error on column index 0, name "phone": converting NULL to string is unsupported | NULL scanned into a plain string | Use a pointer or sql.Null[string] |
Why it exists
Opening a PostgreSQL connection costs a TCP (often TLS) handshake, authentication and a new server process; PostgreSQL then caps the total with max_connections. A Go server handles thousands of concurrent requests with goroutines, so it cannot open a connection per request, and it cannot share one connection either, because a connection runs one statement at a time and carries session state (an open transaction, SET values, prepared statements). The answer is a pool: a few long-lived connections, lent to one goroutine at a time and returned. database/sql is that pool plus a driver interface, so the same code (and the same libraries: migration tools, ORMs, tracing wrappers) works with PostgreSQL, MySQL, SQLite or SQL Server, and each driver only implements the wire protocol.
Portable database/sql | Native pgx |
|---|---|
| One API for every database; libraries expect it | PostgreSQL only |
| Pool in the standard library | pgxpool (built on puddle) |
Types limited to driver.Value plus Scanner/Valuer | About 70 PostgreSQL types via pgtype, binary format |
| No COPY, no batch, no LISTEN | CopyFrom, SendBatch, WaitForNotification |
| Statement handling up to the driver | Automatic statement cache, five exec modes |
| Slightly slower ("The pgx interface is faster", README) | Faster, fewer allocations |
An everyday picture. A car-sharing lot. The company (your process) owns a fixed number of cars (connections). An employee (goroutine) takes a key, drives, and must bring the key back; if everyone keeps their key (unclosed Rows), the next person waits at the counter (the wait queue) until someone returns one or they give up (ctx deadline). A long trip with many stops that must all happen together is a booking (transaction): the same car for the whole trip. Old cars are retired after some kilometres (SetConnMaxLifetime), cars parked too long are returned to the dealer (SetConnMaxIdleTime).
Three common misunderstandings, up front
- "
sql.Openconnects to the database." It "may just validate its arguments without creating a connection"; the first query orPingdials. A wrong password shows up on the first request unless youPingContextat startup. - "I should open and close a
*sql.DBper request."*sql.DBis the pool. "The Open function should be called just once. It is rarely necessary to close a DB." Opening per request means a new pool, a new connection and a closed connection every time. - "
defer tx.Rollback()will undo my committed transaction." After a successfulCommitthe deferredRollbackreturnssql.ErrTxDoneand sends nothing to the server; the test in Go shows the driver never sees it.
Where it comes from
database/sql has been part of the standard library since Go 1 (it is in api/go1.txt), with the driver interfaces in database/sql/driver and no drivers of its own ("No database drivers are included in the Go standard library"). The go.dev wiki page SQLInterface still describes the basic usage, and SQLDrivers lists third-party drivers, marking those that pass the compatibility test suite (both jackc/pgx and lib/pq carry the mark). Go 1.6 added SetConnMaxLifetime (it is listed in api/go1.6.txt). Go 1.8 was the big release: the ...Context methods, so that using them "enables canceling in-progress queries should the driver support that", TxOptions with IsolationLevel and ReadOnly for BeginTx, NamedArg and sql.Named, multiple result sets and ColumnTypes. Go 1.10 added driver.Connector and sql.OpenDB (api/go1.10.txt). Go 1.13 added NullTime and NullInt32. Go 1.15 added SetConnMaxIdleTime, which "allows removing a connection from the connection pool after it has been idle for a period of time, without regard to the total lifespan of the connection", and Row.Err. Go 1.17 added NullInt16 and NullByte. Go 1.22 added the generic Null[T], to "provide a way to scan nullable columns for any column types".
On the PostgreSQL side, lib/pq was the first widely used pure-Go driver. Its v1.10.9 README put it in maintenance mode ("It generally does not accept new features") and said: "For users that require new features or reliable resolution of reported bugs, we recommend using pgx". Releases resumed in 2026 (v1.12.0 in March 2026) and the current README no longer carries that notice, but pgx is what most new PostgreSQL code chooses; sqlc can generate pgx code (sql_package: pgx/v5) but its sql_package "Defaults to database/sql". pgx by Jack Christensen went through v3 and v4; v5.0.0 (17 September 2022) merged pgconn, pgtype and pgproto3 into one repository, added generics-based CollectRows, NamedArgs and a new pgtype. Later 5.x releases added RowToStructByName (5.1.0), StrictNamedArgs (5.6.0), made pgx.ErrNoRows wrap sql.ErrNoRows (5.7.0), added MinIdleConns (5.7.3) and the PrepareConn hook (5.7.6) to pgxpool, required Go 1.24 (5.8.0, December 2025), and then Go 1.25 (5.9.0 onward); 5.13.0 (November 2026) is current.
Go
Before
A store that works on a quiet day. It concatenates user input into SQL, has no context, leaks the connection when Scan fails, never checks rows.Err(), lets sql.NullString leak into the domain type, and moves money with two independent autocommit statements.
// Package before is a first repository that works on a quiet day: it builds SQL
// with string concatenation, has no context, leaks rows on error paths, never
// checks rows.Err, lets sql.NullString leak into the domain and moves money
// with two independent autocommit statements.
package before
import (
"database/sql"
"fmt"
)
// Order leaks a database/sql type (sql.NullString) into the domain model.
type Order struct {
ID int64
Email string
Note sql.NullString
TotalCents int64
}
// Store holds the pool; the bad parts are in the methods.
type Store struct{ DB *sql.DB }
// ByCustomer concatenates user input into SQL (injection) and uses Query without a context.
func (s *Store) ByCustomer(email string) ([]Order, error) {
rows, err := s.DB.Query("SELECT id, email, note, total_cents FROM orders WHERE email = '" + email + "'")
if err != nil {
return nil, err
}
var out []Order
for rows.Next() {
var o Order
if err := rows.Scan(&o.ID, &o.Email, &o.Note, &o.TotalCents); err != nil {
return nil, err // rows is never closed on this path: the connection stays busy
}
out = append(out, o)
}
return out, nil // rows.Err() is never checked: a broken stream looks like a short list
}
// Transfer runs two autocommit statements: if the second fails, the money is gone.
func (s *Store) Transfer(from, to, cents int64) error {
if _, err := s.DB.Exec(fmt.Sprintf("UPDATE accounts SET balance = balance - %d WHERE id = %d", cents, from)); err != nil {
return err
}
_, err := s.DB.Exec(fmt.Sprintf("UPDATE accounts SET balance = balance + %d WHERE id = %d", cents, to))
return err
}Its tests prove two of the problems against the fake driver: the input arrives inside the SQL text with zero arguments, and when the credit fails the debit has already been committed (no BEGIN, no ROLLBACK reached the driver).
package before
import (
"errors"
"strings"
"testing"
"academy/database-sql-pgx/internal/fakedb"
)
func TestInputBecomesSQL(t *testing.T) {
fake := fakedb.New(nil)
s := &Store{DB: fake.Open()}
if _, err := s.ByCustomer("x' OR '1'='1"); err != nil {
t.Fatal(err)
}
q := fake.Calls()[1] // calls[0] is the connect
if !strings.Contains(q.Query, "OR '1'='1'") || len(q.Args) != 0 {
t.Fatalf("expected the input inside the SQL text, got %q args=%v", q.Query, q.Args)
}
}
func TestTransferIsNotAtomic(t *testing.T) {
fake := fakedb.New(func(kind, q string, _ []any) fakedb.Response {
if strings.Contains(q, "balance + ") {
return fakedb.Response{Err: errors.New("connection reset")}
}
return fakedb.Response{Affected: 1}
})
s := &Store{DB: fake.Open()}
if err := s.Transfer(1, 2, 500); err == nil {
t.Fatal("expected the second statement to fail")
}
// The debit ran and was committed on its own: no BEGIN, no ROLLBACK.
if fake.Count("begin") != 0 || fake.Count("rollback") != 0 || fake.Count("exec") != 2 {
t.Fatalf("calls: %v", fake.Kinds())
}
}After
The same store as database/sql expects it: ctx on every call, $1 placeholders, defer rows.Close() and rows.Err(), sql.ErrNoRows mapped to a domain ErrNotFound, a *string for the nullable column, and the transfer in one transaction with defer tx.Rollback(). Each UPDATE must match exactly one row: an UPDATE of a missing account is not an SQL error, it just affects zero rows, so updateOne checks RowsAffected() and returns ErrAccountNotFound, which rolls the whole transfer back.
// Package after is the same store written the way database/sql expects:
// context on every call, placeholders, rows closed and checked, ErrNoRows
// mapped to a domain error, NULL mapped to a pointer, and one transaction
// with the defer-Rollback pattern for the transfer.
package after
import (
"context"
"database/sql"
"errors"
"fmt"
)
// ErrNotFound is the domain error callers check; sql.ErrNoRows stays inside the store.
var ErrNotFound = errors.New("order not found")
// ErrAccountNotFound is returned when a transfer names an account that does not exist.
var ErrAccountNotFound = errors.New("account not found")
// Order uses a plain pointer for the nullable note: nil means SQL NULL.
type Order struct {
ID int64
Email string
Note *string
TotalCents int64
}
// Store wraps the pool. *sql.DB is safe for concurrent use; create it once.
type Store struct{ db *sql.DB }
// NewStore takes the shared pool.
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
// Get returns one order or ErrNotFound.
func (s *Store) Get(ctx context.Context, id int64) (Order, error) {
var o Order
err := s.db.QueryRowContext(ctx,
`SELECT id, email, note, total_cents FROM orders WHERE id = $1`, id,
).Scan(&o.ID, &o.Email, &o.Note, &o.TotalCents)
if errors.Is(err, sql.ErrNoRows) {
return Order{}, fmt.Errorf("get order %d: %w", id, ErrNotFound)
}
if err != nil {
return Order{}, fmt.Errorf("get order %d: %w", id, err)
}
return o, nil
}
// ByCustomer passes the input as an argument ($1), never as SQL text.
func (s *Store) ByCustomer(ctx context.Context, email string) ([]Order, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT id, email, note, total_cents FROM orders WHERE email = $1 ORDER BY id`, email)
if err != nil {
return nil, fmt.Errorf("orders by customer: %w", err)
}
defer rows.Close() // returns the connection to the pool on every path
var out []Order
for rows.Next() {
var o Order
if err := rows.Scan(&o.ID, &o.Email, &o.Note, &o.TotalCents); err != nil {
return nil, fmt.Errorf("scan order: %w", err)
}
out = append(out, o)
}
if err := rows.Err(); err != nil { // errors during iteration surface here, not in Next
return nil, fmt.Errorf("iterate orders: %w", err)
}
return out, nil
}
// Transfer moves money in one transaction: both updates or neither.
func (s *Store) Transfer(ctx context.Context, from, to, cents int64) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin: %w", err)
}
defer tx.Rollback() // no-op after a successful Commit (returns sql.ErrTxDone)
if err := updateOne(ctx, tx, `UPDATE accounts SET balance = balance - $1 WHERE id = $2`, cents, from); err != nil {
return fmt.Errorf("debit %d: %w", from, err)
}
if err := updateOne(ctx, tx, `UPDATE accounts SET balance = balance + $1 WHERE id = $2`, cents, to); err != nil {
return fmt.Errorf("credit %d: %w", to, err)
}
return tx.Commit()
}
// updateOne runs an UPDATE that must match exactly one row. An UPDATE that
// matches nothing is not an error in SQL, so a missing account would
// otherwise let the other half of the transfer commit alone.
func updateOne(ctx context.Context, tx *sql.Tx, q string, args ...any) error {
res, err := tx.ExecContext(ctx, q, args...)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return ErrAccountNotFound
}
return nil
}The tests assert the exact driver call sequence: connect, begin, exec, exec, rollback when the credit fails and connect, begin, exec, exec, commit when it succeeds, which also proves that the deferred Rollback after Commit never reaches the driver. TestTransferRejectsMissingAccount makes the credit to account 999 match zero rows and asserts ErrAccountNotFound, one rollback and no commit.
package after
import (
"database/sql/driver"
"errors"
"slices"
"strings"
"testing"
"academy/database-sql-pgx/internal/fakedb"
)
var cols = []string{"id", "email", "note", "total_cents"}
func TestInputStaysAnArgument(t *testing.T) {
fake := fakedb.New(nil)
s := NewStore(fake.Open())
if _, err := s.ByCustomer(t.Context(), "x' OR '1'='1"); err != nil {
t.Fatal(err)
}
q := fake.Calls()[1]
if strings.Contains(q.Query, "'1'='1'") || q.Args[0] != "x' OR '1'='1" {
t.Fatalf("query %q args %v", q.Query, q.Args)
}
}
func TestGetMapsNoRowsAndNull(t *testing.T) {
fake := fakedb.New(func(kind, q string, args []any) fakedb.Response {
if args[0] == int64(1) {
return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(1), "a@example.test", nil, int64(900)}}}
}
return fakedb.Response{Columns: cols} // zero rows
})
s := NewStore(fake.Open())
o, err := s.Get(t.Context(), 1)
if err != nil || o.Note != nil || o.TotalCents != 900 {
t.Fatalf("got %+v, %v", o, err)
}
if _, err := s.Get(t.Context(), 2); !errors.Is(err, ErrNotFound) {
t.Fatalf("want ErrNotFound, got %v", err)
}
}
func TestRowsErrIsReported(t *testing.T) {
fake := fakedb.New(func(string, string, []any) fakedb.Response {
return fakedb.Response{Columns: cols,
Rows: [][]driver.Value{{int64(1), "a@example.test", "gift", int64(1)}},
RowErr: errors.New("server closed the connection unexpectedly")}
})
_, err := NewStore(fake.Open()).ByCustomer(t.Context(), "a@example.test")
if err == nil || !strings.Contains(err.Error(), "iterate orders") {
t.Fatalf("want iteration error, got %v", err)
}
}
func TestTransferRollsBackOnError(t *testing.T) {
fake := fakedb.New(func(kind, q string, _ []any) fakedb.Response {
if strings.Contains(q, "balance + ") {
return fakedb.Response{Err: errors.New("connection reset")}
}
return fakedb.Response{Affected: 1}
})
if err := NewStore(fake.Open()).Transfer(t.Context(), 1, 2, 500); err == nil {
t.Fatal("expected an error")
}
want := []string{"connect", "begin", "exec", "exec", "rollback"}
if got := fake.Kinds(); !slices.Equal(got, want) {
t.Fatalf("got %v want %v", got, want)
}
}
func TestTransferCommitsOnce(t *testing.T) {
fake := fakedb.New(func(string, string, []any) fakedb.Response { return fakedb.Response{Affected: 1} })
if err := NewStore(fake.Open()).Transfer(t.Context(), 1, 2, 500); err != nil {
t.Fatal(err)
}
// The deferred Rollback after Commit never reaches the driver.
want := []string{"connect", "begin", "exec", "exec", "commit"}
if got := fake.Kinds(); !slices.Equal(got, want) {
t.Fatalf("got %v want %v", got, want)
}
}
// Round 1: a credit to a missing account matches zero rows without an error;
// the transfer must fail and roll back instead of committing the debit alone.
func TestTransferRejectsMissingAccount(t *testing.T) {
fake := fakedb.New(func(kind, q string, args []any) fakedb.Response {
if strings.Contains(q, "balance + ") && args[1] == int64(999) {
return fakedb.Response{Affected: 0}
}
return fakedb.Response{Affected: 1}
})
err := NewStore(fake.Open()).Transfer(t.Context(), 1, 999, 100)
if !errors.Is(err, ErrAccountNotFound) {
t.Fatalf("want ErrAccountNotFound, got %v", err)
}
if fake.Count("commit") != 0 || fake.Count("rollback") != 1 {
t.Fatalf("calls %v", fake.Kinds())
}
}The Go angle
Go splits database access into a small, stable standard-library layer and a competitive driver ecosystem. database/sql gives you the pool, the transaction object, cancellation through context and a scanning contract; drivers decide the wire protocol, type mapping, placeholder syntax and whether a canceled query is stopped on the server. Nothing is hidden: there is no identity map, no lazy loading, no implicit transaction, and every query is a string you wrote or generated. That is why the Go ecosystem leans towards SQL-first tools (sqlc, pgx's CollectRows, squirrel) rather than full ORMs, and why a repository layer is cheap to write: it is just a struct with a *sql.DB or a pgxpool.Pool and a few methods.
The concept catalogue
Opening a database: sql.Open lazy, DB is a pool, Ping Must-know
In plain words: sql.Open("pgx", dsn) builds a pool object and remembers how to connect; it does not connect. Call PingContext at startup so a bad password fails the deploy, not the first customer request. Create it once and share it.
Common misunderstanding: "A nil error from sql.Open means the database is reachable." The doc: "Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping." The opposite mistake is just as common: calling sql.Open in every handler, which creates a pool per request.
Definition: sql.Open(driverName, dataSourceName) looks up a driver registered with sql.Register (usually by a blank import such as _ "github.com/jackc/pgx/v5/stdlib") and returns a *sql.DB. sql.OpenDB(connector) (Go 1.10) does the same from a driver.Connector, which avoids string-based registration and lets you build the config in code. The returned DB "is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once." PingContext borrows a connection (dialing if needed) and calls the driver's Pinger.
1 main() db, err := sql.Open("pgx", dsn) -> err only for unknown driver / bad DSN syntax
2 connections open: 0
3 err = db.PingContext(ctx) -> dials 1 connection, authenticates
4 connections open: 1 (now idle)
5 handler A db.QueryContext(ctx, ...) -> reuses the idle connection
6 handler B db.QueryContext(ctx, ...) (same time) -> dials connection 2
7 shutdown db.Close() -> closes idle conns; in-use ones close when releasedReal scenario: a Kubernetes pod that passes its readiness probe while the database password is wrong because nothing pinged; a CLI that opens a DB per subcommand (fine) next to a web server that opened one per request (2,000 connections per minute, PostgreSQL rejects with 53300 too_many_connections); a service that calls db.Close() in a handler's defer and breaks every other request.
| Constructor | Dials? | Config from | When to use |
|---|---|---|---|
sql.Open("pgx", dsn) | No | DSN string | Default with pgx stdlib or lib/pq |
sql.OpenDB(connector) | No | A driver.Connector | Config built in code (stdlib.GetConnector) |
stdlib.OpenDB(connConfig) | No | pgx.ConnConfig | Need a tracer or TLS config not expressible in a DSN |
stdlib.OpenDBFromPool(pool) | No | Existing pgxpool.Pool | One pool, both APIs |
pgxpool.New(ctx, dsn) | No ("returns without waiting") | DSN | Native pgx |
pgx.Connect(ctx, dsn) | Yes, one connection | DSN | Scripts, migrations, LISTEN |
Fix / how to use it: open in main, ping with a timeout, pass the *sql.DB (or an interface) to constructors. The pool snippet's Open does exactly that, and its first test proves the laziness: zero connections after sql.OpenDB, one after PingContext.
// Package pool configures a *sql.DB: the four pool knobs, a Ping at startup
// (because sql.Open is lazy) and a Stats snapshot for metrics.
package pool
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"time"
)
// Settings are the four database/sql pool knobs.
type Settings struct {
MaxOpen int // SetMaxOpenConns: hard cap; 0 = unlimited (the default)
MaxIdle int // SetMaxIdleConns: idle connections kept; default 2
MaxLifetime time.Duration // SetConnMaxLifetime: recycle after this age; 0 = never
MaxIdleTime time.Duration // SetConnMaxIdleTime: close after this long idle; 0 = never (Go 1.15+)
}
// ForService is a starting point for one service instance talking to PostgreSQL.
// Size MaxOpen from the server's max_connections divided by the number of instances.
func ForService(maxOpen int) Settings {
return Settings{
MaxOpen: maxOpen,
MaxIdle: maxOpen, // keep the pool warm; the idle timeout trims it when quiet
MaxLifetime: 30 * time.Minute,
MaxIdleTime: 5 * time.Minute,
}
}
// Apply sets the knobs on an existing pool.
func Apply(db *sql.DB, s Settings) {
db.SetMaxOpenConns(s.MaxOpen)
db.SetMaxIdleConns(s.MaxIdle)
db.SetConnMaxLifetime(s.MaxLifetime)
db.SetConnMaxIdleTime(s.MaxIdleTime)
}
// Open builds the pool from a driver.Connector (sql.OpenDB), applies the
// settings and pings, so a bad DSN or an unreachable server fails at startup
// instead of on the first request.
func Open(ctx context.Context, c driver.Connector, s Settings) (*sql.DB, error) {
db := sql.OpenDB(c) // like sql.Open: no connection yet
Apply(db, s)
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return db, nil
}
// Snapshot is the subset of sql.DBStats worth exporting as metrics.
type Snapshot struct {
Open, InUse, Idle int
WaitCount int64
WaitDuration time.Duration
MaxIdleClosed int64
MaxIdleTimeClosed int64
MaxLifetimeClosed int64
MaxOpenConnectionsConf int
}
// Stats reads db.Stats(). A growing WaitCount means callers queue for a connection.
func Stats(db *sql.DB) Snapshot {
st := db.Stats()
return Snapshot{
Open: st.OpenConnections, InUse: st.InUse, Idle: st.Idle,
WaitCount: st.WaitCount, WaitDuration: st.WaitDuration,
MaxIdleClosed: st.MaxIdleClosed, MaxIdleTimeClosed: st.MaxIdleTimeClosed,
MaxLifetimeClosed: st.MaxLifetimeClosed, MaxOpenConnectionsConf: st.MaxOpenConnections,
}
}Pool knobs: SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTime Must-know
In plain words: four numbers decide how many connections your process may use, how many it keeps warm, and when it recycles them. The defaults are "unlimited", "2", "forever" and "forever", which is wrong for almost every service.
Common misunderstanding: "Unlimited open connections means maximum throughput." It means that under a traffic spike every goroutine opens its own connection until PostgreSQL refuses (max_connections, "The default is typically 100 connections") and every instance of your service competes for the same server slots. The go.dev guide warns about the other end too: "setting a limit makes database usage similar to acquiring a lock or semaphore, with the result that your application can deadlock waiting for a new database connection" (for example, a goroutine holding a Tx that waits for a second connection from a pool of one).
Definition:
| Knob | Default | Doc says | Typical service value |
|---|---|---|---|
SetMaxOpenConns(n) | 0 = unlimited | "If n <= 0, then there is no limit" | Server budget ÷ instances, e.g. 20 |
SetMaxIdleConns(n) | 2 | "The default max idle connections is currently 2"; reduced to MaxOpen if larger | Equal to MaxOpen for steady load |
SetConnMaxLifetime(d) | 0 = never | "maximum amount of time a connection may be reused"; "closed lazily before reuse" | 30–60 min, shorter behind a load balancer |
SetConnMaxIdleTime(d) | 0 = never | Go 1.15+; "maximum amount of time a connection may be idle" | 1–5 min to shrink after a burst |
pool MaxOpen=2, MaxIdle=2
t=0 G1 QueryContext -> conn#1 in use open=1 inUse=1
t=0 G2 ExecContext -> conn#2 dialed open=2 inUse=2
t=1 G3 QueryContext -> waits (connRequests) WaitCount=1
t=5 G1 rows.Close() -> conn#1 handed to G3 WaitDuration += 4
t=9 G3 ctx deadline? -> if it fired at t=3: "context deadline exceeded" without running any SQLReal scenario: a payment API whose p99 jumped because MaxOpen=10 but a report endpoint kept 8 connections for 30 s; a fleet of 40 pods × unlimited connections taking a 200-connection PostgreSQL down at peak; a NAT gateway or load balancer between the service and the database that silently drops idle TCP flows after a few minutes, fixed with SetConnMaxIdleTime(time.Minute); a failover where old connections kept pointing at the demoted node until SetConnMaxLifetime recycled them.
Symptom in db.Stats() | Meaning | Change |
|---|---|---|
WaitCount and WaitDuration growing | Callers queue for a connection | Shorter queries/transactions first, then a larger MaxOpen |
InUse == MaxOpenConnections for long periods | Saturated or leaked (unclosed rows, long tx) | Look for missing rows.Close, long transactions |
MaxIdleClosed high | Idle cap too small: connections churn | Raise MaxIdle towards MaxOpen |
MaxLifetimeClosed steady | Recycling as configured | Fine |
OpenConnections far below MaxOpen | Pool larger than needed | Lower it; it is a ceiling, not a target |
Fix / how to use it: apply all four at startup, export db.Stats() as gauges, and size the total across all instances against the server (the sizing math is in Connection Pooling). The tests below show a caller timing out while waiting for the only connection, with WaitCount == 1, and an unclosed *sql.Rows starving the pool.
package pool
import (
"context"
"errors"
"testing"
"time"
"academy/database-sql-pgx/internal/fakedb"
)
func TestOpenIsLazyPingConnects(t *testing.T) {
fake := fakedb.New(nil)
db := fake.Open()
defer db.Close()
if fake.Opens() != 0 {
t.Fatalf("sql.OpenDB opened %d connections", fake.Opens())
}
if err := db.PingContext(t.Context()); err != nil {
t.Fatal(err)
}
if fake.Opens() != 1 {
t.Fatalf("after Ping: %d connections", fake.Opens())
}
}
func TestMaxOpenMakesCallersWait(t *testing.T) {
fake := fakedb.New(nil)
db := fake.Open()
defer db.Close()
Apply(db, Settings{MaxOpen: 1, MaxIdle: 1})
held, err := db.Conn(t.Context()) // take the only connection
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
_, err = db.ExecContext(ctx, "SELECT 1")
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want deadline while waiting for a connection, got %v", err)
}
if s := Stats(db); s.WaitCount != 1 || s.InUse != 1 || s.MaxOpenConnectionsConf != 1 {
t.Fatalf("stats %+v", s)
}
held.Close()
if _, err := db.ExecContext(t.Context(), "SELECT 1"); err != nil {
t.Fatal(err)
}
}
func TestUnclosedRowsHoldTheConnection(t *testing.T) {
fake := fakedb.New(func(string, string, []any) fakedb.Response {
return fakedb.Response{Columns: []string{"n"}}
})
db := fake.Open()
defer db.Close()
Apply(db, Settings{MaxOpen: 1, MaxIdle: 1})
rows, err := db.QueryContext(t.Context(), "SELECT n FROM t") // never iterated, never closed
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
if err := db.QueryRowContext(ctx, "SELECT 1").Scan(new(int)); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want pool exhaustion, got %v", err)
}
rows.Close()
}
func TestOpenPings(t *testing.T) {
fake := fakedb.New(nil)
db, err := Open(t.Context(), fake.Connector(), ForService(10))
if err != nil {
t.Fatal(err)
}
defer db.Close()
if fake.Count("ping") != 1 || db.Stats().MaxOpenConnections != 10 {
t.Fatalf("calls %v", fake.Kinds())
}
}Drivers: pgx stdlib, lib/pq legacy, go-sql-driver/mysql Important
In plain words: database/sql speaks no database. A driver package registers itself under a name and implements the protocol; you pick it with a blank import and the name in sql.Open.
Common misunderstanding: "All PostgreSQL drivers behave the same under database/sql." They differ in cancellation (pgx closes or sends a CancelRequest; see context), in type support (arrays, jsonb, numeric), in whether they prepare statements implicitly, and in maintenance status.
Definition: a driver implements driver.Driver (or driver.Connector) and driver.Conn; optional interfaces such as QueryerContext, ExecerContext, ConnBeginTx, Pinger, SessionResetter and NamedValueChecker unlock context support, direct queries without prepare, isolation levels, health checks and custom argument types.
import _ "github.com/jackc/pgx/v5/stdlib" // init(): sql.Register("pgx", ...)
db, _ := sql.Open("pgx", "postgres://app:secret@db:5432/orders?sslmode=verify-full")
-> database/sql: look up "pgx" -> driver.Open(dsn) on first use -> *stdlib.Conn wraps *pgx.ConnReal scenario: a team on lib/pq that needed COPY and LISTEN with reconnects and moved to pgx; a MySQL service where ? placeholders and parseTime=true in the DSN are required to scan DATETIME into time.Time; a library (goose, sqlx, otelsql) that accepts only *sql.DB, so the pgx pool is exposed through stdlib.OpenDBFromPool.
| Driver | Name in sql.Open | Placeholders | Status / notes |
|---|---|---|---|
github.com/jackc/pgx/v5/stdlib | "pgx" (also "pgx/v5") | $1 (no named parameters through database/sql) | Actively developed; (*sql.Conn).Raw gives the *pgx.Conn |
github.com/lib/pq | "postgres" | $1 | Long in maintenance mode (v1.10.9 README recommends pgx); releases resumed 2026; legacy in most codebases |
github.com/go-sql-driver/mysql | "mysql" | ? | MySQL/MariaDB; interpolateParams, parseTime DSN options |
modernc.org/sqlite, github.com/mattn/go-sqlite3 | "sqlite", "sqlite3" | ?, $1 | Pure Go vs cgo |
github.com/microsoft/go-mssqldb | "sqlserver" | @p1 | SQL Server |
Fix / how to use it: for PostgreSQL pick pgx; use its stdlib adapter when you need database/sql compatibility and its native API otherwise (Native pgx). The pgx README's rule: native "is recommended when: 1. The application only targets PostgreSQL. 2. No other libraries that require database/sql are in use."
Querying: QueryContext/QueryRowContext/ExecContext and rows.Next/Scan/Err/Close Must-know
In plain words: QueryContext returns a cursor you must walk and close; QueryRowContext is for one row and releases the connection when you Scan; ExecContext is for statements that return no rows. Always use the Context versions.
Common misunderstanding: "The loop ended, so everything worked." Next returns false both at the end and on an error: "Rows.Err should be consulted to distinguish between the two cases." A dropped connection mid-stream otherwise looks like a short list. Second one: "defer rows.Close() is optional." When Next returns false the rows close themselves, but any early return inside the loop (a Scan error, a break) leaves the connection busy until the garbage collector, if ever.
Definition: Rows.Next "prepares the next result row for reading with the Rows.Scan method"; "Every call to Rows.Scan, even the first one, must be preceded by a call to Rows.Next." Rows.Close is idempotent "and does not affect the result of Rows.Err". Scan converts into *string, *[]byte, the integer and float pointers, *bool, *time.Time, *any, *sql.RawBytes and any Scanner, checking overflow ("a float64 with value 300 or a string with value "300" can scan into a uint16, but not into a uint8"). The non-Context methods (Query, Exec) call the Context ones with context.Background().
1 rows, err := db.QueryContext(ctx, q, 42) conn#3 borrowed
2 defer rows.Close()
3 for rows.Next() { row 1, row 2, ...
4 rows.Scan(&a, &b)
5 } Next == false: EOF or error
6 if err := rows.Err(); err != nil { ... } tells the two apart
7 return Close (no-op if already closed); conn#3 back to the poolReal scenario: an export that silently produced half a CSV after a failover because rows.Err() was not checked; an API that hit pool exhaustion every few hours because a Scan error path returned without closing; a QueryRowContext used for an INSERT ... RETURNING id, which is correct and common.
| Need | Call | Notes |
|---|---|---|
| Many rows | QueryContext | defer rows.Close(), check rows.Err() |
| One row | QueryRowContext(...).Scan(...) | Row.Err() (Go 1.15) to check without scanning |
| INSERT ... RETURNING | QueryRowContext | Scan the returned columns |
| No rows returned | ExecContext | Result.RowsAffected(); LastInsertId is not supported by PostgreSQL drivers |
| Huge result | QueryContext + streaming | Do not collect into a slice; see Cursors & Streaming |
| Multiple result sets | rows.NextResultSet() | Go 1.8+, driver-dependent |
Fix / how to use it: the After ByCustomer method is the template; its TestRowsErrIsReported makes the fake driver fail after the first row and asserts the error surfaces from rows.Err().
No rows: sql.ErrNoRows Must-know
In plain words: when QueryRowContext finds nothing, the error appears at Scan as sql.ErrNoRows. It is not a failure of the database; translate it into your own "not found" right there.
Common misunderstanding: "QueryRowContext returns the error." It returns a *Row that "defers this error until a Scan". And QueryContext with zero rows returns no error at all, just an empty loop.
Definition: var ErrNoRows = errors.New("sql: no rows in result set"), "returned by Row.Scan when DB.QueryRow doesn't return a row". In pgx, pgx.ErrNoRows ("no rows in result set") wraps sql.ErrNoRows since 5.7.0, so errors.Is(err, sql.ErrNoRows) works for both APIs (asserted in the errs test).
1 err := db.QueryRowContext(ctx, `SELECT ... WHERE id = $1`, 99).Scan(&o.ID, ...)
2 errors.Is(err, sql.ErrNoRows) -> true
3 return fmt.Errorf("get order 99: %w", ErrNotFound) -> handler maps ErrNotFound to 404Real scenario: an API returning 500 for an unknown id because the handler logged every error; a repository that returns (nil, nil) for not-found and a caller dereferencing nil; a "find or create" that checks ErrNoRows and then races with a concurrent insert (use INSERT ... ON CONFLICT instead).
| Situation | Result | Map to |
|---|---|---|
QueryRowContext finds nothing | sql.ErrNoRows at Scan | Domain ErrNotFound |
QueryContext finds nothing | No error, zero iterations | Empty slice |
UPDATE matches nothing | RowsAffected() == 0 | Not found or version conflict |
pgx CollectOneRow finds nothing | pgx.ErrNoRows (errors.Is sql.ErrNoRows) | Domain ErrNotFound |
pgx CollectExactlyOneRow finds two | pgx.ErrTooManyRows | Bug or missing constraint |
Fix / how to use it: check with errors.Is, wrap a domain error with %w, and never return ErrNoRows past the repository; the After Get does exactly this.
NULL handling: sql.NullString, sql.Null[T] 1.22, pointers Must-know
In plain words: a SQL NULL cannot go into a Go string or int64. Give Scan something that can say "no value": a sql.NullString-style struct, the generic sql.Null[T], or a pointer.
Common misunderstanding: "An empty string is the same as NULL." In PostgreSQL '' and NULL are different values (unlike Oracle Database, whose SQL reference says it "currently treats a character value with a length of zero as null"), and scanning a NULL into a plain string fails with "converting NULL to string is unsupported" (real output in the nulls test).
Definition: the typed structs (NullString, NullInt64, NullInt32 (1.13), NullInt16 (1.17), NullByte (1.17), NullFloat64, NullBool, NullTime (1.13)) have a value field and Valid bool. sql.Null[T] (Go 1.22) is struct { V T; Valid bool } implementing Scanner and Valuer; "T should be one of the types accepted by driver.Value". A pointer destination (**string passed as &p) is set to nil for NULL. On the way in, a nil pointer or a Valid == false value is sent as NULL.
row: (id=1, middle_name=NULL, deleted_at=NULL, phone=NULL)
Scan(&c.ID, &c.MiddleName, &c.DeletedAt, &c.Phone)
c.MiddleName = sql.NullString{String: "", Valid: false}
c.DeletedAt = sql.Null[time.Time]{V: zero, Valid: false}
c.Phone = (*string)(nil)
Scan(&plainString) on NULL -> error: converting NULL to string is unsupportedReal scenario: a profile page that crashed for users without a phone number after a migration made the column nullable; JSON APIs that must emit null (pointers marshal to null, sql.NullString marshals to an object unless wrapped); COALESCE(note, '') in SQL when the domain genuinely has no NULL concept.
| Style | Scan | JSON | Allocation | Best for |
|---|---|---|---|---|
sql.NullString etc. | Yes | Object {"String":..,"Valid":..} | None | Older code, sqlc with database/sql default |
sql.Null[T] (1.22) | Yes | Object {"V":..,"Valid":..} | None | Any type, including your own |
*T pointer | Yes | null or value | One per non-NULL value | API structs, pgx, sqlc with emit_pointers_for_null_types |
pgtype.Text, pgtype.Int8 | Yes (pgx) | Implements JSON | None | Native pgx code |
COALESCE in SQL | n/a | n/a | None | When NULL has no meaning in the domain |
Fix / how to use it: choose one style per codebase (pointers at the edges, sql.Null[T] in persistence structs is a good split) and test both the NULL and non-NULL path.
// Package nulls shows the three ways to scan a nullable column with
// database/sql: the typed Null* structs, sql.Null[T] (Go 1.22) and pointers.
package nulls
import (
"context"
"database/sql"
"time"
)
// Customer keeps NULL-ability explicit in three styles; pick one per codebase.
type Customer struct {
ID int64
MiddleName sql.NullString // pre-generics style: NullString, NullInt64, NullTime, ...
DeletedAt sql.Null[time.Time] // Go 1.22+: one generic type for any column type
Phone *string // pointer: nil means NULL; what pgx scans NULL into (sqlc emits it only with emit_pointers_for_null_types: true)
}
// Get scans a row whose last three columns may be NULL.
func Get(ctx context.Context, db *sql.DB, id int64) (Customer, error) {
var c Customer
err := db.QueryRowContext(ctx,
`SELECT id, middle_name, deleted_at, phone FROM customers WHERE id = $1`, id,
).Scan(&c.ID, &c.MiddleName, &c.DeletedAt, &c.Phone)
return c, err
}
// SetPhone writes NULL when phone is nil: a nil *string and a zero-Valid Null[T]
// are both sent as NULL by database/sql.
func SetPhone(ctx context.Context, db *sql.DB, id int64, phone *string) error {
_, err := db.ExecContext(ctx, `UPDATE customers SET phone = $1 WHERE id = $2`, phone, id)
return err
}
// NullIfEmpty turns "" into NULL, the usual rule for optional form fields.
func NullIfEmpty(s string) sql.Null[string] {
return sql.Null[string]{V: s, Valid: s != ""}
}package nulls
import (
"database/sql/driver"
"testing"
"time"
"academy/database-sql-pgx/internal/fakedb"
)
func TestScanNulls(t *testing.T) {
deleted := time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC)
fake := fakedb.New(func(kind, q string, args []any) fakedb.Response {
cols := []string{"id", "middle_name", "deleted_at", "phone"}
if args[0] == int64(1) {
return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(1), nil, nil, nil}}}
}
return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(2), "Ann", deleted, "+1-555-0100"}}}
})
db := fake.Open()
c, err := Get(t.Context(), db, 1)
if err != nil {
t.Fatal(err)
}
if c.MiddleName.Valid || c.DeletedAt.Valid || c.Phone != nil {
t.Fatalf("all three should be NULL: %+v", c)
}
c, err = Get(t.Context(), db, 2)
if err != nil {
t.Fatal(err)
}
if c.MiddleName.String != "Ann" || !c.DeletedAt.V.Equal(deleted) || *c.Phone != "+1-555-0100" {
t.Fatalf("values not scanned: %+v", c)
}
}
func TestScanNullIntoStringFails(t *testing.T) {
fake := fakedb.New(func(string, string, []any) fakedb.Response {
return fakedb.Response{Columns: []string{"phone"}, Rows: [][]driver.Value{{nil}}}
})
var phone string // not nullable
err := fake.Open().QueryRowContext(t.Context(), "SELECT phone FROM customers").Scan(&phone)
if err == nil {
t.Fatal("scanning NULL into a plain string must fail")
}
t.Log(err) // converting NULL to string is unsupported
}
func TestWriteNull(t *testing.T) {
fake := fakedb.New(nil)
if err := SetPhone(t.Context(), fake.Open(), 7, nil); err != nil {
t.Fatal(err)
}
if got := fake.Calls()[1].Args[0]; got != nil {
t.Fatalf("nil *string should be sent as NULL, got %#v", got)
}
if v := NullIfEmpty(""); v.Valid {
t.Fatal("empty string should be NULL")
}
}Placeholders: placeholders $1 vs ? and SQL injection Must-know
In plain words: never build SQL by pasting values into the string. Write a placeholder and pass the value separately; the driver sends it as data, so a quote in the input cannot end your string literal.
Common misunderstanding: "database/sql translates ? for every database." It does not touch the SQL text at all. The placeholder syntax belongs to the driver: PostgreSQL drivers use $1, $2, MySQL and SQLite use ?, SQL Server @p1. The go.dev guide: "Parameter placeholders vary depending on the DBMS and driver you're using. For example, pq driver for Postgres accepts a placeholder form such as $1 instead of ?."
Definition: with pgx and the default exec mode the SQL text goes in a Parse message and the values in a Bind message, so the server never parses user input as SQL. go-sql-driver/mysql with interpolateParams=true builds a single query string client-side (fewer round trips) and its README warns that it is only safe when the effective charset is known. Identifiers (table and column names) cannot be placeholders; quote them with pgx.Identifier{name}.Sanitize() or choose from an allow-list.
Before: "... WHERE email = '" + email + "'" email = x' OR '1'='1
-> WHERE email = 'x' OR '1'='1' every row returned, args = []
After: "... WHERE email = $1", email
-> Parse("... = $1") Bind(["x' OR '1'='1"]) no row matches, args = [input]Real scenario: a search box that dumped every customer through ' OR '1'='1; an ORDER BY built from a query parameter (use a map of allowed columns); a LIKE search where the user's % must be escaped but still passed as an argument; an IN (...) list built with string joins instead of = ANY($1).
| Database / driver | Placeholder | Named | Notes |
|---|---|---|---|
| PostgreSQL / pgx stdlib, lib/pq | $1 | No (pgx native: @name with NamedArgs) | $1 may repeat in the text |
| MySQL / go-sql-driver/mysql | ? | No | interpolateParams option |
| SQLite / modernc, mattn | ?, ?NNN, :AAAA, @AAAA, $AAAA (SQLite expression docs) | Yes, sql.Named | Plain ? "is discouraged" by SQLite |
| SQL Server / go-mssqldb | @p1 to @pN, @Name (go-mssqldb README) | Yes, sql.Named | |
| Oracle / godror | :1, :2 (godror README examples) | Not covered here |
Fix / how to use it: placeholders always, = ANY($1) with a slice for lists, allow-lists for identifiers. The two tests in Go show the injected text reaching the driver in the Before store and arriving as an argument in the After store.
Prepared statements: Stmt and implicit per-connection prepare Important
In plain words: a prepared statement is SQL the server has parsed (and maybe planned) once, kept on one connection under a name, and executed many times with different values. In Go you rarely need to prepare by hand: drivers do it for you, and *sql.Stmt hides that it is really "one prepare per connection".
Common misunderstanding: "db.Prepare prepares the statement once on the server." A server-side prepared statement lives in one session. The doc: "If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically." With 20 pool connections that is up to 20 prepares. And a Stmt prepared on a Tx "will be bound to a single underlying connection forever" and becomes unusable when the Tx ends.
Definition: database/sql tries the driver's QueryerContext/ExecerContext first, then the deprecated Queryer/Execer; only if the connection implements neither does it prepare: the driver docs say DB.Query "will first prepare a query, execute the statement, and then close the statement" (in queryDC, ctxDriverPrepare is called after both checks), so every QueryContext costs a Prepare plus an Execute (the implicit per-connection prepare). pgx's stdlib implements both interfaces and uses pgx's own statement cache instead. In PostgreSQL, "Prepared statements only last for the duration of the current database session"; with plan_cache_mode = auto "the first five executions are done with custom plans" before the server considers a generic plan.
pool of 3 connections, stmt := db.Prepare(q) prepared on conn#1
G1 stmt.Query -> conn#1 free, already prepared Bind/Execute
G2 stmt.Query -> conn#1 busy, take conn#2 Parse on conn#2, then Execute
G3 stmt.Query -> conn#3 Parse on conn#3, then Execute
stmt.Close() -> closes it on conn#1..#3Real scenario: a hot price lookup prepared at startup and reused (the snippet); a bulk loop of inserts in one transaction using tx.PrepareContext; an old driver implementing neither QueryerContext nor Queryer doubling round trips for every query until replaced; ERROR: cached plan must not change result type after ALTER TABLE while clients hold prepared SELECT *.
| Way | Who prepares | Where it lives | Cost |
|---|---|---|---|
db.QueryContext with pgx stdlib | pgx statement cache | Each connection, LRU of 512 | 1 extra round trip on first use per connection |
db.QueryContext with a driver implementing neither QueryerContext nor Queryer | database/sql | Prepared and closed per call | 2–3 round trips every call |
db.PrepareContext → *sql.Stmt | database/sql | Lazily on every connection used | Prepare per connection; must Close |
tx.PrepareContext | database/sql | The tx's connection | Closed at Commit/Rollback |
SQL PREPARE name AS ... | You | The session | Breaks behind transaction pooling |
Fix / how to use it: with pgx, skip db.Prepare (the cache does it); with other drivers prepare only statements that run thousands of times. The tests count calls on the fake driver: three queries through a driver exposing only Prepare (no QueryerContext, no Queryer) cause three prepares and three closes; one DB-level Stmt used while its first connection is busy gets prepared again on new connections.
// Package prepared shows explicit *sql.Stmt use. A Stmt prepared on the DB is
// re-prepared lazily on every pool connection it runs on; a Stmt prepared on a
// Tx lives and dies with that transaction.
package prepared
import (
"context"
"database/sql"
"fmt"
)
// PriceLookup prepares one hot statement at startup and reuses it.
type PriceLookup struct{ stmt *sql.Stmt }
// NewPriceLookup prepares on the pool. Close it on shutdown.
func NewPriceLookup(ctx context.Context, db *sql.DB) (*PriceLookup, error) {
st, err := db.PrepareContext(ctx, `SELECT price_cents FROM products WHERE sku = $1`)
if err != nil {
return nil, fmt.Errorf("prepare price lookup: %w", err)
}
return &PriceLookup{stmt: st}, nil
}
// Price runs the prepared statement; safe for concurrent use.
func (p *PriceLookup) Price(ctx context.Context, sku string) (int64, error) {
var cents int64
err := p.stmt.QueryRowContext(ctx, sku).Scan(¢s)
return cents, err
}
// Close releases the statement on every connection it was prepared on.
func (p *PriceLookup) Close() error { return p.stmt.Close() }
// InsertLines uses a transaction-scoped statement for a loop of inserts.
func InsertLines(ctx context.Context, db *sql.DB, orderID int64, skus []string) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
st, err := tx.PrepareContext(ctx, `INSERT INTO order_lines (order_id, sku) VALUES ($1, $2)`)
if err != nil {
return err
}
defer st.Close() // also closed automatically at Commit/Rollback
for _, sku := range skus {
if _, err := st.ExecContext(ctx, orderID, sku); err != nil {
return fmt.Errorf("insert %s: %w", sku, err)
}
}
return tx.Commit()
}package prepared
import (
"database/sql/driver"
"sync"
"testing"
"academy/database-sql-pgx/internal/fakedb"
)
func priceFake() *fakedb.DB {
return fakedb.New(func(kind, q string, _ []any) fakedb.Response {
return fakedb.Response{Columns: []string{"price_cents"}, Rows: [][]driver.Value{{int64(1999)}}}
})
}
// A driver without QueryerContext forces database/sql to prepare every query.
func TestImplicitPreparePerQuery(t *testing.T) {
fake := priceFake()
fake.NoQueryer = true
db := fake.Open()
for range 3 {
if err := db.QueryRowContext(t.Context(), "SELECT 1").Scan(new(int64)); err != nil {
t.Fatal(err)
}
}
if fake.Count("prepare") != 3 || fake.Count("close-stmt") != 3 {
t.Fatalf("calls %v", fake.Kinds())
}
}
// A DB-level Stmt is prepared once per connection it is used on.
func TestStmtReprepareOnNewConnection(t *testing.T) {
fake := priceFake()
db := fake.Open()
p, err := NewPriceLookup(t.Context(), db) // prepared on connection 1
if err != nil {
t.Fatal(err)
}
defer p.Close()
// Two concurrent callers while connection 1 is held force a second connection.
held, _ := db.Conn(t.Context())
var wg sync.WaitGroup
for range 2 {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := p.Price(t.Context(), "A1"); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
held.Close()
if fake.Opens() < 2 || fake.Count("prepare") < 2 {
t.Fatalf("opens=%d prepares=%d", fake.Opens(), fake.Count("prepare"))
}
t.Logf("connections=%d prepares=%d", fake.Opens(), fake.Count("prepare"))
}
func TestTxStmt(t *testing.T) {
fake := fakedb.New(func(string, string, []any) fakedb.Response { return fakedb.Response{Affected: 1} })
if err := InsertLines(t.Context(), fake.Open(), 7, []string{"A1", "B2", "C3"}); err != nil {
t.Fatal(err)
}
if fake.Count("prepare") != 1 || fake.Count("exec") != 3 || fake.Count("commit") != 1 {
t.Fatalf("calls %v", fake.Kinds())
}
}pgx statement cache modes: QueryExecMode Important
In plain words: pgx prepares every query the first time a connection sees it, names it after a hash of the SQL, and reuses it. That makes repeated queries one round trip and fully typed, but it assumes the statement's shape does not change and that the connection stays yours. Five modes let you trade that off.
Common misunderstanding: "Turning off the cache means pgx interpolates values into SQL." Only the simple-protocol mode does client-side interpolation; QueryExecModeExec still sends parameters separately, it just does not create a named statement.
Definition: from conn.go (v5.8.0):
Mode (default_query_exec_mode=) | Round trips | Named statement | Risk / limit |
|---|---|---|---|
QueryExecModeCacheStatement (cache_statement, default) | 1 after first use | Yes, stmtcache_<sha256 prefix> | "If the database schema is modified or the search_path is changed after a statement is cached then the first execution of a previously cached query may fail" |
QueryExecModeCacheDescribe (cache_describe) | 1 after first use | No (caches the description) | Same schema-change caveat |
QueryExecModeDescribeExec (describe_exec) | 2 | No (unnamed statement) | "may cause problems with connection poolers that switch the underlying connection between round trips" |
QueryExecModeExec (exec) | 1 | No | Types inferred from Go values; text format; ambiguous types (map[string]string) rejected |
QueryExecModeSimpleProtocol (simple_protocol) | 1 | No | Client-side interpolation; []byte is bytea; 5.12.0 fixed an injection in simple-protocol batches |
statement_cache_capacity and description_cache_capacity (both default 512) size the per-connection LRU caches. A mode can also be chosen per query by passing it as the first argument: pool.Query(ctx, sql, pgx.QueryExecModeExec, args...).
conn#1 first Query("SELECT ... $1", 7) Parse "stmtcache_9f2c..." + Describe, then Bind/Execute 2 round trips
conn#1 second Query("SELECT ... $1", 8) Bind/Execute stmtcache_9f2c... 1 round trip
ALTER TABLE orders ADD COLUMN note text (SELECT * now returns one more column)
conn#1 third Query(...) ERROR: cached plan must not change result type -> pgx drops the entry; next call re-preparesReal scenario: a SELECT * that failed once per connection right after a migration (list columns explicitly); a service behind PgBouncer 1.18 throwing prepared statement "stmtcache_..." does not exist (switch to exec); a report tool with many one-off queries filling the cache (lower capacity or use exec).
Fix / how to use it: keep the default against PostgreSQL directly; choose exec (or simple_protocol on pgx ≥ 5.12.0) behind a transaction pooler that does not track prepared statements; never write SELECT * in application queries. The pgxnative test parses default_query_exec_mode=exec&statement_cache_capacity=128 from a DSN and asserts both.
Transactions: BeginTx, isolation levels, Commit/Rollback, defer Rollback pattern Must-know
In plain words: BeginTx reserves one connection and starts a transaction on it; every statement must go through the returned *sql.Tx; Commit makes it permanent and returns the connection. Put defer tx.Rollback() right after BeginTx so that any early return, error or panic undoes the work.
Common misunderstanding: "Calling db.ExecContext inside my transaction function is part of the transaction." The go.dev guide: "take care not to call the non-transaction sql.DB methods directly, too, as those will execute outside the transaction, giving your code an inconsistent view of the state of the database or even causing deadlocks". Another: "I can run BEGIN with db.ExecContext." The same guide says not to: "Do not use transaction-related SQL statements such as BEGIN and COMMIT directly", because the next statement may run on a different pool connection.
Definition: BeginTx(ctx, *sql.TxOptions{Isolation, ReadOnly}) (Go 1.8). "The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled." "If a non-default isolation level is used that the driver doesn't support, an error will be returned." The levels are LevelDefault, LevelReadUncommitted, LevelReadCommitted, LevelWriteCommitted, LevelRepeatableRead, LevelSnapshot, LevelSerializable, LevelLinearizable; PostgreSQL drivers map the four ANSI ones (PostgreSQL treats Read Uncommitted as Read Committed; what each level prevents is in Isolation Levels). After Commit or Rollback, every method returns sql.ErrTxDone ("sql: transaction has already been committed or rolled back"). In pgx native, pgx.TxOptions{IsoLevel: pgx.Serializable, AccessMode: pgx.ReadOnly, DeferrableMode: pgx.Deferrable}, Rollback "is safe to call even if the tx is already closed", tx.Begin inside a transaction creates a savepoint (pseudo nested transaction), and pgx.BeginFunc/BeginTxFunc wrap the whole pattern.
G1 (Transfer) PostgreSQL session on conn#4
1 tx, _ := db.BeginTx(ctx, nil) BEGIN
2 defer tx.Rollback()
3 tx.ExecContext(debit) UPDATE accounts ... id=1
4 tx.ExecContext(credit) -> error UPDATE accounts ... id=2 (fails)
5 return err -> deferred Rollback ROLLBACK (debit undone)
--- success path ---
5' tx.Commit() COMMIT
6' deferred Rollback -> sql.ErrTxDone, no SQL conn#4 back in the poolReal scenario: a transfer between wallets; creating an order with its lines and an outbox row; "reserve stock, then charge" where the charge is an HTTP call (keep it outside the transaction, see Outbox Pattern); a read-only report under LevelRepeatableRead, ReadOnly: true so all its queries see one snapshot.
| Option | database/sql | pgx native | PostgreSQL statement |
|---|---|---|---|
| Default level | nil or LevelDefault | pgx.TxOptions{} | BEGIN (server default, usually Read Committed) |
| Repeatable Read | LevelRepeatableRead | pgx.RepeatableRead | BEGIN ISOLATION LEVEL REPEATABLE READ |
| Serializable | LevelSerializable | pgx.Serializable | BEGIN ISOLATION LEVEL SERIALIZABLE |
| Read only | ReadOnly: true | AccessMode: pgx.ReadOnly | READ ONLY |
| Deferrable | not available | DeferrableMode: pgx.Deferrable | DEFERRABLE (serializable read-only) |
| Savepoint | tx.ExecContext("SAVEPOINT s1") | tx.Begin(ctx) | SAVEPOINT |
| MySQL InnoDB | TxOptions.Isolation | n/a | SET TRANSACTION ISOLATION LEVEL ...; its default level is covered in Isolation Levels |
Fix / how to use it: wrap the pattern once in a helper and use it everywhere. txn.WithTx begins, defers the rollback, runs your function and commits; the tests check the call sequence for commit, error and panic, and that LevelSerializable reaches the driver.
// Package txn wraps database/sql transactions: one helper with the
// defer-Rollback pattern, and one that retries the whole transaction on
// SQLSTATE 40001 (serialization failure) and 40P01 (deadlock).
package txn
import (
"context"
"database/sql"
"errors"
"fmt"
"math/rand/v2"
"time"
"github.com/jackc/pgx/v5/pgconn"
)
// WithTx runs fn inside one transaction: Commit when fn returns nil,
// Rollback on an error or a panic.
func WithTx(ctx context.Context, db *sql.DB, opts *sql.TxOptions, fn func(*sql.Tx) error) error {
tx, err := db.BeginTx(ctx, opts)
if err != nil {
return fmt.Errorf("begin: %w", err)
}
// Runs on every exit, including a panic in fn; after Commit it returns
// sql.ErrTxDone without talking to the server.
defer func() { _ = tx.Rollback() }()
if err := fn(tx); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit: %w", err)
}
return nil
}
// Retryable reports whether the whole transaction may be run again.
func Retryable(err error) bool {
var pg *pgconn.PgError
return errors.As(err, &pg) && (pg.Code == "40001" || pg.Code == "40P01")
}
// Serializable is the option set for transactions that rely on SSI.
var Serializable = &sql.TxOptions{Isolation: sql.LevelSerializable}
// WithRetry runs WithTx up to attempts times while the error is retryable,
// sleeping with jittered exponential backoff, and stops when ctx is done.
// fn must be safe to run more than once: no side effects outside the transaction.
func WithRetry(ctx context.Context, db *sql.DB, opts *sql.TxOptions, attempts int,
fn func(*sql.Tx) error) error {
var err error
for i := range attempts {
if err = WithTx(ctx, db, opts, fn); err == nil || !Retryable(err) {
return err
}
backoff := time.Duration(1<<i) * 10 * time.Millisecond
backoff += rand.N(backoff) // full jitter on top of the base
t := time.NewTimer(backoff)
select {
case <-ctx.Done():
t.Stop()
return errors.Join(err, ctx.Err())
case <-t.C:
}
}
return fmt.Errorf("after %d attempts: %w", attempts, err)
}Retrying a transaction: retries on serialization failure 40001 Important
In plain words: under Repeatable Read and Serializable, PostgreSQL may abort your transaction instead of letting it see an inconsistent world. That is not a bug; it is the contract. Run the whole transaction again from the start, a bounded number of times.
Common misunderstanding: "Retry the statement that failed." The PostgreSQL docs: the application "should abort the current transaction and retry the whole transaction from the beginning". Retrying one statement inside an aborted transaction gives 25P02 in_failed_sql_transaction. And "retry everything that fails" is wrong too: a unique violation (23505) on a key the client supplied fails the same way on every attempt. The exception is a key derived inside the transaction: the PostgreSQL docs note that under Serializable "it is possible to see unique constraint violations caused by conflicts with overlapping Serializable transactions even after explicitly checking that the key isn't present" (for example a key computed from the current maximum); a full retry reads again and may pick a free key.
Definition: SQLSTATE 40001 serialization_failure ("could not serialize access due to concurrent update" under Repeatable Read, "due to read/write dependencies among transactions" under Serializable) and 40P01 deadlock_detected are the retryable class 40 codes. "Applications using this level must be prepared to retry transactions due to serialization failures." The retry function must be safe to run twice: no emails, no HTTP calls, no channel sends inside it.
T1 (Serializable) T2 (Serializable)
1 BEGIN; SELECT sum(...) WHERE doctor=7 BEGIN; SELECT sum(...) WHERE doctor=7
2 UPDATE ... SET on_call=false (Alice) UPDATE ... SET on_call=false (Bob)
3 COMMIT -> ok
4 COMMIT -> ERROR 40001 (read/write dependencies)
5 WithRetry: backoff 10-20 ms, run fn again
6 BEGIN; SELECT sees Alice off -> refuses -> COMMIT okReal scenario: on-call scheduling (write skew), seat booking, balance checks under Serializable; a migration-era deadlock between two batch jobs updating rows in different orders (40P01, retry plus consistent ordering, see Deadlocks); CockroachDB, whose docs say "By default, CockroachDB executes all transactions at SERIALIZABLE isolation" and describe 40001 "restart transaction" errors that clients retry.
| Error | SQLSTATE | Retry the transaction? | Why |
|---|---|---|---|
| Serialization failure | 40001 | Yes, with backoff | The contract of RR/Serializable |
| Deadlock detected | 40P01 | Yes, and fix lock order | One victim was chosen |
| Unique violation, key from the client | 23505 | No | Same input, same result |
| Unique violation, key derived in the tx (Serializable) | 23505 | Yes, a bounded full retry | Overlapping Serializable transactions; the retry reads again |
| Lock not available | 55P03 | Maybe, after backoff | lock_timeout or NOWAIT |
| Query canceled | 57014 | Only if the overall budget remains | statement_timeout or a cancel |
| Connection failure | 08006 | Only if the commit outcome is known | A lost COMMIT may have succeeded |
context.Canceled | n/a | No | The caller left |
Fix / how to use it: txn.WithRetry retries only Retryable(err) (40001, 40P01) with jittered exponential backoff and stops when ctx ends. The test fails the first two commits with a hand-built 40001 and asserts the function ran three times; a 23505 runs once. A second test cancels the BeginTx context and polls until database/sql issues the rollback from its background goroutine.
package txn
import (
"context"
"database/sql"
"errors"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
"academy/database-sql-pgx/internal/fakedb"
"github.com/jackc/pgx/v5/pgconn"
)
func TestCommitAndRollback(t *testing.T) {
fake := fakedb.New(nil)
db := fake.Open()
if err := WithTx(t.Context(), db, nil, func(tx *sql.Tx) error {
_, err := tx.ExecContext(t.Context(), "INSERT INTO t VALUES (1)")
return err
}); err != nil {
t.Fatal(err)
}
boom := errors.New("boom")
if err := WithTx(t.Context(), db, nil, func(*sql.Tx) error { return boom }); !errors.Is(err, boom) {
t.Fatal(err)
}
want := []string{"connect", "begin", "exec", "commit", "begin", "rollback"}
if got := fake.Kinds(); !slices.Equal(got, want) {
t.Fatalf("got %v", got)
}
}
func TestRollbackOnPanic(t *testing.T) {
fake := fakedb.New(nil)
func() {
defer func() { _ = recover() }()
_ = WithTx(t.Context(), fake.Open(), nil, func(*sql.Tx) error { panic("bug") })
}()
if fake.Count("rollback") != 1 {
t.Fatalf("calls %v", fake.Kinds())
}
}
func TestIsolationLevelReachesDriver(t *testing.T) {
fake := fakedb.New(nil)
_ = WithTx(t.Context(), fake.Open(), Serializable, func(*sql.Tx) error { return nil })
if q := fake.Calls()[1].Query; !strings.Contains(q, "isolation=Serializable") {
t.Fatal(q)
}
}
func TestRetryOnSerializationFailure(t *testing.T) {
var commits atomic.Int32
fake := fakedb.New(func(kind, q string, _ []any) fakedb.Response {
if kind == "commit" && commits.Add(1) < 3 { // fail the first two commits
return fakedb.Response{Err: &pgconn.PgError{Code: "40001",
Message: "could not serialize access due to read/write dependencies among transactions"}}
}
return fakedb.Response{}
})
var runs int
err := WithRetry(t.Context(), fake.Open(), Serializable, 5, func(*sql.Tx) error { runs++; return nil })
if err != nil || runs != 3 {
t.Fatalf("err=%v runs=%d", err, runs)
}
}
func TestNoRetryOnUniqueViolation(t *testing.T) {
fake := fakedb.New(nil)
var runs int
err := WithRetry(t.Context(), fake.Open(), nil, 5, func(*sql.Tx) error {
runs++
return &pgconn.PgError{Code: "23505"}
})
if err == nil || runs != 1 {
t.Fatalf("err=%v runs=%d", err, runs)
}
}
// database/sql rolls back by itself when the BeginTx context ends; it happens
// in a background goroutine, so the test polls.
func TestContextCancelRollsBack(t *testing.T) {
fake := fakedb.New(nil)
db := fake.Open()
ctx, cancel := context.WithCancel(t.Context())
tx, err := db.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
cancel()
deadline := time.Now().Add(time.Second)
for fake.Count("rollback") == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if fake.Count("rollback") != 1 {
t.Fatalf("calls %v", fake.Kinds())
}
if err := tx.Commit(); err == nil {
t.Fatal("Commit after cancel must fail")
}
}Cancellation: context cancellation behaviour, pgx cancel request Important
In plain words: pass the request's ctx to every query. When it ends, database/sql stops waiting, closes the rows and rolls back the transaction, and the driver decides what happens on the server: pgx by default breaks the connection, or (configured) asks PostgreSQL to cancel the statement.
Common misunderstanding: "When my ctx expires the query stops on the server." Only if the driver sends a cancel. With pgx v5 defaults the context watcher "handles canceled contexts by setting a deadline on a net.Conn", which makes the Go call return and closes that connection; the server notices the closed socket later. CancelRequestContextWatcherHandler "handles canceled contexts by sending a cancel request to the server". Details and a lab are in context.
Definition: the Go 1.8 notes: the Context methods ensure "connections are closed and returned to the connection pool when the request is done; enables canceling in-progress queries should the driver support that; and allows the database pool to cancel waiting for the next available connection." A cancel request is a separate connection that sends the backend PID and secret key; PostgreSQL answers with ERROR: canceling statement due to user request (SQLSTATE 57014) in the original session.
t=0 handler ctx (300 ms budget) -> db.QueryContext(ctx, slowReport)
t=300 ctx.Done()
database/sql: closes the Rows / rolls back the Tx, stops waiting
pgx default: net.Conn deadline -> read fails -> "timeout: context deadline exceeded"; conn discarded
pgx CancelRequest handler: new TCP conn -> CancelRequest(pid, key) -> server: 57014; conn reusable
lib/pq: sends a cancel request and marks the connection bad
t=300+ server-side: statement_timeout is still the backstop if neither reached itReal scenario: a dashboard tab closed during a 20 s report; a gateway timeout of 5 s in front of a 30 s query; a shutdown that cancels the root context and must not leave half-done transactions (they roll back).
| Driver | On ctx cancel | Connection afterwards |
|---|---|---|
pgx v5 default (DeadlineContextWatcherHandler) | Socket deadline | Closed |
pgx v5 with CancelRequestContextWatcherHandler | CancelRequest to the server | Kept if the cancel lands |
| lib/pq | Cancel request (sendCancelRequest in watchCancel) | Marked bad ("so it does not get reused") |
| go-sql-driver/mysql | Closes the connection (no KILL QUERY) | Closed |
| Any driver, waiting for a pool slot | database/sql stops waiting | n/a |
Fix / how to use it: always QueryContext, keep statement_timeout as a server backstop (Timeouts), and configure the cancel-request handler through pgconn.Config.BuildContextWatcherHandler when long statements are common.
Native pgx: pgx v5 native API, pgx.Conn, pgxpool.Pool Must-know
In plain words: pgx can be used without database/sql. pgx.Conn is one connection (not safe for concurrent use); pgxpool.Pool is the concurrency-safe pool you share. The methods look like database/sql but take ctx everywhere and expose PostgreSQL features.
Common misunderstanding: "pgx.Connect gives me a pool." The doc: "*pgx.Conn represents a single connection to the database and is not concurrency safe. Use package github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool." Sharing one *pgx.Conn between goroutines fails with "conn busy".
Definition: pgxpool.New(ctx, dsn) / NewWithConfig(ctx, cfg); pool.Query, QueryRow, Exec, Begin/BeginTx, SendBatch, CopyFrom, Acquire (pin one *pgxpool.Conn, Release when done), Ping, Stat, Close. *pgxpool.Pool, *pgx.Conn and pgx.Tx share these method sets, so an interface over them (like the Querier below) lets a repository run on any of the three. pgconn underneath is "a lower level PostgreSQL driver roughly at the level of libpq".
1 pool, _ := pgxpool.New(ctx, dsn) no connection yet
2 rows, _ := pool.Query(ctx, q, args...) Acquire -> conn#1 (dial) -> query
3 pgx.CollectRows(rows, ...) reads all, closes rows -> conn#1 released
4 tx, _ := pool.Begin(ctx) conn#1 acquired for the whole tx
5 tx.Commit(ctx) releasedReal scenario: a PostgreSQL-only service that wants COPY imports and LISTEN cache invalidation; sqlc generating code for pgx/v5 with pgtype types; a mixed codebase where goose needs *sql.DB, served by stdlib.OpenDBFromPool(pool) from the same pool.
| Feature | database/sql + pgx stdlib | pgx native |
|---|---|---|
| Pool | *sql.DB | *pgxpool.Pool |
| Collect into structs | Manual Scan (or sqlx/scany) | CollectRows + RowToStructByName |
| Named args | No | pgx.NamedArgs, pgx.StrictNamedArgs |
| Batch | No | SendBatch |
| COPY | Only via Raw | CopyFrom |
| LISTEN/NOTIFY | Only via Raw | WaitForNotification |
| Arrays, ranges, jsonb | Via pgtype.Map.SQLScanner; direct on Go 1.27 with pgx ≥ 5.11 | Native |
| Tracing hook | Wrapper drivers (otelsql) | ConnConfig.Tracer |
Fix / how to use it: in a new PostgreSQL-only service, use pgxpool directly and expose *sql.DB only where a library demands it.
package pgxnative
import (
"context"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// Querier is satisfied by *pgxpool.Pool, *pgx.Conn and pgx.Tx.
type Querier interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
CopyFrom(ctx context.Context, table pgx.Identifier, cols []string, src pgx.CopyFromSource) (int64, error)
}
// Order maps columns by name; the db tag overrides the field name.
type Order struct {
ID int64 `db:"id"`
CustomerID int64 `db:"customer_id"`
Status string `db:"status"`
TotalCents int64 `db:"total_cents"`
ShippedAt *time.Time `db:"shipped_at"` // NULL -> nil
}
// OpenOrders uses named arguments and collects rows straight into structs.
// CollectRows closes rows and returns rows.Err() for you.
func OpenOrders(ctx context.Context, q Querier, customerID int64) ([]Order, error) {
rows, err := q.Query(ctx, `
SELECT id, customer_id, status, total_cents, shipped_at
FROM orders WHERE customer_id = @customer AND status = @status ORDER BY id`,
pgx.NamedArgs{"customer": customerID, "status": "open"})
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByName[Order])
}
// MarkShipped updates a set of rows with one array parameter.
func MarkShipped(ctx context.Context, q Querier, ids []int64) (int64, error) {
tag, err := q.Exec(ctx,
`UPDATE orders SET status = 'shipped', shipped_at = now() WHERE id = ANY($1)`, ids)
return tag.RowsAffected(), err
}
// CountByStatus sends N small queries in one network round trip.
func CountByStatus(ctx context.Context, q Querier, statuses []string) (map[string]int64, error) {
b := &pgx.Batch{}
out := make(map[string]int64, len(statuses))
for _, s := range statuses {
b.Queue(`SELECT count(*) FROM orders WHERE status = $1`, s).QueryRow(func(r pgx.Row) error {
var n int64
err := r.Scan(&n)
out[s] = n
return err
})
}
// Close reads every result and returns the first error.
return out, q.SendBatch(ctx, b).Close()
}
// NewOrder is one row of an import.
type NewOrder struct {
CustomerID int64
Email string
TotalCents int64
}
// ImportColumns are the columns Import copies. COPY fills omitted columns with
// their defaults, so every NOT NULL column without a default in schema.sql must
// be listed here (schema_test.go checks it).
var ImportColumns = []string{"customer_id", "email", "total_cents"}
// Import loads many rows with the COPY protocol: one statement, streamed.
func Import(ctx context.Context, q Querier, orders []NewOrder) (int64, error) {
return q.CopyFrom(ctx, pgx.Identifier{"orders"}, ImportColumns,
pgx.CopyFromSlice(len(orders), func(i int) ([]any, error) {
return []any{orders[i].CustomerID, orders[i].Email, orders[i].TotalCents}, nil
}))
}Collecting rows: CollectRows, RowToStructByName, named args Important
In plain words: instead of writing the Next/Scan/Err/Close loop, hand the rows and a mapping function to pgx.CollectRows; pgx.RowToStructByName[T] matches columns to struct fields by name (or db tag). Named arguments (@customer) make long queries readable.
Common misunderstanding: "RowToStructByName ignores extra or missing columns." It requires "the same number of named public fields as row has fields"; a missing column is an error (cannot find field customer_id in returned row, real output in the test). Use RowToStructByNameLax when the struct has extra fields, and db:"-" to ignore one.
Definition: CollectRows[T](rows, fn RowToFunc[T]) ([]T, error) iterates, calls fn per row, closes the rows and returns rows.Err(); it returns an empty slice when there are no rows. CollectOneRow returns ErrNoRows when empty; CollectExactlyOneRow also ErrTooManyRows. ForEachRow runs a callback. Matching is case-insensitive, with snake_case support. NamedArgs "will replace every '@' named placeholder with a '$' ordinal placeholder"; names must start with a letter or underscore; StrictNamedArgs also checks that every name is provided and none is extra. Text inside quotes is left alone.
SQL in: ... WHERE customer_id = @customer AND status = @status AND note <> '@x'
args: pgx.NamedArgs{"customer": 7, "status": "open"}
SQL out: ... WHERE customer_id = $1 AND status = $2 AND note <> '@x' args [7 "open"]
rows -> CollectRows(rows, RowToStructByName[Order]) -> []Order{...}, rows closedReal scenario: list endpoints with 10+ columns where positional Scan broke every time a column was added; a reporting query with the same parameter used three times (@from once in the map); a struct with a computed field tagged db:"-".
| Function | Rows expected | Mapping | Error when |
|---|---|---|---|
CollectRows(rows, RowTo[int32]) | 0..n | Single column | Scan error |
CollectRows(rows, RowToStructByName[T]) | 0..n | By name / db tag | Missing column or field |
CollectRows(rows, RowToStructByNameLax[T]) | 0..n | By name, struct may have more | Unknown column |
CollectRows(rows, RowToStructByPos[T]) | 0..n | By position | Count mismatch |
CollectOneRow | first row | any | ErrNoRows |
CollectExactlyOneRow | exactly 1 | any | ErrNoRows, ErrTooManyRows |
Fix / how to use it: OpenOrders above uses NamedArgs and RowToStructByName. The test feeds a minimal fake pgx.Rows into the real CollectRows, checks NULL → nil pointer mapping, and checks the missing-column error; another test runs NamedArgs.RewriteQuery directly.
package pgxnative
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// fakeRows is a minimal pgx.Rows so CollectRows/RowToStructByName run for real.
type fakeRows struct {
cols []string
data [][]any
i int
}
func (r *fakeRows) Close() {}
func (r *fakeRows) Err() error { return nil }
func (r *fakeRows) CommandTag() pgconn.CommandTag { return pgconn.NewCommandTag("SELECT 2") }
func (r *fakeRows) FieldDescriptions() []pgconn.FieldDescription {
fd := make([]pgconn.FieldDescription, len(r.cols))
for i, c := range r.cols {
fd[i].Name = c
}
return fd
}
func (r *fakeRows) Next() bool { r.i++; return r.i <= len(r.data) }
func (r *fakeRows) Values() ([]any, error) { return r.data[r.i-1], nil }
func (r *fakeRows) RawValues() [][]byte { return nil }
func (r *fakeRows) Conn() *pgx.Conn { return nil }
func (r *fakeRows) Scan(dest ...any) error {
for i, d := range dest {
v := r.data[r.i-1][i]
dv := reflect.ValueOf(d).Elem()
if v == nil {
dv.SetZero()
continue
}
if dv.Kind() == reflect.Pointer {
p := reflect.New(dv.Type().Elem())
p.Elem().Set(reflect.ValueOf(v))
dv.Set(p)
continue
}
dv.Set(reflect.ValueOf(v))
}
return nil
}
type fakeQ struct {
Querier // unimplemented methods panic if called
sql string
args []any
rows *fakeRows
}
func (f *fakeQ) Query(_ context.Context, sql string, args ...any) (pgx.Rows, error) {
f.sql, f.args = sql, args
return f.rows, nil
}
func TestCollectRowsByName(t *testing.T) {
shipped := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
q := &fakeQ{rows: &fakeRows{
cols: []string{"id", "customer_id", "status", "total_cents", "shipped_at"},
data: [][]any{{int64(1), int64(7), "open", int64(900), nil}, {int64(2), int64(7), "open", int64(50), shipped}},
}}
got, err := OpenOrders(t.Context(), q, 7)
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0].ShippedAt != nil || !got[1].ShippedAt.Equal(shipped) || got[1].TotalCents != 50 {
t.Fatalf("%+v", got)
}
if _, ok := q.args[0].(pgx.NamedArgs); !ok {
t.Fatal("named args should be the first argument")
}
}
func TestRowToStructByNameRejectsMissingColumn(t *testing.T) {
q := &fakeQ{rows: &fakeRows{cols: []string{"id", "status"}, data: [][]any{{int64(1), "open"}}}}
_, err := OpenOrders(t.Context(), q, 7)
if err == nil {
t.Fatal("struct fields without a column must be an error")
}
t.Log(err)
var pg *pgconn.PgError
if errors.As(err, &pg) {
t.Fatal("this is a client-side mapping error, not a server error")
}
}Batches and bulk: batch, CopyFrom, COPY, unnest, bulk insert Important
In plain words: many small statements cost many network round trips. Send them together (pgx.Batch), load rows through the COPY protocol (CopyFrom), or pass arrays and let PostgreSQL expand them (unnest, = ANY($1)).
Common misunderstanding: "A batch is just N independent statements sent together." pgx's SendBatch doc: "All queries are run in an implicit transaction unless explicit transaction control statements are executed", so one failing statement undoes the others; and "Depending on the QueryExecMode, all queries may be prepared before any are executed", so creating a table and using it in the same batch can fail. (pgx 5.12+ adds Batch.BeginTx to start a real transaction as the first query of a batch.) Another: "multi-row VALUES scales forever." The Bind message counts parameters in an Int16, so one statement takes at most 65535 parameters (pgconn rejects more with extended protocol limited to %v parameters, %v being math.MaxUint16).
Definition: Batch.Queue(sql, args...) returns a QueuedQuery whose Query, QueryRow or Exec callbacks run when results arrive; SendBatch returns BatchResults, whose Close reads everything and returns the first error. CopyFrom(ctx, pgx.Identifier{"t"}, cols, src) uses COPY FROM STDIN in binary format; sources are CopyFromRows, CopyFromSlice, CopyFromFunc. The doc: "CopyFrom can be faster than an insert with as few as 5 rows." PostgreSQL's populate guide: "Use COPY to load all the rows in one command, instead of using a series of INSERT commands."
1000 order lines to insert
A) loop of ExecContext INSERT 1000 statements, 1000 round trips (or 1000 Bind/Execute in a tx)
B) multi-row VALUES ($1,$2,$3),... 1 statement per 21845 rows (3 cols x 21845 = 65535 params)
C) INSERT ... SELECT * FROM unnest($1::bigint[], $2::text[], $3::bigint[]) 1 statement, 3 params, any size
D) CopyFrom 1 COPY, streamed, fastest; no ON CONFLICT, no RETURNINGReal scenario: a nightly import of 2 million rows (COPY into a staging table, then INSERT ... ON CONFLICT from it); a dashboard issuing 12 small counts per page view (one batch); a sync job upserting 5,000 rows (unnest with ON CONFLICT DO UPDATE).
| Technique | Round trips | ON CONFLICT / RETURNING | Works through database/sql | Limit |
|---|---|---|---|---|
| Loop of INSERT | n | Yes | Yes | Latency × n |
| Multi-row VALUES | ⌈n·cols/65535⌉ | Yes | Yes | 65535 params, new SQL text per size |
unnest arrays | 1 | Yes | Yes (pgx stdlib passes slices) | Memory for the arrays |
pgx.Batch | 1 | Yes | No | Implicit transaction: all or nothing |
CopyFrom | 1 stream | No (use a staging table) | Only via Raw | Triggers and constraints still apply |
Fix / how to use it: Import and CountByStatus in Native pgx show CopyFrom and a batch. COPY fills omitted columns with their defaults, so the column list must include every NOT NULL column without a default: ImportColumns lists customer_id, email, total_cents, and a test parses the lab schema to check it; the bulk snippet does the database/sql versions and the test checks that 50,000 three-column rows become exactly three statements, the first ending in ($65533, $65534, $65535).
// Package bulk fixes the N+1 query and shows two bulk-insert shapes that work
// through database/sql: = ANY($1) / unnest with array parameters, and chunked
// multi-row VALUES that respect PostgreSQL's 65535-parameter limit.
package bulk
import (
"context"
"database/sql"
"fmt"
"strings"
)
// Line is one order line.
type Line struct {
OrderID int64
SKU string
Qty int64
}
// LinesNPlus1 issues one query per order: 1 + N round trips for a page of N orders.
func LinesNPlus1(ctx context.Context, db *sql.DB, orderIDs []int64) (map[int64][]Line, error) {
out := map[int64][]Line{}
for _, id := range orderIDs {
rows, err := db.QueryContext(ctx, `SELECT order_id, sku, qty FROM order_lines WHERE order_id = $1`, id)
if err != nil {
return nil, err
}
if err := collect(rows, out); err != nil {
return nil, err
}
}
return out, nil
}
// LinesBatched issues one query for the whole page. With pgx's stdlib driver
// a []int64 argument is sent as a PostgreSQL bigint[].
func LinesBatched(ctx context.Context, db *sql.DB, orderIDs []int64) (map[int64][]Line, error) {
rows, err := db.QueryContext(ctx,
`SELECT order_id, sku, qty FROM order_lines WHERE order_id = ANY($1) ORDER BY order_id, sku`, orderIDs)
if err != nil {
return nil, err
}
out := map[int64][]Line{}
return out, collect(rows, out)
}
func collect(rows *sql.Rows, out map[int64][]Line) error {
defer rows.Close()
for rows.Next() {
var l Line
if err := rows.Scan(&l.OrderID, &l.SKU, &l.Qty); err != nil {
return err
}
out[l.OrderID] = append(out[l.OrderID], l)
}
return rows.Err()
}
// InsertUnnest inserts any number of lines with three array parameters: the
// statement text never changes, so it is prepared and cached once.
func InsertUnnest(ctx context.Context, db *sql.DB, lines []Line) (int64, error) {
ids := make([]int64, len(lines))
skus := make([]string, len(lines))
qtys := make([]int64, len(lines))
for i, l := range lines {
ids[i], skus[i], qtys[i] = l.OrderID, l.SKU, l.Qty
}
res, err := db.ExecContext(ctx, `INSERT INTO order_lines (order_id, sku, qty)
SELECT * FROM unnest($1::bigint[], $2::text[], $3::bigint[])`, ids, skus, qtys)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// MaxParams is the Bind message limit: the parameter count is an Int16 (65535).
const MaxParams = 65535
// Chunk is one INSERT statement with its arguments.
type Chunk struct {
SQL string
Args []any
}
// ValuesChunks builds INSERT ... VALUES ($1,$2,$3),($4,...) statements, each
// below MaxParams parameters.
func ValuesChunks(table string, cols []string, rows [][]any) []Chunk {
perChunk := MaxParams / len(cols)
var out []Chunk
for start := 0; start < len(rows); start += perChunk {
end := min(start+perChunk, len(rows))
var b strings.Builder
fmt.Fprintf(&b, "INSERT INTO %s (%s) VALUES ", table, strings.Join(cols, ", "))
args := make([]any, 0, (end-start)*len(cols))
for i, r := range rows[start:end] {
if i > 0 {
b.WriteString(", ")
}
b.WriteByte('(')
for j, v := range r {
if j > 0 {
b.WriteString(", ")
}
args = append(args, v)
fmt.Fprintf(&b, "$%d", len(args))
}
b.WriteByte(')')
}
out = append(out, Chunk{SQL: b.String(), Args: args})
}
return out
}LISTEN/NOTIFY Good to know
In plain words: PostgreSQL can push a small message to every session that ran LISTEN channel. A Go service holds one connection, waits on it, and reacts: invalidate a cache, wake a worker.
Common misunderstanding: "NOTIFY is a message queue." There is no persistence and no replay: a listener that was disconnected misses messages. The payload "must be shorter than 8000 bytes" by default, and "if a NOTIFY is executed inside a transaction, the notify events are not delivered until and unless the transaction is committed."
Definition: pgx: conn.Exec(ctx, "listen channelname") then conn.WaitForNotification(ctx), which "blocks until a notification is received or the context is canceled" and returns *pgconn.Notification{PID, Channel, Payload}. Sending: NOTIFY channel, 'payload' or pg_notify(text, text), which "is much easier to use than the NOTIFY command if you need to work with non-constant channel names and payloads". LISTEN is session state, so it never works through PgBouncer transaction pooling ("LISTEN ... Never" in its feature table).
listener (pool.Acquire, held) writer tx
1 LISTEN orders_changed
2 WaitForNotification(ctx) ... BEGIN; UPDATE orders ...; SELECT pg_notify('orders_changed','42')
3 COMMIT
4 <- Notification{Channel:"orders_changed", Payload:"42"}
5 invalidate cache key order:42; wait againReal scenario: cache invalidation across instances; waking a job worker instead of polling every second (still poll on reconnect to catch missed work); a config-reload signal.
Fix / how to use it: Listen acquires and holds one pool connection, sanitizes the channel name with pgx.Identifier, loops on WaitForNotification, and returns on error so the caller can reconnect and re-read state. Before giving the connection back it runs UNLISTEN * on a fresh context, because "A session's listen registrations are automatically cleared when the session ends" and a pooled session does not end: without it the next borrower would keep receiving this channel. If UNLISTEN fails, the connection is taken out of the pool with Hijack and closed. Two tests drive the loop through a fake connection and assert LISTEN "orders_changed" followed by UNLISTEN *, also when the caller's ctx is already canceled.
package pgxnative
import (
"context"
"errors"
"slices"
"testing"
"github.com/jackc/pgx/v5/pgconn"
)
type fakeListener struct {
sqls []string
notes []*pgconn.Notification
ctxOK []bool // whether the ctx passed to Exec was still alive
}
func (f *fakeListener) Exec(ctx context.Context, sql string, _ ...any) (pgconn.CommandTag, error) {
f.sqls = append(f.sqls, sql)
f.ctxOK = append(f.ctxOK, ctx.Err() == nil)
return pgconn.CommandTag{}, nil
}
func (f *fakeListener) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) {
if len(f.notes) == 0 {
<-ctx.Done()
return nil, ctx.Err()
}
n := f.notes[0]
f.notes = f.notes[1:]
return n, nil
}
// Round 1: the LISTEN registration must not survive into the next user of a pooled connection.
func TestListenUnlistensOnHandlerError(t *testing.T) {
f := &fakeListener{notes: []*pgconn.Notification{{Channel: "orders_changed", Payload: "42"}}}
boom := errors.New("handler failed")
err := listenLoop(t.Context(), f, "orders_changed", func(*pgconn.Notification) error { return boom })
if !errors.Is(err, boom) {
t.Fatal(err)
}
if !slices.Equal(f.sqls, []string{`LISTEN "orders_changed"`, "UNLISTEN *"}) {
t.Fatalf("statements %q", f.sqls)
}
}
func TestListenUnlistensWithFreshContextOnCancel(t *testing.T) {
f := &fakeListener{}
ctx, cancel := context.WithCancel(t.Context())
cancel()
_ = listenLoop(ctx, f, "orders_changed", func(*pgconn.Notification) error { return nil })
if len(f.sqls) != 2 || f.sqls[1] != "UNLISTEN *" || !f.ctxOK[1] {
t.Fatalf("statements %q ctx alive %v", f.sqls, f.ctxOK)
}
}package pgxnative
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
)
// Listen holds one pool connection for the whole subscription: LISTEN is
// session state, so it cannot go through a transaction-mode pooler. On exit the
// registration is removed (UNLISTEN *) or, if that fails, the connection is
// destroyed instead of being returned to the pool.
// Notifications are delivered only after the sending transaction commits.
func Listen(ctx context.Context, pool *pgxpool.Pool, channel string,
handle func(*pgconn.Notification) error) error {
conn, err := pool.Acquire(ctx)
if err != nil {
return err
}
err = listenLoop(ctx, pooled{conn}, channel, handle)
if errors.Is(err, errUnlisten) {
// The session may still be registered: never hand it to another caller.
_ = conn.Hijack().Close(context.WithoutCancel(ctx))
return err
}
conn.Release()
return err
}
var errUnlisten = errors.New("unlisten failed")
type listener interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
WaitForNotification(ctx context.Context) (*pgconn.Notification, error)
}
type pooled struct{ c *pgxpool.Conn }
func (p pooled) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
return p.c.Exec(ctx, sql, args...)
}
func (p pooled) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) {
return p.c.Conn().WaitForNotification(ctx)
}
// listenLoop runs LISTEN, delivers notifications until ctx ends or handle fails,
// and always runs UNLISTEN * on a fresh context: LISTEN registrations live until
// UNLISTEN or the end of the session, and a pooled session outlives this call.
func listenLoop(ctx context.Context, c listener, channel string, handle func(*pgconn.Notification) error) (err error) {
if _, err := c.Exec(ctx, "LISTEN "+pgx.Identifier{channel}.Sanitize()); err != nil {
return fmt.Errorf("listen: %w", err)
}
defer func() {
uctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
if _, uerr := c.Exec(uctx, "UNLISTEN *"); uerr != nil {
err = errors.Join(err, errUnlisten, uerr)
}
}()
for {
n, err := c.WaitForNotification(ctx)
if err != nil {
return err
}
if err := handle(n); err != nil {
return err
}
}
}
// Notify sends a payload (under 8000 bytes by default) after the tx commits.
func Notify(ctx context.Context, tx pgx.Tx, channel, payload string) error {
_, err := tx.Exec(ctx, `SELECT pg_notify($1, $2)`, channel, payload)
return err
}
// AsSQLDB exposes the same pgxpool to libraries that need *sql.DB
// (goose, otelsql-wrapped code, sqlx). Pool limits stay on pgxpool.
func AsSQLDB(pool *pgxpool.Pool) *sql.DB { return stdlib.OpenDBFromPool(pool) }
// WithPgxConn reaches the *pgx.Conn under a database/sql connection, for
// pgx-only features such as CopyFrom.
func WithPgxConn(ctx context.Context, db *sql.DB, fn func(*pgx.Conn) error) error {
c, err := db.Conn(ctx)
if err != nil {
return err
}
defer c.Close()
return c.Raw(func(dc any) error { return fn(dc.(*stdlib.Conn).Conn()) })
}Types: pgtype, custom types, AfterConnect Good to know
In plain words: pgx converts between Go values and PostgreSQL types through pgtype. Common types (ints, text, timestamptz, uuid, jsonb, arrays, numeric, inet) work out of the box; your own enums, domains and composite types are registered once per connection.
Common misunderstanding: "Scanning a numeric into float64 is fine for money." It loses precision; use pgtype.Numeric, a decimal adapter such as pgx-shopspring-decimal, or integer cents.
Definition: "pgx uses the pgtype package to converting Go values to and from PostgreSQL values ... User defined data types such as enums, domains, and composite types may require type registration." conn.LoadType(ctx, "order_status") reads the type from the catalog; conn.TypeMap().RegisterType(t) registers it. Because registration is per connection, it goes in pgxpool.Config.AfterConnect, which "is called after a connection is established, but before it is added to the pool". Through database/sql, pgtype.Map.SQLScanner adapts pgtype values to sql.Scanner.
| PostgreSQL | Go (pgx native) | Through database/sql |
|---|---|---|
text, varchar | string, *string, pgtype.Text | string, sql.NullString |
bigint | int64, pgtype.Int8 | int64, sql.NullInt64 |
numeric | pgtype.Numeric, decimal adapters | string |
timestamptz | time.Time, pgtype.Timestamptz | time.Time |
uuid | [16]byte, pgtype.UUID, uuid adapters | string |
jsonb | any JSON-marshallable value | []byte |
bigint[] | []int64 | pgtype.Map.SQLScanner(&a) |
inet / cidr | netip.Addr / netip.Prefix | string |
| enum | string after LoadType | string |
Fix / how to use it: register custom types in AfterConnect (the pgxpool config snippet does it for the order_status enum), keep money in integer cents or numeric with a decimal type. The type must exist before the pool starts, or every new connection fails in AfterConnect: the lab schema creates it, and a test checks that every name in LoadedTypes has a CREATE TYPE in schema.sql.
pgxpool config: MaxConns, health check, AfterConnect, connection string/DSN Must-know
In plain words: pgxpool reads its settings from the connection string (URL or key=value) and from a pgxpool.Config you can edit before creating the pool. The important ones are the size, how long connections live, how often idle ones are checked, and a hook that prepares each new connection.
Common misunderstanding: "The default pool size is 4." The ParseConfig comment says "pool_max_conns: integer greater than 0 (default 4)", but the field doc and code say "The default is the greater of 4 or runtime.NumCPU()"; on the 12-core build machine the test printed 12. Inside a container with a CPU quota that may still be the host's core count, so set it explicitly.
Definition: DSN forms: postgres://user:pass@host:5432/db?sslmode=verify-full&pool_max_conns=20 or host=db user=app dbname=orders pool_max_conns=20. Standard libpq parameters (sslmode, connect_timeout, application_name, target_session_attrs, options) are understood by pgconn; pgx adds default_query_exec_mode, statement_cache_capacity, description_cache_capacity; pgxpool adds the pool keys below. Any other unknown key is sent to the server as a run-time parameter, which is how statement_timeout=5s in RuntimeParams becomes a session default.
| Setting | DSN key | Default | Meaning |
|---|---|---|---|
MaxConns | pool_max_conns | max(4, NumCPU) | Hard cap |
MinConns | pool_min_conns | 0 | Floor kept open |
MinIdleConns | pool_min_idle_conns | 0 | Idle floor ("superior to MinConns" for tail latency) |
MaxConnLifetime | pool_max_conn_lifetime | 1 h | Close after this age |
MaxConnLifetimeJitter | pool_max_conn_lifetime_jitter | 0 | Spread closes so they do not all happen at once |
MaxConnIdleTime | pool_max_conn_idle_time | 30 min | Close idle connections (by the health check) |
HealthCheckPeriod | pool_health_check_period | 1 min | Background check of idle connections |
PingTimeout | pool_ping_timeout (5.11+) | 0 = none | Ping limit when a connection is acquired |
ShouldPing | code only | ping if idle > 1 s | Liveness check on acquire |
AfterConnect | code only | nil | Per-connection setup: types, SET |
PrepareConn / AfterRelease / BeforeClose | code only | nil | Acquire/release hooks (BeforeAcquire is deprecated) |
ConnConfig.ConnectTimeout | connect_timeout | none | Dial + startup limit |
ConnConfig.Tracer | code only | nil | Query tracing (Observability) |
1 cfg, _ := pgxpool.ParseConfig(os.Getenv("DATABASE_URL")) DSN keys parsed, unknown keys -> RuntimeParams
2 cfg.MaxConns = 20; cfg.AfterConnect = registerTypes code overrides
3 pool, _ := pgxpool.NewWithConfig(ctx, cfg) returns at once, starts health check goroutine
4 first Acquire -> dial -> startup(params incl. statement_timeout) -> AfterConnect -> in pool
5 every HealthCheckPeriod: close idle > MaxConnIdleTime, age > MaxConnLifetime(+jitter), refill MinConnsReal scenario: a pod with 2 vCPU on a 64-core node getting a 64-connection pool by default; MinIdleConns: 2 removing the dial from the first request after a quiet night; MaxConnLifetimeJitter preventing all 50 connections from reconnecting in the same second after a deploy; AfterConnect registering an enum so RowToStructByName can scan it.
Fix / how to use it: parse the DSN, then set every pool field in code so the values are reviewed in one place; NewPool pings once so startup fails fast.
// Package pgxnative uses pgx v5's own API: pgxpool configuration, typed row
// collection, named arguments, batches, COPY, LISTEN/NOTIFY and the bridge to
// database/sql. Only the parts that need no server are tested here.
package pgxnative
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// LoadedTypes are the PostgreSQL types AfterConnect registers on every connection.
// They must exist before the pool starts: schema.sql creates them (schema_test.go checks it),
// and a missing type makes every new connection fail.
var LoadedTypes = []string{"order_status"}
// PoolConfig parses a DSN (URL or key=value) and applies production defaults.
// Settings given in the DSN, such as pool_max_conns, are parsed first; the
// fields set here override them, so keep one source of truth per knob.
func PoolConfig(dsn string) (*pgxpool.Config, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("parse dsn: %w", err)
}
cfg.MaxConns = 20 // default: max(4, runtime.NumCPU())
cfg.MinIdleConns = 2 // warm connections for tail latency
cfg.MaxConnLifetime = 30 * time.Minute // default 1h
cfg.MaxConnLifetimeJitter = time.Minute // spread reconnects
cfg.MaxConnIdleTime = 5 * time.Minute // default 30m
cfg.HealthCheckPeriod = 30 * time.Second // default 1m
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
// Server-side backstops, sent as startup parameters on every new connection.
rp := cfg.ConnConfig.RuntimeParams
rp["application_name"] = "orders-api"
rp["statement_timeout"] = "5s"
rp["lock_timeout"] = "2s"
rp["idle_in_transaction_session_timeout"] = "30s"
// AfterConnect runs once per new physical connection, before it joins the pool.
cfg.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
t, err := c.LoadType(ctx, LoadedTypes[0]) // the order_status enum from schema.sql
if err != nil {
return fmt.Errorf("load type %s (run the migrations first): %w", LoadedTypes[0], err)
}
c.TypeMap().RegisterType(t)
return nil
}
return cfg, nil
}
// ForTransactionPooler switches off named prepared statements for a pooler
// in transaction mode that cannot track them (PgBouncer before 1.21, or with
// max_prepared_statements = 0). QueryExecModeExec still sends parameters
// separately (no client-side interpolation) but cannot infer some types,
// for example a map[string]string has to be passed as json text.
// PgBouncer also rejects startup parameters it does not track unless they are
// listed in ignore_startup_parameters, so the timeouts move to ALTER ROLE ... SET.
func ForTransactionPooler(cfg *pgxpool.Config) {
cfg.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeExec
for _, k := range []string{"statement_timeout", "lock_timeout", "idle_in_transaction_session_timeout"} {
delete(cfg.ConnConfig.RuntimeParams, k)
}
cfg.AfterConnect = nil // keep connection setup out of the pooled session
}
// NewPool builds the pool and checks it once: pgxpool.New does not connect.
func NewPool(ctx context.Context, cfg *pgxpool.Config) (*pgxpool.Pool, error) {
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping: %w", err)
}
return pool, nil
}package pgxnative
import (
"context"
"runtime"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Port 1 on loopback refuses connections: nothing here needs PostgreSQL.
const dsn = "postgres://app:secret@127.0.0.1:1/orders?sslmode=disable"
func TestDSNParameters(t *testing.T) {
cfg, err := pgxpool.ParseConfig(dsn +
"&pool_max_conns=10&pool_max_conn_idle_time=2m&default_query_exec_mode=exec&statement_cache_capacity=128")
if err != nil {
t.Fatal(err)
}
if cfg.MaxConns != 10 || cfg.MaxConnIdleTime != 2*time.Minute ||
cfg.ConnConfig.DefaultQueryExecMode != pgx.QueryExecModeExec ||
cfg.ConnConfig.StatementCacheCapacity != 128 {
t.Fatalf("parsed %+v", cfg)
}
}
func TestDefaults(t *testing.T) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
t.Fatal(err)
}
want := int32(max(4, runtime.NumCPU()))
if cfg.MaxConns != want || cfg.MaxConnLifetime != time.Hour ||
cfg.MaxConnIdleTime != 30*time.Minute || cfg.HealthCheckPeriod != time.Minute ||
cfg.ConnConfig.DefaultQueryExecMode != pgx.QueryExecModeCacheStatement ||
cfg.ConnConfig.StatementCacheCapacity != 512 {
t.Fatalf("defaults %+v", cfg)
}
t.Logf("MaxConns default on this machine: %d", cfg.MaxConns)
}
func TestPoolConfigSetsBackstops(t *testing.T) {
cfg, err := PoolConfig(dsn)
if err != nil {
t.Fatal(err)
}
if cfg.ConnConfig.RuntimeParams["statement_timeout"] != "5s" || cfg.MaxConns != 20 || cfg.AfterConnect == nil {
t.Fatalf("%+v", cfg.ConnConfig.RuntimeParams)
}
ForTransactionPooler(cfg)
if cfg.ConnConfig.DefaultQueryExecMode != pgx.QueryExecModeExec {
t.Fatal("exec mode not set")
}
if _, ok := cfg.ConnConfig.RuntimeParams["statement_timeout"]; ok {
t.Fatal("PgBouncer would reject statement_timeout as a startup parameter")
}
}
func TestPoolIsLazy(t *testing.T) {
cfg, _ := pgxpool.ParseConfig(dsn)
pool, err := pgxpool.NewWithConfig(t.Context(), cfg) // returns without connecting
if err != nil {
t.Fatalf("New should not dial: %v", err)
}
defer pool.Close()
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
if err := pool.Ping(ctx); err == nil {
t.Fatal("Ping must fail: nothing listens on port 1")
} else {
t.Log(err)
}
}
func TestNamedArgsRewrite(t *testing.T) {
sql, args, err := pgx.NamedArgs{"customer": int64(7), "status": "open"}.RewriteQuery(t.Context(), nil,
"SELECT 1 FROM orders WHERE customer_id = @customer AND status = @status AND note <> '@x'", nil)
if err != nil {
t.Fatal(err)
}
if sql != "SELECT 1 FROM orders WHERE customer_id = $1 AND status = $2 AND note <> '@x'" || len(args) != 2 {
t.Fatalf("%q %v", sql, args)
}
}Timeouts: statement_timeout, lock_timeout and friends Must-know
In plain words: your ctx bounds how long Go waits; PostgreSQL's own timeouts bound how long the server works and holds locks, even when the client is gone or the driver did not cancel. Use both.
Common misunderstanding: "My ctx has a 2 s deadline, so no statement runs longer than 2 s." With the default pgx handler the connection is closed, but the backend keeps executing until it next tries to talk to the client. statement_timeout stops it on the server. And lock_timeout matters even with a statement timeout: a migration waiting for a lock blocks every query queued behind it.
Definition (PostgreSQL docs): statement_timeout: "Abort any statement that takes more than the specified amount of time ... A value of zero (the default) disables the timeout." lock_timeout: "Abort any statement that waits longer than the specified amount of time while attempting to acquire a lock". idle_in_transaction_session_timeout: "Terminate any session that has been idle ... within an open transaction for longer than the specified amount of time" (an open transaction also "prevents vacuuming away recently-dead tuples"). transaction_timeout (newer PostgreSQL releases) bounds a whole transaction. idle_session_timeout warns: "Be wary of enforcing this timeout on connections made through connection-pooling software". All take milliseconds without a unit. Set them per role (ALTER ROLE app SET statement_timeout = '5s'), per connection (RuntimeParams / DSN options=-c statement_timeout=5s) or per transaction (SET LOCAL).
1 BEGIN;
2 SET LOCAL lock_timeout = '2s'; SET LOCAL statement_timeout = '30s'; only this transaction
3 ALTER TABLE orders ADD COLUMN note text; waits for ACCESS EXCLUSIVE lock behind a long SELECT
4 ... 2 s later: ERROR: canceling statement due to lock timeout (SQLSTATE 55P03)
5 ROLLBACK; queued application queries resume instead of piling up behind the ALTERReal scenario: a runaway report that ran for an hour after its HTTP client gave up; a deploy where ALTER TABLE waited for a lock and froze the API (fixed with lock_timeout plus retry, see Schema Migrations); a connection leaked inside BEGIN by a bug that held row locks until idle_in_transaction_session_timeout killed it.
| Layer | Knob | Protects against | Error |
|---|---|---|---|
| Go | ctx deadline on each call | Waiting forever (pool or query) | context deadline exceeded |
| pgx dial | connect_timeout / ConnectTimeout | Unreachable host | dial timeout |
| PostgreSQL | statement_timeout | Long statements | 57014 "canceling statement due to statement timeout" |
| PostgreSQL | lock_timeout | Waiting for locks | 55P03 "canceling statement due to lock timeout" |
| PostgreSQL | idle_in_transaction_session_timeout | Leaked open transactions | Session terminated |
| PostgreSQL | transaction_timeout | Whole long transactions | Session terminated |
| PgBouncer | query_timeout, server_idle_timeout | Pooler-level limits | Client disconnected |
Fix / how to use it: a role-level statement_timeout a bit above your longest legitimate API query, SET LOCAL for known long jobs, lock_timeout in every migration, idle_in_transaction_session_timeout always on. PoolConfig sets the first three as run-time parameters.
Errors: error inspection, pgconn.PgError, SQLSTATE Must-know
In plain words: every PostgreSQL error carries a five-character SQLSTATE code and often the constraint, table and column involved. Inspect the code with errors.As into *pgconn.PgError, never the message text, which can be translated or reworded.
Common misunderstanding: "err.Error() contains duplicate key, so I can strings.Contains it." Messages depend on lc_messages and server version; codes are stable and listed in Appendix A. And "type-assert err.(*pgconn.PgError)" fails on wrapped errors; the pgx wiki: "errors.Is() and errors.As() should be used instead of directly testing an error for equality or attempting a type assertion."
Definition: pgconn.PgError has Severity, Code, Message, Detail, Hint, Position, SchemaName, TableName, ColumnName, DataTypeName, ConstraintName, File, Line, Routine; Error() formats as Severity + ": " + Message + " (SQLSTATE " + Code + ")". pgconn.Timeout(err) is true for errors "caused within pgconn by a context.DeadlineExceeded or an implementer of net.Error where Timeout() is true"; pgconn.SafeToRetry(err) is true only when the error happened "before sending any data to the server". github.com/jackc/pgerrcode has the code constants.
1 _, err := pool.Exec(ctx, `INSERT INTO users (email) VALUES ($1)`, "a@example.test")
2 err: fmt.Errorf("signup: %w", *pgconn.PgError{Code:"23505", ConstraintName:"users_email_key"})
3 var pg *pgconn.PgError; errors.As(err, &pg) -> true
4 pg.Code == "23505" && pg.ConstraintName == "users_email_key" -> return ErrEmailTaken -> HTTP 409Real scenario: signup returning 409 "email taken" from the unique constraint instead of a racy pre-check; an FK violation (23503) on order_lines.product_id becoming a 422; alerting on 53300 too_many_connections separately from query errors.
| SQLSTATE | Name | Typical cause | Go reaction |
|---|---|---|---|
| 23505 | unique_violation | Duplicate key | 409, or ON CONFLICT |
| 23503 | foreign_key_violation | Missing parent / child exists | 422 |
| 23502 | not_null_violation | Missing value | Bug or 422 |
| 23514 | check_violation | CHECK (balance >= 0) | 422 / business error |
| 40001 | serialization_failure | RR/Serializable conflict | Retry the tx |
| 40P01 | deadlock_detected | Lock cycle | Retry, fix order |
| 55P03 | lock_not_available | lock_timeout, NOWAIT | Back off |
| 57014 | query_canceled | statement_timeout, cancel request | Timeout handling |
| 25P02 | in_failed_sql_transaction | Statement after an error in a tx | Bug: roll back first |
| 26000 | invalid_sql_statement_name | Prepared statement missing (poolers) | PgBouncer |
| 42P05 | duplicate_prepared_statement | Same name prepared twice on a session | Poolers, manual PREPARE |
| 53300 | too_many_connections | max_connections reached | Smaller pools, a pooler |
| 57P01 | admin_shutdown | Server restart / failover | Reconnect, retry idempotent work |
| 08006 | connection_failure | Network | Retry only if safe |
| 42601 / 42P01 / 42703 | syntax_error / undefined_table / undefined_column | Bad SQL, missing migration | Bug |
Fix / how to use it: one classifier per service, used by repositories (domain errors) and by the transaction helper (retry decisions). The test builds PgError values by hand, so it proves the classifier, not the server.
// Package errs turns driver errors into decisions: not found, conflict,
// retry, timeout. It inspects *pgconn.PgError by SQLSTATE, never by message.
package errs
import (
"context"
"database/sql"
"errors"
"github.com/jackc/pgx/v5/pgconn"
)
// SQLSTATE codes used below (PostgreSQL Appendix A).
const (
UniqueViolation = "23505"
ForeignKeyViolation = "23503"
CheckViolation = "23514"
SerializationFailure = "40001"
DeadlockDetected = "40P01"
QueryCanceled = "57014" // statement_timeout or a cancel request
LockNotAvailable = "55P03" // lock_timeout or NOWAIT
TooManyConnections = "53300"
AdminShutdown = "57P01"
)
// Kind is what the caller should do about an error.
type Kind int
const (
KindNone Kind = iota
KindNotFound // map to 404
KindConflict // unique violation: 409
KindInvalid // FK or CHECK violation: 422
KindRetry // serialization failure or deadlock: retry the whole transaction
KindTimeout // our deadline or statement_timeout/lock_timeout
KindCanceled // the caller went away: log at INFO, do not retry
KindUnavailable // server overloaded or restarting: back off
KindOther
)
// Classify inspects err with errors.Is / errors.As, so wrapping with %w is fine.
func Classify(err error) Kind {
if err == nil {
return KindNone
}
if errors.Is(err, sql.ErrNoRows) { // pgx.ErrNoRows wraps sql.ErrNoRows since pgx v5.7.0
return KindNotFound
}
if errors.Is(err, context.Canceled) {
return KindCanceled
}
if errors.Is(err, context.DeadlineExceeded) || pgconn.Timeout(err) {
return KindTimeout
}
var pg *pgconn.PgError
if errors.As(err, &pg) {
switch pg.Code {
case UniqueViolation:
return KindConflict
case ForeignKeyViolation, CheckViolation:
return KindInvalid
case SerializationFailure, DeadlockDetected:
return KindRetry
case QueryCanceled, LockNotAvailable:
return KindTimeout
case TooManyConnections, AdminShutdown:
return KindUnavailable
}
if len(pg.Code) == 2+3 && pg.Code[:2] == "08" { // class 08: connection exception
return KindUnavailable
}
}
return KindOther
}
// ErrEmailTaken is a domain error derived from a specific constraint name.
var ErrEmailTaken = errors.New("email already registered")
// Domain maps a unique violation on users_email_key to ErrEmailTaken.
func Domain(err error) error {
var pg *pgconn.PgError
if errors.As(err, &pg) && pg.Code == UniqueViolation && pg.ConstraintName == "users_email_key" {
return ErrEmailTaken
}
return err
}package errs
import (
"context"
"database/sql"
"errors"
"fmt"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// These PgErrors are built by hand: the test proves the classifier, not the server.
func pgErr(code string) error {
return fmt.Errorf("insert order: %w", &pgconn.PgError{Severity: "ERROR", Code: code, Message: "test"})
}
func TestClassify(t *testing.T) {
cases := []struct {
name string
err error
want Kind
}{
{"nil", nil, KindNone},
{"sql.ErrNoRows", fmt.Errorf("get: %w", sql.ErrNoRows), KindNotFound},
{"pgx.ErrNoRows", pgx.ErrNoRows, KindNotFound},
{"unique", pgErr("23505"), KindConflict},
{"fk", pgErr("23503"), KindInvalid},
{"serialization", pgErr("40001"), KindRetry},
{"deadlock", pgErr("40P01"), KindRetry},
{"statement_timeout", pgErr("57014"), KindTimeout},
{"lock_timeout", pgErr("55P03"), KindTimeout},
{"too many connections", pgErr("53300"), KindUnavailable},
{"connection failure", pgErr("08006"), KindUnavailable},
{"ctx deadline", fmt.Errorf("query: %w", context.DeadlineExceeded), KindTimeout},
{"ctx canceled", context.Canceled, KindCanceled},
{"syntax", pgErr("42601"), KindOther},
}
for _, c := range cases {
if got := Classify(c.err); got != c.want {
t.Errorf("%s: got %d want %d", c.name, got, c.want)
}
}
}
func TestPgErrorText(t *testing.T) {
e := &pgconn.PgError{Severity: "ERROR", Code: "40001",
Message: "could not serialize access due to concurrent update"}
if got := e.Error(); got != "ERROR: could not serialize access due to concurrent update (SQLSTATE 40001)" {
t.Fatal(got)
}
}
func TestPgxErrNoRowsIsSQLErrNoRows(t *testing.T) {
if !errors.Is(pgx.ErrNoRows, sql.ErrNoRows) {
t.Fatal("pgx.ErrNoRows should wrap sql.ErrNoRows")
}
}
func TestDomainConstraint(t *testing.T) {
err := fmt.Errorf("signup: %w", &pgconn.PgError{Code: "23505", ConstraintName: "users_email_key"})
if !errors.Is(Domain(err), ErrEmailTaken) {
t.Fatal("want ErrEmailTaken")
}
}PgBouncer transaction mode and prepared statements Important
In plain words: PgBouncer in transaction mode gives your client a server connection only for the length of one transaction. Anything that lives in the session (named prepared statements, SET, LISTEN, advisory locks, temp tables) may be gone, or on another server connection, by the next transaction. pgx's default statement cache is exactly such session state.
Common misunderstanding: "PgBouncer does not support prepared statements, full stop." That was true before 1.21. PgBouncer 1.21.0 (2023-10-16, "The one with prepared statements") added "support for protocol-level named prepared statements", enabled when max_prepared_statements is non-zero, and 1.24.0 made 200 the default. pgx's own docs (doc.go: "Prepared statements are incompatible with PgBouncer") predate that and are still the safe reading for older poolers, managed poolers that do not track statements, and SQL-level PREPARE, which PgBouncer forwards untouched.
Definition: PgBouncer modes: session ("This mode supports all PostgreSQL features"), transaction ("A server connection is assigned to a client only during a transaction"; "This mode breaks a few session-based features of PostgreSQL") and statement. With max_prepared_statements > 0, PgBouncer "gives each unique query string an internal name with the format PGBOUNCER_{unique_id}" and "transparently prepares the statement before executing it" on whatever server connection the client lands on; the value is the per-server-connection LRU size. Known limit from its docs: if a statement's result types change (a migration), clients get ERROR: cached plan must not change result type until RECONNECT.
pool_mode=transaction, max_prepared_statements=0, pgx default cache_statement
1 tx1 on server A: Parse stmtcache_9f2c... ; Bind/Execute ok
2 tx2 on server B: Bind stmtcache_9f2c... ERROR: prepared statement "stmtcache_9f2c..." does not exist (26000)
3 or tx3 on server A from another client that cached the same SQL earlier: ERROR 42P05 duplicate_prepared_statementReal scenario: a service moved from direct PostgreSQL to a managed pooler on Friday and failing on Monday's deploy; a hosted PostgreSQL offering both a pooled and a direct endpoint, where the pooled one runs transaction mode; a LISTEN-based cache invalidator that must connect directly, bypassing the pooler.
| Setup | pgx DefaultQueryExecMode | Works? | Notes |
|---|---|---|---|
| Direct to PostgreSQL | cache_statement (default) | Yes | Fastest |
| PgBouncer session mode | cache_statement | Yes | Fewer savings from pooling |
PgBouncer ≥ 1.21, transaction mode, max_prepared_statements > 0 | cache_statement | Yes, per PgBouncer docs | Not in pgx's docs; test it; RECONNECT after type-changing migrations |
| PgBouncer transaction mode, no statement tracking | exec or simple_protocol | Yes | exec keeps parameters separate |
| Any transaction pooler | n/a | LISTEN, SET, session advisory locks: never | Use a direct connection for those |
Fix / how to use it: ForTransactionPooler in the config snippet sets QueryExecModeExec and removes the timeout startup parameters: "By default, PgBouncer allows only parameters it can keep track of in startup packets ... All other parameters will raise an error" (unless listed in ignore_startup_parameters), so set statement_timeout and friends with ALTER ROLE ... SET instead. Keep other connection setup that must persist (SET search_path) in role or database defaults too, not in AfterConnect, because behind a pooler your "connection" is not the server's session.
Repository pattern: interface per aggregate Must-know
In plain words: a repository is the one place that knows SQL for an aggregate (an order with its lines). The rest of the code asks it for domain objects and hands them back to save. Define the interface where it is used, one per aggregate, with domain types in the signatures.
Common misunderstanding: "A repository per table, with generic FindAll/Update methods." That leaks the schema upward and invites partial saves of an aggregate (lines without their order). Another: "the repository should hide transactions completely." It should not decide transaction boundaries; the use case does (next section). The DDD view of repositories is in Repositories.
Definition: an Orders interface with Get(ctx, id) (*Order, error) and Save(ctx, *Order) error; a SQLOrders struct implementing it over a DBTX interface (ExecContext, QueryContext, QueryRowContext), which *sql.DB, *sql.Tx and *sql.Conn all satisfy; driver errors translated to ErrNotFound/ErrConflict; optimistic concurrency with a version column so a concurrent save becomes ErrConflict instead of a lost update.
handler -> Service.Cancel(ctx, 7)
InTx: Orders.Get(ctx,7) SELECT order; SELECT lines (2 queries, not 1+N)
o.Status = cancelled
Orders.Save(ctx,o) UPDATE ... WHERE id=7 AND version=4 -> 0 rows => ErrConflict
Outbox.Append(...) INSERT INTO outbox
COMMITReal scenario: swapping the PostgreSQL implementation for an in-memory fake in service tests (Mocking with Interfaces & DI); a REST handler that maps ErrNotFound to 404 and ErrConflict to 409 (A REST API in Go); an order aggregate whose lines are always replaced together, so no code path saves a line alone.
| Design choice | Recommended | Avoid |
|---|---|---|
| Granularity | One repository per aggregate root | One per table |
| Signatures | Domain types, ctx first | *sql.Rows, map[string]any, sql.NullString |
| Errors | ErrNotFound, ErrConflict | sql.ErrNoRows, raw *pgconn.PgError |
| Where the interface lives | In the consumer package | Next to the implementation "just in case" |
| Concurrency control | version column or SELECT ... FOR UPDATE | Last write wins |
| Queries | Explicit columns, batched child loads | SELECT *, a query per child |
Fix / how to use it: the repository snippet has the domain, the service and the interfaces in one file and the PostgreSQL implementation in another.
// Package repository shows the repository pattern on database/sql: one
// interface per aggregate, a PostgreSQL implementation that works on a pool
// or a transaction, and two ways to share one transaction across
// repositories: a transaction carried in the context, or an explicit unit of work.
package repository
import (
"context"
"errors"
"strconv"
)
// Order is the aggregate root; Lines belong to it and are saved with it.
type Order struct {
ID int64
CustomerID int64
Status string
Lines []Line
Version int // optimistic concurrency
}
// Line is part of the Order aggregate, never loaded or saved on its own.
type Line struct {
SKU string
Qty int
}
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("concurrent update")
)
// Orders is the repository for the Order aggregate: domain types in and out,
// no *sql.Rows, no SQL, no driver errors in the signature.
type Orders interface {
Get(ctx context.Context, id int64) (*Order, error)
Save(ctx context.Context, o *Order) error
}
// Outbox records events in the same transaction as the state change.
type Outbox interface {
Append(ctx context.Context, topic string, payload []byte) error
}
// TxRunner runs fn so that every repository call made with the ctx it
// receives joins one transaction.
type TxRunner interface {
InTx(ctx context.Context, fn func(ctx context.Context) error) error
}
// Service is application logic; it sees only interfaces, so tests use fakes.
type Service struct {
Tx TxRunner
Orders Orders
Outbox Outbox
}
// Cancel changes the status and records an event, atomically.
func (s Service) Cancel(ctx context.Context, id int64) error {
return s.Tx.InTx(ctx, func(ctx context.Context) error {
o, err := s.Orders.Get(ctx, id)
if err != nil {
return err
}
if o.Status == "shipped" {
return errors.New("cannot cancel a shipped order")
}
o.Status = "cancelled"
if err := s.Orders.Save(ctx, o); err != nil {
return err
}
return s.Outbox.Append(ctx, "order.cancelled", []byte(`{"id":`+strconv.FormatInt(o.ID, 10)+`}`))
})
}package repository
import (
"context"
"database/sql"
"errors"
"fmt"
)
// DBTX is satisfied by *sql.DB, *sql.Tx and *sql.Conn (sqlc generates the same idea).
type DBTX interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
type txKey struct{}
// conn returns the transaction carried in ctx, or the fallback (pool or tx).
func conn(ctx context.Context, fallback DBTX) DBTX {
if tx, ok := ctx.Value(txKey{}).(*sql.Tx); ok {
return tx
}
return fallback
}
// TxManager implements TxRunner by putting the *sql.Tx into the context.
type TxManager struct{ DB *sql.DB }
// InTx joins an existing transaction or starts one, with the defer-Rollback pattern.
func (m TxManager) InTx(ctx context.Context, fn func(ctx context.Context) error) error {
if _, ok := ctx.Value(txKey{}).(*sql.Tx); ok {
return fn(ctx) // already inside: join, do not nest
}
tx, err := m.DB.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin: %w", err)
}
defer tx.Rollback()
if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
return err
}
return tx.Commit()
}
// SQLOrders is the PostgreSQL implementation of Orders.
type SQLOrders struct{ db DBTX }
// NewSQLOrders works on a pool (then ctx may carry a tx) or directly on a tx.
func NewSQLOrders(db DBTX) *SQLOrders { return &SQLOrders{db: db} }
// Get loads the root and its lines in two queries (not one per line).
func (r *SQLOrders) Get(ctx context.Context, id int64) (*Order, error) {
q := conn(ctx, r.db)
o := &Order{ID: id}
err := q.QueryRowContext(ctx,
`SELECT customer_id, status, version FROM orders WHERE id = $1`, id,
).Scan(&o.CustomerID, &o.Status, &o.Version)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("load order %d: %w", id, err)
}
rows, err := q.QueryContext(ctx,
`SELECT sku, qty FROM order_lines WHERE order_id = $1 ORDER BY sku`, id)
if err != nil {
return nil, fmt.Errorf("load lines: %w", err)
}
defer rows.Close()
for rows.Next() {
var l Line
if err := rows.Scan(&l.SKU, &l.Qty); err != nil {
return nil, err
}
o.Lines = append(o.Lines, l)
}
return o, rows.Err()
}
// Save writes the whole aggregate; the version check rejects lost updates.
func (r *SQLOrders) Save(ctx context.Context, o *Order) error {
q := conn(ctx, r.db)
res, err := q.ExecContext(ctx,
`UPDATE orders SET status = $1, version = version + 1 WHERE id = $2 AND version = $3`,
o.Status, o.ID, o.Version)
if err != nil {
return fmt.Errorf("save order %d: %w", o.ID, err)
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrConflict
}
o.Version++
if _, err := q.ExecContext(ctx, `DELETE FROM order_lines WHERE order_id = $1`, o.ID); err != nil {
return err
}
for _, l := range o.Lines {
if _, err := q.ExecContext(ctx,
`INSERT INTO order_lines (order_id, sku, qty) VALUES ($1, $2, $3)`, o.ID, l.SKU, l.Qty); err != nil {
return err
}
}
return nil
}
// SQLOutbox appends to an outbox table that a relay publishes from.
type SQLOutbox struct{ db DBTX }
// NewSQLOutbox works like NewSQLOrders.
func NewSQLOutbox(db DBTX) *SQLOutbox { return &SQLOutbox{db: db} }
// Append inserts one event row.
func (o *SQLOutbox) Append(ctx context.Context, topic string, payload []byte) error {
_, err := conn(ctx, o.db).ExecContext(ctx,
`INSERT INTO outbox (topic, payload) VALUES ($1, $2)`, topic, payload)
return err
}
// UnitOfWork is the explicit alternative: fn receives repositories bound to one tx.
type UnitOfWork struct{ DB *sql.DB }
// Repos are the repositories available inside one unit of work.
type Repos struct {
Orders Orders
Outbox Outbox
}
// Do begins a transaction, hands tx-bound repositories to fn, commits on nil.
func (u UnitOfWork) Do(ctx context.Context, fn func(Repos) error) error {
tx, err := u.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if err := fn(Repos{Orders: NewSQLOrders(tx), Outbox: NewSQLOutbox(tx)}); err != nil {
return err
}
return tx.Commit()
}Sharing a transaction: tx propagation via context or UnitOfWork Important
In plain words: a use case often touches two repositories (orders and outbox) that must commit together. Either carry the *sql.Tx in the context so every repository picks it up, or pass repositories already bound to the transaction (a unit of work).
Common misunderstanding: "Each repository method should begin its own transaction." Then Save and Append commit separately and a crash between them loses the event. The opposite trap: "store the transaction in the repository struct." Repositories are shared across goroutines; a tx field would mix requests.
Definition: context propagation: TxManager.InTx begins a tx, stores it under an unexported key, and repositories call conn(ctx, fallback) to use it; nested InTx calls join instead of nesting. Unit of work: UnitOfWork.Do(ctx, func(Repos) error) builds NewSQLOrders(tx) and NewSQLOutbox(tx) for the duration of the call. sqlc's generated code takes the second route: its docs show "the WithTx method allows a Queries instance to be associated with a transaction". The context approach is implicit (a function called outside InTx silently runs without a transaction); the unit of work is explicit but changes signatures.
TxManager.InTx(ctx, fn) BEGIN on conn#1; ctx' = ctx + tx
Orders.Get(ctx') conn(ctx') = tx -> conn#1
Orders.Save(ctx') tx -> conn#1
Outbox.Append(ctx') tx -> conn#1
COMMIT on conn#1 all-or-nothing; the test asserts every call ran on conn#1Real scenario: order + outbox row in one commit, relayed later (Outbox Pattern); a service method called both standalone and from a larger use case (context join); a batch job that wants explicit control (unit of work).
| Approach | How the tx travels | Pros | Cons |
|---|---|---|---|
| Tx in context | context.WithValue(ctx, txKey{}, tx) | No signature changes; nested calls join | Implicit; easy to call without a tx |
| Unit of work | Do(ctx, func(Repos) error) | Explicit; compile-time clarity | More plumbing; repositories built per call |
sqlc WithTx | q.WithTx(tx) returns bound queries | Generated, explicit | One Queries per tx |
Pass DBTX parameter | Save(ctx, q DBTX, o) | Very explicit | Persistence type in service code |
Fix / how to use it: pick one approach per service. The tests prove that the context approach runs begin, query, query, exec, exec, exec, exec, commit on one connection, that a version conflict rolls back, and that the unit of work commits once.
package repository
import (
"context"
"database/sql/driver"
"errors"
"slices"
"strings"
"testing"
"academy/database-sql-pgx/internal/fakedb"
)
// In-memory fakes: the service test needs no SQL at all.
type memOrders struct{ m map[int64]*Order }
func (r *memOrders) Get(_ context.Context, id int64) (*Order, error) {
o, ok := r.m[id]
if !ok {
return nil, ErrNotFound
}
c := *o
return &c, nil
}
func (r *memOrders) Save(_ context.Context, o *Order) error { r.m[o.ID] = o; return nil }
type memOutbox struct{ topics []string }
func (o *memOutbox) Append(_ context.Context, topic string, _ []byte) error {
o.topics = append(o.topics, topic)
return nil
}
type noTx struct{}
func (noTx) InTx(ctx context.Context, fn func(context.Context) error) error { return fn(ctx) }
func TestServiceWithFakes(t *testing.T) {
orders := &memOrders{m: map[int64]*Order{7: {ID: 7, Status: "open"}}}
out := &memOutbox{}
s := Service{Tx: noTx{}, Orders: orders, Outbox: out}
if err := s.Cancel(t.Context(), 7); err != nil {
t.Fatal(err)
}
if orders.m[7].Status != "cancelled" || !slices.Equal(out.topics, []string{"order.cancelled"}) {
t.Fatalf("%+v %v", orders.m[7], out.topics)
}
if err := s.Cancel(t.Context(), 99); !errors.Is(err, ErrNotFound) {
t.Fatal(err)
}
}
func orderFake(affected int64) *fakedb.DB {
return fakedb.New(func(kind, q string, _ []any) fakedb.Response {
switch {
case strings.HasPrefix(q, "SELECT customer_id"):
return fakedb.Response{Columns: []string{"customer_id", "status", "version"},
Rows: [][]driver.Value{{int64(3), "open", int64(4)}}}
case strings.HasPrefix(q, "SELECT sku"):
return fakedb.Response{Columns: []string{"sku", "qty"},
Rows: [][]driver.Value{{"A1", int64(2)}}}
case strings.HasPrefix(q, "UPDATE orders"):
return fakedb.Response{Affected: affected}
}
return fakedb.Response{Affected: 1}
})
}
// Every statement of the use case runs on one connection between BEGIN and COMMIT.
func TestTxInContextSharesOneTransaction(t *testing.T) {
fake := orderFake(1)
db := fake.Open()
s := Service{Tx: TxManager{DB: db}, Orders: NewSQLOrders(db), Outbox: NewSQLOutbox(db)}
if err := s.Cancel(t.Context(), 7); err != nil {
t.Fatal(err)
}
calls := fake.Calls()
var kinds []string
for _, c := range calls[1:] {
if c.Conn != calls[1].Conn {
t.Fatalf("statement on another connection: %+v", c)
}
kinds = append(kinds, c.Kind)
}
want := []string{"begin", "query", "query", "exec", "exec", "exec", "exec", "commit"}
if !slices.Equal(kinds, want) {
t.Fatalf("got %v", kinds)
}
}
func TestVersionConflictRollsBack(t *testing.T) {
fake := orderFake(0) // UPDATE matched no row: someone else saved first
db := fake.Open()
s := Service{Tx: TxManager{DB: db}, Orders: NewSQLOrders(db), Outbox: NewSQLOutbox(db)}
if err := s.Cancel(t.Context(), 7); !errors.Is(err, ErrConflict) {
t.Fatal(err)
}
if fake.Count("rollback") != 1 || fake.Count("commit") != 0 {
t.Fatalf("calls %v", fake.Kinds())
}
}
func TestUnitOfWork(t *testing.T) {
fake := orderFake(1)
err := UnitOfWork{DB: fake.Open()}.Do(t.Context(), func(r Repos) error {
o, err := r.Orders.Get(t.Context(), 7)
if err != nil {
return err
}
o.Status = "paid"
if err := r.Orders.Save(t.Context(), o); err != nil {
return err
}
return r.Outbox.Append(t.Context(), "order.paid", nil)
})
if err != nil || fake.Count("commit") != 1 {
t.Fatalf("err=%v calls=%v", err, fake.Kinds())
}
}sqlc for typed queries, squirrel/goqu builders, GORM/ent/bun trade-offs Important
In plain words: you can write SQL by hand (this page), generate typed Go from SQL files (sqlc), build SQL with Go method chains (squirrel, goqu), or map structs to tables with an ORM (GORM, ent, bun). The further right you go, the less SQL you write and the less you see.
Common misunderstanding: "Go needs an ORM like Eloquent." Many Go teams deliberately do not use one: sqlc gives type safety while keeping SQL as the source of truth. And "query builders prevent injection by magic": they do only as long as values go through their placeholder API, not Expr with string formatting.
Definition: sqlc: "sqlc generates type-safe code from SQL"; you write queries in SQL, run sqlc, and call the generated methods; sql_package: "pgx/v5" emits pgx code, emit_pointers_for_null_types uses pointers for NULL columns. squirrel: "fluent SQL generator for Go", now "complete" (bug fixes only). goqu: "an expressive SQL builder and executor". GORM: "The fantastic ORM library for Golang" with associations and hooks. ent: "a simple, yet powerful entity framework for Go" with schema as Go code and a graph traversal API. bun: "Lightweight, SQL-first Golang ORM for PostgreSQL, MySQL, MSSQL, SQLite, and Oracle".
sqlc flow
1 query.sql: -- name: GetOrder :one
SELECT id, status FROM orders WHERE id = $1;
2 sqlc generate -> db/query.sql.go: func (q *Queries) GetOrder(ctx, id int64) (Order, error)
3 repository: o, err := q.GetOrder(ctx, id) compile error if the column or type changesReal scenario: a payments service on sqlc + pgx where every query is reviewed as SQL; an admin back office on GORM for speed of CRUD; a search endpoint with optional filters built with squirrel; an ent schema with generated GraphQL.
| Tool | Style | Type safety | Sees the SQL | Trade-off |
|---|---|---|---|---|
Hand-written + database/sql/pgx | SQL strings | At runtime (Scan) | Fully | Boilerplate; CollectRows helps |
| sqlc | SQL → generated Go | Compile time | Fully | Dynamic queries are awkward |
| squirrel / goqu | Builder | Partial | Via ToSql() | Dynamic filters easy; another DSL |
| sqlx / scany | Scanning helpers | Runtime | Fully | Small; no codegen |
| bun | SQL-first ORM | Partial | Mostly | Lighter than GORM |
| GORM | Full ORM | Runtime, reflection | Hidden by default | Fast CRUD; N+1 and surprise queries (ORM Pitfalls) |
| ent | Schema-as-code ORM | Compile time (generated) | Hidden | Strong graph API; heavy codegen |
Fix / how to use it: a reasonable default for a PostgreSQL service: sqlc for the static queries, a builder for the few dynamic search endpoints, pgx.CollectRows for anything else; reach for an ORM only where CRUD speed matters more than SQL control.
Migrations: golang-migrate, goose, atlas, tern Good to know
In plain words: schema changes live in versioned files applied in order and recorded in a table, by a tool run at deploy time (not by the application at random startup moments).
Common misunderstanding: "Let every instance run migrations on startup." Ten pods racing to run the same ALTER TABLE need a lock; most tools take an advisory lock, but a long migration still blocks the rollout. Run them as a separate deploy step. Zero-downtime technique (expand/contract, CREATE INDEX CONCURRENTLY) is in Schema Migrations.
Definition: golang-migrate: "Database migrations written in Go", usable as a CLI or a library, up/down SQL files, many sources and databases. goose: "a database migration tool. Both a CLI and a library", SQL or Go-function migrations, -- +goose Up/Down annotations, runs on *sql.DB. Atlas: "a language-independent tool for managing and migrating database schemas", with a declarative workflow (atlas schema apply diffs desired against current) and versioned migrations. tern (by the pgx author): "a standalone migration tool for PostgreSQL" with SQL and Go function migrations and data variable interpolation.
| Tool | Format | Declarative diff | Go API | Notes |
|---|---|---|---|---|
| golang-migrate | NNN_name.up.sql / .down.sql | No | Yes | Many databases; "dirty" state on failure |
| goose | -- +goose Up SQL, or Go functions | No | Yes (*sql.DB) | Embeddable with embed.FS |
| Atlas | HCL or SQL schema, versioned dirs | Yes | CLI-first | Lint and diff in CI |
| tern | SQL with templates, Go migrations | No | Yes (migrate package, pgx) | PostgreSQL only |
| sqlc | reads a schema directory | n/a | n/a | Point schema: at your migrations directory |
deploy pipeline
1 build image
2 run: goose -dir migrations postgres "$DATABASE_URL" up (SET lock_timeout inside each file)
3 roll out new pods (code works with old and new schema: expand step)
4 later release: contract (drop old column)N+1 in Go Important
In plain words: loading a list and then one query per item costs 1 + N round trips. In Go nobody hides it from you; it shows up as a query inside a loop. Fetch the children for all parents in one query.
Common misunderstanding: "N+1 is an ORM problem; my hand-written SQL cannot have it." A repository method called in a loop (for _, o := range orders { repo.Lines(ctx, o.ID) }) is the same bug. With 1 ms per round trip, a page of 100 orders spends 100 ms on network waits alone.
Definition: fix it with WHERE order_id = ANY($1) and a slice of ids (pgx sends a bigint[]), a JOIN with grouping in Go, json_agg in SQL, or a pgx Batch when the queries differ. The bulk test counts the driver calls: 10 queries for N+1 over 10 orders, 1 query batched, with the whole []int64 passed as one argument.
N+1: SELECT ... FROM orders LIMIT 100 1
SELECT ... FROM order_lines WHERE order_id = $1 x100
batched: SELECT ... FROM orders LIMIT 100 1
SELECT ... FROM order_lines WHERE order_id = ANY($1) 1 ($1 = 100 ids)| Fix | Queries | When |
|---|---|---|
= ANY($1) with ids | 2 | Default |
JOIN + group in Go | 1 | Small child sets |
json_agg / array_agg | 1 | Read models, APIs that return nested JSON |
pgx.Batch | 1 round trip | Different queries per parent |
| GraphQL dataloader | 1 per level | GraphQL resolvers (GraphQL in Go) |
package bulk
import (
"database/sql/driver"
"strings"
"testing"
"academy/database-sql-pgx/internal/fakedb"
)
func linesFake() *fakedb.DB {
return fakedb.New(func(kind, q string, args []any) fakedb.Response {
cols := []string{"order_id", "sku", "qty"}
if kind == "exec" {
return fakedb.Response{Affected: int64(len(args[0].([]int64)))}
}
return fakedb.Response{Columns: cols, Rows: [][]driver.Value{{int64(1), "A1", int64(2)}}}
})
}
func TestNPlus1VersusBatched(t *testing.T) {
ids := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
slow := linesFake()
if _, err := LinesNPlus1(t.Context(), slow.Open(), ids); err != nil {
t.Fatal(err)
}
fast := linesFake()
if _, err := LinesBatched(t.Context(), fast.Open(), ids); err != nil {
t.Fatal(err)
}
if slow.Count("query") != 10 || fast.Count("query") != 1 {
t.Fatalf("n+1=%d batched=%d", slow.Count("query"), fast.Count("query"))
}
if _, ok := fast.Calls()[1].Args[0].([]int64); !ok {
t.Fatal("the slice should reach the driver as one argument")
}
}
func TestInsertUnnestIsOneStatement(t *testing.T) {
fake := linesFake()
n, err := InsertUnnest(t.Context(), fake.Open(), []Line{{1, "A1", 2}, {1, "B2", 1}, {2, "A1", 5}})
if err != nil || n != 3 || fake.Count("exec") != 1 || len(fake.Calls()[1].Args) != 3 {
t.Fatalf("n=%d err=%v calls=%v", n, err, fake.Kinds())
}
}
func TestValuesChunksRespectParamLimit(t *testing.T) {
rows := make([][]any, 50_000)
for i := range rows {
rows[i] = []any{int64(i), "sku", int64(1)}
}
chunks := ValuesChunks("order_lines", []string{"order_id", "sku", "qty"}, rows)
if len(chunks) != 3 {
t.Fatalf("chunks=%d", len(chunks))
}
total := 0
for _, c := range chunks {
if len(c.Args) > MaxParams {
t.Fatalf("chunk with %d params", len(c.Args))
}
total += len(c.Args)
}
if total != 150_000 || !strings.HasSuffix(chunks[0].SQL, "($65533, $65534, $65535)") {
t.Fatalf("total=%d tail=%q", total, chunks[0].SQL[len(chunks[0].SQL)-30:])
}
}Testing: fake driver, pgx mock, real DB, dockertest/testcontainers pointer Important
In plain words: test services with in-memory fake repositories; test repositories against a real PostgreSQL, because only the server can tell you that your SQL, constraints and isolation behave. Mocks of the driver are for narrow cases.
Common misunderstanding: "sqlmock/pgxmock tests prove my SQL works." They prove your code sent the string you expected and handled the result you scripted. A typo in a column name passes. pgxmock "has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection"; use it for error paths that are hard to trigger for real.
Definition and options:
| Layer | Tool | Proves | Cost |
|---|---|---|---|
| Service logic | In-memory fake implementing the repository interface | Business rules, tx boundaries called | Milliseconds |
database/sql behaviour | A tiny fake driver (this page's internal/fakedb) | Pool, rows, tx call order | Milliseconds |
| Driver interaction | go-sqlmock, pgx mock (pgxmock) | Expected SQL text and args; error paths | Milliseconds, brittle |
| Repository SQL | Real DB: testcontainers-go postgres module, ory/dockertest, or a CI service container | SQL, constraints, isolation, migrations | Seconds per package |
| Isolation per test | Transaction rolled back per test, or a template database per package | No leakage between tests | Low |
TestMain: start one container (testcontainers / dockertest pointer), run migrations once
each test: tx := pool.Begin(ctx); repo := NewSQLOrders(tx); ...; tx.Rollback(ctx)
CI: services: postgres:18 in the pipeline instead of a container from the testReal scenario: a repository test that caught a missing ON CONFLICT target only against a real server; a flaky suite fixed by giving each package its own database cloned from a migrated template; go test -race on service tests with fakes running in under a second.
Fix / how to use it: keep the fake-driver and fake-repository tests in the default go test ./...; put real-database tests behind a build tag or an environment variable so they run in CI with a container. Containers are outside this page's lab rules, so the snippets here stop at fakes.
Observability: otelsql, pgx tracer, pool stats Good to know
In plain words: you want three things from the data layer: a span (or log line) per query with its duration, pool gauges (in use, idle, waits), and error counts by SQLSTATE.
Common misunderstanding: "Log every query with its arguments." Arguments contain personal data and secrets; log SQL text, durations, row counts and error codes. Sample or threshold the rest.
Definition: for database/sql, otelsql "is an OpenTelemetry instrumentation for Golang database/sql" that "instruments traces and metrics" by wrapping the driver. For pgx, ConnConfig.Tracer takes a pgx.QueryTracer (TraceQueryStart returns a ctx passed to TraceQueryEnd), plus BatchTracer, CopyFromTracer, PrepareTracer, ConnectTracer; multitracer combines several, tracelog adapts a logger, and otelpgx provides OpenTelemetry instrumentation for pgx (its README lists Go 1.25 as the minimum). Pool numbers come from db.Stats() and pool.Stat() (AcquiredConns, IdleConns, EmptyAcquireCount, AcquireDuration, CanceledAcquireCount).
TraceQueryStart(ctx, conn, {SQL, Args}) -> ctx' with start time (and a span in otelpgx)
... query runs ...
TraceQueryEnd(ctx', conn, {CommandTag, Err}) -> duration, rows, SQLSTATE -> log / span / histogram| Signal | Source | Alert when |
|---|---|---|
| Query latency p99 | Tracer / otelsql histogram | Above budget |
| Pool wait count / acquire time | db.Stats().WaitCount, pool.Stat().EmptyAcquireCount | Rising |
| In-use == max | InUse, AcquiredConns | Sustained |
| Errors by SQLSTATE | Classifier + counter | 40001 bursts, 53300 any |
| Long transactions | pg_stat_activity (state = 'idle in transaction') | Older than seconds |
// Package observe adds query timing to pgx through its QueryTracer hook
// (ConnConfig.Tracer) and exports pool gauges. Production setups usually use
// otelpgx (pgx) or otelsql (database/sql) for OpenTelemetry spans and metrics;
// this shows the hook they plug into.
package observe
import (
"context"
"log/slog"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// SlowQueries logs failed queries and queries slower than Threshold.
type SlowQueries struct {
Log *slog.Logger
Threshold time.Duration
}
type startKey struct{}
type started struct {
sql string
at time.Time
}
var _ pgx.QueryTracer = (*SlowQueries)(nil)
// TraceQueryStart stores the start time in the returned context.
func (t *SlowQueries) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
return context.WithValue(ctx, startKey{}, started{sql: d.SQL, at: time.Now()})
}
// TraceQueryEnd logs SQL text (never the arguments: they may hold personal data).
func (t *SlowQueries) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
s, ok := ctx.Value(startKey{}).(started)
if !ok {
return
}
took := time.Since(s.at)
switch {
case d.Err != nil:
t.Log.ErrorContext(ctx, "query failed", "sql", s.sql, "took", took, "err", d.Err)
case took >= t.Threshold:
t.Log.WarnContext(ctx, "slow query", "sql", s.sql, "took", took, "rows", d.CommandTag.RowsAffected())
}
}
// Install sets the tracer on a pool config before the pool is created.
func Install(cfg *pgxpool.Config, t pgx.QueryTracer) { cfg.ConnConfig.Tracer = t }
// PoolGauges reads pgxpool.Stat for a metrics exporter.
func PoolGauges(p *pgxpool.Pool) map[string]int64 {
s := p.Stat()
return map[string]int64{
"total": int64(s.TotalConns()),
"acquired": int64(s.AcquiredConns()),
"idle": int64(s.IdleConns()),
"max": int64(s.MaxConns()),
"empty_acquire": s.EmptyAcquireCount(), // had to wait: pool too small or queries too slow
"acquire_ms_total": s.AcquireDuration().Milliseconds(),
"canceled_acquire": s.CanceledAcquireCount(),
}
}Mechanics
Inside the database/sql pool Important
sql.DB keeps freeConn []*driverConn ("free connections ordered by returnedAt oldest to newest"), a set of waiting requests (connRequests), numOpen, the limits, and counters behind Stats(). OpenDB starts a connectionOpener goroutine; a cleaner goroutine starts when a lifetime or idle time is set and closes expired connections ("Expired connections may be closed lazily before reuse").
db.conn(ctx, strategy):
1 ctx already done? -> return ctx.Err()
2 free connection available (cachedOrNewConn)?
take the newest; if expired -> close, try again; resetSession if the driver needs it
3 maxOpen reached? -> register a request, wait on it or ctx.Done() (WaitCount++)
4 else numOpen++, dial via connector -> new driverConn
release (putConn): hand to a waiting request first, else append to freeConn if under maxIdle, else close (MaxIdleClosed++)
driver.ErrBadConn on a fresh call -> retry (maxBadConnRetries = 2), then once with a forced new connectionA *sql.Tx and a *sql.Conn take the connection out of this cycle until they end; *sql.Rows holds it until Close or EOF. The BeginTx context gets a goroutine (awaitDone) that rolls the transaction back when the context ends, which is why the rollback test polls.
Inside pgx and pgxpool Good to know
pgxpool is built on github.com/jackc/puddle/v2; each resource is a *pgx.Conn on a pgconn.PgConn that speaks the frontend/backend protocol with non-blocking I/O. On Query with the default mode, pgx looks the SQL up in the connection's LRU statement cache (name "stmtcache_" + hex(sha256(sql)[:24])), sends Parse/Describe on a miss, then Bind/Execute/Sync, and decodes results with the connection's pgtype.Map. On error the cache entry is invalidated. In Conn.exec (the Exec path), a statement without arguments is sent with the simple protocol regardless of mode. Pipeline mode (one Sync for many statements) underlies SendBatch.
Exact error texts Must-know
| Text | Source |
|---|---|
sql: no rows in result set | sql.ErrNoRows |
sql: transaction has already been committed or rolled back | sql.ErrTxDone |
sql: connection is already closed | sql.ErrConnDone |
sql: Scan error on column index 0, name "phone": converting NULL to string is unsupported | Rows.Scan (real output) |
no rows in result set | pgx.ErrNoRows (wraps sql.ErrNoRows) |
too many rows in result set | pgx.ErrTooManyRows |
tx is closed | pgx.ErrTxClosed |
commit unexpectedly resulted in rollback | pgx.ErrTxCommitRollback |
conn busy | pgconn: one *pgx.Conn used by two goroutines |
cannot find field customer_id in returned row | RowToStructByName (real output) |
extended protocol limited to 65535 parameters | pgconn (%v = math.MaxUint16) |
failed to connect to ... dial error: dial tcp 127.0.0.1:1: connect: connection refused | pgxpool Ping (real output) |
ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) | PostgreSQL, Repeatable Read |
ERROR: could not serialize access due to read/write dependencies among transactions (SQLSTATE 40001) | PostgreSQL, Serializable |
ERROR: current transaction is aborted, commands ignored until end of transaction block (SQLSTATE 25P02) | Statement after an error inside a tx |
ERROR: cached plan must not change result type | Prepared statement after a schema change |
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
sql.Open per request | Connection churn, 53300 | One pool in main | None |
No PingContext at startup | First request fails after a bad deploy | Ping with a timeout | One call |
Unlimited MaxOpenConns | Server overload at peaks | Budget per instance | Some queueing |
Unclosed Rows | Pool exhaustion, WaitCount climbs | defer rows.Close() | None |
Ignoring rows.Err() | Truncated results | Check after the loop | None |
| String-built SQL | Injection | Placeholders, allow-lists | None |
| Statements outside the tx | Partial writes, deadlocks | Use tx everywhere; a helper | Discipline |
| No rollback on error | Locks held until timeout | defer tx.Rollback() | None |
| Retrying one statement | 25P02 | Retry the whole transaction on 40001/40P01 | Idempotent fn |
| HTTP call inside a tx | Long transactions, locks | Outbox, call after commit | Extra table |
SELECT * + statement cache | Error after migrations | Explicit column lists | Typing |
| Cache behind transaction pooler | 26000 / 42P05 | QueryExecModeExec or PgBouncer ≥ 1.21 tracking | Slightly more planning |
| N+1 | Latency grows with page size | = ANY($1), batch | None |
| Matching error messages | Breaks on upgrades/locales | errors.As + SQLSTATE | None |
The repository that hid a transaction per method
Each method beginning its own transaction is the most common reason an event or an audit row goes missing. Move the boundary to the use case with TxManager.InTx or a unit of work (Sharing a transaction); repositories only ever use what they are given.
The long transaction
// Bug: the transaction (and its row locks) lives for the whole HTTP call.
err := txn.WithTx(ctx, db, nil, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx, `UPDATE stock SET qty = qty - 1 WHERE sku = $1`, sku); err != nil {
return err
}
return payments.Charge(ctx, amount) // 2 s on a bad day, locks held all along
})
// Fix: reserve and record the intent in one short transaction, charge outside,
// confirm in a second short transaction (or let a worker drive it from an outbox row).Pool exhaustion from nested connections
A function that holds a Tx and, inside, calls a helper using db needs two connections at once; with MaxOpenConns(n) and n concurrent requests doing this, all n hold one and wait for a second forever (until ctx). That is the deadlock the go.dev guide warns about. Pass the tx (or the ctx carrying it) down instead.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| New PostgreSQL-only service | pgx v5 native + pgxpool | sqlc with sql_package: pgx/v5 | Fastest, full feature set |
| Library or multi-database code | database/sql + pgx stdlib | OpenDBFromPool if you also need pgx | Portable; tools expect *sql.DB |
| Existing lib/pq code | Keep, migrate when touching | Switch driver name to pgx, test NULL/array handling | Low-risk swap |
| MySQL | go-sql-driver/mysql | parseTime=true, ? placeholders | The standard driver |
| Many small reads per page | pgx.Batch or = ANY($1) | Avoid N+1 | Round trips dominate |
| Bulk load | CopyFrom | Staging table + INSERT ... ON CONFLICT | Order of magnitude faster |
| Upsert a few thousand rows | unnest arrays | ON CONFLICT DO UPDATE | One statement, stable SQL text |
| Money transfer, inventory | BeginTx + SELECT ... FOR UPDATE or Serializable | WithRetry on 40001 | Correctness first |
| Read-only report | LevelRepeatableRead, ReadOnly | Replica if lag is acceptable | One snapshot |
| Behind PgBouncer transaction mode | QueryExecModeExec (or PgBouncer ≥ 1.21 tracking) | Direct connection for LISTEN | Session state does not survive |
| Cache invalidation across instances | LISTEN/NOTIFY | Re-read on reconnect | No broker needed |
| Static CRUD + reporting queries | sqlc | Builder for dynamic filters | Typed, SQL visible |
| Admin back office | GORM or bun | Watch for N+1 | Speed of development |
| Service tests | Fake repositories | Real DB for repository tests | Fast and honest |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One pgxpool.Pool (or *sql.DB) created in main, pinged, sized to the database's budget, passed to repositories through constructors; one TxManager for use cases; migrations run by the deploy pipeline. Example: an order API whose POST /orders runs InTx → Orders.Save + Outbox.Append in one transaction with a 2 s ctx budget, statement_timeout = 5s on the role, and MaxConns = 20.
Modular monolith and multiple databases
Each module owns its tables and its repositories; other modules call its Go API, not its tables. Two modules may share one pool and one transaction while they live in the same database (the context-carried tx makes that easy, which is also the risk: it hides coupling). With two databases (orders in PostgreSQL, analytics in another), you have two pools and no shared transaction; the outbox in the orders database plus a consumer is how changes reach the other side. Name pools after their database (ordersDB, billingDB) so nobody passes the wrong one.
Microservices
Each service has its own database and its own pool; the only things crossing service boundaries are API calls and events. A cross-service change is a saga, not a transaction: the order service commits orders + outbox together, a relay publishes order.created, the payment service consumes it idempotently (a processed_messages table with a unique key, checked with 23505) and commits its own state + outbox. Pool sizing is now a fleet problem: 30 services × 4 pods × 20 connections = 2,400, far above a single PostgreSQL's comfortable range, which is why poolers (PgBouncer, RDS Proxy, pgcat) appear, and with them the prepared statement and LISTEN constraints.
Distributed data: replicas, caches, sharded databases, multi-region
A read replica is another pool (replicaPool) with target_session_attrs and default_transaction_read_only; reads that must see the user's own write go to the primary (read-your-writes) or wait for the replica LSN. A failover changes which host is primary: MaxConnLifetime plus target_session_attrs=read-write (multi-host DSN) let pools find the new one; in-flight transactions fail with 57P01 or 08006 and their outcome is unknown, so writes need idempotency keys. Distributed SQL such as CockroachDB speaks the PostgreSQL protocol (pgx's README says pgx "is tested against the latest version of CockroachDB"), and its docs say it executes all transactions at SERIALIZABLE by default, so 40001 is routine and the retry helper becomes mandatory. Sharding by tenant means one pool per shard and a router choosing the pool from the tenant id; cross-shard transactions do not exist.
Scaling path: 1×, 10×, 100×
| Load | What changes | Go data-layer practice |
|---|---|---|
| 1× (one instance) | Defaults hide bugs | One pool, Ping, all four knobs set, defer rows.Close(), tx helper, SQLSTATE classifier |
| 10× (several instances) | Connection budget and slow queries matter | Pool size = budget ÷ instances, statement_timeout, pool metrics, batch/ANY, COPY for imports |
| 100× (fleet, replicas, poolers) | Server connections and failovers dominate | PgBouncer transaction mode (exec mode or 1.21+ tracking), replica pools, retries with budgets, outbox for every cross-service effect |
Lab
1. Run the tests (real)
cd docs/snippets/go/database-sql-pgx/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok academy/database-sql-pgx/after 1.982s
# ok academy/database-sql-pgx/before 1.923s
# ok academy/database-sql-pgx/bulk 1.905s
# ok academy/database-sql-pgx/errs 1.855s
# ? academy/database-sql-pgx/internal/fakedb [no test files]
# ok academy/database-sql-pgx/nulls 1.846s
# ok academy/database-sql-pgx/observe 1.690s
# ok academy/database-sql-pgx/pgxnative 1.679s
# ok academy/database-sql-pgx/pool 1.733s
# ok academy/database-sql-pgx/prepared 1.625s
# ok academy/database-sql-pgx/repository 1.795s
# ok academy/database-sql-pgx/txn 1.859s2. See the defaults and the laziness (real)
go test -count=1 -v -run 'TestDefaults|TestPoolIsLazy|TestScanNullIntoStringFails|TestStmtReprepareOnNewConnection' ./pgxnative ./nulls ./prepared
# config_test.go:41: MaxConns default on this machine: 12
# config_test.go:70: failed to connect to `user=app database=orders`: 127.0.0.1:1 (127.0.0.1): dial error: dial tcp 127.0.0.1:1: connect: connection refused
# nulls_test.go:47: sql: Scan error on column index 0, name "phone": converting NULL to string is unsupported
# prepared_test.go:59: connections=3 prepares=3pgxpool.NewWithConfig returned without error for a port where nothing listens; only Ping failed. One DB-level Stmt used on three connections was prepared three times.
3. Schema for the server labs
The schema lives next to the code as pgxnative/schema.sql, embedded into the package (Schema) so the tests can check it against the code: Import's column list covers every NOT NULL column without a default, and the order_status enum that AfterConnect loads is created here. Apply it before starting a pool built by PoolConfig.
-- Lab schema for the database-sql-pgx snippets (run before starting the service:
-- pgxpool's AfterConnect loads the order_status type on every new connection).
CREATE TYPE order_status AS ENUM ('open', 'paid', 'shipped', 'cancelled');
CREATE TABLE accounts (id bigint PRIMARY KEY, balance bigint NOT NULL CHECK (balance >= 0));
CREATE TABLE users (
id bigserial PRIMARY KEY,
email text NOT NULL,
CONSTRAINT users_email_key UNIQUE (email)
);
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL,
email text NOT NULL,
note text,
status order_status NOT NULL DEFAULT 'open',
total_cents bigint NOT NULL,
shipped_at timestamptz,
version int NOT NULL DEFAULT 1
);
CREATE TABLE order_lines (
order_id bigint NOT NULL REFERENCES orders (id),
sku text NOT NULL,
qty bigint NOT NULL,
PRIMARY KEY (order_id, sku)
);
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
topic text NOT NULL,
payload bytea,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO accounts VALUES (1, 1000), (2, 0);Role-level server backstops for the application user (behind PgBouncer transaction pooling this is the only place the timeouts can live, see PgBouncer):
ALTER ROLE app SET statement_timeout = '5s';
ALTER ROLE app SET lock_timeout = '2s';
ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';package pgxnative
import (
"regexp"
"slices"
"strings"
"testing"
)
// requiredColumns returns the NOT NULL columns without a DEFAULT of one table in schema.sql.
func requiredColumns(t *testing.T, table string) []string {
t.Helper()
m := regexp.MustCompile(`(?s)CREATE TABLE ` + table + ` \((.*?)\n\);`).FindStringSubmatch(Schema)
if m == nil {
t.Fatalf("table %s not in schema.sql", table)
}
var out []string
for _, line := range strings.Split(m[1], "\n") {
f := strings.Fields(strings.TrimSuffix(strings.TrimSpace(line), ","))
if len(f) < 2 || strings.ToUpper(f[0]) == "PRIMARY" {
continue
}
l := strings.ToUpper(line)
if strings.Contains(l, "NOT NULL") && !strings.Contains(l, "DEFAULT") && !strings.Contains(l, "SERIAL") {
out = append(out, f[0])
}
}
return out
}
// Round 1: COPY fails for NOT NULL columns it omits that have no default.
func TestImportCoversRequiredColumns(t *testing.T) {
for _, c := range requiredColumns(t, "orders") {
if !slices.Contains(ImportColumns, c) {
t.Errorf("Import omits required column %q", c)
}
}
}
// Round 1: AfterConnect loads these types; the schema must create them.
func TestSchemaCreatesLoadedTypes(t *testing.T) {
for _, typ := range LoadedTypes {
if !strings.Contains(Schema, "CREATE TYPE "+typ+" ") {
t.Errorf("schema.sql does not create type %s used by AfterConnect", typ)
}
}
}4. A real serialization failure (expected, not run)
Two psql sessions against the schema above:
session A session B
1 BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN ISOLATION LEVEL REPEATABLE READ;
2 SELECT balance FROM accounts WHERE id = 1; -- 1000
3 SELECT balance FROM accounts WHERE id = 1; -- 1000
4 UPDATE accounts SET balance = balance - 100 WHERE id = 1;
5 COMMIT;
6 UPDATE accounts SET balance = balance - 100 WHERE id = 1;
7 -- ERROR: could not serialize access due to concurrent update
8 ROLLBACK; -- txn.WithRetry would now run B again and succeed5. statement_timeout and cancel (expected, not run)
go: pool.Exec(ctx /* 300 ms */, "SELECT pg_sleep(10)")
# default pgx handler: timeout: context deadline exceeded (connection discarded)
psql: SELECT pid, state, query FROM pg_stat_activity WHERE query LIKE '%pg_sleep%';
# row still present until the backend notices the closed socket
go: pool.Exec(context.Background(), "SELECT pg_sleep(10)") with role statement_timeout = 5s
# ERROR: canceling statement due to statement timeout (SQLSTATE 57014) after 5 s6. PgBouncer transaction mode (expected, not run)
With PgBouncer pool_mode = transaction, max_prepared_statements = 0, default_pool_size = 2, run the same pool.Query with a parameter from 20 goroutines through pgx defaults: expect intermittent prepared statement "stmtcache_..." does not exist (SQLSTATE 26000) or 42P05. Add default_query_exec_mode=exec to the DSN: errors disappear. Set max_prepared_statements = 200 (PgBouncer 1.21+) and remove the DSN option: per PgBouncer's docs the default mode works again.
7. LISTEN/NOTIFY (expected, not run)
go: Listen(ctx, pool, "orders_changed", func(n *pgconn.Notification) error { fmt.Println(n.Channel, n.Payload); return nil })
psql: BEGIN; SELECT pg_notify('orders_changed', '42'); -- nothing printed yet
psql: COMMIT; -- go prints: orders_changed 42For PHP/Laravel developers
In PHP-FPM each request is a process with its own PDO connection (or a persistent one per worker), so there is no in-process pool to size. Go's *sql.DB is shared by thousands of goroutines in one process, so pool size, unclosed rows and long transactions are your problem, not FPM's pm.max_children. Eloquent is an Active Record ORM with lazy loading (hence N+1 and with()), while Go code usually writes SQL or generates it with sqlc. Laravel 13's DB::transaction commits or rolls back for you and "accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs"; in Go that is txn.WithRetry, where you decide which SQLSTATEs are retryable (40001 as well as 40P01). Laravel 13 also documents "Pooled PostgreSQL Connections": a pooled connection for transaction-mode poolers plus direct connection details because "some schema operations, migrations, and maintenance commands require a direct database connection", the same split as using a direct pool for migrations and LISTEN in Go.
// Laravel: closure-based transaction, retried up to 3 times on deadlock.
DB::transaction(function () use ($from, $to, $cents) {
DB::update('UPDATE accounts SET balance = balance - ? WHERE id = ?', [$cents, $from]);
DB::update('UPDATE accounts SET balance = balance + ? WHERE id = ?', [$cents, $to]);
}, attempts: 3);| Laravel / PHP | Go |
|---|---|
DB::connection() (PDO) | sql.Open / pgxpool.New (lazy pool) + Ping |
| One connection per FPM worker | One pool per process, SetMaxOpenConns / MaxConns |
? bindings, PDO emulated prepares | $1 placeholders, pgx statement cache |
DB::transaction(fn, attempts) | txn.WithTx / WithRetry |
Eloquent models, with() | Repositories + sqlc, = ANY($1) |
QueryException + errorInfo[0] (SQLSTATE) | errors.As(err, &pgErr); pgErr.Code |
php artisan migrate | goose, golang-migrate, Atlas, tern |
pooled + direct pgsql connection | pooled DSN for queries, direct DSN for migrations and LISTEN |
DB::listen for query logs | pgx.QueryTracer, otelsql |
Common misconceptions
| Belief | Reality |
|---|---|
sql.Open checks the connection | It may not connect at all; call PingContext |
Open a *sql.DB per request | It is a pool; open once per process |
| Unlimited connections are fastest | They overload the server; set MaxOpenConns/MaxConns |
| The pgxpool default size is 4 | max(4, runtime.NumCPU()) |
Next returning false means success | Check rows.Err() |
rows.Close() is optional | Early returns leak the connection without it |
database/sql translates ? to $1 | Placeholder syntax belongs to the driver |
db.Prepare prepares once | Once per connection it runs on |
| Disabling the pgx cache means interpolation | Only the simple protocol interpolates |
defer tx.Rollback() undoes a commit | After Commit it is a no-op returning ErrTxDone |
db.ExecContext inside a tx function is in the tx | It runs on another connection, outside the transaction |
| Retry the failed statement on 40001 | Retry the whole transaction |
| ctx cancel stops the server query | Depends on the driver; pgx default closes the connection |
| PgBouncer can never handle prepared statements | 1.21+ tracks protocol-level ones when max_prepared_statements > 0 |
| sqlmock tests prove the SQL is right | Only a real database can |
Match duplicate key in the message | Check SQLSTATE 23505 and the constraint name |
Cheat sheet
| Topic | Remember |
|---|---|
| Open | Once in main; PingContext with a timeout; lazy otherwise |
| Pool | SetMaxOpenConns, SetMaxIdleConns (default 2), SetConnMaxLifetime, SetConnMaxIdleTime |
| pgxpool | MaxConns default max(4, NumCPU); MinIdleConns; lifetime 1 h; idle 30 min; health check 1 min |
| Query | QueryContext → defer rows.Close() → Next/Scan → rows.Err() |
| One row | QueryRowContext(...).Scan; sql.ErrNoRows → domain not found |
| NULL | Pointer, sql.Null[T] (1.22) or sql.NullString; never plain string |
| Placeholders | PostgreSQL $1, MySQL ?; identifiers via allow-list or pgx.Identifier |
| Prepare | pgx caches automatically (512 per conn); Stmt is per connection |
| Exec modes | cache_statement default; exec behind transaction poolers |
| Transaction | BeginTx → defer tx.Rollback() → work on tx only → Commit |
| Retry | 40001 and 40P01: rerun the whole fn with backoff; 23505 only if the key is derived inside a Serializable tx |
| Timeouts | ctx per call + statement_timeout, lock_timeout, idle_in_transaction_session_timeout |
| Errors | errors.As(err, &*pgconn.PgError); switch on Code |
| Bulk | CopyFrom > unnest arrays > multi-row VALUES (65535 params) > loop |
| N+1 | = ANY($1) with a slice, or pgx.Batch |
| Repository | Interface per aggregate, domain types, version column |
| Shared tx | Tx in ctx (InTx) or unit of work; boundary in the use case |
| Testing | Fakes for services, real PostgreSQL for repositories |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does sql.Open("pgx", dsn) do, and how do you make startup fail on a wrong password? Must-know
Answer
Answer: It finds the registered driver and returns a *sql.DB pool object; it "may just validate its arguments without creating a connection". Call db.PingContext(ctx) with a timeout right after opening; it dials a connection and authenticates, so a bad DSN or password fails the deploy instead of the first request.
2 — Your service has SetMaxOpenConns(10) and requests start timing out with context deadline exceeded while the database is idle. What do you look at first? Must-know
Answer
Answer: db.Stats(): if InUse is 10 and WaitCount climbs, connections are being held, not used. The usual causes are *sql.Rows not closed on an early return, long transactions (an HTTP call inside a Tx), or nested use of db while holding a Tx. Fix the holder before raising the limit.
3 — Why must you call rows.Err() after the for rows.Next() loop? Must-know
Answer
Answer: Next returns false both at the end of the result and when an error happened while reading the next row; "Rows.Err should be consulted to distinguish between the two cases". Without it a broken connection mid-stream looks like a shorter result.
4 — Show the defer-Rollback pattern and explain why the deferred Rollback is harmless after a successful Commit. Must-know
Answer
Answer: tx, err := db.BeginTx(ctx, nil); defer tx.Rollback(); do all work on tx; return tx.Commit(). Every early return or panic rolls back. After Commit the Tx is done, so Rollback returns sql.ErrTxDone without sending anything to the server (the After test shows the driver never sees it).
5 — A transaction fails with SQLSTATE 40001. What does your code do, and what must be true of the transaction function? Must-know
Answer
Answer: Roll back and run the whole transaction again from BeginTx, with backoff and a bounded number of attempts, while the caller's ctx allows. The function must be safe to run twice: no external side effects (emails, HTTP calls, channel sends) inside it; record them in an outbox row instead.
6 — How do you scan a nullable phone column, and what happens if you scan it into a string? Important
Answer
Answer: Into a *string (nil for NULL), a sql.Null[string] (Go 1.22) or a sql.NullString. Scanning a NULL into a plain string fails with converting NULL to string is unsupported.
7 — What does db.PrepareContext really do with a pool of 20 connections? Important
Answer
Answer: It prepares on one connection and returns a *sql.Stmt that "will prepare itself on the new connection automatically" whenever it runs on another one, so up to 20 server-side prepares. With pgx you usually skip it because pgx's statement cache already prepares and reuses queries per connection.
8 — Your pgx service moves behind PgBouncer in transaction mode and logs prepared statement "stmtcache_..." does not exist. Why, and what are the fixes? Important
Answer
Answer: pgx's default cache_statement mode creates named prepared statements on a session; in transaction mode the next transaction may land on another server connection. Either set default_query_exec_mode=exec (or simple_protocol on pgx ≥ 5.12.0), or run PgBouncer 1.21+ with max_prepared_statements > 0, which re-prepares statements on whichever server connection is used.
9 — How do you turn a unique violation on users.email into a 409 without matching message text? Important
Answer
Answer: var pg *pgconn.PgError; if errors.As(err, &pg) && pg.Code == "23505" && pg.ConstraintName == "users_email_key" { return ErrEmailTaken }. errors.As works through %w wrapping, and codes and constraint names are stable across locales and versions.
10 — Two repositories must write in one transaction. Name two ways to share the transaction and one risk of each. Important
Answer
Answer: Carry the *sql.Tx in the context (InTx puts it there, repositories pick it up): implicit, so a call outside InTx silently runs without a transaction. A unit of work that hands tx-bound repositories to a function: explicit, but more plumbing and repositories built per call. In both, the use case owns the boundary, never the repository.
11 — When is CopyFrom the wrong tool for inserting 10,000 rows? Good to know
Answer
Answer: When you need ON CONFLICT (upsert) or RETURNING, which COPY does not support, or when you are stuck with database/sql without Raw. Use INSERT ... SELECT * FROM unnest($1::bigint[], ...) with ON CONFLICT, or COPY into a staging table followed by one INSERT ... ON CONFLICT.
12 — With pgx defaults, what happens on the server when the ctx of a running query is canceled, and what backstop do you add? Good to know
Answer
Answer: pgx's default DeadlineContextWatcherHandler sets a deadline on the socket, the Go call returns and the connection is discarded; the server backend keeps running until it notices the closed connection. Configure CancelRequestContextWatcherHandler to send a cancel request, and keep a role-level statement_timeout as the server-side backstop.
Glossary
| Term | Meaning |
|---|---|
database/sql | Go standard-library package: pool, transactions and a driver interface for SQL databases |
*sql.DB | Concurrency-safe pool of connections; open once per database |
| sql.Open lazy | sql.Open/OpenDB may not connect; Ping or the first query dials |
PingContext | Verifies a connection can be made and used |
SetMaxOpenConns | Cap on open connections; default unlimited |
SetMaxIdleConns | Idle connections kept; default 2 |
SetConnMaxLifetime | Maximum age before a connection is closed |
SetConnMaxIdleTime | Maximum idle time before a connection is closed (Go 1.15) |
DBStats | Pool counters from db.Stats(): open, in use, idle, waits |
| Driver | Package implementing database/sql/driver for one database |
| pgx stdlib | github.com/jackc/pgx/v5/stdlib, the pgx adapter registered as "pgx" |
| lib/pq | Older pure-Go PostgreSQL driver, long in maintenance mode |
| go-sql-driver/mysql | The MySQL driver for database/sql |
QueryContext / QueryRowContext / ExecContext | Context-aware query, single-row query and exec |
*sql.Rows | Result cursor; Next, Scan, Err, Close |
sql.ErrNoRows | Error from Row.Scan when no row was returned |
| NULL handling | Representing SQL NULL in Go with pointers or Null types |
sql.NullString | Typed nullable string with Valid flag |
sql.Null[T] | Generic nullable wrapper (Go 1.22) |
| Placeholder | Parameter marker in SQL: $1 (PostgreSQL), ? (MySQL) |
| SQL injection | User input interpreted as SQL because it was concatenated into the text |
| Prepared statement | Server-side parsed statement in one session, executed with parameters |
*sql.Stmt | database/sql handle that prepares itself on each connection it runs on |
| Implicit per-connection prepare | database/sql preparing each statement when the driver lacks QueryerContext |
| Statement cache | pgx per-connection LRU of prepared statements (stmtcache_..., 512 entries) |
QueryExecMode | pgx setting: cache_statement, cache_describe, describe_exec, exec, simple_protocol |
| Simple protocol | PostgreSQL query protocol with values interpolated into one string |
| Extended protocol | Parse/Bind/Execute messages with separate parameters |
| Transaction | Group of statements committed or rolled back together on one connection |
BeginTx | Starts a transaction with TxOptions (isolation, read-only) |
| Isolation level | Promise about what concurrent transactions can see (LevelSerializable etc.) |
| Commit/Rollback | End a transaction, keeping or discarding its changes |
| Defer Rollback pattern | defer tx.Rollback() right after BeginTx, harmless after Commit |
sql.ErrTxDone | Error from a Tx that is already committed or rolled back |
| Savepoint | Named point inside a transaction; pgx's nested Begin uses them |
| Serialization failure | SQLSTATE 40001: the transaction must be retried |
| Deadlock | SQLSTATE 40P01: a lock cycle; one transaction is aborted |
| Context cancellation behaviour | What database/sql and the driver do when ctx ends |
| Cancel request | PostgreSQL protocol message asking a backend to cancel its current statement |
| pgx v5 native API | Using pgx directly instead of through database/sql |
pgx.Conn | One pgx connection, not concurrency-safe |
pgxpool.Pool | pgx's concurrency-safe connection pool |
pgxpool.Config | Pool settings: MaxConns, lifetimes, health check, hooks |
MaxConns | pgxpool size cap; default max(4, NumCPU) |
| Health check | pgxpool background check of idle connections (HealthCheckPeriod) |
AfterConnect | pgxpool hook run once per new connection |
| Connection string / DSN | URL or key=value text with host, user, database and options |
CollectRows | pgx generic helper collecting rows into a slice |
RowToStructByName | pgx row mapper matching columns to struct fields by name |
| Named args | pgx.NamedArgs: @name placeholders rewritten to $n |
| Batch | pgx.Batch: several statements in one round trip |
CopyFrom | pgx bulk load through the COPY protocol |
| COPY | PostgreSQL bulk load/unload command and protocol |
| unnest | PostgreSQL function expanding arrays to rows; used for bulk insert |
| Bulk insert | Inserting many rows with few statements |
| LISTEN/NOTIFY | PostgreSQL publish/subscribe between sessions, delivered on commit |
| pgtype | pgx package mapping PostgreSQL types to Go |
| Timeouts | Client ctx deadlines and server limits (statement_timeout, lock_timeout) |
statement_timeout | PostgreSQL limit on statement duration (57014) |
lock_timeout | PostgreSQL limit on waiting for a lock (55P03) |
idle_in_transaction_session_timeout | Kills sessions idle inside an open transaction |
| Error inspection | Using errors.Is/errors.As to classify errors |
pgconn.PgError | pgx error type carrying the server's SQLSTATE, message and constraint |
| SQLSTATE | Five-character standard error code |
| PgBouncer | Lightweight PostgreSQL connection pooler |
| Transaction pooling | Pooler mode lending a server connection per transaction |
max_prepared_statements | PgBouncer 1.21+ setting that tracks protocol-level prepared statements |
| Repository pattern | Persistence interface per aggregate that hides SQL from the domain |
| Interface per aggregate | One repository interface per aggregate root, defined by its consumer |
DBTX | Interface satisfied by *sql.DB, *sql.Tx and *sql.Conn |
| Tx propagation | Sharing one transaction across repositories (context or unit of work) |
| Unit of work | Object that runs a function with repositories bound to one transaction |
| Optimistic concurrency | version column checked in UPDATE ... WHERE version = $n |
| Outbox | Table of events written in the same transaction as the state change |
| sqlc | Generator of typed Go code from SQL queries |
| squirrel / goqu | Go SQL query builders |
| GORM / ent / bun | Go ORMs: full-featured, schema-as-code, SQL-first |
| Migrations | Versioned schema changes applied in order |
| golang-migrate / goose / Atlas / tern | Go-ecosystem migration tools |
| N+1 | One query for a list plus one per item |
| pgx mock | pgxmock, a mock implementing pgx interfaces |
| sqlmock | go-sqlmock, a mock database/sql driver |
| Fake driver | Small in-test database/sql driver that records calls |
| Real DB test | Repository test against a real PostgreSQL (container or CI service) |
| testcontainers / dockertest | Libraries that start database containers for tests |
| Observability | Traces, metrics and logs for the data layer |
| otelsql | OpenTelemetry wrapper for database/sql |
| pgx tracer | pgx.QueryTracer and friends set on ConnConfig.Tracer |
| otelpgx | OpenTelemetry tracer for pgx |
References
database/sqlsource and doc comments (Go 1.27): https://go.dev/src/database/sql/sql.godatabase/sql/driversource: https://go.dev/src/database/sql/driver/driver.go- Go docs, "Accessing relational databases": https://go.dev/doc/database/
- Go docs, "Opening a database handle": https://go.dev/doc/database/open-handle
- Go docs, "Managing connections": https://go.dev/doc/database/manage-connections
- Go docs, "Querying for data": https://go.dev/doc/database/querying
- Go docs, "Executing SQL statements that don't return data": https://go.dev/doc/database/change-data
- Go docs, "Using prepared statements": https://go.dev/doc/database/prepared-statements
- Go docs, "Executing transactions": https://go.dev/doc/database/execute-transactions
- Go docs, "Canceling in-progress operations": https://go.dev/doc/database/cancel-operations
- Go docs, "Avoiding SQL injection risk": https://go.dev/doc/database/sql-injection
- Go wiki, SQLInterface: https://go.dev/wiki/SQLInterface
- Go wiki, SQLDrivers: https://go.dev/wiki/SQLDrivers
- Go 1.8 release notes: https://go.dev/doc/go1.8
- Go 1.10 release notes: https://go.dev/doc/go1.10
- Go 1.13 release notes: https://go.dev/doc/go1.13
- Go 1.15 release notes: https://go.dev/doc/go1.15
- Go 1.17 release notes: https://go.dev/doc/go1.17
- Go 1.22 release notes (
Null[T]): https://go.dev/doc/go1.22 - Go API files (
api/go1.txt,go1.6.txt,go1.10.txt): https://raw.githubusercontent.com/golang/go/master/api/go1.6.txt - pgx repository and README: https://github.com/jackc/pgx
- pgx v5.8.0
doc.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/doc.go - pgx v5.8.0
conn.go(QueryExecMode,ParseConfig): https://raw.githubusercontent.com/jackc/pgx/v5.8.0/conn.go - pgx v5.8.0
rows.go(CollectRows,RowToStructByName): https://raw.githubusercontent.com/jackc/pgx/v5.8.0/rows.go - pgx v5.8.0
named_args.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/named_args.go - pgx v5.8.0
batch.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/batch.go - pgx v5.8.0
copy_from.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/copy_from.go - pgx v5.8.0
tx.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/tx.go - pgx v5.8.0
tracer.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/tracer.go - pgx v5.8.0
pgxpool/pool.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/pgxpool/pool.go - pgx v5.8.0
pgxpool/doc.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/pgxpool/doc.go - pgx v5.8.0
stdlib/sql.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/stdlib/sql.go - pgx v5.8.0
pgconn/errors.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/pgconn/errors.go - pgx v5.8.0
pgconn/pgconn.go: https://raw.githubusercontent.com/jackc/pgx/v5.8.0/pgconn/pgconn.go - pgx CHANGELOG (current): https://raw.githubusercontent.com/jackc/pgx/master/CHANGELOG.md
- pgx wiki, Getting started: https://github.com/jackc/pgx/wiki/Getting-started-with-pgx
- pgx wiki, Error Handling: https://github.com/jackc/pgx/wiki/Error-Handling
- pgx wiki, Automatic Prepared Statement Caching: https://github.com/jackc/pgx/wiki/Automatic-Prepared-Statement-Caching
- PostgreSQL, Transaction Isolation: https://www.postgresql.org/docs/current/transaction-iso.html
- PostgreSQL, PREPARE: https://www.postgresql.org/docs/current/sql-prepare.html
- PostgreSQL, Error Codes (Appendix A): https://www.postgresql.org/docs/current/errcodes-appendix.html
- PostgreSQL, COPY: https://www.postgresql.org/docs/current/sql-copy.html
- PostgreSQL, Populating a Database: https://www.postgresql.org/docs/current/populate.html
- PostgreSQL, LISTEN: https://www.postgresql.org/docs/current/sql-listen.html
- PostgreSQL, NOTIFY: https://www.postgresql.org/docs/current/sql-notify.html
- PostgreSQL, Client Connection Defaults (
statement_timeout,lock_timeout): https://www.postgresql.org/docs/current/runtime-config-client.html - PostgreSQL, Connection strings: https://www.postgresql.org/docs/current/libpq-connect.html
- PostgreSQL, Array functions (
unnest): https://www.postgresql.org/docs/current/functions-array.html - PostgreSQL, Message flow (cancel requests): https://www.postgresql.org/docs/current/protocol-flow.html
- PostgreSQL, Message formats (Bind): https://www.postgresql.org/docs/current/protocol-message-formats.html
- PgBouncer, Features (pooling modes, feature table): https://www.pgbouncer.org/features.html
- PgBouncer, Configuration (
max_prepared_statements): https://www.pgbouncer.org/config.html - PgBouncer, Changelog (1.21.0, 1.24.0): https://www.pgbouncer.org/changelog.html
- lib/pq README (current): https://raw.githubusercontent.com/lib/pq/master/README.md
- lib/pq README v1.10.9 (maintenance-mode notice): https://raw.githubusercontent.com/lib/pq/v1.10.9/README.md
- go-sql-driver/mysql README: https://raw.githubusercontent.com/go-sql-driver/mysql/master/README.md
- sqlc README: https://raw.githubusercontent.com/sqlc-dev/sqlc/main/README.md
- sqlc, Getting started with PostgreSQL: https://docs.sqlc.dev/en/latest/tutorials/getting-started-postgresql.html
- sqlc, Using transactions: https://docs.sqlc.dev/en/latest/howto/transactions.html
- sqlc, Configuration reference: https://docs.sqlc.dev/en/latest/reference/config.html
- golang-migrate README: https://raw.githubusercontent.com/golang-migrate/migrate/master/README.md
- goose README: https://raw.githubusercontent.com/pressly/goose/main/README.md
- tern README: https://raw.githubusercontent.com/jackc/tern/master/README.markdown
- Atlas: https://atlasgo.io/getting-started
- squirrel README: https://raw.githubusercontent.com/Masterminds/squirrel/master/README.md
- goqu README: https://raw.githubusercontent.com/doug-martin/goqu/master/README.md
- sqlx README: https://raw.githubusercontent.com/jmoiron/sqlx/master/README.md
- bun README: https://raw.githubusercontent.com/uptrace/bun/master/README.md
- GORM guides: https://gorm.io/docs/
- ent, Getting started: https://entgo.io/docs/getting-started
- otelsql README: https://raw.githubusercontent.com/XSAM/otelsql/main/README.md
- otelpgx README: https://raw.githubusercontent.com/exaring/otelpgx/main/README.md
- pgxmock README: https://raw.githubusercontent.com/pashagolub/pgxmock/master/README.md
- go-sqlmock README: https://raw.githubusercontent.com/DATA-DOG/go-sqlmock/master/README.md
- ory/dockertest README: https://raw.githubusercontent.com/ory/dockertest/v3/README.md
- Testcontainers for Go, Postgres module: https://golang.testcontainers.org/modules/postgres/
- pgx v5.8.0
pgxpool/stat.go(EmptyAcquireCount,AcquireDuration,CanceledAcquireCount): https://raw.githubusercontent.com/jackc/pgx/v5.8.0/pgxpool/stat.go - PostgreSQL source,
postgres.c(timeout, cancel and aborted-transaction messages): https://raw.githubusercontent.com/postgres/postgres/master/src/backend/tcop/postgres.c - PostgreSQL source,
prepare.c(prepared statement "%s" does not exist): https://raw.githubusercontent.com/postgres/postgres/master/src/backend/commands/prepare.c - PostgreSQL source,
plancache.c(cached plan must not change result type): https://raw.githubusercontent.com/postgres/postgres/master/src/backend/utils/cache/plancache.c - PostgreSQL, Connections and Authentication (
max_connections): https://www.postgresql.org/docs/current/runtime-config-connection.html - Oracle Database SQL Language Reference, Nulls: https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/Nulls.html
- SQLite, SQL expressions (parameters): https://www.sqlite.org/lang_expr.html
- go-mssqldb README (
@p1,@Name): https://raw.githubusercontent.com/microsoft/go-mssqldb/main/README.md - godror README: https://raw.githubusercontent.com/godror/godror/main/README.md
- lib/pq
conn.go(watchCancel,sendCancelRequest): https://raw.githubusercontent.com/lib/pq/master/conn.go - CockroachDB, Transactions (default SERIALIZABLE, 40001 retries): https://www.cockroachlabs.com/docs/stable/transactions
- Laravel 13, Database: Getting Started (transactions, pooled PostgreSQL connections): https://laravel.com/docs/13.x/database