-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_transaction.go
48 lines (39 loc) · 981 Bytes
/
db_transaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
func NewTransactionProvider(config *Config, db *pgxpool.Pool) *TransactionProvider {
return &TransactionProvider{
config: config,
db: db,
}
}
type TransactionProvider struct {
config *Config
db *pgxpool.Pool
}
func (t *TransactionProvider) Transact(ctx context.Context, fn func(service *ServiceRegistry) error) error {
return runInTx(ctx, t.db, func(tx pgx.Tx) error {
repository := NewRepositoryRegistry(tx)
service := NewService(t.config, repository)
return fn(service)
})
}
func runInTx(ctx context.Context, db *pgxpool.Pool, fn func(tx pgx.Tx) error) error {
tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
if err != nil {
return err
}
err = fn(tx)
if err == nil {
return tx.Commit(ctx)
}
rollbackErr := tx.Rollback(ctx)
if rollbackErr != nil {
return errors.Join(err, rollbackErr)
}
return err
}