peter-toth commented on code in PR #40856:
URL: https://github.com/apache/spark/pull/40856#discussion_r1173553935
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InlineCTE.scala:
##########
@@ -70,48 +71,69 @@ case class InlineCTE(alwaysInline: Boolean = false) extends
Rule[LogicalPlan] {
def buildCTEMap(
plan: LogicalPlan,
- cteMap: mutable.HashMap[Long, (CTERelationDef, Int)]): Unit = {
+ cteMap: mutable.Map[Long, (CTERelationDef, Int, mutable.Map[Long, Int])],
+ outerCTEId: Option[Long] = None): Unit = {
plan match {
- case WithCTE(_, cteDefs) =>
+ case WithCTE(child, cteDefs) =>
+ cteDefs.foreach { cteDef =>
+ cteMap(cteDef.id) = (cteDef, 0,
mutable.Map.empty.withDefaultValue(0))
+ }
cteDefs.foreach { cteDef =>
- cteMap.put(cteDef.id, (cteDef, 0))
+ buildCTEMap(cteDef, cteMap, Some(cteDef.id))
}
+ buildCTEMap(child, cteMap, outerCTEId)
case ref: CTERelationRef =>
- val (cteDef, refCount) = cteMap(ref.cteId)
- cteMap.update(ref.cteId, (cteDef, refCount + 1))
+ val (cteDef, refCount, refMap) = cteMap(ref.cteId)
+ cteMap(ref.cteId) = (cteDef, refCount + 1, refMap)
+ outerCTEId.foreach { cteId =>
+ val (_, _, outerRefMap) = cteMap(cteId)
+ outerRefMap(ref.cteId) += 1
+ }
case _ =>
- }
-
- if (plan.containsPattern(CTE)) {
- plan.children.foreach { child =>
- buildCTEMap(child, cteMap)
- }
+ if (plan.containsPattern(CTE)) {
+ plan.children.foreach { child =>
+ buildCTEMap(child, cteMap, outerCTEId)
+ }
- plan.expressions.foreach { expr =>
- if (expr.containsAllPatterns(PLAN_EXPRESSION, CTE)) {
- expr.foreach {
- case e: SubqueryExpression =>
- buildCTEMap(e.plan, cteMap)
- case _ =>
+ plan.expressions.foreach { expr =>
+ if (expr.containsAllPatterns(PLAN_EXPRESSION, CTE)) {
+ expr.foreach {
+ case e: SubqueryExpression => buildCTEMap(e.plan, cteMap,
outerCTEId)
+ case _ =>
+ }
+ }
}
}
+ }
+ }
+
+ private def cleanCTEMap(
+ cteRefMap: mutable.SortedMap[Long, (CTERelationDef, Int,
mutable.Map[Long, Int])]
+ ) = {
+ cteRefMap.keys.toSeq.reverse.foreach { currentCTEId =>
+ val (_, currentRefCount, refMap) = cteRefMap(currentCTEId)
Review Comment:
Yes. Added scaladoc in
https://github.com/apache/spark/pull/40856/commits/ecbc4b879a8f1c397d200958b1b7ade0f6768ca5,
let me know if it needs more detailed comments.
--
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]