unitofwork

package module
v0.0.0-...-bb86b3d Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 5 Imported by: 0

README

Unit of Work for Go (unitofwork)

Go Reference Go Report Card

A production-ready, idiomatic Go implementation of the Unit of Work pattern powered by context.Context transaction propagation.

It decouples your domain and application service layers from repository implementations, eliminating the need to pass around *gorm.DB or *sql.Tx across business boundaries.


🌟 Why unitofwork?

In many Go projects (especially Clean Architecture or DDD codebases), handling transactions across multiple repositories often leads to antipatterns:

Anti-Pattern / Traditional Approaches Problems
Passing *gorm.DB or *sql.Tx into Repository methods Leaks database/ORM implementation details into the domain/interface layer.
Injecting tx into Service structs Makes Services non-thread-safe and breaks dependency injection scopes.
Manual tx.Begin(), tx.Commit(), tx.Rollback() Prone to leak connections if defer tx.Rollback() is forgotten or on panic.
Publishing domain events inside transactions If the transaction rolls back after an HTTP/MQ call, data becomes inconsistent.
The unitofwork Solution:
  1. Implicit Transaction Propagation via context.Context: Repositories simply call unitofwork.GetDB(ctx, r.db) — if a transaction exists in the context, it participates; otherwise, it seamlessly falls back to the default database handle.
  2. Re-entrancy & Nested Transactions: Safely nest multiple ExecTx calls without creating deadlock or double-commit issues (PropagationRequired and PropagationRequiresNew).
  3. Transaction Lifecycle Hooks: Register RegisterOnCommit and RegisterOnRollback callbacks directly inside the transaction block (ideal for transactional outbox, cache eviction, or sending notifications).
  4. Panic Safety: Built-in recovery ensures transactions are safely rolled back if a panic occurs, re-propagating the panic afterwards.

🏗️ Architecture

sequenceDiagram
    autonumber
    actor Client
    participant Service as Application Service
    participant UoW as unitofwork.ExecTx
    participant RepoA as OrderRepository
    participant RepoB as OutboxRepository
    participant DB as Database (Tx)

    Client->>Service: CreateOrder(ctx, req)
    Service->>UoW: ExecTx(ctx, db, func(txCtx) { ... })
    UoW->>DB: BeginTx()
    Note over UoW: Injects active Tx & Hooks into txCtx
    
    UoW->>Service: Execute Callback(txCtx)
    Service->>RepoA: Create(txCtx, order)
    RepoA->>DB: unitofwork.GetDB(txCtx) -> Exec INSERT
    Service->>RepoB: RecordEvent(txCtx, event)
    RepoB->>DB: unitofwork.GetDB(txCtx) -> Exec INSERT
    
    Service->>UoW: RegisterOnCommit(txCtx, publishFunc)
    
    alt Success
        Service-->>UoW: return nil
        UoW->>DB: Commit()
        UoW->>UoW: Execute OnCommit Hooks (publishFunc)
        UoW-->>Client: Success Response
    else Failure or Panic
        Service-->>UoW: return err (or panic)
        UoW->>DB: Rollback()
        UoW->>UoW: Execute OnRollback Hooks
        UoW-->>Client: Error
    end

📦 Installation

go get github.com/liusonglei796/unitofwork

Requires Go 1.21 or later.


🚀 Quick Start

1. Basic Usage
package main

import (
    "context"
    "fmt"
    "github.com/liusonglei796/unitofwork"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

func main() {
    db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    ctx := context.Background()

    err := unitofwork.ExecTx(ctx, db, func(txCtx context.Context) error {
        // Automatically retrieves the active transaction handle from txCtx
        tx := unitofwork.GetDB(txCtx, db)

        if err := tx.Exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1").Error; err != nil {
            return err // Auto-rollback on error
        }

        if err := tx.Exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2").Error; err != nil {
            return err
        }

        // Post-commit hook (runs only after successful commit)
        unitofwork.RegisterOnCommit(txCtx, func() error {
            fmt.Println("Transfer committed successfully! Notify users.")
            return nil
        })

        return nil // Auto-commit
    })

    if err != nil {
        fmt.Println("Transaction failed:", err)
    }
}

🧩 Clean Architecture / DDD Example

The pattern shines when building layered architectures. Repositories know nothing about transactions; Services manage the transaction boundaries:

1. Repository Layer
type UserRepository interface {
    Create(ctx context.Context, u *User) error
}

type userRepo struct {
    db *gorm.DB
}

func (r *userRepo) Create(ctx context.Context, u *User) error {
    // If ctx has an active transaction, it uses it!
    // Otherwise, it transparently falls back to r.db!
    return unitofwork.GetDB(ctx, r.db).WithContext(ctx).Create(u).Error
}
2. Service / Use Case Layer
type UserService struct {
    db        *gorm.DB
    userRepo  UserRepository
    auditRepo AuditLogRepository
}

