forked from go-reform/reform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtx.go
60 lines (51 loc) · 1.63 KB
/
tx.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
package reform
import (
"database/sql"
"time"
)
// TXInterface is a subset of *sql.Tx used by reform.
// Can be used together with NewTXFromInterface for easier integration with existing code or for passing test doubles.
type TXInterface interface {
DBTX
Commit() error
Rollback() error
}
// check interface
var _ TXInterface = (*sql.Tx)(nil)
// TX represents a SQL database transaction.
type TX struct {
*Querier
tx TXInterface
}
// NewTX creates new TX object for given SQL database transaction.
// "dbForCallbacks" is passed to callback functions like "BeforeInsert" or "AfterFind" (can be nil)
func NewTX(tx *sql.Tx, dialect Dialect, logger Logger, dbForCallbacks *DB) *TX {
return NewTXFromInterface(tx, dialect, logger, dbForCallbacks)
}
// NewTXFromInterface creates new TX object for given TXInterface.
// Can be used for easier integration with existing code or for passing test doubles.
// "dbForCallbacks" is passed to callback functions like "BeforeInsert" or "AfterFind" (can be nil)
func NewTXFromInterface(tx TXInterface, dialect Dialect, logger Logger, dbForCallbacks *DB) *TX {
return &TX{
Querier: newQuerier(tx, dialect, logger, dbForCallbacks),
tx: tx,
}
}
// Commit commits the transaction.
func (tx *TX) Commit() error {
tx.logBefore("COMMIT", nil)
start := time.Now()
err := tx.tx.Commit()
tx.logAfter("COMMIT", nil, time.Since(start), err)
return err
}
// Rollback aborts the transaction.
func (tx *TX) Rollback() error {
tx.logBefore("ROLLBACK", nil)
start := time.Now()
err := tx.tx.Rollback()
tx.logAfter("ROLLBACK", nil, time.Since(start), err)
return err
}
// check interface
var _ DBTX = (*TX)(nil)