Skip to content

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/sql package source, type DB doc 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 forGo to
The tables you can memorise in one minuteEverything in one minute
Why a pool, why a driver interfaceWhy it exists
History, version by versionWhere it comes from
A bad repository and its fixGo
sql.Open lazy, DB is a pool, PingOpening a database
SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTimePool knobs
Drivers: pgx stdlib, lib/pq legacy, go-sql-driver/mysqlDrivers
QueryContext/QueryRowContext/ExecContext and rows.Next/Scan/Err/CloseQuerying
sql.ErrNoRowsNo rows
NULL handling: sql.NullString, sql.Null[T] 1.22, pointersNULLs
placeholders $1 vs ? and SQL injectionPlaceholders
prepared statements, Stmt, implicit per-connection preparePrepared statements
pgx statement cache modes (QueryExecMode)pgx statement cache
transactions, BeginTx, isolation levels, Commit/Rollback, defer Rollback patternTransactions
retries on serialization failure 40001Retrying a transaction
context cancellation behaviour, pgx cancel requestCancellation
pgx v5 native API: pgx.Conn, pgxpool.PoolNative pgx
CollectRows, RowToStructByName, named argsCollecting rows
batch, CopyFrom, COPY, unnest, bulk insertBatches and bulk
LISTEN/NOTIFYLISTEN/NOTIFY
pgtype, custom types, AfterConnectTypes
pgxpool config, MaxConns, health check, connection string/DSNpgxpool config
timeouts: statement_timeout, lock_timeoutTimeouts
error inspection: pgconn.PgError, SQLSTATEErrors
PgBouncer transaction mode and prepared statementsPgBouncer
repository pattern, interface per aggregateRepository pattern
tx propagation via context or UnitOfWorkSharing a transaction
sqlc for typed queries, squirrel/goqu builders, GORM/ent/bun trade-offssqlc, builders, ORMs
migrations: golang-migrate, goose, atlas, ternMigrations
N+1 in GoN+1
testing: fake driver, pgx mock, real DB, dockertest/testcontainers pointerTesting
observability: otelsql, pgx tracer, pool statsObservability
Internals and exact error textsMechanics
Bugs and fixesSolving the classic problems
What to use whenChoosing
Monolith to distributed systemIn architecture
Reproduce itLab
Eloquent and PDO next to GoFor PHP/Laravel developers

Everything in one minute ​

The database/sql objects. Each row is unpacked in the concept catalogue.

TypeWhat it isLifetimeConcurrency-safeHolds a connection
*sql.DBA pool of connections plus a driverWhole process; open onceYesBorrows one per call
*sql.ConnOne pinned connectionUntil CloseNot for concurrent statementsYes, until Close
*sql.TxOne transactionUntil Commit or RollbackNoYes, the whole time
*sql.StmtA prepared statementUntil CloseYesPrepared lazily on each connection used
*sql.RowsA result cursorUntil Close or the last NextNoYes, until closed
*sql.RowResult of QueryRowContextUntil ScanNoReleased by Scan

The calls you use every day.

CallReturnsUse forMust do afterwards
db.QueryContext(ctx, q, args...)*sql.Rows, errorMany rowsdefer rows.Close(), loop Next, check rows.Err()
db.QueryRowContext(ctx, q, args...)*sql.RowZero or one row.Scan(...); sql.ErrNoRows when empty
db.ExecContext(ctx, q, args...)sql.Result, errorINSERT/UPDATE/DELETE/DDLRowsAffected() if it matters
db.BeginTx(ctx, opts)*sql.Tx, errorSeveral statements, one unitdefer tx.Rollback(), then tx.Commit()
db.PrepareContext(ctx, q)*sql.Stmt, errorOne hot statement reusedstmt.Close() on shutdown
db.PingContext(ctx)errorStartup and readiness checksNothing

The same work in pgx v5 native.

database/sqlpgx v5Difference
sql.Open("pgx", dsn)pgxpool.New(ctx, dsn)Both lazy; pgxpool returns "without waiting for any connections"
db.QueryContext + looppool.Query + pgx.CollectRows(rows, pgx.RowToStructByName[T])Collect closes rows and checks errors
sql.NullString*string or pgtype.Textpgx maps NULL to nil pointers
?/$1 only$1 or @name with pgx.NamedArgsNamed args rewritten client-side
tx.Commit()tx.Commit(ctx)pgx methods take ctx
not availablepool.SendBatch, pool.CopyFrom, conn.WaitForNotificationPostgreSQL-only features
sql.ErrNoRowspgx.ErrNoRowsWraps sql.ErrNoRows since pgx 5.7.0

The errors you will read in logs.

