rdblue commented on a change in pull request #2193:
URL: https://github.com/apache/iceberg/pull/2193#discussion_r568877523



##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/AlignUpdateTable.scala
##########
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, UpdateTable}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+case class AlignUpdateTable(conf: SQLConf) extends Rule[LogicalPlan] with 
AssignmentAlignmentSupport {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+    case u: UpdateTable if u.resolved =>
+      u.copy(assignments = alignAssignments(u.table, u.assignments))

Review comment:
       Should we merge the rules into one then? What is the value of separate 
rules for Update and Merge?

##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeConditionsInRowLevelOperations.scala
##########
@@ -35,6 +35,10 @@ object OptimizeConditionsInRowLevelOperations extends 
Rule[LogicalPlan] {
         if 
!SubqueryExpression.hasSubquery(cond.getOrElse(Literal.TrueLiteral)) && 
isIcebergRelation(table) =>
       val optimizedCond = 
optimizeCondition(cond.getOrElse(Literal.TrueLiteral), table)
       d.copy(condition = Some(optimizedCond))
+    case u @ UpdateTable(table, _, cond)

Review comment:
       This is short enough that I think it's okay.

##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteUpdate.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.Alias
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.expressions.If
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.plans.logical.Assignment
+import org.apache.spark.sql.catalyst.plans.logical.Filter
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.plans.logical.Project
+import org.apache.spark.sql.catalyst.plans.logical.ReplaceData
+import org.apache.spark.sql.catalyst.plans.logical.UpdateTable
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.utils.PlanUtils.isIcebergRelation
+import org.apache.spark.sql.catalyst.utils.RewriteRowLevelOperationHelper
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import 
org.apache.spark.sql.execution.datasources.v2.ExtendedDataSourceV2Implicits
+
+// TODO: should be part of early scan push down after the delete condition is 
optimized

Review comment:
       I'm not sure about this. I thought we wanted to explore moving these 
into the analyzer?

##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteUpdate.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.Alias
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.expressions.If
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.plans.logical.Assignment
+import org.apache.spark.sql.catalyst.plans.logical.Filter
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.plans.logical.Project
+import org.apache.spark.sql.catalyst.plans.logical.ReplaceData
+import org.apache.spark.sql.catalyst.plans.logical.UpdateTable
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.utils.PlanUtils.isIcebergRelation
+import org.apache.spark.sql.catalyst.utils.RewriteRowLevelOperationHelper
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import 
org.apache.spark.sql.execution.datasources.v2.ExtendedDataSourceV2Implicits
+
+// TODO: should be part of early scan push down after the delete condition is 
optimized
+case class RewriteUpdate(spark: SparkSession) extends Rule[LogicalPlan] with 
RewriteRowLevelOperationHelper {
+
+  import ExtendedDataSourceV2Implicits._
+
+  // TODO: can we do any better for no-op updates? when conditions evaluate to 
false/true?
+  override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+    case UpdateTable(r: DataSourceV2Relation, assignments, Some(cond))
+        if isIcebergRelation(r) && SubqueryExpression.hasSubquery(cond) =>
+      throw new AnalysisException("UPDATE statements with subqueries are not 
currently supported")
+
+    case UpdateTable(r: DataSourceV2Relation, assignments, Some(cond)) if 
isIcebergRelation(r) =>
+      val writeInfo = newWriteInfo(r.schema)
+      val mergeBuilder = r.table.asMergeable.newMergeBuilder("update", 
writeInfo)
+
+      val matchingRowsPlanBuilder = scanRelation => Filter(cond, scanRelation)
+      val scanPlan = buildDynamicFilterScanPlan(spark, r.table, r.output, 
mergeBuilder, cond, matchingRowsPlanBuilder)
+
+      val updateProjection = buildUpdateProjection(r, scanPlan, assignments, 
cond)
+
+      val mergeWrite = mergeBuilder.asWriteBuilder.buildForBatch()
+      val writePlan = buildWritePlan(updateProjection, r.table)
+      ReplaceData(r, mergeWrite, writePlan)
+  }
+
+  private def buildUpdateProjection(
+      relation: DataSourceV2Relation,
+      scanPlan: LogicalPlan,
+      assignments: Seq[Assignment],
+      cond: Expression): LogicalPlan = {
+
+    // this method relies on the fact that the assignments have been aligned 
before
+    require(relation.output.size == assignments.size, "assignments must be 
aligned")
+
+    // Spark is going to execute the condition for each column but it seems we 
cannot avoid this

Review comment:
       Yeah, we could use a custom node like `MergeIntoExec` that runs the 
expression and then performs the right projection. I think if we tried to use 
two projections, the optimizer would collapse them and rewrite everything 
equivalent to this, where the condition runs for each column.

##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteUpdate.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.Alias
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.expressions.If
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.plans.logical.Assignment
+import org.apache.spark.sql.catalyst.plans.logical.Filter
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.plans.logical.Project
+import org.apache.spark.sql.catalyst.plans.logical.ReplaceData
+import org.apache.spark.sql.catalyst.plans.logical.UpdateTable
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.utils.PlanUtils.isIcebergRelation
+import org.apache.spark.sql.catalyst.utils.RewriteRowLevelOperationHelper
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import 
org.apache.spark.sql.execution.datasources.v2.ExtendedDataSourceV2Implicits
+
+// TODO: should be part of early scan push down after the delete condition is 
optimized
+case class RewriteUpdate(spark: SparkSession) extends Rule[LogicalPlan] with 
RewriteRowLevelOperationHelper {
+
+  import ExtendedDataSourceV2Implicits._
+
+  // TODO: can we do any better for no-op updates? when conditions evaluate to 
false/true?
+  override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+    case UpdateTable(r: DataSourceV2Relation, assignments, Some(cond))
+        if isIcebergRelation(r) && SubqueryExpression.hasSubquery(cond) =>
+      throw new AnalysisException("UPDATE statements with subqueries are not 
currently supported")
+
+    case UpdateTable(r: DataSourceV2Relation, assignments, Some(cond)) if 
isIcebergRelation(r) =>
+      val writeInfo = newWriteInfo(r.schema)
+      val mergeBuilder = r.table.asMergeable.newMergeBuilder("update", 
writeInfo)
+
+      val matchingRowsPlanBuilder = scanRelation => Filter(cond, scanRelation)
+      val scanPlan = buildDynamicFilterScanPlan(spark, r.table, r.output, 
mergeBuilder, cond, matchingRowsPlanBuilder)
+
+      val updateProjection = buildUpdateProjection(r, scanPlan, assignments, 
cond)
+
+      val mergeWrite = mergeBuilder.asWriteBuilder.buildForBatch()
+      val writePlan = buildWritePlan(updateProjection, r.table)
+      ReplaceData(r, mergeWrite, writePlan)
+  }
+
+  private def buildUpdateProjection(
+      relation: DataSourceV2Relation,
+      scanPlan: LogicalPlan,
+      assignments: Seq[Assignment],
+      cond: Expression): LogicalPlan = {
+
+    // this method relies on the fact that the assignments have been aligned 
before
+    require(relation.output.size == assignments.size, "assignments must be 
aligned")
+
+    // Spark is going to execute the condition for each column but it seems we 
cannot avoid this
+    val assignedExprs = assignments.map(_.value)
+    val updatedExprs = assignedExprs.zip(relation.output).map { case 
(assignedExpr, attr) =>
+      // use semanticEquals to avoid unnecessary if expressions as we may run 
after operator optimization
+      val updatedExpr = if (attr.semanticEquals(assignedExpr)) {
+        attr
+      } else {
+        If(cond, assignedExpr, attr)
+      }
+      Alias(updatedExpr, attr.name)()
+    }
+    Project(updatedExprs, scanPlan)

Review comment:
       Nit: white space after control flow blocks.

##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/RewriteRowLevelOperationHelper.scala
##########
@@ -197,6 +203,22 @@ trait RewriteRowLevelOperationHelper extends 
PredicateHelper with Logging {
       }
     }
   }
+
+  protected def buildWritePlan(childPlan: LogicalPlan, table: Table): 
LogicalPlan = {

Review comment:
       For a follow up, should we add a rule that does this for Append and 
Overwrite plans as well? That would be nice so that we don't have to wait until 
3.2.0 to get write distribution and ordering for normal writes.

##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/AlignUpdateTable.scala
##########
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, UpdateTable}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+case class AlignUpdateTable(conf: SQLConf) extends Rule[LogicalPlan] with 
AssignmentAlignmentSupport {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+    case u: UpdateTable if u.resolved =>
+      u.copy(assignments = alignAssignments(u.table, u.assignments))

Review comment:
       One fewer class/file seems like a good thing.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to