cloud-fan commented on code in PR #60368:
URL: https://github.com/apache/spark/pull/60368#discussion_r4546044003
##########
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 =>
Review Comment:
**Nit (P3):** This map is rebuilt on every `resolveOutput` call, and the
session-fallback pass
(`resolveOutput(StoredExpressionText.parseWithSessionAnsi)`) is a second call.
So a write whose auto-filled column falls back to the session calls the
connector's `capabilities()` and `columns()` again and rebuilds an identical
map, where the base branch built `expected` once and reused it. Only `readSql`
differs between the two passes, so the capability check and the map can be
built once before `resolveOutput`, with each pass only wrapping
`GeneratedColumn.toCatalyst(r, attr.name, expr, readSql)`.
**Verification:**
- **Inspection:** The generation-expression map and the capability check are
computed once per output resolution of a write, and the stored-settings pass
and the session-fallback pass both read that single result, differing only in
how they read SQL text.
##########
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)
Review Comment:
**Non-blocking (P2):** Because this line lets a convertible connector
expression win, the Spark 4.4 SPARK-60757 entry in
`docs/sql-migration-guide.md` no longer describes what a write does for such a
column. The entry still says that a write parses and analyzes the stored text
with ANSI mode on, also for a table created with ANSI off. It gives
`coalesce(s, 1)` with `s = '007'` as storing `7`, and it says that
`spark.sql.legacy.useCurrentConfigsForGeneratedColumn` restores Spark 4.3's
reading. Reading the code, a table created through `CREATE TABLE` with ANSI off
now stores `'007'`, as the updated tests assert. The legacy flag also no longer
changes auto-fill or validation of any column whose connector expression
converts, because it only affects how the SQL text is read, while Spark 4.3.0
auto-filled such a column from its SQL text. Could the entry say that a write
uses the connector expression when Spark can convert it, keeping the implicit
casts of the session that created the t
able, and limit the coalesce example and the legacy-flag sentence to columns
whose text is read?
**Verification:**
- **Inspection:** Each statement in the amended migration note, about which
form a write reads, what the coalesce example stores for tables created with
ANSI on and with ANSI off, and what the legacy flag restores, agrees with the
precedence the write path implements and with the stored values the
generated-column write tests assert.
##########
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)
+ .orElse(Option(genExpr.getSql).map(readSql))
Review Comment:
**Non-blocking (P2):** Now that this fallback runs only when there is no
convertible connector expression, two existing tests no longer exercise the
text path they were written for. 'SPARK-60757: a reserved keyword of an
auto-filled column does not follow the settings of the writer' and
'SPARK-60757: a text the fixed settings cannot analyze is read under the
session' create their tables with `CREATE TABLE`. That stores a convertible
connector expression for `current_date` (a field reference, as
`DataSourceV2DataFrameSuite` asserts for the same DDL) and for
`IDENTIFIER('"a"') + 1`, so their writes convert it and never parse the stored
text. If the text path started following the writer's
`spark.sql.ansi.enforceReservedKeywords`, or lost its session fallback for an
IDENTIFIER string, both tests would still pass, and no other test in the suite
enables reserved-keyword enforcement for a write. Creating these two tables
through the catalog API with SQL-only columns, as 'SPARK-60757: a
text the fixed settings cannot parse is read under the session' already does,
would restore that coverage.
**Verification:**
- **Regression:** With a SQL-only generated column `current_date` over a
column of the same name, a write whose session enables ANSI mode and
reserved-keyword enforcement stores the column's value, and reading the stored
text under the writer's reserved-keyword setting would make the check fail.
- **Regression:** With a SQL-only generated column `IDENTIFIER('"a"') + 1`,
a session with double-quoted identifiers auto-fills the column without a check
and validates a provided value with one, which can only happen when the text
read under the fixed settings fails to analyze and the session reading takes
over.
--
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]