Skip to content

[Server] Return table columns in ordinal position order - #2031

Merged
yili-db merged 2 commits into
unitycatalog:mainfrom
s-maling-celonis:fix-column-order
Oct 25, 2026
Merged

yili-db merged 2 commits into
unitycatalog:mainfrom
s-maling-celonis:fix-column-order

Conversation

@s-maling-celonis

@s-maling-celonis s-maling-celonis commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

PR Checklist

  • 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.
  • 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 (not applicable)

Description of changes

The server returns a table's columns in whatever order the database returns the uc_columns rows, not in ordinal_position order. The columns relationship on TableInfoDAO has no ordering, and the batched load (@BatchSize) issues ... WHERE table_id IN (...) with no ORDER BY. The stored positions are correct; only the read order is undefined.

This matters for views. The Spark connector pairs a view's columns with its persisted query-output column names (view.query.out.col.N) by index. When the rows come back out of position order, each column gets bound to its neighbour's name and type. Analysis then fails with DATATYPE_MISMATCH.CAST_WITH_FUNC_SUGGESTION (for example cannot cast "DOUBLE" to "DATE"). If all the shifted casts happen to be valid, the view silently returns data under the wrong column names.

We hit this on PostgreSQL with views that are recreated frequently. The view's column rows ended up stored out of position order (the physical order was rotated by two), and loading the view failed intermittently, depending on the query plan PostgreSQL chose.

  • TableInfoDAO.columns is now annotated with @OrderBy("ordinalPosition ASC"), so every column load (getTable, listTables, Delta/Iceberg metadata) returns columns in their declared order.
  • No data migration is needed.

Testing

  • BaseViewCRUDTest.testViewCRUD now creates the view with its columns sent out of position order, and checks that getTable returns them field for field equal to COLUMNS (in position order). The existing listTables assertion then covers the batched load too. It fails without the fix (expected "as_int" but was "as_string").
  • SdkViewCRUDTest, SdkTableCRUDTest, SdkMetricViewCRUDTest pass (31 tests), and server/javafmtCheckAll is clean (Java 17).

🤖 Generated with Claude Code

@yili-db

yili-db commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator

/review

