Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
[SPARK-43199][SQL] Make InlineCTE idempotent
  • Loading branch information
peter-toth committed Apr 19, 2023
commit 7dce656348e5d82e70bbd5fd30ff6593cafcf9bc
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,9 @@ trait CheckAnalysis extends PredicateHelper with LookupCatalog with QueryErrorsB

def checkAnalysis(plan: LogicalPlan): Unit = {
val inlineCTE = InlineCTE(alwaysInline = true)
val cteMap = mutable.HashMap.empty[Long, (CTERelationDef, Int)]
val cteMap = mutable.HashMap.empty[Long, (CTERelationDef, Int, mutable.Map[Long, Int])]
inlineCTE.buildCTEMap(plan, cteMap)
cteMap.values.foreach { case (relation, refCount) =>
cteMap.values.foreach { case (relation, refCount, _) =>
// If a CTE relation is never used, it will disappear after inline. Here we explicitly check
// analysis for it, to make sure the entire query plan is valid.
if (refCount == 0) checkAnalysis0(relation.child)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ case class InlineCTE(alwaysInline: Boolean = false) extends Rule[LogicalPlan] {

override def apply(plan: LogicalPlan): LogicalPlan = {
if (!plan.isInstanceOf[Subquery] && plan.containsPattern(CTE)) {
val cteMap = mutable.HashMap.empty[Long, (CTERelationDef, Int)]
val cteMap = mutable.SortedMap.empty[Long, (CTERelationDef, Int, mutable.Map[Long, Int])]
buildCTEMap(plan, cteMap)
cleanCTEMap(cteMap)
val notInlined = mutable.ArrayBuffer.empty[CTERelationDef]
val inlined = inlineCTE(plan, cteMap, notInlined)
// CTEs in SQL Commands have been inlined by `CTESubstitution` already, so it is safe to add
Expand All @@ -70,48 +71,68 @@ 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])],
referencingCTEDefId: 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, referencingCTEDefId)

case ref: CTERelationRef =>
val (cteDef, refCount) = cteMap(ref.cteId)
cteMap.update(ref.cteId, (cteDef, refCount + 1))
val (cteDef, refCount, refMap) = cteMap(ref.cteId)
referencingCTEDefId.foreach(refMap(_) += 1)
cteMap(ref.cteId) = (cteDef, refCount + 1, refMap)

case _ =>
}

if (plan.containsPattern(CTE)) {
plan.children.foreach { child =>
buildCTEMap(child, cteMap)
}
if (plan.containsPattern(CTE)) {
plan.children.foreach { child =>
buildCTEMap(child, cteMap, referencingCTEDefId)
}

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, referencingCTEDefId)
case _ =>
}
}
}
}
}
}

private def cleanCTEMap(
cteRefMap: mutable.SortedMap[Long, (CTERelationDef, Int, mutable.Map[Long, Int])]
) = {
cteRefMap.keys.toSeq.reverse.foreach { currentCTEId =>
val (_, currentRefCount, _) = cteRefMap(currentCTEId)
if (currentRefCount == 0) {
cteRefMap.keys.takeWhile(_ < currentCTEId).foreach { cteId =>
val (cteDef, refCount, refMap) = cteRefMap(cteId)
val uselessRefCount = refMap(currentCTEId)
refMap -= currentCTEId
cteRefMap(cteId) = (cteDef, refCount - uselessRefCount, refMap)
}
}
}
}

private def inlineCTE(
plan: LogicalPlan,
cteMap: mutable.HashMap[Long, (CTERelationDef, Int)],
cteMap: mutable.Map[Long, (CTERelationDef, Int, mutable.Map[Long, Int])],
notInlined: mutable.ArrayBuffer[CTERelationDef]): LogicalPlan = {
plan match {
case WithCTE(child, cteDefs) =>
cteDefs.foreach { cteDef =>
val (cte, refCount) = cteMap(cteDef.id)
val (cte, refCount, refMap) = cteMap(cteDef.id)
if (refCount > 0) {
val inlined = cte.copy(child = inlineCTE(cte.child, cteMap, notInlined))
cteMap.update(cteDef.id, (inlined, refCount))
cteMap(cteDef.id) = (inlined, refCount, refMap)
if (!shouldInline(inlined, refCount)) {
notInlined.append(inlined)
}
Expand All @@ -120,7 +141,7 @@ case class InlineCTE(alwaysInline: Boolean = false) extends Rule[LogicalPlan] {
inlineCTE(child, cteMap, notInlined)

case ref: CTERelationRef =>
val (cteDef, refCount) = cteMap(ref.cteId)
val (cteDef, refCount, _) = cteMap(ref.cteId)
if (shouldInline(cteDef, refCount)) {
if (ref.outputSet == cteDef.outputSet) {
cteDef.child
Expand Down
11 changes: 11 additions & 0 deletions sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4648,6 +4648,17 @@ class SQLQuerySuite extends QueryTest with SharedSparkSession with AdaptiveSpark
sql("SELECT /*+ hash(t2) */ * FROM t1 join t2 on c1 = c2")
}
}

test("SPARK-43199: InlineCTE is idempotent") {
sql(
"""
|WITH
| x(r) AS (SELECT random()),
| y(r) AS (SELECT * FROM x),
| z(r) AS (SELECT * FROM x)
|SELECT * FROM z
|""".stripMargin).collect()
}
}

case class Foo(bar: Option[String])