Handling Database Transaction in Logic layer
In Repository
/Data Access layer
func (r *RepoImpl) Delete(ctx context.Context) (int64, error) {
txn, err := dbtxn.Use(ctx, r.DB) // use transaction if begin detected
if err != nil { // create transaction error
return -1, err
}
db := txn // transaction object or database connection
// result, err := ...
if err != nil {
txn.AppendError(err) // append error to plan for rollback
return -1, err
}
// ...
}
In Service
/Business Logic layer
func (s *SvcImpl) SomeOperation(ctx context.Context) (err error){
txn := dbtxn.Begin(&ctx) // begin the transaction
defer txn.CommitWithError(&err) // commit/rollback in end function and override err variable
// ...
}
This project is licensed under the MIT License - see the LICENSE.md file for details