-
Notifications
You must be signed in to change notification settings - Fork 23
/
query.go
125 lines (110 loc) · 2.07 KB
/
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package jet
import (
"database/sql"
"sync"
)
type jetQuery struct {
m sync.Mutex
db *Db
qo queryObject
id string
query string
args []interface{}
}
// newQuery initiates a new query for the provided query object (either *sql.Tx or *sql.DB)
func newQuery(qo queryObject, db *Db, query string, args ...interface{}) *jetQuery {
return &jetQuery{
qo: qo,
db: db,
id: newQueryId(),
query: query,
args: args,
}
}
func (q *jetQuery) Run() (err error) {
return q.Rows(nil)
}
func (q *jetQuery) Rows(v interface{}) (err error) {
q.m.Lock()
defer q.m.Unlock()
// disable lru in transactions
useLru := true
switch q.qo.(type) {
case *sql.Tx:
useLru = false
}
query, args := substituteMapAndArrayMarks(q.query, q.args...)
// clear query from cache on error
defer func() {
if useLru && err != nil {
q.db.lru.del(query)
}
}()
// encode complex args
enc := make([]interface{}, 0, len(args))
for _, a := range args {
v, ok := a.(ComplexValue)
if ok {
enc = append(enc, v.Encode())
} else {
enc = append(enc, a)
}
}
args = enc
// log
if q.db.LogFunc != nil {
q.db.LogFunc(q.id, query, args...)
}
// prepare statement
stmt, ok := q.db.lru.get(query)
if !useLru || !ok {
stmt, err = q.qo.Prepare(query)
if err != nil {
return err
}
if useLru {
q.db.lru.put(query, stmt)
}
}
// If no rows need to be unpacked use Exec
if v == nil {
_, err := stmt.Exec(args...)
return err
}
// run query
rows, err := stmt.Query(args...)
if err != nil {
return err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return err
}
var i int64 = 0
colMapper := &mapper{
conv: q.db.ColumnConverter,
}
for {
// Break if no more rows
if !rows.Next() {
break
}
// Scan values into containers
cont := make([]interface{}, 0, len(cols))
for i := 0; i < cap(cont); i++ {
cont = append(cont, new(interface{}))
}
err := rows.Scan(cont...)
if err != nil {
return err
}
// Map values
err = colMapper.unpack(cols, cont, v)
if err != nil {
return err
}
i++
}
return nil
}