func (s *UserService) RegisterUser(ctx context.Context, name, email string) (*User, error) {
    user := &User{Name: name, Email: email}

    err := unitofwork.ExecTx(ctx, s.db, func(txCtx context.Context) error {
        // Pass txCtx to repositories
        if err := s.userRepo.Create(txCtx, user); err != nil {
            return err
        }

        if err := s.auditRepo.Log(txCtx, user.ID, "REGISTER"); err != nil {
            return err
        }

        // Send email only AFTER database commit succeeds
        unitofwork.RegisterOnCommit(txCtx, func() error {
            return sendWelcomeEmail(user.Email)
        })

        return nil
    })

    return user, err
}

⚙️ Advanced Features

Transaction Propagation

Control transaction boundaries when methods call other transactional methods:

// PropagationRequired (default): joins current transaction if one exists, creates one if none exists.
unitofwork.ExecTx(ctx, db, fn, unitofwork.WithPropagation(unitofwork.PropagationRequired))

// PropagationRequiresNew: always creates a brand new, isolated transaction.
unitofwork.ExecTx(ctx, db, fn, unitofwork.WithPropagation(unitofwork.PropagationRequiresNew))
Isolation Levels & Read-Only
import "database/sql"

err := unitofwork.ExecTx(ctx, db, fn,
    unitofwork.WithIsolationLevel(sql.LevelSerializable),
    unitofwork.WithReadOnly(true),
)
Transaction Lifecycle Hooks
  • RegisterOnCommit(ctx, fn func() error): Executed sequentially right after the outer transaction successfully commits. If an OnCommit hook fails, it logs or handles errors gracefully without rolling back the already-committed DB transaction.
  • RegisterOnRollback(ctx, fn func()): Executed immediately after a rollback occurs (e.g., to clean up temporary files or release locks).

🧪 Testing

Run all unit tests with full coverage:

go test -v -race -cover ./...

🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package unitofwork provides a lightweight, clean, and idiomatic Go implementation of the Unit of Work pattern using context-based transaction propagation.

It enables decoupled domain/service layers and repositories to seamlessly share the same database transaction without polluting function signatures with framework handles.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoTransaction indicates that no active transaction was found in the context.
	ErrNoTransaction = errors.New("unitofwork: no active transaction in context")
)

Functions

func ExecTx

func ExecTx(ctx context.Context, db *gorm.DB, fn func(txCtx context.Context) error, opts ...Option) (err error)

ExecTx executes fn inside a GORM transaction with support for: 1. Re-entrancy / nested transactions (PropagationRequired vs PropagationRequiresNew) 2. Options (Isolation level, ReadOnly) 3. Post-commit and post-rollback hooks 4. Panic recovery with automatic rollback

func GetDB

func GetDB(ctx context.Context, defaultDB *gorm.DB) *gorm.DB

GetDB extracts the active transaction from context, or falls back to defaultDB with context. If defaultDB is nil (e.g. during unit tests without a real database), it returns the transaction if present or nil.

func HasTx

func HasTx(ctx context.Context) bool

HasTx returns true if there is an active transaction in the context.

func RegisterOnCommit

func RegisterOnCommit(ctx context.Context, fn func() error)

RegisterOnCommit registers a callback to be executed immediately after the outer transaction successfully commits. Useful for publishing domain events, triggering async jobs, or invalidating caches.

func RegisterOnRollback

func RegisterOnRollback(ctx context.Context, fn func())

RegisterOnRollback registers a callback to be executed immediately after the transaction is rolled back.

func WithTx

func WithTx(ctx context.Context, tx *gorm.DB) context.Context

WithTx injects a GORM transaction instance into context.

Types

type GormManager

type GormManager struct {
	// contains filtered or unexported fields
}

GormManager implements Manager using GORM as the underlying ORM engine.

func NewGormManager

func NewGormManager(db *gorm.DB) *GormManager

NewGormManager creates a new GormManager instance.

func (*GormManager) Execute

func (m *GormManager) Execute(ctx context.Context, fn func(txCtx context.Context) error, opts ...Option) error

Execute runs the callback within a GORM transaction.

type Manager

type Manager interface {
	// Execute runs the provided callback inside a managed transaction context.
	// If the callback returns an error or panics, the transaction is rolled back.
	// If the callback returns nil, the transaction is committed and OnCommit hooks are executed.
	Execute(ctx context.Context, fn func(txCtx context.Context) error, opts ...Option) error
}

Manager is the high-level Unit of Work interface that manages transactional boundaries.

type Option

type Option func(*Options)

Option configures an Options instance.

func WithIsolationLevel

func WithIsolationLevel(level sql.IsolationLevel) Option

WithIsolationLevel sets the transaction isolation level.

func WithPropagation

func WithPropagation(p Propagation) Option

WithPropagation sets the transaction propagation behavior.

func WithReadOnly

func WithReadOnly(readOnly bool) Option

WithReadOnly marks the transaction as read-only.

type Options

type Options struct {
	TxOptions   *sql.TxOptions
	Propagation Propagation
}

Options holds configuration for transaction execution.

type Propagation

type Propagation int

Propagation defines how transactions relate to each other.

const (
	// PropagationRequired (default): Support a current transaction, create a new one if none exists.
	PropagationRequired Propagation = iota

	// PropagationRequiresNew: Create a new transaction, suspending the current transaction if one exists.
	PropagationRequiresNew
)

Directories

Path Synopsis
examples
basic command
clean_arch command

Jump to

Keyboard shortcuts

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