tx

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 1 Imported by: 0

README

tx

Go version GoDoc license codecov

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
    })
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FakeManager

type FakeManager[T any] struct {
	// contains filtered or unexported fields
}

FakeManager runs callbacks with a fixed repository without starting transactions. It should only be used in tests.

func NewFakeManager

func NewFakeManager[T any](repo T) *FakeManager[T]

NewFakeManager creates a manager that passes repo to each callback.

func (*FakeManager[T]) InTx

func (m *FakeManager[T]) InTx(ctx context.Context, f func(ctx context.Context, repo T) error) error

InTx calls f with the stored repository and returns its error.

type Manager

type Manager[T any] interface {
	// InTx runs f with a transaction-bound repository.
	InTx(ctx context.Context, f func(ctx context.Context, repo T) error) error
}

Manager runs callbacks with a repository of type T within a transaction.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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