forked from eaigner/jet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tx.go
51 lines (44 loc) · 1.2 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
package jet
import (
"context"
"database/sql"
"errors"
)
// Tx represents a transaction instance.
// It can be created using Begin on the *Db object.
type Tx struct {
db *Db
tx *sql.Tx
qid string
}
// Query creates a prepared query that can be run with Rows or Run.
func (tx *Tx) Query(query string, args ...interface{}) Runnable {
return tx.QueryContext(context.Background(), query, args...)
}
// QueryContext creates a prepared query that can be run with Rows or Run.
func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) Runnable {
q := newQuery(ctx, tx.tx, tx.db, query, args...)
q.id = tx.qid
return q
}
// Exec calls Exec on the underlying sql.Tx.
func (tx *Tx) Exec(query string, args ...interface{}) (sql.Result, error) {
if tx == nil || tx.tx == nil {
return nil, errors.New("jet: Exec called on nil transaction")
}
return tx.tx.Exec(query, args...)
}
// Commit commits the transaction
func (tx *Tx) Commit() error {
if tx.db.LogFunc != nil {
tx.db.LogFunc(tx.qid, "COMMIT")
}
return tx.tx.Commit()
}
// Rollback rolls back the transaction
func (tx *Tx) Rollback() error {
if tx.db.LogFunc != nil {
tx.db.LogFunc(tx.qid, "ROLLBACK")
}
return tx.tx.Rollback()
}