gollback

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: GPL-3.0 Imports: 7 Imported by: 0

README

gollback

go reference tests

a simple pgx transaction manager that automatically rolls back on error.
supports timeouts and read-only transactions.

usage

NewTxnProvider returns a transaction manager and a function to get a connection from the pool.

func main() {
    ctx := context.Background()
    
    pool, err := pgxpool.New(ctx, "postgres://user:pass@localhost:5432/db")
    if err != nil {
        panic(err)
    }
    defer pool.Close()
    
    txnManager, getConn := gollback.NewTxnProvider(pool)
}                                                                                                                                                                                                                                                                                                              

replace pgxpool.Pool in your repositories with getConn

type UserRepo struct {
    db getConn
}

func (r *UserRepo) GetByID(ctx context.Contex, id int) (*User, error) {
    return r.db.QueryRow(ctx, "SELECT * FROM users WHERE id = $1", id)
}

your services can now use the transaction manager to string together multiple repository calls into a single transaction.

type Service struct {
    userRepo UserRepo
    postRepo PostRepo
    txnManager gollback.TxnManager
}

func (s *Service) CreatePost(ctx context.Context, userID int, post *Post) error {
    return s.txnManager.RunInTxn(ctx, func(ctx context.Context) error {
        _, err := s.userRepo.GetByID(ctx, UserID)
        if err != nil {
            return err
        }
        _, err = s.postRepo.Create(ctx, post, user.Name)
        if err != nil {
            return err
        }
        return nil
    }
}

  • the transaction is rolled back if the function returns an error
  • the transaction is committed if the function returns nil

advanced

using timeouts
s.txnManager.RunInTxn(ctx, func(ctx context.Context) error {
    return s.userRepo.GetByID(ctx, 123)
}, gollback.WithTimeout(5*time.Second))

[!IMPORTANT] the timeout cancels in-progress database operations and prevents commits but does not forcibly terminate your function. If your function has long-running computations between database calls, the transaction will remain open until the function completes. For early exit, check ctx.Done() periodically.

read-only transactions
s.txnManager.RunInTxn(ctx, func(ctx context.Context) error {
    return s.userRepo.GetByID(ctx, 123)
}, gollback.ReadOnly())

the above functional options can be combined.

error handling

the following typed errors are returned by the transaction manager:

  • gollback.TxnBeginError
  • gollback.TxnCommitError
  • gollback.TxnRollbackError
    • the original error is available via .Cause

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewTxnProvider

func NewTxnProvider(pool *pgxpool.Pool) (TxnManager, ConnGetter)

Types

type Conn

type Conn interface {
	Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, arguments ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, arguments ...any) pgx.Row
}

Conn provides a common interface for executing queries across different pgx connection types.

type ConnGetter

type ConnGetter func(ctx context.Context) Conn

ConnGetter returns a Conn for the current context. If a transaction is in progress, it returns the transaction Conn, otherwise it returns the pool Conn.

type TxnBeginError

type TxnBeginError struct {
	Err error
}

func (TxnBeginError) Error

func (e TxnBeginError) Error() string

func (TxnBeginError) Unwrap

func (e TxnBeginError) Unwrap() error

type TxnCommitError

type TxnCommitError struct {
	Err error
}

func (TxnCommitError) Error

func (e TxnCommitError) Error() string

func (TxnCommitError) Unwrap

func (e TxnCommitError) Unwrap() error

type TxnManager

type TxnManager interface {
	RunInTxn(ctx context.Context, fn func(ctx context.Context) error, opts ...TxnOption) error
}

TxnManager provides a way to run multiple queries in a transaction.

type TxnOption

type TxnOption func(*TxnOptions)

func ReadOnly

func ReadOnly() TxnOption

func WithTimeout

func WithTimeout(d time.Duration) TxnOption

type TxnOptions

type TxnOptions struct {
	Timeout  time.Duration
	ReadOnly bool
}

type TxnRollbackError

type TxnRollbackError struct {
	RollBackErr error
	Cause       error
}

func (TxnRollbackError) Error

func (e TxnRollbackError) Error() string

func (TxnRollbackError) Unwrap

func (e TxnRollbackError) Unwrap() error

Jump to

Keyboard shortcuts

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