transaction.go 895 字节
package transaction

import (
	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
)

type TransactionContext struct {
	PgDd *pg.DB
	PgTx *pg.Tx
}

func (transactionContext *TransactionContext) StartTransaction() error {
	tx, err := transactionContext.PgDd.Begin()
	if err != nil {
		return err
	}
	transactionContext.PgTx = tx
	return nil
}

func (transactionContext *TransactionContext) CommitTransaction() error {
	err := transactionContext.PgTx.Commit()
	return err
}

func (transactionContext *TransactionContext) RollbackTransaction() error {
	err := transactionContext.PgTx.Rollback()
	return err
}

func (transactionContext *TransactionContext) GetDB() orm.DB {
	if transactionContext.PgTx != nil {
		return transactionContext.PgTx
	}
	return transactionContext.PgDd
}

func NewPGTransactionContext(pgDd *pg.DB) *TransactionContext {
	return &TransactionContext{
		PgDd: pgDd,
	}
}