-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.go
582 lines (511 loc) · 13.9 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
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
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
// This code was derived from https://github.com/youtube/vitess.
//
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file
package parser
import (
"bytes"
"fmt"
)
// SelectStatement represents any SELECT statement.
type SelectStatement interface {
Statement
selectStatement()
}
func (*ParenSelect) selectStatement() {}
func (*SelectClause) selectStatement() {}
func (*UnionClause) selectStatement() {}
func (*ValuesClause) selectStatement() {}
// Select represents a SelectStatement with an ORDER and/or LIMIT.
type Select struct {
Select SelectStatement
OrderBy OrderBy
Limit *Limit
}
// Format implements the NodeFormatter interface.
func (node *Select) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Select)
FormatNode(buf, f, node.OrderBy)
FormatNode(buf, f, node.Limit)
}
// ParenSelect represents a parenthesized SELECT/UNION/VALUES statement.
type ParenSelect struct {
Select *Select
}
// Format implements the NodeFormatter interface.
func (node *ParenSelect) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteByte('(')
FormatNode(buf, f, node.Select)
buf.WriteByte(')')
}
// SelectClause represents a SELECT statement.
type SelectClause struct {
Distinct bool
Exprs SelectExprs
From *From
Where *Where
GroupBy GroupBy
Having *Where
Window Window
tableSelect bool
}
// Format implements the NodeFormatter interface.
func (node *SelectClause) Format(buf *bytes.Buffer, f FmtFlags) {
if node.tableSelect {
buf.WriteString("TABLE ")
FormatNode(buf, f, node.From.Tables[0])
} else {
buf.WriteString("SELECT ")
if node.Distinct {
buf.WriteString("DISTINCT ")
}
FormatNode(buf, f, node.Exprs)
FormatNode(buf, f, node.From)
FormatNode(buf, f, node.Where)
FormatNode(buf, f, node.GroupBy)
FormatNode(buf, f, node.Having)
FormatNode(buf, f, node.Window)
}
}
// SelectExprs represents SELECT expressions.
type SelectExprs []SelectExpr
// Format implements the NodeFormatter interface.
func (node SelectExprs) Format(buf *bytes.Buffer, f FmtFlags) {
for i, n := range node {
if i > 0 {
buf.WriteString(", ")
}
FormatNode(buf, f, n)
}
}
// SelectExpr represents a SELECT expression.
type SelectExpr struct {
Expr Expr
As Name
}
// NormalizeTopLevelVarName preemptively expands any UnresolvedName at
// the top level of the expression into a VarName. This is meant
// to catch stars so that sql.checkRenderStar() can see it prior to
// other expression transformations.
func (node *SelectExpr) NormalizeTopLevelVarName() error {
if vBase, ok := node.Expr.(VarName); ok {
v, err := vBase.NormalizeVarName()
if err != nil {
return err
}
node.Expr = v
}
return nil
}
// starSelectExpr is a convenience function that represents an unqualified "*"
// in a select expression.
func starSelectExpr() SelectExpr {
return SelectExpr{Expr: StarExpr()}
}
// Format implements the NodeFormatter interface.
func (node SelectExpr) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Expr)
if node.As != "" {
buf.WriteString(" AS ")
FormatNode(buf, f, node.As)
}
}
// AliasClause represents an alias, optionally with a column list:
// "AS name" or "AS name(col1, col2)".
type AliasClause struct {
Alias Name
Cols NameList
}
// Format implements the NodeFormatter interface.
func (a AliasClause) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, a.Alias)
if len(a.Cols) != 0 {
// Format as "alias (col1, col2, ...)".
buf.WriteString(" (")
FormatNode(buf, f, a.Cols)
buf.WriteByte(')')
}
}
// AsOfClause represents an as of time.
type AsOfClause struct {
Expr Expr
}
// Format implements the NodeFormatter interface.
func (a AsOfClause) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("AS OF SYSTEM TIME ")
FormatNode(buf, f, a.Expr)
}
// From represents a FROM clause.
type From struct {
Tables TableExprs
AsOf AsOfClause
}
// Format implements the NodeFormatter interface.
func (node *From) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Tables)
if node.AsOf.Expr != nil {
buf.WriteByte(' ')
FormatNode(buf, f, node.AsOf)
}
}
// TableExprs represents a list of table expressions.
type TableExprs []TableExpr
// Format implements the NodeFormatter interface.
func (node TableExprs) Format(buf *bytes.Buffer, f FmtFlags) {
if len(node) != 0 {
buf.WriteString(" FROM ")
for i, n := range node {
if i > 0 {
buf.WriteString(", ")
}
FormatNode(buf, f, n)
}
}
}
// TableExpr represents a table expression.
type TableExpr interface {
NodeFormatter
tableExpr()
}
func (*AliasedTableExpr) tableExpr() {}
func (*ParenTableExpr) tableExpr() {}
func (*JoinTableExpr) tableExpr() {}
func (*FuncExpr) tableExpr() {}
// StatementSource encapsulates one of the other statements as a data source.
type StatementSource struct {
Statement Statement
}
// Format implements the NodeFormatter interface.
func (node *StatementSource) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteByte('[')
node.Statement.Format(buf, f)
buf.WriteByte(']')
}
func (*StatementSource) tableExpr() {}
// IndexID is a custom type for IndexDescriptor IDs.
type IndexID uint32
// IndexHints represents "@<index_name>" or "@{param[,param]}" where param is
// one of:
// - FORCE_INDEX=<index_name>
// - NO_INDEX_JOIN
// It is used optionally after a table name in SELECT statements.
type IndexHints struct {
Index Name
IndexID IndexID
NoIndexJoin bool
}
// Format implements the NodeFormatter interface.
func (n *IndexHints) Format(buf *bytes.Buffer, f FmtFlags) {
if !n.NoIndexJoin {
buf.WriteByte('@')
if n.Index != "" {
FormatNode(buf, f, n.Index)
} else {
fmt.Fprintf(buf, "[%d]", n.IndexID)
}
} else {
if n.Index == "" && n.IndexID == 0 {
buf.WriteString("@{NO_INDEX_JOIN}")
} else {
buf.WriteString("@{FORCE_INDEX=")
if n.Index != "" {
FormatNode(buf, f, n.Index)
} else {
fmt.Fprintf(buf, "[%d]", n.IndexID)
}
buf.WriteString(",NO_INDEX_JOIN}")
}
}
}
// AliasedTableExpr represents a table expression coupled with an optional
// alias.
type AliasedTableExpr struct {
Expr TableExpr
Hints *IndexHints
Ordinality bool
As AliasClause
}
// Format implements the NodeFormatter interface.
func (node *AliasedTableExpr) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Expr)
if node.Hints != nil {
FormatNode(buf, f, node.Hints)
}
if node.Ordinality {
buf.WriteString(" WITH ORDINALITY")
}
if node.As.Alias != "" {
buf.WriteString(" AS ")
FormatNode(buf, f, node.As)
}
}
func (*Subquery) tableExpr() {}
// ParenTableExpr represents a parenthesized TableExpr.
type ParenTableExpr struct {
Expr TableExpr
}
// Format implements the NodeFormatter interface.
func (node *ParenTableExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteByte('(')
FormatNode(buf, f, node.Expr)
buf.WriteByte(')')
}
// JoinTableExpr represents a TableExpr that's a JOIN operation.
type JoinTableExpr struct {
Join string
Left TableExpr
Right TableExpr
Cond JoinCond
}
// JoinTableExpr.Join
const (
astJoin = "JOIN"
astFullJoin = "FULL JOIN"
astLeftJoin = "LEFT JOIN"
astRightJoin = "RIGHT JOIN"
astCrossJoin = "CROSS JOIN"
astInnerJoin = "INNER JOIN"
)
// Format implements the NodeFormatter interface.
func (node *JoinTableExpr) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Left)
buf.WriteByte(' ')
if _, isNatural := node.Cond.(NaturalJoinCond); isNatural {
// Natural joins have a different syntax: "<a> NATURAL <join_type> <b>"
FormatNode(buf, f, node.Cond)
buf.WriteByte(' ')
buf.WriteString(node.Join)
buf.WriteByte(' ')
FormatNode(buf, f, node.Right)
} else {
// General syntax: "<a> <join_type> <b> <condition>"
buf.WriteString(node.Join)
buf.WriteByte(' ')
FormatNode(buf, f, node.Right)
if node.Cond != nil {
FormatNode(buf, f, node.Cond)
}
}
}
// JoinCond represents a join condition.
type JoinCond interface {
NodeFormatter
joinCond()
}
func (NaturalJoinCond) joinCond() {}
func (*OnJoinCond) joinCond() {}
func (*UsingJoinCond) joinCond() {}
// NaturalJoinCond represents a NATURAL join condition
type NaturalJoinCond struct{}
// Format implements the NodeFormatter interface.
func (NaturalJoinCond) Format(buf *bytes.Buffer, _ FmtFlags) {
buf.WriteString("NATURAL")
}
// OnJoinCond represents an ON join condition.
type OnJoinCond struct {
Expr Expr
}
// Format implements the NodeFormatter interface.
func (node *OnJoinCond) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString(" ON ")
FormatNode(buf, f, node.Expr)
}
// UsingJoinCond represents a USING join condition.
type UsingJoinCond struct {
Cols NameList
}
// Format implements the NodeFormatter interface.
func (node *UsingJoinCond) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString(" USING (")
FormatNode(buf, f, node.Cols)
buf.WriteByte(')')
}
// Where represents a WHERE or HAVING clause.
type Where struct {
Type string
Expr Expr
}
// Where.Type
const (
astWhere = "WHERE"
astHaving = "HAVING"
)
// newWhere creates a WHERE or HAVING clause out of an Expr. If the expression
// is nil, it returns nil.
func newWhere(typ string, expr Expr) *Where {
if expr == nil {
return nil
}
return &Where{Type: typ, Expr: expr}
}
// Format implements the NodeFormatter interface.
func (node *Where) Format(buf *bytes.Buffer, f FmtFlags) {
if node != nil {
buf.WriteByte(' ')
buf.WriteString(node.Type)
buf.WriteByte(' ')
FormatNode(buf, f, node.Expr)
}
}
// GroupBy represents a GROUP BY clause.
type GroupBy []Expr
// Format implements the NodeFormatter interface.
func (node GroupBy) Format(buf *bytes.Buffer, f FmtFlags) {
prefix := " GROUP BY "
for _, n := range node {
buf.WriteString(prefix)
FormatNode(buf, f, n)
prefix = ", "
}
}
// OrderBy represents an ORDER By clause.
type OrderBy []*Order
// Format implements the NodeFormatter interface.
func (node OrderBy) Format(buf *bytes.Buffer, f FmtFlags) {
prefix := " ORDER BY "
for _, n := range node {
buf.WriteString(prefix)
FormatNode(buf, f, n)
prefix = ", "
}
}
// Direction for ordering results.
type Direction int
// Direction values.
const (
DefaultDirection Direction = iota
Ascending
Descending
)
var directionName = [...]string{
DefaultDirection: "",
Ascending: "ASC",
Descending: "DESC",
}
func (d Direction) String() string {
if d < 0 || d > Direction(len(directionName)-1) {
return fmt.Sprintf("Direction(%d)", d)
}
return directionName[d]
}
// OrderType indicates which type of expression is used in ORDER BY.
type OrderType int
const (
// OrderByColumn is the regular "by expression/column" ORDER BY specification.
OrderByColumn OrderType = iota
// OrderByIndex enables the user to specify a given index' columns implicitly.
OrderByIndex
)
// Order represents an ordering expression.
type Order struct {
OrderType OrderType
Expr Expr
Direction Direction
// Table/Index replaces Expr when OrderType = OrderByIndex.
Table NormalizableTableName
// If Index is empty, then the order should use the primary key.
Index Name
}
// Format implements the NodeFormatter interface.
func (node *Order) Format(buf *bytes.Buffer, f FmtFlags) {
if node.OrderType == OrderByColumn {
FormatNode(buf, f, node.Expr)
} else {
if node.Index == "" {
buf.WriteString("PRIMARY KEY ")
FormatNode(buf, f, &node.Table)
} else {
buf.WriteString("INDEX ")
FormatNode(buf, f, &node.Table)
buf.WriteByte('@')
FormatNode(buf, f, node.Index)
}
}
if node.Direction != DefaultDirection {
buf.WriteByte(' ')
buf.WriteString(node.Direction.String())
}
}
// Limit represents a LIMIT clause.
type Limit struct {
Offset, Count Expr
}
// Format implements the NodeFormatter interface.
func (node *Limit) Format(buf *bytes.Buffer, f FmtFlags) {
if node != nil {
if node.Count != nil {
buf.WriteString(" LIMIT ")
FormatNode(buf, f, node.Count)
}
if node.Offset != nil {
buf.WriteString(" OFFSET ")
FormatNode(buf, f, node.Offset)
}
}
}
// Window represents a WINDOW clause.
type Window []*WindowDef
// Format implements the NodeFormatter interface.
func (node Window) Format(buf *bytes.Buffer, f FmtFlags) {
prefix := " WINDOW "
for _, n := range node {
buf.WriteString(prefix)
FormatNode(buf, f, n.Name)
buf.WriteString(" AS ")
FormatNode(buf, f, n)
prefix = ", "
}
}
// WindowDef represents a single window definition expression.
type WindowDef struct {
Name Name
RefName Name
Partitions Exprs
OrderBy OrderBy
}
// Format implements the NodeFormatter interface.
func (node *WindowDef) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteRune('(')
needSpaceSeparator := false
if node.RefName != "" {
FormatNode(buf, f, node.RefName)
needSpaceSeparator = true
}
if node.Partitions != nil {
if needSpaceSeparator {
buf.WriteRune(' ')
}
buf.WriteString("PARTITION BY ")
FormatNode(buf, f, node.Partitions)
needSpaceSeparator = true
}
if node.OrderBy != nil {
if needSpaceSeparator {
FormatNode(buf, f, node.OrderBy)
} else {
// We need to remove the initial space produced by OrderBy.Format.
var tmpBuf bytes.Buffer
FormatNode(&tmpBuf, f, node.OrderBy)
buf.WriteString(tmpBuf.String()[1:])
}
needSpaceSeparator = true
_ = needSpaceSeparator // avoid compiler warning until TODO below is addressed.
}
// TODO(nvanbenschoten): Support Window Frames.
// if node.Frame != nil {}
buf.WriteRune(')')
}