pgx

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2024 License: MIT Imports: 7 Imported by: 0

README

Transaction Management with Transactor

Transactor provides robust transaction management capabilities, allowing you to execute operations within transactions using WithTx and manage nested transactions with WithNestedTx. Below are the use cases and examples for each method.

Using WithTx

The WithTx method is used for executing operations within a single transaction. It's ideal for operations that need to be atomic to maintain data integrity.

Use Cases
  • Single Database Action: Use WithTx for individual insert, update, or delete operations.
  • Read and Update: Useful for scenarios where you read data and then perform updates based on that data.
  • Aggregate Operations: For executing multiple operations that need to be atomic.
Example
func UpdateUserEmail(ctx context.Context, txManager pgx.TxManager, userID int, newEmail string) error {
    return txManager.WithTx(ctx, func(ctx context.Context, tx pgx.Tx) error {
        // Perform the update operation
        _, err := tx.Exec(ctx, "UPDATE users SET email = $1 WHERE id = $2", newEmail, userID)
        return err
    })
}

Using WithNestedTx

WithNestedTx is designed for managing potentially nested transactions. It's useful when operations are complex, involve conditional logic, or when you want to maintain modularity in your transaction logic.

Use Cases
  • Nested Operations with Conditions: When different operations need to be performed based on conditions, within their own transactional scope.
  • Recursive Operations: For operations that call themselves with different parameters, where each call should be in its own transaction.
  • Modular Business Processes: When a business process is divided into modules that can execute independently but within one overarching transaction.
  • Long Transactional Chains: For a series of logically connected operations that should be rolled back together in case of an error.
Example
func ProcessOrder(ctx context.Context, txManager pgx.TxManager, orderID int) error {
    return txManager.WithNestedTx(ctx, func(ctx context.Context, tx pgx.Tx) error {
        // Step 1: Update order status
        if err := updateOrderStatus(ctx, tx, orderID, "processing"); err != nil {
            return err
        }

        // Step 2: Reserve inventory
        if err := reserveInventory(ctx, tx, orderID); err != nil {
            return err
        }

        // Step 3: Process payment
        return processPayment(ctx, tx, orderID)
    })
}

These methods offer flexibility and control over transaction management, ensuring data integrity and consistency across your application. Use WithTx for straightforward transactional operations and WithNestedTx for more complex or conditional transaction logic.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrNoTransaction is the error used when no transaction is found in the context.
	ErrNoTransaction = errors.New("no transaction in context")
)

Functions

This section is empty.

Types

type Conn

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

Conn defines the interface for connection

type ConnMock

type ConnMock struct {
	mock.Mock
}

ConnMock is an autogenerated mock type for the Conn type

func NewConnMock

func NewConnMock(t interface {
	mock.TestingT
	Cleanup(func())
}) *ConnMock

NewConnMock creates a new instance of ConnMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*ConnMock) Begin

func (_m *ConnMock) Begin(ctx context.Context) (pgx.Tx, error)

Begin provides a mock function with given fields: ctx

type Row

type Row = pgx.Row

Row is an alias to pgx.Row

type RowMock

type RowMock struct {
	mock.Mock
}

RowMock is an autogenerated mock type for the RowMock type

func NewRowMock

func NewRowMock(t interface {
	mock.TestingT
	Cleanup(func())
}) *RowMock

NewRowMock creates a new instance of RowMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*RowMock) Scan

func (_m *RowMock) Scan(dest ...interface{}) error

Scan provides a mock function with given fields: dest

type Transactor

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

Transactor is a concrete implementation of TxManagerInterface using pgxpool.

func (*Transactor) WithNestedTx

func (t *Transactor) WithNestedTx(ctx context.Context, tFunc func(context.Context, Tx) error) (err error)

WithNestedTx executes a function within the context of a potentially nested transaction. It manages transaction nesting using a counter to track the depth of nested transactions. If there is no active transaction, it starts a new one.

func (*Transactor) WithTx

