forked from rainycape/gondola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
91 lines (82 loc) · 1.81 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
80
81
82
83
84
85
86
87
88
89
90
91
package orm
import (
"gnd.la/orm/driver"
)
var (
ErrInTransaction = driver.ErrInTransaction
ErrNotInTransaction = driver.ErrNotInTransaction
ErrFinished = driver.ErrFinished
)
type Tx struct {
Orm
// Parent orm
o *Orm
tx driver.Tx
done bool
}
// Begin just returns ErrInTransaction when called
// from a transaction.
func (t *Tx) Begin() (*Tx, error) {
return nil, ErrInTransaction
}
// Commit commits the current transaction. If the transaction
// was already committed or rolled back, it returns ErrFinished.
func (t *Tx) Commit() error {
if t.done {
return ErrFinished
}
if t.logger != nil {
t.logger.Debug("Commiting transaction")
}
err := t.tx.Commit()
if err != nil {
return err
}
t.done = true
return nil
}
// MustCommit works like Commit, but panics if there's an error.
func (t *Tx) MustCommit() {
if err := t.Commit(); err != nil {
panic(err)
}
}
// Rollback rolls back the current transaction. If the transaction
// was already committed or rolled back, it returns ErrFinished.
func (t *Tx) Rollback() error {
if t.done {
return ErrFinished
}
if t.logger != nil {
t.logger.Debug("Rolling back transaction")
}
err := t.tx.Rollback()
if err != nil {
return err
}
t.done = true
return nil
}
// MustRollback works like Rollback, but panics if there's an error.
func (t *Tx) MustRollback() {
if err := t.Rollback(); err != nil {
panic(err)
}
}
// Close finishes this transaction with a rollback if it hasn't been
// commited or rolled back yet. It's intended to be called using defer
// so you can cleanly release a transaction even if your code
// panics before commiting it. e.g.
//
// tx, err := o.Begin()
// if err != nil {
// panic(err)
// }
// defer tx.Close()
// // do some stuff with tx
// tx.MustCommit()
func (t *Tx) Close() {
if !t.done {
t.Rollback()
}
}