|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.sql.catalyst.optimizer |
| 19 | + |
| 20 | +import scala.collection.mutable.ArrayBuffer |
| 21 | + |
| 22 | +import org.apache.spark.sql.catalyst.expressions._ |
| 23 | +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LeafNode, LogicalPlan, Project} |
| 24 | +import org.apache.spark.sql.catalyst.rules.Rule |
| 25 | + |
| 26 | +/** |
| 27 | + * This rule tries to merge non-correlated [[ScalarSubquery]]s into [[MultiScalarSubquery]]s. |
| 28 | + * Mergeable [[ScalarSubquery]]s are then replaced to their corresponding [[MultiScalarSubquery]] |
| 29 | + * and the [[ReuseSubquery]] rule makes sure that merged subqueries are computed once. |
| 30 | + * |
| 31 | + * Eg. the following query: |
| 32 | + * |
| 33 | + * SELECT |
| 34 | + * (SELECT avg(a) FROM t GROUP BY b), |
| 35 | + * (SELECT sum(b) FROM t GROUP BY b) |
| 36 | + * |
| 37 | + * is optimized from: |
| 38 | + * |
| 39 | + * Project [scalar-subquery#231 [] AS scalarsubquery()#241, |
| 40 | + * scalar-subquery#232 [] AS scalarsubquery()#242L] |
| 41 | + * : :- Aggregate [b#234], [avg(a#233) AS avg(a)#236] |
| 42 | + * : : +- Relation default.t[a#233,b#234] parquet |
| 43 | + * : +- Aggregate [b#240], [sum(b#240) AS sum(b)#238L] |
| 44 | + * : +- Project [b#240] |
| 45 | + * : +- Relation default.t[a#239,b#240] parquet |
| 46 | + * +- OneRowRelation |
| 47 | + * |
| 48 | + * to: |
| 49 | + * |
| 50 | + * Project [multi-scalar-subquery#231.avg(a) AS scalarsubquery()#241, |
| 51 | + * multi-scalar-subquery#232.sum(b) AS scalarsubquery()#242L] |
| 52 | + * : :- Aggregate [b#234], [avg(a#233) AS avg(a)#236, sum(b#234) AS sum(b)#238L] |
| 53 | + * : : +- Project [a#233, b#234] |
| 54 | + * : : +- Relation default.t[a#233,b#234] parquet |
| 55 | + * : +- Aggregate [b#234], [avg(a#233) AS avg(a)#236, sum(b#234) AS sum(b)#238L] |
| 56 | + * : +- Project [a#233, b#234] |
| 57 | + * : +- Relation default.t[a#233,b#234] parquet |
| 58 | + * +- OneRowRelation |
| 59 | + */ |
| 60 | +object MergeScalarSubqueries extends Rule[LogicalPlan] with PredicateHelper { |
| 61 | + def apply(plan: LogicalPlan): LogicalPlan = { |
| 62 | + if (conf.scalarSubqueryMergeEabled && conf.subqueryReuseEnabled) { |
| 63 | + val mergedSubqueries = ArrayBuffer.empty[LogicalPlan] |
| 64 | + removeReferences(mergeAndInsertReferences(plan, mergedSubqueries), mergedSubqueries) |
| 65 | + } else { |
| 66 | + plan |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private def mergeAndInsertReferences( |
| 71 | + plan: LogicalPlan, |
| 72 | + mergedSubqueries: ArrayBuffer[LogicalPlan]): LogicalPlan = { |
| 73 | + plan.transformAllExpressions { |
| 74 | + case s: ScalarSubquery if s.children.isEmpty => |
| 75 | + val (mergedPlan, ordinal) = mergeAndGetReference(s.plan, mergedSubqueries) |
| 76 | + GetStructField(MultiScalarSubquery(mergedPlan, s.exprId), ordinal) |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + case class SubqueryReference( |
| 81 | + index: Int, |
| 82 | + mergedSubqueries: ArrayBuffer[LogicalPlan]) extends LeafNode { |
| 83 | + override def stringArgs: Iterator[Any] = Iterator(index) |
| 84 | + |
| 85 | + override def output: Seq[Attribute] = mergedSubqueries(index).output |
| 86 | + } |
| 87 | + |
| 88 | + private def mergeAndGetReference( |
| 89 | + plan: LogicalPlan, |
| 90 | + mergedSubqueries: ArrayBuffer[LogicalPlan]): (SubqueryReference, Int) = { |
| 91 | + mergedSubqueries.zipWithIndex.collectFirst { |
| 92 | + Function.unlift { case (s, i) => mergePlans(plan, s).map(_ -> i) } |
| 93 | + }.map { case ((mergedPlan, outputMap), i) => |
| 94 | + mergedSubqueries(i) = mergedPlan |
| 95 | + SubqueryReference(i, mergedSubqueries) -> |
| 96 | + mergedPlan.output.indexOf(outputMap(plan.output.head)) |
| 97 | + }.getOrElse { |
| 98 | + mergedSubqueries += plan |
| 99 | + SubqueryReference(mergedSubqueries.length - 1, mergedSubqueries) -> 0 |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + private def mergePlans( |
| 104 | + newPlan: LogicalPlan, |
| 105 | + existingPlan: LogicalPlan): Option[(LogicalPlan, AttributeMap[Attribute])] = { |
| 106 | + (newPlan, existingPlan) match { |
| 107 | + case (np, ep) if np.canonicalized == ep.canonicalized => |
| 108 | + Some(ep -> AttributeMap(np.output.zip(ep.output))) |
| 109 | + case (np: Project, ep: Project) => |
| 110 | + mergePlans(np.child, ep.child).map { case (mergedChild, outputMap) => |
| 111 | + val newProjectList = replaceAttributes(np.projectList, outputMap) |
| 112 | + val newOutputMap = createOutputMap(np.projectList, newProjectList) |
| 113 | + Project(distinctExpressions(ep.projectList ++ newProjectList), mergedChild) -> |
| 114 | + newOutputMap |
| 115 | + } |
| 116 | + case (np, ep: Project) => |
| 117 | + mergePlans(np, ep.child).map { case (mergedChild, outputMap) => |
| 118 | + Project(distinctExpressions(ep.projectList ++ outputMap.values), mergedChild) -> outputMap |
| 119 | + } |
| 120 | + case (np: Project, ep) => |
| 121 | + mergePlans(np.child, ep).map { case (mergedChild, outputMap) => |
| 122 | + val newProjectList = replaceAttributes(np.projectList, outputMap) |
| 123 | + val newOutputMap = createOutputMap(np.projectList, newProjectList) |
| 124 | + Project(distinctExpressions(ep.output ++ newProjectList), mergedChild) -> newOutputMap |
| 125 | + } |
| 126 | + case (np: Aggregate, ep: Aggregate) => |
| 127 | + mergePlans(np.child, ep.child).flatMap { case (mergedChild, outputMap) => |
| 128 | + val newGroupingExpression = replaceAttributes(np.groupingExpressions, outputMap) |
| 129 | + if (ExpressionSet(newGroupingExpression) == ExpressionSet(ep.groupingExpressions)) { |
| 130 | + val newAggregateExpressions = replaceAttributes(np.aggregateExpressions, outputMap) |
| 131 | + val newOutputMap = createOutputMap(np.aggregateExpressions, newAggregateExpressions) |
| 132 | + Some(Aggregate(ep.groupingExpressions, |
| 133 | + distinctExpressions(ep.aggregateExpressions ++ newAggregateExpressions), |
| 134 | + mergedChild) -> newOutputMap) |
| 135 | + } else { |
| 136 | + None |
| 137 | + } |
| 138 | + } |
| 139 | + case _ => |
| 140 | + None |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + private def replaceAttributes[T <: Expression]( |
| 145 | + expressions: Seq[T], |
| 146 | + outputMap: AttributeMap[Attribute]) = { |
| 147 | + expressions.map(_.transform { |
| 148 | + case a: Attribute => outputMap.getOrElse(a, a) |
| 149 | + }.asInstanceOf[T]) |
| 150 | + } |
| 151 | + |
| 152 | + private def createOutputMap(from: Seq[NamedExpression], to: Seq[NamedExpression]) = { |
| 153 | + AttributeMap(from.map(_.toAttribute).zip(to.map(_.toAttribute))) |
| 154 | + } |
| 155 | + |
| 156 | + private def distinctExpressions(expressions: Seq[NamedExpression]) = { |
| 157 | + ExpressionSet(expressions).toSeq.asInstanceOf[Seq[NamedExpression]] |
| 158 | + } |
| 159 | + |
| 160 | + private def removeReferences( |
| 161 | + plan: LogicalPlan, |
| 162 | + mergedSubqueries: ArrayBuffer[LogicalPlan]): LogicalPlan = { |
| 163 | + plan.transformUp { |
| 164 | + case other => other.transformExpressionsUp { |
| 165 | + case gsf @ GetStructField(mss @ MultiScalarSubquery(sr: SubqueryReference, _), _, _) => |
| 166 | + val dereferencedPlan = removeReferences(mergedSubqueries(sr.index), mergedSubqueries) |
| 167 | + if (dereferencedPlan.outputSet.size > 1) { |
| 168 | + gsf.copy(child = mss.copy(plan = dereferencedPlan)) |
| 169 | + } else { |
| 170 | + ScalarSubquery(dereferencedPlan, exprId = mss.exprId) |
| 171 | + } |
| 172 | + case s: SubqueryExpression => s.withNewPlan(removeReferences(s.plan, mergedSubqueries)) |
| 173 | + } |
| 174 | + } |
| 175 | + } |
| 176 | +} |
0 commit comments