Documentation
¶
Overview ¶
Package transaction provides utilities for wrapping operations in a transaction. Upon transaction failure, changes are expected to be rolled back, and, upon transaction success, changes are committed.
A transaction object contains a list of contexts, each containing their own key (string). Keys should be unique for each transaction type. For example, given a postgres connection and a file service, a TransactionContext can be created for each, satisfying the Context interface. This transaction context can be directly registered into the Transaction.Context map. Then, define a method such as `Use(tx *Transaction)` which attempts to retrieve the context from the tx.Context map. If it doesn't exist, create a new one.
func GetCustomTransactionContext(tx *Transaction, args AnyArgsNeeded) *CustomTransactionContext{
m, ok := tx.Contexts["CustomTransactionContext"]
if ok {
v, ok := m.(*CustomTransactionContext)
if ok {
return v
}
}
v := CreateTransactionContext(args AnyArgsNeeded)
tx.Contexts["CustomTransactionContext"] = v
return v
}
A helper method GetContext is created to help with this logic.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetContext ¶
func GetContext[T Context](tx *Transaction, key string, create func() T) T
GetContext is a helper method to retrieve a context of a certain type from a transaction, associated with a specific key. If it does not exist, it will be created through the provided create method.
func Tx ¶
func Tx(fn func(tx *Transaction) error) error
Tx provides the transaction for wrapping of functions. Functions that wish to sue the function should take in the Transaction that is passed as the argument.
Types ¶
type Context ¶
type Context interface {
// Rollback are operations that need to be done to clean-up on failure.
Rollback()
// Commit solidifies the resultant operations.
Commit()
}
Context defines a group of transactions in the same type of service (e.g., postgers; s3) which can Rollback or Commit.
type TestContext ¶
TestContext is a test transaction context. It implement Context.
func (*TestContext) Commit ¶
func (t *TestContext) Commit()
Commit solidifies the resultant operations.
func (*TestContext) Rollback ¶
func (t *TestContext) Rollback()
Rollback are operations that need to be done to clean-up on failure.
type Transaction ¶
type Transaction struct {
// Contexts are what is used to retrieve any objects required to be stored within the
Contexts map[string]Context
}
Transaction defines a single transaction
func (*Transaction) Commit ¶
func (t *Transaction) Commit()
func (*Transaction) Rollback ¶
func (t *Transaction) Rollback()