anew commented on code in PR #56686:
URL: https://github.com/apache/spark/pull/56686#discussion_r3553052326


##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/AutoCdcAuxiliaryTable.scala:
##########
@@ -0,0 +1,331 @@
+/*
+ * 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.pipelines.graph
+
+import scala.util.control.NonFatal
+
+import org.json4s.JsonAST.{JArray, JString}
+import org.json4s.jackson.JsonMethods.{compact, parse}
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.analysis.Resolver
+import org.apache.spark.sql.connector.catalog.{CatalogV2Util, Table => 
CatalogTable, TableCatalog}
+import org.apache.spark.sql.pipelines.autocdc.{AutoCdcReservedNames, ScdType}
+import org.apache.spark.sql.types.{StructField, StructType}
+
+/**
+ * Helpers to construct and validate an AutoCDC flow's auxiliary table within 
the context of a
+ * dataflow graph.
+ */
+object AutoCdcAuxiliaryTable {
+  /**
+   * Helper for deriving the auxiliary AutoCDC catalog table identifier from a 
target table. If a
+   * table exists with a name matching the name derived here, it is assumed to 
be an AutoCDC
+   * auxiliary table that should be managed by the pipeline.
+   */
+  def identifier(destination: TableIdentifier): TableIdentifier = 
TableIdentifier(
+    table = s"${AutoCdcReservedNames.prefix}aux_state_${destination.table}",
+    database = destination.database,
+    catalog = destination.catalog
+  )
+
+  /**
+   * Reserved table property key set on the auxiliary table to record which 
SCD strategy it
+   * serves.
+   */
+  val scdTypePropertyKey: String = 
s"${PipelinesTableProperties.pipelinesPrefix}autocdc.scdType"
+
+  /**
+   * Table property recording the auxiliary table's unquoted AutoCDC key 
column names as a JSON
+   * string array (e.g. `["id","region"]`). Written once when the auxiliary 
table is created and is
+   * considered immutable; full-refresh is the only way to change it.
+   */
+  val keyColumnNamesProperty: String =
+    s"${PipelinesTableProperties.pipelinesPrefix}autocdc.keyColumnNames"
+
+  /**
+   * Serialize key column names to the JSON form stored at 
[[keyColumnNamesProperty]].
+   * Round-trips an empty list as `[]`; callers are expected to enforce a 
non-empty key set
+   * upstream.
+   */
+  def serializeKeyColumnNames(names: Seq[String]): String = {
+    compact(JArray(names.map(JString(_)).toList))
+  }
+
+  /**
+   * Parse a [[keyColumnNamesProperty]] value. `None` if it is not a JSON 
array of strings.
+   * Round-trips an empty list as `[]`; callers are expected to enforce a 
non-empty key set
+   * upstream.
+   */
+  def parseKeyColumnNames(raw: String): Option[Seq[String]] = {
+    val parsed = try Some(parse(raw)) catch { case NonFatal(_) => None }
+    parsed.flatMap {
+      case JArray(elems) =>
+        val names = elems.collect { case JString(s) => s }
+        if (names.size == elems.size) Some(names) else None
+      case _ => None
+    }
+  }
+
+  /**
+   * Build the auxiliary table spec given an AutoCdc flow and the destination 
table it writes to.
+   *
+   * @param destinationTable the dataset that owns the auxiliary table
+   * @param destinationTableSchema the AutoCDC target's evolved schema as of 
the latest pipeline run
+   *                               (the union of all flows writing to the 
target after schema
+   *                               evolution, NOT the target's 
`specifiedSchema`)
+   * @param inputAutoCdcFlow the AutoCDC flow writing to `destinationTable`
+   * @return the auxiliary-table spec
+   */
+  def buildAuxiliaryTableSpecFor(
+      destinationTable: Table,
+      destinationTableSchema: StructType,
+      inputAutoCdcFlow: AutoCdcMergeFlow): AuxiliaryTableSpec = {
+    inputAutoCdcFlow.changeArgs.storedAsScdType match {
+      case ScdType.Type1 =>
+        buildScd1AuxiliaryTableSpecFor(
+          destinationTable,
+          destinationTableSchema,
+          inputAutoCdcFlow
+        )
+      case ScdType.Type2 =>
+        // SCD2 auxiliary derivation lands with SCD2 support. AutoCdcMergeFlow 
rejects SCD2 at
+        // construction today, so a resolved SCD2 flow cannot exist and this 
branch is unreachable.
+        throw SparkException.internalError(
+          "SCD2 auxiliary table derivation is not yet implemented."
+        )
+    }
+  }
+
+  /**
+   * Build the SCD1 auxiliary table spec given the AutoCdc flow's declared 
keys and the destination
+   * table it writes to.
+   *
+   * @param destinationTable the dataset that owns the SCD1 auxiliary table
+   * @param destinationTableSchema the AutoCDC target's evolved schema as of 
the latest pipeline run
+   *                               (the union of all flows writing to the 
target after schema
+   *                               evolution), from which the key and CDC 
metadata fields are
+   *                               resolved
+   * @param inputAutoCdcFlow the AutoCDC flow writing to `destinationTable`
+   * @return the SCD1 auxiliary-table spec
+   */
+  private def buildScd1AuxiliaryTableSpecFor(
+      destinationTable: Table,
+      destinationTableSchema: StructType,
+      inputAutoCdcFlow: AutoCdcMergeFlow
+  ): AuxiliaryTableSpec = {
+    val scd1AuxiliaryTableIdentifier = identifier(destinationTable.identifier)
+
+    val resolver = inputAutoCdcFlow.df.sparkSession.sessionState.conf.resolver
+    val autoCdcKeyColumnNames = inputAutoCdcFlow.changeArgs.keys.map(_.name)
+
+    // The auxiliary table should derive its schema from the exact same 
key/CDC metadata column
+    // schema in its corresponding destination table. Retrieve those column 
schemas.
+    val keyFields = autoCdcKeyColumnNames.map { keyColumnName =>
+      findFieldInDestinationSchema(
+        destinationTableSchema = destinationTableSchema,
+        destinationTableIdentifier = destinationTable.identifier,
+        autoCdcFlowIdentifier = inputAutoCdcFlow.identifier,
+        fieldName = keyColumnName,
+        resolver = resolver
+      )
+    }
+    val cdcMetadataField = findFieldInDestinationSchema(
+      destinationTableSchema = destinationTableSchema,
+      destinationTableIdentifier = destinationTable.identifier,
+      autoCdcFlowIdentifier = inputAutoCdcFlow.identifier,
+      fieldName = AutoCdcReservedNames.cdcMetadataColName,
+      resolver = resolver
+    )
+
+    val scd1AuxiliaryTableSchema = StructType(keyFields :+ cdcMetadataField)
+
+    val scd1AuxiliaryTableProperties =
+      // Record which SCD strategy this auxiliary table serves so downstream 
readers can identify it
+      // without inspecting the schema.
+      Map(scdTypePropertyKey -> ScdType.Type1.label) ++
+      // Persist the AutoCDC key column names as a JSON list; immutable 
post-creation (full-refresh
+      // is the only way to change it).
+      Map(keyColumnNamesProperty -> 
serializeKeyColumnNames(keyFields.map(_.name))) ++
+      // Inherit the target's format so MERGE semantics line up. When 
unspecified, omit the provider
+      // so the catalog falls back to its default.
+      destinationTable.format.map(TableCatalog.PROP_PROVIDER -> _)
+
+    AutoCdcAuxiliaryTableSpec(
+      identifier = scd1AuxiliaryTableIdentifier,
+      schema = scd1AuxiliaryTableSchema,
+      properties = scd1AuxiliaryTableProperties,
+      targetTableIdentifier = destinationTable.identifier,
+      expectedKeyFields = keyFields,
+      expectedScdType = ScdType.Type1
+    )
+  }
+
+  /**
+   * Resolve the [[StructField]] named `fieldName` in `destinationTableSchema` 
(the AutoCDC target's
+   * evolved schema). The key columns and the CDC metadata column are always 
present in that schema,
+   * so a miss is an implementation invariant and surfaces as an internal 
error.
+   *
+   * @param destinationTableSchema the AutoCDC target's evolved schema to 
resolve against
+   * @param fieldName the column name to resolve
+   * @param resolver the session resolver used for case-sensitivity-aware 
field lookups
+   * @param destinationTableIdentifier the AutoCDC target's identifier, named 
in the error message
+   * @param autoCdcFlowIdentifier the AutoCDC flow writing to the target, 
named in the error message
+   * @return the matching field
+   */
+  private def findFieldInDestinationSchema(
+      destinationTableSchema: StructType,
+      fieldName: String,
+      resolver: Resolver,
+      destinationTableIdentifier: TableIdentifier,
+      autoCdcFlowIdentifier: TableIdentifier): StructField = {
+    destinationTableSchema.fields
+      .find(field => resolver(field.name, fieldName))
+      .getOrElse(
+        throw SparkException.internalError(

Review Comment:
   TIL that we don't use error classes for internal errors.



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