Write a generic decorator that runs any command handler inside a DB transaction
Implement WithTx: wrap any CommandHandler[C] so that the inner handler runs inside one database transaction. Repositories called by the handler must use that transaction, so put it into the context and implement TxFrom to read it back. Requirements: commit only when the inner handler returns nil; roll back on an error and on a panic (re-panic after the rollback); wrap returned errors with %w; the decorator must work for any command type.
type CommandHandler[C any] interface {
Handle(ctx context.Context, cmd C) error
}
type txKey struct{}
// TxFrom returns the transaction that WithTx stored in ctx.
func TxFrom(ctx context.Context) (*sql.Tx, bool) {
// your code here
}
func WithTx[C any](db *sql.DB, next CommandHandler[C]) CommandHandler[C] {
// your code here
}Write the implementation.
Return a wrapper type that begins a transaction, stores it in the context under the private key and calls the inner handler. Commit when it returns nil; otherwise, and on a panic, roll back. Repositories read the transaction back with TxFrom.
- Committing in a deferred call regardless of the handler's error
- Not rolling back on a panic, which keeps the connection busy until the context ends
- Keeping the transaction in a global variable, which races between concurrent requests
- How would you stack logging and metrics decorators on top of this one?
- What are the trade-offs of the data-access pattern Unit of Work versus a transaction in the context?
Solution
The decorator is a type with the same CommandHandler[C] interface that holds the next handler. The transaction is opened before the call, put into the context under the private txKey{} key (an empty unexported type cannot collide with other keys), and finished according to the outcome. The named result err lets the deferred function see the outcome and roll back on any error, including a commit error.
func TxFrom(ctx context.Context) (*sql.Tx, bool) {
tx, ok := ctx.Value(txKey{}).(*sql.Tx)
return tx, ok
}
type txDecorator[C any] struct {
db *sql.DB
next CommandHandler[C]
}
func WithTx[C any](db *sql.DB, next CommandHandler[C]) CommandHandler[C] {
return txDecorator[C]{db: db, next: next}
}
func (d txDecorator[C]) Handle(ctx context.Context, cmd C) (err error) {
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() {
if p := recover(); p != nil {
_ = tx.Rollback()
panic(p) // rolled back, now re-panic
}
if err != nil {
// after a failed Commit the tx is already closed — ErrTxDone is not an error
if rbErr := tx.Rollback(); rbErr != nil && !errors.Is(rbErr, sql.ErrTxDone) {
err = errors.Join(err, fmt.Errorf("rollback: %w", rbErr))
}
}
}()
if err = d.next.Handle(context.WithValue(ctx, txKey{}, tx), cmd); err != nil {
return fmt.Errorf("handle %T: %w", cmd, err)
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("commit: %w", err)
}
return nil
}A repository takes the transaction from the context and fails loudly when called outside the decorator:
func (r *OrderRepo) Save(ctx context.Context, o *order.Order) error {
tx, ok := TxFrom(ctx)
if !ok {
return errors.New("order repo: no transaction in context")
}
_, err := tx.ExecContext(ctx,
`UPDATE orders SET status = $1, version = version + 1 WHERE id = $2`,
o.Status(), o.ID())
return err
}The alternative to a transaction in the context is an explicit Unit of Work: the handler gets a function like Update(ctx, func(repos Repos) error) error that opens a transaction and passes repositories bound to it. The dependency is then visible in the signature instead of hidden in the context, but every handler must call it itself.