forked from huandu/go-sqlbuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion.go
More file actions
362 lines (293 loc) · 8.49 KB
/
union.go
File metadata and controls
362 lines (293 loc) · 8.49 KB
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
// Copyright 2018 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package sqlbuilder
import (
"fmt"
"reflect"
"github.com/huandu/go-clone"
)
const (
unionDistinct = " UNION " // Default union type is DISTINCT.
unionAll = " UNION ALL "
)
const (
unionMarkerInit injectionMarker = iota
unionMarkerAfterUnion
unionMarkerAfterOrderBy
unionMarkerAfterLimit
)
// NewUnionBuilder creates a new UNION builder.
func NewUnionBuilder() *UnionBuilder {
return DefaultFlavor.NewUnionBuilder()
}
func newUnionBuilder() *UnionBuilder {
return &UnionBuilder{
args: &Args{},
injection: newInjection(),
}
}
// Clone returns a deep copy of UnionBuilder.
// It's useful when you want to create a base builder and clone it to build similar queries.
func (ub *UnionBuilder) Clone() *UnionBuilder {
return clone.Clone(ub).(*UnionBuilder)
}
func init() {
t := reflect.TypeOf(UnionBuilder{})
clone.SetCustomFunc(t, func(allocator *clone.Allocator, old, new reflect.Value) {
cloned := allocator.CloneSlowly(old)
new.Set(cloned)
ub := cloned.Addr().Interface().(*UnionBuilder)
for i, b := range ub.builders {
ub.args.Replace(ub.builderVars[i], b)
}
})
}
// UnionBuilder is a builder to build UNION.
type UnionBuilder struct {
opt string
orderByCols []string
order string
limitVar string
offsetVar string
builders []Builder
builderVars []string
args *Args
injection *injection
marker injectionMarker
}
var _ Builder = new(UnionBuilder)
// Union unions all builders together using UNION operator.
func Union(builders ...Builder) *UnionBuilder {
return DefaultFlavor.NewUnionBuilder().Union(builders...)
}
// Union unions all builders together using UNION operator.
func (ub *UnionBuilder) Union(builders ...Builder) *UnionBuilder {
return ub.union(unionDistinct, builders...)
}
// UnionAll unions all builders together using UNION ALL operator.
func UnionAll(builders ...Builder) *UnionBuilder {
return DefaultFlavor.NewUnionBuilder().UnionAll(builders...)
}
// UnionAll unions all builders together using UNION ALL operator.
func (ub *UnionBuilder) UnionAll(builders ...Builder) *UnionBuilder {
return ub.union(unionAll, builders...)
}
func (ub *UnionBuilder) union(opt string, builders ...Builder) *UnionBuilder {
builderVars := make([]string, 0, len(builders))
for _, b := range builders {
builderVars = append(builderVars, ub.Var(b))
}
ub.opt = opt
ub.builders = append([]Builder(nil), builders...)
ub.builderVars = builderVars
ub.marker = unionMarkerAfterUnion
return ub
}
// OrderBy sets columns of ORDER BY in SELECT.
func (ub *UnionBuilder) OrderBy(col ...string) *UnionBuilder {
ub.orderByCols = col
ub.marker = unionMarkerAfterOrderBy
return ub
}
// Asc sets order of ORDER BY to ASC.
func (ub *UnionBuilder) Asc() *UnionBuilder {
ub.order = "ASC"
ub.marker = unionMarkerAfterOrderBy
return ub
}
// Desc sets order of ORDER BY to DESC.
func (ub *UnionBuilder) Desc() *UnionBuilder {
ub.order = "DESC"
ub.marker = unionMarkerAfterOrderBy
return ub
}
// Limit sets the LIMIT in SELECT.
func (ub *UnionBuilder) Limit(limit int) *UnionBuilder {
if limit < 0 {
ub.limitVar = ""
return ub
}
ub.limitVar = ub.Var(limit)
ub.marker = unionMarkerAfterLimit
return ub
}
// Offset sets the LIMIT offset in SELECT.
func (ub *UnionBuilder) Offset(offset int) *UnionBuilder {
if offset < 0 {
ub.offsetVar = ""
return ub
}
ub.offsetVar = ub.Var(offset)
ub.marker = unionMarkerAfterLimit
return ub
}
// String returns the compiled SELECT string.
func (ub *UnionBuilder) String() string {
s, _ := ub.Build()
return s
}
// Build returns compiled SELECT string and args.
// They can be used in `DB#Query` of package `database/sql` directly.
func (ub *UnionBuilder) Build() (sql string, args []interface{}) {
return ub.BuildWithFlavor(ub.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 (ub *UnionBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) {
buf := newStringBuilder()
ub.injection.WriteTo(buf, unionMarkerInit)
nestedSelect := (flavor == Oracle && (len(ub.limitVar) > 0 || len(ub.offsetVar) > 0)) ||
(flavor == Informix && len(ub.limitVar) > 0)
if len(ub.builderVars) > 0 {
needParen := flavor != SQLite
if nestedSelect {
buf.WriteLeadingString("SELECT * FROM (")
}
if needParen {
buf.WriteLeadingString("(")
buf.WriteString(ub.builderVars[0])
buf.WriteRune(')')
} else {
buf.WriteLeadingString(ub.builderVars[0])
}
for _, b := range ub.builderVars[1:] {
buf.WriteString(ub.opt)
if needParen {
buf.WriteRune('(')
}
buf.WriteString(b)
if needParen {
buf.WriteRune(')')
}
}
if nestedSelect {
buf.WriteLeadingString(")")
}
}
ub.injection.WriteTo(buf, unionMarkerAfterUnion)
if len(ub.orderByCols) > 0 {
buf.WriteLeadingString("ORDER BY ")
buf.WriteStrings(ub.orderByCols, ", ")
if ub.order != "" {
buf.WriteRune(' ')
buf.WriteString(ub.order)
}
ub.injection.WriteTo(buf, unionMarkerAfterOrderBy)
}
switch flavor {
case MySQL, SQLite, ClickHouse:
if len(ub.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(ub.limitVar)
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(ub.offsetVar)
}
}
case CQL:
if len(ub.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(ub.limitVar)
}
case PostgreSQL:
if len(ub.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(ub.limitVar)
}
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(ub.offsetVar)
}
case Presto:
// There might be a hidden constraint in Presto requiring offset to be set before limit.
// The select statement documentation (https://prestodb.io/docs/current/sql/select.html)
// puts offset before limit, and Trino, which is based on Presto, seems
// to require this specific order.
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(ub.offsetVar)
}
if len(ub.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(ub.limitVar)
}
case SQLServer:
// If ORDER BY is not set, sort column #1 by default.
// It's required to make OFFSET...FETCH work.
if len(ub.orderByCols) == 0 && (len(ub.limitVar) > 0 || len(ub.offsetVar) > 0) {
buf.WriteLeadingString("ORDER BY 1")
}
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(ub.offsetVar)
buf.WriteString(" ROWS")
}
if len(ub.limitVar) > 0 {
if len(ub.offsetVar) == 0 {
buf.WriteLeadingString("OFFSET 0 ROWS")
}
buf.WriteLeadingString("FETCH NEXT ")
buf.WriteString(ub.limitVar)
buf.WriteString(" ROWS ONLY")
}
case Oracle:
// It's required to make OFFSET...FETCH work.
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(ub.offsetVar)
buf.WriteString(" ROWS")
}
if len(ub.limitVar) > 0 {
if len(ub.offsetVar) == 0 {
buf.WriteLeadingString("OFFSET 0 ROWS")
}
buf.WriteLeadingString("FETCH NEXT ")
buf.WriteString(ub.limitVar)
buf.WriteString(" ROWS ONLY")
}
case Informix:
// [SKIP N] FIRST M
// M must be greater than 0
if len(ub.limitVar) > 0 {
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("SKIP ")
buf.WriteString(ub.offsetVar)
}
buf.WriteLeadingString("FIRST ")
buf.WriteString(ub.limitVar)
}
case Doris:
// #192: Doris doesn't support ? in OFFSET and LIMIT.
if len(ub.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(fmt.Sprint(ub.args.Value(ub.limitVar)))
if len(ub.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(fmt.Sprint(ub.args.Value(ub.offsetVar)))
}
}
}
if len(ub.limitVar) > 0 {
ub.injection.WriteTo(buf, unionMarkerAfterLimit)
}
return ub.args.CompileWithFlavor(buf.String(), flavor, initialArg...)
}
// SetFlavor sets the flavor of compiled sql.
func (ub *UnionBuilder) SetFlavor(flavor Flavor) (old Flavor) {
old = ub.args.Flavor
ub.args.Flavor = flavor
return
}
// Flavor returns flavor of builder
func (ub *UnionBuilder) Flavor() Flavor {
return ub.args.Flavor
}
// Var returns a placeholder for value.
func (ub *UnionBuilder) Var(arg interface{}) string {
return ub.args.Add(arg)
}
// SQL adds an arbitrary sql to current position.
func (ub *UnionBuilder) SQL(sql string) *UnionBuilder {
ub.injection.SQL(ub.marker, sql)
return ub
}