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
1 change: 1 addition & 0 deletions fuzz/fuzz_seeds/postgres_cte_cycle.sql
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
36 changes: 36 additions & 0 deletions src/ast/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,8 @@ pub struct Cte {
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 {
Expand Down Expand Up @@ -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}")?;
}
Expand Down Expand Up @@ -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<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)]
Expand Down
55 changes: 38 additions & 17 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -206,14 +207,16 @@ impl Spanned for Cte {
materialized: _, // enum
closing_paren_token,
search,
cycle,
} = self;

union_spans(
core::iter::once(alias.span())
.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())),
)
}
}
Expand All @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
14 changes: 14 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
///
/// <https://www.postgresql.org/docs/current/sql-creategroup.html>
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/postgresql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<char> {
Some('"')
}
Expand Down
19 changes: 19 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()?);
Expand Down Expand Up @@ -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()?);
Expand Down Expand Up @@ -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<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
Expand Down
1 change: 1 addition & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
44 changes: 44 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)],
);
}
Loading