TextMeaningWhat to do
sql: no rows in result setsql.ErrNoRows from Row.ScanMap to a domain "not found"
sql: transaction has already been committed or rolled backsql.ErrTxDoneExpected from a deferred Rollback; a bug anywhere else
context deadline exceededYour 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 SerializableRetry the whole transaction
ERROR: duplicate key value violates unique constraint "users_email_key" (SQLSTATE 23505)Unique violationMap the constraint to a 409
ERROR: canceling statement due to statement timeout (SQLSTATE 57014)statement_timeout firedFix the query or raise the limit for that job
ERROR: prepared statement "stmtcache_..." does not exist (SQLSTATE 26000)Statement cache behind a transaction-mode poolerSee PgBouncer
sql: Scan error on column index 0, name "phone": converting NULL to string is unsupportedNULL scanned into a plain stringUse 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/sqlNative pgx
One API for every database; libraries expect itPostgreSQL only
Pool in the standard librarypgxpool (built on puddle)
Types limited to driver.Value plus Scanner/ValuerAbout 70 PostgreSQL types via pgtype, binary format
No COPY, no batch, no LISTENCopyFrom, SendBatch, WaitForNotification
Statement handling up to the driverAutomatic 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 ​

  1. "sql.Open connects to the database." It "may just validate its arguments without creating a connection"; the first query or Ping dials. A wrong password shows up on the first request unless you PingContext at startup.
  2. "I should open and close a *sql.DB per request." *sql.DB is 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.
  3. "defer tx.Rollback() will undo my committed transaction." After a successful Commit the deferred Rollback returns sql.ErrTxDone and 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.

go
// 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).

go
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.

go
// 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.

go
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 ​

your repositories and servicesORM: GORM, ent, bunbuilders: squirrel, goqusqlc generated codeemits database/sql or pgx/v5hand-written SQL$1 placeholdersdatabase/sql (*sql.DB pool)portable; driver.Conn interfacespgx v5 native: pgxpool.PoolCopyFrom, Batch, LISTEN, pgtypepgx/v5/stdliblib/pq, mysqlpgx.Conn on pgconn (wire protocol)TCP / TLS to PostgreSQL (optionally through PgBouncer)dashed: stdlib.OpenDBFromPool and (*sql.Conn).Raw bridge the two paths

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 released

Real 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.

ConstructorDials?Config fromWhen to use
sql.Open("pgx", dsn)NoDSN stringDefault with pgx stdlib or lib/pq
sql.OpenDB(connector)NoA driver.ConnectorConfig built in code (stdlib.GetConnector)
stdlib.OpenDB(connConfig)Nopgx.ConnConfigNeed a tracer or TLS config not expressible in a DSN
stdlib.OpenDBFromPool(pool)NoExisting pgxpool.PoolOne pool, both APIs
pgxpool.New(ctx, dsn)No ("returns without waiting")DSNNative pgx
pgx.Connect(ctx, dsn)Yes, one connectionDSNScripts, 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.

go
// 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:

KnobDefaultDoc saysTypical 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 largerEqual 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 = neverGo 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 SQL

Real 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()MeaningChange
WaitCount and WaitDuration growingCallers queue for a connectionShorter queries/transactions first, then a larger MaxOpen
InUse == MaxOpenConnections for long periodsSaturated or leaked (unclosed rows, long tx)Look for missing rows.Close, long transactions
MaxIdleClosed highIdle cap too small: connections churnRaise MaxIdle towards MaxOpen
MaxLifetimeClosed steadyRecycling as configuredFine
OpenConnections far below MaxOpenPool larger than neededLower 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.

go
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())
	}
}
goroutinesQueryContextExecContextBeginTx (pins one)caller #MaxOpen+1*sql.DB = a poolin use: at most MaxOpenConns(default 0 = unlimited)wait queue (connRequests)WaitCount; ctx ends the waitidle list: MaxIdleConns(default 2)PostgreSQL backendsbackend process 1backend process 2backend process 3closedMaxIdleTime / MaxLifetimesql.Open creates no connection; the first query or Ping dials one.Rows not closed keep a connection "in use" until Close or EOF.

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.Conn

Real 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.

DriverName in sql.OpenPlaceholdersStatus / 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"$1Long 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"?, $1Pure Go vs cgo
github.com/microsoft/go-mssqldb"sqlserver"@p1SQL 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 pool

Real 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.

NeedCallNotes
Many rowsQueryContextdefer rows.Close(), check rows.Err()
One rowQueryRowContext(...).Scan(...)Row.Err() (Go 1.15) to check without scanning
INSERT ... RETURNINGQueryRowContextScan the returned columns
No rows returnedExecContextResult.RowsAffected(); LastInsertId is not supported by PostgreSQL drivers
Huge resultQueryContext + streamingDo not collect into a slice; see Cursors & Streaming
Multiple result setsrows.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 404

Real 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).

