feat(uow): add uow
This commit is contained in:
parent
187d4f4f70
commit
85e91699be
1 changed files with 34 additions and 0 deletions
34
persistence/repositories/uow.go
Normal file
34
persistence/repositories/uow.go
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UnitOfWork struct {
|
||||||
|
db *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUnitOfWork(db *sql.DB) *UnitOfWork {
|
||||||
|
return &UnitOfWork{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UnitOfWork) Execute(ctx context.Context, fn func(tx *sql.Tx) error) error {
|
||||||
|
tx, err := u.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if err != nil {
|
||||||
|
_ = tx.Rollback()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := fn(tx); err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue