pgxtransactions

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

PGXTransactions

Go Reference Build Status

PGXTransactions is a small Go library for running PostgreSQL transactions with pgx that automatically retry on transient, retryable failures such as deadlocks, serialization failures, and optimistic concurrency conflicts.

Features

  • Automatic retries for retryable database errors (deadlocks, unique-violation conflicts, and any other errors you classify as retryable).
  • A separate Preparer callback that runs inside the retry loop, but outside the transaction, and an Updater callback that runs inside it - making optimistic concurrency control easy to express.
  • Exponential backoff with jitter and a configurable retry cap.
  • Works against *pgxpool.Pool or any type implementing the small PgxIface interface, so transactions are easy to mock in tests.

Installation

go get github.com/synaptor/pgxtransactions

Usage

Wrap your read-modify-write logic in a call to pgxtransactions.Transaction:

import (
    "context"

    "github.com/jackc/pgx/v5"
    "github.com/jackc/pgx/v5/pgxpool"
    "github.com/synaptor/pgxtransactions"
)

func dataUpdate(ctx context.Context, pool *pgxpool.Pool) error {
    var data string
    var version int

    return pgxtransactions.Transaction(ctx, pool, pgxtransactions.TransactionOptions{
        // Preparer runs outside the transaction to do any expensive work.
        Preparer: func() error {
            // Load the current state from the database.
            err := pool.QueryRow(ctx, "SELECT data, version FROM tbl WHERE id=$1", id).Scan(&data, &version)
            if err != nil {
                return err
            }

            // Perform any expensive computations or API calls that shouldn't keep the transaction open.
            // Prepare data for the Updater, e.g. new values to be stored in the database.
            return nil
        },

        // Updater runs inside the transaction.
        Updater: func(tx pgx.Tx) error {
            // Perform the optimistic concurrency control update. If the row was modified by another transaction since we loaded it in Preparer, this will affect zero rows and we can treat it as a retryable conflict.
            res, err := tx.Exec(ctx, "UPDATE tbl SET data=$1, version=version+1 WHERE id=$2 AND version=$3", data, id, version)
            if err != nil {
                return err
            }
            if res.RowsAffected() == 0 {
                // No rows were updated, which means the version didn't match - i.e. the row was modified by another transaction.
                return pgxtransactions.ErrConflict
            }
            return nil
        },
    })
}

On each retry, Transaction re-runs Preparer (to prepare again) and then Updater inside a fresh transaction. Preparer is optional. Updater is required.

Retrying unique constraint violations

By default, unique constraint violations are not retried. This behavior is needed when the caller updates a unique field to a fixed value, and failure to do so is not retryable. However, if the caller is capable of resolving unique constraint violations (e.g. by generating a new value and retrying), they should be treated as retryable. To enable this, set the RetryUniqueViolations field to true.

Custom IsRetryable logic

By default, Transaction retries deadlocks, unique-violation conflicts and custom pgxtransactions.ErrConflict error. To classify other errors as retryable, set the IsRetryable field of TransactionOptions to a function that returns true for those errors.

Custom MaxRetries

By default, Transaction retries up to 10 times. To change this, set the MaxRetries field of TransactionOptions to the desired maximum number of attempts (including the initial attempt).

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrConflict = errors.New("conflict")

Functions

func Transaction

func Transaction(ctx context.Context, pool PgxIface, opt TransactionOptions) error

Transaction executes a database transaction automatically retrying all retryable errors.

Types

type PgxIface

type PgxIface interface {
	Begin(ctx context.Context) (pgx.Tx, error)
}

PgxIface is an interface for pgxpool.Pool to allow mocking in tests.

type TransactionOptions

type TransactionOptions struct {
	// Preparer (optional field) is called outside of the transaction to load data from the database.
	Preparer func() error

	// Updater (required field) is called inside the transaction to update data in the database.
	// If the updater returns ErrConflict, the transaction will be retried.
	Updater func(tx pgx.Tx) error

	// IsRetryable (optional field) is called to determine if an error returned by Preparer or Updater is retryable.
	// If not provided, all errors are considered non-retryable.
	IsRetryable func(err error) bool

	// RetryUniqueViolations defines how unique-violation errors are handled.
	RetryUniqueViolations bool

	// MaxRetries defines the maximum number of retries (if > 0).
	MaxRetries int
}

TransactionOptions configures a transaction.

Jump to

Keyboard shortcuts

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