szehon-ho commented on code in PR #60560:
URL: https://github.com/apache/spark/pull/60560#discussion_r4606035509


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AssignmentUtils.scala:
##########
@@ -130,7 +139,9 @@ object AssignmentUtils extends SQLConfHelper with 
CastSupport {
       val matchingAssignments = topLevelAssignments.collect {
         case assignment if assignment.key.semanticEquals(attr) => assignment
       }
-      val resolvedValue = if (matchingAssignments.isEmpty) {
+      val resolvedValue = if (matchingAssignments.isEmpty && 
generatedColumns.contains(attr.name)) {
+        GeneratedColumnAssignmentValue(attr.dataType, attr.nullable)
+      } else if (matchingAssignments.isEmpty) {

Review Comment:
   MERGE INSERT now applies 
`spark.sql.generatedColumn.allowNullableIngest.enabled` when Spark computes 
generated columns, while preserving declared defaults. Added coverage for 
single- and multiple-clause insert-only MERGE, full MERGE, and star inserts 
with schema evolution, with the config on and off.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,20 +66,68 @@ private[sql] object RowLevelAssignmentResolution {
     Assignment(cleanedKey, finalValue)
   }
 
+  /**
+   * Fills omitted generated-column assignments for UPDATE and MERGE actions, 
including INSERT
+   * actions within MERGE. Regular INSERT uses WriteOutputResolution instead.
+   *
+   * For g GENERATED ALWAYS AS (a * 2), UPDATE t SET a = b + 1, b = 100 must 
assign
+   * g = (old.b + 1) * 2. Resolve the generation expression against attributes 
for the new values,
+   * then substitute the aligned assignments while preserving their references 
to the original row.
+   * Explicitly supplied generated values pass through for validation against 
the final row.
+   */
+  def resolveGeneratedColumnAssignments(
+      table: LogicalPlan,
+      assignments: Seq[Assignment],
+      analyze: LogicalPlan => LogicalPlan): Seq[Assignment] = {
+    if 
(!assignments.exists(_.value.isInstanceOf[GeneratedColumnAssignmentValue])) {
+      return assignments
+    }
+
+    val relation = table.collectFirst { case r: DataSourceV2Relation => r }.get
+    val generationExpressions = GeneratedColumn.expressionReaders(relation)
+    // assigned aliases old.b + 1 as a and 100 as b, each with a fresh 
attribute ID.
+    val assigned = assignments.collect {
+      case Assignment(attr: Attribute, value)
+          if !value.isInstanceOf[GeneratedColumnAssignmentValue] =>
+        Alias(value, attr.name)()
+    }
+    // input exposes the new a and b; valuesByAttribute maps them back to 
old.b + 1 and 100.
+    val input = assigned.map(_.toAttribute)
+    val valuesByAttribute = AttributeMap(assigned.map(a => a.toAttribute -> 
a.child))
+
+    assignments.map {
+      case Assignment(attr: Attribute, _: GeneratedColumnAssignmentValue) =>
+        // resolved binds a * 2 to input's new a, before substituting assigned 
values.
+        val resolved = generationExpressions(attr.name).resolve(input, 
analyze) { expr =>
+          Cast(expr, attr.dataType, Some(conf.sessionLocalTimeZone), 
ansiEnabled = true)
+        }
+        // generated uses valuesByAttribute once: (old.b + 1) * 2, keeping the 
original b.
+        val generated = resolved.transform {
+          case a: AttributeReference if valuesByAttribute.contains(a) => 
valuesByAttribute(a)

Review Comment:
   Added `GeneratedColumnSharedAssignmentValue` to retain the link between 
assigned values and generated expressions. UPDATE and single-clause insert-only 
MERGE project those values once, with guards for unchanged rows, and both the 
assigned column and generated expressions read the projected result. Added 
UUID, conditionally consumed seeded-random, UDF evaluation-count, and 
guarded-assignment regressions across the write modes.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -205,6 +223,24 @@ object GeneratedColumn {
         }
       }
     }
+
+    /**
+     * Reads and analyzes a value, applying the caller's wrappers to both 
expression forms.
+     * Resolve the lazy SQL session fallback before returning, so callers can 
substitute the
+     * resolved input attributes without waiting for another analyzer pass.
+     */
+    def resolve(
+        input: Seq[Attribute],
+        analyzer: LogicalPlan => LogicalPlan)(
+        prepare: Expression => Expression): Expression = {
+      def inSession: Expression = {
+        val value = 
prepare(toCatalyst(StoredExpressionText.parseWithSessionAnsi))
+        val Project(Seq(Alias(resolved, _)), _) =

Review Comment:
   The SQL fallback now requires a resolved scalar projection over the expected 
input. Other shapes run CheckAnalysis and produce an AnalysisException with the 
table, column, and stored expression instead of a MatchError or 
UnresolvedException. Added aggregate and unresolved-expression regressions, 
including NOT NULL generated columns.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -92,6 +92,9 @@ object ConstantFolding extends Rule[LogicalPlan] {
     case c: ConditionalExpression if !c.foldable =>
       c.mapChildren(constantFolding(_, isConditionalBranch = true))
 
+    case i: MergeRows.Instruction =>

Review Comment:
   The single-clause insert-only MERGE folding case is being handled in 
prerequisite #60559. Keeping the folding change and its coverage in that PR.



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