SituationResultMap to
QueryRowContext finds nothingsql.ErrNoRows at ScanDomain ErrNotFound
QueryContext finds nothingNo error, zero iterationsEmpty slice
UPDATE matches nothingRowsAffected() == 0Not found or version conflict
pgx CollectOneRow finds nothingpgx.ErrNoRows (errors.Is sql.ErrNoRows)Domain ErrNotFound
pgx CollectExactlyOneRow finds twopgx.ErrTooManyRowsBug 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 unsupported

Real 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.

StyleScanJSONAllocationBest for
sql.NullString etc.YesObject {"String":..,"Valid":..}NoneOlder code, sqlc with database/sql default
sql.Null[T] (1.22)YesObject {"V":..,"Valid":..}NoneAny type, including your own
*T pointerYesnull or valueOne per non-NULL valueAPI structs, pgx, sqlc with emit_pointers_for_null_types
pgtype.Text, pgtype.Int8Yes (pgx)Implements JSONNoneNative pgx code
COALESCE in SQLn/an/aNoneWhen 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.

go
// 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 != ""}
}
go
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 / driverPlaceholderNamedNotes
PostgreSQL / pgx stdlib, lib/pq$1No (pgx native: @name with NamedArgs)$1 may repeat in the text
MySQL / go-sql-driver/mysql?NointerpolateParams option
SQLite / modernc, mattn?, ?NNN, :AAAA, @AAAA, $AAAA (SQLite expression docs)Yes, sql.NamedPlain ? "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..#3

Real 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 *.

WayWho preparesWhere it livesCost
db.QueryContext with pgx stdlibpgx statement cacheEach connection, LRU of 5121 extra round trip on first use per connection
db.QueryContext with a driver implementing neither QueryerContext nor Queryerdatabase/sqlPrepared and closed per call2–3 round trips every call
db.PrepareContext → *sql.Stmtdatabase/sqlLazily on every connection usedPrepare per connection; must Close
tx.PrepareContextdatabase/sqlThe tx's connectionClosed at Commit/Rollback
SQL PREPARE name AS ...YouThe sessionBreaks 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.

go
// 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(&cents)
	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()
}
go
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 tripsNamed statementRisk / limit
QueryExecModeCacheStatement (cache_statement, default)1 after first useYes, 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 useNo (caches the description)Same schema-change caveat
QueryExecModeDescribeExec (describe_exec)2No (unnamed statement)"may cause problems with connection poolers that switch the underlying connection between round trips"
QueryExecModeExec (exec)1NoTypes inferred from Go values; text format; ambiguous types (map[string]string) rejected
QueryExecModeSimpleProtocol (simple_protocol)1NoClient-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-prepares

Real 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 pool

Real 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.

Optiondatabase/sqlpgx nativePostgreSQL statement
Default levelnil or LevelDefaultpgx.TxOptions{}BEGIN (server default, usually Read Committed)
Repeatable ReadLevelRepeatableReadpgx.RepeatableReadBEGIN ISOLATION LEVEL REPEATABLE READ
SerializableLevelSerializablepgx.SerializableBEGIN ISOLATION LEVEL SERIALIZABLE
Read onlyReadOnly: trueAccessMode: pgx.ReadOnlyREAD ONLY
Deferrablenot availableDeferrableMode: pgx.DeferrableDEFERRABLE (serializable read-only)
Savepointtx.ExecContext("SAVEPOINT s1")tx.Begin(ctx)SAVEPOINT
MySQL InnoDBTxOptions.Isolationn/aSET 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.

go
// 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)
}
BeginTx(ctx, opts)pins one connectiondefer tx.Rollback()tx.ExecContext ...tx.Commit()COMMITconn backto the poolROLLBACKerror, panic, or ctx canceledSQLSTATE 40001 / 40P01roll back, back off, run the whole fn againretry loop (bounded attempts, ctx budget)deferred Rollback after a successful Commit is a no-op: it returns sql.ErrTxDoneall statements must use tx, not db: db.ExecContext inside the function runs outside the transactiona Commit that times out has an unknown outcome: read back or use an idempotency key

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 ok

Real 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.

ErrorSQLSTATERetry the transaction?Why
Serialization failure40001Yes, with backoffThe contract of RR/Serializable
Deadlock detected40P01Yes, and fix lock orderOne victim was chosen
Unique violation, key from the client23505NoSame input, same result
Unique violation, key derived in the tx (Serializable)23505Yes, a bounded full retryOverlapping Serializable transactions; the retry reads again
Lock not available55P03Maybe, after backofflock_timeout or NOWAIT
Query canceled57014Only if the overall budget remainsstatement_timeout or a cancel
Connection failure08006Only if the commit outcome is knownA lost COMMIT may have succeeded
context.Canceledn/aNoThe 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.

go
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 it

Real 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).

