-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathselect.go
More file actions
411 lines (352 loc) · 10.4 KB
/
Copy pathselect.go
File metadata and controls
411 lines (352 loc) · 10.4 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
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
package pgq
import (
"bytes"
"fmt"
"strings"
)
// SelectBuilder builds SQL SELECT statements.
type SelectBuilder struct {
ctes []cte
prefixes []SQLizer
options []string
columns []SQLizer
from SQLizer
joins []SQLizer
whereParts []SQLizer
groupBys []string
havingParts []SQLizer
orderByParts []SQLizer
limit string
offset string
suffixes []SQLizer
}
// SQL builds the query into a SQL string and bound args.
func (b SelectBuilder) SQL() (sqlStr string, args []any, err error) {
sqlStr, args, err = b.unfinalizedSQL()
if err != nil {
return
}
sqlStr, err = dollarPlaceholder(sqlStr)
return
}
func (b SelectBuilder) unfinalizedSQL() (sqlStr string, args []any, err error) {
if len(b.columns) == 0 {
err = fmt.Errorf("select statements must have at least one result column")
return
}
sql := &bytes.Buffer{}
if len(b.ctes) > 0 {
args, err = appendCTEs(b.ctes, sql, args)
if err != nil {
return
}
}
if len(b.prefixes) > 0 {
args, err = appendSQL(b.prefixes, sql, " ", args)
if err != nil {
return
}
sql.WriteString(" ")
}
sql.WriteString("SELECT ")
if len(b.options) > 0 {
sql.WriteString(strings.Join(b.options, " "))
sql.WriteString(" ")
}
if len(b.columns) > 0 {
args, err = appendSQL(b.columns, sql, ", ", args)
if err != nil {
return
}
}
if b.from != nil {
sql.WriteString(" FROM ")
args, err = appendSQL([]SQLizer{b.from}, sql, "", args)
if err != nil {
return
}
}
if len(b.joins) > 0 {
sql.WriteString(" ")
args, err = appendSQL(b.joins, sql, " ", args)
if err != nil {
return
}
}
if len(b.whereParts) > 0 {
sql.WriteString(" WHERE ")
args, err = appendSQL(b.whereParts, sql, " AND ", args)
if err != nil {
return
}
}
if len(b.groupBys) > 0 {
sql.WriteString(" GROUP BY ")
sql.WriteString(strings.Join(b.groupBys, ", "))
}
if len(b.havingParts) > 0 {
sql.WriteString(" HAVING ")
args, err = appendSQL(b.havingParts, sql, " AND ", args)
if err != nil {
return
}
}
if len(b.orderByParts) > 0 {
sql.WriteString(" ORDER BY ")
args, err = appendSQL(b.orderByParts, sql, ", ", args)
if err != nil {
return
}
}
if b.limit != "" {
sql.WriteString(" LIMIT ")
sql.WriteString(b.limit)
}
if b.offset != "" {
sql.WriteString(" OFFSET ")
sql.WriteString(b.offset)
}
if len(b.suffixes) > 0 {
sql.WriteString(" ")
args, err = appendSQL(b.suffixes, sql, " ", args)
if err != nil {
return
}
}
sqlStr = sql.String()
return
}
// MustSQL builds the query into a SQL string and bound args.
// It panics if there are any errors.
func (b SelectBuilder) MustSQL() (string, []any) {
sql, args, err := b.SQL()
if err != nil {
panic(err)
}
return sql, args
}
// Prefix adds an expression to the beginning of the query
func (b SelectBuilder) Prefix(sql string, args ...any) SelectBuilder {
return b.PrefixExpr(Expr(sql, args...))
}
// PrefixExpr adds an expression to the very beginning of the query
func (b SelectBuilder) PrefixExpr(expr SQLizer) SelectBuilder {
b.prefixes = append(b.prefixes, expr)
return b
}
// With adds a Common Table Expression (CTE) to the query.
//
// Multiple CTEs are supported by chaining With calls; they are rendered as a
// single WITH clause: WITH name1 AS (...), name2 AS (...).
// CTEs are rendered before any Prefix expressions.
func (b SelectBuilder) With(name string, expr SQLizer) SelectBuilder {
b.ctes = append(b.ctes, cte{name: name, expr: expr})
return b
}
// WithRecursive adds a recursive Common Table Expression (CTE) to the query.
//
// The WITH clause will be emitted as WITH RECURSIVE whenever at least one CTE
// is added via WithRecursive. Non-recursive CTEs added via With may appear in
// the same clause.
func (b SelectBuilder) WithRecursive(name string, expr UnionBuilder) SelectBuilder {
b.ctes = append(b.ctes, cte{name: name, expr: expr, recursive: true})
return b
}
// Distinct adds a DISTINCT clause to the query.
func (b SelectBuilder) Distinct() SelectBuilder {
return b.Options("DISTINCT")
}
// Options adds select option to the query
func (b SelectBuilder) Options(options ...string) SelectBuilder {
b.options = append(b.options, options...)
return b
}
// Columns adds result columns to the query.
func (b SelectBuilder) Columns(columns ...string) SelectBuilder {
parts := make([]SQLizer, 0, len(columns))
for _, str := range columns {
parts = append(parts, newPart(str))
}
b.columns = append(b.columns, parts...)
return b
}
// RemoveColumns remove all columns from query.
// Must add a new column with Column or Columns methods, otherwise
// return a error.
func (b SelectBuilder) RemoveColumns() SelectBuilder {
b.columns = nil
return b
}
// Column adds a result column to the query.
// Unlike Columns, Column accepts args which will be bound to placeholders in
// the columns string, for example:
//
// Column("CASE WHEN col IN ("+pgq.Placeholders(3)+") THEN 1 ELSE 0 END as col", 1, 2, 3)
func (b SelectBuilder) Column(column any, args ...any) SelectBuilder {
b.columns = append(b.columns, newPart(column, args...))
return b
}
// From sets the FROM clause of the query.
func (b SelectBuilder) From(from string) SelectBuilder {
b.from = newPart(from)
return b
}
// FromSelect sets a subquery into the FROM clause of the query.
func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder {
b.from = Alias{
Expr: from,
As: alias,
}
return b
}
// JoinClause adds a join clause to the query.
func (b SelectBuilder) JoinClause(pred any, args ...any) SelectBuilder {
b.joins = append(b.joins, newPart(pred, args...))
return b
}
// Join adds a JOIN clause to the query.
func (b SelectBuilder) Join(join string, rest ...any) SelectBuilder {
return b.JoinClause("JOIN "+join, rest...)
}
// LeftJoin adds a LEFT JOIN clause to the query.
func (b SelectBuilder) LeftJoin(join string, rest ...any) SelectBuilder {
return b.JoinClause("LEFT JOIN "+join, rest...)
}
// RightJoin adds a RIGHT JOIN clause to the query.
func (b SelectBuilder) RightJoin(join string, rest ...any) SelectBuilder {
return b.JoinClause("RIGHT JOIN "+join, rest...)
}
// InnerJoin adds a INNER JOIN clause to the query.
func (b SelectBuilder) InnerJoin(join string, rest ...any) SelectBuilder {
return b.JoinClause("INNER JOIN "+join, rest...)
}
// CrossJoin adds a CROSS JOIN clause to the query.
func (b SelectBuilder) CrossJoin(join string, rest ...any) SelectBuilder {
return b.JoinClause("CROSS JOIN "+join, rest...)
}
// Where adds an expression to the WHERE clause of the query.
//
// Expressions are ANDed together in the generated SQL.
//
// Where accepts several types for its pred argument:
//
// nil OR "" - ignored.
//
// string - SQL expression.
// If the expression has SQL placeholders then a set of arguments must be passed
// as well, one for each placeholder.
//
// map[string]any OR Eq - map of SQL expressions to values. Each key is
// transformed into an expression like "<key> = ?", with the corresponding value
// bound to the placeholder. If the value is nil, the expression will be "<key>
// IS NULL". If the value is an array or slice, the expression will be "<key> = ANY
// (?)". These expressions
// are ANDed together.
//
// Where will panic if pred isn't any of the above types.
func (b SelectBuilder) Where(pred any, args ...any) SelectBuilder {
if pred == nil || pred == "" {
return b
}
b.whereParts = append(b.whereParts, newWherePart(pred, args...))
return b
}
// GroupBy adds GROUP BY expressions to the query.
func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder {
b.groupBys = append(b.groupBys, groupBys...)
return b
}
// Having adds an expression to the HAVING clause of the query.
//
// See Where.
func (b SelectBuilder) Having(pred any, rest ...any) SelectBuilder {
b.havingParts = append(b.havingParts, newWherePart(pred, rest...))
return b
}
// OrderByClause adds ORDER BY clause to the query.
func (b SelectBuilder) OrderByClause(pred any, args ...any) SelectBuilder {
b.orderByParts = append(b.orderByParts, newPart(pred, args...))
return b
}
// OrderBy adds ORDER BY expressions to the query.
func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder {
for _, orderBy := range orderBys {
b = b.OrderByClause(orderBy)
}
return b
}
// RemoveOrderBy removes ORDER BY clause.
func (b SelectBuilder) RemoveOrderBy() SelectBuilder {
b.orderByParts = nil
return b
}
// Limit sets a LIMIT clause on the query.
func (b SelectBuilder) Limit(limit uint64) SelectBuilder {
b.limit = fmt.Sprintf("%d", limit)
return b
}
// Limit ALL allows to access all records with limit
func (b SelectBuilder) RemoveLimit() SelectBuilder {
b.limit = ""
return b
}
// Offset sets a OFFSET clause on the query.
func (b SelectBuilder) Offset(offset uint64) SelectBuilder {
b.offset = fmt.Sprintf("%d", offset)
return b
}
// RemoveOffset removes OFFSET clause.
func (b SelectBuilder) RemoveOffset() SelectBuilder {
b.offset = ""
return b
}
// Suffix adds an expression to the end of the query
func (b SelectBuilder) Suffix(sql string, args ...any) SelectBuilder {
return b.SuffixExpr(Expr(sql, args...))
}
// SuffixExpr adds an expression to the end of the query
func (b SelectBuilder) SuffixExpr(expr SQLizer) SelectBuilder {
b.suffixes = append(b.suffixes, expr)
return b
}
// UnionBuilder composes two SELECT statements with UNION or UNION ALL.
// It implements both SQLizer and rawSQLizer so it can be used standalone or
// as a CTE body without premature placeholder numbering.
type UnionBuilder struct {
left SelectBuilder
right SelectBuilder
all bool
}
func (u UnionBuilder) unfinalizedSQL() (sqlStr string, args []any, err error) {
leftSQL, leftArgs, err := u.left.unfinalizedSQL()
if err != nil {
return
}
rightSQL, rightArgs, err := u.right.unfinalizedSQL()
if err != nil {
return
}
if u.all {
sqlStr = leftSQL + " UNION ALL " + rightSQL
} else {
sqlStr = leftSQL + " UNION " + rightSQL
}
args = append(leftArgs, rightArgs...)
return
}
func (u UnionBuilder) SQL() (sqlStr string, args []any, err error) {
sqlStr, args, err = u.unfinalizedSQL()
if err != nil {
return
}
sqlStr, err = dollarPlaceholder(sqlStr)
return
}
// Union returns a SQLizer that renders "left UNION right".
func Union(left, right SelectBuilder) UnionBuilder {
return UnionBuilder{left: left, right: right, all: false}
}
// UnionAll returns a SQLizer that renders "left UNION ALL right".
func UnionAll(left, right SelectBuilder) UnionBuilder {
return UnionBuilder{left: left, right: right, all: true}
}