aokolnychyi commented on code in PR #54488:
URL: https://github.com/apache/spark/pull/54488#discussion_r2923764120


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSchemaEvolution.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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 scala.jdk.CollectionConverters._
+import scala.util.control.NonFatal
+
+import org.apache.spark.{SparkException, SparkThrowable}
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.connector.catalog.{Identifier, Table, 
TableCatalog, TableChange, TableWritePrivilege}
+import org.apache.spark.sql.connector.catalog.TableWritePrivilege.{DELETE, 
INSERT}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, 
QueryExecutionErrors}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
ExtractV2CatalogAndIdentifier}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, AtomicType, DataType, MapType, 
StructField, StructType}
+
+
+/**
+ * A rule that resolves schema evolution for V2 write commands (INSERT, MERGE 
INTO).
+ *
+ * This rule will call the DSV2 Catalog to update the schema of the target 
table.
+ */
+object ResolveSchemaEvolution extends Rule[LogicalPlan] with Logging {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = 
plan.resolveOperatorsWithPruning(
+    _.containsPattern(COMMAND), ruleId) {
+    // This rule should run only if all assignments are resolved, except those
+    // that will be satisfied by schema evolution
+    case write: V2WriteSchemaEvolution if write.pendingSchemaChanges.nonEmpty 
=>
+      write.table match {
+        case relation @ ExtractV2CatalogAndIdentifier(catalog, ident) =>
+          evolveSchema(catalog, ident, write.pendingSchemaChanges)
+          val writePrivileges = getWritePrivileges(write)
+          val newTable = catalog.loadTable(ident, writePrivileges.asJava)
+          val writeWithNewTarget = replaceWriteTarget(write, relation, 
newTable)
+
+          val remainingChanges = writeWithNewTarget.pendingSchemaChanges
+          if (remainingChanges.nonEmpty) {
+            throw 
QueryCompilationErrors.unsupportedAutoSchemaEvolutionChangesError(
+              catalog, ident, remainingChanges)
+          }
+
+          writeWithNewTarget
+        case _ =>
+          write
+      }
+  }
+
+  private def evolveSchema(
+      catalog: TableCatalog,
+      ident: Identifier,
+      changes: Seq[TableChange]): Unit = {
+    try {
+      catalog.alterTable(ident, changes: _*)
+    } catch {
+      case e: IllegalArgumentException if !e.isInstanceOf[SparkThrowable] =>
+        throw QueryExecutionErrors.unsupportedTableChangeError(e)
+      case NonFatal(e) =>
+        throw QueryCompilationErrors.failedAutoSchemaEvolutionError(
+          catalog, ident, e)
+    }
+  }
+
+  private def getWritePrivileges(write: V2WriteSchemaEvolution): 
Set[TableWritePrivilege] =
+    write match {
+      case m: MergeIntoTable =>
+        MergeIntoTable.getWritePrivileges(
+          m.matchedActions,
+          m.notMatchedActions,
+          m.notMatchedBySourceActions
+        ).toSet
+      case _: AppendData => Set(INSERT)
+      case _: OverwriteByExpression | _: OverwritePartitionsDynamic => 
Set(INSERT, DELETE)
+      case _ =>
+        throw SparkException.internalError(
+          s"Attempting schema evolution on a command that does not support it: 
$write")
+    }
+
+  private def replaceWriteTarget(
+      write: V2WriteSchemaEvolution,
+      relation: DataSourceV2Relation,
+      newTable: Table): V2WriteSchemaEvolution = {
+    val oldOutput = write.table.output
+    val newOutput = DataTypeUtils.toAttributes(newTable.columns)
+    val newRelation = relation.copy(table = newTable, output = newOutput)
+
+    val writeWithNewTargetTable = write match {
+      case m: MergeIntoTable =>
+        val newTarget = m.targetTable.transform {
+          case _: DataSourceV2Relation => newRelation
+        }
+        m.copy(targetTable = newTarget)
+      case w: V2WriteCommand =>
+        w.withNewTable(newRelation)
+    }
+    rewriteAttrs(writeWithNewTargetTable, oldOutput, newOutput)
+  }
+
+  private def rewriteAttrs[T <: LogicalPlan](
+      plan: T,
+      oldOutput: Seq[Attribute],
+      newOutput: Seq[Attribute]): T = {
+    val attrMap = AttributeMap(oldOutput.zip(newOutput))
+    plan.rewriteAttrs(attrMap).asInstanceOf[T]
+  }
+
+  /**
+   * Computes the set of table changes needed to evolve `originalTarget` schema
+   * to accommodate `originalSource` schema. When `isByName` is true, fields 
are matched
+   * by name. When false, fields are matched by position.
+   */
+  def computeSchemaChanges(
+      originalTarget: StructType,
+      originalSource: StructType,
+      isByName: Boolean): Array[TableChange] =
+    computeSchemaChanges(
+      originalTarget,
+      originalSource,
+      originalTarget,
+      originalSource,
+      fieldPath = Nil,
+      isByName = isByName

Review Comment:
   Is `isByName = isByName` redundant?



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

Reply via email to