github.com/wfusion/gofusion@v1.1.14/db/tx.go (about)

     1  package db
     2  
     3  import (
     4  	"context"
     5  
     6  	"gorm.io/gorm"
     7  
     8  	"github.com/wfusion/gofusion/common/infra/drivers/orm"
     9  	"github.com/wfusion/gofusion/common/utils"
    10  )
    11  
    12  type txOption struct {
    13  	dbName string
    14  }
    15  
    16  func TxUse(name string) utils.OptionFunc[txOption] {
    17  	return func(o *txOption) {
    18  		o.dbName = name
    19  	}
    20  }
    21  
    22  // WithinTx 事务内执行 DAL 操作
    23  func WithinTx(ctx context.Context, cb func(ctx context.Context) (err error), opts ...utils.OptionExtender) error {
    24  	var db *DB
    25  
    26  	o := utils.ApplyOptions[useOption](opts...)
    27  	opt := utils.ApplyOptions[txOption](opts...)
    28  	if opt.dbName == "" {
    29  		db = GetCtxGormDB(ctx)
    30  	} else {
    31  		utils.IfAny(
    32  			func() bool { db = GetCtxGormDBByName(ctx, opt.dbName); return db != nil },
    33  			func() bool { db = Use(ctx, opt.dbName, AppName(o.appName)); return db != nil },
    34  		)
    35  	}
    36  	if db == nil {
    37  		panic(ErrDatabaseNotFound)
    38  	}
    39  
    40  	return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
    41  		return cb(SetCtxGormDB(ctx, &DB{
    42  			DB:                   &orm.DB{DB: tx},
    43  			Name:                 db.Name,
    44  			tableShardingPlugins: db.tableShardingPlugins,
    45  		}))
    46  	})
    47  }