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_exec.go
More file actions
97 lines (85 loc) · 1.9 KB
/
stmt_exec.go
File metadata and controls
97 lines (85 loc) · 1.9 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package orm
import (
"context"
"database/sql"
"sync"
)
var poolExec = sync.Pool{New: func() interface{} { return &exec{} }}
type exec struct {
Q string
P [][]interface{}
B func(result Result) error
}
func (v *exec) SQL(query string, args ...interface{}) {
v.Q = query
v.Params(args...)
}
func (v *exec) Params(args ...interface{}) {
if len(args) > 0 {
v.P = append(v.P, args)
}
}
func (v *exec) Bind(call func(result Result) error) {
v.B = call
}
func (v *exec) Reset() *exec {
v.Q, v.P, v.B = "", nil, nil
return v
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type (
//Result exec result model
Result struct {
RowsAffected int64
LastInsertId int64
}
//Executor interface for generate execute query
Executor interface {
SQL(query string, args ...interface{})
Params(args ...interface{})
Bind(call func(result Result) error)
}
)
//ExecContext ...
func (s *Stmt) ExecContext(name string, ctx context.Context, call func(q Executor)) error {
return s.CallContext(name, ctx, func(ctx context.Context, db *sql.DB) error {
return callExecContext(ctx, db, call)
})
}
func callExecContext(ctx context.Context, db dbGetter, call func(q Executor)) error {
q, ok := poolExec.Get().(*exec)
if !ok {
return ErrInvalidModelPool
}
defer poolExec.Put(q.Reset())
call(q)
stmt, err := db.PrepareContext(ctx, q.Q)
if err != nil {
return err
}
defer stmt.Close() //nolint: errcheck
var total Result
for _, params := range q.P {
result, err0 := stmt.Exec(params...)
if err0 != nil {
return err0
}
rows, err0 := result.RowsAffected()
if err0 != nil {
return err0
}
total.RowsAffected += rows
rows, err0 = result.LastInsertId()
if err0 != nil {
return err0
}
total.LastInsertId = rows
}
if err = stmt.Close(); err != nil {
return err
}
if q.B == nil {
return nil
}
return q.B(total)
}