-
Notifications
You must be signed in to change notification settings - Fork 552
/
Copy pathquery_builders.go
645 lines (547 loc) · 16.2 KB
/
query_builders.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package queries
import (
"bytes"
"fmt"
"regexp"
"sort"
"strings"
"github.com/volatiletech/strmangle"
)
var (
rgxIdentifier = regexp.MustCompile(`^(?i)"?[a-z_][_a-z0-9]*"?(?:\."?[_a-z][_a-z0-9]*"?)*$`)
rgxInClause = regexp.MustCompile(`^(?i)(.*[\s|\)|\?])IN([\s|\(|\?].*)$`)
rgxNotInClause = regexp.MustCompile(`^(?i)(.*[\s|\)|\?])NOT\s+IN([\s|\(|\?].*)$`)
)
// BuildQuery builds a query object into the query string
// and it's accompanying arguments. Using this method
// allows query building without immediate execution.
func BuildQuery(q *Query) (string, []interface{}) {
var buf *bytes.Buffer
var args []interface{}
q.removeSoftDeleteWhere()
switch {
case len(q.rawSQL.sql) != 0:
return q.rawSQL.sql, q.rawSQL.args
case q.delete:
buf, args = buildDeleteQuery(q)
case len(q.update) > 0:
buf, args = buildUpdateQuery(q)
default:
buf, args = buildSelectQuery(q)
}
defer strmangle.PutBuffer(buf)
// Cache the generated query for query object re-use
bufStr := buf.String()
q.rawSQL.sql = bufStr
q.rawSQL.args = args
return bufStr, args
}
func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
buf := strmangle.GetBuffer()
var args []interface{}
writeComment(q, buf)
writeCTEs(q, buf, &args)
hasHaving := len(q.having) != 0
hasGroupBy := len(q.groupBy) != 0
hasSimpleCount := q.count && !hasHaving && !hasGroupBy
hasComplexCount := q.count && (hasHaving || hasGroupBy)
if hasComplexCount {
buf.WriteString("SELECT COUNT(*) FROM (")
}
buf.WriteString("SELECT ")
if q.dialect.UseTopClause {
if q.limit != nil && q.offset == 0 {
fmt.Fprintf(buf, " TOP (%d) ", *q.limit)
}
}
if hasSimpleCount {
buf.WriteString("COUNT(")
}
hasSelectCols := len(q.selectCols) != 0
hasJoins := len(q.joins) != 0
hasDistinct := q.distinct != ""
if hasDistinct {
buf.WriteString("DISTINCT ")
if hasSimpleCount {
buf.WriteString("(")
}
buf.WriteString(q.distinct)
if hasSimpleCount {
buf.WriteString(")")
}
} else if hasJoins && hasSelectCols && !hasSimpleCount {
selectColsWithAs := writeAsStatements(q)
// Don't identQuoteSlice - writeAsStatements does this
buf.WriteString(strings.Join(selectColsWithAs, ", "))
} else if hasSelectCols {
buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, q.selectCols), ", "))
} else if hasJoins && !hasSimpleCount {
selectColsWithStars := writeStars(q)
buf.WriteString(strings.Join(selectColsWithStars, ", "))
} else {
buf.WriteByte('*')
}
// close SQL COUNT function
if hasSimpleCount {
buf.WriteByte(')')
}
fmt.Fprintf(buf, " FROM %s", strings.Join(strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, q.from), ", "))
if len(q.joins) > 0 {
argsLen := len(args)
joinBuf := strmangle.GetBuffer()
for _, j := range q.joins {
switch j.kind {
case JoinInner:
fmt.Fprintf(joinBuf, " INNER JOIN %s", j.clause)
case JoinOuterLeft:
fmt.Fprintf(joinBuf, " LEFT JOIN %s", j.clause)
case JoinOuterRight:
fmt.Fprintf(joinBuf, " RIGHT JOIN %s", j.clause)
case JoinOuterFull:
fmt.Fprintf(joinBuf, " FULL JOIN %s", j.clause)
default:
panic(fmt.Sprintf("Unsupported join of kind %v", j.kind))
}
args = append(args, j.args...)
}
var resp string
if q.dialect.UseIndexPlaceholders {
resp, _ = convertQuestionMarks(joinBuf.String(), argsLen+1)
} else {
resp = joinBuf.String()
}
fmt.Fprintf(buf, resp)
strmangle.PutBuffer(joinBuf)
}
where, whereArgs := whereClause(q, len(args)+1)
buf.WriteString(where)
if len(whereArgs) != 0 {
args = append(args, whereArgs...)
}
writeModifiers(q, buf, &args)
if hasComplexCount {
buf.WriteByte(')')
}
buf.WriteByte(';')
return buf, args
}
func buildDeleteQuery(q *Query) (*bytes.Buffer, []interface{}) {
var args []interface{}
buf := strmangle.GetBuffer()
writeComment(q, buf)
writeCTEs(q, buf, &args)
buf.WriteString("DELETE FROM ")
buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, q.from), ", "))
where, whereArgs := whereClause(q, 1)
if len(whereArgs) != 0 {
args = append(args, whereArgs...)
}
buf.WriteString(where)
writeModifiers(q, buf, &args)
buf.WriteByte(';')
return buf, args
}
func buildUpdateQuery(q *Query) (*bytes.Buffer, []interface{}) {
buf := strmangle.GetBuffer()
var args []interface{}
writeComment(q, buf)
writeCTEs(q, buf, &args)
buf.WriteString("UPDATE ")
buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, q.from), ", "))
cols := make(sort.StringSlice, len(q.update))
count := 0
for name := range q.update {
cols[count] = name
count++
}
cols.Sort()
for i := 0; i < len(cols); i++ {
args = append(args, q.update[cols[i]])
cols[i] = strmangle.IdentQuote(q.dialect.LQ, q.dialect.RQ, cols[i])
}
setSlice := make([]string, len(cols))
for index, col := range cols {
setSlice[index] = fmt.Sprintf("%s = %s", col, strmangle.Placeholders(q.dialect.UseIndexPlaceholders, 1, index+1, 1))
}
fmt.Fprintf(buf, " SET %s", strings.Join(setSlice, ", "))
where, whereArgs := whereClause(q, len(args)+1)
if len(whereArgs) != 0 {
args = append(args, whereArgs...)
}
buf.WriteString(where)
writeModifiers(q, buf, &args)
buf.WriteByte(';')
return buf, args
}
func writeParameterizedModifiers(q *Query, buf *bytes.Buffer, args *[]interface{}, keyword, delim string, clauses []argClause) {
argsLen := len(*args)
modBuf := strmangle.GetBuffer()
fmt.Fprintf(modBuf, keyword)
for i, j := range clauses {
if i > 0 {
modBuf.WriteString(delim)
}
modBuf.WriteString(j.clause)
*args = append(*args, j.args...)
}
var resp string
if q.dialect.UseIndexPlaceholders {
resp, _ = convertQuestionMarks(modBuf.String(), argsLen+1)
} else {
resp = modBuf.String()
}
buf.WriteString(resp)
strmangle.PutBuffer(modBuf)
}
func writeModifiers(q *Query, buf *bytes.Buffer, args *[]interface{}) {
if len(q.groupBy) != 0 {
fmt.Fprintf(buf, " GROUP BY %s", strings.Join(q.groupBy, ", "))
}
if len(q.having) != 0 {
writeParameterizedModifiers(q, buf, args, " HAVING ", " AND ", q.having)
}
if len(q.orderBy) != 0 {
writeParameterizedModifiers(q, buf, args, " ORDER BY ", ", ", q.orderBy)
}
if !q.dialect.UseTopClause {
if q.limit != nil {
fmt.Fprintf(buf, " LIMIT %d", *q.limit)
}
if q.offset != 0 {
fmt.Fprintf(buf, " OFFSET %d", q.offset)
}
} else {
// From MS SQL 2012 and above: https://technet.microsoft.com/en-us/library/ms188385(v=sql.110).aspx
// ORDER BY ...
// OFFSET N ROWS
// FETCH NEXT M ROWS ONLY
if q.offset != 0 {
// Hack from https://www.microsoftpressstore.com/articles/article.aspx?p=2314819
// ...
// As mentioned, the OFFSET-FETCH filter requires an ORDER BY clause. If you want to use arbitrary order,
// like TOP without an ORDER BY clause, you can use the trick with ORDER BY (SELECT NULL)
// ...
if len(q.orderBy) == 0 {
buf.WriteString(" ORDER BY (SELECT NULL)")
}
// This seems to be the latest version of mssql's syntax for offset
// (the suffix ROWS)
// This is true for latest sql server as well as their cloud offerings & the upcoming sql server 2019
// https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017
// https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15
fmt.Fprintf(buf, " OFFSET %d ROWS", q.offset)
if q.limit != nil {
fmt.Fprintf(buf, " FETCH NEXT %d ROWS ONLY", *q.limit)
}
}
}
if len(q.forlock) != 0 {
fmt.Fprintf(buf, " FOR %s", q.forlock)
}
}
func writeStars(q *Query) []string {
cols := make([]string, len(q.from))
for i, f := range q.from {
toks := strings.Split(f, " ")
if len(toks) == 1 {
cols[i] = fmt.Sprintf(`%s.*`, strmangle.IdentQuote(q.dialect.LQ, q.dialect.RQ, toks[0]))
continue
}
alias, name, ok := parseFromClause(toks)
if !ok {
return nil
}
if len(alias) != 0 {
name = alias
}
cols[i] = fmt.Sprintf(`%s.*`, strmangle.IdentQuote(q.dialect.LQ, q.dialect.RQ, name))
}
return cols
}
func writeAsStatements(q *Query) []string {
cols := make([]string, len(q.selectCols))
for i, col := range q.selectCols {
if !rgxIdentifier.MatchString(col) {
cols[i] = col
continue
}
toks := strings.Split(col, ".")
if len(toks) == 1 {
cols[i] = strmangle.IdentQuote(q.dialect.LQ, q.dialect.RQ, col)
continue
}
asParts := make([]string, len(toks))
for j, tok := range toks {
asParts[j] = strings.Trim(tok, `"`)
}
cols[i] = fmt.Sprintf(`%s as "%s"`, strmangle.IdentQuote(q.dialect.LQ, q.dialect.RQ, col), strings.Join(asParts, "."))
}
return cols
}
// whereClause parses a where slice and converts it into a
// single WHERE clause like:
// WHERE (a=$1) AND (b=$2) AND (a,b) in (($3, $4), ($5, $6))
//
// startAt specifies what number placeholders start at
func whereClause(q *Query, startAt int) (string, []interface{}) {
if len(q.where) == 0 {
return "", nil
}
manualParens := false
ManualParen:
for _, w := range q.where {
switch w.kind {
case whereKindLeftParen, whereKindRightParen:
manualParens = true
break ManualParen
}
}
buf := strmangle.GetBuffer()
defer strmangle.PutBuffer(buf)
var args []interface{}
notFirstExpression := false
buf.WriteString(" WHERE ")
for _, where := range q.where {
if notFirstExpression && where.kind != whereKindRightParen {
if where.orSeparator {
buf.WriteString(" OR ")
} else {
buf.WriteString(" AND ")
}
} else {
notFirstExpression = true
}
switch where.kind {
case whereKindNormal:
if !manualParens {
buf.WriteByte('(')
}
if q.dialect.UseIndexPlaceholders {
replaced, n := convertQuestionMarks(where.clause, startAt)
buf.WriteString(replaced)
startAt += n
} else {
buf.WriteString(where.clause)
}
if !manualParens {
buf.WriteByte(')')
}
args = append(args, where.args...)
case whereKindLeftParen:
buf.WriteByte('(')
notFirstExpression = false
case whereKindRightParen:
buf.WriteByte(')')
case whereKindIn, whereKindNotIn:
ln := len(where.args)
// WHERE IN () is invalid sql, so it is difficult to simply run code like:
// for _, u := range model.Users(qm.WhereIn("id IN ?",uids...)).AllP(db) {
// ...
// }
// instead when we see empty IN we produce 1=0 so it can still be chained
// with other queries
if ln == 0 {
if where.kind == whereKindIn {
buf.WriteString("(1=0)")
} else if where.kind == whereKindNotIn {
buf.WriteString("(1=1)")
}
break
}
var matches []string
if where.kind == whereKindIn {
matches = rgxInClause.FindStringSubmatch(where.clause)
} else {
matches = rgxNotInClause.FindStringSubmatch(where.clause)
}
// If we can't find any matches attempt a simple replace with 1 group.
// Clauses that fit this criteria will not be able to contain ? in their
// column name side, however if this case is being hit then the regexp
// probably needs adjustment, or the user is passing in invalid clauses.
if matches == nil {
clause, count := convertInQuestionMarks(q.dialect.UseIndexPlaceholders, where.clause, startAt, 1, ln)
if !manualParens {
buf.WriteByte('(')
}
buf.WriteString(clause)
if !manualParens {
buf.WriteByte(')')
}
args = append(args, where.args...)
startAt += count
break
}
leftSide := strings.TrimSpace(matches[1])
rightSide := strings.TrimSpace(matches[2])
// If matches are found, we have to parse the left side (column side)
// of the clause to determine how many columns they are using.
// This number determines the groupAt for the convert function.
cols := strings.Split(leftSide, ",")
cols = strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, cols)
groupAt := len(cols)
var leftClause string
var leftCount int
if q.dialect.UseIndexPlaceholders {
leftClause, leftCount = convertQuestionMarks(strings.Join(cols, ","), startAt)
} else {
// Count the number of cols that are question marks, so we know
// how much to offset convertInQuestionMarks by
for _, v := range cols {
if v == "?" {
leftCount++
}
}
leftClause = strings.Join(cols, ",")
}
rightClause, rightCount := convertInQuestionMarks(q.dialect.UseIndexPlaceholders, rightSide, startAt+leftCount, groupAt, ln-leftCount)
if !manualParens {
buf.WriteByte('(')
}
buf.WriteString(leftClause)
if where.kind == whereKindIn {
buf.WriteString(" IN ")
} else if where.kind == whereKindNotIn {
buf.WriteString(" NOT IN ")
}
buf.WriteString(rightClause)
if !manualParens {
buf.WriteByte(')')
}
startAt += leftCount + rightCount
args = append(args, where.args...)
default:
panic("unknown where type")
}
}
return buf.String(), args
}
// convertInQuestionMarks finds the first unescaped occurrence of ? and swaps it
// with a list of numbered placeholders, starting at startAt.
// It uses groupAt to determine how many placeholders should be in each group,
// for example, groupAt 2 would result in: (($1,$2),($3,$4))
// and groupAt 1 would result in ($1,$2,$3,$4)
func convertInQuestionMarks(UseIndexPlaceholders bool, clause string, startAt, groupAt, total int) (string, int) {
if startAt == 0 || len(clause) == 0 {
panic("Not a valid start number.")
}
paramBuf := strmangle.GetBuffer()
defer strmangle.PutBuffer(paramBuf)
foundAt := -1
for i := 0; i < len(clause); i++ {
if (i == 0 && clause[i] == '?') || (clause[i] == '?' && clause[i-1] != '\\') {
foundAt = i
break
}
}
if foundAt == -1 {
return strings.ReplaceAll(clause, `\?`, "?"), 0
}
paramBuf.WriteString(clause[:foundAt])
paramBuf.WriteByte('(')
paramBuf.WriteString(strmangle.Placeholders(UseIndexPlaceholders, total, startAt, groupAt))
paramBuf.WriteByte(')')
paramBuf.WriteString(clause[foundAt+1:])
// Remove all backslashes from escaped question-marks
ret := strings.ReplaceAll(paramBuf.String(), `\?`, "?")
return ret, total
}
// convertQuestionMarks converts each occurrence of ? with $<number>
// where <number> is an incrementing digit starting at startAt.
// If question-mark (?) is escaped using back-slash (\), it will be ignored.
func convertQuestionMarks(clause string, startAt int) (string, int) {
if startAt == 0 {
panic("Not a valid start number.")
}
paramBuf := strmangle.GetBuffer()
defer strmangle.PutBuffer(paramBuf)
paramIndex := 0
total := 0
for {
if paramIndex >= len(clause) {
break
}
clause = clause[paramIndex:]
paramIndex = strings.IndexByte(clause, '?')
if paramIndex == -1 {
paramBuf.WriteString(clause)
break
}
escapeIndex := strings.Index(clause, `\?`)
if escapeIndex != -1 && paramIndex > escapeIndex {
paramBuf.WriteString(clause[:escapeIndex] + "?")
paramIndex++
continue
}
paramBuf.WriteString(clause[:paramIndex] + fmt.Sprintf("$%d", startAt))
total++
startAt++
paramIndex++
}
return paramBuf.String(), total
}
// parseFromClause will parse something that looks like
// a
// a b
// a as b
func parseFromClause(toks []string) (alias, name string, ok bool) {
if len(toks) > 3 {
toks = toks[:3]
}
sawIdent, sawAs := false, false
for _, tok := range toks {
if t := strings.ToLower(tok); sawIdent && t == "as" {
sawAs = true
continue
} else if sawIdent && t == "on" {
break
}
if !rgxIdentifier.MatchString(tok) {
break
}
if sawIdent || sawAs {
alias = strings.Trim(tok, `"`)
break
}
name = strings.Trim(tok, `"`)
sawIdent = true
ok = true
}
return alias, name, ok
}
var commnetSplit = regexp.MustCompile(`[\n\r]+`)
func writeComment(q *Query, buf *bytes.Buffer) {
if len(q.comment) == 0 {
return
}
lines := commnetSplit.Split(q.comment, -1)
for _, line := range lines {
buf.WriteString("-- ")
buf.WriteString(line)
buf.WriteByte('\n')
}
}
func writeCTEs(q *Query, buf *bytes.Buffer, args *[]interface{}) {
if len(q.withs) == 0 {
return
}
buf.WriteString("WITH")
argsLen := len(*args)
withBuf := strmangle.GetBuffer()
lastPos := len(q.withs) - 1
for i, w := range q.withs {
fmt.Fprintf(withBuf, " %s", w.clause)
if i >= 0 && i < lastPos {
withBuf.WriteByte(',')
}
*args = append(*args, w.args...)
}
withBuf.WriteByte(' ')
var resp string
if q.dialect.UseIndexPlaceholders {
resp, _ = convertQuestionMarks(withBuf.String(), argsLen+1)
} else {
resp = withBuf.String()
}
fmt.Fprintf(buf, resp)
strmangle.PutBuffer(withBuf)
}