quartermaster

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 5 Imported by: 0

README

quartermaster

CI Go Reference

I can do more damage on my laptop in pajamas before my first cup of tea than you can in a year in the field. — Q, Skyfall (2012)

A typed transaction closure for sqlc and pgx/v5, built on Go 1.27 generic methods. Requires Go 1.27+.

Before 1.27 a method couldn't declare its own type parameters, so txr.RunTx couldn't return a typed result: you needed a package-level function or captured variables. RunTx[R] returns whatever your closure returns:

txr := quartermaster.New(pool, db.New(pool)) // pool is a *pgxpool.Pool

payment, err := txr.RunTx(ctx, func(q *db.Queries) (Payment, error) {
    if err := q.InsertPayment(ctx, params); err != nil {
        return Payment{}, err
    }
    return payment, q.InsertOutbox(ctx, event)
})

RunTx begins a transaction, calls your closure with db.Queries bound to it (via sqlc's generated WithTx), and commits if you return nil. An error, a panic or a canceled context rolls it back.

It is deliberately narrow: sqlc output with sql_package: "pgx/v5", on a *pgxpool.Pool. No driver abstraction and no other query layers.

Design

A DB transaction is a critical section: keep it short, block on nothing outside the database, and give it one owner. Many popular Transactor helpers do the opposite. They put the open transaction in ctx and quietly join nested calls, so nothing at the call site tells you whether you're inside one, transactions end up spanning services, and a network call slips in.

Read the post this came from: When did we forget transactions are critical sections?

The name is the idea: Q is the quartermaster, who issues the kit, knows who has it, and makes sure it comes back.

  • Issued to a named holder. q goes to exactly one closure, never into ctx.
  • Signed out as briefly as possible. No network calls while you hold it.
  • Always comes back. It's returned on every path: commit, error, panic or cancel.
  • Nobody draws twice on one chit. Nested calls get their own issue.

Semantics

  • fn's error is returned unwrapped, so errors.Is works.
  • A panic in fn rolls back and propagates. There is no recover.
  • No joining. A nested RunTx opens a second, independent transaction on a second connection.
  • NewWithConfig takes a Config. TxOptions sets the isolation level for every transaction a Transactor starts; for a different level, build another Transactor. RollbackTimeout bounds the rollback.

Commit errors, the rollback timeout and the cost of nesting are in the package documentation.

External calls

Don't keep the transaction open around a network call. Store pending, make the call, store the result. examples/payments shows it, along with an idempotency key and an outbox write committing together.

Alternatives

metalfm/transactor is the closest design, a typed argument, but its closure can only return error.

Library How the transaction reaches your code
Thiht/transactor, go-transaction-manager, pgxtx, pgxatomic context.Context
metalfm/transactor typed argument, closure returns only error
pgx.BeginFunc raw pgx.Tx, no sqlc binding

Development

make help lists the targets. make test needs Docker, since the tests run against a real Postgres in a container. make check runs the same checks CI runs.

License

MIT

Documentation

Overview

Package quartermaster runs short PostgreSQL transactions for sqlc's pgx/v5 output and returns a typed result from the closure. It requires Go 1.27, whose generic methods let Transactor.RunTx declare its own result type: it takes a func(Q) (R, error) and returns (R, error).

The transaction is an argument, never read from or stored in context.Context. The quartermaster issues the kit, knows exactly who has it, and makes sure it comes back: Transactor.RunTx begins a transaction, binds it to your generated Queries with WithTx, calls fn exactly once, and then commits or rolls back.

Usage

Wire a Transactor once, next to your sqlc-generated Queries:

txr := quartermaster.New(pool, db.New(pool)) // pool is a *pgxpool.Pool

payment, err := txr.RunTx(ctx, func(q *db.Queries) (Payment, error) {
	// q is bound to the transaction; nothing is read from ctx.
	...
})

Errors

The error returned by fn is returned unwrapped, so errors.Is and errors.As work on it. Errors from beginning and committing are wrapped with the prefixes "quartermaster: begin: " and "quartermaster: commit: ".

A commit error does not always mean the transaction was rolled back. If the context is canceled while COMMIT is on the wire, the server may or may not have committed, and the caller cannot tell which. Check the state before retrying a write that is not idempotent.

Rollback

If fn returns an error or panics, the transaction is rolled back; a panic propagates. The rollback ignores ctx's cancellation, so it still runs after the request was canceled. If the cancellation interrupted a query, pgx has already closed the connection and PostgreSQL aborts the transaction when it drops. The rollback is bounded so that an unresponsive server cannot block Transactor.RunTx forever. The bound is, in order: the duration set in Config.RollbackTimeout; the time remaining until ctx's deadline, if it has one and has not passed; otherwise five seconds.

Nested transactions

There is no context lookup and no joining: calling RunTx inside fn starts a separate transaction that commits or rolls back independently. That has two costs. The nested transaction holds a second pooled connection, so enough concurrent nesting can exhaust the pool, with every outer transaction waiting for a connection that only its own return can free. And if the nested transaction touches rows the outer one has locked, it waits on the outer transaction while the outer one waits in Go; PostgreSQL's deadlock detector cannot see that, so only ctx or lock_timeout ends it. Pass a context with a deadline, and prefer writing one method that owns an invariant over nesting.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// TxOptions are the isolation level, access mode and deferrable mode for
	// every transaction the Transactor starts. For a different level, build
	// another Transactor with [NewWithConfig].
	//
	// Under [pgx.Serializable] and [pgx.RepeatableRead], PostgreSQL can fail a
	// transaction with SQLSTATE 40001; retrying the whole closure is up to the
	// caller.
	TxOptions pgx.TxOptions

	// RollbackTimeout bounds how long a rollback may take. Zero or less uses the
	// default: the time remaining until the context's deadline if it has one
	// that has not passed, otherwise five seconds. See the package
	// documentation.
	RollbackTimeout time.Duration
}

