-
Notifications
You must be signed in to change notification settings - Fork 28
/
transaction.go
58 lines (51 loc) · 1.12 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
package sqlingo
import (
"context"
"database/sql"
)
// Transaction is the interface of a transaction with underlying sql.Tx object.
// It provides methods to execute DDL and TCL operations.
type Transaction interface {
GetDB() *sql.DB
GetTx() *sql.Tx
Query(sql string) (Cursor, error)
Execute(sql string) (sql.Result, error)
Select(fields ...interface{}) selectWithFields
SelectDistinct(fields ...interface{}) selectWithFields
SelectFrom(tables ...Table) selectWithTables
InsertInto(table Table) insertWithTable
Update(table Table) updateWithSet
DeleteFrom(table Table) deleteWithTable
}
func (d *database) GetTx() *sql.Tx {
return d.tx
}
func (d *database) BeginTx(ctx context.Context, opts *sql.TxOptions, f func(tx Transaction) error) error {
if ctx == nil {
ctx = context.Background()
}
tx, err := d.db.BeginTx(ctx, opts)
if err != nil {
return err
}
isCommitted := false
defer func() {
if !isCommitted {
_ = tx.Rollback()
}
}()
if f != nil {
db := *d
db.tx = tx
err = f(&db)
if err != nil {
return err
}
}
err = tx.Commit()
if err != nil {
return err
}
isCommitted = true
return nil
}