dongjoon-hyun commented on code in PR #60368:
URL: https://github.com/apache/spark/pull/60368#discussion_r4553040959
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -97,7 +95,7 @@ private[sql] class TableConstraintResolution(
Option(col.columnGenerationExpression())
.filter(_ => !autoFilledGenCols.exists(n => resolver(n, col.name)))
.map { genExpr =>
- val catalystExpr = buildGenerationCatalystExpression(r, col.name,
genExpr)
+ val catalystExpr = GeneratedColumn.toCatalyst(r, col.name, genExpr)
val colRef = UnresolvedAttribute.quoted(col.name)
val columnExtractors = Seq(col.name -> colRef)
val genExprSql = Option(genExpr.getSql()).getOrElse(catalystExpr.sql)
Review Comment:
**[1] The violation message shows the SQL text, but the check now evaluates
the modeled expression.** L98 now prefers the modeled expression, while
`genExprSql` here still prefers `getSql()`. So when the two forms differ, the
CHECK_CONSTRAINT_VIOLATION message names an expression other than the one that
failed. In the new test `modeled generation expression takes precedence with
SQL fallback` (`GenerationExpression("a + 1", a + 100)`), `INSERT ... VALUES
(1, 2)` is rejected (GeneratedColumnWriteSuite.scala:431-433) with the message
`b <=> a + 1`, which `b = 2` satisfies. With the text `"NOT VALID SQL"` or `""`
from `convertible modeled generation expression does not parse SQL`, the
message shows that text. Before this PR, the check read the SQL text first, so
the message and the check agreed. Could the message use the SQL text only when
`toCatalyst` read it, and `catalystExpr.sql` otherwise?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/WriteOutputResolution.scala:
##########
@@ -46,23 +47,34 @@ private[sql] object WriteOutputResolution {
val defaultValueFillMode =
if (conf.coerceInsertNestedTypes && v2Write.schemaEvolutionEnabled)
RECURSE
else FILL
- // Generation expressions live on the table's columns, so attach them to
the expected
- // output for TableOutputResolver, which auto-fills the generated columns
the query is
- // missing.
- val expected = v2Write.table match {
- case r: DataSourceV2Relation =>
GeneratedColumn.attachGenerationExpressions(r)
- case _ => v2Write.table.output
- }
val schemaAlignmentConfig = v2Write.table match {
case ExtractV2Table(table: SupportsConfigurableSchemaAlignment) =>
table.schemaAlignmentConfig()
case _ => SchemaAlignmentConfig.DEFAULT
}
- def resolveOutput(readGenerationExpr: String => Expression) =
+ def resolveOutput(readSql: String => Expression) = {
+ // Read directly from the V2 columns so modeled expressions do not pass
through SQL text
+ // or schema metadata. Only tables with the write capability ask Spark
to generate values.
+ val readGenerationExpr: Attribute => Option[() => Expression] =
v2Write.table match {
+ case r: DataSourceV2Relation if
GeneratedColumn.supportsGeneratedColumnsOnWrite(r.table) =>
+ val expressions = r.table.columns().flatMap { col =>
+ // Read SQL text, a modeled expression, or both.
+ val generationExpr =
Option(col.columnGenerationExpression()).orElse {
+ // Support connectors implementing only the legacy SQL getter.
+ Option(col.generationExpression()).map(sql => new
GenerationExpression(sql))
+ }
+ generationExpr.map(col.name -> _)
+ }.toMap
+ attr => expressions.get(attr.name).map { expr =>
+ () => GeneratedColumn.toCatalyst(r, attr.name, expr, readSql)
Review Comment:
**[3] The session pass re-analyzes a converted modeled expression with the
writer's type coercion.** `readSql` matters only when `toCatalyst` reads the
SQL text, so for a convertible modeled expression the second `resolveOutput` at
L93 yields the same tree as the first. When that tree does not analyze under
the fixed settings, `analyzeAutoFilledGeneratedColumns` takes it from the
session pass, and the write resolves it with the coercion of the session. For
example, take a `BOOLEAN` column generated by `new Predicate("=",
Array(FieldReference(Seq("flag")), LiteralValue(1, IntegerType)))` over `flag
BOOLEAN`. It does not analyze with ANSI mode on, because only the non-ANSI
`BooleanEquality` rule accepts `flag = 1`. So a writer with
`spark.sql.ansi.enabled=false` auto-fills it while an ANSI writer fails, and
the stored value depends on the writing session. That goes against the
`GenerationExpression` doc, where a connector expression follows the ANSI SQL
standard. The check at TableC
onstraintResolution.scala:113-118 does the same; on master it already did so
for a column with only a modeled expression. Could the session pass apply only
when the SQL text was read, so that a converted modeled expression that does
not analyze fails the write?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -122,31 +123,28 @@ object GeneratedColumn {
}
/**
- * Returns `relation`'s output with every generated column's generation
expression recorded in
- * the attribute's metadata, which is where [[TableOutputResolver]] looks
when it auto-fills the
- * generated columns a write does not provide a value for.
- *
- * Generation expressions are internal metadata: they should neither surface
in a DataFrame's
- * schema nor propagate into tables created from it. A table's V2 columns
are the persisted form
- * and the source of truth, so the write path copies the expression into
plan attribute metadata
- * only for as long as resolving the write takes.
- *
- * The output is returned unchanged if the table does not ask Spark to
handle generated columns.
+ * Converts a generation expression for both auto-fill and validation. Try
the modeled expression
+ * first, falling back to SQL text when it is absent or cannot be converted,
as defaults and CHECK
+ * constraints do.
*/
- def attachGenerationExpressions(relation: DataSourceV2Relation):
Seq[AttributeReference] = {
- if (!supportsGeneratedColumnsOnWrite(relation.table)) {
- return relation.output
- }
- val genExprs = relation.table.columns()
- .flatMap(col => Option(col.generationExpression()).map(col.name -> _))
- .toMap
- relation.output.map { attr =>
- genExprs.get(attr.name) match {
- case Some(genExpr) =>
- withMetadataEntry(attr, GENERATION_EXPRESSION_METADATA_KEY, genExpr)
- case None => attr
+ def toCatalyst(
+ relation: DataSourceV2Relation,
+ colName: String,
+ genExpr: GenerationExpression,
+ readSql: String => Expression = StoredExpressionText.parse): Expression
= {
+ Option(genExpr.getExpression)
+ .flatMap(V2ExpressionUtils.toCatalyst)
Review Comment:
**[2] A malformed modeled expression now fails the write instead of falling
back to the SQL text.** The scaladoc says this falls back to the SQL text when
the modeled expression cannot be converted, but `V2ExpressionUtils.toCatalyst`
throws for some malformed inputs instead of returning `None`. `convertExpr`
does not check the number of children, so `WIDTH_BUCKET` with two children
reaches `children(2)` (V2ExpressionUtils.scala:409-412), and `IN` or
`BOOLEAN_EXPRESSION` without children reaches `children.head`
(V2ExpressionUtils.scala:347-348). For example, with `new
GenerationExpression("width_bucket(a, 0, 10, 5)", new
GeneralScalarExpression("WIDTH_BUCKET", Array(a, 0)))` (a field reference and a
literal), every INSERT, also one that provides the value, now fails with an
`IndexOutOfBoundsException` during analysis. Before this PR, both the auto-fill
and the check read the SQL text, so these writes succeeded. The converter
predates this PR, but a valid SQL text no longer protects
the write. Could the converter check the arity of these functions, so that it
returns `None` and the SQL text is used?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -114,37 +112,14 @@ private[sql] class TableConstraintResolution(
// row Spark auto-filled passes it when a later write carries it.
StoredExpressionText.analyze(
check(catalystExpr),
-
check(Option(genExpr.getSql).map(StoredExpressionText.parseWithSessionAnsi)
- .getOrElse(catalystExpr)),
+ check(GeneratedColumn.toCatalyst(
Review Comment:
**[4] Nit: the modeled expression is converted twice per column.** For a
convertible modeled expression, `readSql` is unused, so this call builds the
same tree as `catalystExpr` at L98. Before this PR, the session alternative
reused `catalystExpr` when there was no SQL text. Could the modeled conversion
run once, with only the SQL fallback read twice? This also goes away with the
suggestion in [3].
--
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]