Repository navigation
[Spark] Keep comment and table properties on non-Delta tables - #2228
Conversation
UCProxy.loadV1Table built the CatalogTable for every format without a comment or table properties and put all UC properties into the storage properties. For Parquet, ORC, JSON and CSV tables this dropped COMMENT and TBLPROPERTIES from DESCRIBE, SHOW TBLPROPERTIES and catalog.getTable, and passed every table property to the reader and writer as an option. Non-Delta tables now split UC properties the way Spark stores them: option.-prefixed keys become data source options with the prefix removed, and the remaining keys (minus the bare copies Spark writes for each option) become table properties. The comment is set from the UC table. Delta tables are unchanged, since Delta reads the UC table id from the storage properties and its comment and properties from the log. Signed-off-by: Maha Rana Yadavalli <[email protected]>
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] The approach matches Spark's own convention, and the Delta path is unchanged. Please fix the bare-key collision (inline, UCSingleCatalog.scala) and document a migration path for existing REST or CLI tables that use bare reader keys. The test restructuring is the main ask. The remaining items are nits.
| properties: Map[String, String]): (Map[String, String], Map[String, String]) = { | ||
| val (prefixed, bare) = properties.partition(_._1.startsWith(TableCatalog.OPTION_PREFIX)) | ||
| val options = prefixed.map { case (k, v) => k.stripPrefix(TableCatalog.OPTION_PREFIX) -> v } | ||
| (bare -- options.keys, options) |
There was a problem hiding this comment.
[AI Assisted] The bare copy is dropped by name, whatever its value. Spark writes the same value for both copies, but a table created through the REST API or CLI can set header and option.header to different values. Then the bare header table property is lost without a warning. Could we drop a bare key only when its value equals the option value, for example bare.filterNot { case (k, v) => options.get(k).contains(v) }?
There was a problem hiding this comment.
Done in 849ecb9. A bare key is dropped only when its value equals the option value, and the scaladoc says so.
| 5. `properties`: _\[Optional\]_ The properties of the table in JSON format | ||
| (e.g., `'{"key1": "value1", "key2": "value2"}'`). Make sure to either escape the double quotes(`\"`) inside the properties string or just use single quotes(`''`) around the same. | ||
| When Spark reads a non-Delta table, only keys prefixed with `option.` are passed to the reader and writer, with the | ||
| prefix removed (e.g., `'{"option.header": "true"}'` for a CSV file with a header row). This matches what Spark's |
There was a problem hiding this comment.
[AI Assisted] This stops passing bare keys to the reader for existing non-Delta tables created through the REST API or CLI, so a table registered with a bare header no longer reads with a header row. The change is disclosed here, but existing tables have no migration path in the doc. Could the doc say how an existing table is fixed, for example by re-registering with the option. key, and add the same note to the PR description?
There was a problem hiding this comment.
Added in c520524. The doc and PR description say to re-register existing tables with option.-prefixed keys, for example option.header.
| import org.junit.jupiter.params.provider.ValueSource; | ||
|
|
||
| /** COMMENT, TBLPROPERTIES and OPTIONS of external tables as Spark sees them after a reload. */ | ||
| public class ExternalTableMetadataTest extends BaseSparkIntegrationTest { |
There was a problem hiding this comment.
[AI Assisted] Please fold this class into existing tests instead of keeping a new class. ParquetExternalTableReadWriteTest.testLoadTableKeepsColumnDefaultValue (line 72 of ParquetExternalTableReadWriteTest.java) already creates an external table through UC and loads it, so it is the right host. Add three cases there: (1) a comment with quotes and unicode, checked through session.table(...).description() and the DESCRIBE TABLE EXTENDED Comment row; (2) TBLPROPERTIES ('pathGlobFilter' = '*.nothing'), checked with SHOW TBLPROPERTIES, and a read that still returns every row, which shows the property is not applied as a reader option; (3) a missing comment, as a second table in the same method. The Delta case is already covered by DeltaManagedTableReadWriteTest. Move the option.-only case and the bare-vs-option collision case to UCProxySuite as mock tests, which need no server or session. That removes this class and its 15 server and session starts per job.
There was a problem hiding this comment.
Done in c520524. I removed ExternalTableMetadataTest, added the three cases to ParquetExternalTableReadWriteTest and moved the option-only and collision cases to UCProxySuite.
| } | ||
|
|
||
| @Test | ||
| public void testCsvOptionsStayReaderOptions() throws IOException { |
There was a problem hiding this comment.
[AI Assisted] Optional, not required: the reader check on the Parquet table already covers the option routing, since the reader and writer take the same storage properties. If you want a writer check, one insert on the same table would cover it at no extra server cost.
There was a problem hiding this comment.
Added one insert on the same Parquet table in c520524, so writer options are covered without another server start.
| schema = StructType(fields), | ||
| provider = Some(t.getDataSourceFormat.getValue.toLowerCase()), | ||
| properties = tableProperties, | ||
| comment = if (isDelta) None else Option(t.getComment), |
There was a problem hiding this comment.
[AI Assisted] A short note here would stop someone from setting the Delta comment from UC later: Delta takes its comment and table properties from the Delta log. The scaladoc could also say that a bare key equal to an option key is dropped.
There was a problem hiding this comment.
Added in 849ecb9. The comment says Delta takes its comment and table properties from the Delta log.
| (e.g., `'{"key1": "value1", "key2": "value2"}'`). Make sure to either escape the double quotes(`\"`) inside the properties string or just use single quotes(`''`) around the same. | ||
| When Spark reads a non-Delta table, only keys prefixed with `option.` are passed to the reader and writer, with the | ||
| prefix removed (e.g., `'{"option.header": "true"}'` for a CSV file with a header row). This matches what Spark's | ||
| `OPTIONS (header 'true')` stores. Other keys are table properties. |
There was a problem hiding this comment.
[AI Assisted] Spark stores both header and option.header for OPTIONS, and the connector ignores the bare copy, so 'matches what Spark stores' is not quite right. Could the sentence say only that option.-prefixed keys become reader and writer options?
There was a problem hiding this comment.
Reworded in 849ecb9. It now says only that option.-prefixed keys become reader and writer options
| */ | ||
| private def splitOptionsFromTableProperties( | ||
| properties: Map[String, String]): (Map[String, String], Map[String, String]) = { | ||
| val (prefixed, bare) = properties.partition(_._1.startsWith(TableCatalog.OPTION_PREFIX)) |
There was a problem hiding this comment.
[AI Assisted] This decodes the option. prefix a second time, and UCTableProperties.withoutOptionPrefix already does it. Could the split move next to that helper so the convention lives in one place?
There was a problem hiding this comment.
Moved in 849ecb9. The split now sits next to UCTableProperties.withoutOptionPrefix, so the convention lives in one place.
… tests Drop a bare property only when it duplicates its option. copy with the same key and value, so a REST-created table with a different bare value keeps it as a table property. Move the split into UCTableProperties next to withoutOptionPrefix and unit test it, and cover loadTable for CSV and Delta in UCProxySuite. Add CSV writer tests for OPTIONS and for a header table property, and explain the option. rule in the CLI and Spark docs. Signed-off-by: Maha Rana Yadavalli <[email protected]>
Replace ExternalTableMetadataTest with one Parquet case in ParquetExternalTableReadWriteTest (comment with quotes and non-ASCII text, a pathGlobFilter table property that must not reach the reader, an insert, and a second table without a comment) and two mock UCProxySuite cases for option.-only properties and bare keys that collide with an option. Document how to fix an existing table that relies on a bare reader-option key. Signed-off-by: Maha Rana Yadavalli <[email protected]>
Signed-off-by: Maha Rana Yadavalli <[email protected]>
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Approving, with two inline follow-ups (writer check, cli.md wording) that are not blocking.
| "CREATE TABLE %s (i INT, s STRING) USING PARQUET COMMENT 'Sales \"Q3\" café 日本 it\\'s'" | ||
| + " TBLPROPERTIES ('pathGlobFilter' = '*.nothing') LOCATION '%s'", | ||
| fullTableName, getLocation(options)); | ||
| sql("INSERT INTO %s VALUES (1, 'a'), (2, 'b')", fullTableName); |
There was a problem hiding this comment.
[AI Assisted] This insert does not check the writer side. The table has only a table property, so no writer option is asserted, and the reply that says writer options are covered is not accurate. Could we either assert a writer option here (for example a Parquet write option that changes the output files), or correct the reply and drop the writer claim from the test description?
| (e.g., `'{"key1": "value1", "key2": "value2"}'`). Make sure to either escape the double quotes(`\"`) inside the properties string or just use single quotes(`''`) around the same. | ||
| For non-Delta tables read or written through the Unity Catalog Spark connector, only keys prefixed with `option.` | ||
| become reader and writer options, with the prefix removed (e.g., `'{"option.header": "true"}'` for a CSV file with | ||
| a header row). Other keys, such as a bare `header`, are table properties. This applies to tables created through |
There was a problem hiding this comment.
[AI Assisted] Nit: this says other keys, such as a bare header, are table properties. A bare key that duplicates an option with the same value is dropped, not kept as a table property, so this is not always true. Could we say a bare header with no matching option. header, or add unless option.header has the same value?
…#2232) **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [ ] If there is a related issue, make sure it is linked to this PR. - [x] If you've fixed a bug or added code that should be tested, add tests! - [x] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** For a partitioned table of a file-source format (Parquet, ORC, JSON, CSV, Avro or text) whose partition column is not declared last, `DESCRIBE TABLE` shows a different column order than the one Spark reads and writes. After `CREATE TABLE t (a INT, p INT, b INT) USING parquet PARTITIONED BY (p) LOCATION '...'`, `DESCRIBE TABLE t` lists `a, p, b`, while `SELECT *` returns `a, b, p` and `INSERT INTO t VALUES (...)` takes the values in that order too. A user who writes `INSERT INTO t VALUES (1, 2, 3)` following `DESCRIBE` gets `p = 3` and `b = 2`, in partition directory `p=3`, with no error. When the swapped columns have types that can't be cast to each other, the insert fails with `CANNOT_SAFELY_CAST` instead, which is confusing given what `DESCRIBE` shows. `UCProxy.loadV1Table` builds the `CatalogTable` schema in UC's declared column order and also sets `partitionColumnNames`. Spark's file sources treat the schema as data columns followed by partition columns, and Spark's own catalog stores it that way (it moves the partition columns last at CREATE), so the relation Spark scans and writes is `a, b, p` while the schema the catalog returns, which `DESCRIBE` shows, is `a, p, b`. For tables of those file-source formats the connector now builds the schema from the non-partition columns in UC order followed by the partition columns in partition index order, so with `PARTITIONED BY (q, p)` the schema ends in `q, p` whatever the declared order. Column comments, defaults and other metadata stay on each field, since the fields are built the same way and only reordered. Tables of other formats keep the declared order. Delta takes its schema from the Delta log, and Iceberg or any format added later is left alone so it does not change by default. This matches Spark's built-in catalog for the same DDL. On Spark 4.0 and 4.1, `CREATE TABLE spark_catalog.default.t (a INT, p INT, b STRING) USING parquet PARTITIONED BY (p)` also describes as `a, b, p`, and `SELECT *` and `INSERT ... VALUES` use that order. UC still stores and returns the columns in the declared order, so the REST API, the CLI and other engines see no change, and a table created through the REST API with `partition_index` set is reordered the same way when Spark loads it. Backward compatibility: no data written before this change is affected, since `SELECT *` and `INSERT ... VALUES` already used the data-then-partition order. What changes is the column order `DESCRIBE TABLE` and the loaded table's schema report for these tables. CTAS into a file-source UC table fails before and after this change, and no table is left behind. Before, Spark rejected it because the table does not support batch append. Now, when the partition column is not last in the query, the positional cast check runs first and reports `INCOMPATIBLE_DATA_FOR_TABLE.CANNOT_SAFELY_CAST` instead, the same as an `INSERT ... VALUES` in that order would. PR #2228 also edited `loadV1Table` (comment and table properties for non-Delta tables). It has merged, and this branch merges main without conflicts. Tests: `ParquetExternalTableReadWriteTest.testLoadTableKeepsColumnMetadataAndListsPartitionColumnsLast` runs against a real UC server. It creates a Parquet table with the partition column in the middle, writes with a positional `INSERT ... VALUES` and with a column list that leaves out a column with a `DEFAULT`, and checks the `DESCRIBE TABLE` rows (including the comment of the moved partition column) and `SELECT *`. It does the same for a table with two partition columns `PARTITIONED BY (q, p)` declared as `p` before `q`, which covers the partition index sort. `DeltaExternalTableReadWriteTest.testPartitionedTableKeepsDeclaredColumnOrder` checks that a partitioned Delta table keeps its declared order. `UCProxySuite` loads a table as it comes from the REST API with `partition_index` set, without a server, and checks the loaded schema, the partition order, and that a moved column keeps its comment and default for each of the six file-source formats, and that Delta and Iceberg keep the declared order. I ran these on Linux (GitHub Actions on my fork) against Spark 4.1.0 with Delta 4.4.1. With the fix reverted, `testLoadTableKeepsColumnMetadataAndListsPartitionColumnsLast` and all six file-source cases of `testLoadFileSourceTablePutsPartitionColumnsLast` fail on the column order, while the Delta and Iceberg cases pass. I also checked locally that with the earlier version of this PR, which reordered every format except Delta, the Iceberg case of `testLoadNonFileSourceTableKeepsUCColumnOrder` fails. With the fix, all of them pass, and the full `spark/test` suite passes (293 tests, 0 failures). Spark 4.0, 4.2 and 4.3 are left to the CI matrix. ``` build/sbt "spark/testOnly io.unitycatalog.spark.ParquetExternalTableReadWriteTest io.unitycatalog.spark.DeltaExternalTableReadWriteTest io.unitycatalog.spark.UCProxySuite" build/sbt spark/test ``` --------- Signed-off-by: Maha Rana Yadavalli <[email protected]> Co-authored-by: Maha Rana Yadavalli <[email protected]>
…#2324) **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [x] If there is a related issue, make sure it is linked to this PR. - [x] If you've fixed a bug or added code that should be tested, add tests! - [ ] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** A non-Delta table loses a data source option whose name is also a reserved table property. For example, `CREATE TABLE t (s STRING, i INT) USING CSV OPTIONS (comment '#') LOCATION '...'` stores no comment option. So for a file holding "# exported by tool", "x,1" and "y,2", `SELECT * FROM t` returns three rows starting with `["# exported by tool", null]` instead of the two rows that `spark.read.option("comment", "#")` gives. Spark hands each option to the catalog as `option.<key>`, and `UCTableProperties.shouldPersistProperty` removed that prefix before checking the reserved keys, so `option.comment` matched the table comment key and was never sent to the server. #1830, shipped in 0.7.0, stopped storing it. Earlier releases stored it, but the reader never saw it until #2228 started stripping the `option.` prefix on load, so tables created by 0.6.0 already have the option stored and read correctly on `main`. In SQL only `comment` reaches the catalog this way, and also `table_type` on Spark 4.0, where it isn't reserved. The parser rejects the other reserved names in OPTIONS, or drops them when `spark.sql.legacy.notReserveProperties` is set. A TBLPROPERTIES key such as `option.owner` was dropped the same way. The check now compares the reserved keys with the key as Spark passes it. So the bare reserved keys are still dropped, and an `option.` key with the same name is stored like any other option. Vended `fs.*` credentials and Spark schema JSON are still dropped with or without the prefix. `UCProxy.createTable` and the Spark 4.2 and later `createView` path both use this method. Tables created by 0.7.0 have no stored comment option. To fix an external one, drop it and create it again with the same LOCATION and the same `OPTIONS (comment ...)` clause. An `option.` key set through TBLPROPERTIES with one of these names is now stored, and on a non-Delta table it's used as a reader option, as other `option.` keys already are. A managed Delta table shows a kept `option.comment` as `option.option.comment` through `DeltaTableV2.properties`, the same route every other stored option key already takes. Spark also passes each option without the prefix, and a COMMENT clause replaces that copy, so `OPTIONS (comment '#')` on its own made "#" the table comment. For non-Delta tables, `createTable` now ignores a table comment equal to `option.comment`, using the same `UCTableProperties.isBareCopyOfOption` rule the load path uses to drop the bare copy of each option. It has the same trade-off. Spark passes the same properties for `COMMENT '#' OPTIONS (comment '#')` as for the option alone, so that explicit description is dropped too and the table has no comment. Delta tables keep the comment they are given. **Tests** `UCTablePropertiesTest` checks each of the eight reserved names in both forms. `UCProxySuite.testCsvCommentOptionSkipsCommentLines` runs a SparkSession against a mocked UC store and reads a CSV file through a table with `OPTIONS (comment '#')` through a second table that also has `COMMENT 'Exported rows'`, and through a third with `COMMENT '#'` equal to the option. It checks that all three skip the comment line, that the first and third have no table comment, and that the second keeps its comment. The full `UCProxySuite` passes on Spark 4.0.0 locally (35 of 35). The test fake now stores what `createTable` sent, so a CSV table round-trips with its format, comment and options. `UCProxySuite.testCreateTableCommentEqualToCommentOption` checks that a CSV table drops a comment equal to the option, that an external and a managed Delta table keep it, and that each stores `option.comment` and no bare `comment` property. `UCViewProxySuite.testCreateViewKeepsOptionKeyNamedLikeReservedKey` checks that `createView` stores `option.comment` and keeps the view comment as the comment field. On `main` the new tests fail. Putting back the old prefix-stripped check, removing the reserved-key check, checking `fs.` without the prefix, removing the comment rule, or dropping its non-Delta condition each makes a test fail. Putting back the prefix-stripped reserved-key check also fails the new stored-property and view assertions. On Windows with JDK 17 at the current head, `UCTablePropertiesTest` and the `createTable` tests in `UCProxySuite` pass on Spark 4.1, `UCViewProxySuite` passes on 4.2 (37 of 37), and `spark/javafmtCheckAll` and checkstyle pass. The `UCProxySuite` tests that write files through Hadoop, including `testCsvCommentOptionSkipsCommentLines`, need Hadoop's native Windows library, which this machine lacks, so they run in CI. The server-backed suites run in CI too. --------- Signed-off-by: Maha Rana Yadavalli <[email protected]> Co-authored-by: Maha Rana Yadavalli <[email protected]>
PR Checklist
docsis updatedDescription of changes
Non-Delta tables (Parquet, ORC, JSON, CSV, Avro, text) lose their comment and table properties when Spark loads them through
UCSingleCatalog.UCProxy.loadV1Tablebuilds theCatalogTablewithoutcommentorpropertiesand puts every UC property into the storage properties. So afterCREATE TABLE ... USING CSV COMMENT 'c' TBLPROPERTIES ('k' = 'v'),DESCRIBE TABLE EXTENDEDhas no Comment row,spark.catalog.getTable(...).descriptionis null, andSHOW TBLPROPERTIES t ('k')says the table has no such property (it only showsoption.k). Every table property also reaches the reader and writer as an option, soTBLPROPERTIES ('header' = 'true')on a CSV table makes Spark skip the first data row on read and write a header row on insert. The view path already sets both fields.For non-Delta tables the connector now splits the UC properties the way Spark stores them. Spark writes each
OPTIONS (...)entry twice, bare and with theoption.prefix. Theoption.keys become the storage properties (reader and writer options) with the prefix removed, which is how Spark's session catalog builds them. The other keys become table properties, except that a bare key is dropped whenoption.<key>with the same case holds the same value, since that is Spark's duplicate of the option. A bare key with a different value, such as one set through the REST API, stays a table property. The comment comes from the UC table, and vended credentials still go into the storage properties. The split lives inUCTableProperties.dataSourceOptionsandtablePropertiesWithoutOptions, next to the existingoption.prefix handling.Delta tables are unchanged. They keep all UC properties as storage properties, since Delta reads
io.unitycatalog.tableIdthere, and Delta takes its comment and table properties from the Delta log.Backward compatibility: tables created by Spark already carry both forms of each option, so reads and writes behave as before apart from table properties no longer leaking into reader and writer options. A non-Delta table created through the REST API or CLI with a bare key such as
headermeant as a reader option no longer passes it to the Spark reader or writer. To fix such a table, delete it and create it again with the same storage location andoption.header. Deleting an external table does not delete its data files.docs/usage/cli.mddescribes this, anddocs/integrations/unity-catalog-spark.mdpoints to it.Tests:
ParquetExternalTableReadWriteTest.testLoadTableKeepsCommentAndTablePropertiesruns Spark against a real UC server. It creates an external Parquet table with a comment containing quotes and non-ASCII text andTBLPROPERTIES ('pathGlobFilter' = '*.nothing'), inserts two rows, and checks that a read returns both rows (the property is not a reader option), thatSHOW TBLPROPERTIESlists the property, and that the comment shows up inspark.catalog.getTable(...).descriptionand in theDESCRIBE TABLE EXTENDEDComment row. A second table without a comment has no description and no Comment row.UCProxySuitechecks theCatalogTablethatloadTablebuilds from a mocked UC response:option.-only properties become options while other keys stay table properties, and a bare key is dropped only when it duplicates its option with the same value and case.DeltaManagedTableReadWriteTestandDeltaExternalTableReadWriteTest.With the
UCSingleCatalog.scalachange reverted, all three new tests fail (45 cases run across both classes, 3 failed). With the change, all 45 pass on Spark 4.0 and 4.1, and the fullspark/testsuite passes on Spark 4.0.