DriverOn ctx cancelConnection afterwards
pgx v5 default (DeadlineContextWatcherHandler)Socket deadlineClosed
pgx v5 with CancelRequestContextWatcherHandlerCancelRequest to the serverKept if the cancel lands
lib/pqCancel request (sendCancelRequest in watchCancel)Marked bad ("so it does not get reused")
go-sql-driver/mysqlCloses the connection (no KILL QUERY)Closed
Any driver, waiting for a pool slotdatabase/sql stops waitingn/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)                            released

Real 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.

Featuredatabase/sql + pgx stdlibpgx native
Pool*sql.DB*pgxpool.Pool
Collect into structsManual Scan (or sqlx/scany)CollectRows + RowToStructByName
Named argsNopgx.NamedArgs, pgx.StrictNamedArgs
BatchNoSendBatch
COPYOnly via RawCopyFrom
LISTEN/NOTIFYOnly via RawWaitForNotification
Arrays, ranges, jsonbVia pgtype.Map.SQLScanner; direct on Go 1.27 with pgx ≥ 5.11Native
Tracing hookWrapper 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.

go
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 closed

Real 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:"-".

FunctionRows expectedMappingError when
CollectRows(rows, RowTo[int32])0..nSingle columnScan error
CollectRows(rows, RowToStructByName[T])0..nBy name / db tagMissing column or field
CollectRows(rows, RowToStructByNameLax[T])0..nBy name, struct may have moreUnknown column
CollectRows(rows, RowToStructByPos[T])0..nBy positionCount mismatch
CollectOneRowfirst rowanyErrNoRows
CollectExactlyOneRowexactly 1anyErrNoRows, 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.

go
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 RETURNING

Real 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).

TechniqueRound tripsON CONFLICT / RETURNINGWorks through database/sqlLimit
Loop of INSERTnYesYesLatency × n
Multi-row VALUES⌈n·cols/65535⌉YesYes65535 params, new SQL text per size
unnest arrays1YesYes (pgx stdlib passes slices)Memory for the arrays
pgx.Batch1YesNoImplicit transaction: all or nothing
CopyFrom1 streamNo (use a staging table)Only via RawTriggers 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).

go
// 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 again

Real 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.

go
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)
	}
}
go
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.

PostgreSQLGo (pgx native)Through database/sql
text, varcharstring, *string, pgtype.Textstring, sql.NullString
bigintint64, pgtype.Int8int64, sql.NullInt64
numericpgtype.Numeric, decimal adaptersstring
timestamptztime.Time, pgtype.Timestamptztime.Time
uuid[16]byte, pgtype.UUID, uuid adaptersstring
jsonbany JSON-marshallable value[]byte
bigint[][]int64pgtype.Map.SQLScanner(&a)
inet / cidrnetip.Addr / netip.Prefixstring
enumstring after LoadTypestring

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.

SettingDSN keyDefaultMeaning
MaxConnspool_max_connsmax(4, NumCPU)Hard cap
MinConnspool_min_conns0Floor kept open
MinIdleConnspool_min_idle_conns0Idle floor ("superior to MinConns" for tail latency)
MaxConnLifetimepool_max_conn_lifetime1 hClose after this age
MaxConnLifetimeJitterpool_max_conn_lifetime_jitter0Spread closes so they do not all happen at once
MaxConnIdleTimepool_max_conn_idle_time30 minClose idle connections (by the health check)
HealthCheckPeriodpool_health_check_period1 minBackground check of idle connections
PingTimeoutpool_ping_timeout (5.11+)0 = nonePing limit when a connection is acquired
ShouldPingcode onlyping if idle > 1 sLiveness check on acquire
AfterConnectcode onlynilPer-connection setup: types, SET
PrepareConn / AfterRelease / BeforeClosecode onlynilAcquire/release hooks (BeforeAcquire is deprecated)
ConnConfig.ConnectTimeoutconnect_timeoutnoneDial + startup limit
ConnConfig.Tracercode onlynilQuery 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 MinConns

Real 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.

go
// 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
}
go
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 ALTER

Real 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.

LayerKnobProtects againstError
Goctx deadline on each callWaiting forever (pool or query)context deadline exceeded
pgx dialconnect_timeout / ConnectTimeoutUnreachable hostdial timeout
PostgreSQLstatement_timeoutLong statements57014 "canceling statement due to statement timeout"
PostgreSQLlock_timeoutWaiting for locks55P03 "canceling statement due to lock timeout"
PostgreSQLidle_in_transaction_session_timeoutLeaked open transactionsSession terminated
PostgreSQLtransaction_timeoutWhole long transactionsSession terminated
PgBouncerquery_timeout, server_idle_timeoutPooler-level limitsClient 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 409

Real 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.

