milanisvet commented on code in PR #49232:
URL: https://github.com/apache/spark/pull/49232#discussion_r1898006150
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CTESubstitution.scala:
##########
@@ -247,58 +259,137 @@ object CTESubstitution extends Rule[LogicalPlan] {
// NOTE: we must call `traverseAndSubstituteCTE` before
`substituteCTE`, as the relations
// in the inner CTE have higher priority over the relations in the
outer CTE when resolving
// inner CTE relations. For example:
- // WITH t1 AS (SELECT 1)
- // t2 AS (
- // WITH t1 AS (SELECT 2)
- // WITH t3 AS (SELECT * FROM t1)
- // )
+ // WITH
+ // t1 AS (SELECT 1),
+ // t2 AS (
+ // WITH
+ // t1 AS (SELECT 2),
+ // t3 AS (SELECT * FROM t1)
+ // SELECT * FROM t1
+ // )
+ // SELECT * FROM t2
// t3 should resolve the t1 to `SELECT 2` instead of `SELECT 1`.
- traverseAndSubstituteCTE(relation, forceInline, resolvedCTERelations,
cteDefs)._1
+ //
+ // When recursion allowed:
+ // - don't add current definition to outer definitions of
`traverseAndSubstituteCTE()` to
+ // prevent recursion inside inner CTEs.
+ // E.g. the following query will not resolve `t1` within `t2`:
+ // WITH RECURSIVE
+ // t1 AS (
+ // SELECT 1 AS level
+ // UNION (
+ // WITH t2 AS (SELECT level + 1 FROM t1 WHERE level < 10)
+ // SELECT * FROM t2
+ // )
+ // )
+ // SELECT * FROM t1
+ // - remove definitions that conflict with current relation `name`
from outer definitions of
+ // `traverseAndSubstituteCTE()` to prevent weird resolutions.
+ // E.g. we don't want to resolve `t1` within `t3` to `SELECT 1`:
+ // WITH
+ // t1 AS (SELECT 1),
+ // t2 AS (
+ // WITH RECURSIVE
+ // t1 AS (
+ // SELECT 1 AS level
+ // UNION (
+ // WITH t3 AS (SELECT level + 1 FROM t1 WHERE level < 10)
Review Comment:
New comments should explain this in a better way
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]