Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetDB ¶
GetDB retrieves the appropriate *gorm.DB instance for database operations. It checks if a transaction (*gorm.DB) exists within the provided context.
- If a transaction is found (placed there by TransactionManager.ExecuteInTx), it returns the transaction instance (*gorm.Tx, which is *gorm.DB).
- If no transaction is found in the context, it returns the original *gorm.DB instance passed as an argument, allowing for non-transactional operations.
This function simplifies repository logic, allowing repository methods to work seamlessly both within and outside a transaction without needing explicit Context checks everywhere. Repository methods should call GetDB(ctx, repo.db) at the start.
Types ¶
type GormTransactionManager ¶
type GormTransactionManager struct {
// contains filtered or unexported fields
}
GormTransactionManager is a TransactionManager implementation for GORM. It holds the base *gorm.DB instance used for starting transactions.
func NewGormTransactionManager ¶
func NewGormTransactionManager(db *gorm.DB) *GormTransactionManager
NewGormTransactionManager creates a new GormTransactionManager. It takes the base *gorm.DB instance used for starting transactions. This should be called during application initialization.
func (*GormTransactionManager) ExecuteInTx ¶
func (m *GormTransactionManager) ExecuteInTx(ctx context.Context, fn TxFn) error
ExecuteInTx implements the TransactionManager interface. It wraps the standard GORM Begin/Commit/Rollback logic around the execution of fn.
type TransactionManager ¶
type TransactionManager interface {
// ExecuteInTx runs the given function within a transaction.
// The transaction is committed if fn returns nil, otherwise it's rolled back.
// The context passed to fn will contain the transaction instance, which repositories
// should retrieve using GetDB.
ExecuteInTx(ctx context.Context, fn TxFn) error
}
TransactionManager defines the interface for executing operations within a transaction. The service layer should depend on this interface.