SQLSTATENameTypical causeGo reaction
23505unique_violationDuplicate key409, or ON CONFLICT
23503foreign_key_violationMissing parent / child exists422
23502not_null_violationMissing valueBug or 422
23514check_violationCHECK (balance >= 0)422 / business error
40001serialization_failureRR/Serializable conflictRetry the tx
40P01deadlock_detectedLock cycleRetry, fix order
55P03lock_not_availablelock_timeout, NOWAITBack off
57014query_canceledstatement_timeout, cancel requestTimeout handling
25P02in_failed_sql_transactionStatement after an error in a txBug: roll back first
26000invalid_sql_statement_namePrepared statement missing (poolers)PgBouncer
42P05duplicate_prepared_statementSame name prepared twice on a sessionPoolers, manual PREPARE
53300too_many_connectionsmax_connections reachedSmaller pools, a pooler
57P01admin_shutdownServer restart / failoverReconnect, retry idempotent work
08006connection_failureNetworkRetry only if safe
42601 / 42P01 / 42703syntax_error / undefined_table / undefined_columnBad SQL, missing migrationBug

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.

go
// 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
}
go
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_statement

Real 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.

Setuppgx DefaultQueryExecModeWorks?Notes
Direct to PostgreSQLcache_statement (default)YesFastest
PgBouncer session modecache_statementYesFewer savings from pooling
PgBouncer ≥ 1.21, transaction mode, max_prepared_statements > 0cache_statementYes, per PgBouncer docsNot in pgx's docs; test it; RECONNECT after type-changing migrations
PgBouncer transaction mode, no statement trackingexec or simple_protocolYesexec keeps parameters separate
Any transaction poolern/aLISTEN, SET, session advisory locks: neverUse 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.

Go service (pgx)tx 1: Parse stmtcache_1then Bind/Executetx 2: Bind stmtcache_1(cached, no Parse)PgBouncerpool_mode =transactionserver conn Ahas stmtcache_1server conn Bno such statement: 26000fixesPgBouncer 1.21+: max_prepared_statements > 0 (default 200 since 1.24) re-prepares on Bor pgx DefaultQueryExecMode = QueryExecModeExec / QueryExecModeSimpleProtocolor session pooling; LISTEN and SET never work in transaction pooling

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
             COMMIT

Real 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 choiceRecommendedAvoid
GranularityOne repository per aggregate rootOne per table
SignaturesDomain types, ctx first*sql.Rows, map[string]any, sql.NullString
ErrorsErrNotFound, ErrConflictsql.ErrNoRows, raw *pgconn.PgError
Where the interface livesIn the consumer packageNext to the implementation "just in case"
Concurrency controlversion column or SELECT ... FOR UPDATELast write wins
QueriesExplicit columns, batched child loadsSELECT *, 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.

go
// 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)+`}`))
	})
}
go
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#1

Real 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).

ApproachHow the tx travelsProsCons
Tx in contextcontext.WithValue(ctx, txKey{}, tx)No signature changes; nested calls joinImplicit; easy to call without a tx
Unit of workDo(ctx, func(Repos) error)Explicit; compile-time clarityMore plumbing; repositories built per call
sqlc WithTxq.WithTx(tx) returns bound queriesGenerated, explicitOne Queries per tx
Pass DBTX parameterSave(ctx, q DBTX, o)Very explicitPersistence 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.

go
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 changes

Real 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.

ToolStyleType safetySees the SQLTrade-off
Hand-written + database/sql/pgxSQL stringsAt runtime (Scan)FullyBoilerplate; CollectRows helps
sqlcSQL → generated GoCompile timeFullyDynamic queries are awkward
squirrel / goquBuilderPartialVia ToSql()Dynamic filters easy; another DSL
sqlx / scanyScanning helpersRuntimeFullySmall; no codegen
bunSQL-first ORMPartialMostlyLighter than GORM
GORMFull ORMRuntime, reflectionHidden by defaultFast CRUD; N+1 and surprise queries (ORM Pitfalls)
entSchema-as-code ORMCompile time (generated)HiddenStrong 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.

ToolFormatDeclarative diffGo APINotes
golang-migrateNNN_name.up.sql / .down.sqlNoYesMany databases; "dirty" state on failure
goose-- +goose Up SQL, or Go functionsNoYes (*sql.DB)Embeddable with embed.FS
AtlasHCL or SQL schema, versioned dirsYesCLI-firstLint and diff in CI
ternSQL with templates, Go migrationsNoYes (migrate package, pgx)PostgreSQL only
sqlcreads a schema directoryn/an/aPoint 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)
FixQueriesWhen
= ANY($1) with ids2Default
JOIN + group in Go1Small child sets
json_agg / array_agg1Read models, APIs that return nested JSON
pgx.Batch1 round tripDifferent queries per parent
GraphQL dataloader1 per levelGraphQL resolvers (GraphQL in Go)
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:

