-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathselect_subquery.go
More file actions
401 lines (362 loc) · 11.8 KB
/
select_subquery.go
File metadata and controls
401 lines (362 loc) · 11.8 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
// 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_subquery.go
// Derived table and JOIN table reference parsing (subqueries in FROM/JOIN clauses,
// table hints for SQL Server).
package parser
import (
"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"
)
// parseFromTableReference parses a single table reference in a FROM clause,
// including derived tables (subqueries), LATERAL, and optional aliases.
func (p *Parser) parseFromTableReference() (ast.TableReference, error) {
var tableRef ast.TableReference
// Check for LATERAL keyword (PostgreSQL)
isLateral := false
if p.isType(models.TokenTypeLateral) {
isLateral = true
p.advance() // Consume LATERAL
}
// Check for derived table (subquery in parentheses)
if p.isType(models.TokenTypeLParen) {
p.advance() // Consume (
// Check if this is a subquery (starts with SELECT or WITH)
if !p.isType(models.TokenTypeSelect) && !p.isType(models.TokenTypeWith) {
return tableRef, p.expectedError("SELECT in derived table")
}
// Consume SELECT token before calling parseSelectStatement
p.advance() // Consume SELECT
// Parse the subquery
subquery, err := p.parseSelectStatement()
if err != nil {
return tableRef, err
}
selectStmt, ok := subquery.(*ast.SelectStatement)
if !ok {
return tableRef, p.expectedError("SELECT statement in derived table")
}
// Expect closing parenthesis
if !p.isType(models.TokenTypeRParen) {
return tableRef, p.expectedError(")")
}
p.advance() // Consume )
tableRef = ast.TableReference{
Subquery: selectStmt,
Lateral: isLateral,
}
} else if p.dialect == string(keywords.DialectSnowflake) &&
p.isType(models.TokenTypePlaceholder) && strings.HasPrefix(p.currentToken.Token.Value, "@") {
// Snowflake stage reference: @stage_name or @db.schema.stage/path.
// Tokenized as PLACEHOLDER; consume as a table name.
// Gated to Snowflake to avoid misinterpreting @variable in other dialects.
stageName := p.currentToken.Token.Value
p.advance()
// Optional /path suffix — consume tokens joined by / until a space boundary.
// Slash tokenizes as TokenTypeDiv.
for p.isType(models.TokenTypeDiv) {
stageName += "/"
p.advance()
if p.isIdentifier() || p.isType(models.TokenTypeKeyword) {
stageName += p.currentToken.Token.Value
p.advance()
}
}
tableRef = ast.TableReference{
Name: stageName,
Lateral: isLateral,
}
// Stage may be followed by (FILE_FORMAT => ...) args — use the same
// function-call path as FLATTEN/TABLE(...).
if p.isType(models.TokenTypeLParen) {
funcCall, ferr := p.parseFunctionCall(stageName)
if ferr != nil {
return tableRef, ferr
}
tableRef.TableFunc = funcCall
}
} else {
// Parse regular table name (supports schema.table qualification)
qualifiedName, err := p.parseQualifiedName()
if err != nil {
return tableRef, err
}
tableRef = ast.TableReference{
Name: qualifiedName,
Lateral: isLateral,
}
// Function-call table reference (Snowflake FLATTEN, TABLE(...),
// IDENTIFIER(...), PostgreSQL unnest(...), BigQuery UNNEST(...)).
// If the parsed name is followed by '(' at FROM position, reparse
// it as a function call. Gated to dialects that actually use this.
if p.isType(models.TokenTypeLParen) && p.supportsTableFunction() {
funcCall, ferr := p.parseFunctionCall(qualifiedName)
if ferr != nil {
return tableRef, ferr
}
tableRef.TableFunc = funcCall
}
// Snowflake / ANSI SAMPLE or TABLESAMPLE clause on a table reference:
// SAMPLE [BERNOULLI | SYSTEM | BLOCK | ROW] (N [ROWS])
// TABLESAMPLE [method] (N [ROWS])
// Consume permissively — the method and paren block are consumed
// but not yet modeled on the AST.
if strings.EqualFold(p.currentToken.Token.Value, "SAMPLE") ||
strings.EqualFold(p.currentToken.Token.Value, "TABLESAMPLE") {
p.advance() // SAMPLE / TABLESAMPLE
// Optional method name
upper := strings.ToUpper(p.currentToken.Token.Value)
if upper == "BERNOULLI" || upper == "SYSTEM" || upper == "BLOCK" || upper == "ROW" {
p.advance()
}
// (N [ROWS]) block
if p.isType(models.TokenTypeLParen) {
depth := 0
for {
t := p.currentToken.Token.Type
if t == models.TokenTypeEOF {
break
}
if t == models.TokenTypeLParen {
depth++
} else if t == models.TokenTypeRParen {
depth--
if depth == 0 {
p.advance()
break
}
}
p.advance()
}
}
}
// Snowflake time-travel / change-tracking clauses:
// AT (TIMESTAMP => ...)
// BEFORE (STATEMENT => ...)
// CHANGES (INFORMATION => DEFAULT) AT (...)
if p.isSnowflakeTimeTravelStart() {
tt, err := p.parseSnowflakeTimeTravel()
if err != nil {
return tableRef, err
}
tableRef.TimeTravel = tt
}
}
// Check for table alias (required for derived tables, optional for regular tables).
// Guard: in MariaDB, CONNECT followed by BY is a hierarchical query clause, not an alias.
// Similarly, START followed by WITH is a hierarchical query seed, not an alias.
// Don't consume PIVOT/UNPIVOT as a table alias — they are contextual
// keywords in SQL Server/Oracle and must reach the pivot-clause parser below.
if (p.isIdentifier() || p.isType(models.TokenTypeAs)) && !p.isMariaDBClauseStart() && !p.isPivotKeyword() && !p.isUnpivotKeyword() && !p.isQualifyKeyword() && !p.isMinusSetOp() && !p.isSnowflakeTimeTravelStart() && !p.isSampleKeyword() && !p.isMatchRecognizeKeyword() {
if p.isType(models.TokenTypeAs) {
p.advance() // Consume AS
if !p.isIdentifier() {
return tableRef, p.expectedError("alias after AS")
}
}
if p.isIdentifier() {
tableRef.Alias = p.currentToken.Token.Value
p.advance()
}
}
// MariaDB FOR SYSTEM_TIME temporal query (10.3.4+)
if p.isMariaDB() && p.isType(models.TokenTypeFor) {
// Only parse as FOR SYSTEM_TIME if next token is SYSTEM_TIME
next := p.peekToken()
if strings.EqualFold(next.Token.Value, "SYSTEM_TIME") {
p.advance() // Consume FOR
sysTime, err := p.parseForSystemTimeClause()
if err != nil {
return tableRef, err
}
tableRef.ForSystemTime = sysTime
}
}
// SQL Server table hints: WITH (NOLOCK), WITH (ROWLOCK, UPDLOCK), etc.
if p.dialect == string(keywords.DialectSQLServer) && p.isType(models.TokenTypeWith) {
if p.peekToken().Token.Type == models.TokenTypeLParen {
hints, err := p.parseTableHints()
if err != nil {
return tableRef, err
}
tableRef.TableHints = hints
}
}
// SQL Server / Oracle PIVOT clause
if p.isPivotKeyword() {
pivot, err := p.parsePivotClause()
if err != nil {
return tableRef, err
}
tableRef.Pivot = pivot
p.parsePivotAlias(&tableRef)
}
// SQL Server / Oracle UNPIVOT clause
if p.isUnpivotKeyword() {
unpivot, err := p.parseUnpivotClause()
if err != nil {
return tableRef, err
}
tableRef.Unpivot = unpivot
p.parsePivotAlias(&tableRef)
}
// Snowflake / Oracle MATCH_RECOGNIZE clause
if p.isMatchRecognizeKeyword() {
mr, err := p.parseMatchRecognize()
if err != nil {
return tableRef, err
}
tableRef.MatchRecognize = mr
// Optional alias after MATCH_RECOGNIZE (...)
if p.isType(models.TokenTypeAs) {
p.advance()
}
if p.isIdentifier() {
tableRef.Alias = p.currentToken.Token.Value
p.advance()
}
}
return tableRef, nil
}
// parseJoinedTableRef parses the table reference on the right-hand side of a JOIN.
func (p *Parser) parseJoinedTableRef(joinType string) (ast.TableReference, error) {
var ref ast.TableReference
// Optional LATERAL (PostgreSQL)
isLateral := false
if p.isType(models.TokenTypeLateral) {
isLateral = true
p.advance()
}
if p.isType(models.TokenTypeLParen) {
// Derived table (subquery)
p.advance() // Consume (
if !p.isType(models.TokenTypeSelect) && !p.isType(models.TokenTypeWith) {
return ref, p.expectedError("SELECT in derived table")
}
p.advance() // Consume SELECT
subquery, err := p.parseSelectStatement()
if err != nil {
return ref, err
}
selectStmt, ok := subquery.(*ast.SelectStatement)
if !ok {
return ref, p.expectedError("SELECT statement in derived table")
}
if !p.isType(models.TokenTypeRParen) {
return ref, p.expectedError(")")
}
p.advance() // Consume )
ref = ast.TableReference{Subquery: selectStmt, Lateral: isLateral}
} else {
joinedName, err := p.parseQualifiedName()
if err != nil {
return ref, goerrors.ExpectedTokenError(
"table name after "+joinType+" JOIN",
p.currentToken.Token.Type.String(),
p.currentLocation(),
"",
)
}
ref = ast.TableReference{Name: joinedName, Lateral: isLateral}
}
// Optional alias.
// Guard: in MariaDB, CONNECT followed by BY is a hierarchical query clause, not an alias.
// Similarly, START followed by WITH is a hierarchical query seed, not an alias.
// Don't consume PIVOT/UNPIVOT as a table alias — they are contextual
// keywords in SQL Server/Oracle and must reach the pivot-clause parser below.
if (p.isIdentifier() || p.isType(models.TokenTypeAs)) && !p.isMariaDBClauseStart() && !p.isPivotKeyword() && !p.isUnpivotKeyword() && !p.isQualifyKeyword() && !p.isMinusSetOp() && !p.isSnowflakeTimeTravelStart() && !p.isSampleKeyword() && !p.isMatchRecognizeKeyword() {
if p.isType(models.TokenTypeAs) {
p.advance()
if !p.isIdentifier() {
return ref, p.expectedError("alias after AS")
}
}
if p.isIdentifier() {
ref.Alias = p.currentToken.Token.Value
p.advance()
}
}
// MariaDB FOR SYSTEM_TIME temporal query (10.3.4+)
if p.isMariaDB() && p.isType(models.TokenTypeFor) {
// Only parse as FOR SYSTEM_TIME if next token is SYSTEM_TIME
next := p.peekToken()
if strings.EqualFold(next.Token.Value, "SYSTEM_TIME") {
p.advance() // Consume FOR
sysTime, err := p.parseForSystemTimeClause()
if err != nil {
return ref, err
}
ref.ForSystemTime = sysTime
}
}
// SQL Server table hints
if p.dialect == string(keywords.DialectSQLServer) && p.isType(models.TokenTypeWith) {
if p.peekToken().Token.Type == models.TokenTypeLParen {
hints, err := p.parseTableHints()
if err != nil {
return ref, err
}
ref.TableHints = hints
}
}
// SQL Server / Oracle PIVOT clause
if p.isPivotKeyword() {
pivot, err := p.parsePivotClause()
if err != nil {
return ref, err
}
ref.Pivot = pivot
p.parsePivotAlias(&ref)
}
// SQL Server / Oracle UNPIVOT clause
if p.isUnpivotKeyword() {
unpivot, err := p.parseUnpivotClause()
if err != nil {
return ref, err
}
ref.Unpivot = unpivot
p.parsePivotAlias(&ref)
}
return ref, nil
}
// parseTableHints parses SQL Server table hints: WITH (NOLOCK), WITH (ROWLOCK, UPDLOCK), etc.
// Called when current token is WITH and peek is LParen.
func (p *Parser) parseTableHints() ([]string, error) {
p.advance() // Consume WITH
p.advance() // Consume (
var hints []string
for {
if p.isType(models.TokenTypeRParen) {
break
}
hint := strings.ToUpper(p.currentToken.Token.Value)
if hint == "" {
return nil, p.expectedError("table hint inside WITH (...)")
}
hints = append(hints, hint)
p.advance()
// Consume optional comma between hints
if p.isType(models.TokenTypeComma) {
p.advance()
}
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(") after table hints")
}
p.advance() // Consume )
return hints, nil
}