txmanager

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2024 License: MIT Imports: 7 Imported by: 0

README

go-txmanager

Transaction Manager with gorm. Supports gorm v1 and v2.

How To Use

Prerequisite on repository

make sure to pass context on a repository, and check txConn like

var tx *gorm.DB
if txConn := txmanager.GetTxConn(ctx); txConn != nil {
    tx = txConn
}
if tx == nil {
    tx = p.db.Begin()
    defer func() {
        if err != nil {
            tx.Rollback()
            return
        }
        tx.Commit()
    }()
}

this will check current tx on passing context

Making transaction with TxManager

first, you need to start the TxManager

txManager := txmanager.StartTxManager(db)

and then make a transaction function, which form like this (just an example), you need to pass context to repository

transaction := func(ctx context.Context) error {
    err := repoA.Update(ctx, id, model)
    if err != nil {
        return err
    }

    err := repoB.Update(ctx, id, model)
    if err != nil {
        return err
    }
    return nil
}

and to execute the transaction

err := txManager.WithTransaction(context, transaction)

also you can find the example on txmanager_integration_test.go

Testing

Run Test

Run the following command to start the local test mysql

$ make test-infra-up

Run the test

$ make test

Stop the test mysql when finish testing

$ make test-infra-down

Documentation

Index

Constants

View Source
const TxConnKey = "txConn"

Variables

This section is empty.

Functions

func GetTxConn

func GetTxConn(ctx context.Context) *gorm.DB

func GetTxConnV2 added in v0.1.1

func GetTxConnV2(ctx context.Context) *gormv2.DB

Types

type GormTxManager

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

func (*GormTxManager) WithTransaction

func (g *GormTxManager) WithTransaction(parentCtx context.Context, txfn TxFn) (err error)

WithTransaction creates a new transaction and handles rollback/commit based on the error object returned by the `TxFn`

type GormV2TxManager added in v0.1.1

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

func (*GormV2TxManager) WithTransaction added in v0.1.1

func (g *GormV2TxManager) WithTransaction(parentCtx context.Context, txfn TxFn) (err error)

type TxFn

type TxFn func(ctx context.Context) error

type TxManager

type TxManager interface {
	WithTransaction(ctx context.Context, txfn TxFn) error
}

func NewGormTxManager added in v0.1.1

func NewGormTxManager(db *gormv2.DB) TxManager

NewGormTxManager create TxManagerGormV2 with dbv2

func StartTxManager

func StartTxManager(db *gorm.DB) TxManager

StartTxManager create TxManager with db

Jump to

Keyboard shortcuts

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