aokolnychyi commented on code in PR #54488: URL: https://github.com/apache/spark/pull/54488#discussion_r2923757930
########## 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 { Review Comment: I wonder if it makes sense to define extra methods in the parent interface for schema evolution. ``` def writePrivileges: Set[TableWritePrivilege] def withEvolvedTable(newTable: LogicalPlan): SupportsSchemaEvolution ``` Then we won't have to pattern match anymore. -- 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]
