From 9967d39cda235d9c3062b04c0fd4609f73f3cdba Mon Sep 17 00:00:00 2001 From: Mosha Pasumansky Date: Thu, 26 Nov 2026 12:38:36 -0800 Subject: [PATCH] Parser: optionally charge infix operator chains to the recursion limit Co-Authored-By: Claude Opus 5.5 --- src/parser/mod.rs | 16 ++++++++++++++++ tests/sqlparser_common.rs | 15 +++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 8bed885c8b..6fd8d4f1e2 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -371,6 +371,8 @@ pub struct Parser<'a> { /// every level, taking 2^N time. Maps the arm's start to where a parsed /// query lacked its `)`. failed_in_subquery_positions: BTreeMap>, + /// See [`Parser::with_infix_chain_depth`]. + infix_chain_depth: bool, } /// Whether an alias names a select item or a table. @@ -426,6 +428,7 @@ impl<'a> Parser<'a> { failed_derived_table_factor_positions: BTreeSet::new(), failed_position_syntax_positions: BTreeSet::new(), failed_in_subquery_positions: BTreeMap::new(), + infix_chain_depth: false, } } @@ -460,6 +463,15 @@ impl<'a> Parser<'a> { self } + /// Also charge each operator of a chain such as `a + b + c` to the + /// recursion limit. The chain nests the resulting [`Expr`] one level per + /// operator, and dropping or serializing it recurses that deep. Defaults + /// to false. + pub fn with_infix_chain_depth(mut self, infix_chain_depth: bool) -> Self { + self.infix_chain_depth = infix_chain_depth; + self + } + /// Specify additional parser options /// /// [`Parser`] supports additional options ([`ParserOptions`]) @@ -1473,6 +1485,7 @@ impl<'a> Parser<'a> { } debug!("prefix: {expr:?}"); + let mut _chain_guards = vec![]; loop { let next_precedence = self.get_next_precedence()?; debug!("next precedence: {next_precedence:?}"); @@ -1487,6 +1500,9 @@ impl<'a> Parser<'a> { break; } + if self.infix_chain_depth { + _chain_guards.push(self.recursion_counter.try_decrease()?); + } expr = self.parse_infix(expr, next_precedence)?; } Ok(expr) diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index ead186d438..812eff446f 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -12450,6 +12450,21 @@ fn parse_deeply_nested_unary_op_hits_recursion_limits() { assert_eq!(ParserError::RecursionLimitExceeded, res.unwrap_err()); } +#[test] +fn parse_infix_chain_with_chain_depth_hits_recursion_limits() { + let dialect = GenericDialect {}; + let sql = format!("SELECT {}", vec!["1"; 100].join(" + ")); + let parse = |infix_chain_depth| { + Parser::new(&dialect) + .with_infix_chain_depth(infix_chain_depth) + .try_with_sql(&sql) + .expect("tokenize to work") + .parse_statements() + }; + parse(false).expect("chain parses without the option"); + assert_eq!(parse(true), Err(ParserError::RecursionLimitExceeded)); +} + #[test] fn parse_deeply_nested_expr_hits_recursion_limits() { let dialect = GenericDialect {};