diff --git a/fuzz/fuzz_seeds/postgres_cte_cycle.sql b/fuzz/fuzz_seeds/postgres_cte_cycle.sql new file mode 100644 index 0000000000..32ebc00dcc --- /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 e079cf198b..40481cbcd9 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -102,8 +102,8 @@ pub use self::dml::{ }; 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 4c71ed014a..3bc0945744 100644 --- a/src/ast/query.rs +++ b/src/ast/query.rs @@ -813,6 +813,8 @@ pub struct Cte { pub closing_paren_token: AttachedToken, /// Optional PostgreSQL `SEARCH { BREADTH | DEPTH } FIRST BY ... SET ...` clause. pub search: Option, + /// Optional PostgreSQL `CYCLE ... SET ... USING ...` clause. + pub cycle: Option, } impl fmt::Display for Cte { @@ -840,6 +842,9 @@ impl fmt::Display for Cte { 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 @@ impl fmt::Display for CteSearchOrder { } } +/// 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, + /// 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 2603521250..ad3b408a69 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -35,22 +35,23 @@ use super::{ 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 @@ impl Spanned for Cte { materialized: _, // enum closing_paren_token, search, + cycle, } = self; union_spans( @@ -213,7 +215,8 @@ impl Spanned for Cte { .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 CteSearchClause { } } +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 14f3c981c2..3953c9d9b2 100644 --- a/src/dialect/generic.rs +++ b/src/dialect/generic.rs @@ -369,6 +369,10 @@ impl Dialect for GenericDialect { 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 5affae4055..3a7e700c7f 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs @@ -466,6 +466,20 @@ pub trait Dialect: Debug + Any { 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`. /// /// diff --git a/src/dialect/postgresql.rs b/src/dialect/postgresql.rs index 7034f2ba13..e8eebeb7ce 100644 --- a/src/dialect/postgresql.rs +++ b/src/dialect/postgresql.rs @@ -232,6 +232,10 @@ impl Dialect for PostgreSqlDialect { true } + fn supports_cte_cycle_clause(&self) -> bool { + true + } + fn identifier_quote_style(&self, _identifier: &str) -> Option { Some('"') } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 96fe12d3ae..adfd576f36 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -16086,6 +16086,7 @@ impl<'a> Parser<'a> { 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()?); @@ -16132,6 +16133,7 @@ impl<'a> Parser<'a> { 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()?); @@ -16164,6 +16166,23 @@ impl<'a> Parser<'a> { })) } + /// Parse the optional `CYCLE` clause after a CTE's closing parenthesis. + fn parse_cte_cycle_clause(&mut self) -> Result, 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 cee65c9888..ee9990350e 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -8909,6 +8909,7 @@ fn parse_recursive_cte() { 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 f936014062..0e8237940e 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -13578,3 +13578,47 @@ fn parse_cte_search_clause() { )], ); } + +#[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"), + }) + ); + + assert_recursive_cte_errors( + &pg(), + &[ + ("CYCLE id SET is_cycle", "Expected: USING, found: SELECT"), + ( + "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", + )], + ); +}