Documentation ¶
Overview ¶
Package tx provides a simple transaction abstraction in order to enable decoupling / abstraction of persistence from application / domain logic while still leaving transaction control to the application service / use case coordinator (Something like @Transactional annotation in Java, without the annotation)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func From ¶
From returns underlying tx value from context if it can be type-casted to T Otherwise it returns default T, false. From returns underlying T from the context which in most cases should probably be pgx.Tx T will mostly be your Tx type (pgx.Tx, *sql.Tx, etc...) but is left as a generic type in order to accommodate cases where people tend to abstract the whole connection/transaction away behind an interface for example, something like Executor (see example).
Example:
type Executor interface { Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) // ... other stuff }
tx, err := tx.From[Executor](ctx, pool)
Or ¶
tx, err := tx.From[pgx.Tx](ctx, pool)
Types ¶
type DB ¶
type DB interface {
Begin(ctx context.Context) (Transaction, error)
}
DB represents an interface to a db capable of starting a transaction
type Option ¶
type Option func(tx *TX)
func WithIgnoredErrors ¶
WithIgnoredErrors offers a way to provide a list of errors which will not cause the transaction to be rolled back.
The transaction will still be committed but the actual error will be returned by the WithTransaction method.
type TX ¶
type TX struct {
// contains filtered or unexported fields
}
TX represents sql transactor
func (*TX) WithTransaction ¶
WithTransaction will wrap f in a sql transaction depending on the DB provider. This is mostly useful for when we want to control the transaction scope from application layer, for example application service/command handler. If f fails with an error, transactor will automatically try to roll the transaction back and report back any errors, otherwise, the implicit transaction will be committed.
type Transaction ¶
type Transaction interface { Commit(ctx context.Context) error Rollback(ctx context.Context) error }
Transaction represents db transaction
type Transactor ¶
type Transactor interface { // WithTransaction will wrap f in a sql transaction depending on the DB provider. // This is mostly useful for when we want to control the transaction scope from // application layer, for example application service/command handler. // If f fails with an error, transactor will automatically try to roll the transaction back and report back any errors, // otherwise, the implicit transaction will be committed. WithTransaction(ctx context.Context, f func(ctx context.Context) error) error }
Transactor is a helper transactor interface added for brevity purposes, so you don't have to define your own See TX