PostgreSQL: Support `CYCLE` on a recursive CTE
diff --git a/fuzz/fuzz_seeds/postgres_cte_cycle.sql b/fuzz/fuzz_seeds/postgres_cte_cycle.sql new file mode 100644 index 0000000..32ebc00 --- /dev/null +++ b/fuzz/fuzz_seeds/postgres_cte_cycle.sql
@@ -0,0 +1 @@ +WITH RECURSIVE r (id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM r) SEARCH BREADTH FIRST BY id SET o CYCLE id SET c USING p SELECT id FROM r
diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 5d81229..46590a3 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs
@@ -103,8 +103,8 @@ }; pub use self::operator::{BinaryOperator, UnaryOperator}; pub use self::query::{ - AfterMatchSkip, ConnectByKind, Cte, CteAsMaterialized, CteSearchClause, CteSearchOrder, - Distinct, EmptyMatchesMode, ExceptSelectItem, ExcludeSelectItem, ExprWithAlias, + AfterMatchSkip, ConnectByKind, Cte, CteAsMaterialized, CteCycleClause, CteSearchClause, + CteSearchOrder, Distinct, EmptyMatchesMode, ExceptSelectItem, ExcludeSelectItem, ExprWithAlias, ExprWithAliasAndOrderBy, Fetch, ForClause, ForJson, ForXml, FormatClause, GroupByExpr, GroupByWithModifier, IdentWithAlias, IlikeSelectItem, InputFormatClause, Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator, JsonTableColumn,
diff --git a/src/ast/query.rs b/src/ast/query.rs index 35c3cd2..47f31e1 100644 --- a/src/ast/query.rs +++ b/src/ast/query.rs
@@ -813,6 +813,8 @@ pub closing_paren_token: AttachedToken, /// Optional PostgreSQL `SEARCH { BREADTH | DEPTH } FIRST BY ... SET ...` clause. pub search: Option<CteSearchClause>, + /// Optional PostgreSQL `CYCLE ... SET ... USING ...` clause. + pub cycle: Option<CteCycleClause>, } impl fmt::Display for Cte { @@ -840,6 +842,9 @@ if let Some(search) = &self.search { write!(f, " {search}")?; } + if let Some(cycle) = &self.cycle { + write!(f, " {cycle}")?; + } if let Some(ref fr) = self.from { write!(f, " FROM {fr}")?; } @@ -898,6 +903,37 @@ } } +/// The `CYCLE` clause of a recursive CTE. +/// +/// ```sql +/// CYCLE id SET is_cycle USING path +/// ``` +/// +/// [PostgreSQL](https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-CYCLE) +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct CteCycleClause { + /// The columns checked for cycles. + pub columns: Vec<Ident>, + /// The cycle mark column after `SET`. + pub mark_column: Ident, + /// The path column after `USING`. + pub path_column: Ident, +} + +impl fmt::Display for CteCycleClause { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "CYCLE {} SET {}", + display_comma_separated(&self.columns), + self.mark_column + )?; + write!(f, " USING {}", self.path_column) + } +} + /// Represents an expression behind a wildcard expansion in a projection. /// `SELECT T.* FROM T; #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
diff --git a/src/ast/spans.rs b/src/ast/spans.rs index 200eff0..50395d1 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs
@@ -35,22 +35,23 @@ ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef, ConditionalStatementBlock, ConditionalStatements, ConflictTarget, ConnectByKind, ConstraintCharacteristics, CopySource, CreateIndex, CreateRule, CreateRuleAction, CreateTable, CreateTableOptions, CreateUserMapping, - Cte, CteSearchClause, Delete, DoOption, DoStatement, DoUpdate, DropRule, ExceptSelectItem, - ExcludeConstraintElement, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, ForValues, FromTable, - Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, - FunctionArguments, GroupByExpr, HavingBound, IfStatement, IlikeSelectItem, InTarget, - IndexColumn, Insert, Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator, - JsonPath, JsonPathElem, LateralView, LimitClause, MatchRecognizePattern, Measure, Merge, - MergeAction, MergeClause, MergeInsertExpr, MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, - NamedParenthesizedList, NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, - OnConflictAction, OnInsert, OpenStatement, OperateFunctionArg, OrderBy, OrderByExpr, - OrderByKind, OutputClause, Parens, Partition, PartitionBoundValue, PivotValueSource, - ProjectionSelect, Query, RaiseStatement, RaiseStatementValue, ReferentialAction, - RefreshMaterializedView, RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, - SelectInto, SelectItem, SetExpr, Setting, SqlOption, Statement, Subscript, SymbolDefinition, - TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject, - TableOptionsClustered, TableWithJoins, Update, UpdateTableFromKind, Use, UserMappingUser, - Values, ViewColumnDef, WhileStatement, WildcardAdditionalOptions, With, WithFill, + Cte, CteCycleClause, CteSearchClause, Delete, DoOption, DoStatement, DoUpdate, DropRule, + ExceptSelectItem, ExcludeConstraintElement, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, + ForValues, FromTable, Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, + FunctionArgumentList, FunctionArguments, GroupByExpr, HavingBound, IfStatement, + IlikeSelectItem, InTarget, IndexColumn, Insert, Interpolate, InterpolateExpr, Join, + JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause, + MatchRecognizePattern, Measure, Merge, MergeAction, MergeClause, MergeInsertExpr, + MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, NamedParenthesizedList, + NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction, + OnInsert, OpenStatement, OperateFunctionArg, OrderBy, OrderByExpr, OrderByKind, OutputClause, + Parens, Partition, PartitionBoundValue, PivotValueSource, ProjectionSelect, Query, + RaiseStatement, RaiseStatementValue, ReferentialAction, RefreshMaterializedView, + RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, SelectInto, SelectItem, + SetExpr, Setting, SqlOption, Statement, Subscript, SymbolDefinition, TableAlias, + TableAliasColumnDef, TableConstraint, TableFactor, TableObject, TableOptionsClustered, + TableWithJoins, Update, UpdateTableFromKind, Use, UserMappingUser, Values, ViewColumnDef, + WhileStatement, WildcardAdditionalOptions, With, WithFill, }; /// Given an iterator of spans, return the [Span::union] of all spans. @@ -206,6 +207,7 @@ materialized: _, // enum closing_paren_token, search, + cycle, } = self; union_spans( @@ -213,7 +215,8 @@ .chain(core::iter::once(query.span())) .chain(from.iter().map(|item| item.span)) .chain(core::iter::once(closing_paren_token.0.span)) - .chain(search.iter().map(|item| item.span())), + .chain(search.iter().map(|item| item.span())) + .chain(cycle.iter().map(|item| item.span())), ) } } @@ -235,6 +238,24 @@ } } +impl Spanned for CteCycleClause { + fn span(&self) -> Span { + let CteCycleClause { + columns, + mark_column, + path_column, + } = self; + + union_spans( + columns + .iter() + .map(|item| item.span) + .chain(core::iter::once(mark_column.span)) + .chain(core::iter::once(path_column.span)), + ) + } +} + /// # partial span /// /// [SetExpr::Table] is not implemented.
diff --git a/src/dialect/generic.rs b/src/dialect/generic.rs index 3e61a45..875aaf3 100644 --- a/src/dialect/generic.rs +++ b/src/dialect/generic.rs
@@ -373,6 +373,10 @@ true } + fn supports_cte_cycle_clause(&self) -> bool { + true + } + fn supports_select_item_multi_column_alias(&self) -> bool { true }
diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs index f978a23..fcb072d 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs
@@ -466,6 +466,20 @@ false } + /// Returns true if the dialect supports the `CYCLE` clause after a common + /// table expression. + /// + /// ```sql + /// WITH RECURSIVE t(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM t) + /// CYCLE id SET is_cycle USING path + /// SELECT * FROM t + /// ``` + /// + /// [PostgreSQL](https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-CYCLE) + fn supports_cte_cycle_clause(&self) -> bool { + false + } + /// Returns true if the dialect supports `CREATE GROUP`. /// /// <https://www.postgresql.org/docs/current/sql-creategroup.html>
diff --git a/src/dialect/postgresql.rs b/src/dialect/postgresql.rs index a454376..a2d9977 100644 --- a/src/dialect/postgresql.rs +++ b/src/dialect/postgresql.rs
@@ -234,6 +234,10 @@ true } + fn supports_cte_cycle_clause(&self) -> bool { + true + } + fn identifier_quote_style(&self, _identifier: &str) -> Option<char> { Some('"') }
diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 6622c95..83f58e9 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs
@@ -16490,6 +16490,7 @@ materialized: None, closing_paren_token: closing_paren_token.into(), search: self.parse_cte_search_clause()?, + cycle: self.parse_cte_cycle_clause()?, }; if self.parse_keyword(Keyword::FROM) { cte.from = Some(self.parse_identifier()?); @@ -16536,6 +16537,7 @@ materialized: is_materialized, closing_paren_token: closing_paren_token.into(), search: self.parse_cte_search_clause()?, + cycle: self.parse_cte_cycle_clause()?, }; if self.dialect.supports_from_first_insert() && self.parse_keyword(Keyword::FROM) { cte.from = Some(self.parse_identifier()?); @@ -16568,6 +16570,23 @@ })) } + /// Parse the optional `CYCLE` clause after a CTE's closing parenthesis. + fn parse_cte_cycle_clause(&mut self) -> Result<Option<CteCycleClause>, ParserError> { + if !self.dialect.supports_cte_cycle_clause() || !self.parse_keyword(Keyword::CYCLE) { + return Ok(None); + } + let columns = self.parse_comma_separated(|parser| parser.parse_identifier())?; + self.expect_keyword_is(Keyword::SET)?; + let mark_column = self.parse_identifier()?; + self.expect_keyword_is(Keyword::USING)?; + let path_column = self.parse_identifier()?; + Ok(Some(CteCycleClause { + columns, + mark_column, + path_column, + })) + } + /// Parse a "query body", which is an expression with roughly the /// following grammar: /// ```sql
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 65e765e..70e3863 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs
@@ -8941,6 +8941,7 @@ materialized: None, closing_paren_token: AttachedToken::empty(), search: None, + cycle: None, }; assert_eq!(with.cte_tables.first().unwrap(), &expected); }
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index b936722..80e3367 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs
@@ -15067,3 +15067,86 @@ "sql parser error: Expected: one of BREADTH or DEPTH, found: FIRST at Line: 1, Column: 26" ); } + +#[test] +fn parse_cte_cycle_clause() { + for clauses in [ + "CYCLE id SET is_cycle USING path", + "CYCLE id, parent_id SET is_cycle USING path", + "CYCLE id SET is_cycle USING path, s AS (SELECT 1)", + "SEARCH DEPTH FIRST BY id SET ordercol CYCLE id SET is_cycle USING path", + ] { + pg_and_generic().verified_stmt(&format!( + "{RECURSIVE_GROUPS_CTE} {clauses} SELECT id FROM r" + )); + } + + let query = pg().verified_query(&format!( + "{RECURSIVE_GROUPS_CTE} CYCLE id SET is_cycle USING path SELECT id FROM r" + )); + assert_eq!( + query.with.unwrap().cte_tables[0].cycle, + Some(CteCycleClause { + columns: vec![Ident::new("id")], + mark_column: Ident::new("is_cycle"), + path_column: Ident::new("path"), + }) + ); + + let sql = format!("{RECURSIVE_GROUPS_CTE} CYCLE id SET is_cycle USING path SELECT id FROM r"); + let statements = Parser::parse_sql(&PostgreSqlDialect {}, &sql).unwrap(); + let Statement::Query(query) = &statements[0] else { + panic!("{sql}") + }; + let cte = &query.with.as_ref().unwrap().cte_tables[0]; + assert_eq!( + cte.cycle.as_ref().unwrap().span(), + Span::new(Location::new(1, 172), Location::new(1, 198)) + ); + assert_eq!( + cte.span(), + Span::new(Location::new(1, 16), Location::new(1, 198)) + ); + + assert_cte_display_propagates_write_error(cte, " SET "); + + assert_recursive_cte_errors( + &pg(), + &[ + ("CYCLE id SET is_cycle", "Expected: USING, found: SELECT"), + ( + "CYCLE 1 SET is_cycle USING path", + "Expected: identifier, found: 1", + ), + ("CYCLE id USING path", "Expected: SET, found: USING"), + ( + "CYCLE id SET 1 USING path", + "Expected: identifier, found: 1", + ), + ( + "CYCLE id SET is_cycle USING 1", + "Expected: identifier, found: 1", + ), + ( + "CYCLE id SET is_cycle USING path SEARCH DEPTH FIRST BY id SET ordercol", + "Expected: SELECT, VALUES, or a subquery in the query body, found: SEARCH", + ), + ], + ); + assert_recursive_cte_errors( + &all_dialects_where(|d| !d.supports_cte_cycle_clause()), + &[( + "CYCLE id SET is_cycle USING path", + "Expected: SELECT, VALUES, or a subquery in the query body, found: CYCLE", + )], + ); + assert_eq!( + Parser::parse_sql( + &GenericDialect {}, + "WITH r (SELECT 1) CYCLE id USING path SELECT 1" + ) + .unwrap_err() + .to_string(), + "sql parser error: Expected: SET, found: USING at Line: 1, Column: 28" + ); +}