forked from gocraft/dbr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
57 lines (50 loc) · 1.27 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
package dbr
import "database/sql"
// Tx is a transaction for the given Session
type Tx struct {
*Session
*sql.Tx
}
// Begin creates a transaction for the given session
func (sess *Session) Begin() (*Tx, error) {
tx, err := sess.DB.Begin()
if err != nil {
return nil, sess.EventErr("dbr.begin.error", err)
}
sess.Event("dbr.begin")
return &Tx{
Session: sess,
Tx: tx,
}, 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")
}
}