cloud-fan commented on code in PR #40856:
URL: https://github.com/apache/spark/pull/40856#discussion_r1173547503
##########
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:
so the idea is, if a CTE relation A is referenced by another CTE relation B,
and relation B has no references, we should update the relation A reference
count to exclude the references from relation B? Can we add comments to write
it down?
--
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]