Debian Codegraph @

query.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package dbx
6
7 import (
8 "context"
9 "database/sql"
10 "database/sql/driver"
11 "encoding/hex"
12 "errors"
13 "fmt"
14 "strings"
15 "time"
16 )
17
18 // ExecHookFunc executes before op allowing custom handling like auto fail/retry.
19 type ExecHookFunc func(q *Query, op func() error) error
20
21 // OneHookFunc executes right before the query populate the row result from One() call (aka. op).
22 type OneHookFunc func(q *Query, a interface{}, op func(b interface{}) error) error
23
24 // AllHookFunc executes right before the query populate the row result from All() call (aka. op).
25 type AllHookFunc func(q *Query, sliceA interface{}, op func(sliceB interface{}) error) error
26
27 // Params represents a list of parameter values to be bound to a SQL statement.
28 // The map keys are the parameter names while the map values are the corresponding parameter values.
29 type Params map[string]interface{}
30
31 // Executor prepares, executes, or queries a SQL statement.
32 type Executor interface {
33 // Exec executes a SQL statement
34 Exec(query string, args ...interface{}) (sql.Result, error)
35 // ExecContext executes a SQL statement with the given context
36 ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
37 // Query queries a SQL statement
38 Query(query string, args ...interface{}) (*sql.Rows, error)
39 // QueryContext queries a SQL statement with the given context
40 QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
41 // Prepare creates a prepared statement
42 Prepare(query string) (*sql.Stmt, error)
43 }
44
45 // Query represents a SQL statement to be executed.
46 type Query struct {
47 executor Executor
48
49 sql, rawSQL string
50 placeholders []string
51 params Params
52
53 stmt *sql.Stmt
54 ctx context.Context
55
56 // hooks
57 execHook ExecHookFunc
58 oneHook OneHookFunc
59 allHook AllHookFunc
60
61 // FieldMapper maps struct field names to DB column names.
62 FieldMapper FieldMapFunc
63 // LastError contains the last error (if any) of the query.
64 // LastError is cleared by Execute(), Row(), Rows(), One(), and All().
65 LastError error
66 // LogFunc is used to log the SQL statement being executed.
67 LogFunc LogFunc
68 // PerfFunc is used to log the SQL execution time. It is ignored if nil.
69 // Deprecated: Please use QueryLogFunc and ExecLogFunc instead.
70 PerfFunc PerfFunc
71 // QueryLogFunc is called each time when performing a SQL query that returns data.
72 QueryLogFunc QueryLogFunc
73 // ExecLogFunc is called each time when a SQL statement is executed.
74 ExecLogFunc ExecLogFunc
75 }
76
77 // NewQuery creates a new Query with the given SQL statement.
78 func NewQuery(db *DB, executor Executor, sql string) *Query {
79 rawSQL, placeholders := db.processSQL(sql)
80 return &Query{
81 executor: executor,
82 sql: sql,
83 rawSQL: rawSQL,
84 placeholders: placeholders,
85 params: Params{},
86 ctx: db.ctx,
87 FieldMapper: db.FieldMapper,
88 LogFunc: db.LogFunc,
89 PerfFunc: db.PerfFunc,
90 QueryLogFunc: db.QueryLogFunc,
91 ExecLogFunc: db.ExecLogFunc,
92 }
93 }
94
95 // SQL returns the original SQL used to create the query.
96 // The actual SQL (RawSQL) being executed is obtained by replacing the named
97 // parameter placeholders with anonymous ones.
98 func (q *Query) SQL() string {
99 return q.sql
100 }
101
102 // Context returns the context associated with the query.
103 func (q *Query) Context() context.Context {
104 return q.ctx
105 }
106
107 // WithContext associates a context with the query.
108 func (q *Query) WithContext(ctx context.Context) *Query {
109 q.ctx = ctx
110 return q
111 }
112
113 // WithExecHook associates the provided exec hook function with the query.
114 //
115 // It is called for every Query resolver (Execute(), One(), All(), Row(), Column()),
116 // allowing you to implement auto fail/retry or any other additional handling.
117 func (q *Query) WithExecHook(fn ExecHookFunc) *Query {
118 q.execHook = fn
119 return q
120 }
121
122 // WithOneHook associates the provided hook function with the query,
123 // called on q.One(), allowing you to implement custom struct scan based
124 // on the One() argument and/or result.
125 func (q *Query) WithOneHook(fn OneHookFunc) *Query {
126 q.oneHook = fn
127 return q
128 }
129
130 // WithOneHook associates the provided hook function with the query,
131 // called on q.All(), allowing you to implement custom slice scan based
132 // on the All() argument and/or result.
133 func (q *Query) WithAllHook(fn AllHookFunc) *Query {
134 q.allHook = fn
135 return q
136 }
137
138 // logSQL returns the SQL statement with parameters being replaced with the actual values.
139 // The result is only for logging purpose and should not be used to execute.
140 func (q *Query) logSQL() string {
141 s := q.sql
142 for k, v := range q.params {
143 if valuer, ok := v.(driver.Valuer); ok && valuer != nil {
144 v, _ = valuer.Value()
145 }
146 var sv string
147 if str, ok := v.(string); ok {
148 sv = "'" + strings.Replace(str, "'", "''", -1) + "'"
149 } else if bs, ok := v.([]byte); ok {
150 sv = "0x" + hex.EncodeToString(bs)
151 } else {
152 sv = fmt.Sprintf("%v", v)
153 }
154 s = strings.Replace(s, "{:"+k+"}", sv, -1)
155 }
156 return s
157 }
158
159 // Params returns the parameters to be bound to the SQL statement represented by this query.
160 func (q *Query) Params() Params {
161 return q.params
162 }
163
164 // Prepare creates a prepared statement for later queries or executions.
165 // Close() should be called after finishing all queries.
166 func (q *Query) Prepare() *Query {
167 stmt, err := q.executor.Prepare(q.rawSQL)
168 if err != nil {
169 q.LastError = err
170 return q
171 }
172 q.stmt = stmt
173 return q
174 }
175
176 // Close closes the underlying prepared statement.
177 // Close does nothing if the query has not been prepared before.
178 func (q *Query) Close() error {
179 if q.stmt == nil {
180 return nil
181 }
182
183 err := q.stmt.Close()
184 q.stmt = nil
185 return err
186 }
187
188 // Bind sets the parameters that should be bound to the SQL statement.
189 // The parameter placeholders in the SQL statement are in the format of "{:ParamName}".
190 func (q *Query) Bind(params Params) *Query {
191 if len(q.params) == 0 {
192 q.params = params
193 } else {
194 for k, v := range params {
195 q.params[k] = v
196 }
197 }
198 return q
199 }
200
201 // Execute executes the SQL statement without retrieving data.
202 func (q *Query) Execute() (sql.Result, error) {
203 var result sql.Result
204
205 execErr := q.execWrap(func() error {
206 var err error
207 result, err = q.execute()
208 return err
209 })
210
211 return result, execErr
212 }
213
214 func (q *Query) execute() (result sql.Result, err error) {
215 err = q.LastError
216 q.LastError = nil
217 if err != nil {
218 return
219 }
220
221 var params []interface{}
222 params, err = replacePlaceholders(q.placeholders, q.params)
223 if err != nil {
224 return
225 }
226
227 start := time.Now()
228
229 if q.ctx == nil {
230 if q.stmt == nil {
231 result, err = q.executor.Exec(q.rawSQL, params...)
232 } else {
233 result, err = q.stmt.Exec(params...)
234 }
235 } else {
236 if q.stmt == nil {
237 result, err = q.executor.ExecContext(q.ctx, q.rawSQL, params...)
238 } else {
239 result, err = q.stmt.ExecContext(q.ctx, params...)
240 }
241 }
242
243 if q.ExecLogFunc != nil {
244 q.ExecLogFunc(q.ctx, time.Now().Sub(start), q.logSQL(), result, err)
245 }
246 if q.LogFunc != nil {
247 q.LogFunc("[%.2fms] Execute SQL: %v", float64(time.Now().Sub(start).Milliseconds()), q.logSQL())
248 }
249 if q.PerfFunc != nil {
250 q.PerfFunc(time.Now().Sub(start).Nanoseconds(), q.logSQL(), true)
251 }
252 return
253 }
254
255 // One executes the SQL statement and populates the first row of the result into a struct or NullStringMap.
256 // Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how to specify
257 // the variable to be populated.
258 // Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned.
259 func (q *Query) One(a interface{}) error {
260 return q.execWrap(func() error {
261 rows, err := q.Rows()
262 if err != nil {
263 return err
264 }
265
266 if q.oneHook != nil {
267 return q.oneHook(q, a, rows.one)
268 }
269
270 return rows.one(a)
271 })
272 }
273
274 // All executes the SQL statement and populates all the resulting rows into a slice of struct or NullStringMap.
275 // The slice must be given as a pointer. Each slice element must be either a struct or a NullStringMap.
276 // Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how each slice element can be.
277 // If the query returns no row, the slice will be an empty slice (not nil).
278 func (q *Query) All(slice interface{}) error {
279 return q.execWrap(func() error {
280 rows, err := q.Rows()
281 if err != nil {
282 return err
283 }
284
285 if q.allHook != nil {
286 return q.allHook(q, slice, rows.all)
287 }
288
289 return rows.all(slice)
290 })
291 }
292
293 // Row executes the SQL statement and populates the first row of the result into a list of variables.
294 // Note that the number of the variables should match to that of the columns in the query result.
295 // Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned.
296 func (q *Query) Row(a ...interface{}) error {
297 return q.execWrap(func() error {
298 rows, err := q.Rows()
299 if err != nil {
300 return err
301 }
302 return rows.row(a...)
303 })
304 }
305
306 // Column executes the SQL statement and populates the first column of the result into a slice.
307 // Note that the parameter must be a pointer to a slice.
308 func (q *Query) Column(a interface{}) error {
309 return q.execWrap(func() error {
310 rows, err := q.Rows()
311 if err != nil {
312 return err
313 }
314 return rows.column(a)
315 })
316 }
317
318 // Rows executes the SQL statement and returns a Rows object to allow retrieving data row by row.
319 func (q *Query) Rows() (rows *Rows, err error) {
320 err = q.LastError
321 q.LastError = nil
322 if err != nil {
323 return
324 }
325
326 var params []interface{}
327 params, err = replacePlaceholders(q.placeholders, q.params)
328 if err != nil {
329 return
330 }
331
332 start := time.Now()
333
334 var rr *sql.Rows
335 if q.ctx == nil {
336 if q.stmt == nil {
337 rr, err = q.executor.Query(q.rawSQL, params...)
338 } else {
339 rr, err = q.stmt.Query(params...)
340 }
341 } else {
342 if q.stmt == nil {
343 rr, err = q.executor.QueryContext(q.ctx, q.rawSQL, params...)
344 } else {
345 rr, err = q.stmt.QueryContext(q.ctx, params...)
346 }
347 }
348 rows = &Rows{rr, q.FieldMapper}
349
350 if q.QueryLogFunc != nil {
351 q.QueryLogFunc(q.ctx, time.Now().Sub(start), q.logSQL(), rr, err)
352 }
353 if q.LogFunc != nil {
354 q.LogFunc("[%.2fms] Query SQL: %v", float64(time.Now().Sub(start).Milliseconds()), q.logSQL())
355 }
356 if q.PerfFunc != nil {
357 q.PerfFunc(time.Now().Sub(start).Nanoseconds(), q.logSQL(), false)
358 }
359 return
360 }
361
362 func (q *Query) execWrap(op func() error) error {
363 if q.execHook != nil {
364 return q.execHook(q, op)
365 }
366 return op()
367 }
368
369 // replacePlaceholders converts a list of named parameters into a list of anonymous parameters.
370 func replacePlaceholders(placeholders []string, params Params) ([]interface{}, error) {
371 if len(placeholders) == 0 {
372 return nil, nil
373 }
374
375 var result []interface{}
376 for _, name := range placeholders {
377 if value, ok := params[name]; ok {
378 result = append(result, value)
379 } else {
380 return nil, errors.New("Named parameter not found: " + name)
381 }
382 }
383 return result, nil
384 }