LayerToolProvesCost
Service logicIn-memory fake implementing the repository interfaceBusiness rules, tx boundaries calledMilliseconds
database/sql behaviourA tiny fake driver (this page's internal/fakedb)Pool, rows, tx call orderMilliseconds
Driver interactiongo-sqlmock, pgx mock (pgxmock)Expected SQL text and args; error pathsMilliseconds, brittle
Repository SQLReal DB: testcontainers-go postgres module, ory/dockertest, or a CI service containerSQL, constraints, isolation, migrationsSeconds per package
Isolation per testTransaction rolled back per test, or a template database per packageNo leakage between testsLow
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 test

Real 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
SignalSourceAlert when
Query latency p99Tracer / otelsql histogramAbove budget
Pool wait count / acquire timedb.Stats().WaitCount, pool.Stat().EmptyAcquireCountRising
In-use == maxInUse, AcquiredConnsSustained
Errors by SQLSTATEClassifier + counter40001 bursts, 53300 any
Long transactionspg_stat_activity (state = 'idle in transaction')Older than seconds
go
// 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 connection

A *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 ​

TextSource
sql: no rows in result setsql.ErrNoRows
sql: transaction has already been committed or rolled backsql.ErrTxDone
sql: connection is already closedsql.ErrConnDone
sql: Scan error on column index 0, name "phone": converting NULL to string is unsupportedRows.Scan (real output)
no rows in result setpgx.ErrNoRows (wraps sql.ErrNoRows)
too many rows in result setpgx.ErrTooManyRows
tx is closedpgx.ErrTxClosed
commit unexpectedly resulted in rollbackpgx.ErrTxCommitRollback
conn busypgconn: one *pgx.Conn used by two goroutines
cannot find field customer_id in returned rowRowToStructByName (real output)
extended protocol limited to 65535 parameterspgconn (%v = math.MaxUint16)
failed to connect to ... dial error: dial tcp 127.0.0.1:1: connect: connection refusedpgxpool 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 typePrepared statement after a schema change

Solving the classic problems ​

BugSymptomFixCost
sql.Open per requestConnection churn, 53300One pool in mainNone
No PingContext at startupFirst request fails after a bad deployPing with a timeoutOne call
Unlimited MaxOpenConnsServer overload at peaksBudget per instanceSome queueing
Unclosed RowsPool exhaustion, WaitCount climbsdefer rows.Close()None
Ignoring rows.Err()Truncated resultsCheck after the loopNone
String-built SQLInjectionPlaceholders, allow-listsNone
Statements outside the txPartial writes, deadlocksUse tx everywhere; a helperDiscipline
No rollback on errorLocks held until timeoutdefer tx.Rollback()None
Retrying one statement25P02Retry the whole transaction on 40001/40P01Idempotent fn
HTTP call inside a txLong transactions, locksOutbox, call after commitExtra table
SELECT * + statement cacheError after migrationsExplicit column listsTyping
Cache behind transaction pooler26000 / 42P05QueryExecModeExec or PgBouncer ≥ 1.21 trackingSlightly more planning
N+1Latency grows with page size= ANY($1), batchNone
Matching error messagesBreaks on upgrades/localeserrors.As + SQLSTATENone

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 ​

go
// 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 ​

SituationUseExtra techniqueReason
New PostgreSQL-only servicepgx v5 native + pgxpoolsqlc with sql_package: pgx/v5Fastest, full feature set
Library or multi-database codedatabase/sql + pgx stdlibOpenDBFromPool if you also need pgxPortable; tools expect *sql.DB
Existing lib/pq codeKeep, migrate when touchingSwitch driver name to pgx, test NULL/array handlingLow-risk swap
MySQLgo-sql-driver/mysqlparseTime=true, ? placeholdersThe standard driver
Many small reads per pagepgx.Batch or = ANY($1)Avoid N+1Round trips dominate
Bulk loadCopyFromStaging table + INSERT ... ON CONFLICTOrder of magnitude faster
Upsert a few thousand rowsunnest arraysON CONFLICT DO UPDATEOne statement, stable SQL text
Money transfer, inventoryBeginTx + SELECT ... FOR UPDATE or SerializableWithRetry on 40001Correctness first
Read-only reportLevelRepeatableRead, ReadOnlyReplica if lag is acceptableOne snapshot
Behind PgBouncer transaction modeQueryExecModeExec (or PgBouncer ≥ 1.21 tracking)Direct connection for LISTENSession state does not survive
Cache invalidation across instancesLISTEN/NOTIFYRe-read on reconnectNo broker needed
Static CRUD + reporting queriessqlcBuilder for dynamic filtersTyped, SQL visible
Admin back officeGORM or bunWatch for N+1Speed of development
Service testsFake repositoriesReal DB for repository testsFast 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× ​

LoadWhat changesGo data-layer practice
1× (one instance)Defaults hide bugsOne pool, Ping, all four knobs set, defer rows.Close(), tx helper, SQLSTATE classifier
10× (several instances)Connection budget and slow queries matterPool size = budget ÷ instances, statement_timeout, pool metrics, batch/ANY, COPY for imports
100× (fleet, replicas, poolers)Server connections and failovers dominatePgBouncer 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.859s

2. 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=3

pgxpool.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.

sql
-- 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):