Config configures a Transactor. The zero value is valid.

type Queries

type Queries[Q any] interface {
	WithTx(pgx.Tx) Q
}

Queries is satisfied by sqlc-generated *Queries (sql_package: "pgx/v5"), which has a WithTx method returning a Queries bound to the transaction.

type Transactor

type Transactor[Q Queries[Q]] struct {
	// contains filtered or unexported fields
}

Transactor runs functions inside a transaction. Q is the sqlc-generated *Queries type. A Transactor is safe for concurrent use by multiple goroutines.

func New

func New[Q Queries[Q]](pool *pgxpool.Pool, q Q) *Transactor[Q]

New returns a Transactor that begins transactions on pool and binds each one to q with q.WithTx, using the default Config:

txr := quartermaster.New(pool, db.New(pool))
Example

Wire the Transactor once, next to your sqlc-generated Queries.

// pool is a *pgxpool.Pool; testdb.New is sqlc's generated constructor.
txr := quartermaster.New(pool, testdb.New(pool))
_ = txr

func NewWithConfig

func NewWithConfig[Q Queries[Q]](pool *pgxpool.Pool, q Q, cfg Config) *Transactor[Q]

NewWithConfig is like New but uses cfg:

txr := quartermaster.NewWithConfig(pool, db.New(pool), quartermaster.Config{
	TxOptions:       pgx.TxOptions{IsoLevel: pgx.RepeatableRead},
	RollbackTimeout: 2 * time.Second,
})
Example

Config sets the options for every transaction the Transactor starts. Under Serializable or RepeatableRead, PostgreSQL can fail a transaction with SQLSTATE 40001; retrying the whole closure is up to the caller.

ctx := context.Background()

// pool is a *pgxpool.Pool; testdb.New is sqlc's generated constructor.
txr := quartermaster.NewWithConfig(pool, testdb.New(pool), quartermaster.Config{
	TxOptions:       pgx.TxOptions{IsoLevel: pgx.RepeatableRead},
	RollbackTimeout: 2 * time.Second,
})

level, err := txr.RunTx(ctx, func(q *testdb.Queries) (string, error) {
	return q.IsolationLevel(ctx)
})
fmt.Println(level, err)
Output:
repeatable read <nil>

func (*Transactor[Q]) RunTx

func (t *Transactor[Q]) RunTx[R any](ctx context.Context, fn func(Q) (R, error)) (R, error)

RunTx begins a transaction, calls fn with Queries bound to it, and commits if fn returns a nil error. If fn returns an error or panics, the transaction is rolled back; the error from fn is returned unwrapped, and a panic propagates. See the package documentation for how errors from begin and commit are reported.

Keep fn short and don't make network calls inside it. The transaction holds a pooled connection and any row locks until fn returns.

RunTx never reads a transaction from ctx. Calling RunTx from inside fn starts a separate transaction on a second connection that commits or rolls back independently; see "Nested transactions" in the package documentation.

Example

Give each repository method its own short transaction. The Queries passed to the closure are bound to the transaction; nothing is read from ctx.

ctx := context.Background()

// pool is a *pgxpool.Pool; testdb.New is sqlc's generated constructor.
txr := quartermaster.New(pool, testdb.New(pool))

item, err := txr.RunTx(ctx, func(q *testdb.Queries) (testdb.Item, error) {
	return q.InsertItem(ctx, "example")
})
if err != nil {
	fmt.Println("rolled back:", err)
	return
}
fmt.Println("committed:", item.Name)
Output:
committed: example
Example (Rollback)

An error from the closure rolls the transaction back and comes back unwrapped, so errors.Is and errors.As work on it.

ctx := context.Background()
txr := quartermaster.New(pool, testdb.New(pool))

errInsufficient := errors.New("insufficient funds")
_, err := txr.RunTx(ctx, func(q *testdb.Queries) (struct{}, error) {
	if _, err := q.InsertItem(ctx, "rolled-back"); err != nil {
		return struct{}{}, err
	}
	return struct{}{}, errInsufficient
})
fmt.Println("same error:", errors.Is(err, errInsufficient))

n, _ := testdb.New(pool).CountItemsByName(ctx, "rolled-back")
fmt.Println("rows committed:", n)
Output:
same error: true
rows committed: 0

Directories

Path Synopsis
examples
payments
Package payments is the worked example from the post: an idempotent payment that writes an outbox event, and a service that never holds a transaction across the network call to the payment rail.
Package payments is the worked example from the post: an idempotent payment that writes an outbox event, and a service that never holds a transaction across the network call to the payment rail.
internal
pgtest
Package pgtest starts a throwaway PostgreSQL container for tests.
Package pgtest starts a throwaway PostgreSQL container for tests.
testdb
Package testdb is sqlc output used to test quartermaster against the code sqlc really generates.
Package testdb is sqlc output used to test quartermaster against the code sqlc really generates.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL