forked from gocraft/dbr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
79 lines (70 loc) · 1.74 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package dbr
import (
"context"
"database/sql"
"time"
)
// Tx is a transaction created by Session.
type Tx struct {
EventReceiver
Dialect
*sql.Tx
Timeout time.Duration
}
// GetTimeout returns timeout enforced in Tx.
func (tx *Tx) GetTimeout() time.Duration {
return tx.Timeout
}
// BeginTx creates a transaction with TxOptions.
func (sess *Session) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := sess.Connection.BeginTx(ctx, opts)
if err != nil {
return nil, sess.EventErr("dbr.begin.error", err)
}
sess.Event("dbr.begin")
return &Tx{
EventReceiver: sess.EventReceiver,
Dialect: sess.Dialect,
Tx: tx,
Timeout: sess.GetTimeout(),
}, nil
}
// Begin creates a transaction for the given session.
func (sess *Session) Begin() (*Tx, error) {
return sess.BeginTx(context.Background(), nil)
}
// Commit finishes the transaction.
func (tx *Tx) Commit() error {
err := tx.Tx.Commit()
if err != nil {
return tx.EventErr("dbr.commit.error", err)
}
tx.Event("dbr.commit")
return nil
}
// Rollback cancels the transaction.
func (tx *Tx) Rollback() error {
err := tx.Tx.Rollback()
if err != nil {
return tx.EventErr("dbr.rollback", err)
}
tx.Event("dbr.rollback")
return nil
}
// RollbackUnlessCommitted rollsback the transaction unless
// it has already been committed or rolled back.
//
// Useful to defer tx.RollbackUnlessCommitted(), so you don't
// have to handle N failure cases.
// Keep in mind the only way to detect an error on the rollback
// is via the event log.
func (tx *Tx) RollbackUnlessCommitted() {
err := tx.Tx.Rollback()
if err == sql.ErrTxDone {
// ok
} else if err != nil {
tx.EventErr("dbr.rollback_unless_committed", err)
} else {
tx.Event("dbr.rollback")
}
}