pgxtxn

package
v0.0.0-...-aa94d8a Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package pgxtxn executes transactions safely and with concurrency retries.

Index

Constants

View Source
const PGCodeDeadlockDetected = "40P01"

PGCodeDeadlockDetected is the Postgres error code for a deadlock. See: https://www.postgresql.org/docs/current/errcodes-appendix.html

View Source
const PGCodeSerializationFailure = "40001"

PGCodeSerializationFailure is the Postgres error code for a serialization failure. See: https://www.postgresql.org/docs/current/errcodes-appendix.html

Variables

This section is empty.

Functions

func Run

func Run(
	ctx context.Context, db TransactionalDB, body func(ctx context.Context, tx pgx.Tx) error,
	txOptions pgx.TxOptions,
) error

Run executes body in a transaction that will always commit or roll back, and with retries in case of deadlocks or serialization errors. If body returns an error, the transaction is rolled back. If it returns nil, the transaction is committed. The body function should not call Commit, but may call Rollback. The ctx argument is passed to Begin, Commit, Rollback and body without modification.

This prevents the following common mistakes: - Forgetting to COMMIT or ROLLBACK in all cases, leaving "stuck" transactions - Forgetting to retry on serialization errors

TODO: Pass an interface that does not have Commit to body to avoid mistakes?

Types

type TransactionalDB

type TransactionalDB interface {
	// Begin is starts a pgx transaction. See pgxpool.BeginTx for details.
	BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
}

TransactionalDB is a database that can run transactions.

Jump to

Keyboard shortcuts

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