-
Notifications
You must be signed in to change notification settings - Fork 16
/
transaction.go
53 lines (46 loc) · 1.26 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
package gobatch
import (
"database/sql"
)
// TransactionManager used by chunk step to execute chunk process in a transaction.
type TransactionManager interface {
BeginTx() (tx interface{}, err BatchError)
Commit(tx interface{}) BatchError
Rollback(tx interface{}) BatchError
}
// DefaultTxManager default TransactionManager implementation
type DefaultTxManager struct {
db *sql.DB
}
// NewTransactionManager create a TransactionManager instance
func NewTransactionManager(db *sql.DB) TransactionManager {
return &DefaultTxManager{
db: db,
}
}
// BeginTx begin a transaction
func (tm *DefaultTxManager) BeginTx() (interface{}, BatchError) {
tx, err := tm.db.Begin()
if err != nil {
return nil, NewBatchError(ErrCodeDbFail, "start transaction failed", err)
}
return tx, nil
}
// Commit commit a transaction
func (tm *DefaultTxManager) Commit(tx interface{}) BatchError {
tx1 := tx.(*sql.Tx)
err := tx1.Commit()
if err != nil {
return NewBatchError(ErrCodeDbFail, "transaction commit failed", err)
}
return nil
}
// Rollback rollback a transaction
func (tm *DefaultTxManager) Rollback(tx interface{}) BatchError {
tx1 := tx.(*sql.Tx)
err := tx1.Rollback()
if err != nil {
return NewBatchError(ErrCodeDbFail, "transaction rollback failed", err)
}
return nil
}