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