sql
ALTER ROLE app SET statement_timeout = '5s';
ALTER ROLE app SET lock_timeout = '2s';
ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';
go
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 succeed

5. 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 s

6. 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 42

For 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.

php
// 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 / PHPGo
DB::connection() (PDO)sql.Open / pgxpool.New (lazy pool) + Ping
One connection per FPM workerOne 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 migrategoose, golang-migrate, Atlas, tern
pooled + direct pgsql connectionpooled DSN for queries, direct DSN for migrations and LISTEN
DB::listen for query logspgx.QueryTracer, otelsql

Common misconceptions ​

BeliefReality
sql.Open checks the connectionIt may not connect at all; call PingContext
Open a *sql.DB per requestIt is a pool; open once per process
Unlimited connections are fastestThey overload the server; set MaxOpenConns/MaxConns
The pgxpool default size is 4max(4, runtime.NumCPU())
Next returning false means successCheck rows.Err()
rows.Close() is optionalEarly returns leak the connection without it
database/sql translates ? to $1Placeholder syntax belongs to the driver
db.Prepare prepares onceOnce per connection it runs on
Disabling the pgx cache means interpolationOnly the simple protocol interpolates
defer tx.Rollback() undoes a commitAfter Commit it is a no-op returning ErrTxDone
db.ExecContext inside a tx function is in the txIt runs on another connection, outside the transaction
Retry the failed statement on 40001Retry the whole transaction
ctx cancel stops the server queryDepends on the driver; pgx default closes the connection
PgBouncer can never handle prepared statements1.21+ tracks protocol-level ones when max_prepared_statements > 0
sqlmock tests prove the SQL is rightOnly a real database can
Match duplicate key in the messageCheck SQLSTATE 23505 and the constraint name

Cheat sheet ​

