Debian Codegraph @

select.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 "reflect"
10 )
11
12 // BuildHookFunc defines a callback function that is executed on Query creation.
13 type BuildHookFunc func(q *Query)
14
15 // SelectQuery represents a DB-agnostic SELECT query.
16 // It can be built into a DB-specific query by calling the Build() method.
17 type SelectQuery struct {
18 // FieldMapper maps struct field names to DB column names.
19 FieldMapper FieldMapFunc
20 // TableMapper maps structs to DB table names.
21 TableMapper TableMapFunc
22
23 builder Builder
24 ctx context.Context
25 buildHook BuildHookFunc
26
27 preFragment string
28 postFragment string
29 selects []string
30 distinct bool
31 selectOption string
32 from []string
33 where Expression
34 join []JoinInfo
35 orderBy []string
36 groupBy []string
37 having Expression
38 union []UnionInfo
39 limit int64
40 offset int64
41 params Params
42 }
43
44 // JoinInfo contains the specification for a JOIN clause.
45 type JoinInfo struct {
46 Join string
47 Table string
48 On Expression
49 }
50
51 // UnionInfo contains the specification for a UNION clause.
52 type UnionInfo struct {
53 All bool
54 Query *Query
55 }
56
57 // NewSelectQuery creates a new SelectQuery instance.
58 func NewSelectQuery(builder Builder, db *DB) *SelectQuery {
59 return &SelectQuery{
60 builder: builder,
61 selects: []string{},
62 from: []string{},
63 join: []JoinInfo{},
64 orderBy: []string{},
65 groupBy: []string{},
66 union: []UnionInfo{},
67 limit: -1,
68 params: Params{},
69 ctx: db.ctx,
70 FieldMapper: db.FieldMapper,
71 TableMapper: db.TableMapper,
72 }
73 }
74
75 // WithBuildHook runs the provided hook function with the query created on Build().
76 func (q *SelectQuery) WithBuildHook(fn BuildHookFunc) *SelectQuery {
77 q.buildHook = fn
78 return q
79 }
80
81 // Context returns the context associated with the query.
82 func (q *SelectQuery) Context() context.Context {
83 return q.ctx
84 }
85
86 // WithContext associates a context with the query.
87 func (q *SelectQuery) WithContext(ctx context.Context) *SelectQuery {
88 q.ctx = ctx
89 return q
90 }
91
92 // PreFragment sets SQL fragment that should be prepended before the select query (e.g. WITH clause).
93 func (s *SelectQuery) PreFragment(fragment string) *SelectQuery {
94 s.preFragment = fragment
95 return s
96 }
97
98 // PostFragment sets SQL fragment that should be appended at the end of the main select query.
99 //
100 // If there is "UNION"/"UNION ALL" clause then the extra UNION queries
101 // are appended after the PostFragment.
102 func (s *SelectQuery) PostFragment(fragment string) *SelectQuery {
103 s.postFragment = fragment
104 return s
105 }
106
107 // Select specifies the columns to be selected.
108 // Column names will be automatically quoted.
109 func (s *SelectQuery) Select(cols ...string) *SelectQuery {
110 s.selects = cols
111 return s
112 }
113
114 // AndSelect adds additional columns to be selected.
115 // Column names will be automatically quoted.
116 func (s *SelectQuery) AndSelect(cols ...string) *SelectQuery {
117 s.selects = append(s.selects, cols...)
118 return s
119 }
120
121 // Distinct specifies whether to select columns distinctively.
122 // By default, distinct is false.
123 func (s *SelectQuery) Distinct(v bool) *SelectQuery {
124 s.distinct = v
125 return s
126 }
127
128 // SelectOption specifies additional option that should be append to "SELECT".
129 func (s *SelectQuery) SelectOption(option string) *SelectQuery {
130 s.selectOption = option
131 return s
132 }
133
134 // From specifies which tables to select from.
135 // Table names will be automatically quoted.
136 func (s *SelectQuery) From(tables ...string) *SelectQuery {
137 s.from = tables
138 return s
139 }
140
141 // Where specifies the WHERE condition.
142 func (s *SelectQuery) Where(e Expression) *SelectQuery {
143 s.where = e
144 return s
145 }
146
147 // AndWhere concatenates a new WHERE condition with the existing one (if any) using "AND".
148 func (s *SelectQuery) AndWhere(e Expression) *SelectQuery {
149 s.where = And(s.where, e)
150 return s
151 }
152
153 // OrWhere concatenates a new WHERE condition with the existing one (if any) using "OR".
154 func (s *SelectQuery) OrWhere(e Expression) *SelectQuery {
155 s.where = Or(s.where, e)
156 return s
157 }
158
159 // Join specifies a JOIN clause.
160 // The "typ" parameter specifies the JOIN type (e.g. "INNER JOIN", "LEFT JOIN").
161 func (s *SelectQuery) Join(typ string, table string, on Expression) *SelectQuery {
162 s.join = append(s.join, JoinInfo{typ, table, on})
163 return s
164 }
165
166 // InnerJoin specifies an INNER JOIN clause.
167 // This is a shortcut method for Join.
168 func (s *SelectQuery) InnerJoin(table string, on Expression) *SelectQuery {
169 return s.Join("INNER JOIN", table, on)
170 }
171
172 // LeftJoin specifies a LEFT JOIN clause.
173 // This is a shortcut method for Join.
174 func (s *SelectQuery) LeftJoin(table string, on Expression) *SelectQuery {
175 return s.Join("LEFT JOIN", table, on)
176 }
177
178 // RightJoin specifies a RIGHT JOIN clause.
179 // This is a shortcut method for Join.
180 func (s *SelectQuery) RightJoin(table string, on Expression) *SelectQuery {
181 return s.Join("RIGHT JOIN", table, on)
182 }
183
184 // OrderBy specifies the ORDER BY clause.
185 // Column names will be properly quoted. A column name can contain "ASC" or "DESC" to indicate its ordering direction.
186 func (s *SelectQuery) OrderBy(cols ...string) *SelectQuery {
187 s.orderBy = cols
188 return s
189 }
190
191 // AndOrderBy appends additional columns to the existing ORDER BY clause.
192 // Column names will be properly quoted. A column name can contain "ASC" or "DESC" to indicate its ordering direction.
193 func (s *SelectQuery) AndOrderBy(cols ...string) *SelectQuery {
194 s.orderBy = append(s.orderBy, cols...)
195 return s
196 }
197
198 // GroupBy specifies the GROUP BY clause.
199 // Column names will be properly quoted.
200 func (s *SelectQuery) GroupBy(cols ...string) *SelectQuery {
201 s.groupBy = cols
202 return s
203 }
204
205 // AndGroupBy appends additional columns to the existing GROUP BY clause.
206 // Column names will be properly quoted.
207 func (s *SelectQuery) AndGroupBy(cols ...string) *SelectQuery {
208 s.groupBy = append(s.groupBy, cols...)
209 return s
210 }
211
212 // Having specifies the HAVING clause.
213 func (s *SelectQuery) Having(e Expression) *SelectQuery {
214 s.having = e
215 return s
216 }
217
218 // AndHaving concatenates a new HAVING condition with the existing one (if any) using "AND".
219 func (s *SelectQuery) AndHaving(e Expression) *SelectQuery {
220 s.having = And(s.having, e)
221 return s
222 }
223
224 // OrHaving concatenates a new HAVING condition with the existing one (if any) using "OR".
225 func (s *SelectQuery) OrHaving(e Expression) *SelectQuery {
226 s.having = Or(s.having, e)
227 return s
228 }
229
230 // Union specifies a UNION clause.
231 func (s *SelectQuery) Union(q *Query) *SelectQuery {
232 s.union = append(s.union, UnionInfo{false, q})
233 return s
234 }
235
236 // UnionAll specifies a UNION ALL clause.
237 func (s *SelectQuery) UnionAll(q *Query) *SelectQuery {
238 s.union = append(s.union, UnionInfo{true, q})
239 return s
240 }
241
242 // Limit specifies the LIMIT clause.
243 // A negative limit means no limit.
244 func (s *SelectQuery) Limit(limit int64) *SelectQuery {
245 s.limit = limit
246 return s
247 }
248
249 // Offset specifies the OFFSET clause.
250 // A negative offset means no offset.
251 func (s *SelectQuery) Offset(offset int64) *SelectQuery {
252 s.offset = offset
253 return s
254 }
255
256 // Bind specifies the parameter values to be bound to the query.
257 func (s *SelectQuery) Bind(params Params) *SelectQuery {
258 s.params = params
259 return s
260 }
261
262 // AndBind appends additional parameters to be bound to the query.
263 func (s *SelectQuery) AndBind(params Params) *SelectQuery {
264 if len(s.params) == 0 {
265 s.params = params
266 } else {
267 for k, v := range params {
268 s.params[k] = v
269 }
270 }
271 return s
272 }
273
274 // Build builds the SELECT query and returns an executable Query object.
275 func (s *SelectQuery) Build() *Query {
276 params := Params{}
277 for k, v := range s.params {
278 params[k] = v
279 }
280
281 qb := s.builder.QueryBuilder()
282
283 clauses := []string{
284 s.preFragment,
285 qb.BuildSelect(s.selects, s.distinct, s.selectOption),
286 qb.BuildFrom(s.from),
287 qb.BuildJoin(s.join, params),
288 qb.BuildWhere(s.where, params),
289 qb.BuildGroupBy(s.groupBy),
290 qb.BuildHaving(s.having, params),
291 }
292
293 sql := ""
294 for _, clause := range clauses {
295 if clause != "" {
296 if sql == "" {
297 sql = clause
298 } else {
299 sql += " " + clause
300 }
301 }
302 }
303
304 sql = qb.BuildOrderByAndLimit(sql, s.orderBy, s.limit, s.offset)
305
306 if s.postFragment != "" {
307 sql += " " + s.postFragment
308 }
309
310 sql = qb.CombineUnion(sql, qb.BuildUnion(s.union, params))
311
312 query := s.builder.NewQuery(sql).Bind(params).WithContext(s.ctx)
313
314 if s.buildHook != nil {
315 s.buildHook(query)
316 }
317
318 return query
319 }
320
321 // One executes the SELECT query and populates the first row of the result into the specified variable.
322 //
323 // If the query does not specify a "from" clause, the method will try to infer the name of the table
324 // to be selected from by calling getTableName() which will return either the variable type name
325 // or the TableName() method if the variable implements the TableModel interface.
326 //
327 // Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned.
328 func (s *SelectQuery) One(a interface{}) error {
329 if len(s.from) == 0 {
330 if tableName := s.TableMapper(a); tableName != "" {
331 s.from = []string{tableName}
332 }
333 }
334
335 return s.Build().One(a)
336 }
337
338 // Model selects the row with the specified primary key and populates the model with the row data.
339 //
340 // The model variable should be a pointer to a struct. If the query does not specify a "from" clause,
341 // it will use the model struct to determine which table to select data from. It will also use the model
342 // to infer the name of the primary key column. Only simple primary key is supported. For composite primary keys,
343 // please use Where() to specify the filtering condition.
344 func (s *SelectQuery) Model(pk, model interface{}) error {
345 t := reflect.TypeOf(model)
346 if t.Kind() == reflect.Ptr {
347 t = t.Elem()
348 }
349 if t.Kind() != reflect.Struct {
350 return VarTypeError("must be a pointer to a struct")
351 }
352
353 si := getStructInfo(t, s.FieldMapper)
354 if len(si.pkNames) == 1 {
355 return s.AndWhere(HashExp{si.nameMap[si.pkNames[0]].dbName: pk}).One(model)
356 }
357 if len(si.pkNames) == 0 {
358 return MissingPKError
359 }
360
361 return CompositePKError
362 }
363
364 // All executes the SELECT query and populates all rows of the result into a slice.
365 //
366 // Note that the slice must be passed in as a pointer.
367 //
368 // If the query does not specify a "from" clause, the method will try to infer the name of the table
369 // to be selected from by calling getTableName() which will return either the type name of the slice elements
370 // or the TableName() method if the slice element implements the TableModel interface.
371 func (s *SelectQuery) All(slice interface{}) error {
372 if len(s.from) == 0 {
373 if tableName := s.TableMapper(slice); tableName != "" {
374 s.from = []string{tableName}
375 }
376 }
377
378 return s.Build().All(slice)
379 }
380
381 // Rows builds and executes the SELECT query and returns a Rows object for data retrieval purpose.
382 // This is a shortcut to SelectQuery.Build().Rows()
383 func (s *SelectQuery) Rows() (*Rows, error) {
384 return s.Build().Rows()
385 }
386
387 // Row builds and executes the SELECT query and populates the first row of the result into the specified variables.
388 // This is a shortcut to SelectQuery.Build().Row()
389 func (s *SelectQuery) Row(a ...interface{}) error {
390 return s.Build().Row(a...)
391 }
392
393 // Column builds and executes the SELECT statement and populates the first column of the result into a slice.
394 // Note that the parameter must be a pointer to a slice.
395 // This is a shortcut to SelectQuery.Build().Column()
396 func (s *SelectQuery) Column(a interface{}) error {
397 return s.Build().Column(a)
398 }
399
400 // QueryInfo represents a debug/info struct with exported SelectQuery fields.
401 type QueryInfo struct {
402 PreFragment string
403 PostFragment string
404 Builder Builder
405 Selects []string
406 Distinct bool
407 SelectOption string
408 From []string
409 Where Expression
410 Join []JoinInfo
411 OrderBy []string
412 GroupBy []string
413 Having Expression
414 Union []UnionInfo
415 Limit int64
416 Offset int64
417 Params Params
418 Context context.Context
419 BuildHook BuildHookFunc
420 }
421
422 // Info exports common SelectQuery fields allowing to inspect the
423 // current select query options.
424 func (s *SelectQuery) Info() *QueryInfo {
425 return &QueryInfo{
426 Builder: s.builder,
427 PreFragment: s.preFragment,
428 PostFragment: s.postFragment,
429 Selects: s.selects,
430 Distinct: s.distinct,
431 SelectOption: s.selectOption,
432 From: s.from,
433 Where: s.where,
434 Join: s.join,
435 OrderBy: s.orderBy,
436 GroupBy: s.groupBy,
437 Having: s.having,
438 Union: s.union,
439 Limit: s.limit,
440 Offset: s.offset,
441 Params: s.params,
442 Context: s.ctx,
443 BuildHook: s.buildHook,
444 }
445 }