szehon-ho commented on code in PR #54126: URL: https://github.com/apache/spark/pull/54126#discussion_r3345232427
########## 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: Went with mirroring `DefaultValueExpression`. `GeneratedColumnExpression` is now an `AnalysisAwareExpression`: it snapshots the analyzed (pre-optimization) child in `markAsAnalyzed()`, and `toV2` builds the V2 expression from that snapshot. So `CURRENT_TIMESTAMP` and friends are no longer folded into definition-time literals — they have no V2 representation, so `getExpression()` is `null` and the connector falls back to the SQL string (same as `DefaultValue`'s current default). Also dropped the "captures the semantics fully" claim from the `GenerationExpression`/`DefaultValue` javadocs, and added an assertion that `getExpression()` is `null` in the `current_timestamp` generated-column test. ########## 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: Done. -- 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]
