1#[cfg(not(feature = "std"))]
16use alloc::{
17 boxed::Box,
18 format,
19 string::{String, ToString},
20 vec,
21 vec::Vec,
22};
23use core::fmt;
24
25use ddl::WebhookSourceInfo;
26use itertools::Itertools;
27use tracing::{debug, instrument};
28use winnow::combinator::{alt, cut_err, dispatch, fail, opt, peek, preceded, repeat, separated};
29use winnow::{ModalResult, Parser as _};
30
31use crate::ast::*;
32use crate::keywords::{self, Keyword};
33use crate::parser_v2::{
34 ParserExt as _, dollar_quoted_string, keyword, literal_i64, literal_uint, single_quoted_string,
35 token_number,
36};
37use crate::tokenizer::*;
38use crate::{impl_parse_to, parser_v2};
39
40pub(crate) const UPSTREAM_SOURCE_KEY: &str = "connector";
41pub(crate) const WEBHOOK_CONNECTOR: &str = "webhook";
42
43const WEBHOOK_WAIT_FOR_PERSISTENCE: &str = "webhook.wait_for_persistence";
44
45#[derive(Debug, Clone, PartialEq)]
46pub enum ParserError {
47 TokenizerError(String),
48 ParserError(String),
49}
50
51impl ParserError {
52 pub fn inner_msg(self) -> String {
53 match self {
54 ParserError::TokenizerError(s) | ParserError::ParserError(s) => s,
55 }
56 }
57}
58
59#[derive(Debug, thiserror::Error)]
60#[error("{0}")]
61pub struct StrError(pub String);
62
63#[macro_export]
65macro_rules! parser_err {
66 ($($arg:tt)*) => {
67 return Err(winnow::error::ErrMode::Backtrack(<winnow::error::ContextError as winnow::error::FromExternalError<_, _>>::from_external_error(
68 &Parser::default(),
69 $crate::parser::StrError(format!($($arg)*)),
70 )))
71 };
72}
73
74impl From<StrError> for winnow::error::ErrMode<winnow::error::ContextError> {
75 fn from(e: StrError) -> Self {
76 winnow::error::ErrMode::Backtrack(<winnow::error::ContextError as winnow::error::FromExternalError<_, _>>::from_external_error(
77 &Parser::default(),
78 e,
79 ))
80 }
81}
82
83macro_rules! return_ok_if_some {
85 ($e:expr) => {{
86 if let Some(v) = $e {
87 return Ok(v);
88 }
89 }};
90}
91
92#[derive(PartialEq)]
93pub enum IsOptional {
94 Optional,
95 Mandatory,
96}
97
98use IsOptional::*;
99
100pub enum IsLateral {
101 Lateral,
102 NotLateral,
103}
104
105use IsLateral::*;
106
107use crate::ast::ddl::AlterFragmentOperation;
108
109pub type IncludeOption = Vec<IncludeOptionItem>;
110
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112#[derive(Eq, Clone, Debug, PartialEq, Hash)]
113pub struct IncludeOptionItem {
114 pub column_type: Ident,
115 pub column_alias: Option<Ident>,
116 pub inner_field: Option<String>,
117 pub header_inner_expect_type: Option<DataType>,
118}
119
120#[derive(Debug)]
121pub enum WildcardOrExpr {
122 Expr(Expr),
123 ExprQualifiedWildcard(Expr, Vec<Ident>),
129 QualifiedWildcard(ObjectName, Option<Vec<Expr>>),
131 Wildcard(Option<Vec<Expr>>),
132}
133
134impl From<WildcardOrExpr> for FunctionArgExpr {
135 fn from(wildcard_expr: WildcardOrExpr) -> Self {
136 match wildcard_expr {
137 WildcardOrExpr::Expr(expr) => Self::Expr(expr),
138 WildcardOrExpr::ExprQualifiedWildcard(expr, prefix) => {
139 Self::ExprQualifiedWildcard(expr, prefix)
140 }
141 WildcardOrExpr::QualifiedWildcard(prefix, except) => {
142 Self::QualifiedWildcard(prefix, except)
143 }
144 WildcardOrExpr::Wildcard(except) => Self::Wildcard(except),
145 }
146 }
147}
148
149impl From<TokenizerError> for ParserError {
150 fn from(e: TokenizerError) -> Self {
151 ParserError::TokenizerError(e.to_string())
152 }
153}
154
155impl fmt::Display for ParserError {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 write!(
158 f,
159 "sql parser error: {}",
160 match self {
161 ParserError::TokenizerError(s) => s,
162 ParserError::ParserError(s) => s,
163 }
164 )
165 }
166}
167
168#[cfg(feature = "std")]
169impl std::error::Error for ParserError {}
170
171type ColumnsDefTuple = (
172 Vec<ColumnDef>,
173 Vec<TableConstraint>,
174 Vec<SourceWatermark>,
175 Option<usize>,
176);
177
178#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
181pub enum Precedence {
182 Zero = 0,
183 LogicalOr, LogicalXor,
185 LogicalAnd, UnaryNot, Is, Cmp,
189 Like, Between, Other,
192 PlusMinus, MulDiv, Exp,
195 At,
196 Collate,
197 UnaryPosNeg,
198 PostfixFactorial,
199 Array,
200 DoubleColon, }
202
203#[derive(Clone, Copy, Default)]
204pub struct Parser<'a>(pub(crate) &'a [TokenWithLocation]);
205
206impl Parser<'_> {
207 #[instrument(level = "debug")]
209 pub fn parse_sql(sql: &str) -> Result<Vec<Statement>, ParserError> {
210 let mut tokenizer = Tokenizer::new(sql);
211 let tokens = tokenizer.tokenize_with_location()?;
212 let parser = Parser(&tokens);
213 let stmts = Parser::parse_statements.parse(parser).map_err(|e| {
214 let loc = match tokens.get(e.offset()) {
217 Some(token) => token.location.clone(),
218 None => {
219 Location {
221 line: sql.lines().count() as u64,
222 column: sql.lines().last().map_or(0, |l| l.len() as u64) + 1,
223 }
224 }
225 };
226 let prefix = format!("LINE {}: ", loc.line);
227 let sql_line = sql.split('\n').nth(loc.line as usize - 1).unwrap();
228 let cursor = " ".repeat(prefix.len() + loc.column as usize - 1);
229 ParserError::ParserError(format!(
230 "{}\n{}{}\n{}^",
231 e.inner().to_string().replace('\n', ": "),
232 prefix,
233 sql_line,
234 cursor
235 ))
236 })?;
237 Ok(stmts)
238 }
239
240 pub fn parse_object_name_str(s: &str) -> Result<ObjectName, ParserError> {
242 let mut tokenizer = Tokenizer::new(s);
243 let tokens = tokenizer.tokenize_with_location()?;
244 let parser = Parser(&tokens);
245 Parser::parse_object_name
246 .parse(parser)
247 .map_err(|e| ParserError::ParserError(e.inner().to_string()))
248 }
249
250 pub fn parse_function_desc_str(func: &str) -> Result<FunctionDesc, ParserError> {
252 let mut tokenizer = Tokenizer::new(func);
253 let tokens = tokenizer.tokenize_with_location()?;
254 let parser = Parser(&tokens);
255 Parser::parse_function_desc
256 .parse(parser)
257 .map_err(|e| ParserError::ParserError(e.inner().to_string()))
258 }
259
260 fn parse_statements(&mut self) -> ModalResult<Vec<Statement>> {
262 let mut stmts = Vec::new();
263 let mut expecting_statement_delimiter = false;
264 loop {
265 while self.consume_token(&Token::SemiColon) {
267 expecting_statement_delimiter = false;
268 }
269
270 if self.peek_token() == Token::EOF {
271 break;
272 }
273 if expecting_statement_delimiter {
274 return self.expected("end of statement");
275 }
276
277 let statement = self.parse_statement()?;
278 stmts.push(statement);
279 expecting_statement_delimiter = true;
280 }
281 debug!("parsed statements:\n{:#?}", stmts);
282 Ok(stmts)
283 }
284
285 pub fn parse_statement(&mut self) -> ModalResult<Statement> {
288 let checkpoint = *self;
289 let token = self.next_token();
290 match token.token {
291 Token::Word(w) => match w.keyword {
292 Keyword::EXPLAIN => Ok(self.parse_explain()?),
293 Keyword::ANALYZE => Ok(self.parse_analyze()?),
294 Keyword::SELECT | Keyword::WITH | Keyword::VALUES => {
295 *self = checkpoint;
296 Ok(Statement::Query(Box::new(self.parse_query()?)))
297 }
298 Keyword::DECLARE => Ok(self.parse_declare()?),
299 Keyword::FETCH => Ok(self.parse_fetch_cursor()?),
300 Keyword::CLOSE => Ok(self.parse_close_cursor()?),
301 Keyword::TRUNCATE => Ok(self.parse_truncate()?),
302 Keyword::CREATE => Ok(self.parse_create()?),
303 Keyword::DISCARD => Ok(self.parse_discard()?),
304 Keyword::DROP => Ok(self.parse_drop()?),
305 Keyword::DELETE => Ok(self.parse_delete()?),
306 Keyword::INSERT => Ok(self.parse_insert()?),
307 Keyword::UPDATE => Ok(self.parse_update()?),
308 Keyword::ALTER => Ok(self.parse_alter()?),
309 Keyword::COPY => Ok(self.parse_copy()?),
310 Keyword::SET => Ok(self.parse_set()?),
311 Keyword::SHOW => {
312 if self.parse_keyword(Keyword::CREATE) {
313 Ok(self.parse_show_create()?)
314 } else {
315 Ok(self.parse_show()?)
316 }
317 }
318 Keyword::CANCEL => Ok(self.parse_cancel_job()?),
319 Keyword::KILL => Ok(self.parse_kill_process()?),
320 Keyword::DESCRIBE => Ok(Statement::Describe {
321 name: self.parse_object_name()?,
322 }),
323 Keyword::GRANT => Ok(self.parse_grant()?),
324 Keyword::REVOKE => Ok(self.parse_revoke()?),
325 Keyword::START => Ok(self.parse_start_transaction()?),
326 Keyword::ABORT => Ok(Statement::Abort),
327 Keyword::BEGIN => Ok(self.parse_begin()?),
331 Keyword::COMMIT => Ok(self.parse_commit()?),
332 Keyword::ROLLBACK => Ok(self.parse_rollback()?),
333 Keyword::DEALLOCATE => Ok(self.parse_deallocate()?),
336 Keyword::EXECUTE => Ok(self.parse_execute()?),
337 Keyword::PREPARE => Ok(self.parse_prepare()?),
338 Keyword::COMMENT => Ok(self.parse_comment()?),
339 Keyword::FLUSH => Ok(Statement::Flush),
340 Keyword::WAIT => Ok(Statement::Wait),
341 Keyword::RECOVER => Ok(Statement::Recover),
342 Keyword::USE => Ok(self.parse_use()?),
343 _ => self.expected_at(checkpoint, "statement"),
344 },
345 Token::LParen => {
346 *self = checkpoint;
347 Ok(Statement::Query(Box::new(self.parse_query()?)))
348 }
349 _ => self.expected_at(checkpoint, "statement"),
350 }
351 }
352
353 pub fn parse_truncate(&mut self) -> ModalResult<Statement> {
354 let _ = self.parse_keyword(Keyword::TABLE);
355 let table_name = self.parse_object_name()?;
356 Ok(Statement::Truncate { table_name })
357 }
358
359 pub fn parse_analyze(&mut self) -> ModalResult<Statement> {
360 let table_name = self.parse_object_name()?;
361
362 Ok(Statement::Analyze { table_name })
363 }
364
365 pub fn parse_wildcard_or_expr(&mut self) -> ModalResult<WildcardOrExpr> {
374 let checkpoint = *self;
375
376 match self.next_token().token {
377 Token::Word(w) if self.peek_token() == Token::Period => {
378 let wildcard_expr = self.parse_simple_wildcard_expr(checkpoint)?;
381 return self.word_concat_wildcard_expr(w.to_ident()?, wildcard_expr);
382 }
383 Token::Mul => {
384 return Ok(WildcardOrExpr::Wildcard(self.parse_except()?));
385 }
386 Token::LParen => {
389 let mut expr = self.parse_expr()?;
390 if self.consume_token(&Token::RParen) {
391 while let Expr::Nested(inner) = expr {
393 expr = *inner;
394 }
395 let wildcard_expr = self.parse_simple_wildcard_expr(checkpoint)?;
398 return self.expr_concat_wildcard_expr(expr, wildcard_expr);
399 }
400 }
401 _ => (),
402 };
403
404 *self = checkpoint;
405 self.parse_expr().map(WildcardOrExpr::Expr)
406 }
407
408 pub fn word_concat_wildcard_expr(
410 &mut self,
411 ident: Ident,
412 simple_wildcard_expr: WildcardOrExpr,
413 ) -> ModalResult<WildcardOrExpr> {
414 let mut idents = vec![ident];
415 let mut except_cols = vec![];
416 match simple_wildcard_expr {
417 WildcardOrExpr::QualifiedWildcard(ids, except) => {
418 idents.extend(ids.0);
419 if let Some(cols) = except {
420 except_cols = cols;
421 }
422 }
423 WildcardOrExpr::Wildcard(except) => {
424 if let Some(cols) = except {
425 except_cols = cols;
426 }
427 }
428 WildcardOrExpr::ExprQualifiedWildcard(_, _) => unreachable!(),
429 WildcardOrExpr::Expr(e) => return Ok(WildcardOrExpr::Expr(e)),
430 }
431 Ok(WildcardOrExpr::QualifiedWildcard(
432 ObjectName(idents),
433 if except_cols.is_empty() {
434 None
435 } else {
436 Some(except_cols)
437 },
438 ))
439 }
440
441 pub fn expr_concat_wildcard_expr(
443 &mut self,
444 expr: Expr,
445 simple_wildcard_expr: WildcardOrExpr,
446 ) -> ModalResult<WildcardOrExpr> {
447 if let WildcardOrExpr::Expr(e) = simple_wildcard_expr {
448 return Ok(WildcardOrExpr::Expr(e));
449 }
450
451 let mut idents = vec![];
453 let expr = match expr {
454 Expr::Identifier(_) => expr,
456 Expr::CompoundIdentifier(_) => expr,
458 Expr::Cast { .. } => expr,
460 Expr::Function(_) => expr,
462 Expr::FieldIdentifier(expr, ids) => {
464 idents.extend(ids);
466 *expr
467 }
468 _ => return Ok(WildcardOrExpr::Expr(expr)),
471 };
472
473 match simple_wildcard_expr {
474 WildcardOrExpr::QualifiedWildcard(ids, except) => {
475 if except.is_some() {
476 return self.expected("Expr quantified wildcard does not support except");
477 }
478 idents.extend(ids.0);
479 }
480 WildcardOrExpr::Wildcard(except) => {
481 if except.is_some() {
482 return self.expected("Expr quantified wildcard does not support except");
483 }
484 }
485 WildcardOrExpr::ExprQualifiedWildcard(_, _) => unreachable!(),
486 WildcardOrExpr::Expr(_) => unreachable!(),
487 }
488 Ok(WildcardOrExpr::ExprQualifiedWildcard(expr, idents))
489 }
490
491 pub fn parse_simple_wildcard_expr(&mut self, checkpoint: Self) -> ModalResult<WildcardOrExpr> {
495 let mut id_parts = vec![];
496 while self.consume_token(&Token::Period) {
497 let ckpt = *self;
498 let token = self.next_token();
499 match token.token {
500 Token::Word(w) => id_parts.push(w.to_ident()?),
501 Token::Mul => {
502 return if id_parts.is_empty() {
503 Ok(WildcardOrExpr::Wildcard(self.parse_except()?))
504 } else {
505 Ok(WildcardOrExpr::QualifiedWildcard(
506 ObjectName(id_parts),
507 self.parse_except()?,
508 ))
509 };
510 }
511 _ => {
512 *self = ckpt;
513 return self.expected("an identifier or a '*' after '.'");
514 }
515 }
516 }
517 *self = checkpoint;
518 self.parse_expr().map(WildcardOrExpr::Expr)
519 }
520
521 pub fn parse_except(&mut self) -> ModalResult<Option<Vec<Expr>>> {
522 if !self.parse_keyword(Keyword::EXCEPT) {
523 return Ok(None);
524 }
525 if !self.consume_token(&Token::LParen) {
526 return self.expected("EXCEPT should be followed by (");
527 }
528 let exprs = self.parse_comma_separated(Parser::parse_expr)?;
529 if self.consume_token(&Token::RParen) {
530 Ok(Some(exprs))
531 } else {
532 self.expected("( should be followed by ) after column names")
533 }
534 }
535
536 pub fn parse_expr(&mut self) -> ModalResult<Expr> {
538 self.parse_subexpr(Precedence::Zero)
539 }
540
541 pub fn parse_subexpr(&mut self, precedence: Precedence) -> ModalResult<Expr> {
543 debug!("parsing expr, current token: {:?}", self.peek_token().token);
544 let mut expr = self.parse_prefix()?;
545 debug!("prefix: {:?}", expr);
546 loop {
547 let next_precedence = self.get_next_precedence()?;
548 debug!("precedence: {precedence:?}, next precedence: {next_precedence:?}");
549
550 if precedence >= next_precedence {
551 break;
552 }
553
554 expr = self.parse_infix(expr, next_precedence)?;
555 }
556 Ok(expr)
557 }
558
559 pub fn parse_prefix(&mut self) -> ModalResult<Expr> {
561 return_ok_if_some!(self.maybe_parse(|parser| {
578 match parser.parse_data_type()? {
579 DataType::Interval => parser.parse_literal_interval(),
580 DataType::Custom(..) => parser_err!("dummy"),
588 data_type => Ok(Expr::TypedString {
589 data_type,
590 value: parser.parse_literal_string()?,
591 }),
592 }
593 }));
594
595 let checkpoint = *self;
596 let token = self.next_token();
597 let expr = match token.token.clone() {
598 Token::Word(w) => match w.keyword {
599 Keyword::TRUE | Keyword::FALSE | Keyword::NULL => {
600 *self = checkpoint;
601 Ok(Expr::Value(self.ensure_parse_value()?))
602 }
603 Keyword::CASE => self.parse_case_expr(),
604 Keyword::CAST => self.parse_cast_expr(),
605 Keyword::TRY_CAST => self.parse_try_cast_expr(),
606 Keyword::EXISTS => self.parse_exists_expr(),
607 Keyword::EXTRACT => self.parse_extract_expr(),
608 Keyword::SUBSTRING => self.parse_substring_expr(),
609 Keyword::POSITION => self.parse_position_expr(),
610 Keyword::OVERLAY => self.parse_overlay_expr(),
611 Keyword::TRIM => self.parse_trim_expr(),
612 Keyword::INTERVAL => self.parse_literal_interval(),
613 Keyword::NOT => Ok(Expr::UnaryOp {
614 op: UnaryOperator::Not,
615 expr: Box::new(self.parse_subexpr(Precedence::UnaryNot)?),
616 }),
617 Keyword::ROW => self.parse_row_expr(),
618 Keyword::ARRAY if self.peek_token() == Token::LParen => {
619 self.expect_token(&Token::LParen)?;
621 let exists_node = Expr::ArraySubquery(Box::new(self.parse_query()?));
622 self.expect_token(&Token::RParen)?;
623 Ok(exists_node)
624 }
625 Keyword::ARRAY if self.peek_token() == Token::LBracket => self.parse_array_expr(),
626 Keyword::MAP if self.peek_token() == Token::LBrace => self.parse_map_expr(),
627 Keyword::LEFT | Keyword::RIGHT => {
629 *self = checkpoint;
630 self.parse_function()
631 }
632 Keyword::OPERATOR if self.peek_token().token == Token::LParen => {
633 let op = UnaryOperator::PGQualified(Box::new(self.parse_qualified_operator()?));
634 Ok(Expr::UnaryOp {
635 op,
636 expr: Box::new(self.parse_subexpr(Precedence::Other)?),
637 })
638 }
639 keyword @ (Keyword::ALL | Keyword::ANY | Keyword::SOME) => {
640 self.expect_token(&Token::LParen)?;
641 let sub = self.parse_expr()?;
644 self.expect_token(&Token::RParen)?;
645
646 if let Expr::Subquery(_) = &sub {
648 parser_err!("ANY/SOME/ALL(Subquery) is not implemented");
649 }
650
651 Ok(match keyword {
652 Keyword::ALL => Expr::AllOp(Box::new(sub)),
653 Keyword::ANY | Keyword::SOME => Expr::SomeOp(Box::new(sub)),
655 _ => unreachable!(),
656 })
657 }
658 k if keywords::RESERVED_FOR_COLUMN_OR_TABLE_NAME.contains(&k) => {
659 parser_err!("syntax error at or near {token}")
660 }
661 _ => match self.peek_token().token {
664 Token::LParen | Token::Period | Token::Colon => {
665 *self = checkpoint;
666 if let Ok(object_name) = self.parse_object_name()
667 && !matches!(self.peek_token().token, Token::LParen | Token::Colon)
668 {
669 Ok(Expr::CompoundIdentifier(object_name.0))
670 } else {
671 *self = checkpoint;
672 self.parse_function()
673 }
674 }
675 _ => Ok(Expr::Identifier(w.to_ident()?)),
676 },
677 }, tok @ Token::Minus | tok @ Token::Plus => {
680 let op = if tok == Token::Plus {
681 UnaryOperator::Plus
682 } else {
683 UnaryOperator::Minus
684 };
685 let mut sub_expr = self.parse_subexpr(Precedence::UnaryPosNeg)?;
686 if let Expr::Value(Value::Number(ref mut s)) = sub_expr {
687 if tok == Token::Minus {
688 *s = format!("-{}", s);
689 }
690 return Ok(sub_expr);
691 }
692 Ok(Expr::UnaryOp {
693 op,
694 expr: Box::new(sub_expr),
695 })
696 }
697 tok @ Token::DoubleExclamationMark
698 | tok @ Token::PGSquareRoot
699 | tok @ Token::PGCubeRoot
700 | tok @ Token::AtSign
701 | tok @ Token::Tilde => {
702 let op = match tok {
703 Token::DoubleExclamationMark => UnaryOperator::PGPrefixFactorial,
704 Token::PGSquareRoot => UnaryOperator::PGSquareRoot,
705 Token::PGCubeRoot => UnaryOperator::PGCubeRoot,
706 Token::AtSign => UnaryOperator::PGAbs,
707 Token::Tilde => UnaryOperator::PGBitwiseNot,
708 _ => unreachable!(),
709 };
710 Ok(Expr::UnaryOp {
713 op,
714 expr: Box::new(self.parse_subexpr(Precedence::Other)?),
715 })
716 }
717 Token::Number(_)
718 | Token::SingleQuotedString(_)
719 | Token::DollarQuotedString(_)
720 | Token::NationalStringLiteral(_)
721 | Token::HexStringLiteral(_)
722 | Token::CstyleEscapesString(_) => {
723 *self = checkpoint;
724 Ok(Expr::Value(self.ensure_parse_value()?))
725 }
726 Token::Parameter(number) => self.parse_param(number),
727 Token::Pipe => {
728 let args = self.parse_comma_separated(Parser::parse_identifier)?;
729 self.expect_token(&Token::Pipe)?;
730 let body = self.parse_expr()?;
731 Ok(Expr::LambdaFunction {
732 args,
733 body: Box::new(body),
734 })
735 }
736 Token::LParen => {
737 let expr = if matches!(self.peek_token().token, Token::Word(w) if w.keyword == Keyword::SELECT || w.keyword == Keyword::WITH)
738 {
739 Expr::Subquery(Box::new(self.parse_query()?))
740 } else {
741 let mut exprs = self.parse_comma_separated(Parser::parse_expr)?;
742 if exprs.len() == 1 {
743 Expr::Nested(Box::new(exprs.pop().unwrap()))
744 } else {
745 Expr::Row(exprs)
746 }
747 };
748 self.expect_token(&Token::RParen)?;
749 if self.peek_token() == Token::Period && matches!(expr, Expr::Nested(_)) {
750 self.parse_struct_selection(expr)
751 } else {
752 Ok(expr)
753 }
754 }
755 _ => self.expected_at(checkpoint, "an expression"),
756 }?;
757
758 if self.parse_keyword(Keyword::COLLATE) {
759 Ok(Expr::Collate {
760 expr: Box::new(expr),
761 collation: self.parse_object_name()?,
762 })
763 } else {
764 Ok(expr)
765 }
766 }
767
768 fn parse_param(&mut self, param: String) -> ModalResult<Expr> {
769 let Ok(index) = param.parse() else {
770 parser_err!("Parameter symbol has a invalid index {}.", param);
771 };
772 Ok(Expr::Parameter { index })
773 }
774
775 pub fn parse_struct_selection(&mut self, expr: Expr) -> ModalResult<Expr> {
777 let mut nested_expr = expr;
778 while let Expr::Nested(inner) = nested_expr {
780 nested_expr = *inner;
781 }
782 let fields = self.parse_fields()?;
783 Ok(Expr::FieldIdentifier(Box::new(nested_expr), fields))
784 }
785
786 pub fn parse_fields(&mut self) -> ModalResult<Vec<Ident>> {
788 repeat(.., preceded(Token::Period, cut_err(Self::parse_identifier))).parse_next(self)
789 }
790
791 pub fn parse_qualified_operator(&mut self) -> ModalResult<QualifiedOperator> {
792 self.expect_token(&Token::LParen)?;
793
794 let checkpoint = *self;
795 let schema = match self.parse_identifier_non_reserved() {
796 Ok(ident) => {
797 self.expect_token(&Token::Period)?;
798 Some(ident)
799 }
800 Err(_) => {
801 *self = checkpoint;
802 None
803 }
804 };
805
806 const OP_CHARS: &[char] = &[
808 '+', '-', '*', '/', '<', '>', '=', '~', '!', '@', '#', '%', '^', '&', '|', '`', '?',
809 ];
810 let name = {
811 let checkpoint = *self;
818 let token = self.next_token();
819 let name = token.token.to_string();
820 if !name.trim_matches(OP_CHARS).is_empty() {
821 return self
822 .expected_at(checkpoint, &format!("one of {}", OP_CHARS.iter().join(" ")));
823 }
824 name
825 };
826
827 self.expect_token(&Token::RParen)?;
828 Ok(QualifiedOperator { schema, name })
829 }
830
831 pub fn parse_function(&mut self) -> ModalResult<Expr> {
833 let scalar_as_agg = if self.parse_keyword(Keyword::AGGREGATE) {
835 self.expect_token(&Token::Colon)?;
836 true
837 } else {
838 false
839 };
840 let name = self.parse_object_name()?;
841 let arg_list = self.parse_argument_list()?;
842
843 let within_group = if self.parse_keywords(&[Keyword::WITHIN, Keyword::GROUP]) {
844 self.expect_token(&Token::LParen)?;
845 self.expect_keywords(&[Keyword::ORDER, Keyword::BY])?;
846 let order_by = self.parse_order_by_expr()?;
847 self.expect_token(&Token::RParen)?;
848 Some(Box::new(order_by.clone()))
849 } else {
850 None
851 };
852
853 let filter = if self.parse_keyword(Keyword::FILTER) {
854 self.expect_token(&Token::LParen)?;
855 self.expect_keyword(Keyword::WHERE)?;
856 let filter_expr = self.parse_expr()?;
857 self.expect_token(&Token::RParen)?;
858 Some(Box::new(filter_expr))
859 } else {
860 None
861 };
862
863 let over = if self.parse_keyword(Keyword::OVER) {
864 self.expect_token(&Token::LParen)?;
866 let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
867 self.parse_comma_separated(Parser::parse_expr)?
869 } else {
870 vec![]
871 };
872 let order_by_window = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
873 self.parse_comma_separated(Parser::parse_order_by_expr)?
874 } else {
875 vec![]
876 };
877 let window_frame = if !self.consume_token(&Token::RParen) {
878 let window_frame = self.parse_window_frame()?;
879 self.expect_token(&Token::RParen)?;
880 Some(window_frame)
881 } else {
882 None
883 };
884
885 Some(WindowSpec {
886 partition_by,
887 order_by: order_by_window,
888 window_frame,
889 })
890 } else {
891 None
892 };
893
894 Ok(Expr::Function(Function {
895 scalar_as_agg,
896 name,
897 arg_list,
898 within_group,
899 filter,
900 over,
901 }))
902 }
903
904 pub fn parse_window_frame_units(&mut self) -> ModalResult<WindowFrameUnits> {
905 dispatch! { peek(keyword);
906 Keyword::ROWS => keyword.value(WindowFrameUnits::Rows),
907 Keyword::RANGE => keyword.value(WindowFrameUnits::Range),
908 Keyword::GROUPS => keyword.value(WindowFrameUnits::Groups),
909 Keyword::SESSION => keyword.value(WindowFrameUnits::Session),
910 _ => fail,
911 }
912 .expect("ROWS, RANGE, or GROUPS")
913 .parse_next(self)
914 }
915
916 pub fn parse_window_frame(&mut self) -> ModalResult<WindowFrame> {
917 let units = self.parse_window_frame_units()?;
918 let bounds = if self.parse_keyword(Keyword::BETWEEN) {
919 let start = self.parse_window_frame_bound()?;
921 self.expect_keyword(Keyword::AND)?;
922 let end = Some(self.parse_window_frame_bound()?);
923 WindowFrameBounds::Bounds { start, end }
924 } else if self.parse_keywords(&[Keyword::WITH, Keyword::GAP]) {
925 WindowFrameBounds::Gap(Box::new(self.parse_expr()?))
927 } else {
928 WindowFrameBounds::Bounds {
930 start: self.parse_window_frame_bound()?,
931 end: None,
932 }
933 };
934 let exclusion = if self.parse_keyword(Keyword::EXCLUDE) {
935 Some(self.parse_window_frame_exclusion()?)
936 } else {
937 None
938 };
939 Ok(WindowFrame {
940 units,
941 bounds,
942 exclusion,
943 })
944 }
945
946 pub fn parse_window_frame_bound(&mut self) -> ModalResult<WindowFrameBound> {
948 if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
949 Ok(WindowFrameBound::CurrentRow)
950 } else {
951 let rows = if self.parse_keyword(Keyword::UNBOUNDED) {
952 None
953 } else {
954 Some(Box::new(self.parse_expr()?))
955 };
956 if self.parse_keyword(Keyword::PRECEDING) {
957 Ok(WindowFrameBound::Preceding(rows))
958 } else if self.parse_keyword(Keyword::FOLLOWING) {
959 Ok(WindowFrameBound::Following(rows))
960 } else {
961 self.expected("PRECEDING or FOLLOWING")
962 }
963 }
964 }
965
966 pub fn parse_window_frame_exclusion(&mut self) -> ModalResult<WindowFrameExclusion> {
967 if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
968 Ok(WindowFrameExclusion::CurrentRow)
969 } else if self.parse_keyword(Keyword::GROUP) {
970 Ok(WindowFrameExclusion::Group)
971 } else if self.parse_keyword(Keyword::TIES) {
972 Ok(WindowFrameExclusion::Ties)
973 } else if self.parse_keywords(&[Keyword::NO, Keyword::OTHERS]) {
974 Ok(WindowFrameExclusion::NoOthers)
975 } else {
976 self.expected("CURRENT ROW, GROUP, TIES, or NO OTHERS")
977 }
978 }
979
980 fn parse_group_by_expr(&mut self) -> ModalResult<Expr> {
983 if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
984 self.expect_token(&Token::LParen)?;
985 let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
986 self.expect_token(&Token::RParen)?;
987 Ok(Expr::GroupingSets(result))
988 } else if self.parse_keyword(Keyword::CUBE) {
989 self.expect_token(&Token::LParen)?;
990 let result = self.parse_comma_separated(|p| p.parse_tuple(true, false))?;
991 self.expect_token(&Token::RParen)?;
992 Ok(Expr::Cube(result))
993 } else if self.parse_keyword(Keyword::ROLLUP) {
994 self.expect_token(&Token::LParen)?;
995 let result = self.parse_comma_separated(|p| p.parse_tuple(true, false))?;
996 self.expect_token(&Token::RParen)?;
997 Ok(Expr::Rollup(result))
998 } else {
999 self.parse_expr()
1000 }
1001 }
1002
1003 fn parse_tuple(&mut self, lift_singleton: bool, allow_empty: bool) -> ModalResult<Vec<Expr>> {
1007 if lift_singleton {
1008 if self.consume_token(&Token::LParen) {
1009 let result = if allow_empty && self.consume_token(&Token::RParen) {
1010 vec![]
1011 } else {
1012 let result = self.parse_comma_separated(Parser::parse_expr)?;
1013 self.expect_token(&Token::RParen)?;
1014 result
1015 };
1016 Ok(result)
1017 } else {
1018 Ok(vec![self.parse_expr()?])
1019 }
1020 } else {
1021 self.expect_token(&Token::LParen)?;
1022 let result = if allow_empty && self.consume_token(&Token::RParen) {
1023 vec![]
1024 } else {
1025 let result = self.parse_comma_separated(Parser::parse_expr)?;
1026 self.expect_token(&Token::RParen)?;
1027 result
1028 };
1029 Ok(result)
1030 }
1031 }
1032
1033 pub fn parse_case_expr(&mut self) -> ModalResult<Expr> {
1034 parser_v2::expr_case(self)
1035 }
1036
1037 pub fn parse_cast_expr(&mut self) -> ModalResult<Expr> {
1039 parser_v2::expr_cast(self)
1040 }
1041
1042 pub fn parse_try_cast_expr(&mut self) -> ModalResult<Expr> {
1044 parser_v2::expr_try_cast(self)
1045 }
1046
1047 pub fn parse_exists_expr(&mut self) -> ModalResult<Expr> {
1049 self.expect_token(&Token::LParen)?;
1050 let exists_node = Expr::Exists(Box::new(self.parse_query()?));
1051 self.expect_token(&Token::RParen)?;
1052 Ok(exists_node)
1053 }
1054
1055 pub fn parse_extract_expr(&mut self) -> ModalResult<Expr> {
1056 parser_v2::expr_extract(self)
1057 }
1058
1059 pub fn parse_substring_expr(&mut self) -> ModalResult<Expr> {
1060 parser_v2::expr_substring(self)
1061 }
1062
1063 pub fn parse_position_expr(&mut self) -> ModalResult<Expr> {
1065 parser_v2::expr_position(self)
1066 }
1067
1068 pub fn parse_overlay_expr(&mut self) -> ModalResult<Expr> {
1070 parser_v2::expr_overlay(self)
1071 }
1072
1073 pub fn parse_trim_expr(&mut self) -> ModalResult<Expr> {
1076 self.expect_token(&Token::LParen)?;
1077 let mut trim_where = None;
1078 if let Token::Word(word) = self.peek_token().token {
1079 if [Keyword::BOTH, Keyword::LEADING, Keyword::TRAILING].contains(&word.keyword) {
1080 trim_where = Some(self.parse_trim_where()?);
1081 }
1082 }
1083
1084 let (mut trim_what, expr) = if self.parse_keyword(Keyword::FROM) {
1085 (None, self.parse_expr()?)
1086 } else {
1087 let mut expr = self.parse_expr()?;
1088 if self.parse_keyword(Keyword::FROM) {
1089 let trim_what = std::mem::replace(&mut expr, self.parse_expr()?);
1090 (Some(Box::new(trim_what)), expr)
1091 } else {
1092 (None, expr)
1093 }
1094 };
1095
1096 if trim_what.is_none() && self.consume_token(&Token::Comma) {
1097 trim_what = Some(Box::new(self.parse_expr()?));
1098 }
1099 self.expect_token(&Token::RParen)?;
1100
1101 Ok(Expr::Trim {
1102 expr: Box::new(expr),
1103 trim_where,
1104 trim_what,
1105 })
1106 }
1107
1108 pub fn parse_trim_where(&mut self) -> ModalResult<TrimWhereField> {
1109 dispatch! { peek(keyword);
1110 Keyword::BOTH => keyword.value(TrimWhereField::Both),
1111 Keyword::LEADING => keyword.value(TrimWhereField::Leading),
1112 Keyword::TRAILING => keyword.value(TrimWhereField::Trailing),
1113 _ => fail
1114 }
1115 .expect("BOTH, LEADING, or TRAILING")
1116 .parse_next(self)
1117 }
1118
1119 pub fn parse_array_expr(&mut self) -> ModalResult<Expr> {
1121 let mut expected_depth = None;
1122 let exprs = self.parse_array_inner(0, &mut expected_depth)?;
1123 Ok(Expr::Array(Array {
1124 elem: exprs,
1125 named: true,
1127 }))
1128 }
1129
1130 fn parse_array_inner(
1131 &mut self,
1132 depth: usize,
1133 expected_depth: &mut Option<usize>,
1134 ) -> ModalResult<Vec<Expr>> {
1135 self.expect_token(&Token::LBracket)?;
1136 if let Some(expected_depth) = *expected_depth
1137 && depth > expected_depth
1138 {
1139 return self.expected("]");
1140 }
1141 let exprs = if self.peek_token() == Token::LBracket {
1142 self.parse_comma_separated(|parser| {
1143 let exprs = parser.parse_array_inner(depth + 1, expected_depth)?;
1144 Ok(Expr::Array(Array {
1145 elem: exprs,
1146 named: false,
1147 }))
1148 })?
1149 } else {
1150 if let Some(expected_depth) = *expected_depth {
1151 if depth < expected_depth {
1152 return self.expected("[");
1153 }
1154 } else {
1155 *expected_depth = Some(depth);
1156 }
1157 if self.consume_token(&Token::RBracket) {
1158 return Ok(vec![]);
1159 }
1160 self.parse_comma_separated(Self::parse_expr)?
1161 };
1162 self.expect_token(&Token::RBracket)?;
1163 Ok(exprs)
1164 }
1165
1166 pub fn parse_map_expr(&mut self) -> ModalResult<Expr> {
1168 self.expect_token(&Token::LBrace)?;
1169 if self.consume_token(&Token::RBrace) {
1170 return Ok(Expr::Map { entries: vec![] });
1171 }
1172 let entries = self.parse_comma_separated(|parser| {
1173 let key = parser.parse_expr()?;
1174 parser.expect_token(&Token::Colon)?;
1175 let value = parser.parse_expr()?;
1176 Ok((key, value))
1177 })?;
1178 self.expect_token(&Token::RBrace)?;
1179 Ok(Expr::Map { entries })
1180 }
1181
1182 pub fn parse_date_time_field(&mut self) -> ModalResult<DateTimeField> {
1184 dispatch! { peek(keyword);
1185 Keyword::YEAR => keyword.value(DateTimeField::Year),
1186 Keyword::MONTH => keyword.value(DateTimeField::Month),
1187 Keyword::DAY => keyword.value(DateTimeField::Day),
1188 Keyword::HOUR => keyword.value(DateTimeField::Hour),
1189 Keyword::MINUTE => keyword.value(DateTimeField::Minute),
1190 Keyword::SECOND => keyword.value(DateTimeField::Second),
1191 _ => fail,
1192 }
1193 .expect("date/time field")
1194 .parse_next(self)
1195 }
1196
1197 pub fn parse_date_time_field_in_extract(&mut self) -> ModalResult<String> {
1207 let checkpoint = *self;
1208 let token = self.next_token();
1209 match token.token {
1210 Token::Word(w) => Ok(w.value.to_uppercase()),
1211 Token::SingleQuotedString(s) => Ok(s.to_uppercase()),
1212 _ => {
1213 *self = checkpoint;
1214 self.expected("date/time field")
1215 }
1216 }
1217 }
1218
1219 pub fn parse_literal_interval(&mut self) -> ModalResult<Expr> {
1232 let value = self.parse_literal_string()?;
1240
1241 let leading_field = match self.peek_token().token {
1247 Token::Word(kw)
1248 if [
1249 Keyword::YEAR,
1250 Keyword::MONTH,
1251 Keyword::DAY,
1252 Keyword::HOUR,
1253 Keyword::MINUTE,
1254 Keyword::SECOND,
1255 ]
1256 .contains(&kw.keyword) =>
1257 {
1258 Some(self.parse_date_time_field()?)
1259 }
1260 _ => None,
1261 };
1262
1263 let (leading_precision, last_field, fsec_precision) =
1264 if leading_field == Some(DateTimeField::Second) {
1265 let last_field = None;
1271 let (leading_precision, fsec_precision) = self.parse_optional_precision_scale()?;
1272 (leading_precision, last_field, fsec_precision)
1273 } else {
1274 let leading_precision = self.parse_optional_precision()?;
1275 if self.parse_keyword(Keyword::TO) {
1276 let last_field = Some(self.parse_date_time_field()?);
1277 let fsec_precision = if last_field == Some(DateTimeField::Second) {
1278 self.parse_optional_precision()?
1279 } else {
1280 None
1281 };
1282 (leading_precision, last_field, fsec_precision)
1283 } else {
1284 (leading_precision, None, None)
1285 }
1286 };
1287
1288 Ok(Expr::Value(Value::Interval {
1289 value,
1290 leading_field,
1291 leading_precision,
1292 last_field,
1293 fractional_seconds_precision: fsec_precision,
1294 }))
1295 }
1296
1297 pub fn parse_infix(&mut self, expr: Expr, precedence: Precedence) -> ModalResult<Expr> {
1299 let checkpoint = *self;
1300 let tok = self.next_token();
1301 debug!("parsing infix {:?}", tok.token);
1302 let regular_binary_operator = match &tok.token {
1303 Token::Spaceship => Some(BinaryOperator::Spaceship),
1304 Token::DoubleEq => Some(BinaryOperator::Eq),
1305 Token::Eq => Some(BinaryOperator::Eq),
1306 Token::Neq => Some(BinaryOperator::NotEq),
1307 Token::Gt => Some(BinaryOperator::Gt),
1308 Token::GtEq => Some(BinaryOperator::GtEq),
1309 Token::Lt => Some(BinaryOperator::Lt),
1310 Token::LtEq => Some(BinaryOperator::LtEq),
1311 Token::Plus => Some(BinaryOperator::Plus),
1312 Token::Minus => Some(BinaryOperator::Minus),
1313 Token::Mul => Some(BinaryOperator::Multiply),
1314 Token::Mod => Some(BinaryOperator::Modulo),
1315 Token::Concat => Some(BinaryOperator::Concat),
1316 Token::Pipe => Some(BinaryOperator::BitwiseOr),
1317 Token::Caret => Some(BinaryOperator::BitwiseXor),
1318 Token::Prefix => Some(BinaryOperator::Prefix),
1319 Token::Ampersand => Some(BinaryOperator::BitwiseAnd),
1320 Token::Div => Some(BinaryOperator::Divide),
1321 Token::ShiftLeft => Some(BinaryOperator::PGBitwiseShiftLeft),
1322 Token::ShiftRight => Some(BinaryOperator::PGBitwiseShiftRight),
1323 Token::Sharp => Some(BinaryOperator::PGBitwiseXor),
1324 Token::Tilde => Some(BinaryOperator::PGRegexMatch),
1325 Token::TildeAsterisk => Some(BinaryOperator::PGRegexIMatch),
1326 Token::ExclamationMarkTilde => Some(BinaryOperator::PGRegexNotMatch),
1327 Token::ExclamationMarkTildeAsterisk => Some(BinaryOperator::PGRegexNotIMatch),
1328 Token::DoubleTilde => Some(BinaryOperator::PGLikeMatch),
1329 Token::DoubleTildeAsterisk => Some(BinaryOperator::PGILikeMatch),
1330 Token::ExclamationMarkDoubleTilde => Some(BinaryOperator::PGNotLikeMatch),
1331 Token::ExclamationMarkDoubleTildeAsterisk => Some(BinaryOperator::PGNotILikeMatch),
1332 Token::Arrow => Some(BinaryOperator::Arrow),
1333 Token::LongArrow => Some(BinaryOperator::LongArrow),
1334 Token::HashArrow => Some(BinaryOperator::HashArrow),
1335 Token::HashLongArrow => Some(BinaryOperator::HashLongArrow),
1336 Token::HashMinus => Some(BinaryOperator::HashMinus),
1337 Token::AtArrow => Some(BinaryOperator::Contains),
1338 Token::ArrowAt => Some(BinaryOperator::Contained),
1339 Token::QuestionMark => Some(BinaryOperator::Exists),
1340 Token::QuestionMarkPipe => Some(BinaryOperator::ExistsAny),
1341 Token::QuestionMarkAmpersand => Some(BinaryOperator::ExistsAll),
1342 Token::AtQuestionMark => Some(BinaryOperator::PathExists),
1343 Token::AtAt => Some(BinaryOperator::PathMatch),
1344 Token::Word(w) => match w.keyword {
1345 Keyword::AND => Some(BinaryOperator::And),
1346 Keyword::OR => Some(BinaryOperator::Or),
1347 Keyword::XOR => Some(BinaryOperator::Xor),
1348 Keyword::OPERATOR if self.peek_token() == Token::LParen => Some(
1349 BinaryOperator::PGQualified(Box::new(self.parse_qualified_operator()?)),
1350 ),
1351 _ => None,
1352 },
1353 _ => None,
1354 };
1355
1356 if let Some(op) = regular_binary_operator {
1357 Ok(Expr::BinaryOp {
1386 left: Box::new(expr),
1387 op,
1388 right: Box::new(self.parse_subexpr(precedence)?),
1389 })
1390 } else if let Token::Word(w) = &tok.token {
1392 match w.keyword {
1393 Keyword::IS => {
1394 if self.parse_keyword(Keyword::TRUE) {
1395 Ok(Expr::IsTrue(Box::new(expr)))
1396 } else if self.parse_keywords(&[Keyword::NOT, Keyword::TRUE]) {
1397 Ok(Expr::IsNotTrue(Box::new(expr)))
1398 } else if self.parse_keyword(Keyword::FALSE) {
1399 Ok(Expr::IsFalse(Box::new(expr)))
1400 } else if self.parse_keywords(&[Keyword::NOT, Keyword::FALSE]) {
1401 Ok(Expr::IsNotFalse(Box::new(expr)))
1402 } else if self.parse_keyword(Keyword::UNKNOWN) {
1403 Ok(Expr::IsUnknown(Box::new(expr)))
1404 } else if self.parse_keywords(&[Keyword::NOT, Keyword::UNKNOWN]) {
1405 Ok(Expr::IsNotUnknown(Box::new(expr)))
1406 } else if self.parse_keyword(Keyword::NULL) {
1407 Ok(Expr::IsNull(Box::new(expr)))
1408 } else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
1409 Ok(Expr::IsNotNull(Box::new(expr)))
1410 } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::FROM]) {
1411 let expr2 = self.parse_expr()?;
1412 Ok(Expr::IsDistinctFrom(Box::new(expr), Box::new(expr2)))
1413 } else if self.parse_keywords(&[Keyword::NOT, Keyword::DISTINCT, Keyword::FROM])
1414 {
1415 let expr2 = self.parse_expr()?;
1416 Ok(Expr::IsNotDistinctFrom(Box::new(expr), Box::new(expr2)))
1417 } else {
1418 let negated = self.parse_keyword(Keyword::NOT);
1419
1420 if self.parse_keyword(Keyword::JSON) {
1421 self.parse_is_json(expr, negated)
1422 } else {
1423 self.expected(
1424 "[NOT] { TRUE | FALSE | UNKNOWN | NULL | DISTINCT FROM | JSON } after IS",
1425 )
1426 }
1427 }
1428 }
1429 Keyword::AT => {
1430 assert_eq!(precedence, Precedence::At);
1431 let time_zone = Box::new(
1432 preceded(
1433 (Keyword::TIME, Keyword::ZONE),
1434 cut_err(|p: &mut Self| p.parse_subexpr(precedence)),
1435 )
1436 .parse_next(self)?,
1437 );
1438 Ok(Expr::AtTimeZone {
1439 timestamp: Box::new(expr),
1440 time_zone,
1441 })
1442 }
1443 keyword @ (Keyword::ALL | Keyword::ANY | Keyword::SOME) => {
1444 self.expect_token(&Token::LParen)?;
1445 let sub = self.parse_expr()?;
1448 self.expect_token(&Token::RParen)?;
1449
1450 if let Expr::Subquery(_) = &sub {
1452 parser_err!("ANY/SOME/ALL(Subquery) is not implemented");
1453 }
1454
1455 Ok(match keyword {
1456 Keyword::ALL => Expr::AllOp(Box::new(sub)),
1457 Keyword::ANY | Keyword::SOME => Expr::SomeOp(Box::new(sub)),
1459 _ => unreachable!(),
1460 })
1461 }
1462 Keyword::NOT
1463 | Keyword::IN
1464 | Keyword::BETWEEN
1465 | Keyword::LIKE
1466 | Keyword::ILIKE
1467 | Keyword::SIMILAR => {
1468 *self = checkpoint;
1469 let negated = self.parse_keyword(Keyword::NOT);
1470 if self.parse_keyword(Keyword::IN) {
1471 self.parse_in(expr, negated)
1472 } else if self.parse_keyword(Keyword::BETWEEN) {
1473 self.parse_between(expr, negated)
1474 } else if self.parse_keyword(Keyword::LIKE) {
1475 Ok(Expr::Like {
1476 negated,
1477 expr: Box::new(expr),
1478 pattern: Box::new(self.parse_subexpr(Precedence::Like)?),
1479 escape_char: self.parse_escape()?,
1480 })
1481 } else if self.parse_keyword(Keyword::ILIKE) {
1482 Ok(Expr::ILike {
1483 negated,
1484 expr: Box::new(expr),
1485 pattern: Box::new(self.parse_subexpr(Precedence::Like)?),
1486 escape_char: self.parse_escape()?,
1487 })
1488 } else if self.parse_keywords(&[Keyword::SIMILAR, Keyword::TO]) {
1489 Ok(Expr::SimilarTo {
1490 negated,
1491 expr: Box::new(expr),
1492 pattern: Box::new(self.parse_subexpr(Precedence::Like)?),
1493 escape_char: self.parse_escape()?,
1494 })
1495 } else {
1496 self.expected("IN, BETWEEN or SIMILAR TO after NOT")
1497 }
1498 }
1499 _ => parser_err!("No infix parser for token {:?}", tok),
1501 }
1502 } else if Token::DoubleColon == tok {
1503 self.parse_pg_cast(expr)
1504 } else if Token::ExclamationMark == tok {
1505 Ok(Expr::UnaryOp {
1507 op: UnaryOperator::PGPostfixFactorial,
1508 expr: Box::new(expr),
1509 })
1510 } else if Token::LBracket == tok {
1511 self.parse_array_index(expr)
1512 } else {
1513 parser_err!("No infix parser for token {:?}", tok)
1515 }
1516 }
1517
1518 pub fn parse_escape(&mut self) -> ModalResult<Option<EscapeChar>> {
1520 if self.parse_keyword(Keyword::ESCAPE) {
1521 let s = self.parse_literal_string()?;
1522 let mut chs = s.chars();
1523 if let Some(ch) = chs.next() {
1524 if chs.next().is_some() {
1525 parser_err!("Escape string must be empty or one character, found {s:?}")
1526 } else {
1527 Ok(Some(EscapeChar::escape(ch)))
1528 }
1529 } else {
1530 Ok(Some(EscapeChar::empty()))
1531 }
1532 } else {
1533 Ok(None)
1534 }
1535 }
1536
1537 pub fn parse_array_index(&mut self, expr: Expr) -> ModalResult<Expr> {
1540 let new_expr = match self.peek_token().token {
1541 Token::Colon => {
1542 assert!(self.consume_token(&Token::Colon));
1544 let end = match self.peek_token().token {
1545 Token::RBracket => None,
1546 _ => {
1547 let end_index = Box::new(self.parse_expr()?);
1548 Some(end_index)
1549 }
1550 };
1551 Expr::ArrayRangeIndex {
1552 obj: Box::new(expr),
1553 start: None,
1554 end,
1555 }
1556 }
1557 _ => {
1558 let index = Box::new(self.parse_expr()?);
1560 match self.peek_token().token {
1561 Token::Colon => {
1562 assert!(self.consume_token(&Token::Colon));
1564 match self.peek_token().token {
1565 Token::RBracket => {
1566 Expr::ArrayRangeIndex {
1568 obj: Box::new(expr),
1569 start: Some(index),
1570 end: None,
1571 }
1572 }
1573 _ => {
1574 let end = Some(Box::new(self.parse_expr()?));
1576 Expr::ArrayRangeIndex {
1577 obj: Box::new(expr),
1578 start: Some(index),
1579 end,
1580 }
1581 }
1582 }
1583 }
1584 _ => {
1585 Expr::Index {
1587 obj: Box::new(expr),
1588 index,
1589 }
1590 }
1591 }
1592 }
1593 };
1594 self.expect_token(&Token::RBracket)?;
1595 if self.consume_token(&Token::LBracket) {
1597 self.parse_array_index(new_expr)
1598 } else {
1599 Ok(new_expr)
1600 }
1601 }
1602
1603 pub fn parse_is_json(&mut self, expr: Expr, negated: bool) -> ModalResult<Expr> {
1605 let item_type = match self.peek_token().token {
1606 Token::Word(w) => match w.keyword {
1607 Keyword::VALUE => Some(JsonPredicateType::Value),
1608 Keyword::ARRAY => Some(JsonPredicateType::Array),
1609 Keyword::OBJECT => Some(JsonPredicateType::Object),
1610 Keyword::SCALAR => Some(JsonPredicateType::Scalar),
1611 _ => None,
1612 },
1613 _ => None,
1614 };
1615 if item_type.is_some() {
1616 self.next_token();
1617 }
1618 let item_type = item_type.unwrap_or_default();
1619
1620 let unique_keys = self.parse_one_of_keywords(&[Keyword::WITH, Keyword::WITHOUT]);
1621 if unique_keys.is_some() {
1622 self.expect_keyword(Keyword::UNIQUE)?;
1623 _ = self.parse_keyword(Keyword::KEYS);
1624 }
1625 let unique_keys = unique_keys.is_some_and(|w| w == Keyword::WITH);
1626
1627 Ok(Expr::IsJson {
1628 expr: Box::new(expr),
1629 negated,
1630 item_type,
1631 unique_keys,
1632 })
1633 }
1634
1635 pub fn parse_in(&mut self, expr: Expr, negated: bool) -> ModalResult<Expr> {
1637 self.expect_token(&Token::LParen)?;
1638 let in_op = if matches!(self.peek_token().token, Token::Word(w) if w.keyword == Keyword::SELECT || w.keyword == Keyword::WITH)
1639 {
1640 Expr::InSubquery {
1641 expr: Box::new(expr),
1642 subquery: Box::new(self.parse_query()?),
1643 negated,
1644 }
1645 } else {
1646 Expr::InList {
1647 expr: Box::new(expr),
1648 list: self.parse_comma_separated(Parser::parse_expr)?,
1649 negated,
1650 }
1651 };
1652 self.expect_token(&Token::RParen)?;
1653 Ok(in_op)
1654 }
1655
1656 pub fn parse_between(&mut self, expr: Expr, negated: bool) -> ModalResult<Expr> {
1658 let low = self.parse_subexpr(Precedence::Between)?;
1661 self.expect_keyword(Keyword::AND)?;
1662 let high = self.parse_subexpr(Precedence::Between)?;
1663 Ok(Expr::Between {
1664 expr: Box::new(expr),
1665 negated,
1666 low: Box::new(low),
1667 high: Box::new(high),
1668 })
1669 }
1670
1671 pub fn parse_pg_cast(&mut self, expr: Expr) -> ModalResult<Expr> {
1673 Ok(Expr::Cast {
1674 expr: Box::new(expr),
1675 data_type: self.parse_data_type()?,
1676 })
1677 }
1678
1679 pub fn get_next_precedence(&self) -> ModalResult<Precedence> {
1681 use Precedence as P;
1682
1683 let token = self.peek_token();
1684 debug!("get_next_precedence() {:?}", token);
1685 match token.token {
1686 Token::Word(w) if w.keyword == Keyword::OR => Ok(P::LogicalOr),
1687 Token::Word(w) if w.keyword == Keyword::XOR => Ok(P::LogicalXor),
1688 Token::Word(w) if w.keyword == Keyword::AND => Ok(P::LogicalAnd),
1689 Token::Word(w) if w.keyword == Keyword::AT => {
1690 match (self.peek_nth_token(1).token, self.peek_nth_token(2).token) {
1691 (Token::Word(w), Token::Word(w2))
1692 if w.keyword == Keyword::TIME && w2.keyword == Keyword::ZONE =>
1693 {
1694 Ok(P::At)
1695 }
1696 _ => Ok(P::Zero),
1697 }
1698 }
1699
1700 Token::Word(w) if w.keyword == Keyword::NOT => match self.peek_nth_token(1).token {
1701 Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(P::Between),
1707 Token::Word(w) if w.keyword == Keyword::IN => Ok(P::Between),
1708 Token::Word(w) if w.keyword == Keyword::LIKE => Ok(P::Like),
1709 Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(P::Like),
1710 Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(P::Like),
1711 _ => Ok(P::Zero),
1712 },
1713
1714 Token::Word(w) if w.keyword == Keyword::IS => Ok(P::Is),
1715 Token::Word(w) if w.keyword == Keyword::ISNULL => Ok(P::Is),
1716 Token::Word(w) if w.keyword == Keyword::NOTNULL => Ok(P::Is),
1717 Token::Eq
1718 | Token::Lt
1719 | Token::LtEq
1720 | Token::Neq
1721 | Token::Gt
1722 | Token::GtEq
1723 | Token::DoubleEq
1724 | Token::Spaceship => Ok(P::Cmp),
1725 Token::Word(w) if w.keyword == Keyword::IN => Ok(P::Between),
1726 Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(P::Between),
1727 Token::Word(w) if w.keyword == Keyword::LIKE => Ok(P::Like),
1728 Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(P::Like),
1729 Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(P::Like),
1730 Token::Word(w) if w.keyword == Keyword::ALL => Ok(P::Other),
1731 Token::Word(w) if w.keyword == Keyword::ANY => Ok(P::Other),
1732 Token::Word(w) if w.keyword == Keyword::SOME => Ok(P::Other),
1733 Token::Tilde
1734 | Token::TildeAsterisk
1735 | Token::ExclamationMarkTilde
1736 | Token::ExclamationMarkTildeAsterisk
1737 | Token::DoubleTilde
1738 | Token::DoubleTildeAsterisk
1739 | Token::ExclamationMarkDoubleTilde
1740 | Token::ExclamationMarkDoubleTildeAsterisk
1741 | Token::Concat
1742 | Token::Prefix
1743 | Token::Arrow
1744 | Token::LongArrow
1745 | Token::HashArrow
1746 | Token::HashLongArrow
1747 | Token::HashMinus
1748 | Token::AtArrow
1749 | Token::ArrowAt
1750 | Token::QuestionMark
1751 | Token::QuestionMarkPipe
1752 | Token::QuestionMarkAmpersand
1753 | Token::AtQuestionMark
1754 | Token::AtAt => Ok(P::Other),
1755 Token::Word(w)
1756 if w.keyword == Keyword::OPERATOR && self.peek_nth_token(1) == Token::LParen =>
1757 {
1758 Ok(P::Other)
1759 }
1760 Token::Pipe => Ok(P::Other),
1764 Token::Sharp => Ok(P::Other),
1765 Token::Ampersand => Ok(P::Other),
1766 Token::ShiftRight | Token::ShiftLeft => Ok(P::Other),
1767 Token::Plus | Token::Minus => Ok(P::PlusMinus),
1768 Token::Mul | Token::Div | Token::Mod => Ok(P::MulDiv),
1769 Token::Caret => Ok(P::Exp),
1770 Token::ExclamationMark => Ok(P::PostfixFactorial),
1771 Token::LBracket => Ok(P::Array),
1772 Token::DoubleColon => Ok(P::DoubleColon),
1773 _ => Ok(P::Zero),
1774 }
1775 }
1776
1777 pub fn peek_token(&self) -> TokenWithLocation {
1780 self.peek_nth_token(0)
1781 }
1782
1783 pub fn peek_nth_token(&self, mut n: usize) -> TokenWithLocation {
1785 let mut index = 0;
1786 loop {
1787 let token = self.0.get(index);
1788 index += 1;
1789 match token.map(|x| &x.token) {
1790 Some(Token::Whitespace(_)) => continue,
1791 _ => {
1792 if n == 0 {
1793 return token.cloned().unwrap_or(TokenWithLocation::eof());
1794 }
1795 n -= 1;
1796 }
1797 }
1798 }
1799 }
1800
1801 pub fn next_token(&mut self) -> TokenWithLocation {
1805 loop {
1806 let Some(token) = self.0.first() else {
1807 return TokenWithLocation::eof();
1808 };
1809 self.0 = &self.0[1..];
1810 match token.token {
1811 Token::Whitespace(_) => continue,
1812 _ => return token.clone(),
1813 }
1814 }
1815 }
1816
1817 pub fn next_token_no_skip(&mut self) -> Option<&TokenWithLocation> {
1819 if self.0.is_empty() {
1820 None
1821 } else {
1822 let (first, rest) = self.0.split_at(1);
1823 self.0 = rest;
1824 Some(&first[0])
1825 }
1826 }
1827
1828 pub fn expected<T>(&self, expected: &str) -> ModalResult<T> {
1830 parser_err!("expected {}, found: {}", expected, self.peek_token().token)
1831 }
1832
1833 pub fn expected_at<T>(&mut self, checkpoint: Self, expected: &str) -> ModalResult<T> {
1835 *self = checkpoint;
1836 self.expected(expected)
1837 }
1838
1839 pub fn parse_word(&mut self, expected: &str) -> bool {
1842 match self.peek_token().token {
1843 Token::Word(w) if w.value.to_uppercase() == expected => {
1844 self.next_token();
1845 true
1846 }
1847 _ => false,
1848 }
1849 }
1850
1851 #[must_use]
1853 pub fn parse_keyword(&mut self, expected: Keyword) -> bool {
1854 match self.peek_token().token {
1855 Token::Word(w) if expected == w.keyword => {
1856 self.next_token();
1857 true
1858 }
1859 _ => false,
1860 }
1861 }
1862
1863 #[must_use]
1865 pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool {
1866 let checkpoint = *self;
1867 for &keyword in keywords {
1868 if !self.parse_keyword(keyword) {
1869 *self = checkpoint;
1872 return false;
1873 }
1874 }
1875 true
1876 }
1877
1878 #[must_use]
1880 pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword> {
1881 match self.peek_token().token {
1882 Token::Word(w) => {
1883 keywords
1884 .iter()
1885 .find(|keyword| **keyword == w.keyword)
1886 .map(|keyword| {
1887 self.next_token();
1888 *keyword
1889 })
1890 }
1891 _ => None,
1892 }
1893 }
1894
1895 pub fn peek_nth_any_of_keywords(&mut self, n: usize, keywords: &[Keyword]) -> bool {
1896 match self.peek_nth_token(n).token {
1897 Token::Word(w) => keywords.contains(&w.keyword),
1898 _ => false,
1899 }
1900 }
1901
1902 pub fn expect_one_of_keywords(&mut self, keywords: &[Keyword]) -> ModalResult<Keyword> {
1904 if let Some(keyword) = self.parse_one_of_keywords(keywords) {
1905 Ok(keyword)
1906 } else {
1907 let keywords: Vec<String> = keywords.iter().map(|x| format!("{:?}", x)).collect();
1908 self.expected(&format!("one of {}", keywords.join(" or ")))
1909 }
1910 }
1911
1912 pub fn expect_keyword(&mut self, expected: Keyword) -> ModalResult<()> {
1914 if self.parse_keyword(expected) {
1915 Ok(())
1916 } else {
1917 self.expected(format!("{:?}", &expected).as_str())
1918 }
1919 }
1920
1921 pub fn expect_keywords(&mut self, expected: &[Keyword]) -> ModalResult<()> {
1924 for &kw in expected {
1925 self.expect_keyword(kw)?;
1926 }
1927 Ok(())
1928 }
1929
1930 #[must_use]
1932 pub fn consume_token(&mut self, expected: &Token) -> bool {
1933 if self.peek_token() == *expected {
1934 self.next_token();
1935 true
1936 } else {
1937 false
1938 }
1939 }
1940
1941 pub fn expect_token(&mut self, expected: &Token) -> ModalResult<()> {
1943 if self.consume_token(expected) {
1944 Ok(())
1945 } else {
1946 self.expected(&expected.to_string())
1947 }
1948 }
1949
1950 pub fn parse_comma_separated<T, F>(&mut self, mut f: F) -> ModalResult<Vec<T>>
1952 where
1953 F: FnMut(&mut Self) -> ModalResult<T>,
1954 {
1955 let mut values = vec![];
1956 loop {
1957 values.push(f(self)?);
1958 if !self.consume_token(&Token::Comma) {
1959 break;
1960 }
1961 }
1962 Ok(values)
1963 }
1964
1965 #[must_use]
1968 fn maybe_parse<T, F>(&mut self, mut f: F) -> Option<T>
1969 where
1970 F: FnMut(&mut Self) -> ModalResult<T>,
1971 {
1972 let checkpoint = *self;
1973 match f(self) {
1974 Ok(t) => Some(t),
1975 _ => {
1976 *self = checkpoint;
1977 None
1978 }
1979 }
1980 }
1981
1982 pub fn parse_all_or_distinct(&mut self) -> ModalResult<bool> {
1985 let all = self.parse_keyword(Keyword::ALL);
1986 let distinct = self.parse_keyword(Keyword::DISTINCT);
1987 if all && distinct {
1988 parser_err!("Cannot specify both ALL and DISTINCT")
1989 } else {
1990 Ok(distinct)
1991 }
1992 }
1993
1994 pub fn parse_all_or_distinct_on(&mut self) -> ModalResult<Distinct> {
1996 if self.parse_keywords(&[Keyword::DISTINCT, Keyword::ON]) {
1997 self.expect_token(&Token::LParen)?;
1998 let exprs = self.parse_comma_separated(Parser::parse_expr)?;
1999 self.expect_token(&Token::RParen)?;
2000 return Ok(Distinct::DistinctOn(exprs));
2001 } else if self.parse_keyword(Keyword::DISTINCT) {
2002 return Ok(Distinct::Distinct);
2003 };
2004 _ = self.parse_keyword(Keyword::ALL);
2005 Ok(Distinct::All)
2006 }
2007
2008 pub fn parse_create(&mut self) -> ModalResult<Statement> {
2010 let or_replace = self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]);
2011 let temporary = self
2012 .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
2013 .is_some();
2014 if self.parse_keyword(Keyword::TABLE) {
2015 self.parse_create_table(or_replace, temporary)
2016 } else if self.parse_keyword(Keyword::VIEW) {
2017 self.parse_create_view(false, or_replace)
2018 } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
2019 self.parse_create_view(true, or_replace)
2020 } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::SOURCE]) {
2021 parser_err!("CREATE MATERIALIZED SOURCE has been deprecated, use CREATE TABLE instead")
2022 } else if self.parse_keyword(Keyword::SOURCE) {
2023 self.parse_create_source(or_replace, temporary)
2024 } else if self.parse_keyword(Keyword::SINK) {
2025 self.parse_create_sink(or_replace)
2026 } else if self.parse_keyword(Keyword::SUBSCRIPTION) {
2027 self.parse_create_subscription(or_replace)
2028 } else if self.parse_keyword(Keyword::CONNECTION) {
2029 self.parse_create_connection()
2030 } else if self.parse_keyword(Keyword::FUNCTION) {
2031 self.parse_create_function(or_replace, temporary)
2032 } else if self.parse_keyword(Keyword::AGGREGATE) {
2033 self.parse_create_aggregate(or_replace)
2034 } else if or_replace {
2035 self.expected(
2036 "[EXTERNAL] TABLE or [MATERIALIZED] VIEW or [MATERIALIZED] SOURCE or SINK or FUNCTION after CREATE OR REPLACE",
2037 )
2038 } else if self.parse_keyword(Keyword::INDEX) {
2039 self.parse_create_index(false)
2040 } else if self.parse_keywords(&[Keyword::UNIQUE, Keyword::INDEX]) {
2041 self.parse_create_index(true)
2042 } else if self.parse_keyword(Keyword::SCHEMA) {
2043 self.parse_create_schema()
2044 } else if self.parse_keyword(Keyword::DATABASE) {
2045 self.parse_create_database()
2046 } else if self.parse_keyword(Keyword::USER) {
2047 self.parse_create_user()
2048 } else if self.parse_keyword(Keyword::SECRET) {
2049 self.parse_create_secret()
2050 } else {
2051 self.expected("an object type after CREATE")
2052 }
2053 }
2054
2055 pub fn parse_create_schema(&mut self) -> ModalResult<Statement> {
2056 let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2057 let (schema_name, owner) = if self.parse_keyword(Keyword::AUTHORIZATION) {
2058 let owner = self.parse_object_name()?;
2059 (owner.clone(), Some(owner))
2060 } else {
2061 let schema_name = self.parse_object_name()?;
2062 let owner = if self.parse_keyword(Keyword::AUTHORIZATION) {
2063 Some(self.parse_object_name()?)
2064 } else {
2065 None
2066 };
2067 (schema_name, owner)
2068 };
2069 Ok(Statement::CreateSchema {
2070 schema_name,
2071 if_not_exists,
2072 owner,
2073 })
2074 }
2075
2076 pub fn parse_create_database(&mut self) -> ModalResult<Statement> {
2077 let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2078 let db_name = self.parse_object_name()?;
2079 let _ = self.parse_keyword(Keyword::WITH);
2080
2081 let mut owner = None;
2082 let mut resource_group = None;
2083
2084 while let Some(keyword) =
2085 self.parse_one_of_keywords(&[Keyword::OWNER, Keyword::RESOURCE_GROUP])
2086 {
2087 match keyword {
2088 Keyword::OWNER => {
2089 if owner.is_some() {
2090 parser_err!("duplicate OWNER clause in CREATE DATABASE");
2091 }
2092
2093 let _ = self.consume_token(&Token::Eq);
2094 owner = Some(self.parse_object_name()?);
2095 }
2096 Keyword::RESOURCE_GROUP => {
2097 if resource_group.is_some() {
2098 parser_err!("duplicate RESOURCE_GROUP clause in CREATE DATABASE");
2099 }
2100
2101 let _ = self.consume_token(&Token::Eq);
2102 resource_group = Some(self.parse_set_variable()?);
2103 }
2104 _ => unreachable!(),
2105 }
2106 }
2107
2108 Ok(Statement::CreateDatabase {
2109 db_name,
2110 if_not_exists,
2111 owner,
2112 resource_group,
2113 })
2114 }
2115
2116 pub fn parse_create_view(
2117 &mut self,
2118 materialized: bool,
2119 or_replace: bool,
2120 ) -> ModalResult<Statement> {
2121 let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2122 let name = self.parse_object_name()?;
2125 let columns = self.parse_parenthesized_column_list(Optional)?;
2126 let with_options = self.parse_options_with_preceding_keyword(Keyword::WITH)?;
2127 self.expect_keyword(Keyword::AS)?;
2128 let query = Box::new(self.parse_query()?);
2129 let emit_mode = if materialized {
2130 self.parse_emit_mode()?
2131 } else {
2132 None
2133 };
2134 Ok(Statement::CreateView {
2136 if_not_exists,
2137 name,
2138 columns,
2139 query,
2140 materialized,
2141 or_replace,
2142 with_options,
2143 emit_mode,
2144 })
2145 }
2146
2147 pub fn parse_create_source(
2156 &mut self,
2157 _or_replace: bool,
2158 temporary: bool,
2159 ) -> ModalResult<Statement> {
2160 impl_parse_to!(if_not_exists => [Keyword::IF, Keyword::NOT, Keyword::EXISTS], self);
2161 impl_parse_to!(source_name: ObjectName, self);
2162
2163 let (columns, constraints, source_watermarks, wildcard_idx) =
2165 self.parse_columns_with_watermark()?;
2166 let include_options = self.parse_include_options()?;
2167
2168 let with_options = self.parse_with_properties()?;
2169 let option = with_options
2170 .iter()
2171 .find(|&opt| opt.name.real_value() == UPSTREAM_SOURCE_KEY);
2172 let connector: String = option.map(|opt| opt.value.to_string()).unwrap_or_default();
2173 let cdc_source_job = connector.contains("-cdc");
2174 if cdc_source_job && (!columns.is_empty() || !constraints.is_empty()) {
2175 parser_err!("CDC source cannot define columns and constraints");
2176 }
2177
2178 let format_encode = self.parse_format_encode_with_connector(&connector, cdc_source_job)?;
2181
2182 let stmt = CreateSourceStatement {
2183 temporary,
2184 if_not_exists,
2185 columns,
2186 wildcard_idx,
2187 constraints,
2188 source_name,
2189 with_properties: WithProperties(with_options),
2190 format_encode,
2191 source_watermarks,
2192 include_column_options: include_options,
2193 };
2194
2195 Ok(Statement::CreateSource { stmt })
2196 }
2197
2198 pub fn parse_create_sink(&mut self, _or_replace: bool) -> ModalResult<Statement> {
2206 Ok(Statement::CreateSink {
2207 stmt: CreateSinkStatement::parse_to(self)?,
2208 })
2209 }
2210
2211 pub fn parse_create_subscription(&mut self, _or_replace: bool) -> ModalResult<Statement> {
2219 Ok(Statement::CreateSubscription {
2220 stmt: CreateSubscriptionStatement::parse_to(self)?,
2221 })
2222 }
2223
2224 pub fn parse_create_connection(&mut self) -> ModalResult<Statement> {
2230 Ok(Statement::CreateConnection {
2231 stmt: CreateConnectionStatement::parse_to(self)?,
2232 })
2233 }
2234
2235 pub fn parse_create_function(
2236 &mut self,
2237 or_replace: bool,
2238 temporary: bool,
2239 ) -> ModalResult<Statement> {
2240 impl_parse_to!(if_not_exists => [Keyword::IF, Keyword::NOT, Keyword::EXISTS], self);
2241
2242 let FunctionDesc { name, args } = self.parse_function_desc()?;
2243
2244 let return_type = if self.parse_keyword(Keyword::RETURNS) {
2245 if self.parse_keyword(Keyword::TABLE) {
2246 self.expect_token(&Token::LParen)?;
2247 let mut values = vec![];
2248 loop {
2249 values.push(self.parse_table_column_def()?);
2250 let comma = self.consume_token(&Token::Comma);
2251 if self.consume_token(&Token::RParen) {
2252 break;
2254 } else if !comma {
2255 return self.expected("',' or ')'");
2256 }
2257 }
2258 Some(CreateFunctionReturns::Table(values))
2259 } else {
2260 Some(CreateFunctionReturns::Value(self.parse_data_type()?))
2261 }
2262 } else {
2263 None
2264 };
2265
2266 let params = self.parse_create_function_body()?;
2267 let with_options = self.parse_options_with_preceding_keyword(Keyword::WITH)?;
2268 let with_options = with_options.try_into()?;
2269 Ok(Statement::CreateFunction {
2270 or_replace,
2271 temporary,
2272 if_not_exists,
2273 name,
2274 args,
2275 returns: return_type,
2276 params,
2277 with_options,
2278 })
2279 }
2280
2281 fn parse_create_aggregate(&mut self, or_replace: bool) -> ModalResult<Statement> {
2282 impl_parse_to!(if_not_exists => [Keyword::IF, Keyword::NOT, Keyword::EXISTS], self);
2283
2284 let name = self.parse_object_name()?;
2285 self.expect_token(&Token::LParen)?;
2286 let args = self.parse_comma_separated(Parser::parse_function_arg)?;
2287 self.expect_token(&Token::RParen)?;
2288
2289 self.expect_keyword(Keyword::RETURNS)?;
2290 let returns = self.parse_data_type()?;
2291
2292 let append_only = self.parse_keywords(&[Keyword::APPEND, Keyword::ONLY]);
2293 let params = self.parse_create_function_body()?;
2294
2295 Ok(Statement::CreateAggregate {
2296 or_replace,
2297 if_not_exists,
2298 name,
2299 args,
2300 returns,
2301 append_only,
2302 params,
2303 })
2304 }
2305
2306 pub fn parse_declare(&mut self) -> ModalResult<Statement> {
2307 Ok(Statement::DeclareCursor {
2308 stmt: DeclareCursorStatement::parse_to(self)?,
2309 })
2310 }
2311
2312 pub fn parse_fetch_cursor(&mut self) -> ModalResult<Statement> {
2313 Ok(Statement::FetchCursor {
2314 stmt: FetchCursorStatement::parse_to(self)?,
2315 })
2316 }
2317
2318 pub fn parse_close_cursor(&mut self) -> ModalResult<Statement> {
2319 Ok(Statement::CloseCursor {
2320 stmt: CloseCursorStatement::parse_to(self)?,
2321 })
2322 }
2323
2324 fn parse_table_column_def(&mut self) -> ModalResult<TableColumnDef> {
2325 Ok(TableColumnDef {
2326 name: self.parse_identifier_non_reserved()?,
2327 data_type: self.parse_data_type()?,
2328 })
2329 }
2330
2331 fn parse_function_arg(&mut self) -> ModalResult<OperateFunctionArg> {
2332 let mode = if self.parse_keyword(Keyword::IN) {
2333 Some(ArgMode::In)
2334 } else if self.parse_keyword(Keyword::OUT) {
2335 Some(ArgMode::Out)
2336 } else if self.parse_keyword(Keyword::INOUT) {
2337 Some(ArgMode::InOut)
2338 } else {
2339 None
2340 };
2341
2342 let mut name = None;
2344 let mut data_type = self.parse_data_type()?;
2345 if let DataType::Custom(n) = &data_type
2346 && !matches!(self.peek_token().token, Token::Comma | Token::RParen)
2347 {
2348 name = Some(n.0[0].clone());
2350 data_type = self.parse_data_type()?;
2351 }
2352
2353 let default_expr = if self.parse_keyword(Keyword::DEFAULT) || self.consume_token(&Token::Eq)
2354 {
2355 Some(self.parse_expr()?)
2356 } else {
2357 None
2358 };
2359 Ok(OperateFunctionArg {
2360 mode,
2361 name,
2362 data_type,
2363 default_expr,
2364 })
2365 }
2366
2367 fn parse_create_function_body(&mut self) -> ModalResult<CreateFunctionBody> {
2368 let mut body = CreateFunctionBody::default();
2369 loop {
2370 fn ensure_not_set<T>(field: &Option<T>, name: &str) -> ModalResult<()> {
2371 if field.is_some() {
2372 parser_err!("{name} specified more than once");
2373 }
2374 Ok(())
2375 }
2376 if self.parse_keyword(Keyword::AS) {
2377 ensure_not_set(&body.as_, "AS")?;
2378 body.as_ = Some(self.parse_function_definition()?);
2379 } else if self.parse_keyword(Keyword::LANGUAGE) {
2380 ensure_not_set(&body.language, "LANGUAGE")?;
2381 body.language = Some(self.parse_identifier()?);
2382 } else if self.parse_keyword(Keyword::RUNTIME) {
2383 ensure_not_set(&body.runtime, "RUNTIME")?;
2384 body.runtime = Some(self.parse_identifier()?);
2385 } else if self.parse_keyword(Keyword::IMMUTABLE) {
2386 ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
2387 body.behavior = Some(FunctionBehavior::Immutable);
2388 } else if self.parse_keyword(Keyword::STABLE) {
2389 ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
2390 body.behavior = Some(FunctionBehavior::Stable);
2391 } else if self.parse_keyword(Keyword::VOLATILE) {
2392 ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
2393 body.behavior = Some(FunctionBehavior::Volatile);
2394 } else if self.parse_keyword(Keyword::RETURN) {
2395 ensure_not_set(&body.return_, "RETURN")?;
2396 body.return_ = Some(self.parse_expr()?);
2397 } else if self.parse_keyword(Keyword::USING) {
2398 ensure_not_set(&body.using, "USING")?;
2399 body.using = Some(self.parse_create_function_using()?);
2400 } else {
2401 return Ok(body);
2402 }
2403 }
2404 }
2405
2406 fn parse_create_function_using(&mut self) -> ModalResult<CreateFunctionUsing> {
2407 let keyword = self.expect_one_of_keywords(&[Keyword::LINK, Keyword::BASE64])?;
2408
2409 match keyword {
2410 Keyword::LINK => {
2411 let uri = self.parse_literal_string()?;
2412 Ok(CreateFunctionUsing::Link(uri))
2413 }
2414 Keyword::BASE64 => {
2415 let base64 = self.parse_literal_string()?;
2416 Ok(CreateFunctionUsing::Base64(base64))
2417 }
2418 _ => unreachable!("{}", keyword),
2419 }
2420 }
2421
2422 fn parse_create_user(&mut self) -> ModalResult<Statement> {
2430 Ok(Statement::CreateUser(CreateUserStatement::parse_to(self)?))
2431 }
2432
2433 fn parse_create_secret(&mut self) -> ModalResult<Statement> {
2434 Ok(Statement::CreateSecret {
2435 stmt: CreateSecretStatement::parse_to(self)?,
2436 })
2437 }
2438
2439 pub fn parse_with_properties(&mut self) -> ModalResult<Vec<SqlOption>> {
2440 Ok(self
2441 .parse_options_with_preceding_keyword(Keyword::WITH)?
2442 .to_vec())
2443 }
2444
2445 pub fn parse_discard(&mut self) -> ModalResult<Statement> {
2446 self.expect_keyword(Keyword::ALL)?;
2447 Ok(Statement::Discard(DiscardType::All))
2448 }
2449
2450 pub fn parse_drop(&mut self) -> ModalResult<Statement> {
2451 if self.parse_keyword(Keyword::FUNCTION) {
2452 return self.parse_drop_function();
2453 } else if self.parse_keyword(Keyword::AGGREGATE) {
2454 return self.parse_drop_aggregate();
2455 }
2456 Ok(Statement::Drop(DropStatement::parse_to(self)?))
2457 }
2458
2459 fn parse_drop_function(&mut self) -> ModalResult<Statement> {
2464 let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
2465 let func_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
2466 let option = match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
2467 Some(Keyword::CASCADE) => Some(ReferentialAction::Cascade),
2468 Some(Keyword::RESTRICT) => Some(ReferentialAction::Restrict),
2469 _ => None,
2470 };
2471 Ok(Statement::DropFunction {
2472 if_exists,
2473 func_desc,
2474 option,
2475 })
2476 }
2477
2478 fn parse_drop_aggregate(&mut self) -> ModalResult<Statement> {
2483 let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
2484 let func_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
2485 let option = match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
2486 Some(Keyword::CASCADE) => Some(ReferentialAction::Cascade),
2487 Some(Keyword::RESTRICT) => Some(ReferentialAction::Restrict),
2488 _ => None,
2489 };
2490 Ok(Statement::DropAggregate {
2491 if_exists,
2492 func_desc,
2493 option,
2494 })
2495 }
2496
2497 fn parse_function_desc(&mut self) -> ModalResult<FunctionDesc> {
2498 let name = self.parse_object_name()?;
2499
2500 let args = if self.consume_token(&Token::LParen) {
2501 if self.consume_token(&Token::RParen) {
2502 Some(vec![])
2503 } else {
2504 let args = self.parse_comma_separated(Parser::parse_function_arg)?;
2505 self.expect_token(&Token::RParen)?;
2506 Some(args)
2507 }
2508 } else {
2509 None
2510 };
2511
2512 Ok(FunctionDesc { name, args })
2513 }
2514
2515 pub fn parse_create_index(&mut self, unique: bool) -> ModalResult<Statement> {
2516 let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2517 let index_name = self.parse_object_name()?;
2518 self.expect_keyword(Keyword::ON)?;
2519 let table_name = self.parse_object_name()?;
2520 self.expect_token(&Token::LParen)?;
2521 let columns = self.parse_comma_separated(Parser::parse_order_by_expr)?;
2522 self.expect_token(&Token::RParen)?;
2523 let mut include = vec![];
2524 if self.parse_keyword(Keyword::INCLUDE) {
2525 self.expect_token(&Token::LParen)?;
2526 include = self.parse_comma_separated(Parser::parse_identifier_non_reserved)?;
2527 self.expect_token(&Token::RParen)?;
2528 }
2529 let mut distributed_by = vec![];
2530 if self.parse_keywords(&[Keyword::DISTRIBUTED, Keyword::BY]) {
2531 self.expect_token(&Token::LParen)?;
2532 distributed_by = self.parse_comma_separated(Parser::parse_expr)?;
2533 self.expect_token(&Token::RParen)?;
2534 }
2535 Ok(Statement::CreateIndex {
2536 name: index_name,
2537 table_name,
2538 columns,
2539 include,
2540 distributed_by,
2541 unique,
2542 if_not_exists,
2543 })
2544 }
2545
2546 pub fn parse_with_version_column(&mut self) -> ModalResult<Option<Ident>> {
2547 if self.parse_keywords(&[Keyword::WITH, Keyword::VERSION, Keyword::COLUMN]) {
2548 self.expect_token(&Token::LParen)?;
2549 let name = self.parse_identifier_non_reserved()?;
2550 self.expect_token(&Token::RParen)?;
2551 Ok(Some(name))
2552 } else {
2553 Ok(None)
2554 }
2555 }
2556
2557 pub fn parse_on_conflict(&mut self) -> ModalResult<Option<OnConflict>> {
2558 if self.parse_keywords(&[Keyword::ON, Keyword::CONFLICT]) {
2559 self.parse_handle_conflict_behavior()
2560 } else {
2561 Ok(None)
2562 }
2563 }
2564
2565 pub fn parse_create_table(
2566 &mut self,
2567 or_replace: bool,
2568 temporary: bool,
2569 ) -> ModalResult<Statement> {
2570 let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2571 let table_name = self.parse_object_name()?;
2572 let (columns, constraints, source_watermarks, wildcard_idx) =
2574 self.parse_columns_with_watermark()?;
2575
2576 let append_only = if self.parse_keyword(Keyword::APPEND) {
2577 self.expect_keyword(Keyword::ONLY)?;
2578 true
2579 } else {
2580 false
2581 };
2582
2583 let on_conflict = self.parse_on_conflict()?;
2584
2585 let with_version_column = self.parse_with_version_column()?;
2586 let include_options = self.parse_include_options()?;
2587
2588 let with_options = self.parse_with_properties()?;
2590
2591 let option = with_options
2592 .iter()
2593 .find(|&opt| opt.name.real_value() == UPSTREAM_SOURCE_KEY);
2594 let connector = option.map(|opt| opt.value.to_string());
2595 let contain_webhook =
2596 connector.is_some() && connector.as_ref().unwrap().contains(WEBHOOK_CONNECTOR);
2597
2598 let format_encode = if let Some(connector) = connector
2600 && !contain_webhook
2601 {
2602 Some(self.parse_format_encode_with_connector(&connector, false)?)
2603 } else {
2604 None };
2606 let query = if self.parse_keyword(Keyword::AS) {
2608 if !source_watermarks.is_empty() {
2609 parser_err!("Watermarks can't be defined on table created by CREATE TABLE AS");
2610 }
2611 Some(Box::new(self.parse_query()?))
2612 } else {
2613 None
2614 };
2615
2616 let cdc_table_info = if self.parse_keyword(Keyword::FROM) {
2617 let source_name = self.parse_object_name()?;
2618 self.expect_keyword(Keyword::TABLE)?;
2619 let external_table_name = self.parse_literal_string()?;
2620 Some(CdcTableInfo {
2621 source_name,
2622 external_table_name,
2623 })
2624 } else {
2625 None
2626 };
2627
2628 let webhook_info = if self.parse_keyword(Keyword::VALIDATE) {
2629 if !contain_webhook {
2630 parser_err!("VALIDATE is only supported for tables created with webhook source");
2631 }
2632
2633 let wait_for_persistence = with_options
2634 .iter()
2635 .find(|&opt| opt.name.real_value() == WEBHOOK_WAIT_FOR_PERSISTENCE)
2636 .map(|opt| opt.value.to_string().eq_ignore_ascii_case("true"))
2637 .unwrap_or(true);
2638 let secret_ref = if self.parse_keyword(Keyword::SECRET) {
2639 let secret_ref = self.parse_secret_ref()?;
2640 if secret_ref.ref_as == SecretRefAsType::File {
2641 parser_err!("Secret for SECURE_COMPARE() does not support AS FILE");
2642 };
2643 Some(secret_ref)
2644 } else {
2645 None
2646 };
2647
2648 self.expect_keyword(Keyword::AS)?;
2649 let signature_expr = self.parse_function()?;
2650
2651 Some(WebhookSourceInfo {
2652 secret_ref,
2653 signature_expr,
2654 wait_for_persistence,
2655 })
2656 } else {
2657 None
2658 };
2659
2660 let engine = if self.parse_keyword(Keyword::ENGINE) {
2661 self.expect_token(&Token::Eq)?;
2662 let engine_name = self.parse_object_name()?;
2663 if "iceberg".eq_ignore_ascii_case(&engine_name.real_value()) {
2664 Engine::Iceberg
2665 } else if "hummock".eq_ignore_ascii_case(&engine_name.real_value()) {
2666 Engine::Hummock
2667 } else {
2668 parser_err!("Unsupported engine: {}", engine_name);
2669 }
2670 } else {
2671 Engine::Hummock
2672 };
2673
2674 Ok(Statement::CreateTable {
2675 name: table_name,
2676 temporary,
2677 columns,
2678 wildcard_idx,
2679 constraints,
2680 with_options,
2681 or_replace,
2682 if_not_exists,
2683 format_encode,
2684 source_watermarks,
2685 append_only,
2686 on_conflict,
2687 with_version_column,
2688 query,
2689 cdc_table_info,
2690 include_column_options: include_options,
2691 webhook_info,
2692 engine,
2693 })
2694 }
2695
2696 pub fn parse_include_options(&mut self) -> ModalResult<IncludeOption> {
2697 let mut options = vec![];
2698 while self.parse_keyword(Keyword::INCLUDE) {
2699 let column_type = self.parse_identifier()?;
2700
2701 let mut column_inner_field = None;
2702 let mut header_inner_expect_type = None;
2703 if let Token::SingleQuotedString(inner_field) = self.peek_token().token {
2704 self.next_token();
2705 column_inner_field = Some(inner_field);
2706
2707 header_inner_expect_type =
2729 opt(parser_v2::data_type.verify(|dt| !matches!(dt, DataType::Custom(_))))
2730 .parse_next(self)?;
2731 }
2732
2733 let mut column_alias = None;
2734 if self.parse_keyword(Keyword::AS) {
2735 column_alias = Some(self.parse_identifier()?);
2736 }
2737
2738 options.push(IncludeOptionItem {
2739 column_type,
2740 inner_field: column_inner_field,
2741 column_alias,
2742 header_inner_expect_type,
2743 });
2744
2745 let _ = self.consume_token(&Token::Comma);
2747 }
2748 Ok(options)
2749 }
2750
2751 pub fn parse_columns_with_watermark(&mut self) -> ModalResult<ColumnsDefTuple> {
2752 let mut columns = vec![];
2753 let mut constraints = vec![];
2754 let mut watermarks = vec![];
2755 let mut wildcard_idx = None;
2756 if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
2757 return Ok((columns, constraints, watermarks, wildcard_idx));
2758 }
2759
2760 loop {
2761 if self.consume_token(&Token::Mul) {
2762 if wildcard_idx.is_none() {
2763 wildcard_idx = Some(columns.len());
2764 } else {
2765 parser_err!("At most 1 wildcard is allowed in source definetion");
2766 }
2767 } else if let Some(constraint) = self.parse_optional_table_constraint()? {
2768 constraints.push(constraint);
2769 } else if let Some(watermark) = self.parse_optional_watermark()? {
2770 watermarks.push(watermark);
2771 if watermarks.len() > 1 {
2772 parser_err!("Only 1 watermark is allowed to be defined on source.");
2774 }
2775 } else if let Token::Word(_) = self.peek_token().token {
2776 columns.push(self.parse_column_def()?);
2777 } else {
2778 return self.expected("column name or constraint definition");
2779 }
2780 let comma = self.consume_token(&Token::Comma);
2781 if self.consume_token(&Token::RParen) {
2782 break;
2784 } else if !comma {
2785 return self.expected("',' or ')' after column definition");
2786 }
2787 }
2788
2789 Ok((columns, constraints, watermarks, wildcard_idx))
2790 }
2791
2792 fn parse_column_def(&mut self) -> ModalResult<ColumnDef> {
2793 let name = self.parse_identifier_non_reserved()?;
2794 let data_type = if let Token::Word(_) = self.peek_token().token {
2795 Some(self.parse_data_type()?)
2796 } else {
2797 None
2798 };
2799
2800 let collation = if self.parse_keyword(Keyword::COLLATE) {
2801 Some(self.parse_object_name()?)
2802 } else {
2803 None
2804 };
2805 let mut options = vec![];
2806 loop {
2807 if self.parse_keyword(Keyword::CONSTRAINT) {
2808 let name = Some(self.parse_identifier_non_reserved()?);
2809 if let Some(option) = self.parse_optional_column_option()? {
2810 options.push(ColumnOptionDef { name, option });
2811 } else {
2812 return self.expected("constraint details after CONSTRAINT <name>");
2813 }
2814 } else if let Some(option) = self.parse_optional_column_option()? {
2815 options.push(ColumnOptionDef { name: None, option });
2816 } else {
2817 break;
2818 };
2819 }
2820 Ok(ColumnDef {
2821 name,
2822 data_type,
2823 collation,
2824 options,
2825 })
2826 }
2827
2828 pub fn parse_optional_column_option(&mut self) -> ModalResult<Option<ColumnOption>> {
2829 if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
2830 Ok(Some(ColumnOption::NotNull))
2831 } else if self.parse_keyword(Keyword::NULL) {
2832 Ok(Some(ColumnOption::Null))
2833 } else if self.parse_keyword(Keyword::DEFAULT) {
2834 if self.parse_keyword(Keyword::INTERNAL) {
2835 Ok(Some(ColumnOption::DefaultValueInternal {
2836 persisted: Default::default(),
2838 expr: None,
2839 }))
2840 } else {
2841 Ok(Some(ColumnOption::DefaultValue(self.parse_expr()?)))
2842 }
2843 } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
2844 Ok(Some(ColumnOption::Unique { is_primary: true }))
2845 } else if self.parse_keyword(Keyword::UNIQUE) {
2846 Ok(Some(ColumnOption::Unique { is_primary: false }))
2847 } else if self.parse_keyword(Keyword::REFERENCES) {
2848 let foreign_table = self.parse_object_name()?;
2849 let referred_columns = self.parse_parenthesized_column_list(Optional)?;
2852 let mut on_delete = None;
2853 let mut on_update = None;
2854 loop {
2855 if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
2856 on_delete = Some(self.parse_referential_action()?);
2857 } else if on_update.is_none()
2858 && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
2859 {
2860 on_update = Some(self.parse_referential_action()?);
2861 } else {
2862 break;
2863 }
2864 }
2865 Ok(Some(ColumnOption::ForeignKey {
2866 foreign_table,
2867 referred_columns,
2868 on_delete,
2869 on_update,
2870 }))
2871 } else if self.parse_keyword(Keyword::CHECK) {
2872 self.expect_token(&Token::LParen)?;
2873 let expr = self.parse_expr()?;
2874 self.expect_token(&Token::RParen)?;
2875 Ok(Some(ColumnOption::Check(expr)))
2876 } else if self.parse_keyword(Keyword::AS) {
2877 Ok(Some(ColumnOption::GeneratedColumns(self.parse_expr()?)))
2878 } else {
2879 Ok(None)
2880 }
2881 }
2882
2883 pub fn parse_handle_conflict_behavior(&mut self) -> ModalResult<Option<OnConflict>> {
2884 if self.parse_keyword(Keyword::OVERWRITE) {
2885 Ok(Some(OnConflict::UpdateFull))
2887 } else if self.parse_keyword(Keyword::IGNORE) {
2888 Ok(Some(OnConflict::Nothing))
2890 } else if self.parse_keywords(&[
2891 Keyword::DO,
2892 Keyword::UPDATE,
2893 Keyword::IF,
2894 Keyword::NOT,
2895 Keyword::NULL,
2896 ]) {
2897 Ok(Some(OnConflict::UpdateIfNotNull))
2898 } else if self.parse_keywords(&[Keyword::DO, Keyword::UPDATE, Keyword::FULL]) {
2899 Ok(Some(OnConflict::UpdateFull))
2900 } else if self.parse_keywords(&[Keyword::DO, Keyword::NOTHING]) {
2901 Ok(Some(OnConflict::Nothing))
2902 } else {
2903 Ok(None)
2904 }
2905 }
2906
2907 pub fn parse_referential_action(&mut self) -> ModalResult<ReferentialAction> {
2908 if self.parse_keyword(Keyword::RESTRICT) {
2909 Ok(ReferentialAction::Restrict)
2910 } else if self.parse_keyword(Keyword::CASCADE) {
2911 Ok(ReferentialAction::Cascade)
2912 } else if self.parse_keywords(&[Keyword::SET, Keyword::NULL]) {
2913 Ok(ReferentialAction::SetNull)
2914 } else if self.parse_keywords(&[Keyword::NO, Keyword::ACTION]) {
2915 Ok(ReferentialAction::NoAction)
2916 } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
2917 Ok(ReferentialAction::SetDefault)
2918 } else {
2919 self.expected("one of RESTRICT, CASCADE, SET NULL, NO ACTION or SET DEFAULT")
2920 }
2921 }
2922
2923 pub fn parse_optional_watermark(&mut self) -> ModalResult<Option<SourceWatermark>> {
2924 if self.parse_keyword(Keyword::WATERMARK) {
2925 self.expect_keyword(Keyword::FOR)?;
2926 let column = self.parse_identifier_non_reserved()?;
2927 self.expect_keyword(Keyword::AS)?;
2928 let expr = self.parse_expr()?;
2929 Ok(Some(SourceWatermark { column, expr }))
2930 } else {
2931 Ok(None)
2932 }
2933 }
2934
2935 pub fn parse_optional_table_constraint(&mut self) -> ModalResult<Option<TableConstraint>> {
2936 let name = if self.parse_keyword(Keyword::CONSTRAINT) {
2937 Some(self.parse_identifier_non_reserved()?)
2938 } else {
2939 None
2940 };
2941 let checkpoint = *self;
2942 let token = self.next_token();
2943 match token.token {
2944 Token::Word(w) if w.keyword == Keyword::PRIMARY || w.keyword == Keyword::UNIQUE => {
2945 let is_primary = w.keyword == Keyword::PRIMARY;
2946 if is_primary {
2947 self.expect_keyword(Keyword::KEY)?;
2948 }
2949 let columns = self.parse_parenthesized_column_list(Mandatory)?;
2950 Ok(Some(TableConstraint::Unique {
2951 name,
2952 columns,
2953 is_primary,
2954 }))
2955 }
2956 Token::Word(w) if w.keyword == Keyword::FOREIGN => {
2957 self.expect_keyword(Keyword::KEY)?;
2958 let columns = self.parse_parenthesized_column_list(Mandatory)?;
2959 self.expect_keyword(Keyword::REFERENCES)?;
2960 let foreign_table = self.parse_object_name()?;
2961 let referred_columns = self.parse_parenthesized_column_list(Mandatory)?;
2962 let mut on_delete = None;
2963 let mut on_update = None;
2964 loop {
2965 if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
2966 on_delete = Some(self.parse_referential_action()?);
2967 } else if on_update.is_none()
2968 && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
2969 {
2970 on_update = Some(self.parse_referential_action()?);
2971 } else {
2972 break;
2973 }
2974 }
2975 Ok(Some(TableConstraint::ForeignKey {
2976 name,
2977 columns,
2978 foreign_table,
2979 referred_columns,
2980 on_delete,
2981 on_update,
2982 }))
2983 }
2984 Token::Word(w) if w.keyword == Keyword::CHECK => {
2985 self.expect_token(&Token::LParen)?;
2986 let expr = Box::new(self.parse_expr()?);
2987 self.expect_token(&Token::RParen)?;
2988 Ok(Some(TableConstraint::Check { name, expr }))
2989 }
2990 _ => {
2991 *self = checkpoint;
2992 if name.is_some() {
2993 self.expected("PRIMARY, UNIQUE, FOREIGN, or CHECK")
2994 } else {
2995 Ok(None)
2996 }
2997 }
2998 }
2999 }
3000
3001 pub fn parse_options_with_preceding_keyword(
3002 &mut self,
3003 keyword: Keyword,
3004 ) -> ModalResult<Vec<SqlOption>> {
3005 if self.parse_keyword(keyword) {
3006 self.expect_token(&Token::LParen)?;
3007 self.parse_options_inner()
3008 } else {
3009 Ok(vec![])
3010 }
3011 }
3012
3013 pub fn parse_options(&mut self) -> ModalResult<Vec<SqlOption>> {
3014 if self.peek_token() == Token::LParen {
3015 self.next_token();
3016 self.parse_options_inner()
3017 } else {
3018 Ok(vec![])
3019 }
3020 }
3021
3022 pub fn parse_options_inner(&mut self) -> ModalResult<Vec<SqlOption>> {
3024 let mut values = vec![];
3025 loop {
3026 values.push(Parser::parse_sql_option(self)?);
3027 let comma = self.consume_token(&Token::Comma);
3028 if self.consume_token(&Token::RParen) {
3029 break;
3031 } else if !comma {
3032 return self.expected("',' or ')' after option definition");
3033 }
3034 }
3035 Ok(values)
3036 }
3037
3038 pub fn parse_sql_option(&mut self) -> ModalResult<SqlOption> {
3039 let name = self.parse_object_name()?;
3040 self.expect_token(&Token::Eq)?;
3041 let value = {
3042 const CONNECTION_REF_KEY: &str = "connection";
3043 if name.real_value().eq_ignore_ascii_case(CONNECTION_REF_KEY) {
3044 let connection_name = self.parse_object_name()?;
3045 let connection_name = match connection_name.0.as_slice() {
3047 [ident] if ident.real_value() == CONNECTION_REF_KEY => {
3048 self.parse_object_name()?
3049 }
3050 _ => connection_name,
3051 };
3052 SqlOptionValue::ConnectionRef(ConnectionRefValue { connection_name })
3053 } else {
3054 self.parse_value_and_obj_ref::<false>()?
3055 }
3056 };
3057 Ok(SqlOption { name, value })
3058 }
3059
3060 pub fn parse_since(&mut self) -> ModalResult<Since> {
3061 if self.parse_keyword(Keyword::SINCE) {
3062 let checkpoint = *self;
3063 let token = self.next_token();
3064 match token.token {
3065 Token::Word(w) => {
3066 let ident = w.to_ident()?;
3067 if ident.real_value() == "proctime" || ident.real_value() == "now" {
3069 self.expect_token(&Token::LParen)?;
3070 self.expect_token(&Token::RParen)?;
3071 Ok(Since::ProcessTime)
3072 } else if ident.real_value() == "begin" {
3073 self.expect_token(&Token::LParen)?;
3074 self.expect_token(&Token::RParen)?;
3075 Ok(Since::Begin)
3076 } else {
3077 parser_err!(
3078 "Expected proctime(), begin() or now(), found: {}",
3079 ident.real_value()
3080 )
3081 }
3082 }
3083 Token::Number(s) => {
3084 let num = s
3085 .parse::<u64>()
3086 .map_err(|e| StrError(format!("Could not parse '{}' as u64: {}", s, e)))?;
3087 Ok(Since::TimestampMsNum(num))
3088 }
3089 _ => self.expected_at(checkpoint, "proctime(), begin() , now(), Number"),
3090 }
3091 } else if self.parse_word("FULL") {
3092 Ok(Since::Full)
3093 } else {
3094 Ok(Since::ProcessTime)
3095 }
3096 }
3097
3098 pub fn parse_emit_mode(&mut self) -> ModalResult<Option<EmitMode>> {
3099 if self.parse_keyword(Keyword::EMIT) {
3100 match self.parse_one_of_keywords(&[Keyword::IMMEDIATELY, Keyword::ON]) {
3101 Some(Keyword::IMMEDIATELY) => Ok(Some(EmitMode::Immediately)),
3102 Some(Keyword::ON) => {
3103 self.expect_keywords(&[Keyword::WINDOW, Keyword::CLOSE])?;
3104 Ok(Some(EmitMode::OnWindowClose))
3105 }
3106 Some(_) => unreachable!(),
3107 None => self.expected("IMMEDIATELY or ON WINDOW CLOSE after EMIT"),
3108 }
3109 } else {
3110 Ok(None)
3111 }
3112 }
3113
3114 pub fn parse_alter(&mut self) -> ModalResult<Statement> {
3115 if self.parse_keyword(Keyword::DATABASE) {
3116 self.parse_alter_database()
3117 } else if self.parse_keyword(Keyword::SCHEMA) {
3118 self.parse_alter_schema()
3119 } else if self.parse_keyword(Keyword::TABLE) {
3120 self.parse_alter_table()
3121 } else if self.parse_keyword(Keyword::INDEX) {
3122 self.parse_alter_index()
3123 } else if self.parse_keyword(Keyword::VIEW) {
3124 self.parse_alter_view(false)
3125 } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
3126 self.parse_alter_view(true)
3127 } else if self.parse_keyword(Keyword::SINK) {
3128 self.parse_alter_sink()
3129 } else if self.parse_keyword(Keyword::SOURCE) {
3130 self.parse_alter_source()
3131 } else if self.parse_keyword(Keyword::FUNCTION) {
3132 self.parse_alter_function()
3133 } else if self.parse_keyword(Keyword::CONNECTION) {
3134 self.parse_alter_connection()
3135 } else if self.parse_keyword(Keyword::USER) {
3136 self.parse_alter_user()
3137 } else if self.parse_keyword(Keyword::SYSTEM) {
3138 self.parse_alter_system()
3139 } else if self.parse_keyword(Keyword::SUBSCRIPTION) {
3140 self.parse_alter_subscription()
3141 } else if self.parse_keyword(Keyword::SECRET) {
3142 self.parse_alter_secret()
3143 } else if self.parse_word("FRAGMENT") {
3144 self.parse_alter_fragment()
3145 } else {
3146 self.expected(
3147 "DATABASE, FRAGMENT, SCHEMA, TABLE, INDEX, MATERIALIZED, VIEW, SINK, SUBSCRIPTION, SOURCE, FUNCTION, USER, SECRET or SYSTEM after ALTER"
3148 )
3149 }
3150 }
3151
3152 pub fn parse_alter_database(&mut self) -> ModalResult<Statement> {
3153 let database_name = self.parse_object_name()?;
3154 let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3155 let owner_name: Ident = self.parse_identifier()?;
3156 AlterDatabaseOperation::ChangeOwner {
3157 new_owner_name: owner_name,
3158 }
3159 } else if self.parse_keyword(Keyword::RENAME) {
3160 if self.parse_keyword(Keyword::TO) {
3161 let database_name = self.parse_object_name()?;
3162 AlterDatabaseOperation::RenameDatabase { database_name }
3163 } else {
3164 return self.expected("TO after RENAME");
3165 }
3166 } else {
3167 return self.expected("OWNER TO after ALTER DATABASE");
3168 };
3169
3170 Ok(Statement::AlterDatabase {
3171 name: database_name,
3172 operation,
3173 })
3174 }
3175
3176 pub fn parse_alter_schema(&mut self) -> ModalResult<Statement> {
3177 let schema_name = self.parse_object_name()?;
3178 let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3179 let owner_name: Ident = self.parse_identifier()?;
3180 AlterSchemaOperation::ChangeOwner {
3181 new_owner_name: owner_name,
3182 }
3183 } else if self.parse_keyword(Keyword::RENAME) {
3184 self.expect_keyword(Keyword::TO)?;
3185 let schema_name = self.parse_object_name()?;
3186 AlterSchemaOperation::RenameSchema { schema_name }
3187 } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3188 let target_schema = self.parse_object_name()?;
3189 AlterSchemaOperation::SwapRenameSchema { target_schema }
3190 } else {
3191 return self.expected("RENAME, OWNER TO, OR SWAP WITH after ALTER SCHEMA");
3192 };
3193
3194 Ok(Statement::AlterSchema {
3195 name: schema_name,
3196 operation,
3197 })
3198 }
3199
3200 pub fn parse_alter_user(&mut self) -> ModalResult<Statement> {
3201 Ok(Statement::AlterUser(AlterUserStatement::parse_to(self)?))
3202 }
3203
3204 pub fn parse_alter_table(&mut self) -> ModalResult<Statement> {
3205 let _ = self.parse_keyword(Keyword::ONLY);
3206 let table_name = self.parse_object_name()?;
3207 let operation = if self.parse_keyword(Keyword::ADD) {
3208 if let Some(constraint) = self.parse_optional_table_constraint()? {
3209 AlterTableOperation::AddConstraint(constraint)
3210 } else {
3211 let _ = self.parse_keyword(Keyword::COLUMN);
3212 let _if_not_exists =
3213 self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
3214 let column_def = self.parse_column_def()?;
3215 AlterTableOperation::AddColumn { column_def }
3216 }
3217 } else if self.parse_keywords(&[Keyword::DROP, Keyword::CONNECTOR]) {
3218 AlterTableOperation::DropConnector
3219 } else if self.parse_keyword(Keyword::RENAME) {
3220 if self.parse_keyword(Keyword::CONSTRAINT) {
3221 let old_name = self.parse_identifier_non_reserved()?;
3222 self.expect_keyword(Keyword::TO)?;
3223 let new_name = self.parse_identifier_non_reserved()?;
3224 AlterTableOperation::RenameConstraint { old_name, new_name }
3225 } else if self.parse_keyword(Keyword::TO) {
3226 let table_name = self.parse_object_name()?;
3227 AlterTableOperation::RenameTable { table_name }
3228 } else {
3229 let _ = self.parse_keyword(Keyword::COLUMN);
3230 let old_column_name = self.parse_identifier_non_reserved()?;
3231 self.expect_keyword(Keyword::TO)?;
3232 let new_column_name = self.parse_identifier_non_reserved()?;
3233 AlterTableOperation::RenameColumn {
3234 old_column_name,
3235 new_column_name,
3236 }
3237 }
3238 } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3239 let owner_name: Ident = self.parse_identifier()?;
3240 AlterTableOperation::ChangeOwner {
3241 new_owner_name: owner_name,
3242 }
3243 } else if self.parse_keyword(Keyword::SET) {
3244 if self.parse_keyword(Keyword::SCHEMA) {
3245 let schema_name = self.parse_object_name()?;
3246 AlterTableOperation::SetSchema {
3247 new_schema_name: schema_name,
3248 }
3249 } else if self.parse_keyword(Keyword::PARALLELISM) {
3250 if self.expect_keyword(Keyword::TO).is_err()
3251 && self.expect_token(&Token::Eq).is_err()
3252 {
3253 return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3254 }
3255
3256 let value = self.parse_set_variable()?;
3257
3258 let deferred = self.parse_keyword(Keyword::DEFERRED);
3259
3260 AlterTableOperation::SetParallelism {
3261 parallelism: value,
3262 deferred,
3263 }
3264 } else if let Some(rate_limit) = self.parse_alter_source_rate_limit(true)? {
3265 AlterTableOperation::SetSourceRateLimit { rate_limit }
3266 } else if let Some(rate_limit) = self.parse_alter_backfill_rate_limit()? {
3267 AlterTableOperation::SetBackfillRateLimit { rate_limit }
3268 } else if let Some(rate_limit) = self.parse_alter_dml_rate_limit()? {
3269 AlterTableOperation::SetDmlRateLimit { rate_limit }
3270 } else {
3271 return self
3272 .expected("SCHEMA/PARALLELISM/SOURCE_RATE_LIMIT/DML_RATE_LIMIT after SET");
3273 }
3274 } else if self.parse_keyword(Keyword::DROP) {
3275 let _ = self.parse_keyword(Keyword::COLUMN);
3276 let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
3277 let column_name = self.parse_identifier_non_reserved()?;
3278 let cascade = self.parse_keyword(Keyword::CASCADE);
3279 AlterTableOperation::DropColumn {
3280 column_name,
3281 if_exists,
3282 cascade,
3283 }
3284 } else if self.parse_keyword(Keyword::ALTER) {
3285 let _ = self.parse_keyword(Keyword::COLUMN);
3286 let column_name = self.parse_identifier_non_reserved()?;
3287
3288 let op = if self.parse_keywords(&[Keyword::SET, Keyword::NOT, Keyword::NULL]) {
3289 AlterColumnOperation::SetNotNull {}
3290 } else if self.parse_keywords(&[Keyword::DROP, Keyword::NOT, Keyword::NULL]) {
3291 AlterColumnOperation::DropNotNull {}
3292 } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
3293 AlterColumnOperation::SetDefault {
3294 value: self.parse_expr()?,
3295 }
3296 } else if self.parse_keywords(&[Keyword::DROP, Keyword::DEFAULT]) {
3297 AlterColumnOperation::DropDefault {}
3298 } else if self.parse_keywords(&[Keyword::SET, Keyword::DATA, Keyword::TYPE])
3299 || (self.parse_keyword(Keyword::TYPE))
3300 {
3301 let data_type = self.parse_data_type()?;
3302 let using = if self.parse_keyword(Keyword::USING) {
3303 Some(self.parse_expr()?)
3304 } else {
3305 None
3306 };
3307 AlterColumnOperation::SetDataType { data_type, using }
3308 } else {
3309 return self
3310 .expected("SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE after ALTER COLUMN");
3311 };
3312 AlterTableOperation::AlterColumn { column_name, op }
3313 } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::SCHEMA]) {
3314 AlterTableOperation::RefreshSchema
3315 } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3316 let target_table = self.parse_object_name()?;
3317 AlterTableOperation::SwapRenameTable { target_table }
3318 } else {
3319 return self
3320 .expected("ADD or RENAME or OWNER TO or SET or DROP or SWAP after ALTER TABLE");
3321 };
3322 Ok(Statement::AlterTable {
3323 name: table_name,
3324 operation,
3325 })
3326 }
3327
3328 pub fn parse_alter_backfill_rate_limit(&mut self) -> ModalResult<Option<i32>> {
3331 if !self.parse_word("BACKFILL_RATE_LIMIT") {
3332 return Ok(None);
3333 }
3334 if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3335 return self.expected("TO or = after ALTER TABLE SET BACKFILL_RATE_LIMIT");
3336 }
3337 let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3338 -1
3339 } else {
3340 let s = self.parse_number_value()?;
3341 if let Ok(n) = s.parse::<i32>() {
3342 n
3343 } else {
3344 return self.expected("number or DEFAULT");
3345 }
3346 };
3347 Ok(Some(rate_limit))
3348 }
3349
3350 pub fn parse_alter_dml_rate_limit(&mut self) -> ModalResult<Option<i32>> {
3353 if !self.parse_word("DML_RATE_LIMIT") {
3354 return Ok(None);
3355 }
3356 if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3357 return self.expected("TO or = after ALTER TABLE SET DML_RATE_LIMIT");
3358 }
3359 let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3360 -1
3361 } else {
3362 let s = self.parse_number_value()?;
3363 if let Ok(n) = s.parse::<i32>() {
3364 n
3365 } else {
3366 return self.expected("number or DEFAULT");
3367 }
3368 };
3369 Ok(Some(rate_limit))
3370 }
3371
3372 pub fn parse_alter_source_rate_limit(&mut self, is_table: bool) -> ModalResult<Option<i32>> {
3375 if !self.parse_word("SOURCE_RATE_LIMIT") {
3376 return Ok(None);
3377 }
3378 if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3379 let ddl = if is_table { "TABLE" } else { "SOURCE" };
3380 return self.expected(&format!("TO or = after ALTER {ddl} SET SOURCE_RATE_LIMIT"));
3381 }
3382 let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3383 -1
3384 } else {
3385 let s = self.parse_number_value()?;
3386 if let Ok(n) = s.parse::<i32>() {
3387 n
3388 } else {
3389 return self.expected("number or DEFAULT");
3390 }
3391 };
3392 Ok(Some(rate_limit))
3393 }
3394
3395 pub fn parse_alter_index(&mut self) -> ModalResult<Statement> {
3396 let index_name = self.parse_object_name()?;
3397 let operation = if self.parse_keyword(Keyword::RENAME) {
3398 if self.parse_keyword(Keyword::TO) {
3399 let index_name = self.parse_object_name()?;
3400 AlterIndexOperation::RenameIndex { index_name }
3401 } else {
3402 return self.expected("TO after RENAME");
3403 }
3404 } else if self.parse_keyword(Keyword::SET) {
3405 if self.parse_keyword(Keyword::PARALLELISM) {
3406 if self.expect_keyword(Keyword::TO).is_err()
3407 && self.expect_token(&Token::Eq).is_err()
3408 {
3409 return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3410 }
3411
3412 let value = self.parse_set_variable()?;
3413
3414 let deferred = self.parse_keyword(Keyword::DEFERRED);
3415
3416 AlterIndexOperation::SetParallelism {
3417 parallelism: value,
3418 deferred,
3419 }
3420 } else {
3421 return self.expected("PARALLELISM after SET");
3422 }
3423 } else {
3424 return self.expected("RENAME after ALTER INDEX");
3425 };
3426
3427 Ok(Statement::AlterIndex {
3428 name: index_name,
3429 operation,
3430 })
3431 }
3432
3433 pub fn parse_alter_view(&mut self, materialized: bool) -> ModalResult<Statement> {
3434 let view_name = self.parse_object_name()?;
3435 let operation = if self.parse_keyword(Keyword::RENAME) {
3436 if self.parse_keyword(Keyword::TO) {
3437 let view_name = self.parse_object_name()?;
3438 AlterViewOperation::RenameView { view_name }
3439 } else {
3440 return self.expected("TO after RENAME");
3441 }
3442 } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3443 let owner_name: Ident = self.parse_identifier()?;
3444 AlterViewOperation::ChangeOwner {
3445 new_owner_name: owner_name,
3446 }
3447 } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3448 let target_view = self.parse_object_name()?;
3449 AlterViewOperation::SwapRenameView { target_view }
3450 } else if self.parse_keyword(Keyword::SET) {
3451 if self.parse_keyword(Keyword::SCHEMA) {
3452 let schema_name = self.parse_object_name()?;
3453 AlterViewOperation::SetSchema {
3454 new_schema_name: schema_name,
3455 }
3456 } else if self.parse_keyword(Keyword::PARALLELISM) && materialized {
3457 if self.expect_keyword(Keyword::TO).is_err()
3458 && self.expect_token(&Token::Eq).is_err()
3459 {
3460 return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3461 }
3462
3463 let value = self.parse_set_variable()?;
3464
3465 let deferred = self.parse_keyword(Keyword::DEFERRED);
3466
3467 AlterViewOperation::SetParallelism {
3468 parallelism: value,
3469 deferred,
3470 }
3471 } else if self.parse_keyword(Keyword::RESOURCE_GROUP) && materialized {
3472 if self.expect_keyword(Keyword::TO).is_err()
3473 && self.expect_token(&Token::Eq).is_err()
3474 {
3475 return self
3476 .expected("TO or = after ALTER MATERIALIZED VIEW SET RESOURCE_GROUP");
3477 }
3478 let value = self.parse_set_variable()?;
3479 let deferred = self.parse_keyword(Keyword::DEFERRED);
3480
3481 AlterViewOperation::SetResourceGroup {
3482 resource_group: Some(value),
3483 deferred,
3484 }
3485 } else if materialized
3486 && let Some(rate_limit) = self.parse_alter_backfill_rate_limit()?
3487 {
3488 AlterViewOperation::SetBackfillRateLimit { rate_limit }
3489 } else {
3490 return self.expected("SCHEMA/PARALLELISM/BACKFILL_RATE_LIMIT after SET");
3491 }
3492 } else if self.parse_keyword(Keyword::RESET) {
3493 if self.parse_keyword(Keyword::RESOURCE_GROUP) && materialized {
3494 let deferred = self.parse_keyword(Keyword::DEFERRED);
3495
3496 AlterViewOperation::SetResourceGroup {
3497 resource_group: None,
3498 deferred,
3499 }
3500 } else {
3501 return self.expected("RESOURCE_GROUP after RESET");
3502 }
3503 } else {
3504 return self.expected(&format!(
3505 "RENAME or OWNER TO or SET or SWAP after ALTER {}VIEW",
3506 if materialized { "MATERIALIZED " } else { "" }
3507 ));
3508 };
3509
3510 Ok(Statement::AlterView {
3511 materialized,
3512 name: view_name,
3513 operation,
3514 })
3515 }
3516
3517 pub fn parse_alter_sink_rate_limit(&mut self) -> ModalResult<Option<i32>> {
3520 if !self.parse_word("SINK_RATE_LIMIT") {
3521 return Ok(None);
3522 }
3523 if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3524 return self.expected("TO or = after ALTER SINK SET SINK_RATE_LIMIT");
3525 }
3526 let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3527 -1
3528 } else {
3529 let s = self.parse_number_value()?;
3530 if let Ok(n) = s.parse::<i32>() {
3531 n
3532 } else {
3533 return self.expected("number or DEFAULT");
3534 }
3535 };
3536 Ok(Some(rate_limit))
3537 }
3538
3539 pub fn parse_alter_sink(&mut self) -> ModalResult<Statement> {
3540 let sink_name = self.parse_object_name()?;
3541 let operation = if self.parse_keyword(Keyword::RENAME) {
3542 if self.parse_keyword(Keyword::TO) {
3543 let sink_name = self.parse_object_name()?;
3544 AlterSinkOperation::RenameSink { sink_name }
3545 } else {
3546 return self.expected("TO after RENAME");
3547 }
3548 } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3549 let owner_name: Ident = self.parse_identifier()?;
3550 AlterSinkOperation::ChangeOwner {
3551 new_owner_name: owner_name,
3552 }
3553 } else if self.parse_keyword(Keyword::SET) {
3554 if self.parse_keyword(Keyword::SCHEMA) {
3555 let schema_name = self.parse_object_name()?;
3556 AlterSinkOperation::SetSchema {
3557 new_schema_name: schema_name,
3558 }
3559 } else if self.parse_keyword(Keyword::PARALLELISM) {
3560 if self.expect_keyword(Keyword::TO).is_err()
3561 && self.expect_token(&Token::Eq).is_err()
3562 {
3563 return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3564 }
3565
3566 let value = self.parse_set_variable()?;
3567 let deferred = self.parse_keyword(Keyword::DEFERRED);
3568
3569 AlterSinkOperation::SetParallelism {
3570 parallelism: value,
3571 deferred,
3572 }
3573 } else if let Some(rate_limit) = self.parse_alter_sink_rate_limit()? {
3574 AlterSinkOperation::SetSinkRateLimit { rate_limit }
3575 } else {
3576 return self.expected("SCHEMA/PARALLELISM after SET");
3577 }
3578 } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3579 let target_sink = self.parse_object_name()?;
3580 AlterSinkOperation::SwapRenameSink { target_sink }
3581 } else {
3582 return self.expected("RENAME or OWNER TO or SET after ALTER SINK");
3583 };
3584
3585 Ok(Statement::AlterSink {
3586 name: sink_name,
3587 operation,
3588 })
3589 }
3590
3591 pub fn parse_alter_subscription(&mut self) -> ModalResult<Statement> {
3592 let subscription_name = self.parse_object_name()?;
3593 let operation = if self.parse_keyword(Keyword::RENAME) {
3594 if self.parse_keyword(Keyword::TO) {
3595 let subscription_name = self.parse_object_name()?;
3596 AlterSubscriptionOperation::RenameSubscription { subscription_name }
3597 } else {
3598 return self.expected("TO after RENAME");
3599 }
3600 } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3601 let owner_name: Ident = self.parse_identifier()?;
3602 AlterSubscriptionOperation::ChangeOwner {
3603 new_owner_name: owner_name,
3604 }
3605 } else if self.parse_keyword(Keyword::SET) {
3606 if self.parse_keyword(Keyword::SCHEMA) {
3607 let schema_name = self.parse_object_name()?;
3608 AlterSubscriptionOperation::SetSchema {
3609 new_schema_name: schema_name,
3610 }
3611 } else {
3612 return self.expected("SCHEMA after SET");
3613 }
3614 } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3615 let target_subscription = self.parse_object_name()?;
3616 AlterSubscriptionOperation::SwapRenameSubscription {
3617 target_subscription,
3618 }
3619 } else {
3620 return self.expected("RENAME or OWNER TO or SET or SWAP after ALTER SUBSCRIPTION");
3621 };
3622
3623 Ok(Statement::AlterSubscription {
3624 name: subscription_name,
3625 operation,
3626 })
3627 }
3628
3629 pub fn parse_alter_source(&mut self) -> ModalResult<Statement> {
3630 let source_name = self.parse_object_name()?;
3631 let operation = if self.parse_keyword(Keyword::RENAME) {
3632 if self.parse_keyword(Keyword::TO) {
3633 let source_name = self.parse_object_name()?;
3634 AlterSourceOperation::RenameSource { source_name }
3635 } else {
3636 return self.expected("TO after RENAME");
3637 }
3638 } else if self.parse_keyword(Keyword::ADD) {
3639 let _ = self.parse_keyword(Keyword::COLUMN);
3640 let _if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
3641 let column_def = self.parse_column_def()?;
3642 AlterSourceOperation::AddColumn { column_def }
3643 } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3644 let owner_name: Ident = self.parse_identifier()?;
3645 AlterSourceOperation::ChangeOwner {
3646 new_owner_name: owner_name,
3647 }
3648 } else if self.parse_keyword(Keyword::SET) {
3649 if self.parse_keyword(Keyword::SCHEMA) {
3650 let schema_name = self.parse_object_name()?;
3651 AlterSourceOperation::SetSchema {
3652 new_schema_name: schema_name,
3653 }
3654 } else if let Some(rate_limit) = self.parse_alter_source_rate_limit(false)? {
3655 AlterSourceOperation::SetSourceRateLimit { rate_limit }
3656 } else if self.parse_keyword(Keyword::PARALLELISM) {
3657 if self.expect_keyword(Keyword::TO).is_err()
3658 && self.expect_token(&Token::Eq).is_err()
3659 {
3660 return self.expected("TO or = after ALTER SOURCE SET PARALLELISM");
3661 }
3662
3663 let value = self.parse_set_variable()?;
3664 let deferred = self.parse_keyword(Keyword::DEFERRED);
3665
3666 AlterSourceOperation::SetParallelism {
3667 parallelism: value,
3668 deferred,
3669 }
3670 } else {
3671 return self.expected("SCHEMA, SOURCE_RATE_LIMIT or PARALLELISM after SET");
3672 }
3673 } else if self.peek_nth_any_of_keywords(0, &[Keyword::FORMAT]) {
3674 let format_encode = self.parse_schema()?.unwrap();
3675 if format_encode.key_encode.is_some() {
3676 parser_err!("key encode clause is not supported in source schema");
3677 }
3678 AlterSourceOperation::FormatEncode { format_encode }
3679 } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::SCHEMA]) {
3680 AlterSourceOperation::RefreshSchema
3681 } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3682 let target_source = self.parse_object_name()?;
3683 AlterSourceOperation::SwapRenameSource { target_source }
3684 } else {
3685 return self.expected("RENAME, ADD COLUMN, OWNER TO or SET after ALTER SOURCE");
3686 };
3687
3688 Ok(Statement::AlterSource {
3689 name: source_name,
3690 operation,
3691 })
3692 }
3693
3694 pub fn parse_alter_function(&mut self) -> ModalResult<Statement> {
3695 let FunctionDesc { name, args } = self.parse_function_desc()?;
3696
3697 let operation = if self.parse_keyword(Keyword::SET) {
3698 if self.parse_keyword(Keyword::SCHEMA) {
3699 let schema_name = self.parse_object_name()?;
3700 AlterFunctionOperation::SetSchema {
3701 new_schema_name: schema_name,
3702 }
3703 } else {
3704 return self.expected("SCHEMA after SET");
3705 }
3706 } else {
3707 return self.expected("SET after ALTER FUNCTION");
3708 };
3709
3710 Ok(Statement::AlterFunction {
3711 name,
3712 args,
3713 operation,
3714 })
3715 }
3716
3717 pub fn parse_alter_connection(&mut self) -> ModalResult<Statement> {
3718 let connection_name = self.parse_object_name()?;
3719 let operation = if self.parse_keyword(Keyword::SET) {
3720 if self.parse_keyword(Keyword::SCHEMA) {
3721 let schema_name = self.parse_object_name()?;
3722 AlterConnectionOperation::SetSchema {
3723 new_schema_name: schema_name,
3724 }
3725 } else {
3726 return self.expected("SCHEMA after SET");
3727 }
3728 } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3729 let owner_name: Ident = self.parse_identifier()?;
3730 AlterConnectionOperation::ChangeOwner {
3731 new_owner_name: owner_name,
3732 }
3733 } else {
3734 return self.expected("SET, or OWNER TO after ALTER CONNECTION");
3735 };
3736
3737 Ok(Statement::AlterConnection {
3738 name: connection_name,
3739 operation,
3740 })
3741 }
3742
3743 pub fn parse_alter_system(&mut self) -> ModalResult<Statement> {
3744 self.expect_keyword(Keyword::SET)?;
3745 let param = self.parse_identifier()?;
3746 if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3747 return self.expected("TO or = after ALTER SYSTEM SET");
3748 }
3749 let value = self.parse_set_variable()?;
3750 Ok(Statement::AlterSystem { param, value })
3751 }
3752
3753 pub fn parse_alter_secret(&mut self) -> ModalResult<Statement> {
3754 let secret_name = self.parse_object_name()?;
3755 let with_options = self.parse_with_properties()?;
3756 self.expect_keyword(Keyword::AS)?;
3757 let new_credential = self.ensure_parse_value()?;
3758 let operation = AlterSecretOperation::ChangeCredential { new_credential };
3759 Ok(Statement::AlterSecret {
3760 name: secret_name,
3761 with_options,
3762 operation,
3763 })
3764 }
3765
3766 pub fn parse_alter_fragment(&mut self) -> ModalResult<Statement> {
3767 let fragment_id = self.parse_literal_uint()? as u32;
3768 if !self.parse_keyword(Keyword::SET) {
3769 return self.expected("SET after ALTER FRAGMENT");
3770 }
3771 let rate_limit = self.parse_alter_fragment_rate_limit()?;
3772 let operation = AlterFragmentOperation::AlterBackfillRateLimit { rate_limit };
3773 Ok(Statement::AlterFragment {
3774 fragment_id,
3775 operation,
3776 })
3777 }
3778
3779 fn parse_alter_fragment_rate_limit(&mut self) -> ModalResult<i32> {
3780 if !self.parse_word("RATE_LIMIT") {
3781 return self.expected("expected RATE_LIMIT after SET");
3782 }
3783 if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3784 return self.expected("TO or = after RATE_LIMIT");
3785 }
3786 let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3787 -1
3788 } else {
3789 let s = self.parse_number_value()?;
3790 if let Ok(n) = s.parse::<i32>() {
3791 n
3792 } else {
3793 return self.expected("number or DEFAULT");
3794 }
3795 };
3796 Ok(rate_limit)
3797 }
3798
3799 pub fn parse_copy(&mut self) -> ModalResult<Statement> {
3801 let table_name = self.parse_object_name()?;
3802 let columns = self.parse_parenthesized_column_list(Optional)?;
3803 self.expect_keywords(&[Keyword::FROM, Keyword::STDIN])?;
3804 self.expect_token(&Token::SemiColon)?;
3805 let values = self.parse_tsv();
3806 Ok(Statement::Copy {
3807 table_name,
3808 columns,
3809 values,
3810 })
3811 }
3812
3813 fn parse_tsv(&mut self) -> Vec<Option<String>> {
3816 self.parse_tab_value()
3817 }
3818
3819 fn parse_tab_value(&mut self) -> Vec<Option<String>> {
3820 let mut values = vec![];
3821 let mut content = String::from("");
3822 while let Some(t) = self.next_token_no_skip() {
3823 match t.token {
3824 Token::Whitespace(Whitespace::Tab) => {
3825 values.push(Some(content.clone()));
3826 content.clear();
3827 }
3828 Token::Whitespace(Whitespace::Newline) => {
3829 values.push(Some(content.clone()));
3830 content.clear();
3831 }
3832 Token::Backslash => {
3833 if self.consume_token(&Token::Period) {
3834 return values;
3835 }
3836 if let Token::Word(w) = self.next_token().token {
3837 if w.value == "N" {
3838 values.push(None);
3839 }
3840 }
3841 }
3842 _ => {
3843 content.push_str(&t.to_string());
3844 }
3845 }
3846 }
3847 values
3848 }
3849
3850 pub fn ensure_parse_value(&mut self) -> ModalResult<Value> {
3851 match self.parse_value_and_obj_ref::<true>()? {
3852 SqlOptionValue::Value(value) => Ok(value),
3853 SqlOptionValue::SecretRef(_) | SqlOptionValue::ConnectionRef(_) => unreachable!(),
3854 }
3855 }
3856
3857 pub fn parse_value_and_obj_ref<const FORBID_OBJ_REF: bool>(
3859 &mut self,
3860 ) -> ModalResult<SqlOptionValue> {
3861 let checkpoint = *self;
3862 let token = self.next_token();
3863 match token.token {
3864 Token::Word(w) => match w.keyword {
3865 Keyword::TRUE => Ok(Value::Boolean(true).into()),
3866 Keyword::FALSE => Ok(Value::Boolean(false).into()),
3867 Keyword::NULL => Ok(Value::Null.into()),
3868 Keyword::NoKeyword if w.quote_style.is_some() => match w.quote_style {
3869 Some('"') => Ok(Value::DoubleQuotedString(w.value).into()),
3870 Some('\'') => Ok(Value::SingleQuotedString(w.value).into()),
3871 _ => self.expected_at(checkpoint, "A value")?,
3872 },
3873 Keyword::SECRET => {
3874 if FORBID_OBJ_REF {
3875 return self.expected_at(
3876 checkpoint,
3877 "a concrete value rather than a secret reference",
3878 );
3879 }
3880 let secret = self.parse_secret_ref()?;
3881 Ok(SqlOptionValue::SecretRef(secret))
3882 }
3883 _ => self.expected_at(checkpoint, "a concrete value"),
3884 },
3885 Token::Number(ref n) => Ok(Value::Number(n.clone()).into()),
3886 Token::SingleQuotedString(ref s) => Ok(Value::SingleQuotedString(s.to_string()).into()),
3887 Token::DollarQuotedString(ref s) => Ok(Value::DollarQuotedString(s.clone()).into()),
3888 Token::CstyleEscapesString(ref s) => Ok(Value::CstyleEscapedString(s.clone()).into()),
3889 Token::NationalStringLiteral(ref s) => {
3890 Ok(Value::NationalStringLiteral(s.to_string()).into())
3891 }
3892 Token::HexStringLiteral(ref s) => Ok(Value::HexStringLiteral(s.to_string()).into()),
3893 _ => self.expected_at(checkpoint, "a value"),
3894 }
3895 }
3896
3897 fn parse_secret_ref(&mut self) -> ModalResult<SecretRefValue> {
3898 let secret_name = self.parse_object_name()?;
3899 let ref_as = if self.parse_keywords(&[Keyword::AS, Keyword::FILE]) {
3900 SecretRefAsType::File
3901 } else {
3902 SecretRefAsType::Text
3903 };
3904 Ok(SecretRefValue {
3905 secret_name,
3906 ref_as,
3907 })
3908 }
3909
3910 fn parse_set_variable(&mut self) -> ModalResult<SetVariableValue> {
3911 alt((
3912 Keyword::DEFAULT.value(SetVariableValue::Default),
3913 separated(
3914 1..,
3915 alt((
3916 Self::ensure_parse_value.map(SetVariableValueSingle::Literal),
3917 |parser: &mut Self| {
3918 let checkpoint = *parser;
3919 let ident = parser.parse_identifier()?;
3920 if ident.value == "default" {
3921 *parser = checkpoint;
3922 return parser.expected("parameter list value").map_err(|e| e.cut());
3923 }
3924 Ok(SetVariableValueSingle::Ident(ident))
3925 },
3926 fail.expect("parameter value"),
3927 )),
3928 Token::Comma,
3929 )
3930 .map(|list: Vec<SetVariableValueSingle>| {
3931 if list.len() == 1 {
3932 SetVariableValue::Single(list[0].clone())
3933 } else {
3934 SetVariableValue::List(list)
3935 }
3936 }),
3937 ))
3938 .parse_next(self)
3939 }
3940
3941 pub fn parse_number_value(&mut self) -> ModalResult<String> {
3942 let checkpoint = *self;
3943 match self.ensure_parse_value()? {
3944 Value::Number(v) => Ok(v),
3945 _ => self.expected_at(checkpoint, "literal number"),
3946 }
3947 }
3948
3949 pub fn parse_literal_uint(&mut self) -> ModalResult<u64> {
3951 literal_uint(self)
3952 }
3953
3954 pub fn parse_function_definition(&mut self) -> ModalResult<FunctionDefinition> {
3955 alt((
3956 single_quoted_string.map(FunctionDefinition::SingleQuotedDef),
3957 dollar_quoted_string.map(FunctionDefinition::DoubleDollarDef),
3958 Self::parse_identifier.map(|i| FunctionDefinition::Identifier(i.value)),
3959 fail.expect("function definition"),
3960 ))
3961 .parse_next(self)
3962 }
3963
3964 pub fn parse_literal_string(&mut self) -> ModalResult<String> {
3966 let checkpoint = *self;
3967 let token = self.next_token();
3968 match token.token {
3969 Token::SingleQuotedString(s) => Ok(s),
3970 _ => self.expected_at(checkpoint, "literal string"),
3971 }
3972 }
3973
3974 pub fn parse_map_key(&mut self) -> ModalResult<Expr> {
3976 alt((
3977 Self::parse_function,
3978 single_quoted_string.map(|s| Expr::Value(Value::SingleQuotedString(s))),
3979 token_number.map(|s| Expr::Value(Value::Number(s))),
3980 fail.expect("literal string, number or function"),
3981 ))
3982 .parse_next(self)
3983 }
3984
3985 pub fn parse_data_type(&mut self) -> ModalResult<DataType> {
3987 parser_v2::data_type(self)
3988 }
3989
3990 pub fn parse_optional_alias(
3994 &mut self,
3995 reserved_kwds: &[Keyword],
3996 ) -> ModalResult<Option<Ident>> {
3997 let after_as = self.parse_keyword(Keyword::AS);
3998 let checkpoint = *self;
3999 let token = self.next_token();
4000 match token.token {
4001 Token::Word(w) if after_as || (!reserved_kwds.contains(&w.keyword)) => {
4007 Ok(Some(w.to_ident()?))
4008 }
4009 _ => {
4010 *self = checkpoint;
4011 if after_as {
4012 return self.expected("an identifier after AS");
4013 }
4014 Ok(None) }
4016 }
4017 }
4018
4019 pub fn parse_optional_table_alias(
4024 &mut self,
4025 reserved_kwds: &[Keyword],
4026 ) -> ModalResult<Option<TableAlias>> {
4027 match self.parse_optional_alias(reserved_kwds)? {
4028 Some(name) => {
4029 let columns = self.parse_parenthesized_column_list(Optional)?;
4030 Ok(Some(TableAlias { name, columns }))
4031 }
4032 None => Ok(None),
4033 }
4034 }
4035
4036 pub fn parse_as_of(&mut self) -> ModalResult<AsOf> {
4038 Keyword::FOR.parse_next(self)?;
4039 alt((
4040 preceded(
4041 (Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF),
4042 cut_err(
4043 alt((
4044 preceded(
4045 (
4046 Self::parse_identifier.verify(|ident| ident.real_value() == "now"),
4047 cut_err(Token::LParen),
4048 cut_err(Token::RParen),
4049 Token::Minus,
4050 ),
4051 Self::parse_literal_interval.try_map(|e| match e {
4052 Expr::Value(v) => match v {
4053 Value::Interval {
4054 value,
4055 leading_field,
4056 ..
4057 } => {
4058 let Some(leading_field) = leading_field else {
4059 return Err(StrError("expect duration unit".into()));
4060 };
4061 Ok(AsOf::ProcessTimeWithInterval((value, leading_field)))
4062 }
4063 _ => Err(StrError("expect Value::Interval".into())),
4064 },
4065 _ => Err(StrError("expect Expr::Value".into())),
4066 }),
4067 ),
4068 (
4069 Self::parse_identifier.verify(|ident| ident.real_value() == "now"),
4070 cut_err(Token::LParen),
4071 cut_err(Token::RParen),
4072 )
4073 .value(AsOf::ProcessTimeWithInterval((
4074 "0".to_owned(),
4075 DateTimeField::Second,
4076 ))),
4077 (
4078 Self::parse_identifier.verify(|ident| ident.real_value() == "proctime"),
4079 cut_err(Token::LParen),
4080 cut_err(Token::RParen),
4081 )
4082 .value(AsOf::ProcessTime),
4083 literal_i64.map(AsOf::TimestampNum),
4084 single_quoted_string.map(AsOf::TimestampString),
4085 ))
4086 .expect("proctime(), now(), number or string"),
4087 ),
4088 ),
4089 preceded(
4090 (Keyword::SYSTEM_VERSION, Keyword::AS, Keyword::OF),
4091 cut_err(
4092 alt((
4093 literal_i64.map(AsOf::VersionNum),
4094 single_quoted_string.map(AsOf::VersionString),
4095 ))
4096 .expect("number or string"),
4097 ),
4098 ),
4099 ))
4100 .parse_next(self)
4101 }
4102
4103 pub fn parse_object_name(&mut self) -> ModalResult<ObjectName> {
4106 let mut idents = vec![];
4107 loop {
4108 idents.push(self.parse_identifier()?);
4109 if !self.consume_token(&Token::Period) {
4110 break;
4111 }
4112 }
4113 Ok(ObjectName(idents))
4114 }
4115
4116 pub fn parse_identifiers_non_keywords(&mut self) -> ModalResult<Vec<Ident>> {
4118 let mut idents = vec![];
4119 loop {
4120 match self.peek_token().token {
4121 Token::Word(w) => {
4122 if w.keyword != Keyword::NoKeyword {
4123 break;
4124 }
4125
4126 idents.push(w.to_ident()?);
4127 }
4128 Token::EOF | Token::Eq => break,
4129 _ => {}
4130 }
4131
4132 self.next_token();
4133 }
4134
4135 Ok(idents)
4136 }
4137
4138 pub fn parse_identifiers(&mut self) -> ModalResult<Vec<Ident>> {
4140 let mut idents = vec![];
4141 loop {
4142 let token = self.next_token();
4143 match token.token {
4144 Token::Word(w) => {
4145 idents.push(w.to_ident()?);
4146 }
4147 Token::EOF => break,
4148 _ => {}
4149 }
4150 }
4151
4152 Ok(idents)
4153 }
4154
4155 pub fn parse_identifier(&mut self) -> ModalResult<Ident> {
4157 let checkpoint = *self;
4158 let token = self.next_token();
4159 match token.token {
4160 Token::Word(w) => Ok(w.to_ident()?),
4161 _ => self.expected_at(checkpoint, "identifier"),
4162 }
4163 }
4164
4165 pub fn parse_identifier_non_reserved(&mut self) -> ModalResult<Ident> {
4167 let checkpoint = *self;
4168 let token = self.next_token();
4169 match token.token {
4170 Token::Word(w) => {
4171 match keywords::RESERVED_FOR_COLUMN_OR_TABLE_NAME.contains(&w.keyword) {
4172 true => parser_err!("syntax error at or near {w}"),
4173 false => Ok(w.to_ident()?),
4174 }
4175 }
4176 _ => self.expected_at(checkpoint, "identifier"),
4177 }
4178 }
4179
4180 pub fn parse_parenthesized_column_list(
4182 &mut self,
4183 optional: IsOptional,
4184 ) -> ModalResult<Vec<Ident>> {
4185 if self.consume_token(&Token::LParen) {
4186 let cols = self.parse_comma_separated(Parser::parse_identifier_non_reserved)?;
4187 self.expect_token(&Token::RParen)?;
4188 Ok(cols)
4189 } else if optional == Optional {
4190 Ok(vec![])
4191 } else {
4192 self.expected("a list of columns in parentheses")
4193 }
4194 }
4195
4196 pub fn parse_returning(&mut self, optional: IsOptional) -> ModalResult<Vec<SelectItem>> {
4197 if self.parse_keyword(Keyword::RETURNING) {
4198 let cols = self.parse_comma_separated(Parser::parse_select_item)?;
4199 Ok(cols)
4200 } else if optional == Optional {
4201 Ok(vec![])
4202 } else {
4203 self.expected("a list of columns or * after returning")
4204 }
4205 }
4206
4207 pub fn parse_row_expr(&mut self) -> ModalResult<Expr> {
4208 Ok(Expr::Row(self.parse_token_wrapped_exprs(
4209 &Token::LParen,
4210 &Token::RParen,
4211 )?))
4212 }
4213
4214 pub fn parse_token_wrapped_exprs(
4216 &mut self,
4217 left: &Token,
4218 right: &Token,
4219 ) -> ModalResult<Vec<Expr>> {
4220 if self.consume_token(left) {
4221 let exprs = if self.consume_token(right) {
4222 vec![]
4223 } else {
4224 let exprs = self.parse_comma_separated(Parser::parse_expr)?;
4225 self.expect_token(right)?;
4226 exprs
4227 };
4228 Ok(exprs)
4229 } else {
4230 self.expected(left.to_string().as_str())
4231 }
4232 }
4233
4234 pub fn parse_optional_precision(&mut self) -> ModalResult<Option<u64>> {
4235 if self.consume_token(&Token::LParen) {
4236 let n = self.parse_literal_uint()?;
4237 self.expect_token(&Token::RParen)?;
4238 Ok(Some(n))
4239 } else {
4240 Ok(None)
4241 }
4242 }
4243
4244 pub fn parse_optional_precision_scale(&mut self) -> ModalResult<(Option<u64>, Option<u64>)> {
4245 if self.consume_token(&Token::LParen) {
4246 let n = self.parse_literal_uint()?;
4247 let scale = if self.consume_token(&Token::Comma) {
4248 Some(self.parse_literal_uint()?)
4249 } else {
4250 None
4251 };
4252 self.expect_token(&Token::RParen)?;
4253 Ok((Some(n), scale))
4254 } else {
4255 Ok((None, None))
4256 }
4257 }
4258
4259 pub fn parse_delete(&mut self) -> ModalResult<Statement> {
4260 self.expect_keyword(Keyword::FROM)?;
4261 let table_name = self.parse_object_name()?;
4262 let selection = if self.parse_keyword(Keyword::WHERE) {
4263 Some(self.parse_expr()?)
4264 } else {
4265 None
4266 };
4267 let returning = self.parse_returning(Optional)?;
4268
4269 Ok(Statement::Delete {
4270 table_name,
4271 selection,
4272 returning,
4273 })
4274 }
4275
4276 pub fn parse_optional_boolean(&mut self, default: bool) -> bool {
4277 if let Some(keyword) = self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]) {
4278 match keyword {
4279 Keyword::TRUE => true,
4280 Keyword::FALSE => false,
4281 _ => unreachable!(),
4282 }
4283 } else {
4284 default
4285 }
4286 }
4287
4288 pub fn parse_explain(&mut self) -> ModalResult<Statement> {
4289 let mut options = ExplainOptions::default();
4290 let mut analyze_duration = None;
4291
4292 let explain_key_words = [
4293 Keyword::VERBOSE,
4294 Keyword::TRACE,
4295 Keyword::TYPE,
4296 Keyword::LOGICAL,
4297 Keyword::PHYSICAL,
4298 Keyword::DISTSQL,
4299 Keyword::FORMAT,
4300 Keyword::DURATION_SECS,
4301 ];
4302
4303 let parse_explain_option = |parser: &mut Parser<'_>| -> ModalResult<()> {
4304 let keyword = parser.expect_one_of_keywords(&explain_key_words)?;
4305 match keyword {
4306 Keyword::VERBOSE => options.verbose = parser.parse_optional_boolean(true),
4307 Keyword::TRACE => options.trace = parser.parse_optional_boolean(true),
4308 Keyword::TYPE => {
4309 let explain_type = parser.expect_one_of_keywords(&[
4310 Keyword::LOGICAL,
4311 Keyword::PHYSICAL,
4312 Keyword::DISTSQL,
4313 ])?;
4314 match explain_type {
4315 Keyword::LOGICAL => options.explain_type = ExplainType::Logical,
4316 Keyword::PHYSICAL => options.explain_type = ExplainType::Physical,
4317 Keyword::DISTSQL => options.explain_type = ExplainType::DistSql,
4318 _ => unreachable!("{}", keyword),
4319 }
4320 }
4321 Keyword::LOGICAL => options.explain_type = ExplainType::Logical,
4322 Keyword::PHYSICAL => options.explain_type = ExplainType::Physical,
4323 Keyword::DISTSQL => options.explain_type = ExplainType::DistSql,
4324 Keyword::FORMAT => {
4325 options.explain_format = {
4326 match parser.expect_one_of_keywords(&[
4327 Keyword::TEXT,
4328 Keyword::JSON,
4329 Keyword::XML,
4330 Keyword::YAML,
4331 Keyword::DOT,
4332 ])? {
4333 Keyword::TEXT => ExplainFormat::Text,
4334 Keyword::JSON => ExplainFormat::Json,
4335 Keyword::XML => ExplainFormat::Xml,
4336 Keyword::YAML => ExplainFormat::Yaml,
4337 Keyword::DOT => ExplainFormat::Dot,
4338 _ => unreachable!("{}", keyword),
4339 }
4340 }
4341 }
4342 Keyword::DURATION_SECS => {
4343 analyze_duration = Some(parser.parse_literal_uint()?);
4344 }
4345 _ => unreachable!("{}", keyword),
4346 };
4347 Ok(())
4348 };
4349
4350 let analyze = self.parse_keyword(Keyword::ANALYZE);
4351 if self.peek_token() == Token::LParen
4354 && self.peek_nth_any_of_keywords(1, &explain_key_words)
4355 && self.consume_token(&Token::LParen)
4356 {
4357 self.parse_comma_separated(parse_explain_option)?;
4358 self.expect_token(&Token::RParen)?;
4359 }
4360
4361 if analyze {
4362 fn parse_analyze_target(parser: &mut Parser<'_>) -> ModalResult<Option<AnalyzeTarget>> {
4363 if parser.parse_keyword(Keyword::TABLE) {
4364 let table_name = parser.parse_object_name()?;
4365 Ok(Some(AnalyzeTarget::Table(table_name)))
4366 } else if parser.parse_keyword(Keyword::INDEX) {
4367 let index_name = parser.parse_object_name()?;
4368 Ok(Some(AnalyzeTarget::Index(index_name)))
4369 } else if parser.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
4370 let view_name = parser.parse_object_name()?;
4371 Ok(Some(AnalyzeTarget::MaterializedView(view_name)))
4372 } else if parser.parse_keyword(Keyword::INDEX) {
4373 let index_name = parser.parse_object_name()?;
4374 Ok(Some(AnalyzeTarget::Index(index_name)))
4375 } else if parser.parse_keyword(Keyword::SINK) {
4376 let sink_name = parser.parse_object_name()?;
4377 Ok(Some(AnalyzeTarget::Sink(sink_name)))
4378 } else if parser.parse_word("ID") {
4379 let job_id = parser.parse_literal_uint()? as u32;
4380 Ok(Some(AnalyzeTarget::Id(job_id)))
4381 } else {
4382 Ok(None)
4383 }
4384 }
4385 if let Some(target) = parse_analyze_target(self)? {
4386 let statement = Statement::ExplainAnalyzeStreamJob {
4387 target,
4388 duration_secs: analyze_duration,
4389 };
4390 return Ok(statement);
4391 }
4392 }
4393
4394 let statement = match self.parse_statement() {
4395 Ok(statement) => statement,
4396 error @ Err(_) => {
4397 return if analyze {
4398 self.expected_at(
4399 *self,
4400 "SINK, TABLE, MATERIALIZED VIEW, INDEX or a statement after ANALYZE",
4401 )
4402 } else {
4403 error
4404 };
4405 }
4406 };
4407 Ok(Statement::Explain {
4408 analyze,
4409 statement: Box::new(statement),
4410 options,
4411 })
4412 }
4413
4414 pub fn parse_query(&mut self) -> ModalResult<Query> {
4419 let with = if self.parse_keyword(Keyword::WITH) {
4420 Some(With {
4421 recursive: self.parse_keyword(Keyword::RECURSIVE),
4422 cte_tables: self.parse_comma_separated(Parser::parse_cte)?,
4423 })
4424 } else {
4425 None
4426 };
4427
4428 let body = self.parse_query_body(0)?;
4429
4430 let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
4431 self.parse_comma_separated(Parser::parse_order_by_expr)?
4432 } else {
4433 vec![]
4434 };
4435
4436 let mut limit = None;
4437 let mut offset = None;
4438 for _x in 0..2 {
4439 if limit.is_none() && self.parse_keyword(Keyword::LIMIT) {
4440 limit = self.parse_limit()?
4441 }
4442
4443 if offset.is_none() && self.parse_keyword(Keyword::OFFSET) {
4444 offset = Some(self.parse_offset()?)
4445 }
4446 }
4447
4448 let fetch = if self.parse_keyword(Keyword::FETCH) {
4449 if limit.is_some() {
4450 parser_err!("Cannot specify both LIMIT and FETCH");
4451 }
4452 let fetch = self.parse_fetch()?;
4453 if fetch.with_ties && order_by.is_empty() {
4454 parser_err!("WITH TIES cannot be specified without ORDER BY clause");
4455 }
4456 Some(fetch)
4457 } else {
4458 None
4459 };
4460
4461 Ok(Query {
4462 with,
4463 body,
4464 order_by,
4465 limit,
4466 offset,
4467 fetch,
4468 })
4469 }
4470
4471 fn parse_cte(&mut self) -> ModalResult<Cte> {
4473 let name = self.parse_identifier_non_reserved()?;
4474 let cte = if self.parse_keyword(Keyword::AS) {
4475 let cte_inner = self.parse_cte_inner()?;
4476 let alias = TableAlias {
4477 name,
4478 columns: vec![],
4479 };
4480 Cte { alias, cte_inner }
4481 } else {
4482 let columns = self.parse_parenthesized_column_list(Optional)?;
4483 self.expect_keyword(Keyword::AS)?;
4484 let cte_inner = self.parse_cte_inner()?;
4485 let alias = TableAlias { name, columns };
4486 Cte { alias, cte_inner }
4487 };
4488 Ok(cte)
4489 }
4490
4491 fn parse_cte_inner(&mut self) -> ModalResult<CteInner> {
4492 match self.expect_token(&Token::LParen) {
4493 Ok(()) => {
4494 let query = self.parse_query()?;
4495 self.expect_token(&Token::RParen)?;
4496 Ok(CteInner::Query(Box::new(query)))
4497 }
4498 _ => {
4499 let changelog = self.parse_identifier_non_reserved()?;
4500 if changelog.to_string().to_lowercase() != "changelog" {
4501 parser_err!("Expected 'changelog' but found '{}'", changelog);
4502 }
4503 self.expect_keyword(Keyword::FROM)?;
4504 Ok(CteInner::ChangeLog(self.parse_object_name()?))
4505 }
4506 }
4507 }
4508
4509 fn parse_query_body(&mut self, precedence: u8) -> ModalResult<SetExpr> {
4518 let mut expr = if self.parse_keyword(Keyword::SELECT) {
4521 SetExpr::Select(Box::new(self.parse_select()?))
4522 } else if self.consume_token(&Token::LParen) {
4523 let subquery = self.parse_query()?;
4525 self.expect_token(&Token::RParen)?;
4526 SetExpr::Query(Box::new(subquery))
4527 } else if self.parse_keyword(Keyword::VALUES) {
4528 SetExpr::Values(self.parse_values()?)
4529 } else {
4530 return self.expected("SELECT, VALUES, or a subquery in the query body");
4531 };
4532
4533 loop {
4534 let op = self.parse_set_operator(&self.peek_token().token);
4536 let next_precedence = match op {
4537 Some(SetOperator::Union) | Some(SetOperator::Except) => 10,
4539 Some(SetOperator::Intersect) => 20,
4541 None => break,
4543 };
4544 if precedence >= next_precedence {
4545 break;
4546 }
4547 self.next_token(); let all = self.parse_keyword(Keyword::ALL);
4550 let corresponding = self.parse_corresponding()?;
4551
4552 expr = SetExpr::SetOperation {
4553 left: Box::new(expr),
4554 op: op.unwrap(),
4555 corresponding,
4556 all,
4557 right: Box::new(self.parse_query_body(next_precedence)?),
4558 };
4559 }
4560
4561 Ok(expr)
4562 }
4563
4564 fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator> {
4565 match token {
4566 Token::Word(w) if w.keyword == Keyword::UNION => Some(SetOperator::Union),
4567 Token::Word(w) if w.keyword == Keyword::EXCEPT => Some(SetOperator::Except),
4568 Token::Word(w) if w.keyword == Keyword::INTERSECT => Some(SetOperator::Intersect),
4569 _ => None,
4570 }
4571 }
4572
4573 fn parse_corresponding(&mut self) -> ModalResult<Corresponding> {
4574 let corresponding = if self.parse_keyword(Keyword::CORRESPONDING) {
4575 let column_list = if self.parse_keyword(Keyword::BY) {
4576 Some(self.parse_parenthesized_column_list(IsOptional::Mandatory)?)
4577 } else {
4578 None
4579 };
4580 Corresponding::with_column_list(column_list)
4581 } else {
4582 Corresponding::none()
4583 };
4584 Ok(corresponding)
4585 }
4586
4587 pub fn parse_select(&mut self) -> ModalResult<Select> {
4590 let distinct = self.parse_all_or_distinct_on()?;
4591
4592 let projection = self.parse_comma_separated(Parser::parse_select_item)?;
4593
4594 let from = if self.parse_keyword(Keyword::FROM) {
4600 self.parse_comma_separated(Parser::parse_table_and_joins)?
4601 } else {
4602 vec![]
4603 };
4604 let mut lateral_views = vec![];
4605 loop {
4606 if self.parse_keywords(&[Keyword::LATERAL, Keyword::VIEW]) {
4607 let outer = self.parse_keyword(Keyword::OUTER);
4608 let lateral_view = self.parse_expr()?;
4609 let lateral_view_name = self.parse_object_name()?;
4610 let lateral_col_alias = self
4611 .parse_comma_separated(|parser| {
4612 parser.parse_optional_alias(&[
4613 Keyword::WHERE,
4614 Keyword::GROUP,
4615 Keyword::CLUSTER,
4616 Keyword::HAVING,
4617 Keyword::LATERAL,
4618 ]) })?
4620 .into_iter()
4621 .flatten()
4622 .collect();
4623
4624 lateral_views.push(LateralView {
4625 lateral_view,
4626 lateral_view_name,
4627 lateral_col_alias,
4628 outer,
4629 });
4630 } else {
4631 break;
4632 }
4633 }
4634
4635 let selection = if self.parse_keyword(Keyword::WHERE) {
4636 Some(self.parse_expr()?)
4637 } else {
4638 None
4639 };
4640
4641 let group_by = if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
4642 self.parse_comma_separated(Parser::parse_group_by_expr)?
4643 } else {
4644 vec![]
4645 };
4646
4647 let having = if self.parse_keyword(Keyword::HAVING) {
4648 Some(self.parse_expr()?)
4649 } else {
4650 None
4651 };
4652
4653 Ok(Select {
4654 distinct,
4655 projection,
4656 from,
4657 lateral_views,
4658 selection,
4659 group_by,
4660 having,
4661 })
4662 }
4663
4664 pub fn parse_set(&mut self) -> ModalResult<Statement> {
4665 let modifier = self.parse_one_of_keywords(&[Keyword::SESSION, Keyword::LOCAL]);
4666 if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE]) {
4667 let value = alt((
4668 Keyword::DEFAULT.value(SetTimeZoneValue::Default),
4669 Keyword::LOCAL.value(SetTimeZoneValue::Local),
4670 preceded(
4671 Keyword::INTERVAL,
4672 cut_err(Self::parse_literal_interval.try_map(|e| match e {
4673 Expr::Value(v) => match v {
4676 Value::Interval { value, .. } => {
4677 if value != "+00:00" {
4678 return Err(StrError("only support \"+00:00\" ".into()));
4679 }
4680 Ok(SetTimeZoneValue::Ident(Ident::with_quote_unchecked(
4681 '\'',
4682 "UTC".to_owned(),
4683 )))
4684 }
4685 _ => Err(StrError("expect Value::Interval".into())),
4686 },
4687 _ => Err(StrError("expect Expr::Value".into())),
4688 })),
4689 ),
4690 Self::parse_identifier.map(SetTimeZoneValue::Ident),
4691 Self::ensure_parse_value.map(SetTimeZoneValue::Literal),
4692 ))
4693 .expect("variable")
4694 .parse_next(self)?;
4695
4696 Ok(Statement::SetTimeZone {
4697 local: modifier == Some(Keyword::LOCAL),
4698 value,
4699 })
4700 } else if self.parse_keyword(Keyword::CHARACTERISTICS) && modifier == Some(Keyword::SESSION)
4701 {
4702 self.expect_keywords(&[Keyword::AS, Keyword::TRANSACTION])?;
4703 Ok(Statement::SetTransaction {
4704 modes: self.parse_transaction_modes()?,
4705 snapshot: None,
4706 session: true,
4707 })
4708 } else if self.parse_keyword(Keyword::TRANSACTION) && modifier.is_none() {
4709 if self.parse_keyword(Keyword::SNAPSHOT) {
4710 let snapshot_id = self.ensure_parse_value()?;
4711 return Ok(Statement::SetTransaction {
4712 modes: vec![],
4713 snapshot: Some(snapshot_id),
4714 session: false,
4715 });
4716 }
4717 Ok(Statement::SetTransaction {
4718 modes: self.parse_transaction_modes()?,
4719 snapshot: None,
4720 session: false,
4721 })
4722 } else {
4723 let variable = self.parse_identifier()?;
4724
4725 if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
4726 let value = self.parse_set_variable()?;
4727 Ok(Statement::SetVariable {
4728 local: modifier == Some(Keyword::LOCAL),
4729 variable,
4730 value,
4731 })
4732 } else {
4733 self.expected("equals sign or TO")
4734 }
4735 }
4736 }
4737
4738 pub fn parse_show(&mut self) -> ModalResult<Statement> {
4742 let checkpoint = *self;
4743 if let Token::Word(w) = self.next_token().token {
4744 match w.keyword {
4745 Keyword::TABLES => {
4746 return Ok(Statement::ShowObjects {
4747 object: ShowObject::Table {
4748 schema: self.parse_from_and_identifier()?,
4749 },
4750 filter: self.parse_show_statement_filter()?,
4751 });
4752 }
4753 Keyword::INTERNAL => {
4754 self.expect_keyword(Keyword::TABLES)?;
4755 return Ok(Statement::ShowObjects {
4756 object: ShowObject::InternalTable {
4757 schema: self.parse_from_and_identifier()?,
4758 },
4759 filter: self.parse_show_statement_filter()?,
4760 });
4761 }
4762 Keyword::SOURCES => {
4763 return Ok(Statement::ShowObjects {
4764 object: ShowObject::Source {
4765 schema: self.parse_from_and_identifier()?,
4766 },
4767 filter: self.parse_show_statement_filter()?,
4768 });
4769 }
4770 Keyword::SINKS => {
4771 return Ok(Statement::ShowObjects {
4772 object: ShowObject::Sink {
4773 schema: self.parse_from_and_identifier()?,
4774 },
4775 filter: self.parse_show_statement_filter()?,
4776 });
4777 }
4778 Keyword::SUBSCRIPTIONS => {
4779 return Ok(Statement::ShowObjects {
4780 object: ShowObject::Subscription {
4781 schema: self.parse_from_and_identifier()?,
4782 },
4783 filter: self.parse_show_statement_filter()?,
4784 });
4785 }
4786 Keyword::DATABASES => {
4787 return Ok(Statement::ShowObjects {
4788 object: ShowObject::Database,
4789 filter: self.parse_show_statement_filter()?,
4790 });
4791 }
4792 Keyword::SCHEMAS => {
4793 return Ok(Statement::ShowObjects {
4794 object: ShowObject::Schema,
4795 filter: self.parse_show_statement_filter()?,
4796 });
4797 }
4798 Keyword::VIEWS => {
4799 return Ok(Statement::ShowObjects {
4800 object: ShowObject::View {
4801 schema: self.parse_from_and_identifier()?,
4802 },
4803 filter: self.parse_show_statement_filter()?,
4804 });
4805 }
4806 Keyword::MATERIALIZED => {
4807 if self.parse_keyword(Keyword::VIEWS) {
4808 return Ok(Statement::ShowObjects {
4809 object: ShowObject::MaterializedView {
4810 schema: self.parse_from_and_identifier()?,
4811 },
4812 filter: self.parse_show_statement_filter()?,
4813 });
4814 } else {
4815 return self.expected("VIEWS after MATERIALIZED");
4816 }
4817 }
4818 Keyword::COLUMNS => {
4819 if self.parse_keyword(Keyword::FROM) {
4820 return Ok(Statement::ShowObjects {
4821 object: ShowObject::Columns {
4822 table: self.parse_object_name()?,
4823 },
4824 filter: self.parse_show_statement_filter()?,
4825 });
4826 } else {
4827 return self.expected("from after columns");
4828 }
4829 }
4830 Keyword::SECRETS => {
4831 return Ok(Statement::ShowObjects {
4832 object: ShowObject::Secret {
4833 schema: self.parse_from_and_identifier()?,
4834 },
4835 filter: self.parse_show_statement_filter()?,
4836 });
4837 }
4838 Keyword::CONNECTIONS => {
4839 return Ok(Statement::ShowObjects {
4840 object: ShowObject::Connection {
4841 schema: self.parse_from_and_identifier()?,
4842 },
4843 filter: self.parse_show_statement_filter()?,
4844 });
4845 }
4846 Keyword::FUNCTIONS => {
4847 return Ok(Statement::ShowObjects {
4848 object: ShowObject::Function {
4849 schema: self.parse_from_and_identifier()?,
4850 },
4851 filter: self.parse_show_statement_filter()?,
4852 });
4853 }
4854 Keyword::INDEXES => {
4855 if self.parse_keyword(Keyword::FROM) {
4856 return Ok(Statement::ShowObjects {
4857 object: ShowObject::Indexes {
4858 table: self.parse_object_name()?,
4859 },
4860 filter: self.parse_show_statement_filter()?,
4861 });
4862 } else {
4863 return self.expected("from after indexes");
4864 }
4865 }
4866 Keyword::CLUSTER => {
4867 return Ok(Statement::ShowObjects {
4868 object: ShowObject::Cluster,
4869 filter: self.parse_show_statement_filter()?,
4870 });
4871 }
4872 Keyword::JOBS => {
4873 return Ok(Statement::ShowObjects {
4874 object: ShowObject::Jobs,
4875 filter: self.parse_show_statement_filter()?,
4876 });
4877 }
4878 Keyword::PROCESSLIST => {
4879 return Ok(Statement::ShowObjects {
4880 object: ShowObject::ProcessList,
4881 filter: self.parse_show_statement_filter()?,
4882 });
4883 }
4884 Keyword::TRANSACTION => {
4885 self.expect_keywords(&[Keyword::ISOLATION, Keyword::LEVEL])?;
4886 return Ok(Statement::ShowTransactionIsolationLevel);
4887 }
4888 Keyword::CURSORS => {
4889 return Ok(Statement::ShowObjects {
4890 object: ShowObject::Cursor,
4891 filter: None,
4892 });
4893 }
4894 Keyword::SUBSCRIPTION => {
4895 self.expect_keyword(Keyword::CURSORS)?;
4896 return Ok(Statement::ShowObjects {
4897 object: ShowObject::SubscriptionCursor,
4898 filter: None,
4899 });
4900 }
4901 _ => {}
4902 }
4903 }
4904 *self = checkpoint;
4905 Ok(Statement::ShowVariable {
4906 variable: self.parse_identifiers()?,
4907 })
4908 }
4909
4910 pub fn parse_cancel_job(&mut self) -> ModalResult<Statement> {
4911 match self.peek_token().token {
4913 Token::Word(w) if Keyword::JOBS == w.keyword || Keyword::JOB == w.keyword => {
4914 self.next_token();
4915 }
4916 _ => return self.expected("JOBS or JOB after CANCEL"),
4917 }
4918
4919 let mut job_ids = vec![];
4920 loop {
4921 job_ids.push(self.parse_literal_uint()? as u32);
4922 if !self.consume_token(&Token::Comma) {
4923 break;
4924 }
4925 }
4926 Ok(Statement::CancelJobs(JobIdents(job_ids)))
4927 }
4928
4929 pub fn parse_kill_process(&mut self) -> ModalResult<Statement> {
4930 let process_id = self.parse_literal_uint()? as i32;
4931 Ok(Statement::Kill(process_id))
4932 }
4933
4934 pub fn parse_from_and_identifier(&mut self) -> ModalResult<Option<Ident>> {
4937 if self.parse_keyword(Keyword::FROM) {
4938 Ok(Some(self.parse_identifier_non_reserved()?))
4939 } else {
4940 Ok(None)
4941 }
4942 }
4943
4944 pub fn parse_show_create(&mut self) -> ModalResult<Statement> {
4946 if let Token::Word(w) = self.next_token().token {
4947 let show_type = match w.keyword {
4948 Keyword::TABLE => ShowCreateType::Table,
4949 Keyword::MATERIALIZED => {
4950 if self.parse_keyword(Keyword::VIEW) {
4951 ShowCreateType::MaterializedView
4952 } else {
4953 return self.expected("VIEW after MATERIALIZED");
4954 }
4955 }
4956 Keyword::VIEW => ShowCreateType::View,
4957 Keyword::INDEX => ShowCreateType::Index,
4958 Keyword::SOURCE => ShowCreateType::Source,
4959 Keyword::SINK => ShowCreateType::Sink,
4960 Keyword::SUBSCRIPTION => ShowCreateType::Subscription,
4961 Keyword::FUNCTION => ShowCreateType::Function,
4962 _ => return self.expected(
4963 "TABLE, MATERIALIZED VIEW, VIEW, INDEX, FUNCTION, SOURCE, SUBSCRIPTION or SINK",
4964 ),
4965 };
4966 return Ok(Statement::ShowCreateObject {
4967 create_type: show_type,
4968 name: self.parse_object_name()?,
4969 });
4970 }
4971 self.expected(
4972 "TABLE, MATERIALIZED VIEW, VIEW, INDEX, FUNCTION, SOURCE, SUBSCRIPTION or SINK",
4973 )
4974 }
4975
4976 pub fn parse_show_statement_filter(&mut self) -> ModalResult<Option<ShowStatementFilter>> {
4977 if self.parse_keyword(Keyword::LIKE) {
4978 Ok(Some(ShowStatementFilter::Like(
4979 self.parse_literal_string()?,
4980 )))
4981 } else if self.parse_keyword(Keyword::ILIKE) {
4982 Ok(Some(ShowStatementFilter::ILike(
4983 self.parse_literal_string()?,
4984 )))
4985 } else if self.parse_keyword(Keyword::WHERE) {
4986 Ok(Some(ShowStatementFilter::Where(self.parse_expr()?)))
4987 } else {
4988 Ok(None)
4989 }
4990 }
4991
4992 pub fn parse_table_and_joins(&mut self) -> ModalResult<TableWithJoins> {
4993 let relation = self.parse_table_factor()?;
4994
4995 let mut joins = vec![];
4999 loop {
5000 let join = if self.parse_keyword(Keyword::CROSS) {
5001 let join_operator = if self.parse_keyword(Keyword::JOIN) {
5002 JoinOperator::CrossJoin
5003 } else {
5004 return self.expected("JOIN after CROSS");
5005 };
5006 Join {
5007 relation: self.parse_table_factor()?,
5008 join_operator,
5009 }
5010 } else {
5011 let (natural, asof) =
5012 match self.parse_one_of_keywords(&[Keyword::NATURAL, Keyword::ASOF]) {
5013 Some(Keyword::NATURAL) => (true, false),
5014 Some(Keyword::ASOF) => (false, true),
5015 Some(_) => unreachable!(),
5016 None => (false, false),
5017 };
5018 let peek_keyword = if let Token::Word(w) = self.peek_token().token {
5019 w.keyword
5020 } else {
5021 Keyword::NoKeyword
5022 };
5023
5024 let join_operator_type = match peek_keyword {
5025 Keyword::INNER | Keyword::JOIN => {
5026 let _ = self.parse_keyword(Keyword::INNER);
5027 self.expect_keyword(Keyword::JOIN)?;
5028 if asof {
5029 JoinOperator::AsOfInner
5030 } else {
5031 JoinOperator::Inner
5032 }
5033 }
5034 kw @ Keyword::LEFT | kw @ Keyword::RIGHT | kw @ Keyword::FULL => {
5035 let checkpoint = *self;
5036 let _ = self.next_token();
5037 let _ = self.parse_keyword(Keyword::OUTER);
5038 self.expect_keyword(Keyword::JOIN)?;
5039 if asof {
5040 if Keyword::LEFT == kw {
5041 JoinOperator::AsOfLeft
5042 } else {
5043 return self.expected_at(
5044 checkpoint,
5045 "LEFT after ASOF. RIGHT or FULL are not supported",
5046 );
5047 }
5048 } else {
5049 match kw {
5050 Keyword::LEFT => JoinOperator::LeftOuter,
5051 Keyword::RIGHT => JoinOperator::RightOuter,
5052 Keyword::FULL => JoinOperator::FullOuter,
5053 _ => unreachable!(),
5054 }
5055 }
5056 }
5057 Keyword::OUTER => {
5058 return self.expected("LEFT, RIGHT, or FULL");
5059 }
5060 _ if natural => {
5061 return self.expected("a join type after NATURAL");
5062 }
5063 _ if asof => {
5064 return self.expected("a join type after ASOF");
5065 }
5066 _ => break,
5067 };
5068 let relation = self.parse_table_factor()?;
5069 let join_constraint = self.parse_join_constraint(natural)?;
5070 let join_operator = join_operator_type(join_constraint);
5071 let need_constraint = match join_operator {
5072 JoinOperator::Inner(JoinConstraint::None) => Some("INNER JOIN"),
5073 JoinOperator::AsOfInner(JoinConstraint::None) => Some("ASOF INNER JOIN"),
5074 JoinOperator::AsOfLeft(JoinConstraint::None) => Some("ASOF LEFT JOIN"),
5075 _ => None,
5076 };
5077 if let Some(join_type) = need_constraint {
5078 return self.expected(&format!("join constraint after {join_type}"));
5079 }
5080
5081 Join {
5082 relation,
5083 join_operator,
5084 }
5085 };
5086 joins.push(join);
5087 }
5088 Ok(TableWithJoins { relation, joins })
5089 }
5090
5091 pub fn parse_table_factor(&mut self) -> ModalResult<TableFactor> {
5093 if self.parse_keyword(Keyword::LATERAL) {
5094 if !self.consume_token(&Token::LParen) {
5096 self.expected("subquery after LATERAL")?;
5097 }
5098 self.parse_derived_table_factor(Lateral)
5099 } else if self.consume_token(&Token::LParen) {
5100 match self.peek_token().token {
5120 Token::Word(w)
5121 if [Keyword::SELECT, Keyword::WITH, Keyword::VALUES].contains(&w.keyword) =>
5122 {
5123 return self.parse_derived_table_factor(NotLateral);
5124 }
5125 _ => {}
5126 };
5127 if self.peek_token() == Token::LParen {
5131 return_ok_if_some!(
5132 self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))
5133 );
5134 }
5135
5136 let table_and_joins = self.parse_table_and_joins()?;
5143
5144 #[allow(clippy::if_same_then_else)]
5145 if !table_and_joins.joins.is_empty() {
5146 self.expect_token(&Token::RParen)?;
5147 Ok(TableFactor::NestedJoin(Box::new(table_and_joins))) } else if let TableFactor::NestedJoin(_) = &table_and_joins.relation {
5149 self.expect_token(&Token::RParen)?;
5152 Ok(TableFactor::NestedJoin(Box::new(table_and_joins)))
5153 } else {
5154 parser_err!(
5157 "Expected joined table, found: {table_and_joins}, next_token: {}",
5158 self.peek_token()
5159 );
5160 }
5161 } else {
5162 let name = self.parse_object_name()?;
5163 if self.peek_token() == Token::LParen {
5164 let arg_list = self.parse_argument_list()?;
5167 if arg_list.distinct {
5168 parser_err!("DISTINCT is not supported in table-valued function calls");
5169 }
5170 if !arg_list.order_by.is_empty() {
5171 parser_err!("ORDER BY is not supported in table-valued function calls");
5172 }
5173 if arg_list.ignore_nulls {
5174 parser_err!("IGNORE NULLS is not supported in table-valued function calls");
5175 }
5176
5177 let args = arg_list.args;
5178 let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
5179 let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5180
5181 Ok(TableFactor::TableFunction {
5182 name,
5183 alias,
5184 args,
5185 with_ordinality,
5186 })
5187 } else {
5188 let as_of = opt(Self::parse_as_of).parse_next(self)?;
5189 let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5190 Ok(TableFactor::Table { name, alias, as_of })
5191 }
5192 }
5193 }
5194
5195 pub fn parse_derived_table_factor(&mut self, lateral: IsLateral) -> ModalResult<TableFactor> {
5196 let subquery = Box::new(self.parse_query()?);
5197 self.expect_token(&Token::RParen)?;
5198 let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5199 Ok(TableFactor::Derived {
5200 lateral: match lateral {
5201 Lateral => true,
5202 NotLateral => false,
5203 },
5204 subquery,
5205 alias,
5206 })
5207 }
5208
5209 fn parse_join_constraint(&mut self, natural: bool) -> ModalResult<JoinConstraint> {
5210 if natural {
5211 Ok(JoinConstraint::Natural)
5212 } else if self.parse_keyword(Keyword::ON) {
5213 let constraint = self.parse_expr()?;
5214 Ok(JoinConstraint::On(constraint))
5215 } else if self.parse_keyword(Keyword::USING) {
5216 let columns = self.parse_parenthesized_column_list(Mandatory)?;
5217 Ok(JoinConstraint::Using(columns))
5218 } else {
5219 Ok(JoinConstraint::None)
5220 }
5222 }
5223
5224 pub fn parse_grant(&mut self) -> ModalResult<Statement> {
5226 let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
5227
5228 self.expect_keyword(Keyword::TO)?;
5229 let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
5230
5231 let with_grant_option =
5232 self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
5233
5234 let granted_by = self
5235 .parse_keywords(&[Keyword::GRANTED, Keyword::BY])
5236 .then(|| self.parse_identifier().unwrap());
5237
5238 Ok(Statement::Grant {
5239 privileges,
5240 objects,
5241 grantees,
5242 with_grant_option,
5243 granted_by,
5244 })
5245 }
5246
5247 fn parse_grant_revoke_privileges_objects(&mut self) -> ModalResult<(Privileges, GrantObjects)> {
5248 let privileges = if self.parse_keyword(Keyword::ALL) {
5249 Privileges::All {
5250 with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
5251 }
5252 } else {
5253 Privileges::Actions(
5254 self.parse_comma_separated(Parser::parse_grant_permission)?
5255 .into_iter()
5256 .map(|(kw, columns)| match kw {
5257 Keyword::CONNECT => Action::Connect,
5258 Keyword::CREATE => Action::Create,
5259 Keyword::DELETE => Action::Delete,
5260 Keyword::EXECUTE => Action::Execute,
5261 Keyword::INSERT => Action::Insert { columns },
5262 Keyword::REFERENCES => Action::References { columns },
5263 Keyword::SELECT => Action::Select { columns },
5264 Keyword::TEMPORARY => Action::Temporary,
5265 Keyword::TRIGGER => Action::Trigger,
5266 Keyword::TRUNCATE => Action::Truncate,
5267 Keyword::UPDATE => Action::Update { columns },
5268 Keyword::USAGE => Action::Usage,
5269 _ => unreachable!(),
5270 })
5271 .collect(),
5272 )
5273 };
5274
5275 self.expect_keyword(Keyword::ON)?;
5276
5277 let objects = if self.parse_keywords(&[
5278 Keyword::ALL,
5279 Keyword::TABLES,
5280 Keyword::IN,
5281 Keyword::SCHEMA,
5282 ]) {
5283 GrantObjects::AllTablesInSchema {
5284 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5285 }
5286 } else if self.parse_keywords(&[
5287 Keyword::ALL,
5288 Keyword::SEQUENCES,
5289 Keyword::IN,
5290 Keyword::SCHEMA,
5291 ]) {
5292 GrantObjects::AllSequencesInSchema {
5293 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5294 }
5295 } else if self.parse_keywords(&[
5296 Keyword::ALL,
5297 Keyword::SOURCES,
5298 Keyword::IN,
5299 Keyword::SCHEMA,
5300 ]) {
5301 GrantObjects::AllSourcesInSchema {
5302 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5303 }
5304 } else if self.parse_keywords(&[Keyword::ALL, Keyword::SINKS, Keyword::IN, Keyword::SCHEMA])
5305 {
5306 GrantObjects::AllSinksInSchema {
5307 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5308 }
5309 } else if self.parse_keywords(&[
5310 Keyword::ALL,
5311 Keyword::MATERIALIZED,
5312 Keyword::VIEWS,
5313 Keyword::IN,
5314 Keyword::SCHEMA,
5315 ]) {
5316 GrantObjects::AllMviewsInSchema {
5317 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5318 }
5319 } else if self.parse_keywords(&[Keyword::ALL, Keyword::VIEWS, Keyword::IN, Keyword::SCHEMA])
5320 {
5321 GrantObjects::AllViewsInSchema {
5322 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5323 }
5324 } else if self.parse_keywords(&[
5325 Keyword::ALL,
5326 Keyword::FUNCTIONS,
5327 Keyword::IN,
5328 Keyword::SCHEMA,
5329 ]) {
5330 GrantObjects::AllFunctionsInSchema {
5331 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5332 }
5333 } else if self.parse_keywords(&[
5334 Keyword::ALL,
5335 Keyword::SECRETS,
5336 Keyword::IN,
5337 Keyword::SCHEMA,
5338 ]) {
5339 GrantObjects::AllSecretsInSchema {
5340 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5341 }
5342 } else if self.parse_keywords(&[
5343 Keyword::ALL,
5344 Keyword::CONNECTIONS,
5345 Keyword::IN,
5346 Keyword::SCHEMA,
5347 ]) {
5348 GrantObjects::AllConnectionsInSchema {
5349 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5350 }
5351 } else if self.parse_keywords(&[
5352 Keyword::ALL,
5353 Keyword::SUBSCRIPTIONS,
5354 Keyword::IN,
5355 Keyword::SCHEMA,
5356 ]) {
5357 GrantObjects::AllSubscriptionsInSchema {
5358 schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5359 }
5360 } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
5361 GrantObjects::Mviews(self.parse_comma_separated(Parser::parse_object_name)?)
5362 } else {
5363 let object_type = self.parse_one_of_keywords(&[
5364 Keyword::SEQUENCE,
5365 Keyword::DATABASE,
5366 Keyword::SCHEMA,
5367 Keyword::TABLE,
5368 Keyword::SOURCE,
5369 Keyword::SINK,
5370 Keyword::VIEW,
5371 Keyword::SUBSCRIPTION,
5372 Keyword::FUNCTION,
5373 Keyword::CONNECTION,
5374 Keyword::SECRET,
5375 ]);
5376 if let Some(Keyword::FUNCTION) = object_type {
5377 let func_descs = self.parse_comma_separated(Parser::parse_function_desc)?;
5378 GrantObjects::Functions(func_descs)
5379 } else {
5380 let objects = self.parse_comma_separated(Parser::parse_object_name);
5381 match object_type {
5382 Some(Keyword::DATABASE) => GrantObjects::Databases(objects?),
5383 Some(Keyword::SCHEMA) => GrantObjects::Schemas(objects?),
5384 Some(Keyword::SEQUENCE) => GrantObjects::Sequences(objects?),
5385 Some(Keyword::SOURCE) => GrantObjects::Sources(objects?),
5386 Some(Keyword::SINK) => GrantObjects::Sinks(objects?),
5387 Some(Keyword::VIEW) => GrantObjects::Views(objects?),
5388 Some(Keyword::SUBSCRIPTION) => GrantObjects::Subscriptions(objects?),
5389 Some(Keyword::CONNECTION) => GrantObjects::Connections(objects?),
5390 Some(Keyword::SECRET) => GrantObjects::Secrets(objects?),
5391 Some(Keyword::TABLE) | None => GrantObjects::Tables(objects?),
5392 _ => unreachable!(),
5393 }
5394 }
5395 };
5396
5397 Ok((privileges, objects))
5398 }
5399
5400 fn parse_grant_permission(&mut self) -> ModalResult<(Keyword, Option<Vec<Ident>>)> {
5401 let kw = self.expect_one_of_keywords(&[
5402 Keyword::CONNECT,
5403 Keyword::CREATE,
5404 Keyword::DELETE,
5405 Keyword::EXECUTE,
5406 Keyword::INSERT,
5407 Keyword::REFERENCES,
5408 Keyword::SELECT,
5409 Keyword::TEMPORARY,
5410 Keyword::TRIGGER,
5411 Keyword::TRUNCATE,
5412 Keyword::UPDATE,
5413 Keyword::USAGE,
5414 ])?;
5415 let columns = match kw {
5416 Keyword::INSERT | Keyword::REFERENCES | Keyword::SELECT | Keyword::UPDATE => {
5417 let columns = self.parse_parenthesized_column_list(Optional)?;
5418 if columns.is_empty() {
5419 None
5420 } else {
5421 Some(columns)
5422 }
5423 }
5424 _ => None,
5425 };
5426 Ok((kw, columns))
5427 }
5428
5429 pub fn parse_revoke(&mut self) -> ModalResult<Statement> {
5431 let revoke_grant_option =
5432 self.parse_keywords(&[Keyword::GRANT, Keyword::OPTION, Keyword::FOR]);
5433 let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
5434
5435 self.expect_keyword(Keyword::FROM)?;
5436 let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
5437
5438 let granted_by = self
5439 .parse_keywords(&[Keyword::GRANTED, Keyword::BY])
5440 .then(|| self.parse_identifier().unwrap());
5441
5442 let cascade = self.parse_keyword(Keyword::CASCADE);
5443 let restrict = self.parse_keyword(Keyword::RESTRICT);
5444 if cascade && restrict {
5445 parser_err!("Cannot specify both CASCADE and RESTRICT in REVOKE");
5446 }
5447
5448 Ok(Statement::Revoke {
5449 privileges,
5450 objects,
5451 grantees,
5452 granted_by,
5453 revoke_grant_option,
5454 cascade,
5455 })
5456 }
5457
5458 pub fn parse_insert(&mut self) -> ModalResult<Statement> {
5460 self.expect_keyword(Keyword::INTO)?;
5461
5462 let table_name = self.parse_object_name()?;
5463 let columns = self.parse_parenthesized_column_list(Optional)?;
5464
5465 let source = Box::new(self.parse_query()?);
5466 let returning = self.parse_returning(Optional)?;
5467 Ok(Statement::Insert {
5468 table_name,
5469 columns,
5470 source,
5471 returning,
5472 })
5473 }
5474
5475 pub fn parse_update(&mut self) -> ModalResult<Statement> {
5476 let table_name = self.parse_object_name()?;
5477
5478 self.expect_keyword(Keyword::SET)?;
5479 let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
5480 let selection = if self.parse_keyword(Keyword::WHERE) {
5481 Some(self.parse_expr()?)
5482 } else {
5483 None
5484 };
5485 let returning = self.parse_returning(Optional)?;
5486 Ok(Statement::Update {
5487 table_name,
5488 assignments,
5489 selection,
5490 returning,
5491 })
5492 }
5493
5494 pub fn parse_assignment(&mut self) -> ModalResult<Assignment> {
5496 let id = self.parse_identifiers_non_keywords()?;
5497 self.expect_token(&Token::Eq)?;
5498
5499 let value = if self.parse_keyword(Keyword::DEFAULT) {
5500 AssignmentValue::Default
5501 } else {
5502 AssignmentValue::Expr(self.parse_expr()?)
5503 };
5504
5505 Ok(Assignment { id, value })
5506 }
5507
5508 fn parse_function_args(&mut self) -> ModalResult<(bool, FunctionArg)> {
5510 let variadic = self.parse_keyword(Keyword::VARIADIC);
5511 let arg = if self.peek_nth_token(1) == Token::RArrow {
5512 let name = self.parse_identifier()?;
5513
5514 self.expect_token(&Token::RArrow)?;
5515 let arg = self.parse_wildcard_or_expr()?.into();
5516
5517 FunctionArg::Named { name, arg }
5518 } else {
5519 FunctionArg::Unnamed(self.parse_wildcard_or_expr()?.into())
5520 };
5521 Ok((variadic, arg))
5522 }
5523
5524 pub fn parse_argument_list(&mut self) -> ModalResult<FunctionArgList> {
5525 self.expect_token(&Token::LParen)?;
5526 if self.consume_token(&Token::RParen) {
5527 Ok(FunctionArgList::empty())
5528 } else {
5529 let distinct = self.parse_all_or_distinct()?;
5530 let args = self.parse_comma_separated(Parser::parse_function_args)?;
5531 if args
5532 .iter()
5533 .take(args.len() - 1)
5534 .any(|(variadic, _)| *variadic)
5535 {
5536 parser_err!("VARIADIC argument must be the last");
5537 }
5538 let variadic = args.last().map(|(variadic, _)| *variadic).unwrap_or(false);
5539 let args = args.into_iter().map(|(_, arg)| arg).collect();
5540
5541 let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
5542 self.parse_comma_separated(Parser::parse_order_by_expr)?
5543 } else {
5544 vec![]
5545 };
5546
5547 let ignore_nulls = self.parse_keywords(&[Keyword::IGNORE, Keyword::NULLS]);
5548
5549 let arg_list = FunctionArgList {
5550 distinct,
5551 args,
5552 variadic,
5553 order_by,
5554 ignore_nulls,
5555 };
5556
5557 self.expect_token(&Token::RParen)?;
5558 Ok(arg_list)
5559 }
5560 }
5561
5562 pub fn parse_select_item(&mut self) -> ModalResult<SelectItem> {
5564 match self.parse_wildcard_or_expr()? {
5565 WildcardOrExpr::Expr(expr) => self
5566 .parse_optional_alias(keywords::RESERVED_FOR_COLUMN_ALIAS)
5567 .map(|alias| match alias {
5568 Some(alias) => SelectItem::ExprWithAlias { expr, alias },
5569 None => SelectItem::UnnamedExpr(expr),
5570 }),
5571 WildcardOrExpr::QualifiedWildcard(prefix, except) => {
5572 Ok(SelectItem::QualifiedWildcard(prefix, except))
5573 }
5574 WildcardOrExpr::ExprQualifiedWildcard(expr, prefix) => {
5575 Ok(SelectItem::ExprQualifiedWildcard(expr, prefix))
5576 }
5577 WildcardOrExpr::Wildcard(except) => Ok(SelectItem::Wildcard(except)),
5578 }
5579 }
5580
5581 pub fn parse_order_by_expr(&mut self) -> ModalResult<OrderByExpr> {
5583 let expr = self.parse_expr()?;
5584
5585 let asc = if self.parse_keyword(Keyword::ASC) {
5586 Some(true)
5587 } else if self.parse_keyword(Keyword::DESC) {
5588 Some(false)
5589 } else {
5590 None
5591 };
5592
5593 let nulls_first = if self.parse_keywords(&[Keyword::NULLS, Keyword::FIRST]) {
5594 Some(true)
5595 } else if self.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
5596 Some(false)
5597 } else {
5598 None
5599 };
5600
5601 Ok(OrderByExpr {
5602 expr,
5603 asc,
5604 nulls_first,
5605 })
5606 }
5607
5608 pub fn parse_limit(&mut self) -> ModalResult<Option<Expr>> {
5610 if self.parse_keyword(Keyword::ALL) {
5611 Ok(None)
5612 } else {
5613 let expr = self.parse_expr()?;
5614 Ok(Some(expr))
5615 }
5616 }
5617
5618 pub fn parse_offset(&mut self) -> ModalResult<String> {
5620 let value = self.parse_number_value()?;
5621 if self.consume_token(&Token::DoubleColon) {
5623 self.expect_keyword(Keyword::BIGINT)?;
5624 }
5625 _ = self.parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS]);
5626 Ok(value)
5627 }
5628
5629 pub fn parse_fetch(&mut self) -> ModalResult<Fetch> {
5631 self.expect_one_of_keywords(&[Keyword::FIRST, Keyword::NEXT])?;
5632 let quantity = if self
5633 .parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])
5634 .is_some()
5635 {
5636 None
5637 } else {
5638 let quantity = self.parse_number_value()?;
5639 self.expect_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])?;
5640 Some(quantity)
5641 };
5642 let with_ties = if self.parse_keyword(Keyword::ONLY) {
5643 false
5644 } else if self.parse_keywords(&[Keyword::WITH, Keyword::TIES]) {
5645 true
5646 } else {
5647 return self.expected("one of ONLY or WITH TIES");
5648 };
5649 Ok(Fetch {
5650 with_ties,
5651 quantity,
5652 })
5653 }
5654
5655 pub fn parse_values(&mut self) -> ModalResult<Values> {
5656 let values = self.parse_comma_separated(|parser| {
5657 parser.expect_token(&Token::LParen)?;
5658 let exprs = parser.parse_comma_separated(Parser::parse_expr)?;
5659 parser.expect_token(&Token::RParen)?;
5660 Ok(exprs)
5661 })?;
5662 Ok(Values(values))
5663 }
5664
5665 pub fn parse_start_transaction(&mut self) -> ModalResult<Statement> {
5666 self.expect_keyword(Keyword::TRANSACTION)?;
5667 Ok(Statement::StartTransaction {
5668 modes: self.parse_transaction_modes()?,
5669 })
5670 }
5671
5672 pub fn parse_begin(&mut self) -> ModalResult<Statement> {
5673 let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
5674 Ok(Statement::Begin {
5675 modes: self.parse_transaction_modes()?,
5676 })
5677 }
5678
5679 pub fn parse_transaction_modes(&mut self) -> ModalResult<Vec<TransactionMode>> {
5680 let mut modes = vec![];
5681 let mut required = false;
5682 loop {
5683 let mode = if self.parse_keywords(&[Keyword::ISOLATION, Keyword::LEVEL]) {
5684 let iso_level = if self.parse_keywords(&[Keyword::READ, Keyword::UNCOMMITTED]) {
5685 TransactionIsolationLevel::ReadUncommitted
5686 } else if self.parse_keywords(&[Keyword::READ, Keyword::COMMITTED]) {
5687 TransactionIsolationLevel::ReadCommitted
5688 } else if self.parse_keywords(&[Keyword::REPEATABLE, Keyword::READ]) {
5689 TransactionIsolationLevel::RepeatableRead
5690 } else if self.parse_keyword(Keyword::SERIALIZABLE) {
5691 TransactionIsolationLevel::Serializable
5692 } else {
5693 self.expected("isolation level")?
5694 };
5695 TransactionMode::IsolationLevel(iso_level)
5696 } else if self.parse_keywords(&[Keyword::READ, Keyword::ONLY]) {
5697 TransactionMode::AccessMode(TransactionAccessMode::ReadOnly)
5698 } else if self.parse_keywords(&[Keyword::READ, Keyword::WRITE]) {
5699 TransactionMode::AccessMode(TransactionAccessMode::ReadWrite)
5700 } else if required {
5701 self.expected("transaction mode")?
5702 } else {
5703 break;
5704 };
5705 modes.push(mode);
5706 required = self.consume_token(&Token::Comma);
5711 }
5712 Ok(modes)
5713 }
5714
5715 pub fn parse_commit(&mut self) -> ModalResult<Statement> {
5716 Ok(Statement::Commit {
5717 chain: self.parse_commit_rollback_chain()?,
5718 })
5719 }
5720
5721 pub fn parse_rollback(&mut self) -> ModalResult<Statement> {
5722 Ok(Statement::Rollback {
5723 chain: self.parse_commit_rollback_chain()?,
5724 })
5725 }
5726
5727 pub fn parse_commit_rollback_chain(&mut self) -> ModalResult<bool> {
5728 let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
5729 if self.parse_keyword(Keyword::AND) {
5730 let chain = !self.parse_keyword(Keyword::NO);
5731 self.expect_keyword(Keyword::CHAIN)?;
5732 Ok(chain)
5733 } else {
5734 Ok(false)
5735 }
5736 }
5737
5738 fn parse_deallocate(&mut self) -> ModalResult<Statement> {
5739 let prepare = self.parse_keyword(Keyword::PREPARE);
5740 let name = self.parse_identifier()?;
5741 Ok(Statement::Deallocate { name, prepare })
5742 }
5743
5744 fn parse_execute(&mut self) -> ModalResult<Statement> {
5745 let name = self.parse_identifier()?;
5746
5747 let mut parameters = vec![];
5748 if self.consume_token(&Token::LParen) {
5749 parameters = self.parse_comma_separated(Parser::parse_expr)?;
5750 self.expect_token(&Token::RParen)?;
5751 }
5752
5753 Ok(Statement::Execute { name, parameters })
5754 }
5755
5756 fn parse_prepare(&mut self) -> ModalResult<Statement> {
5757 let name = self.parse_identifier()?;
5758
5759 let mut data_types = vec![];
5760 if self.consume_token(&Token::LParen) {
5761 data_types = self.parse_comma_separated(Parser::parse_data_type)?;
5762 self.expect_token(&Token::RParen)?;
5763 }
5764
5765 self.expect_keyword(Keyword::AS)?;
5766 let statement = Box::new(self.parse_statement()?);
5767 Ok(Statement::Prepare {
5768 name,
5769 data_types,
5770 statement,
5771 })
5772 }
5773
5774 fn parse_comment(&mut self) -> ModalResult<Statement> {
5775 self.expect_keyword(Keyword::ON)?;
5776 let checkpoint = *self;
5777 let token = self.next_token();
5778
5779 let (object_type, object_name) = match token.token {
5780 Token::Word(w) if w.keyword == Keyword::COLUMN => {
5781 let object_name = self.parse_object_name()?;
5782 (CommentObject::Column, object_name)
5783 }
5784 Token::Word(w) if w.keyword == Keyword::TABLE => {
5785 let object_name = self.parse_object_name()?;
5786 (CommentObject::Table, object_name)
5787 }
5788 _ => self.expected_at(checkpoint, "comment object_type")?,
5789 };
5790
5791 self.expect_keyword(Keyword::IS)?;
5792 let comment = if self.parse_keyword(Keyword::NULL) {
5793 None
5794 } else {
5795 Some(self.parse_literal_string()?)
5796 };
5797 Ok(Statement::Comment {
5798 object_type,
5799 object_name,
5800 comment,
5801 })
5802 }
5803
5804 fn parse_use(&mut self) -> ModalResult<Statement> {
5805 let db_name = self.parse_object_name()?;
5806 Ok(Statement::Use { db_name })
5807 }
5808}
5809
5810impl Word {
5811 pub fn to_ident(&self) -> ModalResult<Ident> {
5813 if self.value.is_empty() {
5814 parser_err!("zero-length delimited identifier at or near \"{self}\"")
5815 } else {
5816 Ok(Ident {
5817 value: self.value.clone(),
5818 quote_style: self.quote_style,
5819 })
5820 }
5821 }
5822}
5823
5824#[cfg(test)]
5825mod tests {
5826 use super::*;
5827 use crate::test_utils::run_parser_method;
5828
5829 #[test]
5830 fn test_parse_integer_min() {
5831 let min_bigint = "-9223372036854775808";
5832 run_parser_method(min_bigint, |parser| {
5833 assert_eq!(
5834 parser.parse_expr().unwrap(),
5835 Expr::Value(Value::Number("-9223372036854775808".to_owned()))
5836 )
5837 });
5838 }
5839}