tx

A tiny transaction manager
Installation
Install the core library:
go get github.com/koaim/tx
Then install the adapter for your database library:
| Library |
Installation command |
database/sql |
go get github.com/koaim/tx/sqltx |
sqlx |
go get github.com/koaim/tx/sqlxtx |
pgx |
go get github.com/koaim/tx/pgxtx |
gorm |
go get github.com/koaim/tx/gormtx |
Features
- Does not store transactions in
context.Context
- Works with
database/sql, sqlx, pgx, and gorm
- Compatible with
sqlc and jet
- Configurable transaction isolation levels
Example
Source code
package handler
import (
"context"
"github.com/koaim/tx"
"github.com/koaim/tx/internal/example/model"
)
type users interface {
Save(ctx context.Context, user model.User) error
}
type orders interface {
Save(ctx context.Context, order model.Order) error
}
type Tx struct {
users users
orders orders
}
func NewTx(u users, o orders) Tx {
return Tx{users: u, orders: o}
}
type Handler struct {
txmngr tx.Manager[Tx]
}
func NewHandler(mngr tx.Manager[Tx]) *Handler {
return &Handler{txmngr: mngr}
}
func (h *Handler) Handle(ctx context.Context) error {
return h.txmngr.InTx(ctx, func(ctx context.Context, repo Tx) error {
// this code runs within a transaction.
repo.orders.Save(ctx, model.Order{})
repo.users.Save(ctx, model.User{})
return nil
})
}