-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransaction.go
54 lines (42 loc) · 1.17 KB
/
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
49
50
51
52
53
54
package makroud
import (
"context"
"database/sql"
"github.com/pkg/errors"
)
// TxOptions is an alias for sql.TxOptions to reduce import leak.
// This alias allows the use of makroud.TxOptions and sql.TxOptions seamlessly.
type TxOptions = sql.TxOptions
// List of supported isolation level for a postgres transaction.
const (
LevelDefault = sql.LevelDefault
LevelReadUncommitted = sql.LevelReadUncommitted
LevelReadCommitted = sql.LevelReadCommitted
LevelRepeatableRead = sql.LevelRepeatableRead
LevelSerializable = sql.LevelSerializable
)
// Transaction will creates a transaction.
func Transaction(ctx context.Context, driver Driver, opts *TxOptions,
handler func(driver Driver) error) error {
if driver == nil {
return errors.Wrap(ErrInvalidDriver, "makroud: cannot create a transaction")
}
tx, err := driver.Begin(ctx, opts)
if err != nil {
return err
}
err = handler(tx)
if err != nil {
thr := tx.Rollback()
if thr != nil && driver.HasObserver() {
thr = errors.Wrap(thr, "makroud: trying to rollback transaction")
driver.Observer().OnRollback(thr, nil)
}
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}