-
Notifications
You must be signed in to change notification settings - Fork 36
/
transaction.go
69 lines (61 loc) · 1.61 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
package dbr
import (
"context"
"database/sql"
)
// Tx is a transaction for the given Session
type Tx struct {
EventReceiver
Dialect Dialect
*sql.Tx
ctx context.Context
}
// Begin creates a transaction for the given session
func (sess *Session) Begin() (*Tx, error) {
return sess.BeginWithOpts(&sql.TxOptions{})
}
// BeginWithOpts creates a transaction for the given section with ability to set TxOpts
func (sess *Session) BeginWithOpts(opts *sql.TxOptions) (*Tx, error) {
tx, err := sess.beginTx(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,
ctx: sess.ctx,
}, 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")
}
}