func (t *Transactor) WithTx(ctx context.Context, tFunc func(context.Context, Tx) error) (err error)

WithTx executes a function within the context of a transaction. This method checks if there is already an ongoing transaction in the context. If not, it starts a new transaction and then executes the provided function. After the function execution, it commits the transaction if no errors occurred, or rollbacks in case of an error or panic. The transaction object is passed to the function, allowing direct transaction control.

type Tx

type Tx = pgx.Tx

Tx is an alias to pgx.Tx

type TxManager

type TxManager interface {
	WithTx(ctx context.Context, fn func(context.Context, Tx) error) error
	WithNestedTx(ctx context.Context, tFunc func(context.Context, Tx) error) error
}

TxManager defines the interface for transaction management.

func NewTxManager

func NewTxManager(registry *pgxpool.Registry) (TxManager, error)

NewTxManager creates a new instance of TxManager with a given registry. It uses the master connection pool for managing transactions.

type TxManagerMock

type TxManagerMock struct {
	mock.Mock
}

TxManagerMock is an autogenerated mock type for the TxManager type

func NewTxManagerMock

func NewTxManagerMock(t interface {
	mock.TestingT
	Cleanup(func())
}) *TxManagerMock

NewTxManagerMock creates a new instance of TxManagerMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*TxManagerMock) WithNestedTx

func (_m *TxManagerMock) WithNestedTx(ctx context.Context, tFunc func(context.Context, pgx.Tx) error) error

WithNestedTx provides a mock function with given fields: ctx, tFunc

func (*TxManagerMock) WithTx

func (_m *TxManagerMock) WithTx(ctx context.Context, fn func(context.Context, pgx.Tx) error) error

WithTx provides a mock function with given fields: ctx, fn

type TxMock

type TxMock struct {
	mock.Mock
}

TxMock is an autogenerated mock type for the TxMock type

func NewTxMock

func NewTxMock(t interface {
	mock.TestingT
	Cleanup(func())
}) *TxMock

NewTxMock creates a new instance of TxMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*TxMock) Begin

func (_m *TxMock) Begin(ctx context.Context) (pgx.Tx, error)

Begin provides a mock function with given fields: ctx

func (*TxMock) BeginFunc

func (_m *TxMock) BeginFunc(ctx context.Context, f func(pgx.Tx) error) error

BeginFunc provides a mock function with given fields: ctx, f

func (*TxMock) Commit

func (_m *TxMock) Commit(ctx context.Context) error

Commit provides a mock function with given fields: ctx

func (*TxMock) Conn

func (_m *TxMock) Conn() *pgx.Conn

Conn provides a mock function with given fields:

func (*TxMock) CopyFrom

func (_m *TxMock) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)

CopyFrom provides a mock function with given fields: ctx, tableName, columnNames, rowSrc

func (*TxMock) Exec

func (_m *TxMock) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)

Exec provides a mock function with given fields: ctx, sql, arguments

func (*TxMock) LargeObjects

func (_m *TxMock) LargeObjects() pgx.LargeObjects

LargeObjects provides a mock function with given fields:

func (*TxMock) Prepare

func (_m *TxMock) Prepare(ctx context.Context, name string, sql string) (*pgconn.StatementDescription, error)

Prepare provides a mock function with given fields: ctx, name, sql

func (*TxMock) Query

func (_m *TxMock) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)

Query provides a mock function with given fields: ctx, sql, args

func (*TxMock) QueryFunc

func (_m *TxMock) QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error)

QueryFunc provides a mock function with given fields: ctx, sql, args, scans, f

func (*TxMock) QueryRow

func (_m *TxMock) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row

QueryRow provides a mock function with given fields: ctx, sql, args

func (*TxMock) Rollback

func (_m *TxMock) Rollback(ctx context.Context) error

Rollback provides a mock function with given fields: ctx

func (*TxMock) SendBatch

func (_m *TxMock) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults

SendBatch provides a mock function with given fields: ctx, b

Jump to

Keyboard shortcuts

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