This repository has been 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
/
stmt_query.go
80 lines (67 loc) · 1.55 KB
/
stmt_query.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package orm
import (
"context"
"database/sql"
"sync"
)
var poolQuery = sync.Pool{New: func() interface{} { return &query{} }}
type query struct {
Q string
P []interface{}
B func(bind Scanner) error
}
func (v *query) SQL(query string, args ...interface{}) {
v.Q, v.P = query, args
}
func (v *query) Bind(call func(bind Scanner) error) {
v.B = call
}
func (v *query) Reset() *query {
v.Q, v.P, v.B = "", nil, nil
return v
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type (
//Scanner interface for bind data
Scanner interface {
Scan(args ...interface{}) error
}
//Querier interface for generate query
Querier interface {
SQL(query string, args ...interface{})
Bind(call func(bind Scanner) error)
}
)
//QueryContext ...
func (s *Stmt) QueryContext(name string, ctx context.Context, call func(q Querier)) error {
return s.CallContext(name, ctx, func(ctx context.Context, db *sql.DB) error {
return callQueryContext(ctx, db, call)
})
}
func callQueryContext(ctx context.Context, db dbGetter, call func(q Querier)) error {
q, ok := poolQuery.Get().(*query)
if !ok {
return ErrInvalidModelPool
}
defer poolQuery.Put(q.Reset())
call(q)
rows, err := db.QueryContext(ctx, q.Q, q.P...)
if err != nil {
return err
}
defer rows.Close() //nolint: errcheck
if q.B != nil {
for rows.Next() {
if err = q.B(rows); err != nil {
return err
}
}
}
if err = rows.Close(); err != nil {
return err
}
if err = rows.Err(); err != nil {
return err
}
return nil
}