pgxtx

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package pgxtx carries a PostgreSQL transaction in a context, so the code that owns a unit of work begins it and the code that runs statements finds it, without the transaction appearing in any signature in between.

The owner calls Within (or Snapshot for a consistent read), and every statement goes through Querier, which returns the context's transaction or, outside one, the pool. Code declaring the unit of work needs only an interface with the Within method, so it never mentions the driver.

There is no automatic retry: a deadlock or serialization failure is returned (through the configured wrapper) for the caller to report, and the lock order of a unit of work is fixed in its code instead.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AfterCommit

func AfterCommit(ctx context.Context, fn func())

AfterCommit runs fn once the transaction ctx carries commits, and never if it rolls back; outside a transaction, where each statement commits on its own, it runs fn at once. It lets a repository tell the rest of its process about a change only once other transactions can see it, such as a replica's cache learning the version it just wrote. fn runs on the committing goroutine and must return promptly.

func Local added in v0.2.0

func Local[T any](ctx context.Context, key any, init func() T) (T, bool)

Local returns the value the transaction ctx carries under key, storing init() there first when it carries none, so code called more than once in one unit of work remembers what it learned earlier in it, such as what a row held before the unit of work changed it. key is compared as a map key, so a package uses an unexported type of its own. Outside a transaction there is nothing to remember: it returns init() and false.

func Outside added in v0.2.0

func Outside(ctx context.Context) context.Context

Outside returns ctx without the transaction it carries, keeping its deadline and values otherwise: statements under it run on the pool, and a Within or Snapshot under it begins a transaction of its own. Code waiting inside a unit of work for what other transactions committed reads under it, on another connection.

Types

type DB

type DB interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
	CopyFrom(ctx context.Context, table pgx.Identifier, columns []string, rows pgx.CopyFromSource) (int64, error)
}

DB is what a statement runs on: a transaction or the pool.

func Querier

func Querier(ctx context.Context, pool *pgxpool.Pool) DB

Querier returns the transaction ctx carries, or pool outside one. Every statement of a repository goes through it, so the repository takes part in whatever unit of work its caller began.

type Option

type Option func(*Transactor)

Option configures a Transactor.

func WithConcurrencyFailure

func WithConcurrencyFailure(wrap func(error) error) Option

WithConcurrencyFailure sets how a deadlock (SQLSTATE 40P01) or a serialization failure (40001) returned by a unit of work is reported: wrap turns it into the error the caller returns, keeping it as the cause.

type Transactor

type Transactor struct {
	// contains filtered or unexported fields
}

Transactor begins transactions on a pool.

func New

func New(pool *pgxpool.Pool, opts ...Option) *Transactor

New returns a Transactor beginning transactions on pool.

func (*Transactor) Snapshot

func (t *Transactor) Snapshot(ctx context.Context, fn func(ctx context.Context) error) error

Snapshot runs fn in a REPEATABLE READ READ ONLY transaction, so a query of several statements sees one consistent view while other transactions commit. A Snapshot inside another joins it; one inside a Within is a programming error and panics.

func (*Transactor) Within

func (t *Transactor) Within(ctx context.Context, fn func(ctx context.Context) error) error

Within runs fn in a READ COMMITTED read-write transaction carried by the context it passes to fn. It commits when fn returns nil and rolls back when fn returns an error or panics, re-panicking after the rollback. A Within inside another joins the outer transaction: only the outermost commits, so a unit of work composed of others is still one. An inner failure rolls everything back when the outer function returns it; an outer function that swallows it commits whatever statements succeeded. A Within inside a Snapshot is a programming error and panics.

Example

A handler owns the transaction; the repositories it calls take part in it.

package main

import (
	"context"

	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/azverinus/flagnetic/internal/pkg/pgxtx"
)

// transactor is how an application handler declares the unit of work it owns:
// one method, no driver type, satisfied by *pgxtx.Transactor.
type transactor interface {
	Within(ctx context.Context, fn func(ctx context.Context) error) error
}

var _ transactor = (*pgxtx.Transactor)(nil)

// renameNote is a repository method: it runs on whatever transaction its
// caller began, or on the pool outside one.
func renameNote(ctx context.Context, pool *pgxpool.Pool, from, to string) error {
	_, err := pgxtx.Querier(ctx, pool).Exec(ctx, `UPDATE note SET key = $2 WHERE key = $1`, from, to)
	return err
}

// A handler owns the transaction; the repositories it calls take part in it.
func main() {
	var pool *pgxpool.Pool // the server's pool
	var tx transactor = pgxtx.New(pool)

	_ = tx.Within(context.Background(), func(ctx context.Context) error {
		if err := renameNote(ctx, pool, "draft", "final"); err != nil {
			return err // rolls back both renames
		}
		return renameNote(ctx, pool, "final-old", "archive")
	})
}

Jump to

Keyboard shortcuts

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