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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
use std::sync::atomic::{AtomicU64, Ordering};
use super::*;
/// Counter for generating unique derived table aliases when none is provided.
/// SQLite allows derived tables without aliases, unlike SQL:1999 which requires them.
static DERIVED_TABLE_COUNTER: AtomicU64 = AtomicU64::new(0);
impl Parser {
/// Parse FROM clause
pub(crate) fn parse_from_clause(&mut self) -> Result<vibesql_ast::FromClause, ParseError> {
// Parse the first table reference
let mut left = self.parse_table_reference()?;
// Check for USING without a preceding JOIN - SQLite error compatibility
if self.peek_keyword(Keyword::Using) {
return Err(ParseError {
message: "a JOIN clause is required before USING".to_string(),
});
}
// Check for JOINs or commas (left-associative)
while self.is_join_keyword() || self.peek() == &Token::Comma {
let (join_type, right, condition, using_columns, natural) =
if self.peek() == &Token::Comma {
// Comma normally represents CROSS JOIN, but SQLite's legacy syntax
// allows "FROM t1, t2 ON condition" which behaves like INNER JOIN
self.advance(); // Consume comma
let right = self.parse_table_reference()?;
// Check for legacy ON clause after comma-join
// SQLite allows: FROM t1, t2 ON t1.a=t2.b (treated as INNER JOIN)
if self.peek_keyword(Keyword::On) {
self.consume_keyword(Keyword::On)?;
let condition = self.parse_expression()?;
(vibesql_ast::JoinType::Inner, right, Some(condition), None, false)
} else {
(vibesql_ast::JoinType::Cross, right, None, None, false)
}
} else {
let (join_type, natural) = self.parse_join_type()?;
// Parse right table reference
let right = self.parse_table_reference()?;
// Parse ON condition or USING clause (comes after table reference)
// NATURAL JOIN should not have an ON or USING clause
let (condition, using_columns) = if self.peek_keyword(Keyword::On) {
if natural {
return Err(ParseError {
message: "a NATURAL join may not have an ON or USING clause"
.to_string(),
});
}
self.consume_keyword(Keyword::On)?;
(Some(self.parse_expression()?), None)
} else if self.peek_keyword(Keyword::Using) {
if natural {
return Err(ParseError {
message: "a NATURAL join may not have an ON or USING clause"
.to_string(),
});
}
self.consume_keyword(Keyword::Using)?;
self.expect_token(Token::LParen)?;
let columns = self.parse_comma_separated_list(|p| p.parse_identifier())?;
self.expect_token(Token::RParen)?;
(None, Some(columns))
} else {
(None, None)
};
(join_type, right, condition, using_columns, natural)
};
// Build JOIN node
left = vibesql_ast::FromClause::Join {
left: Box::new(left),
right: Box::new(right),
join_type,
condition,
using_columns,
natural,
alias: None,
};
}
Ok(left)
}
/// Parse VALUES clause rows: VALUES(1,2), (3,4), ...
/// Returns Vec<Vec<Expression>> where each inner vec is a row
pub(crate) fn parse_values_rows(
&mut self,
) -> Result<Vec<Vec<vibesql_ast::Expression>>, ParseError> {
self.expect_keyword(Keyword::Values)?;
let mut rows = Vec::new();
loop {
self.expect_token(Token::LParen)?;
let row = self.parse_comma_separated_list(|p| p.parse_expression())?;
self.expect_token(Token::RParen)?;
rows.push(row);
if matches!(self.peek(), Token::Comma) {
self.advance();
} else {
break;
}
}
Ok(rows)
}
/// Parse a single table reference (table name, subquery, or derived table with alias)
pub(crate) fn parse_table_reference(&mut self) -> Result<vibesql_ast::FromClause, ParseError> {
match self.peek() {
Token::LParen => {
// Parenthesized expression: could be a subquery, VALUES, or a JOIN expression
self.advance(); // Consume '('
// Check if this is a subquery (starts with SELECT or WITH), VALUES, or a table
// reference/JOIN
let result =
if self.peek_keyword(Keyword::Select) || self.peek_keyword(Keyword::With) {
// Parse the SELECT statement (subquery, possibly with CTE)
let query = Box::new(self.parse_select_statement()?);
// Expect closing ')'
match self.peek() {
Token::RParen => {
self.advance();
}
_ => {
return Err(ParseError {
message: "Expected ')' after subquery".to_string(),
})
}
}
// Support both SQL:1999 (AS required) and MySQL (AS optional) modes
// Parse optional AS keyword
if self.peek_keyword(Keyword::As) {
self.consume_keyword(Keyword::As)?;
}
// Parse alias - keywords allowed as aliases (except clause keywords)
// SQLite allows derived tables without aliases; auto-generate if not provided
// SQLite also allows single-quoted strings as aliases (non-standard but common)
let alias = match self.peek() {
Token::Identifier(id)
| Token::DelimitedIdentifier(id)
| Token::String(id) => {
let alias = id.clone();
self.advance();
alias
}
Token::Keyword { keyword: kw, .. } => {
// Only consume keyword if it looks like it could be an alias
// (not a SQL keyword that starts a new clause)
if !matches!(
kw,
Keyword::Where
| Keyword::Order
| Keyword::Limit
| Keyword::Offset
| Keyword::Group
| Keyword::Having
| Keyword::Union
| Keyword::Intersect
| Keyword::Except
| Keyword::Join
| Keyword::Inner
| Keyword::Left
| Keyword::Right
| Keyword::Full
| Keyword::Cross
| Keyword::Natural
| Keyword::On
| Keyword::Using
) {
let alias = kw.to_string();
self.advance();
alias
} else {
// Generate default alias for clause keywords
format!(
"(subquery-{})",
DERIVED_TABLE_COUNTER.fetch_add(1, Ordering::Relaxed)
)
}
}
_ => {
// Auto-generate unique alias for SQLite compatibility
format!(
"(subquery-{})",
DERIVED_TABLE_COUNTER.fetch_add(1, Ordering::Relaxed)
)
}
};
// Parse optional column aliases: AS alias (col1, col2, ...)
// SQL:1999 Feature E051-09
let column_aliases = self.parse_column_alias_list()?;
vibesql_ast::FromClause::Subquery { query, alias, column_aliases }
} else if self.peek_keyword(Keyword::Values) {
// Parse VALUES clause as table constructor
// Example: (VALUES(1,'a'), (2,'b')) AS t(x, y)
let rows = self.parse_values_rows()?;
// Expect closing ')'
match self.peek() {
Token::RParen => {
self.advance();
}
_ => {
return Err(ParseError {
message: "Expected ')' after VALUES clause".to_string(),
})
}
}
// Parse optional AS keyword
if self.peek_keyword(Keyword::As) {
self.consume_keyword(Keyword::As)?;
}
// Parse alias (optional for VALUES tables) - keywords allowed as aliases
// If no alias is provided, generate a default one
// SQLite also allows single-quoted strings as aliases (non-standard but common)
let alias = match self.peek() {
Token::Identifier(id)
| Token::DelimitedIdentifier(id)
| Token::String(id) => {
let alias = id.clone();
self.advance();
alias
}
Token::Keyword { keyword: kw, .. } => {
// Only consume keyword if it looks like it could be an alias
// (not a SQL keyword that starts a new clause)
if !matches!(
kw,
Keyword::Where
| Keyword::Order
| Keyword::Limit
| Keyword::Offset
| Keyword::Group
| Keyword::Having
| Keyword::Union
| Keyword::Intersect
| Keyword::Except
| Keyword::Join
| Keyword::Inner
| Keyword::Left
| Keyword::Right
| Keyword::Full
| Keyword::Cross
| Keyword::Natural
| Keyword::On
| Keyword::Using
) {
let alias = kw.to_string();
self.advance();
alias
} else {
// Generate default alias when no explicit alias provided
"_values_".to_string()
}
}
_ => {
// Generate default alias when no explicit alias provided
"_values_".to_string()
}
};
// Parse optional column aliases: AS alias (col1, col2, ...)
let column_aliases = self.parse_column_alias_list()?;
vibesql_ast::FromClause::Values { rows, alias, column_aliases }
} else {
// Parenthesized table reference or JOIN expression
// Parse as a FROM clause (which handles JOINs)
let mut from_clause = self.parse_from_clause()?;
// Expect closing ')'
match self.peek() {
Token::RParen => {
self.advance();
}
_ => {
return Err(ParseError {
message: "Expected ')' after parenthesized table reference"
.to_string(),
})
}
}
// Parse optional alias for parenthesized join expressions
// Example: FROM t1 JOIN (t2 JOIN t3 USING(id)) AS j1 ON j1.id=t1.id
if self.peek_keyword(Keyword::As) {
self.consume_keyword(Keyword::As)?;
// Parse alias - must be an identifier or keyword usable as identifier
let alias = self.parse_alias_name()?;
// Set alias on the outermost Join node
if let vibesql_ast::FromClause::Join {
left,
right,
join_type,
condition,
using_columns,
natural,
..
} = from_clause
{
from_clause = vibesql_ast::FromClause::Join {
left,
right,
join_type,
condition,
using_columns,
natural,
alias: Some(alias),
};
}
}
from_clause
};
Ok(result)
}
// SQLite compatibility: single-quoted strings can be used as table names
Token::Identifier(_) | Token::DelimitedIdentifier(_) | Token::String(_) => {
let table = self.parse_table_ref()?;
// Check for optional alias
// Parse optional table alias - keywords allowed after AS (e.g., FROM t AS year)
let alias = if self.peek_keyword(Keyword::As) {
self.consume_keyword(Keyword::As)?;
Some(self.parse_alias_name()?)
} else if matches!(
self.peek(),
Token::Identifier(_) | Token::DelimitedIdentifier(_)
) && !self.is_join_keyword()
&& !self.peek_index_hint()
{
// Implicit alias (no AS keyword) - but not a JOIN keyword
match self.peek() {
Token::Identifier(id) | Token::DelimitedIdentifier(id) => {
let alias = id.clone();
self.advance();
Some(alias)
}
_ => None,
}
} else if matches!(self.peek(), Token::Keyword { keyword: _, .. })
&& !self.is_join_keyword()
&& !self.is_clause_keyword()
&& !self.peek_index_hint()
{
// Allow non-reserved keywords as implicit aliases (e.g., FROM t m)
// Keywords like M, YEAR, etc. can be used as aliases
match self.peek() {
Token::Keyword { keyword: kw, .. } => {
let alias = kw.to_string();
self.advance();
Some(alias)
}
_ => None,
}
} else {
None
};
// Parse optional column aliases: AS alias (col1, col2, ...)
// SQL:1999 Feature E051-09
// Note: column_aliases requires an alias to be present
let column_aliases =
if alias.is_some() { self.parse_column_alias_list()? } else { None };
// Parse SQLite index hints: INDEXED BY <name> / NOT INDEXED
let index_hint = self.parse_index_hint()?;
Ok(vibesql_ast::FromClause::Table {
name: table.full_name(),
alias,
column_aliases,
quoted: table.is_any_quoted(),
index_hint,
})
}
// Allow unreserved keywords (like NULLS, TIMESTAMP, etc.) as table names
Token::Keyword { keyword: kw, .. } if kw.can_be_identifier() => {
let table = self.parse_table_ref()?;
// Check for optional alias
let alias = if self.peek_keyword(Keyword::As) {
self.consume_keyword(Keyword::As)?;
Some(self.parse_alias_name()?)
} else if matches!(
self.peek(),
Token::Identifier(_) | Token::DelimitedIdentifier(_)
) && !self.is_join_keyword()
&& !self.peek_index_hint()
{
match self.peek() {
Token::Identifier(id) | Token::DelimitedIdentifier(id) => {
let alias = id.clone();
self.advance();
Some(alias)
}
_ => None,
}
} else {
None
};
let column_aliases =
if alias.is_some() { self.parse_column_alias_list()? } else { None };
// Parse SQLite index hints: INDEXED BY <name> / NOT INDEXED
let index_hint = self.parse_index_hint()?;
Ok(vibesql_ast::FromClause::Table {
name: table.full_name(),
alias,
column_aliases,
quoted: table.is_any_quoted(),
index_hint,
})
}
// No table name / subquery where one was required (e.g. `SELECT * FROM;`).
// SQLite reports this as a token-level syntax error — `near ";": syntax
// error` — rather than a descriptive message, so mirror that. This also
// lets CREATE TRIGGER bodies surface the same syntax error at create time
// (trigger1-2.1 / 2.2).
_ => Err(ParseError { message: self.peek().syntax_error() }),
}
}
/// Check if the upcoming tokens form a SQLite index hint:
/// `INDEXED BY <name>` or `NOT INDEXED`.
///
/// Note: INDEXED is not a keyword in our lexer, so it arrives as an
/// identifier token (lowercased by the lexer).
pub(crate) fn peek_index_hint(&self) -> bool {
match self.peek() {
Token::Identifier(id) if id.eq_ignore_ascii_case("indexed") => {
self.peek_next_keyword(Keyword::By)
}
Token::Keyword { keyword: Keyword::Not, .. } => {
matches!(self.peek_next(), Token::Identifier(id) if id.eq_ignore_ascii_case("indexed"))
}
_ => false,
}
}
/// Parse SQLite index hints: `INDEXED BY <index-name>` or `NOT INDEXED`.
///
/// The hint is carried through the AST so the executor can validate that
/// an `INDEXED BY` index exists on the table (SQLite: `no such index: X`).
/// VibeSQL's planner chooses indexes independently, so the hint has no
/// effect on planning.
pub(crate) fn parse_index_hint(
&mut self,
) -> Result<Option<vibesql_ast::IndexHint>, ParseError> {
if !self.peek_index_hint() {
return Ok(None);
}
if self.peek_keyword(Keyword::Not) {
self.advance(); // consume NOT
self.advance(); // consume INDEXED
return Ok(Some(vibesql_ast::IndexHint::NotIndexed));
}
self.advance(); // consume INDEXED
self.advance(); // consume BY
match self.peek() {
Token::Identifier(name) | Token::DelimitedIdentifier(name) => {
let name = name.clone();
self.advance();
Ok(Some(vibesql_ast::IndexHint::IndexedBy(name)))
}
Token::Keyword { keyword: kw, .. } if kw.can_be_identifier() => {
let name = kw.to_string();
self.advance();
Ok(Some(vibesql_ast::IndexHint::IndexedBy(name)))
}
_ => Err(ParseError { message: "Expected index name after INDEXED BY".to_string() }),
}
}
/// Check if current token is a JOIN keyword
pub(crate) fn is_join_keyword(&self) -> bool {
matches!(
self.peek(),
Token::Keyword { keyword: Keyword::Join, .. }
| Token::Keyword { keyword: Keyword::Inner, .. }
| Token::Keyword { keyword: Keyword::Left, .. }
| Token::Keyword { keyword: Keyword::Right, .. }
| Token::Keyword { keyword: Keyword::Cross, .. }
| Token::Keyword { keyword: Keyword::Full, .. }
| Token::Keyword { keyword: Keyword::Natural, .. }
| Token::Keyword { keyword: Keyword::Outer, .. }
)
}
/// Check if current token is a clause keyword that cannot be used as implicit alias
/// These keywords start new clauses in SELECT statements
pub(crate) fn is_clause_keyword(&self) -> bool {
matches!(
self.peek(),
Token::Keyword { keyword: Keyword::On, .. }
| Token::Keyword { keyword: Keyword::Where, .. }
| Token::Keyword { keyword: Keyword::Group, .. }
| Token::Keyword { keyword: Keyword::Having, .. }
| Token::Keyword { keyword: Keyword::Window, .. }
| Token::Keyword { keyword: Keyword::Order, .. }
| Token::Keyword { keyword: Keyword::Limit, .. }
| Token::Keyword { keyword: Keyword::Offset, .. }
| Token::Keyword { keyword: Keyword::Union, .. }
| Token::Keyword { keyword: Keyword::Intersect, .. }
| Token::Keyword { keyword: Keyword::Except, .. }
| Token::Keyword { keyword: Keyword::Using, .. }
| Token::Keyword { keyword: Keyword::For, .. }
// RETURNING terminates the SELECT embedded in INSERT ... SELECT
// ... RETURNING; SQLite likewise refuses RETURNING as an
// implicit (AS-less) table alias.
| Token::Keyword { keyword: Keyword::Returning, .. }
)
}
/// Parse JOIN type (INNER JOIN, LEFT JOIN, NATURAL JOIN, etc.)
/// Returns (JoinType, is_natural)
///
/// SQLite supports NATURAL in various positions:
/// - NATURAL JOIN, NATURAL LEFT JOIN, NATURAL LEFT OUTER JOIN
/// - LEFT NATURAL JOIN, LEFT OUTER NATURAL JOIN
/// - OUTER LEFT NATURAL JOIN
///
/// Invalid combinations like "INNER OUTER" or "LEFT BOGUS" produce:
/// "unknown join type: INNER OUTER" (SQLite-compatible error message)
pub(crate) fn parse_join_type(&mut self) -> Result<(vibesql_ast::JoinType, bool), ParseError> {
// Track consumed join type keywords for error messages
let mut consumed_keywords: Vec<String> = Vec::new();
// Check for optional NATURAL keyword first
let mut is_natural = if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
consumed_keywords.push("NATURAL".to_string());
true
} else {
false
};
let join_type = match self.peek() {
Token::Keyword { keyword: Keyword::Join, .. } => {
self.advance();
vibesql_ast::JoinType::Inner // Default JOIN is INNER JOIN
}
Token::Keyword { keyword: Keyword::Inner, .. } => {
self.advance();
consumed_keywords.push("INNER".to_string());
// Check for NATURAL after INNER (INNER NATURAL JOIN)
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
// Check for invalid combinations like "INNER OUTER" or "INNER BOGUS"
if let Token::Keyword { keyword: kw, .. } = self.peek() {
if *kw != Keyword::Join && *kw != Keyword::Natural {
// Consume remaining non-JOIN keywords to build error message
while let Token::Keyword { keyword: next_kw, .. } = self.peek() {
if *next_kw == Keyword::Join {
break;
}
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
// If we ended on JOIN, that's part of an invalid combination
if self.peek_keyword(Keyword::Join) {
// We have something like "INNER OUTER JOIN" - invalid
return Err(ParseError {
message: format!(
"unknown join type: {}",
consumed_keywords.join(" ")
),
});
}
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
});
}
} else if let Token::Identifier(id) = self.peek() {
// Handle "INNER BOGUS" where BOGUS is an identifier
consumed_keywords.push(id.to_uppercase());
self.advance();
// Consume any more keywords/identifiers before JOIN
loop {
match self.peek() {
Token::Keyword { keyword: next_kw, .. }
if *next_kw != Keyword::Join =>
{
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
Token::Identifier(id2) => {
consumed_keywords.push(id2.to_uppercase());
self.advance();
}
_ => break,
}
}
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
});
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::Inner
}
Token::Keyword { keyword: Keyword::Left, .. } => {
self.advance();
consumed_keywords.push("LEFT".to_string());
// Optional OUTER keyword
if self.peek_keyword(Keyword::Outer) {
self.consume_keyword(Keyword::Outer)?;
}
// Check for NATURAL after LEFT [OUTER] (LEFT NATURAL JOIN, LEFT OUTER NATURAL JOIN)
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
// Check for invalid combinations like "LEFT BOGUS"
if let Token::Keyword { keyword: kw, .. } = self.peek() {
if *kw != Keyword::Join && *kw != Keyword::Natural && *kw != Keyword::Outer {
// Consume remaining non-JOIN keywords to build error message
while let Token::Keyword { keyword: next_kw, .. } = self.peek() {
if *next_kw == Keyword::Join {
break;
}
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
});
}
} else if let Token::Identifier(id) = self.peek() {
// Handle "LEFT BOGUS" where BOGUS is an identifier
consumed_keywords.push(id.to_uppercase());
self.advance();
// Consume any more keywords before JOIN
while let Token::Keyword { keyword: next_kw, .. } = self.peek() {
if *next_kw == Keyword::Join {
break;
}
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
});
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::LeftOuter
}
Token::Keyword { keyword: Keyword::Right, .. } => {
self.advance();
consumed_keywords.push("RIGHT".to_string());
// Optional OUTER keyword
if self.peek_keyword(Keyword::Outer) {
self.consume_keyword(Keyword::Outer)?;
}
// Check for NATURAL after RIGHT [OUTER]
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::RightOuter
}
Token::Keyword { keyword: Keyword::Cross, .. } => {
self.advance();
consumed_keywords.push("CROSS".to_string());
// Check for NATURAL after CROSS
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::Cross
}
Token::Keyword { keyword: Keyword::Full, .. } => {
self.advance();
consumed_keywords.push("FULL".to_string());
// Optional OUTER keyword
if self.peek_keyword(Keyword::Outer) {
self.consume_keyword(Keyword::Outer)?;
}
// Check for NATURAL after FULL [OUTER]
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::FullOuter
}
// Support "OUTER LEFT/RIGHT/FULL JOIN" syntax (SQLite compatibility)
Token::Keyword { keyword: Keyword::Outer, .. } => {
self.advance(); // Consume OUTER
consumed_keywords.push("OUTER".to_string());
match self.peek() {
Token::Keyword { keyword: Keyword::Left, .. } => {
self.advance();
// Check for NATURAL after OUTER LEFT
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::LeftOuter
}
Token::Keyword { keyword: Keyword::Right, .. } => {
self.advance();
// Check for NATURAL after OUTER RIGHT
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::RightOuter
}
Token::Keyword { keyword: Keyword::Full, .. } => {
self.advance();
// Check for NATURAL after OUTER FULL
if self.peek_keyword(Keyword::Natural) {
self.consume_keyword(Keyword::Natural)?;
is_natural = true;
}
self.expect_keyword(Keyword::Join)?;
vibesql_ast::JoinType::FullOuter
}
Token::Keyword { keyword: Keyword::Join, .. } => {
// "OUTER JOIN" without LEFT/RIGHT/FULL defaults to LEFT OUTER JOIN
self.advance();
vibesql_ast::JoinType::LeftOuter
}
Token::Keyword { keyword: kw, .. } => {
// Invalid combination like "OUTER NATURAL INNER"
consumed_keywords.push(kw.to_string().to_uppercase());
self.advance();
// Consume any more keywords before JOIN
while let Token::Keyword { keyword: next_kw, .. } = self.peek() {
if *next_kw == Keyword::Join {
break;
}
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
});
}
_ => {
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
})
}
}
}
_ => {
// Handle "NATURAL AWK SED JOIN" and similar
if !consumed_keywords.is_empty() {
// We already consumed NATURAL, now we see something unexpected
while let Token::Keyword { keyword: next_kw, .. } = self.peek() {
if *next_kw == Keyword::Join {
break;
}
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
while let Token::Identifier(id) = self.peek() {
consumed_keywords.push(id.to_uppercase());
self.advance();
}
// Keep consuming keywords until JOIN
while let Token::Keyword { keyword: next_kw, .. } = self.peek() {
if *next_kw == Keyword::Join {
break;
}
consumed_keywords.push(next_kw.to_string().to_uppercase());
self.advance();
}
return Err(ParseError {
message: format!("unknown join type: {}", consumed_keywords.join(" ")),
});
}
return Err(ParseError { message: "Expected JOIN keyword".to_string() });
}
};
// NATURAL CROSS JOIN is valid SQL and should apply the natural join condition
// (matching on common column names). The executor handles this by treating
// NATURAL CROSS JOIN as an inner join with the natural join condition.
Ok((join_type, is_natural))
}
}