This repository was archived by the owner on Feb 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstmt_tx.go
More file actions
72 lines (61 loc) · 1.32 KB
/
stmt_tx.go
File metadata and controls
72 lines (61 loc) · 1.32 KB
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
package orm
import (
"context"
"database/sql"
"fmt"
"sync"
)
var poolTx = sync.Pool{New: func() interface{} { return &tx{} }}
type (
Tx interface {
Exec(vv ...func(e Executor))
Query(vv ...func(q Querier))
}
tx struct {
v []interface{}
}
dbGetter interface {
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}
)
func (v *tx) Exec(vv ...func(q Executor)) {
for _, f := range vv {
v.v = append(v.v, f)
}
}
func (v *tx) Query(vv ...func(q Querier)) {
for _, f := range vv {
v.v = append(v.v, f)
}
}
func (v *tx) Reset() *tx {
v.v = v.v[:0]
return v
}
func (s *Stmt) TransactionContext(name string, ctx context.Context, call func(v Tx)) error {
q, ok := poolTx.Get().(*tx)
if !ok {
return ErrInvalidModelPool
}
defer poolTx.Put(q.Reset())
call(q)
return s.TxContext(name, ctx, func(ctx context.Context, tx *sql.Tx) error {
for i, c := range q.v {
if cc, ok := c.(func(q Executor)); ok {
if err := callExecContext(ctx, tx, cc); err != nil {
return err
}
continue
}
if cc, ok := c.(func(q Querier)); ok {
if err := callQueryContext(ctx, tx, cc); err != nil {
return err
}
continue
}
return fmt.Errorf("unknown query model #%d", i)
}
return nil
})
}