cloud-fan commented on code in PR #54126:
URL: https://github.com/apache/spark/pull/54126#discussion_r3329837539


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -4833,9 +4833,13 @@ class AstBuilder extends DataTypeAstBuilder
   /**
    * Create a generation expression string.

Review Comment:
   Stale after the return-type change — this no longer creates a string.
   ```suggestion
      * Create a generation expression.
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/GeneratedColumnExpression.scala:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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.plans.logical
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.expressions.{AttributeReference, Cast, 
Expression, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.trees.TreePattern.PLAN_EXPRESSION
+import org.apache.spark.sql.catalyst.util.V2ExpressionBuilder
+import org.apache.spark.sql.connector.catalog.GenerationExpression
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.sql.util.SchemaUtils
+
+/**
+ * A wrapper expression to hold the generation expression and its original SQL 
text.
+ * The child expression is resolved by the normal analyzer rules through the 
expression tree.
+ */
+case class GeneratedColumnExpression(
+    child: Expression,
+    originalSQL: String)
+  extends UnaryExpression with Unevaluable {
+
+  override def dataType: DataType = child.dataType
+
+  override def stringArgs: Iterator[Any] = Iterator(child, originalSQL)
+
+  override protected def withNewChildInternal(newChild: Expression): 
Expression =
+    copy(child = newChild)
+
+  /**
+   * Validate the generation expression and throw an AnalysisException if 
invalid.
+   * Validations include:
+   * - The expression cannot reference itself
+   * - The expression cannot reference other generated columns
+   * - The expression must be deterministic
+   * - The expression data type can be safely up-cast to the destination 
column data type
+   * - No subquery expressions
+   * - No non-UTF8 binary collation
+   */
+  def validate(
+      fieldName: String,
+      targetDataType: DataType,
+      allColumns: Seq[ColumnDefinition]): Unit = {
+    def unsupportedExpressionError(reason: String): AnalysisException = {
+      new AnalysisException(
+        errorClass = "UNSUPPORTED_EXPRESSION_GENERATED_COLUMN",
+        messageParameters = Map(
+          "fieldName" -> fieldName,
+          "expressionStr" -> originalSQL,
+          "reason" -> reason))
+    }
+
+    // Don't allow subquery expressions
+    if (child.containsPattern(PLAN_EXPRESSION)) {
+      throw unsupportedExpressionError("subquery expressions are not allowed 
for generated columns")
+    }
+
+    // Use the resolver to respect case sensitivity settings
+    val resolver = SQLConf.get.resolver
+
+    // Check for self-reference - the expression cannot reference itself
+    val referencedColumns = child.collect {
+      case a: AttributeReference => a.name
+    }
+    if (referencedColumns.exists(resolver(_, fieldName))) {
+      throw unsupportedExpressionError("generation expression cannot reference 
itself")
+    }
+
+    // Check for references to other generated columns
+    val generatedColumnNames = allColumns
+      .filter(col => col.generationExpression.isDefined && !resolver(col.name, 
fieldName))
+      .map(_.name)
+    if (referencedColumns.exists(ref => 
generatedColumnNames.exists(resolver(ref, _)))) {
+      throw unsupportedExpressionError(
+        "generation expression cannot reference another generated column")
+    }
+
+    if (!child.deterministic) {
+      throw unsupportedExpressionError("generation expression is not 
deterministic")
+    }
+
+    if (!Cast.canUpCast(child.dataType, targetDataType)) {
+      throw unsupportedExpressionError(
+        s"generation expression data type ${child.dataType.simpleString} " +
+          s"is incompatible with column data type 
${targetDataType.simpleString}")
+    }
+
+    if (child.exists(e => SchemaUtils.hasNonUTF8BinaryCollation(e.dataType))) {
+      throw unsupportedExpressionError(
+        "generation expression cannot contain non utf8 binary collated string 
type")
+    }
+  }
+
+  // Convert the generation expression to V2 GenerationExpression
+  def toV2: GenerationExpression = {
+    val v2Expr: V2Expression = new V2ExpressionBuilder(child).build().orNull

Review Comment:
   `toV2` runs at planning/strategy time, by which point `child` has been 
through the optimizer. For a foldable but context/time-varying function the 
optimizer (`ComputeCurrentTime` / `ReplaceCurrentLike`) has already folded it 
to a **definition-time literal** — and these functions are `deterministic == 
true`, so `validate()` doesn't reject them. So for `b GENERATED ALWAYS AS 
(CURRENT_TIMESTAMP)`, `getExpression()` becomes a frozen literal while 
`getSql()` stays `"CURRENT_TIMESTAMP"` (re-evaluated per row by a SQL-based 
connector). That contradicts the new class javadoc here and on `DefaultValue` — 
"the `Expression` form captures the semantics fully and unambiguously, similar 
to how a view captures the configs" — since a view re-evaluates 
`CURRENT_TIMESTAMP` rather than freezing it. A connector that follows the 
javadoc and prefers the Expression form would store a constant for every row.
   
   The sibling `DefaultValueExpression` avoids this precisely: it's 
`AnalysisAwareExpression`, snapshots `analyzedChild` at `markAsAnalyzed()`, and 
builds its V2 "current default" from that pre-optimization tree so a `DEFAULT 
current_date()` re-evaluates per insert. I'd mirror that here — capture the 
analyzed child and build the V2 expression from it. (Pure-constant folding like 
`1+1` then just isn't reflected in the stored expression, which is harmless and 
matches DEFAULT behavior.)
   
   If you instead want to keep folding (the PR's stated goal), then generated 
columns should additionally reject non-immutable functions, since the 
determinism check alone doesn't. Either way, worth confirming the intended 
contract — and the `current_time` test asserts only `getSql`; adding an 
assertion on `getExpression()` would lock the decision in. This is the concrete 
answer to @juliuszsompolski's "do Expressions capture semantics like Views?" 
question.



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