txutil

package
v0.0.0-...-692e47d Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2023 License: MIT Imports: 5 Imported by: 2

Documentation

Overview

The txutil package implements utility functions relating to automatically retrying transactions.

Index

Constants

This section is empty.

Variables

View Source
var ErrorRollbackSuccess = errors.New("internal error: rollback-but-succeed")

ErrorRollbackSuccess if returned from the TxLoopDb function, will cause the transaction will be rolled back, but 'nil' to be returned from the outer function. This allows an easy way to rollback a transaction while having the outer operation not need any special logic.

Functions

func ShouldRetry

func ShouldRetry(err error) bool

ShouldRetry takes an error and tries to determine if it's an error which should lead to a transaction retry, or a transaction failure. Currently only works for mattn/go-sqlite3 error codes.

func TxLoopDb

func TxLoopDb(db *sqlx.DB, txFunc func(eq sqlx.Ext) error) error

TxLoopDb implements the boilerplate around making transaction loops.

The callback will be handed an interface suitable to do Query and Exec calls. Any error it gets from database calls should be passed up either as-is, or reachable by an appropriate number of Unwrap calls.

TxLoopDb will start the transaction, and check for errors which should lead to a retry; those transactions will be re-started and the function called again. An ErrorRollbackSuccess error will cause the transaction to be cancelled, but 'nil' to be returned to the top level. Any other error will cause the transaction to be cancelled and will be passed up unchanged.

Callers should make sure that the function has no changes to long-term outside state, even if returing success, as the final commit may still fail.

Example:

var FooType Foo

err := TxLoopDb(db, func(eq sqlx.Ext) error {
    _, err := eq.Exec(...)
   if err != nil {
       return fmt.Errorf("...: %w", err)
   }

   err := sqlx.Get(eq, &Foo, ...)
   if err != nil {
       return fmt.Errorf("...: %w", err)
   }

  return nil

}

// Use Foo only if TxLoopDb returned no error

Types

This section is empty.

Jump to

Keyboard shortcuts

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