Comment on lines +132 to +159
/**
* Column rows are not guaranteed to be stored (and therefore read back) in ordinal_position
* order. Clients bind view columns by position, so getTable and listTables must return them
* sorted by position regardless of the order they were persisted in.
*/
@Test
public void testViewColumnsAreReturnedInPositionOrder() throws Exception {
createSourceTable();
List<ColumnInfo> reversed = new ArrayList<>(COLUMNS);
Collections.reverse(reversed);

tableOperations.createTable(validViewRequest().columns(reversed));

List<String> expected = COLUMNS.stream().map(ColumnInfo::getName).toList();
assertThat(tableOperations.getTable(VIEW_FULL_NAME).getColumns())
.extracting(ColumnInfo::getName)
.containsExactlyElementsOf(expected);
assertThat(
tableOperations
.listTables(TestUtils.CATALOG_NAME, TestUtils.SCHEMA_NAME, Optional.empty())
.stream()
.filter(t -> VIEW_NAME.equals(t.getName()))
.findFirst()
.orElseThrow()
.getColumns())
.extracting(ColumnInfo::getName)
.containsExactlyElementsOf(expected);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Can this be folded into testViewCRUD instead of a separate test? Create the view there with out-of-order columns, compare everything except columns against the create response, then compare the columns row by row against COLUMNS:

    CreateTable createRequest =
        validViewRequest()
            .comment("A simple SQL view")
            .properties(PROPERTIES)
            // Out of position order: reads must still return columns in position order.
            .columns(List.of(COLUMNS.get(1), COLUMNS.get(0)));

    TableInfo created = tableOperations.createTable(createRequest);
    ...
    TableInfo fetched = tableOperations.getTable(VIEW_FULL_NAME);
    assertThat(fetched)
        .as("getTable should return the same view that createTable returned")
        .usingRecursiveComparison()
        .ignoringFields("columns")
        .isEqualTo(created);
    // The server lowercases typeText on create.
    assertThat(fetched.getColumns())
        .usingRecursiveComparison()
        .withEqualsForFields(String::equalsIgnoreCase, "typeText")
        .isEqualTo(COLUMNS);
  • created echoes the request order, so the existing isEqualTo(created) cannot catch this bug; comparing against COLUMNS checks every field, including position, in order.
  • The existing assertThat(tables).contains(fetched) then also covers the batched listTables load, since TableInfo.equals compares the column lists in order.
  • This drops the separate test and the ArrayList/Collections imports.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 624649b: folded the check into testViewCRUD and dropped the separate test. One small change from the snippet: withEqualsForFields(String::equalsIgnoreCase, "typeText") doesn't compile because the predicate takes Objects, so I used withComparatorForFields(String.CASE_INSENSITIVE_ORDER, "typeText") instead. I also checked that testViewCRUD fails without the @OrderBy.

s-maling-celonis and others added 2 commits October 23, 2026 09:19
The columns relationship on TableInfoDAO has no ordering, so the server
returns uc_columns rows in whatever order the database produces them.
The Spark connector pairs a view's columns with its persisted
query-output names by index, so an out-of-order list binds each column
to its neighbour's name and type and view analysis fails with
DATATYPE_MISMATCH.

Order the relationship by ordinal position.

Signed-off-by: s-maling-celonis <[email protected]>
Create the view with out-of-order columns and compare the fetched
columns against COLUMNS, so getTable and listTables are both checked
for position order without a separate test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: s-maling-celonis <[email protected]>
@yili-db

yili-db commented Oct 25, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db
yili-db merged commit f1eea42 into unitycatalog:main Oct 25, 2026
17 of 18 checks passed
yili-db pushed a commit that referenced this pull request Oct 29, 2026
## 🥞 Stacked PR
Use this
[link](https://github.com/unitycatalog/unitycatalog/pull/2044/files) to
review incremental changes.
-
[stack/uc-one-suite](#2008)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2008/files)]
[MERGED]
-
[stack/uc-one-suite-ci](#2009)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2009/files)]
[MERGED]
-
[**stack/uc-mysql-suite**](#2044)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2044/files)]
← _this PR_
-
[stack/uc-flyway-schema](#2045)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2045/files/5542c615b9b5af8925439fe9021ef7c6b2868238..3efb98336a796a03fa69e1699760e5ef646749f5)]
-
[stack/uc-flyway-merge-checks](#2046)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2046/files/3efb98336a796a03fa69e1699760e5ef646749f5..faabc3d450357bdd37a79fe1409a9dfedc0e4ed2)]

---------
**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**


**Every pull request now also runs the whole test suite on MySQL 8.4,
and the bugs that run found are fixed.**

#2008 and #2009 run every test on PostgreSQL 18. This PR does the same
for MySQL:

- `SupportedDatabase.MYSQL_8`, `build/sbt testMySQL8`, and one blocking
CI row, `All tests (Spark 4.0.0, Delta 4.3.1, MYSQL_8)`.
- PostgreSQL and MySQL test databases now come from one shared harness
(`TemplateDatabases`): the schema is built once per JVM, and each test
gets its own copy.
- `@TempDatabase` injects a per-test database (from the #2008 review).
The 12 classes that created and closed one by hand now declare a field.
- `MySQLDeltaCommitsCRUDTest`, which started its own MySQL container, is
removed. Its lock test moves into `SdkDeltaCommitsCRUDTest`, so it runs
on every database.

Bugs the MySQL run found:

- **Columns came back in the wrong order.** `GET` on a table returned
columns in MySQL's primary-key order (random UUIDs), so Spark could
build the table schema with columns swapped. Function parameters had the
same problem. Both collections are now ordered by position with
`@OrderBy`: the table columns by #2031 on main, the function parameters
here. No schema change.
- **Storage paths were compared case-insensitively.** MySQL's default
collation treats `s3://b/RESERVED` and `s3://b/reserved` as equal,
unlike S3, Linux, PostgreSQL and H2. The deployment docs and the example
compose file now create the database with `utf8mb4_0900_bin`, and the
server logs a warning at startup when the database or its tables compare
text case-insensitively.

### Testing

- `server/test` passes on H2, PostgreSQL 18 and MySQL 8.4.
- The whole MySQL suite (all projects) passes. Before the fixes, 6 Spark
`testTableWithSupportedDataTypes` cases failed on column order and
`ExternalLocationUtilsTest` failed on path case.
- `BaseFunctionCRUDTest` now creates a function with 4 parameters
submitted out of position order and checks they come back in position
order, so a missing `ORDER BY position` fails on every database (the old
test passed on MySQL about 1 time in 24).

<details>
<summary>📐 Design notes & details</summary>

**Why `@OrderBy` and not sorting in Java.** The order is a property of
the data, so the entity's list is ordered for every reader, not only for
callers that remember to sort. For tables, the existing unique key
`(table_id, ordinal_position, name)` lets MySQL read the rows in order.
PostgreSQL and H2 returned insertion order only by luck: a PostgreSQL
`UPDATE` writes a new row version at the end of the table, so the same
unsorted query reorders after one update.

**Why a database collation, not query changes.** A session or connection
collation (for example JDBC `connectionCollation`) doesn't change how a
column compares: the column's own collation wins. A database created
with `COLLATE utf8mb4_0900_bin` gives every table created in it that
collation, so every `=`, `LIKE` and unique key becomes case-sensitive
with no code change. `utf8mb4_0900_bin` is NO PAD, like PostgreSQL and
H2 (`utf8mb4_bin` would treat `'a'` and `'a '` as equal). `ALTER
DATABASE` doesn't convert existing tables, so existing installs keep
working as before and get the warning.

**How MySQL test databases are copied.** MySQL has no `CREATE DATABASE …
TEMPLATE`. The template's `SHOW CREATE TABLE` statements are captured
once and replayed into each new database with foreign key checks off.
The replay keeps primary keys, unique keys, indexes, foreign keys and
check constraints. The template build checks that every mapped table
exists, because MySQL rejects one Hibernate index
(`idx_staging_location`, a 2048-character column is over InnoDB's
3072-byte key limit) and the build must continue past that error.

**Pinned test images.** The PostgreSQL and MySQL test images are pinned
by digest (tag in a comment), like the repo's actions and Dockerfile
base images.

**Test container settings.** Both containers keep their data in memory
and skip disk syncs (PostgreSQL `fsync=off`, MySQL InnoDB flush and
binary log off). Schema setup per test drops from about 1.2 s to 0.5 s
on MySQL.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants