-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathselect.go
More file actions
342 lines (299 loc) · 10.2 KB
/
select.go
File metadata and controls
342 lines (299 loc) · 10.2 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
// Copyright 2026 GoSQLX 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.
// Package parser - select.go
// Core SELECT statement parsing.
// Related modules:
// - select_clauses.go - FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, FETCH, FOR
// - select_set_ops.go - UNION, INTERSECT, EXCEPT
// - select_subquery.go - derived tables, JOIN table references, table hints
package parser
import (
"fmt"
"strings"
goerrors "github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
"github.com/ajitpratap0/GoSQLX/pkg/sql/ast"
"github.com/ajitpratap0/GoSQLX/pkg/sql/keywords"
)
// parseSelectStatement parses a SELECT statement.
// It delegates each clause to a focused helper method.
func (p *Parser) parseSelectStatement() (ast.Statement, error) {
// We've already consumed the SELECT token in matchType.
// DISTINCT / ALL modifier
isDistinct, distinctOnColumns, err := p.parseDistinctModifier()
if err != nil {
return nil, err
}
// Reject TOP in dialects that use LIMIT/OFFSET or ROWNUM/FETCH FIRST instead.
// String comparison is used here because the lexer has no TokenTypeTOP constant;
// TOP is emitted as an identifier literal (see parseTopClause comment).
nonTopDialects := map[string]bool{
string(keywords.DialectMySQL): true,
string(keywords.DialectPostgreSQL): true,
string(keywords.DialectSQLite): true,
string(keywords.DialectOracle): true,
}
if nonTopDialects[p.dialect] && strings.ToUpper(p.currentToken.Token.Value) == "TOP" {
if p.dialect == string(keywords.DialectOracle) {
return nil, fmt.Errorf("TOP clause is not supported in Oracle; use ROWNUM or FETCH FIRST … ROWS ONLY instead")
}
return nil, fmt.Errorf("TOP clause is not supported in %s; use LIMIT/OFFSET instead", p.dialect)
}
// SQL Server TOP clause
topClause, err := p.parseTopClause()
if err != nil {
return nil, err
}
// Column list
columns, err := p.parseSelectColumnList()
if err != nil {
return nil, err
}
// FROM … JOIN clauses
tableName, tables, joins, err := p.parseFromClause()
if err != nil {
return nil, err
}
// Initialise the statement early so clause parsers can check dialect etc.
selectStmt := &ast.SelectStatement{
Distinct: isDistinct,
DistinctOnColumns: distinctOnColumns,
Top: topClause,
Columns: columns,
From: tables,
Joins: joins,
TableName: tableName,
}
// SAMPLE (ClickHouse-specific, specifies sampling rate/size; comes after FROM/FINAL)
if p.dialect == string(keywords.DialectClickHouse) && p.isTokenMatch("SAMPLE") {
if selectStmt.Sample, err = p.parseSampleClause(); err != nil {
return nil, err
}
}
// PREWHERE (ClickHouse-specific, applied before WHERE for early data filtering)
if p.dialect == string(keywords.DialectClickHouse) {
if selectStmt.PrewhereClause, err = p.parsePrewhereClause(); err != nil {
return nil, err
}
}
// WHERE
if selectStmt.Where, err = p.parseWhereClause(); err != nil {
return nil, err
}
// GROUP BY
if selectStmt.GroupBy, err = p.parseGroupByClause(); err != nil {
return nil, err
}
// HAVING
if selectStmt.Having, err = p.parseHavingClause(); err != nil {
return nil, err
}
// Snowflake / BigQuery QUALIFY: filters rows after window functions.
// Appears between HAVING and ORDER BY. Tokenizes as identifier or
// keyword depending on dialect tables; detect by value.
if (p.dialect == string(keywords.DialectSnowflake) ||
p.dialect == string(keywords.DialectBigQuery)) &&
strings.EqualFold(p.currentToken.Token.Value, "QUALIFY") {
p.advance() // Consume QUALIFY
qexpr, qerr := p.parseExpression()
if qerr != nil {
return nil, qerr
}
selectStmt.Qualify = qexpr
}
// Oracle/MariaDB: START WITH ... CONNECT BY hierarchical queries
if p.isMariaDB() || p.dialect == string(keywords.DialectOracle) {
if strings.EqualFold(p.currentToken.Token.Value, "START") {
p.advance() // Consume START
if !strings.EqualFold(p.currentToken.Token.Value, "WITH") {
return nil, fmt.Errorf("expected WITH after START, got %q", p.currentToken.Token.Value)
}
p.advance() // Consume WITH
startExpr, startErr := p.parseExpression()
if startErr != nil {
return nil, startErr
}
selectStmt.StartWith = startExpr
}
if strings.EqualFold(p.currentToken.Token.Value, "CONNECT") {
connectPos := p.currentLocation() // position of CONNECT keyword
p.advance() // Consume CONNECT
if !strings.EqualFold(p.currentToken.Token.Value, "BY") {
return nil, fmt.Errorf("expected BY after CONNECT, got %q", p.currentToken.Token.Value)
}
p.advance() // Consume BY
cb := &ast.ConnectByClause{}
cb.Pos = connectPos
if strings.EqualFold(p.currentToken.Token.Value, "NOCYCLE") {
cb.NoCycle = true
p.advance() // Consume NOCYCLE
}
cond, condErr := p.parseConnectByCondition()
if condErr != nil {
return nil, condErr
}
if cond == nil {
return nil, fmt.Errorf("expected condition after CONNECT BY")
}
cb.Condition = cond
selectStmt.ConnectBy = cb
}
}
// ORDER BY
if selectStmt.OrderBy, err = p.parseOrderByClause(); err != nil {
return nil, err
}
// LIMIT / OFFSET
if selectStmt.Limit, selectStmt.Offset, err = p.parseLimitOffsetClause(); err != nil {
return nil, err
}
// FETCH FIRST / NEXT
if p.isType(models.TokenTypeFetch) {
if selectStmt.Fetch, err = p.parseFetchClause(); err != nil {
return nil, err
}
}
// FOR UPDATE / SHARE / …
if p.isType(models.TokenTypeFor) {
if selectStmt.For, err = p.parseForClause(); err != nil {
return nil, err
}
}
return selectStmt, nil
}
// parseDistinctModifier parses the optional DISTINCT [ON (...)] or ALL keyword
// immediately after SELECT.
func (p *Parser) parseDistinctModifier() (isDistinct bool, distinctOnColumns []ast.Expression, err error) {
if p.isType(models.TokenTypeDistinct) {
isDistinct = true
p.advance() // Consume DISTINCT
// PostgreSQL DISTINCT ON (expr, ...)
if p.isType(models.TokenTypeOn) {
p.advance() // Consume ON
if !p.isType(models.TokenTypeLParen) {
return false, nil, p.expectedError("( after DISTINCT ON")
}
p.advance() // Consume (
for {
expr, e := p.parseExpression()
if e != nil {
return false, nil, e
}
distinctOnColumns = append(distinctOnColumns, expr)
if !p.isType(models.TokenTypeComma) {
break
}
p.advance()
}
if !p.isType(models.TokenTypeRParen) {
return false, nil, p.expectedError(") after DISTINCT ON expression list")
}
p.advance() // Consume )
}
} else if p.isType(models.TokenTypeAll) {
p.advance() // ALL is the default; just consume it
}
return isDistinct, distinctOnColumns, nil
}
// parseTopClause parses SQL Server's TOP n [PERCENT] [WITH TIES] clause.
// Returns nil when the current dialect is not SQL Server or TOP is absent.
//
// Note: "TOP" is detected via a string comparison rather than a dedicated token-type
// constant because the lexer does not define a TokenTypeTOP - it tokenises TOP as a
// plain identifier/keyword literal. A future lexer enhancement could introduce
// models.TokenTypeTop and replace the strings.ToUpper check below.
func (p *Parser) parseTopClause() (*ast.TopClause, error) {
if p.dialect != string(keywords.DialectSQLServer) || strings.ToUpper(p.currentToken.Token.Value) != "TOP" {
return nil, nil
}
p.advance() // Consume TOP
hasParen := p.isType(models.TokenTypeLParen)
if hasParen {
p.advance() // Consume (
}
countExpr, err := p.parsePrimaryExpression()
if err != nil {
return nil, fmt.Errorf("expected expression after TOP: %w", err)
}
if hasParen {
if !p.isType(models.TokenTypeRightParen) {
return nil, p.expectedError(") after TOP expression")
}
p.advance() // Consume )
}
topClause := &ast.TopClause{Count: countExpr}
// Optional PERCENT
if p.isType(models.TokenTypePercent) ||
(p.currentToken.Token.Type == models.TokenTypeKeyword && strings.ToUpper(p.currentToken.Token.Value) == "PERCENT") {
topClause.IsPercent = true
p.advance()
}
// Optional WITH TIES
if p.isType(models.TokenTypeWith) && p.peekToken().Token.Type == models.TokenTypeTies {
topClause.WithTies = true
p.advance() // Consume WITH
p.advance() // Consume TIES
}
return topClause, nil
}
// parseSelectColumnList parses the comma-separated column/expression list in SELECT.
func (p *Parser) parseSelectColumnList() ([]ast.Expression, error) {
// Guard: SELECT immediately followed by FROM is an error.
if p.isType(models.TokenTypeFrom) {
return nil, goerrors.ExpectedTokenError(
"column expression",
"FROM",
p.currentLocation(),
"SELECT requires at least one column expression before FROM",
)
}
columns := make([]ast.Expression, 0, 8)
for {
var expr ast.Expression
if p.isType(models.TokenTypeAsterisk) || p.isType(models.TokenTypeMul) {
// Both TokenTypeAsterisk and TokenTypeMul represent '*' in SQL.
// The tokenizer may produce either depending on context.
expr = &ast.Identifier{Name: "*"}
p.advance()
} else {
var err error
expr, err = p.parseExpression()
if err != nil {
return nil, err
}
// Optional alias: AS name or implicit name (non-identifier expressions only)
if p.isType(models.TokenTypeAs) {
p.advance() // Consume AS
if !p.isIdentifier() {
return nil, p.expectedError("alias name after AS")
}
alias := p.currentToken.Token.Value
p.advance()
expr = &ast.AliasedExpression{Expr: expr, Alias: alias}
} else if p.canBeAlias() {
if _, ok := expr.(*ast.Identifier); !ok {
alias := p.currentToken.Token.Value
p.advance()
expr = &ast.AliasedExpression{Expr: expr, Alias: alias}
}
}
}
columns = append(columns, expr)
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
return columns, nil
}