TopicRemember
OpenOnce in main; PingContext with a timeout; lazy otherwise
PoolSetMaxOpenConns, SetMaxIdleConns (default 2), SetConnMaxLifetime, SetConnMaxIdleTime
pgxpoolMaxConns default max(4, NumCPU); MinIdleConns; lifetime 1 h; idle 30 min; health check 1 min
QueryQueryContext → defer rows.Close() → Next/Scan → rows.Err()
One rowQueryRowContext(...).Scan; sql.ErrNoRows → domain not found
NULLPointer, sql.Null[T] (1.22) or sql.NullString; never plain string
PlaceholdersPostgreSQL $1, MySQL ?; identifiers via allow-list or pgx.Identifier
Preparepgx caches automatically (512 per conn); Stmt is per connection
Exec modescache_statement default; exec behind transaction poolers
TransactionBeginTx → defer tx.Rollback() → work on tx only → Commit
Retry40001 and 40P01: rerun the whole fn with backoff; 23505 only if the key is derived inside a Serializable tx
Timeoutsctx per call + statement_timeout, lock_timeout, idle_in_transaction_session_timeout
Errorserrors.As(err, &*pgconn.PgError); switch on Code
BulkCopyFrom > unnest arrays > multi-row VALUES (65535 params) > loop
N+1= ANY($1) with a slice, or pgx.Batch
RepositoryInterface per aggregate, domain types, version column
Shared txTx in ctx (InTx) or unit of work; boundary in the use case
TestingFakes for services, real PostgreSQL for repositories

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
database/sqlGo standard-library package: pool, transactions and a driver interface for SQL databases
*sql.DBConcurrency-safe pool of connections; open once per database
sql.Open lazysql.Open/OpenDB may not connect; Ping or the first query dials
PingContextVerifies a connection can be made and used
SetMaxOpenConnsCap on open connections; default unlimited
SetMaxIdleConnsIdle connections kept; default 2
SetConnMaxLifetimeMaximum age before a connection is closed
SetConnMaxIdleTimeMaximum idle time before a connection is closed (Go 1.15)
DBStatsPool counters from db.Stats(): open, in use, idle, waits
DriverPackage implementing database/sql/driver for one database
pgx stdlibgithub.com/jackc/pgx/v5/stdlib, the pgx adapter registered as "pgx"
lib/pqOlder pure-Go PostgreSQL driver, long in maintenance mode
go-sql-driver/mysqlThe MySQL driver for database/sql
QueryContext / QueryRowContext / ExecContextContext-aware query, single-row query and exec
*sql.RowsResult cursor; Next, Scan, Err, Close
sql.ErrNoRowsError from Row.Scan when no row was returned
NULL handlingRepresenting SQL NULL in Go with pointers or Null types
sql.NullStringTyped nullable string with Valid flag
sql.Null[T]Generic nullable wrapper (Go 1.22)
PlaceholderParameter marker in SQL: $1 (PostgreSQL), ? (MySQL)
SQL injectionUser input interpreted as SQL because it was concatenated into the text
Prepared statementServer-side parsed statement in one session, executed with parameters
*sql.Stmtdatabase/sql handle that prepares itself on each connection it runs on
Implicit per-connection preparedatabase/sql preparing each statement when the driver lacks QueryerContext
Statement cachepgx per-connection LRU of prepared statements (stmtcache_..., 512 entries)
QueryExecModepgx setting: cache_statement, cache_describe, describe_exec, exec, simple_protocol
Simple protocolPostgreSQL query protocol with values interpolated into one string
Extended protocolParse/Bind/Execute messages with separate parameters
TransactionGroup of statements committed or rolled back together on one connection
BeginTxStarts a transaction with TxOptions (isolation, read-only)
Isolation levelPromise about what concurrent transactions can see (LevelSerializable etc.)
Commit/RollbackEnd a transaction, keeping or discarding its changes
Defer Rollback patterndefer tx.Rollback() right after BeginTx, harmless after Commit
sql.ErrTxDoneError from a Tx that is already committed or rolled back
SavepointNamed point inside a transaction; pgx's nested Begin uses them
Serialization failureSQLSTATE 40001: the transaction must be retried
DeadlockSQLSTATE 40P01: a lock cycle; one transaction is aborted
Context cancellation behaviourWhat database/sql and the driver do when ctx ends
Cancel requestPostgreSQL protocol message asking a backend to cancel its current statement
pgx v5 native APIUsing pgx directly instead of through database/sql
pgx.ConnOne pgx connection, not concurrency-safe
pgxpool.Poolpgx's concurrency-safe connection pool
pgxpool.ConfigPool settings: MaxConns, lifetimes, health check, hooks
MaxConnspgxpool size cap; default max(4, NumCPU)
Health checkpgxpool background check of idle connections (HealthCheckPeriod)
AfterConnectpgxpool hook run once per new connection
Connection string / DSNURL or key=value text with host, user, database and options
CollectRowspgx generic helper collecting rows into a slice
RowToStructByNamepgx row mapper matching columns to struct fields by name
Named argspgx.NamedArgs: @name placeholders rewritten to $n
Batchpgx.Batch: several statements in one round trip
CopyFrompgx bulk load through the COPY protocol
COPYPostgreSQL bulk load/unload command and protocol
unnestPostgreSQL function expanding arrays to rows; used for bulk insert
Bulk insertInserting many rows with few statements
LISTEN/NOTIFYPostgreSQL publish/subscribe between sessions, delivered on commit
pgtypepgx package mapping PostgreSQL types to Go
TimeoutsClient ctx deadlines and server limits (statement_timeout, lock_timeout)
statement_timeoutPostgreSQL limit on statement duration (57014)
lock_timeoutPostgreSQL limit on waiting for a lock (55P03)
idle_in_transaction_session_timeoutKills sessions idle inside an open transaction
Error inspectionUsing errors.Is/errors.As to classify errors
pgconn.PgErrorpgx error type carrying the server's SQLSTATE, message and constraint
SQLSTATEFive-character standard error code
PgBouncerLightweight PostgreSQL connection pooler
Transaction poolingPooler mode lending a server connection per transaction
max_prepared_statementsPgBouncer 1.21+ setting that tracks protocol-level prepared statements
Repository patternPersistence interface per aggregate that hides SQL from the domain
Interface per aggregateOne repository interface per aggregate root, defined by its consumer
DBTXInterface satisfied by *sql.DB, *sql.Tx and *sql.Conn
Tx propagationSharing one transaction across repositories (context or unit of work)
Unit of workObject that runs a function with repositories bound to one transaction
Optimistic concurrencyversion column checked in UPDATE ... WHERE version = $n
OutboxTable of events written in the same transaction as the state change
sqlcGenerator of typed Go code from SQL queries
squirrel / goquGo SQL query builders
GORM / ent / bunGo ORMs: full-featured, schema-as-code, SQL-first
MigrationsVersioned schema changes applied in order
golang-migrate / goose / Atlas / ternGo-ecosystem migration tools
N+1One query for a list plus one per item
pgx mockpgxmock, a mock implementing pgx interfaces
sqlmockgo-sqlmock, a mock database/sql driver
Fake driverSmall in-test database/sql driver that records calls
Real DB testRepository test against a real PostgreSQL (container or CI service)
testcontainers / dockertestLibraries that start database containers for tests
ObservabilityTraces, metrics and logs for the data layer
otelsqlOpenTelemetry wrapper for database/sql
pgx tracerpgx.QueryTracer and friends set on ConnConfig.Tracer
otelpgxOpenTelemetry tracer for pgx

References ​

Built by Morteza Negahi