-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.go
451 lines (378 loc) · 11 KB
/
select.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
// Copyright 2018 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package sqlbuilder
import (
"fmt"
"strconv"
"strings"
)
const (
selectMarkerInit injectionMarker = iota
selectMarkerAfterSelect
selectMarkerAfterFrom
selectMarkerAfterJoin
selectMarkerAfterWhere
selectMarkerAfterGroupBy
selectMarkerAfterOrderBy
selectMarkerAfterLimit
selectMarkerAfterFor
)
// JoinOption is the option in JOIN.
type JoinOption string
// Join options.
const (
FullJoin JoinOption = "FULL"
FullOuterJoin JoinOption = "FULL OUTER"
InnerJoin JoinOption = "INNER"
LeftJoin JoinOption = "LEFT"
LeftOuterJoin JoinOption = "LEFT OUTER"
RightJoin JoinOption = "RIGHT"
RightOuterJoin JoinOption = "RIGHT OUTER"
)
// NewSelectBuilder creates a new SELECT builder.
func NewSelectBuilder() *SelectBuilder {
return DefaultFlavor.NewSelectBuilder()
}
func newSelectBuilder() *SelectBuilder {
args := &Args{}
return &SelectBuilder{
Cond: Cond{
Args: args,
},
limit: -1,
offset: -1,
args: args,
injection: newInjection(),
}
}
// SelectBuilder is a builder to build SELECT.
type SelectBuilder struct {
Cond
distinct bool
tables []string
selectCols []string
joinOptions []JoinOption
joinTables []string
joinExprs [][]string
whereExprs []string
havingExprs []string
groupByCols []string
orderByCols []string
order string
limit int
offset int
forWhat string
args *Args
injection *injection
marker injectionMarker
}
var _ Builder = new(SelectBuilder)
// Select sets columns in SELECT.
func Select(col ...string) *SelectBuilder {
return DefaultFlavor.NewSelectBuilder().Select(col...)
}
// Select sets columns in SELECT.
func (sb *SelectBuilder) Select(col ...string) *SelectBuilder {
sb.selectCols = col
sb.marker = selectMarkerAfterSelect
return sb
}
// Distinct marks this SELECT as DISTINCT.
func (sb *SelectBuilder) Distinct() *SelectBuilder {
sb.distinct = true
sb.marker = selectMarkerAfterSelect
return sb
}
// From sets table names in SELECT.
func (sb *SelectBuilder) From(table ...string) *SelectBuilder {
sb.tables = table
sb.marker = selectMarkerAfterFrom
return sb
}
// Join sets expressions of JOIN in SELECT.
//
// It builds a JOIN expression like
//
// JOIN table ON onExpr[0] AND onExpr[1] ...
func (sb *SelectBuilder) Join(table string, onExpr ...string) *SelectBuilder {
sb.marker = selectMarkerAfterJoin
return sb.JoinWithOption("", table, onExpr...)
}
// JoinWithOption sets expressions of JOIN with an option.
//
// It builds a JOIN expression like
//
// option JOIN table ON onExpr[0] AND onExpr[1] ...
//
// Here is a list of supported options.
// - FullJoin: FULL JOIN
// - FullOuterJoin: FULL OUTER JOIN
// - InnerJoin: INNER JOIN
// - LeftJoin: LEFT JOIN
// - LeftOuterJoin: LEFT OUTER JOIN
// - RightJoin: RIGHT JOIN
// - RightOuterJoin: RIGHT OUTER JOIN
func (sb *SelectBuilder) JoinWithOption(option JoinOption, table string, onExpr ...string) *SelectBuilder {
sb.joinOptions = append(sb.joinOptions, option)
sb.joinTables = append(sb.joinTables, table)
sb.joinExprs = append(sb.joinExprs, onExpr)
sb.marker = selectMarkerAfterJoin
return sb
}
// Where sets expressions of WHERE in SELECT.
func (sb *SelectBuilder) Where(andExpr ...string) *SelectBuilder {
sb.whereExprs = append(sb.whereExprs, andExpr...)
sb.marker = selectMarkerAfterWhere
return sb
}
// Having sets expressions of HAVING in SELECT.
func (sb *SelectBuilder) Having(andExpr ...string) *SelectBuilder {
sb.havingExprs = append(sb.havingExprs, andExpr...)
sb.marker = selectMarkerAfterGroupBy
return sb
}
// GroupBy sets columns of GROUP BY in SELECT.
func (sb *SelectBuilder) GroupBy(col ...string) *SelectBuilder {
sb.groupByCols = append(sb.groupByCols, col...)
sb.marker = selectMarkerAfterGroupBy
return sb
}
// OrderBy sets columns of ORDER BY in SELECT.
func (sb *SelectBuilder) OrderBy(col ...string) *SelectBuilder {
sb.orderByCols = append(sb.orderByCols, col...)
sb.marker = selectMarkerAfterOrderBy
return sb
}
// Asc sets order of ORDER BY to ASC.
func (sb *SelectBuilder) Asc() *SelectBuilder {
sb.order = "ASC"
sb.marker = selectMarkerAfterOrderBy
return sb
}
// Desc sets order of ORDER BY to DESC.
func (sb *SelectBuilder) Desc() *SelectBuilder {
sb.order = "DESC"
sb.marker = selectMarkerAfterOrderBy
return sb
}
// Limit sets the LIMIT in SELECT.
func (sb *SelectBuilder) Limit(limit int) *SelectBuilder {
sb.limit = limit
sb.marker = selectMarkerAfterLimit
return sb
}
// Offset sets the LIMIT offset in SELECT.
func (sb *SelectBuilder) Offset(offset int) *SelectBuilder {
sb.offset = offset
sb.marker = selectMarkerAfterLimit
return sb
}
// ForUpdate adds FOR UPDATE at the end of SELECT statement.
func (sb *SelectBuilder) ForUpdate() *SelectBuilder {
sb.forWhat = "UPDATE"
sb.marker = selectMarkerAfterFor
return sb
}
// ForShare adds FOR SHARE at the end of SELECT statement.
func (sb *SelectBuilder) ForShare() *SelectBuilder {
sb.forWhat = "SHARE"
sb.marker = selectMarkerAfterFor
return sb
}
// As returns an AS expression.
func (sb *SelectBuilder) As(name, alias string) string {
return fmt.Sprintf("%s AS %s", name, alias)
}
// BuilderAs returns an AS expression wrapping a complex SQL.
// According to SQL syntax, SQL built by builder is surrounded by parens.
func (sb *SelectBuilder) BuilderAs(builder Builder, alias string) string {
return fmt.Sprintf("(%s) AS %s", sb.Var(builder), alias)
}
// String returns the compiled SELECT string.
func (sb *SelectBuilder) String() string {
s, _ := sb.Build()
return s
}
// Build returns compiled SELECT string and args.
// They can be used in `DB#Query` of package `database/sql` directly.
func (sb *SelectBuilder) Build() (sql string, args []interface{}) {
return sb.BuildWithFlavor(sb.args.Flavor)
}
// BuildWithFlavor returns compiled SELECT string and args with flavor and initial args.
// They can be used in `DB#Query` of package `database/sql` directly.
func (sb *SelectBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) {
buf := newStringBuilder()
sb.injection.WriteTo(buf, selectMarkerInit)
oraclePage := flavor == Oracle && (sb.limit >= 0 || sb.offset >= 0)
if len(sb.selectCols) > 0 {
buf.WriteLeadingString("SELECT ")
if sb.distinct {
buf.WriteString("DISTINCT ")
}
if oraclePage {
var selectCols []string
for i := range sb.selectCols {
cols := strings.SplitN(sb.selectCols[i], ".", 2)
if len(cols) == 1 {
selectCols = append(selectCols, cols[0])
} else {
selectCols = append(selectCols, cols[1])
}
}
buf.WriteString(strings.Join(selectCols, ", "))
} else {
buf.WriteString(strings.Join(sb.selectCols, ", "))
}
}
sb.injection.WriteTo(buf, selectMarkerAfterSelect)
if oraclePage {
if len(sb.selectCols) > 0 {
buf.WriteLeadingString("FROM ( SELECT ")
if sb.distinct {
buf.WriteString("DISTINCT ")
}
var selectCols = make([]string, 0, len(sb.selectCols)+1)
selectCols = append(selectCols, "ROWNUM r")
selectCols = append(selectCols, sb.selectCols...)
buf.WriteString(strings.Join(selectCols, ", "))
buf.WriteLeadingString("FROM ( SELECT ")
buf.WriteString(strings.Join(sb.selectCols, ", "))
}
}
if len(sb.tables) > 0 {
buf.WriteLeadingString("FROM ")
buf.WriteString(strings.Join(sb.tables, ", "))
}
sb.injection.WriteTo(buf, selectMarkerAfterFrom)
for i := range sb.joinTables {
if option := sb.joinOptions[i]; option != "" {
buf.WriteLeadingString(string(option))
}
buf.WriteLeadingString("JOIN ")
buf.WriteString(sb.joinTables[i])
if exprs := sb.joinExprs[i]; len(exprs) > 0 {
buf.WriteString(" ON ")
buf.WriteString(strings.Join(sb.joinExprs[i], " AND "))
}
}
if len(sb.joinTables) > 0 {
sb.injection.WriteTo(buf, selectMarkerAfterJoin)
}
if len(sb.whereExprs) > 0 {
buf.WriteLeadingString("WHERE ")
buf.WriteString(strings.Join(sb.whereExprs, " AND "))
sb.injection.WriteTo(buf, selectMarkerAfterWhere)
}
if len(sb.groupByCols) > 0 {
buf.WriteLeadingString("GROUP BY ")
buf.WriteString(strings.Join(sb.groupByCols, ", "))
if len(sb.havingExprs) > 0 {
buf.WriteString(" HAVING ")
buf.WriteString(strings.Join(sb.havingExprs, " AND "))
}
sb.injection.WriteTo(buf, selectMarkerAfterGroupBy)
}
if len(sb.orderByCols) > 0 {
buf.WriteLeadingString("ORDER BY ")
buf.WriteString(strings.Join(sb.orderByCols, ", "))
if sb.order != "" {
buf.WriteRune(' ')
buf.WriteString(sb.order)
}
sb.injection.WriteTo(buf, selectMarkerAfterOrderBy)
}
switch flavor {
case MySQL, SQLite, ClickHouse:
if sb.limit >= 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(strconv.Itoa(sb.limit))
if sb.offset >= 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(strconv.Itoa(sb.offset))
}
}
case CQL:
if sb.limit >= 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(strconv.Itoa(sb.limit))
}
case PostgreSQL:
if sb.limit >= 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(strconv.Itoa(sb.limit))
}
if sb.offset >= 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(strconv.Itoa(sb.offset))
}
case Presto:
if sb.offset >= 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(strconv.Itoa(sb.offset))
}
if sb.limit >= 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(strconv.Itoa(sb.limit))
}
case SQLServer:
// If ORDER BY is not set, sort column #1 by default.
// It's required to make OFFSET...FETCH work.
if len(sb.orderByCols) == 0 && (sb.limit >= 0 || sb.offset >= 0) {
buf.WriteLeadingString("ORDER BY 1")
}
if sb.offset >= 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(strconv.Itoa(sb.offset))
buf.WriteString(" ROWS")
}
if sb.limit >= 0 {
if sb.offset < 0 {
buf.WriteLeadingString("OFFSET 0 ROWS")
}
buf.WriteLeadingString("FETCH NEXT ")
buf.WriteString(strconv.Itoa(sb.limit))
buf.WriteString(" ROWS ONLY")
}
case Oracle:
if oraclePage {
buf.WriteString(" ) ")
if len(sb.tables) > 0 {
buf.WriteString(strings.Join(sb.tables, ", "))
}
min := sb.offset
if min < 0 {
min = 0
}
buf.WriteString(" ) WHERE ")
if sb.limit >= 0 {
buf.WriteString("r BETWEEN ")
buf.WriteString(strconv.Itoa(min + 1))
buf.WriteString(" AND ")
buf.WriteString(strconv.Itoa(sb.limit + min))
} else {
buf.WriteString("r >= ")
buf.WriteString(strconv.Itoa(min + 1))
}
}
}
if sb.limit >= 0 {
sb.injection.WriteTo(buf, selectMarkerAfterLimit)
}
if sb.forWhat != "" {
buf.WriteLeadingString("FOR ")
buf.WriteString(sb.forWhat)
sb.injection.WriteTo(buf, selectMarkerAfterFor)
}
return sb.args.CompileWithFlavor(buf.String(), flavor, initialArg...)
}
// SetFlavor sets the flavor of compiled sql.
func (sb *SelectBuilder) SetFlavor(flavor Flavor) (old Flavor) {
old = sb.args.Flavor
sb.args.Flavor = flavor
return
}
// SQL adds an arbitrary sql to current position.
func (sb *SelectBuilder) SQL(sql string) *SelectBuilder {
sb.injection.SQL(sb.marker, sql)
return sb
}