spark-test commented on code in PR #60462:
URL: https://github.com/apache/spark/pull/60462#discussion_r4593566465
##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -742,7 +783,14 @@ object DatasetManager extends Logging {
}
.collect { case (key, Some(value)) => key -> value }
- validatedAndCanonicalizedProps ++ specialProps
+ val declaredPropertyKeys = if (validatedAndCanonicalizedProps.nonEmpty) {
Review Comment:
**Non-blocking (P2):** Whenever the definition declares a table property,
this adds `pipelines.declaredPropertyKeys` to the properties that
`materializeTable` passes to `createTable`. `JDBCTableCatalog.createTable`
appends every property except `comment`, `provider`, `owner` and `location` to
`JDBC_CREATE_TABLE_OPTIONS`, and the JDBC dialect appends those options
verbatim after the column list.
By my reading of the code, `CREATE MATERIALIZED VIEW sales_summary
TBLPROPERTIES ('ENGINE' = 'InnoDB') AS SELECT ...` in a MySQL-backed JDBC
catalog now sends `CREATE TABLE ... (...) ENGINE InnoDB
pipelines.declaredPropertyKeys ["ENGINE"]`, which the database rejects, so the
update fails with `TableMaterializationException`. On the base branch that run
creates the table and fills it with `saveAsTable`. The same happens to a
definition whose only table property is a comment or an owner, which the JDBC
catalog turns into the table comment or ignores. Refreshing such a view already
fails on the base branch, because JDBC tables do not support `TRUNCATE TABLE`,
so the run that creates it is the one this change breaks.
The record cannot do anything for a JDBC table: `JDBCTable` reports no
properties, so it is never read back, and `JDBCTableCatalog.alterTable` rejects
property changes. The rejection itself comes from the database's DDL parser,
outside Spark.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60462#discussion_r4584763648).
**Recommended change:** Keep the declared-keys record out of catalogs that
turn table properties into DDL: when the target catalog is a JDBCTableCatalog,
resolveTableProperties adds no pipelines.declaredPropertyKeys, so a JDBC view's
CREATE TABLE statement carries only the options its definition declares, as on
the base branch. Add a pipeline materialization test against an H2-backed JDBC
catalog that checks the properties reaching createTable; the pipelines module
has no H2 test dependency yet, so add the one the sql/core JDBC catalog tests
use, because a generic recording catalog would not take the JDBC branch. Say in
the declaredPropertyKeys Scaladoc that tables in a JDBC catalog do not get the
record.
**Why this works:** materializeTable already resolves the target catalog
before it builds the properties, so it can tell resolveTableProperties whether
to add the record. A JDBC table reports no properties, so its record could
never be read back to drive a removal, and leaving it out changes nothing else
for that table. evolveTable needs no change: it reads the record only from the
existing table, and a JDBC table never reports one. A JDBC materialized view
never reaches evolveTable, because its refresh fails at TRUNCATE TABLE first,
and a JDBC streaming table that reaches it on an incremental run fails at
alterTable on any declared property exactly as on the base branch, because the
JDBC dialect rejects property changes.
**Scope:** Decide in the pipeline's table-property resolution whether the
target catalog gets the declared-keys record, and cover the JDBC case with a
materialization test against an H2-backed JDBC catalog.
**Compatibility:** Catalogs other than JDBCTableCatalog keep receiving and
maintaining the declared-keys record exactly as this PR implements it.
**Risks:** A materialized view in a JDBC catalog never gets the record, so
dropped properties are never removed from it; this changes nothing in practice,
because the pipeline cannot refresh a JDBC table. Catalogs outside this
repository that also turn table properties into DDL, or that reject unknown
keys, still receive the record, because the fix recognizes only
JDBCTableCatalog.
**Constraints:** Every other catalog must keep receiving the record on
create and evolve, so property removal and the record's lifecycle stay as this
PR defines them. The JDBC CREATE TABLE statement must carry the declared
options exactly as on the base branch.
**Exclusions:**
- Catalogs outside this repository that turn table properties into DDL are
left to their owners; recognizing them in general would need a new catalog
capability, which this fix does not add.
**Success:** A materialized view in a JDBC catalog whose definition declares
table properties is created with a CREATE TABLE statement that carries only the
declared options, without pipelines.declaredPropertyKeys. In every other
catalog, the record is still written when the definition declares a property,
and dropped recorded properties are still removed. The declaredPropertyKeys
Scaladoc says that tables in a JDBC catalog do not get the record.
**Verification:**
- **Regression:** Materializing a view into a JDBC catalog with a declared
table property passes no pipelines.declaredPropertyKeys to the catalog's
createTable, so the CREATE TABLE statement contains only the declared options.
- **Compatibility:** On the recording catalog and the session catalog, a
definition that declares properties still writes the record on create and
evolve, and a dropped recorded property is still removed in the same alterTable.
##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/JsonStringArrayCodec.scala:
##########
@@ -0,0 +1,50 @@
+/*
+ * 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.pipelines.graph
+
+import scala.util.control.NonFatal
+
+import org.json4s.JsonAST.{JArray, JString}
+import org.json4s.jackson.JsonMethods
+
+/**
+ * Codec for table property values that hold a list of strings as a JSON
string array, e.g.
+ * `["id","region"]`. Used for
[[PipelinesTableProperties.declaredPropertyKeys]] and for the
+ * column-name lists [[AutoCdcAuxiliaryTable]] records on auxiliary tables. An
empty list
+ * round-trips as `[]`; whether an empty list is meaningful is up to the
caller.
+ */
+private[graph] object JsonStringArrayCodec {
+
+ def serialize(values: Seq[String]): String = {
+ JsonMethods.compact(JArray(values.map(JString(_)).toList))
+ }
+
+ /**
+ * Parses a value written by [[serialize]]. `None` if it is not JSON, or not
a JSON array whose
+ * elements are all strings, so that callers can treat a malformed value as
absent.
+ */
+ def parse(raw: String): Option[Seq[String]] = {
+ val parsed = try Some(JsonMethods.parse(raw)) catch { case NonFatal(_) =>
None }
Review Comment:
**Nit (P3):** `JsonMethods.parse` in json4s-jackson 4.0.7 reads through an
`ObjectReader` that rejects input after the first value only when
`DeserializationFeature.FAIL_ON_TRAILING_TOKENS` is enabled, and that feature
is off by default in jackson-databind 2.22.4. By my reading of those sources, a
record set with `ALTER TABLE ... SET TBLPROPERTIES` to `["p.stale"]x`,
`["p.a"]]` or `["p.a"],["p.b"]` parses to its leading array, so the next run
removes `p.stale` once the definition no longer declares it, instead of
treating the record as malformed and rewriting it. That contradicts this
method's Scaladoc and the rule that a record that is not a JSON string array
removes nothing, and `JsonStringArrayCodecSuite` has no negative case with a
complete array followed by more input. Only a hand-edited record can reach this.
Reading through the json4s mapper's `ObjectReader` with
`FAIL_ON_TRAILING_TOKENS` enabled, keeping the `NonFatal` to `None` mapping,
and adding such inputs to the negative cases would close it. The AutoCDC
column-name properties share this parse, so a hand-corrupted one would then
fail with the existing `AUXILIARY_TABLE_PROPERTY_MALFORMED` error instead of
being read as its leading array.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60462#discussion_r4584763640).
**Verification:**
- **Regression:** Parsing a JSON string array followed by trailing text, an
extra closing bracket, or a second array returns no value, and a table whose
declared-keys record has such trailing content keeps the properties that array
lists and ends with a well-formed record.
- **Compatibility:** Lists the codec writes still parse back unchanged,
including the empty list, keys that need JSON escaping, and arrays with
whitespace inside or after them.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/V2SessionCatalogSuite.scala:
##########
@@ -379,6 +379,54 @@ class V2SessionCatalogTableSuite extends
V2SessionCatalogBaseSuite {
assert(filterV2TableProperties(table.properties) == Map())
}
+ test("SPARK-57670: alterTable keeps the comment and collation when no change
names them") {
+ val catalog = newCatalog()
+ // A table created by DDL keeps its comment and default collation only in
the dedicated fields
+ // of the catalog table, not in its properties.
+ spark.sql(s"CREATE TABLE $testIdentQuoted (id INT, data STRING) USING
parquet " +
+ "COMMENT 'table comment' DEFAULT COLLATION UTF8_LCASE")
+ val created =
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+ assert(created.comment.contains("table comment"))
+ assert(created.collation.contains("UTF8_LCASE"))
+ assert(!created.properties.contains(TableCatalog.PROP_COMMENT))
+ assert(!created.properties.contains(TableCatalog.PROP_COLLATION))
+
+ catalog.alterTable(testIdent, TableChange.setProperty("prop-1", "1"))
+ val afterSet =
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+ assert(afterSet.properties.get("prop-1").contains("1"))
+ assert(afterSet.comment.contains("table comment"))
+ assert(afterSet.collation.contains("UTF8_LCASE"))
+
+ catalog.alterTable(testIdent, TableChange.removeProperty("prop-1"))
+ val afterRemove =
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+ assert(!afterRemove.properties.contains("prop-1"))
+ assert(afterRemove.comment.contains("table comment"))
+ assert(afterRemove.collation.contains("UTF8_LCASE"))
+ }
+
+ test("SPARK-57670: alterTable sets or removes the comment and collation a
change names") {
+ val catalog = newCatalog()
+ spark.sql(s"CREATE TABLE $testIdentQuoted (id INT, data STRING) USING
parquet " +
+ "COMMENT 'table comment' DEFAULT COLLATION UTF8_LCASE")
+
+ catalog.alterTable(testIdent,
TableChange.setProperty(TableCatalog.PROP_COMMENT, "new comment"))
+ val afterComment =
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+ assert(afterComment.comment.contains("new comment"))
+ assert(afterComment.collation.contains("UTF8_LCASE"))
+
+ catalog.alterTable(testIdent,
TableChange.setProperty(TableCatalog.PROP_COLLATION, "UNICODE"))
+ val afterCollation =
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+ assert(afterCollation.comment.contains("new comment"))
+ assert(afterCollation.collation.contains("UNICODE"))
+
+ catalog.alterTable(testIdent,
Review Comment:
**Nit (P3):** This step removes `comment` and `collation` in one
`alterTable`, and it is the only removal of either field in these tests; the
new `HiveDDLSuite` test and the `MaterializeTablesSuite` comment tests remove
the comment only from tables that have no collation. `COMMENT ON TABLE t IS
NULL` sends only `RemoveProperty(comment)`, and this PR promises it no longer
clears the default collation. By my reading, a one-word slip that makes the
collation branch call `removesProperty(changes, TableCatalog.PROP_COMMENT)`
would pass every suite while making that command clear the collation as well. A
step that removes only the comment while the collation is set, and one that
removes only the collation while the comment is set, each asserting that the
other field survives, would pin the per-field rule.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60462#discussion_r4584763625).
**Verification:**
- **Regression:** Removing only the comment from a session-catalog table
with a default collation leaves the collation set, and removing only the
collation from a table with a comment leaves the comment set; making the
collation branch test the comment key, or clearing both fields on any
reserved-key removal, makes this coverage fail.
##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/PipelinesTableProperties.scala:
##########
@@ -37,6 +37,27 @@ object PipelinesTableProperties {
val resetAllowed: PipelineTableProperty[Boolean] =
buildProp("pipelines.reset.allowed", default = true)
+ /**
+ * Internal table property recording, as a sorted JSON string array (see
+ * [[JsonStringArrayCodec]]), the keys of the table properties declared in
the dataset definition
+ * (SQL `TBLPROPERTIES`, Python `table_properties`) as of the latest
materialization.
+ *
+ * `DatasetManager` writes it, through `resolveTableProperties`, only when
the definition declares
+ * at least one table property. It covers those declared keys, not the
`comment` and `provider`
+ * entries derived from the dataset's comment and format. On the next
materialization,
+ * `evolveTable` removes a recorded key when the definition no longer
declares it, it is still on
Review Comment:
**Nit (P3):** The rewrite now states the presence check, the reserved-key
exemption and ownership by declaration, but two cases still read wrong against
`evolveTable`. This line says a recorded key is removed when the definition no
longer declares it, and lines 53-54 say the record is removed together with the
last declared property. `evolveTable` tests whether the resolved properties
still contain the key, and those include the comment taken from the
definition's comment field. So a comment moved from `TBLPROPERTIES` to the
comment field stays while only the record goes, as 'a comment moved from the
table properties to the comment field stays' asserts. And when the last
declared property is a reserved key such as `owner` from Python
`table_properties`, dropping it removes the record but keeps `owner`.
Separately, the `@param properties` entry of `evolveTable` says any property
outside its listed conditions is left in place, yet the record itself is
removed once `properties` no lo
nger carries it.
Stating the condition as the code applies it (the resolved properties,
including the comment and provider derived from the definition, no longer
contain the key), saying that the record is removed once the definition
declares no table property, and adding the record's own removal to the `@param`
entry would make both comments match the code.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60462#discussion_r4584763630).
**Verification:**
- **Inspection:** Read against evolveTable's removal code, every condition
the declaredPropertyKeys Scaladoc and the evolveTable @param entry state
matches the code, including a comment supplied through the comment field, a
non-removable reserved key, and the record's own removal.
##########
docs/sql-migration-guide.md:
##########
@@ -100,6 +100,7 @@ license: |
- Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT`
adds to a Data Source V2 table, and whose condition reads the current time,
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db =
current_database()`, is checked against their values at the time of each write.
Previously, it was checked against their values at the time of the `ALTER
TABLE`, unless a write could not read back a predicate for its condition, such
as one with a lambda function or one that passes a column to `datediff`, `year`
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so
each write parses and analyzes its SQL text under the session of the write, as
it does for a constraint without a predicate that `CREATE TABLE` adds. A
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it
fail to parse the text or read it differently. A row-level operation
that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A
condition that Spark detects a write could resolve differently is stored as
before, so a write accepts and rejects the same rows for it as before. Examples
are conditions that also read a variable, a `CHAR` column, a name with more
than one part such as a column qualified by the table name, or a constant that
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a
timestamp. So are conditions with a name such as `current_date` or `user`
without parentheses, which a write can read as a column name, and conditions
whose text the parser settings of the `ALTER TABLE`, such as
`spark.sql.ansi.doubleQuotedIdentifiers` or
`spark.sql.parser.escapedStringLiterals`, r
ead differently from their default values. ANSI mode,
`spark.sql.timestampType` and the session time zone are taken from the session
for this comparison, as for a generation expression. A condition that reads the
current date or time only through a typed literal such as `DATE 'today'` is
also stored as before. An existing constraint keeps its stored predicate until
it is dropped and added again. `Check.predicate()` is null for a constraint
stored without a predicate, so a connector that validates or enforces it itself
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding
the constraint. A constraint added without it is not changed.
- Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'`
whose class implements
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends
either a Hive UDF class (such as `UDF` or `GenericUDF`) or
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions
created in earlier versions. Its result type, argument coercion, and null
handling are defined by the V2 implementation selected by
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic`
property do not control the V2 path. For scalar functions, determinism uses
`BoundFunction.isDeterministic()` (default `true`) and the arguments'
determinism. A call with constant arguments can therefore become eligible for
constant folding during query planning instead of being evaluated per row.
- Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW`
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc`
fails with it when the result is earlier than the minimum `DATE`,
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these
functions silently returned a wrong date, in most cases one at the other end of
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`.
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday,
and now return `-5877641-06-29`.
+- Since Spark 4.4, [Declarative
Pipelines](declarative-pipelines-programming-guide.html) removes a table
property from a materialized view or streaming table when the property is
dropped from the dataset definition (SQL `TBLPROPERTIES` or Python
`table_properties`). Previously, a dropped property stayed on the table. A
table whose definition declares at least one table property now carries the
table property `pipelines.declaredPropertyKeys`, which lists the declared keys.
A table created before this change gets the record on its first run after
upgrading whose definition declares a property, and a dropped property is
removed starting with the run after the one that first recorded the table's
declared keys. Properties the definition never declared, such as those managed
by the catalog or set with `ALTER TABLE ... SET TBLPROPERTIES`, are left in
place. To keep a property on the table, declare it in the dataset definition.
Review Comment:
**Nit (P3):** By my reading of `evolveTable`, a property is removed only if
a record written by an earlier run lists it, and the first run that writes the
record lists only that run's declared keys. So a property dropped before a
table first records its declared keys stays for good, whether an earlier
version left it behind or it was dropped on the first run after upgrading;
'dropped properties are not removed from a table without a declared-keys
record' asserts this. This entry does not say so, and the new
`table_properties` docstrings in `api.py` and `output.py` promise removal 'on
the next pipeline run'. Reserved keys other than `comment`, such as `owner`,
which Python `table_properties` passes through, are recorded but never removed.
The entry also says a table 'gets the record' without naming
`pipelines.declaredPropertyKeys` as that record.
Naming the property, saying that properties dropped before the first
recording stay and can be removed with `ALTER TABLE ... UNSET TBLPROPERTIES`,
and noting the reserved-key exception, here and in the docstrings or by
pointing the docstrings here, would make the documentation match the code.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60462#issuecomment-6925299091).
**Verification:**
- **Inspection:** The migration-guide entry names
pipelines.declaredPropertyKeys, and states that properties dropped before a
table first records its declared keys stay on the table and that reserved keys
other than comment passed through Python table_properties are never removed.
- **Inspection:** Each of the four table_properties docstrings either states
the same exceptions or points to the migration guide, and none promises
unconditional removal on the next pipeline run.
--
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]