Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize, Option<usize>>,
/// See [`Parser::with_infix_chain_depth`].
infix_chain_depth: bool,
}

/// Whether an alias names a select item or a table.
Expand Down Expand Up @@ -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,
}
}

Expand Down Expand Up @@ -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`])
Expand Down Expand Up @@ -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:?}");
Expand All @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {};
Expand Down
Loading