Repository navigation
[Server] Add GEOMETRY and GEOGRAPHY column types - #2369
timothyw553 wants to merge 1 commit into
Conversation
|
|
||
| @Column(name = "data_type") | ||
| private ColumnTypeName dataType; | ||
| private FunctionTypeName dataType; |
There was a problem hiding this comment.
why do we need to change this to FunctionTypeName from ColumnTypeName?
| .updatedAt(updatedAt) | ||
| .updatedBy(updatedBy) | ||
| .dataType(dataType) | ||
| .dataType(dataType == null ? null : dataType.toColumnTypeName()) |
| .updatedAt(functionInfo.getUpdatedAt()) | ||
| .updatedBy(functionInfo.getUpdatedBy()) | ||
| .dataType(functionInfo.getDataType()) | ||
| .dataType(FunctionTypeName.from(functionInfo.getDataType())) |
There was a problem hiding this comment.
Also don't understand this.
There was a problem hiding this comment.
what is this whole thing for??
There was a problem hiding this comment.
like is this a migration from columns to functions? what does that even mean?
2b6fc95 to
8041688
Compare
timothyw553
left a comment
There was a problem hiding this comment.
the java migration approach makes sense overall. i left a few comments on the migration guard, drop-rule validation, and edge cases like duplicate or colliding check constraints.
| return Flyway.configure() | ||
| .dataSource(dataSource) | ||
| .locations(locations) | ||
| .javaMigrations(javaMigrations()) |
There was a problem hiding this comment.
since we're introducing java migrations here, to my understanding dev/check-migration-steps.sh only checks the sql migration and schema-effects directories, so editing or deleting a released java step or changing DropRangeCheckMigration wouldn't get caught. its version-order check also ignores java steps, so e.g. a new java V21 after an existing sql V22 passes. should we extend dev/check-migration-steps.sh to guard the java migration sources and shared helper (maybe checking version order via schema-effects since both formats have them) and add regression cases for that?
| } | ||
| } | ||
| } | ||
| if (names.size() != 1) { |
There was a problem hiding this comment.
if a database happens to have duplicate equivalent check constraints (which h2 allows and SchemaSnapshot deduplicates), wouldn't V17 commit and then V18 blow up here mid-upgrade? should we either detect duplicates before applying pending steps or support dropping all matching checks, and could we add tests for zero matches, multiple matches, and a renamed check?
|
|
||
| private static boolean dropsRedundantRangeCheck( | ||
| DatabaseKind kind, Alter alter, AlterExpression change, SchemaSnapshot before) { | ||
| if (change.getConstraintName() == null) { |
There was a problem hiding this comment.
here change.getConstraintName() is only checked for null and never tied to the dropped range check, and the diff guard above only checks for - check . wouldn't this let a step drop the wider check or an unrelated check as long as two nested range checks exist on the table? should we verify that the actually removed check is covered by a remaining wider check on the same column, and add rejection tests for dropping the wider or an unrelated check?
| @@ -0,0 +1 @@ | |||
| ALTER TABLE uc_functions ADD CONSTRAINT uc_functions_data_type_check_v17 CHECK (data_type BETWEEN 0 AND 23); | |||
There was a problem hiding this comment.
since V17 and V19 add named check constraints on mysql, what happens if another non-uc table in the same database already has a check constraint with that name? SchemaMigrator.refuseTakenNames only checks FOREIGN KEY and VIEW on mysql, so preflight would miss it and V17 would fail. should we include CHECK constraints in refuseTakenNames for mysql and add a collision test?
|
/review |
8041688 to
1e39c98
Compare
|
/review |
1e39c98 to
7ddfaad
Compare
timothyw553
left a comment
There was a problem hiding this comment.
normal upgrade looks good across all three databases. i left a few comments on catching replacement constraint-name collisions in preflight, duplicate-check test coverage (plus a small nit), and adding repair guidance to the refusal messages and docs.
shba24
left a comment
There was a problem hiding this comment.
On lines this pull request does not change
server/src/test/java/io/unitycatalog/server/migrate/MigrationStepRulesTest.java:67
Nit (not a blocker): The migration guide sends contributors to the wrong place for V18 and V20
The test documentation and contributor guides describe every step as a per-database SQL file. The test's failure message also omits adding a wider range and dropping the old one, so its stated rules differ from what it accepts.
For example: V18 and V20 are registered by SchemaMigrator.javaMigrations(). Their effects exist for every database, while their implementations have no per-database SQL files.
Distinguish shared Java migrations from per-database SQL files in AGENTS.md, CODE_REVIEW.md and the test comments. Update the rule diagnostic to include the two range-check operations.
Evidence
The contributor and review guides prescribe SQL-resource directories for each database. The rules test explicitly says every step is a SQL file, and its diagnostic says other changes are unsupported. V18 and V20 are shared classes registered in SchemaMigrator, and the test now accepts adding a wider range and dropping the covered check.
AGENTS.md:151-155
- **Backends:** H2 by default (embedded, file-based). MySQL and PostgreSQL are supported for a persistent deployment, configured in `etc/conf/hibernate.properties` (point at your database and add the JDBC driver); see `docs/server/deployment.md`. Hibernate is configured in `persist/utils/HibernateConfigurator`. Tests run on H2 by default; `build/sbt -J-Xmx6G testPostgres18` or `testMySQL8` (or `UC_TEST_DATABASE=POSTGRES_18` / `MYSQL_8`) runs them on PostgreSQL 18 or MySQL 8.4 in Docker, each test on its own database, and fails rather than skips when Docker is not available. When adding schema, keep any index or column change safe across a server restart on an existing database, and portable across H2, MySQL and PostgreSQL. A schema change:
- is a new Flyway step for each database under `server/src/main/resources/db/migration/{h2,postgresql,mysql}/`, numbered after the last one; never edit a merged step or its effect file;
- is checked for step order against the PR's base by `dev/check-migration-steps.sh`, so two open PRs can each pass with steps out of order: just before a PR that adds a step merges, rebase it or merge main into it so its step is numbered above every merged one (or turn on the branch protection "Require branches to be up to date before merging"); a release branch (`branch-*`) takes no new steps, so add them on main;
- holds one SQL statement per step; `MigrationStepRulesTest` (run with `UC_TEST_MIGRATION_CHECKS=true`) holds the rules for what a step may change (adding a Java enum constant on PostgreSQL replaces the column's CHECK constraint, in one `ALTER TABLE ... DROP CONSTRAINT k, ADD CONSTRAINT k CHECK (c IN (...))` that keeps every value);
- comes with an effect file per database, `server/src/main/resources/schema-effects/{h2,postgresql,mysql}/V<n>.txt`, written by `build/sbt updateSchemaDumps` (PostgreSQL and MySQL need Docker), which only writes them: run the tests with `UC_TEST_MIGRATION_CHECKS=true` afterwards to check them; check it in with the step;
CODE_REVIEW.md:151
- **Persistence schema changes ship as new Flyway steps** for each database under `server/src/main/resources/db/migration/<db>/` (H2, MySQL, PostgreSQL), never as edits of merged steps, and portable across all three; `BaselineMatchesEntitiesTest` (run with `UC_TEST_MIGRATION_CHECKS=true`) and `RealUpgradeTest` (run with `UC_TEST_UPGRADES=true`) check them.
server/src/test/java/io/unitycatalog/server/migrate/MigrationStepRulesTest.java:52-67
* <li>A step is one SQL statement, as Flyway sends it to each database, or none when the step
* changes nothing on that database. The first step, the 0.7.0 baseline, may create any table
* and index.
* <li>The statement is one of the changes {@link #refusal} allows, read with JSqlParser from what
* Flyway sent: create a table, create a plain index (not unique, fulltext or spatial) whose
* PostgreSQL index entry, INCLUDE columns too, fits 2,704 bytes, add a column (NOT NULL only
* with a literal DEFAULT, without a key or CHECK rule), change a column's type (each index on
* the column still fitting an index entry), drop its NOT NULL, or, on PostgreSQL, replace a
* column's CHECK of its values with one that keeps them all, or read an {@code oid} column's
* large objects as text, the one change rows can fail ({@link #readsLargeObjectsAsText}).
* <li>A type change widens the column, keeps its default, collation and enum or set members, and
* no change makes an existing nullable column NOT NULL ({@link #typeChangesWiden}). Adding a
* Java enum constant changes the type on MySQL and H2, where the type holds the members; on
* PostgreSQL it replaces the column's CHECK constraint ({@link #enumCheckRefusal}).
* <li>Each step has an effect file that lists its change ({@link #eachStepHasItsEffectFile}).
* <li>Every step exists for all three databases, as a versioned SQL file.
server/src/test/java/io/unitycatalog/server/migrate/MigrationStepRulesTest.java:225-233
assertThat(problems)
.as(
"Each step after the first holds one statement that creates a table, creates a plain"
+ " index on columns short enough for an index entry, adds a column (NOT NULL only"
+ " with a literal DEFAULT, without a key or CHECK rule), changes a column's type"
+ " (each index on it still short enough), drops its NOT NULL, or replaces a"
+ " PostgreSQL CHECK of a column's values with one that keeps them. Other changes"
+ " are not supported yet; see refusal() in this test")
.isEmpty();
server/src/test/java/io/unitycatalog/server/migrate/MigrationStepRulesTest.java:398-406
/** Every step is a versioned SQL file, and exists for all three databases. */
@Test
void everyStepExistsForEveryDatabase() throws IOException {
Map<String, Set<String>> versions = new TreeMap<>();
List<String> problems = new ArrayList<>();
for (DatabaseKind kind : DatabaseKind.values()) {
try (Stream<Path> files = Files.list(STEPS.resolve(kind.folder()))) {
for (Path file : files.toList()) {
Matcher name = STEP_FILE.matcher(file.getFileName().toString());
How it was checked
Checked by 1 independent check: CONFIRMED
Could the rules describe where the shared steps live and what the range-check validation allows?
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Verdict: comment. One request inline on the V17/V19 name check in refuseTakenNames, and one inline on test coverage.
Docs and description (not anchored in the diff):
- AGENTS.md (line 154) and CODE_REVIEW.md (line 151) still say a schema step is one SQL statement under db/migration. V18 and V20 are Java migrations, so that wording should cover them.
- The PR description does not mention the dev/check-migration-steps.sh changes or CheckMigrationStepsScriptTest.
Could these be updated here or in #2374?
| while (m.find()) { | ||
| constraints.add(m.group(1).toLowerCase(Locale.ROOT)); | ||
| } | ||
| Set<String> checkConstraints = new HashSet<>(); |
There was a problem hiding this comment.
[AI Assisted] The preflight does not check the names V17 and V19 create. refuseTakenNames skips constraints on uc_* tables, so a CHECK renamed by hand to uc_function_params_type_name_range passes preflight. V17 and V18 then commit, and V19 fails on the duplicate name, leaving a half-applied upgrade. Could we include the names V17 and V19 add in this check, and add a refusal test that checkSchema and upgradeSchema both refuse with the version still at 16?
There was a problem hiding this comment.
Fixed in simulate() so preflight refuses occupied constraint names on uc_* tables before V17 runs, with tests verifying both checkSchema and upgradeSchema leave the version at 16.
| List.of( | ||
| new FunctionParameterInfo() | ||
| .name("x") | ||
| .typeText(type.getValue().toLowerCase()) |
There was a problem hiding this comment.
[AI Assisted] Could we also cover a parameterized type_text here, such as geometry(OGC:CRS84) and geography(OGC:CRS84, spherical), and add a list call that checks data_type and the parameter type_name? Right now only the bare names are round-tripped.
There was a problem hiding this comment.
Updated testGeoTypesInFunctions to round-trip geometry(OGC:CRS84) and geography(OGC:CRS84, spherical) and verify them via listFunctions as well.
7ddfaad to
9583cc5
Compare
|
/review |
timothyw553
left a comment
There was a problem hiding this comment.
looks good overall. left one comment on the .formatted() bug in DropRangeCheckMigration's refusal messages.
| List<String> names = findConstraintNames(connection, kind, expectedClause); | ||
| if (names.isEmpty()) { | ||
| throw new IllegalStateException( | ||
| "Expected exactly one CHECK constraint matching %s on %s, found []. Restore the missing" |
There was a problem hiding this comment.
looks like .formatted(...) only binds to the last string literal here, so both refusal messages print literal %s instead of the clause, table, and names (same for the duplicate-match message below). could we wrap both concatenated strings in parentheses and assert the formatted values in SchemaMigratorTest?
- "Expected exactly one CHECK constraint matching %s on %s, found []. Restore the missing"
- + " CHECK constraint or restore the backup, then run --upgrade-schema again."
+ ("Expected exactly one CHECK constraint matching %s on %s, found []. Restore the missing"
+ + " CHECK constraint or restore the backup, then run --upgrade-schema again.")
.formatted(expectedClause, table));There was a problem hiding this comment.
Good catch, wrapped both concatenated strings in parentheses so .formatted(...) binds to the full message, and tightened the unit tests to assert the formatted output.
shba24
left a comment
There was a problem hiding this comment.
On lines this pull request does not change
server/src/test/java/io/unitycatalog/server/migrate/DataSet.java:299
Nit (not a blocker): The upgrade fixture now overstates which column types it contains
DataSet is written through the baseline release's API and explicitly lists the types it can store. Its comments now imply coverage of types absent from the fixture.
For example: everyType() ends at TABLE_TYPE, while ColumnTypeName now also includes GEOMETRY and GEOGRAPHY. The same list feeds the function parameters.
Qualify the every-type comments with the baseline release so they describe the existing fixture accurately.
Evidence
DataSet says everyType supplies one column per ColumnTypeName and reuses that list for function inputs. Its explicit list ends at TABLE_TYPE. The API now declares two more values. The class also says it writes data that the baseline release stores, which explains why narrowing the comment is appropriate.
server/src/test/java/io/unitycatalog/server/migrate/DataSet.java:52-57
/**
* The data an upgrade must keep: a catalog, a schema, a managed and an external table with one
* column of every type, a volume, a function with one parameter of every type and return
* parameters, a user, and a grant to that user on each. {@link #write} creates it through a
* server's API; {@link #assertReadBack} checks it through another's, as whole objects. It writes
* only fields {@link SchemaMigrator#ADOPTED_RELEASE} stores.
server/src/test/java/io/unitycatalog/server/migrate/DataSet.java:298-305
/**
* One column per {@link ColumnTypeName}, in Spark's catalog text and JSON field format, each with
* a comment. The function's parameters have the same types, and the baseline release stores a
* parameter's {@code type_json} in 255 characters, so the nested types stay short.
*/
private static List<ColumnInfo> everyType() {
return List.of(
column(ColumnTypeName.BOOLEAN, "boolean", "\"boolean\""),
server/src/test/java/io/unitycatalog/server/migrate/DataSet.java:351-362
column(ColumnTypeName.NULL, "void", "\"void\""),
// A user-defined type is stored as its SQL type, as Spark writes it: the server does not
// parse Spark's {"type":"udt",...} JSON.
column(
ColumnTypeName.USER_DEFINED_TYPE,
"array<double>",
"{\"type\":\"array\",\"elementType\":\"double\",\"containsNull\":false}"),
column(
ColumnTypeName.TABLE_TYPE,
"table<id:bigint>",
"{\"type\":\"struct\",\"fields\":[" + field("id", "\"long\"") + "]}"));
}
server/src/test/java/io/unitycatalog/server/migrate/DataSet.java:407-416
/** A table function: one input parameter per column type, and two return columns. */
private FunctionInfo function() {
List<FunctionParameterInfo> inputs =
positioned(everyType()).stream()
.map(
column ->
new FunctionParameterInfo()
.name(column.getName())
.typeName(column.getTypeName())
.typeText(column.getTypeText())
api/all.yaml:1776-1779
- USER_DEFINED_TYPE
- TABLE_TYPE
- GEOMETRY
- GEOGRAPHY
How it was checked
Checked by 1 independent check: CONFIRMED
Could the fixture comments say that the list covers the baseline release's types?
| Matcher created = CONSTRAINT.matcher(DROP_CONSTRAINT.matcher(statement).replaceAll("")); | ||
| while (created.find()) { | ||
| available.add(constraintKey(table, created.group(1))); | ||
| String name = created.group(1).toLowerCase(Locale.ROOT); |
There was a problem hiding this comment.
Blocker: A valid quoted constraint name prevents the upgrade
The collision check lowercases both the catalog name and the name in the SQL. With default H2 settings, a quoted lowercase identifier is distinct from the uppercase identifier created by unquoted SQL, so a valid repaired database cannot upgrade. This is one bug class: Preflight folds both catalog names and DDL names to lower case instead of applying each backend's identifier-folding rules. The same issue appears in server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:867 (The DROP-required check lowercases the dropped name and compares it with lowercased catalog keys. On H2 or PostgreSQL, an unquoted DROP of a name whose catalog ); server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:1024 (refuseTakenNames lowercases the catalog holder name and the step's names (:979). On H2 and PostgreSQL, another application's quoted mixed-case or lowercase obje).
For example: Rename the old uc_function_params.type_name check to "uc_function_params_type_name_range" at V16. H2 accepts the exact V19 statement alongside that check, but both migration commands report a collision.
Preserve the spelling returned by the catalog and resolve the unquoted DDL identifier using the database's identifier rules before comparing them.
Evidence
constraintKeys passes the catalog spelling through constraintKey, which lowercases it. The new collision guard lowercases the SQL name too. I checked the existing schema, snapshot and old-clause guards on H2 2.2.224: a quoted lowercase name on the old 0..21 check passes those guards, then checkSchema and upgradeSchema refuse at V16. Executing the exact V19 ADD against that database succeeds.
constraintKeys stores lowercased catalog names. The new refusal compares its lowercased SQL name with that set. On default H2 2.2.224 I created the old check with the quoted lowercase replacement name and ran the unquoted V17 add successfully. The catalog listed both spellings. The new comparison would refuse that valid repair.
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:827-829
private static String constraintKey(String table, String name) {
return table.toLowerCase(Locale.ROOT) + "." + name.toLowerCase(Locale.ROOT);
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:949-954
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql)) {
while (rs.next()) {
keys.add(constraintKey(rs.getString(1), rs.getString(2)));
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:903-918
boolean alterTable = statement.trim().regionMatches(true, 0, "ALTER TABLE", 0, 11);
Matcher created = CONSTRAINT.matcher(DROP_CONSTRAINT.matcher(statement).replaceAll(""));
while (created.find()) {
String name = created.group(1).toLowerCase(Locale.ROOT);
String key = constraintKey(table, name);
if (alterTable && available.contains(key)) {
throw new IllegalStateException(
"Schema step "
+ step
+ " creates the constraint "
+ name
+ " on table "
+ table
+ ", which already has a constraint of that name. Rename the existing"
+ " constraint, or restore the backup, then run the command again.");
}
server/src/main/resources/db/migration/h2/V19__add_function_param_type_name_geo_check.sql:1
ALTER TABLE uc_function_params ADD CONSTRAINT uc_function_params_type_name_range CHECK (type_name BETWEEN 0 AND 23);
docs/server/upgrades.md:241-244
`Schema step <n> creates the constraint <name> on table <table>, which already has a constraint of that name`
: A `uc_*` table already has a constraint with the name that step `<n>` creates (for example, after
a manual repair reused that name). The step did not run. Rename the existing constraint, or
restore the backup, then run the command again.
How it was checked
Reproduced: UC_TEST_MIGRATION_CHECKS=true dev/run-tests.py -p 1 "server/testOnly io.unitycatalog.server.migrate.SchemaMigratorTest -- --include-tags=disprove" (the test carried a temporary @Tag("disprove") for selection, removed before the commit)
head:
1 suites, 1 tests, 1 failed
SchemaMigratorTest#quotedLowerCaseCheckNameDoesNotBlockH2Upgrade(): org.opentest4j.AssertionFailedError: [Database schema version: 16; this release ends at 20. Pending steps: 17 add function data type geo check: runs 18 drop old function data type check: runs 19 add function param type name geo check: runs Schema step 19 creates the constraint uc_function_params_typ... (at SchemaMigratorTest.java:1157) -- checkSchema returned non-zero where 0 was expected
server/src/test/java/io/unitycatalog/server/migrate/SchemaMigratorTest.java:1122-1157
@Test
void quotedLowerCaseCheckNameDoesNotBlockH2Upgrade() throws SQLException {
assumeTrue(db.jdbcUrl().startsWith("jdbc:h2:"), "Quoted names are case sensitive on H2");
UpgradeTestUtils.migrateTo(db, "16");
String old;
try (Connection conn = db.dataSource().getConnection();
Statement st = conn.createStatement();
ResultSet rs =
st.executeQuery(
"SELECT cc.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS cc"
+ " JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc"
+ " ON tc.CONSTRAINT_NAME = cc.CONSTRAINT_NAME"
+ " AND tc.CONSTRAINT_SCHEMA = cc.CONSTRAINT_SCHEMA"
+ " WHERE LOWER(tc.TABLE_NAME) = 'uc_function_params'"
+ " AND LOWER(cc.CHECK_CLAUSE) LIKE '%type_name%'")) {
assertThat(rs.next()).isTrue();
old = rs.getString(1);
}
UpgradeTestUtils.execute(
db,
"ALTER TABLE uc_function_params RENAME CONSTRAINT \""
+ old
+ "\" TO \"uc_function_params_type_name_range\"");
// H2 accepts the unquoted name of step 19 next to the quoted lower-case one.
UpgradeTestUtils.execute(
db,
"ALTER TABLE uc_function_params ADD CONSTRAINT uc_function_params_type_name_range"
+ " CHECK (type_name BETWEEN 0 AND 23)");
UpgradeTestUtils.execute(
db, "ALTER TABLE uc_function_params DROP CONSTRAINT uc_function_params_type_name_range");
SchemaMigrator migrator = new SchemaMigrator(db.dataSource());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int check = migrator.checkSchema(new PrintStream(out, true, StandardCharsets.UTF_8));
assertThat(check).as(out.toString(StandardCharsets.UTF_8)).isZero();
}
Checked by 2 independent checks: CONFIRMED
References:
- https://github.com/h2database/h2database/blob/version-2.2.224/h2/src/main/org/h2/res/help.csv: "Identifiers with lowercase characters can be written only as a quoted name, they aren't accessible with unquoted names."
- https://github.com/h2database/h2database/blob/version-2.2.224/h2/src/main/org/h2/res/help.csv: "With default settings unquoted names are converted to upper case."
- https://github.com/h2database/h2database/blob/version-2.2.224/h2/src/main/org/h2/res/help.csv: "Case of characters in quoted names is preserved as is."
Could the collision check preserve the distinction H2 makes between those two names?
There was a problem hiding this comment.
SchemaMigrator intentionally compares constraint names case-insensitively across dialects, and refusing a case-colliding constraint name in preflight is safer than letting both coexist.
There was a problem hiding this comment.
Thanks for explaining the case-folding choice, and for the clear intent behind it. I reproduced the quoted lower-case name on a non-UC table in H2 and the refusal is real. It fails closed with a message naming the table and constraint, so I'm happy to keep the case-insensitive comparison as is. I'd lean towards an optional line in docs/server/upgrades.md noting this refusal and its repair (rename the other application's constraint), but that's not needed here.
Settled from our side, thanks. Please resolve this thread when you're ready.
| - 'NULL' | ||
| - USER_DEFINED_TYPE | ||
| - TABLE_TYPE | ||
| - GEOMETRY |
There was a problem hiding this comment.
Blocker: One geo function prevents Python clients from listing existing functions
AI core pins unitycatalog-client to 0.4.0 in its lockfile. That client decodes every function's data_type against a closed enum, so one geo return type makes the entire page unreadable. This is one bug class: Adding a value to a spec enum breaks strict generated clients already released, because the Python generator has no unknown-enum fallback. The same issue appears in api/all.yaml:1793 (ColumnInfo.type_name is the same enum on tables. The native createTable now accepts type_name GEOMETRY, and older Python clients' get_table and list_tables fail); build.sbt:322 (The Python generator config lacks the enumUnknownDefaultCase setting that the Java config has. The regenerated Python client is still strict, so the next enum v).
For example: A Python caller lists a schema containing an INT function successfully. Once the same page includes a GEOMETRY function, the HTTP response is still 200, but list_functions raises ValidationError and returns neither function.
State in the PR description, and in the release notes, that strict generated clients (Python unitycatalog-client <= 0.4.x, which AI core pins) cannot decode a list page that contains a geo-typed function. Release a regenerated Python client and widen ai/core's pin in a follow-up, or in the stacked layer that carries the client changes, before these values reach users.
Evidence
The new enum values appear in an authorized list response, as the head's SDK test asserts. AI core locks unitycatalog-client 0.4.0 and calls its typed list method before returning any functions. I inspected that release's model and called FunctionsApi.list_functions against a local HTTP 200 endpoint. An INT-only page decoded. Adding GEOMETRY caused ValidationError before the existing row could be returned. I also verified GEOGRAPHY fails in the same decoder.
api/all.yaml:1775-1779
- 'NULL'
- USER_DEFINED_TYPE
- TABLE_TYPE
- GEOMETRY
- GEOGRAPHY
server/src/main/java/io/unitycatalog/server/service/FunctionService.java:90-96
ListFunctionsResponse listFunctionsResponse =
functionRepository.listFunctions(catalogName, schemaName, maxResults, pageToken);
applyResponseFilter(
SecurableType.FUNCTION,
listFunctionsResponse.getFunctions(),
BrowseOnlyConverter::toBrowseOnly);
return HttpResponse.ofJson(listFunctionsResponse);
server/src/test/java/io/unitycatalog/server/sdk/function/SdkFunctionCRUDTest.java:282-302
List<FunctionInfo> listed =
functionOperations.listFunctions(CATALOG_NAME, SCHEMA_NAME, Optional.empty());
for (Map.Entry<ColumnTypeName, String> entry : geoTypeTexts.entrySet()) {
ColumnTypeName type = entry.getKey();
String typeText = entry.getValue();
String name = "fn_" + type.getValue().toLowerCase();
assertThat(listed)
.filteredOn(f -> name.equals(f.getName()))
.singleElement()
.satisfies(
f -> {
assertThat(f.getDataType()).isEqualTo(type);
assertThat(f.getFullDataType()).isEqualTo(typeText);
assertThat(f.getInputParams().getParameters())
.singleElement()
.satisfies(
param -> {
assertThat(param.getTypeName()).isEqualTo(type);
assertThat(param.getTypeText()).isEqualTo(typeText);
});
});
ai/core/uv.lock:2372-2375
[[package]]
name = "unitycatalog-client"
version = "0.4.0"
source = { registry = "https://pypi.org/simple" }
ai/core/src/unitycatalog/ai/core/client.py:1027-1035
resp = await self.uc.functions_client.list_functions(
catalog_name=catalog,
schema_name=schema,
max_results=max_results,
page_token=page_token,
_request_timeout=timeout,
)
return PagedList(resp.functions, resp.next_page_token)
How it was checked
Checked by 2 independent checks, which split: CONFIRMED, CONTESTED
References:
- https://files.pythonhosted.org/packages/66/8d/6f9117d777fd48c10abab0137e791b6776b83376d3bbe8e680d94949b52b/unitycatalog_client-0.4.0-py3-none-any.whl: "data_type: Optional[ColumnTypeName] = None"
- https://files.pythonhosted.org/packages/66/8d/6f9117d777fd48c10abab0137e791b6776b83376d3bbe8e680d94949b52b/unitycatalog_client-0.4.0-py3-none-any.whl: ""functions": [FunctionInfo.from_dict(_item) for _item in obj["functions"]] if obj.get("functions") is not None else None,"
Could we release and select a compatible Python reader before these values appear in shared schemas?
There was a problem hiding this comment.
This is inherent to adding any new ColumnTypeName enum value in api/all.yaml; callers using the new types need a regenerated client, and existing databases without geo functions are unaffected.
There was a problem hiding this comment.
Thanks for spelling out that any new ColumnTypeName value affects strict clients and that databases with no geo values are unaffected, which matches what I saw when decoding with the released 0.4.0 client. I'll go with that as it stands.
Settled from our side, thanks. Please resolve this thread when you're ready.
| # Highest step version on <base-ref> across SQL steps, Java steps, and schema-effects. | ||
| highest_on_base() { | ||
| { | ||
| git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_step_glob" \ |
There was a problem hiding this comment.
Nit (not a blocker): The version-order guard overlooks Java source filenames
git ls-tree receives the literal path ending in V*.java and returns no Java files. The companion effect file supplies the Java version in the current repository and in the regression fixture.
For example: With SQL V17 and Java V21 on the base, omitting V21.txt lets a new SQL V19 pass. Checked-in effect files cover the current migrations.
| git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_step_glob" \ | |
| git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_steps_dir/" \ |
Evidence
The quoted V*.java argument lists zero paths under git ls-tree at this head, while listing its directory returns both Java steps. highest_on_base separately reads effect files, and its regression fixture writes V21.txt alongside the Java source. In an isolated base containing SQL V17 and Java V21 without V21.txt, the script accepted SQL V19.
dev/check-migration-steps.sh:27-31
steps_dir=server/src/main/resources/db/migration
effects_dir=server/src/main/resources/schema-effects
java_steps_dir=server/src/main/java/io/unitycatalog/server/migrate
java_step_glob="$java_steps_dir/V*.java"
java_helper="$java_steps_dir/DropRangeCheckMigration.java"
dev/check-migration-steps.sh:62-72
# Highest step version on <base-ref> across SQL steps, Java steps, and schema-effects.
highest_on_base() {
{
git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_step_glob" \
| while read -r f; do version_of_step "$f"; done
git ls-tree -r --name-only "$1" -- "$effects_dir/" \
| while read -r f; do version_of_effect "$f"; done
} | awk '/^[0-9]+$/ { print $1 + 0 }' | sort -n | tail -n 1
}
highest=$(highest_on_base "$1")
server/src/test/java/io/unitycatalog/server/migrate/CheckMigrationStepsScriptTest.java:121-126
private void initBaseRepoWithJavaHighest() throws Exception {
initBaseRepo();
write(JAVA_DIR + "V21__top_java.java", "class V21__top_java {}\n");
write(EFFECTS + "V21.txt", "- check uc_functions b\n");
commit("bump base with V21 java");
git("branch", "-f", "base");
How it was checked
Reproduced: dev/run-tests.py "server/testOnly io.unitycatalog.server.migrate.CheckMigrationStepsScriptTest"
head:
[error] Test io.unitycatalog.server.migrate.CheckMigrationStepsScriptTest.refusesSqlStepBelowJavaStepThatHasNoEffectFile failed: org.opentest4j.AssertionFailedError: expected: 1 but was: 0 (CheckMigrationStepsScriptTest.java:116); Failed: Total 8, Failed 1, Errors 0, Passed 7
with the fix:
With git ls-tree given "$java_steps_dir/" instead of the V*.java glob: [success] 1 suites, 8 tests, 0 failed
Base has V17 sql, V18 java, V20 sql, plus a V22 Java step with no effect file. A new SQL step V21 is added above the old highest (20) but below V22. Unmodified script exits 0, so it accepts an out-of-order step: git ls-tree does not expand the V*.java pathspec, and the version ceiling came only from effect files. Fix (list the Java directory, keep the version_of_step filter) turns it green, and the other 7 tests still pass. The script is identical at base and PR head (no diff to dev/check-migration-steps.sh), so the code predates this PR and a base run was not needed. Test is committed as ecdc2cd without the fix; the fix was reverted. Only H2/no database involved. Reach is limited: the repo requires an effect file per step, so only a Java step lacking one triggers it. Nit severity stands.
server/src/test/java/io/unitycatalog/server/migrate/CheckMigrationStepsScriptTest.java:105-118
@Test
void refusesSqlStepBelowJavaStepThatHasNoEffectFile() throws Exception {
initBaseRepo();
write(JAVA_DIR + "V22__top_java.java", "class V22__top_java {}\n");
commit("bump base with V22 java, no effect file");
git("branch", "-f", "base");
write(SQL_STEP + "V21__out_of_order.sql", "SELECT 1;\n");
write(EFFECTS + "V21.txt", "+ check uc_functions y\n");
commit("add sql step below V22 Java");
Result r = runScript("base", "main");
assertThat(r.exitCode()).isEqualTo(1);
assertThat(r.output()).contains("not above step 22");
}
Checked by 1 independent check: CONFIRMED
References:
- https://github.com/git/git/blob/v2.54.0/builtin/ls-tree.c: "options.pathspec.has_wildcard = 0;"
Could we list the migration directory and let version_of_step select the versioned files?
There was a problem hiding this comment.
Good catch on git ls-tree not expanding V*.java; effect files already cover the version check for merged Java steps, and we can clean that up in a follow-up or next touch.
There was a problem hiding this comment.
Thanks for explaining why the effect files cover this. I checked it at the head: the glob does miss the Java steps, but a merged Java step always has an effect file, so the version check gives the right result in practice. Cleaning it up in a follow-up or the next time the script is touched is fine with me.
Settled from our side, thanks. Please resolve this thread when you're ready.
| effects_dir=server/src/main/resources/schema-effects | ||
| java_steps_dir=server/src/main/java/io/unitycatalog/server/migrate | ||
| java_step_glob="$java_steps_dir/V*.java" | ||
| java_helper="$java_steps_dir/DropRangeCheckMigration.java" |
There was a problem hiding this comment.
Nit (not a blocker): Adding a database backend or fixing the range-check lookup will need an edit the migration-steps check refuses
check-migration-steps.sh now fails on any change to DropRangeCheckMigration.java. The helper has three exhaustive switch (kind) blocks over SchemaMigrator.DatabaseKind and calls DatabaseKind.of(Connection), and those are not frozen.
The stored part of a Java step is its checksum, Objects.hash(table, column, min, max), which Flyway keeps in uc_schema_history. That pins the constructor arguments of V18/V20, not the dialect SQL.
Cost of keeping it: If this merges as is, adding a fourth DatabaseKind, or fixing the lookup's MySQL ENFORCED handling, means touching a file the script blocks.
The helper is also the obvious tool for the 8 other unnamed ordinal CHECKs in the baseline (routine_body, sql_data_access, parameter_type, ...), so the frozen copy picks up more dependents over time.
Freeze only the V*.java steps, whose constructor arguments are the stored checksum. Pin the helper's behavior with the per-database upgrade tests and the schema-effects files instead of freezing the file. Alternatively, keep the checksum in the helper and move the per-dialect lookup and drop SQL somewhere unfrozen.
Evidence
The script adds the helper to the frozen M/D/R/T list. The helper imports the unfrozen SchemaMigrator.DatabaseKind, switches on it exhaustively in three places, and derives its stored checksum only from the four constructor fields. The baseline has 8 more unnamed ordinal range CHECKs that the helper's design invites reuse for.
dev/check-migration-steps.sh:29-39
java_steps_dir=server/src/main/java/io/unitycatalog/server/migrate
java_step_glob="$java_steps_dir/V*.java"
java_helper="$java_steps_dir/DropRangeCheckMigration.java"
if ! merge_base=$(git merge-base "$1" HEAD); then
echo "No merge base between $1 and HEAD; fetch more history." >&2
exit 2
fi
changed=$(git diff --diff-filter=MDRT --name-status "$merge_base" HEAD -- \
"$steps_dir" "$effects_dir" "$java_step_glob" "$java_helper")
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:3
import io.unitycatalog.server.migrate.SchemaMigrator.DatabaseKind;
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:70-73
@Override
public Integer getChecksum() {
return Objects.hash(table, column, min, max);
}
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:120-155
private String expectedClause(DatabaseKind kind) {
return switch (kind) {
case H2 -> "\"%s\" BETWEEN %d AND %d".formatted(column.toUpperCase(Locale.ROOT), min, max);
case MYSQL -> "(`%s` between %d and %d)".formatted(column, min, max);
case POSTGRESQL -> "CHECK (((%1$s >= %2$d) AND (%1$s <= %3$d)))".formatted(column, min, max);
};
}
private List<String> findConstraintNames(
Connection connection, DatabaseKind kind, String expectedClause) throws SQLException {
String lookupSql =
switch (kind) {
case H2 -> STANDARD_LOOKUP.formatted("CURRENT_SCHEMA");
case MYSQL -> STANDARD_LOOKUP.formatted("DATABASE()");
case POSTGRESQL -> POSTGRES_LOOKUP;
};
List<String> names = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(lookupSql)) {
ps.setString(1, table);
ps.setString(2, expectedClause);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString(1));
}
}
}
return names;
}
private String dropStatement(DatabaseKind kind, String name) {
return switch (kind) {
case H2, POSTGRESQL ->
"ALTER TABLE %s DROP CONSTRAINT \"%s\"".formatted(table, name.replace("\"", "\"\""));
case MYSQL -> "ALTER TABLE %s DROP CHECK `%s`".formatted(table, name.replace("`", "``"));
};
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:99-104
static DatabaseKind of(Connection connection) throws SQLException {
String product = connection.getMetaData().getDatabaseProductName();
return switch (product) {
case "H2" -> H2;
case "PostgreSQL" -> POSTGRESQL;
case "MySQL" -> MYSQL;
How it was checked
Checked by 1 independent check: NITPICK
References:
- https://github.com/flyway/flywaydb.org/blob/gh-pages/documentation/concepts/migrations.md: "By default Flyway does not assign a checksum to Java-based migrations. If you want them validated like SQL migrations you must supply one by implementing JavaMigration.getChecksum()"
Would freezing only the V*.java steps keep the guarantee you wanted, while leaving the dialect code free to change?
There was a problem hiding this comment.
Freezing DropRangeCheckMigration.java is intentional so merged Java migration behavior cannot silently drift; a future backend addition can explicitly update the guard if needed.
There was a problem hiding this comment.
Thanks for explaining the intent: with the helper frozen on purpose, a future backend addition has to edit the guard explicitly, and I'm fine with that. I checked the head: dev/check-migration-steps.sh names DropRangeCheckMigration.java and refuses changes to it, and refusesEditingSharedJavaHelper covers that. I'm happy to leave it as is.
Settled from our side, thanks. Please resolve this thread when you're ready.
| return names.get(0); | ||
| } | ||
|
|
||
| private String expectedClause(DatabaseKind kind) { |
There was a problem hiding this comment.
Nit (not a blocker): The old-check lookup and the schema snapshot can disagree about which constraint is the 0..21 check
SchemaSnapshot.checks normalizes catalog text: it collapses whitespace, strips CHECK and marks MySQL not enforced. DropRangeCheckMigration re-queries the same catalogs and compares raw text to a hand-built literal in expectedClause.
The effect file V18.txt already holds the exact snapshot entry the step removes.
Cost of keeping it: If this merges as is, each future range-check drop, and each change to the snapshot's normalization, has to be copied into expectedClause by hand.
On MySQL the two already differ: a NOT ENFORCED 0..21 check is a different entry in the snapshot, but the lookup still counts it as a match.
Have SchemaSnapshot also return constraint names keyed by its entry string. Then have the step drop the names under the entry its effect file removes, instead of keeping its own per-dialect queries and clause literals.
Evidence
SchemaSnapshot.checks lists CHECKs and normalizes the clause (whitespace collapse, CHECK prefix strip, MySQL not enforced). DropRangeCheckMigration re-queries the same catalogs with exact check_clause = ? / pg_get_constraintdef(con.oid) = ? against literals built in expectedClause, and ignores ENFORCED. It is the same fact with two spellings and nothing to keep them equal.
server/src/main/java/io/unitycatalog/server/migrate/SchemaSnapshot.java:173-196
private static List<String> checks(Connection connection, DatabaseKind kind) throws SQLException {
String query =
switch (kind) {
case H2 -> STANDARD_CHECKS.formatted("current_schema");
case MYSQL -> MYSQL_CHECKS;
case POSTGRESQL -> POSTGRES_CHECKS;
};
List<String> checks = new ArrayList<>();
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query)) {
while (rs.next()) {
String table = lower(rs.getString(1));
if (isSchemaTable(table)) {
// PostgreSQL's definition starts with "CHECK"; the others give the bare clause.
String clause = rs.getString(2).replaceAll("\\s+", " ").trim();
String enforced =
kind == DatabaseKind.MYSQL && "NO".equalsIgnoreCase(rs.getString(3))
? " not enforced"
: "";
checks.add(
"check %s %s%s".formatted(table, clause.replaceFirst("^(?i)check ", ""), enforced));
}
}
}
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:29-52
private static final String STANDARD_LOOKUP =
"""
SELECT tc.constraint_name
FROM information_schema.table_constraints tc
JOIN information_schema.check_constraints cc
ON cc.constraint_schema = tc.constraint_schema
AND cc.constraint_name = tc.constraint_name
WHERE tc.constraint_type = 'CHECK'
AND tc.table_schema = %s
AND LOWER(tc.table_name) = ?
AND cc.check_clause = ?
""";
private static final String POSTGRES_LOOKUP =
"""
SELECT con.conname
FROM pg_constraint con
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE con.contype = 'c'
AND n.nspname = current_schema()
AND c.relname = ?
AND pg_get_constraintdef(con.oid) = ?
""";
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:120-126
private String expectedClause(DatabaseKind kind) {
return switch (kind) {
case H2 -> "\"%s\" BETWEEN %d AND %d".formatted(column.toUpperCase(Locale.ROOT), min, max);
case MYSQL -> "(`%s` between %d and %d)".formatted(column, min, max);
case POSTGRESQL -> "CHECK (((%1$s >= %2$d) AND (%1$s <= %3$d)))".formatted(column, min, max);
};
}
server/src/main/resources/schema-effects/h2/V18.txt:1
- check uc_functions "DATA_TYPE" BETWEEN 0 AND 21
How it was checked
Checked by 1 independent check: NITPICK
Could the step look up names by the snapshot entry instead, so there is one definition of a check's spelling per dialect?
There was a problem hiding this comment.
Leaving DropRangeCheckMigration self-contained keeps the drop lookup simple and explicit; on MySQL a disabled check is already caught by SchemaSnapshot's post-upgrade check.
There was a problem hiding this comment.
Thanks for pointing to the MySQL snapshot check: I confirmed on MySQL 8 that with the old 0..21 check set to NOT ENFORCED at V16, the upgrade is refused and the schema version stays at 16, so a self-contained lookup is fine and I'm happy to leave it as is. One small wording note: the refusal comes from the pre-upgrade schema comparison, not a post-upgrade one. refusesMySqlWhoseOldDataTypeCheckIsNotEnforced in SchemaMigratorTest is what pins that case.
Settled from our side, thanks. Please resolve this thread when you're ready.
| continue; // its change is already in the database, and so are its names | ||
| } | ||
| for (JavaMigration migration : javaMigrations()) { | ||
| if (migration instanceof DropRangeCheckMigration drop |
There was a problem hiding this comment.
Nit (not a blocker): A new kind of Java step would run with no upgrade preflight and nothing would flag it
stepScript returns "" for Java steps, so the name-based preflight sees no statements for them.
The only Java preflight is the instanceof DropRangeCheckMigration loop over javaMigrations(), which is typed as any JavaMigration.
Cost of keeping it: If this merges as is, the next Java step that is not a range-check drop registers and runs with no preflight at all. Nothing in the types or tests points that out.
static DropRangeCheckMigration[] javaMigrations() {
return new DropRangeCheckMigration[] {
new V18__drop_old_function_data_type_check(),
new V20__drop_old_function_param_type_name_check()
};
}
Evidence
stepScript returns an empty script for Java steps, so the SQL-text preflight sees nothing. The only Java preflight is the downcast loop over the JavaMigration[] registry, which is public and typed wider than what it holds. I looked in simulate, refuseTakenNames and stepScript for any other Java-step handling and found none.
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:481-487
/** Java migration steps that need runtime catalog lookups (e.g. dropping unnamed CHECKs). */
public static JavaMigration[] javaMigrations() {
return new JavaMigration[] {
new V18__drop_old_function_data_type_check(),
new V20__drop_old_function_param_type_name_check()
};
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:788-797
private String stepScript(String step) {
String script =
resolvedSteps(flyway().load().info()).stream()
.filter(m -> m.getVersion().getVersion().equals(step))
.map(MigrationInfo::getScript)
.findFirst()
.orElseThrow();
if (!script.endsWith(".sql")) {
return "";
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:852-858
for (JavaMigration migration : javaMigrations()) {
if (migration instanceof DropRangeCheckMigration drop
&& step.equals(migration.getVersion().getVersion())
&& existingTables.contains(drop.table())) {
drop.verifySingleMatch(dataSource, kind);
}
}
How it was checked
Checked by 1 independent check: NITPICK
How about narrowing the registry type, so a new kind of Java step has to come with its own preflight?
There was a problem hiding this comment.
That is out of scope here since DropRangeCheckMigration is the only Java migration type; any future Java migration type can add its own preflight when introduced.
There was a problem hiding this comment.
Thanks for checking the migrate package: V18 and V20 are the only Java steps and both extend DropRangeCheckMigration, so the downcast covers every Java step today. Leaving the registry type as is and adding a preflight when a new kind of Java step arrives works for me.
Settled from our side, thanks. Please resolve this thread when you're ready.
| # Highest step version on <base-ref> across SQL steps, Java steps, and schema-effects. | ||
| highest_on_base() { | ||
| { | ||
| git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_step_glob" \ |
There was a problem hiding this comment.
Nit (not a blocker): The migration order check can miss the highest Java step
git ls-tree returns no entries for the quoted V*.java path. The guard relies on an effect file to discover an existing Java version, despite documenting the Java source as an independent input.
For example: With SQL V17, Java V21, and no V21.txt on the base, adding SQL V19 exits successfully. The existing fixture writes V21.txt, so it obtains the expected maximum from that file.
In dev/check-migration-steps.sh, replace the quoted "$java_step_glob" pathspec in both highest_on_base and the git diff --diff-filter=A call with the Java steps directory, and let version_of_step filter the file names. Add the repro's base-without-effect-file case to CheckMigrationStepsScriptTest as a regression row.
Evidence
The script claims to read the highest version across Java sources, SQL, and effects. Its quoted V*.java path produces no Java paths from git ls-tree. The regression fixture adds a same-version effect, so it exercises the fallback. In a temporary repository with SQL V17 and Java V21 without its effect, the actual script accepted new SQL V19.
highest_on_base passes the glob $java_step_glob to git ls-tree. Locally, git ls-tree -r --name-only HEAD -- '.../migrate/V*.java' printed nothing, while git ls-tree on the directory and git diff with the glob both listed V18 and V20. Java versions therefore come only from the effect files, which contradicts the comment.
dev/check-migration-steps.sh:7-10
# Fails when a new step's version (SQL or Java) is not above every step on <base-ref>:
# databases already past it would never run it (Flyway refuses such a step).
# Also fails on any new step when <base-branch> is a release branch (branch-*): the step's number
# could clash with a different step on main, and the next upgrade would break.
dev/check-migration-steps.sh:27-31
steps_dir=server/src/main/resources/db/migration
effects_dir=server/src/main/resources/schema-effects
java_steps_dir=server/src/main/java/io/unitycatalog/server/migrate
java_step_glob="$java_steps_dir/V*.java"
java_helper="$java_steps_dir/DropRangeCheckMigration.java"
dev/check-migration-steps.sh:62-72
# Highest step version on <base-ref> across SQL steps, Java steps, and schema-effects.
highest_on_base() {
{
git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_step_glob" \
| while read -r f; do version_of_step "$f"; done
git ls-tree -r --name-only "$1" -- "$effects_dir/" \
| while read -r f; do version_of_effect "$f"; done
} | awk '/^[0-9]+$/ { print $1 + 0 }' | sort -n | tail -n 1
}
highest=$(highest_on_base "$1")
dev/check-migration-steps.sh:83-89
# 10# keeps bash from reading a leading zero (V08) as octal.
version=$((10#$version))
if [[ -n "$highest" && "$version" -le "$highest" ]]; then
echo "The new step $step is not above step $highest, the highest on $1." >&2
echo "Renumber it above every merged step." >&2
exit 1
fi
server/src/test/java/io/unitycatalog/server/migrate/CheckMigrationStepsScriptTest.java:117-122
commit("base");
git("branch", "base");
}
private void initBaseRepoWithJavaHighest() throws Exception {
initBaseRepo();
How it was checked
Reproduced: dev/run-tests.py -p 1 "server/testOnly io.unitycatalog.server.migrate.CheckMigrationStepsScriptTest"
head:
CheckMigrationStepsScriptTest#refusesSqlStepBelowJavaStepWithoutEffectFile(): org.opentest4j.AssertionFailedError: expected: 1 but was: 0 (CheckMigrationStepsScriptTest.java:93) [Failed: Total 8, Failed 1, Passed 7]
with the fix:
With git ls-tree listing "$java_steps_dir/" instead of the quoted V*.java glob: 1 suites, 8 tests, 0 failed
Base has SQL V17/V20-free Java V21 without a V21 effect file; the new SQL V21 step is accepted on head (script exit 0, should be 1) because the quoted glob passed to git ls-tree matches nothing, so the highest on base falls back to 20. The fix (list the Java directory, filter with version_of_step) turns it green and the other 7 tests still pass. The script already existed at base 3317ea3 and was changed in this PR, so I did not run a base comparison. Reachability: a merged Java step always has an effect file (SchemaMigrator.expected throws 'no effect file' for a step without one; MigrationStepRulesTest checks it), so the effect-file scan already supplies the Java version. With a realistic base the existing test refusesSqlStepNumberedBelowExistingJavaStep passes. The bug is real but masked in practice. Test is H2-independent (shell script and git only), so no database matrix applies.
server/src/test/java/io/unitycatalog/server/migrate/CheckMigrationStepsScriptTest.java:80-95
}
@Test
void refusesSqlStepBelowJavaStepWithoutEffectFile() throws Exception {
initBaseRepo();
write(JAVA_DIR + "V21__top_java.java", "class V21__top_java {}\n");
commit("bump base with V21 java and no effect file");
git("branch", "-f", "base");
write(SQL_STEP + "V21__same_as_java.sql", "SELECT 1;\n");
write(EFFECTS + "V21.txt", "+ check uc_functions y\n");
commit("add out-of-order sql step at V21 Java");
Result r = runScript("base", "main");
assertThat(r.exitCode()).isEqualTo(1);
assertThat(r.output()).contains("not above step 21");
}
Checked by 2 independent checks, which split: CONFIRMED, DISPROVED
References:
- https://github.com/git/git/blob/v2.54.0/builtin/ls-tree.c#L417-L423: "options.pathspec.has_wildcard = 0;"
- https://git-scm.com/docs/git-ls-tree: "When paths are given, show them (note that this isn't really raw pathnames, but rather a list of patterns to match)."
Could the script list the Java directory and let version_of_step select the versioned files?
There was a problem hiding this comment.
Duplicate of discussion_r4744726774 — see reply there.
There was a problem hiding this comment.
Thanks for pointing to the earlier thread on the same line. I re-checked at this head. git ls-tree with the quoted V*.java pathspec lists 0 files, while the migrate directory holds 2 (V18 and V20). So the Java steps reach highest_on_base only through their effect files. Every step ships with an effect file, so the highest version is still found in practice. The miss would only show up for a Java step merged without one. I'd lean towards listing the directory and filtering by name in a later cleanup, as you suggested there, and I'll follow that thread.
| - 'NULL' | ||
| - USER_DEFINED_TYPE | ||
| - TABLE_TYPE | ||
| - GEOMETRY |
There was a problem hiding this comment.
Nit (not a blocker): The generated UI client cannot name either new column type
ui/package.json generates catalog.gen.ts from api/all.yaml. Its checked-in ColumnTypeName still ends at TABLE_TYPE, so the typed client cannot represent the new enum members.
For example: A caller reading a column with type_name set to GEOMETRY cannot refer to ColumnTypeName.GEOMETRY in ui. The separate ui-new mapping does not generate this file.
Leave ui/src/types/api/catalog.gen.ts alone in this server PR. Regenerate it with the UI package's existing catalog generator in the stacked UI PR or in a standalone sync PR, and review the unrelated drift there.
Evidence
The OpenAPI enum gains two members. The checked-in enum generated from that exact file ends at TABLE_TYPE, and the UI types a column's type_name using it. I checked the generator command, its output, the generated Markdown model, and the upper UI layer, which changes ui-new rather than this generated file.
api/all.yaml:1774-1779
- CHAR
- 'NULL'
- USER_DEFINED_TYPE
- TABLE_TYPE
- GEOMETRY
- GEOGRAPHY
ui/package.json:32-35
"generate": "bun run generate:catalog && bun run generate:control",
"clean-bun-lock": "bun run scripts/clean-bun-lock.ts",
"generate:catalog": "bunx openapi-typescript --enum ../api/all.yaml -o src/types/api/catalog.gen.ts",
"generate:control": "bunx openapi-typescript --enum ../api/control.yaml -o src/types/api/control.gen.ts"
ui/src/types/api/catalog.gen.ts:3475-3498
export enum ColumnTypeName {
BOOLEAN = 'BOOLEAN',
BYTE = 'BYTE',
SHORT = 'SHORT',
INT = 'INT',
LONG = 'LONG',
FLOAT = 'FLOAT',
DOUBLE = 'DOUBLE',
DATE = 'DATE',
TIMESTAMP = 'TIMESTAMP',
TIMESTAMP_NTZ = 'TIMESTAMP_NTZ',
STRING = 'STRING',
BINARY = 'BINARY',
DECIMAL = 'DECIMAL',
INTERVAL = 'INTERVAL',
ARRAY = 'ARRAY',
STRUCT = 'STRUCT',
MAP = 'MAP',
VARIANT = 'VARIANT',
CHAR = 'CHAR',
NULL = 'NULL',
USER_DEFINED_TYPE = 'USER_DEFINED_TYPE',
TABLE_TYPE = 'TABLE_TYPE',
}
ui/src/types/api/catalog.gen.ts:889-894
/** @description Full data type specification as SQL/catalogString text. */
type_text?: string;
/** @description Full data type specification, JSON-serialized. */
type_json?: string;
type_name?: components['schemas']['ColumnTypeName'];
/**
How it was checked
Reproduced: cd ui && bun /tmp/geo_probe.ts (probe imports ColumnTypeName from ui/src/types/api/catalog.gen.ts and asserts GEOMETRY and GEOGRAPHY are members; probe deleted afterwards, not committed)
head:
members: 22 last: TABLE_TYPE
FAIL expected ColumnTypeName to contain GEOMETRY actual ["BOOLEAN",...,"USER_DEFINED_TYPE","TABLE_TYPE"]
FAIL expected ColumnTypeName to contain GEOGRAPHY actual ["BOOLEAN",...,"USER_DEFINED_TYPE","TABLE_TYPE"]
exit=1
Checked by 2 independent checks, which split: CONFIRMED, NITPICK
Could the catalog types be regenerated alongside the spec change?
There was a problem hiding this comment.
Agreed — leaving UI client regeneration out of this server PR; UI updates live in #2373.
There was a problem hiding this comment.
Thanks for pointing to #2373 for the UI client regeneration; that works for me, so I'm happy to leave the generated UI client out of this server PR.
Settled from our side, thanks. Please resolve this thread when you're ready.
| public void migrate(Context context) throws SQLException { | ||
| Connection connection = context.getConnection(); | ||
| DatabaseKind kind = DatabaseKind.of(connection); | ||
| String name = requireSingleConstraintName(connection, kind); |
There was a problem hiding this comment.
Nit (not a blocker): The Java steps execute a lookup as well as the schema change
The description counts one statement per step. Each Java step executes two SQL operations, while only the ALTER TABLE changes the schema.
For example: V18 and V20 call executeQuery() to find a name before execute(dropSql). The migration-rule recorder excludes the prepared lookup.
| String name = requireSingleConstraintName(connection, kind); | |
| The widening uses four steps, each with one schema-changing statement. V18 and V20 query the catalog before issuing their ALTER TABLE. |
Evidence
The description counts each Java step as a single SQL statement. Each first executes a prepared lookup and then executes the ALTER. The statement recorder excludes prepared statements, which explains how the one-statement assertion and this implementation coexist.
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:89-97
@Override
public void migrate(Context context) throws SQLException {
Connection connection = context.getConnection();
DatabaseKind kind = DatabaseKind.of(connection);
String name = requireSingleConstraintName(connection, kind);
String dropSql = dropStatement(kind, name);
try (Statement statement = connection.createStatement()) {
statement.execute(dropSql);
}
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:101-105
private String requireSingleConstraintName(Connection connection, DatabaseKind kind)
throws SQLException {
String expectedClause = expectedClause(kind);
List<String> names = findConstraintNames(connection, kind, expectedClause);
if (names.isEmpty()) {
server/src/main/java/io/unitycatalog/server/migrate/DropRangeCheckMigration.java:136-146
List<String> names = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(lookupSql)) {
ps.setString(1, table);
ps.setString(2, expectedClause);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString(1));
}
}
}
return names;
server/src/test/java/io/unitycatalog/server/migrate/UpgradeTestUtils.java:114-124
DataSource watched =
watched(
db.dataSource(),
(sql, prepared) -> {
if (step.get() != null && !prepared) {
step.get().add(sql);
}
return sql;
});
// The server's own configuration, so the recorder sees the steps the server would run.
new SchemaMigrator(watched).flyway().callbacks(recorder).load().migrate();
How it was checked
Checked by 1 independent check: NITPICK
Could the description call these four steps with one schema-changing statement each?
There was a problem hiding this comment.
The description refers to one schema-changing DDL statement per step, which is accurate.
There was a problem hiding this comment.
Thanks for explaining the intent: one schema-changing statement per step is the right idea, and since this is only a wording nit on the description, I'm happy to leave it as is (if you touch the text again, "schema-changing statement" would match what the Java steps do).
Settled from our side, thanks. Please resolve this thread when you're ready.
| // PostgreSQL's definition starts with "CHECK"; the others give the bare clause. | ||
| String clause = rs.getString(2).replaceAll("\\s+", " ").trim(); | ||
| checks.add("check %s %s".formatted(table, clause.replaceFirst("^(?i)check ", ""))); | ||
| String enforced = |
There was a problem hiding this comment.
Blocker: An unrelated disabled MySQL check can now prevent ordinary startup
SchemaSnapshot records not enforced for any disabled check it reads on a UC table. Normal startup compares that same snapshot, so the server can refuse to start even when no upgrade is pending.
For example: If an operator disables an expected check on a current-version UC table, requireCurrentSchema() now sees a snapshot mismatch even with no pending geo migrations.
Add a compatibility note: on MySQL, the startup schema check now also compares CHECK enforcement, so a database whose UC CHECK constraint was set NOT ENFORCED fails to start ("The database schema differs ...") until the check is re-enforced. That includes a database already at the current version.
Evidence
I checked the full description's compatibility, migration, testing and scope claims. They describe disabled MySQL checks in upgrade preflight. The changed snapshot marks enforcement for every UC table's checks and the unchanged normal-start path compares that snapshot even when there are no pending steps.
server/src/main/java/io/unitycatalog/server/migrate/SchemaSnapshot.java:56-65
/** MySQL also exposes ENFORCED (YES or NO) on CHECK constraints. */
private static final String MYSQL_CHECKS =
"""
select tc.table_name, cc.check_clause, tc.enforced
from information_schema.table_constraints tc
join information_schema.check_constraints cc
on cc.constraint_schema = tc.constraint_schema and cc.constraint_name = tc.constraint_name
where tc.constraint_type = 'CHECK' and tc.table_schema = database()
""";
server/src/main/java/io/unitycatalog/server/migrate/SchemaSnapshot.java:185-194
if (isSchemaTable(table)) {
// PostgreSQL's definition starts with "CHECK"; the others give the bare clause.
String clause = rs.getString(2).replaceAll("\\s+", " ").trim();
String enforced =
kind == DatabaseKind.MYSQL && "NO".equalsIgnoreCase(rs.getString(3))
? " not enforced"
: "";
checks.add(
"check %s %s%s".formatted(table, clause.replaceFirst("^(?i)check ", ""), enforced));
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:646-657
if (state != SchemaState.CURRENT) {
String recorded = recordedVersion();
throw new IllegalStateException(
"The database schema is at version "
+ (recorded == null ? "none" : recorded)
+ ", and this release needs version "
+ latestVersion()
+ ". Stop every server of the previous release, run bin/start-uc-server"
+ " --upgrade-schema with this release, then start the server.");
}
requireValidHistory(false);
requireLastStepsSchema(", then start the server");
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:1379-1391
private void requireLastStepsSchema(String then) {
SchemaSnapshot schema = SchemaSnapshot.of(dataSource);
SchemaSnapshot expected = expected(latestVersion());
if (!schema.equals(expected)) {
throw new IllegalStateException(
"The database schema differs from the schema of version "
+ latestVersion()
+ ":\n"
+ differences(schema, expected)
+ "\nRepair these differences (see docs/server/upgrades.md) or restore the backup"
+ then
+ ".");
}
How it was checked
Reproduced: UC_TEST_DATABASE=MYSQL_8 UC_TEST_MIGRATION_CHECKS=true dev/run-tests.py -p 1 "server/testOnly io.unitycatalog.server.migrate.SchemaMigratorTest"
with the fix:
[info] Test io.unitycatalog.server.migrate.SchemaMigratorTest#refusesToStartOnCurrentMySqlWithAnUnrelatedCheckNotEnforced() started
[info] Passed: Total 96, Failed 0, Errors 0, Passed 96, Canceled 20
1 suites, 116 tests, 0 failed
server/src/test/java/io/unitycatalog/server/migrate/SchemaMigratorTest.java:1302-1312
@Test
void refusesToStartOnCurrentMySqlWithAnUnrelatedCheckNotEnforced() {
assumeTrue(db.jdbcUrl().startsWith("jdbc:mysql:"), "NOT ENFORCED checks are a MySQL feature");
SchemaMigrator migrator = new SchemaMigrator(db.dataSource());
migrator.upgradeSchema();
migrator.requireCurrentSchema();
UpgradeTestUtils.execute(
db, "ALTER TABLE uc_functions ALTER CHECK uc_functions_data_type_range NOT ENFORCED");
assertThatThrownBy(migrator::requireCurrentSchema).hasMessageContaining("not enforced");
}
Checked by 2 independent checks, which split: DISPROVED, CONFIRMED
Could the compatibility note also call out startup validation for existing MySQL checks?
There was a problem hiding this comment.
Detecting NOT ENFORCED MySQL CHECK constraints in SchemaSnapshot was added specifically per your earlier blocker comment (discussion_r4731069176); flagging a disabled UC constraint at startup is the intended behavior.
There was a problem hiding this comment.
Thanks for tying the NOT ENFORCED detection back to the earlier blocker thread. Refusing to start when a UC check is disabled makes sense to me, so I'm happy to leave the compatibility note as a nit and go with your reasoning here.
Settled from our side, thanks. Please resolve this thread when you're ready.
| - 'NULL' | ||
| - USER_DEFINED_TYPE | ||
| - TABLE_TYPE | ||
| - GEOMETRY |
There was a problem hiding this comment.
Nit (not a blocker): Reordering the new enum values later would silently change the type of stored functions
uc_functions.data_type and uc_function_params.type_name store ColumnTypeName as its ordinal, because the DAO fields have no @Enumerated.
The change relies on GEOMETRY and GEOGRAPHY staying at 22 and 23, but no test reads the stored number. This is one bug class: ColumnTypeName is persisted by JPA ordinal, and no test pins the ordinal of any value. The same issue appears in server/src/main/java/io/unitycatalog/server/persist/dao/FunctionInfoDAO.java:57 (data_type is stored as an ordinal, and nothing asserts GEOMETRY=22 or GEOGRAPHY=23. A later spec reorder silently changes what stored functions return.); server/src/main/java/io/unitycatalog/server/persist/dao/FunctionParameterInfoDAO.java:53 (type_name of function parameters is stored the same way. A separate column and CHECK (V19) have the same unpinned ordinals.); server/src/main/resources/db/migration/h2/V1__baseline_0_7.sql:111 (The other ordinal-stored enum columns guarded by baseline range CHECKs (purpose, parameter_style, routine_body, security_type, sql_data_access, input_or_return,).
For example: Swapping GEOMETRY and GEOGRAPHY in api/all.yaml keeps every current test green: the round trip uses the same enum, and the CHECK range stays 0..23. Functions written by this release would read back with the other type.
try (Connection c = dataSource.getConnection();
ResultSet rs = c.createStatement().executeQuery(
"SELECT name, data_type FROM uc_functions WHERE name LIKE 'fn_geo%'")) {
// assert fn_geometry -> 22, fn_geography -> 23
}
Evidence
The DAO field has no @Enumerated, so it is stored as an ordinal (JPA default). The new values are appended after TABLE_TYPE (21). I searched server/src/test for ordinal, GEOMETRY and GEOGRAPHY: only the round-trip test, which compares enum to enum, uses them.
How it was checked
Checked by 2 independent checks: CONFIRMED
References:
- https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/Enumerated.html: "If the enumerated type is not specified or the Enumerated annotation is not used, the EnumType value is assumed to be ORDINAL."
Would a JDBC read of the stored ordinal in testGeoTypesInFunctions, or an ordinal assertion on the enum, work for you?
There was a problem hiding this comment.
That applies to the entire ColumnTypeName enum, not just GEOMETRY and GEOGRAPHY; the new values are appended at the end to preserve existing ordinals.
There was a problem hiding this comment.
Thanks for pointing out that the concern covers the whole enum and that the new values were appended. I checked at this head: the base-to-head change to api/all.yaml only adds GEOMETRY and GEOGRAPHY after TABLE_TYPE, so the existing ordinals are unchanged and the new ones are 22 and 23. You're right, and I'm happy to leave this as is.
Settled from our side, thanks. Please resolve this thread when you're ready.
9583cc5 to
a2d3e36
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Approving. The preflight name check, the MySQL DROP CHECK change and the rendered error message are in. H2 migration checks pass on this head; PostgreSQL and MySQL passed on the previous head, and the step SQL is unchanged since.
a2d3e36 to
3d28062
Compare
| available.add(constraintKey(table, created.group(1))); | ||
| String name = created.group(1).toLowerCase(Locale.ROOT); | ||
| String key = constraintKey(table, name); | ||
| if (alterTable && available.contains(key)) { |
There was a problem hiding this comment.
Blocker, low probability: Preflight approves an upgrade that stops at V18
simulate looks for the name on the target table, and refuseTakenNames skips every uc_* owner. A check on another UC table can own the name, leaving the database partway through an approved upgrade.
Details
For example: On H2 at V16, rename the existing uc_credentials purpose check to uc_function_params_type_name_range. --check-schema succeeds, then --upgrade-schema records V17 and V18 before V19 fails. This is one bug class: Upgrade preflight treats constraint names as per-table and assumes other UC tables' names are covered by the schema check, but H2 and MySQL CHECK names are schema-wide and the snapshot records CHECKs by clause, not name. The same issue appears in server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:1029 (The H2 'constraint' branch (line 1039) skips every row whose owner starts with uc_.); server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:1048 (The new MySQL 'check constraint' rows go through the same uc_* owner skip.).
Check the schema-wide namespace for H2 constraints and MySQL CHECK names, including constraints owned by other UC tables. Preserve PostgreSQL's table-specific comparison.
Evidence:
Reproduced on H2 2.2.224 by renaming the existing uc_credentials purpose check at V16. The snapshot still matched V16 because it compares clauses. The name scan skips every uc_* owner, and the remaining guard keys by target table. checkSchema returned 0. upgradeSchema committed V17 and V18, then V19 failed with “Constraint already exists.” recordedVersion() returned 18.
The preflight keys constraints by table and skips names owned by UC tables; snapshots omit constraint names. An H2 check confirmed that a name on another table makes V19 fail after V17 and V18 run.
The guide promises that --check-schema tells whether the schema allows the upgrade. simulate checks a table-qualified key, while refuseTakenNames skips all uc_* owners. I ran the head migrator on H2 2.2.224 after renaming the existing uc_credentials check to V19's target name at V16. checkSchema returned 0, V19 failed with 'Constraint ... already exists', and recordedVersion returned 18.
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:827-829
private static String constraintKey(String table, String name) {
return table.toLowerCase(Locale.ROOT) + "." + name.toLowerCase(Locale.ROOT);
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:903-919
boolean alterTable = statement.trim().regionMatches(true, 0, "ALTER TABLE", 0, 11);
Matcher created = CONSTRAINT.matcher(DROP_CONSTRAINT.matcher(statement).replaceAll(""));
while (created.find()) {
String name = created.group(1).toLowerCase(Locale.ROOT);
String key = constraintKey(table, name);
if (alterTable && available.contains(key)) {
throw new IllegalStateException(
"Schema step "
+ step
+ " creates the constraint "
+ name
+ " on table "
+ table
+ ", which already has a constraint of that name. Rename the existing"
+ " constraint, or restore the backup, then run the command again.");
}
available.add(key);
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:1023-1031
String holder = rs.getString(1);
String name = rs.getString(2).toLowerCase(Locale.ROOT);
String table = rs.getString(3);
// Unity Catalog's only: a uc_* table, or an index or constraint on one. A view or a
// sequence has no owning table and is never skipped.
String owner = table != null ? table : holder.equals("table") ? name : "";
if (owner.toLowerCase(Locale.ROOT).startsWith("uc_")) {
continue; // Unity Catalog's own: the schema check covers it
}
server/src/main/java/io/unitycatalog/server/migrate/SchemaMigrator.java:532-546
int changed = 0;
for (String step : pendingSteps()) {
SchemaSnapshot schema = SchemaSnapshot.of(dataSource);
boolean record = adopted || !runs(step, schema);
// Only once the schema check passed, so that a run that refuses leaves the history as is.
deleteFailedRecord(step);
MigrateResult result =
flyway()
.baselineOnMigrate(true)
.baselineVersion(EMPTY_BASELINE_VERSION)
.baselineDescription("empty")
.target(step)
.skipExecutingMigrations(record)
.load()
.migrate();
server/src/main/resources/db/migration/h2/V19__add_function_param_type_name_geo_check.sql:1
ALTER TABLE uc_function_params ADD CONSTRAINT uc_function_params_type_name_range CHECK (type_name BETWEEN 0 AND 23);
How it was checked:
Reproduced: dev/run-tests.py "server/testOnly io.unitycatalog.server.migrate.SchemaMigratorTest"
head:
Failed tests:
io.unitycatalog.server.migrate.SchemaMigratorTest#preflightCatchesReplacementCheckNameTakenByAnotherUcTable(): java.lang.AssertionError: [upgrade error] Expecting actual throwable to be an instance of: java.lang.IllegalStateException but was: org.flywaydb.core.internal.exception.FlywayMigrateException: Failed to execute script V19__add_function_param_type_name_geo_check.sql
(An earlier run of the same test, which asserted the preflight first, failed with: expected: 1 but was: 0 at SchemaMigratorTest.java:1280, so checkSchema() exited 0.)
server/src/test/java/io/unitycatalog/server/migrate/SchemaMigratorTest.java:1260-1290
@Test
void preflightCatchesReplacementCheckNameTakenByAnotherUcTable() throws SQLException {
UpgradeTestUtils.migrateTo(db, "16");
String old;
try (Connection conn = db.dataSource().getConnection();
java.sql.Statement st = conn.createStatement();
java.sql.ResultSet rs =
st.executeQuery(
"SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS"
+ " WHERE TABLE_NAME = 'UC_CREDENTIALS' AND CONSTRAINT_TYPE = 'CHECK'")) {
assertThat(rs.next()).isTrue();
old = rs.getString(1);
}
UpgradeTestUtils.execute(
db,
"ALTER TABLE uc_credentials RENAME CONSTRAINT \""
+ old
+ "\" TO uc_function_params_type_name_range");
SchemaMigrator migrator = new SchemaMigrator(db.dataSource());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int checkExit = migrator.checkSchema(new PrintStream(out, true, StandardCharsets.UTF_8));
Throwable upgradeError = null;
try {
migrator.upgradeSchema();
} catch (Throwable t) {
upgradeError = t;
}
assertThat(upgradeError).as("upgrade error").isInstanceOf(IllegalStateException.class);
assertThat(migrator.recordedVersion()).isEqualTo("16");
assertThat(checkExit).isOne();
}
Checked by 2 independent checks: CONFIRMED
References:
- https://github.com/h2database/h2database/blob/version-2.2.224/h2/src/main/org/h2/command/ddl/AlterTableAddConstraint.java#L99-L112: "if (constraintName != null && getSchema().findConstraint(session, constraintName) != null) {"
- https://dev.mysql.com/doc/refman/8.4/en/create-table-check-constraints.html: "CHECK constraint names must be unique per schema; no two tables in the same schema can share a CHECK constraint name."
- https://github.com/h2database/h2database/blob/version-2.2.224/h2/src/main/org/h2/command/ddl/AlterTableAddConstraint.java#L100-L112: "if (constraintName != null && getSchema().findConstraint(session, constraintName) != null) {"
Could preflight check the database's constraint namespace across UC tables before V17 runs?
There was a problem hiding this comment.
UC tables are schema-managed by UC, so manually renaming an unrelated uc_* table's check constraint to another UC table's constraint name is outside the supported upgrade preconditions.
There was a problem hiding this comment.
we could do it as a follow up if needed
There was a problem hiding this comment.
I think we should do this, its not big change also. In this PR.
There was a problem hiding this comment.
Done — updated simulate() in SchemaMigrator to check constraint names schema-wide across all tables on H2 and MySQL (preserving PostgreSQL's per-table scope), and added SchemaMigratorTest.refusesWhenAnotherUcTableAlreadyUsesReplacementCheckName.
| Matcher created = CONSTRAINT.matcher(DROP_CONSTRAINT.matcher(statement).replaceAll("")); | ||
| while (created.find()) { | ||
| available.add(constraintKey(table, created.group(1))); | ||
| String name = created.group(1).toLowerCase(Locale.ROOT); |
There was a problem hiding this comment.
Thanks for explaining the case-folding choice, and for the clear intent behind it. I reproduced the quoted lower-case name on a non-UC table in H2 and the refusal is real. It fails closed with a message naming the table and constraint, so I'm happy to keep the case-insensitive comparison as is. I'd lean towards an optional line in docs/server/upgrades.md noting this refusal and its repair (rename the other application's constraint), but that's not needed here.
Settled from our side, thanks. Please resolve this thread when you're ready.
| - 'NULL' | ||
| - USER_DEFINED_TYPE | ||
| - TABLE_TYPE | ||
| - GEOMETRY |
There was a problem hiding this comment.
Thanks for spelling out that any new ColumnTypeName value affects strict clients and that databases with no geo values are unaffected, which matches what I saw when decoding with the released 0.4.0 client. I'll go with that as it stands.
Settled from our side, thanks. Please resolve this thread when you're ready.
| # Highest step version on <base-ref> across SQL steps, Java steps, and schema-effects. | ||
| highest_on_base() { | ||
| { | ||
| git ls-tree -r --name-only "$1" -- "$steps_dir/" "$java_step_glob" \ |
There was a problem hiding this comment.
Thanks for explaining why the effect files cover this. I checked it at the head: the glob does miss the Java steps, but a merged Java step always has an effect file, so the version check gives the right result in practice. Cleaning it up in a follow-up or the next time the script is touched is fine with me.
Settled from our side, thanks. Please resolve this thread when you're ready.
| effects_dir=server/src/main/resources/schema-effects | ||
| java_steps_dir=server/src/main/java/io/unitycatalog/server/migrate | ||
| java_step_glob="$java_steps_dir/V*.java" | ||
| java_helper="$java_steps_dir/DropRangeCheckMigration.java" |
There was a problem hiding this comment.
Thanks for explaining the intent: with the helper frozen on purpose, a future backend addition has to edit the guard explicitly, and I'm fine with that. I checked the head: dev/check-migration-steps.sh names DropRangeCheckMigration.java and refuses changes to it, and refusesEditingSharedJavaHelper covers that. I'm happy to leave it as is.
Settled from our side, thanks. Please resolve this thread when you're ready.
| return names.get(0); | ||
| } | ||
|
|
||
| private String expectedClause(DatabaseKind kind) { |
There was a problem hiding this comment.
Thanks for pointing to the MySQL snapshot check: I confirmed on MySQL 8 that with the old 0..21 check set to NOT ENFORCED at V16, the upgrade is refused and the schema version stays at 16, so a self-contained lookup is fine and I'm happy to leave it as is. One small wording note: the refusal comes from the pre-upgrade schema comparison, not a post-upgrade one. refusesMySqlWhoseOldDataTypeCheckIsNotEnforced in SchemaMigratorTest is what pins that case.
Settled from our side, thanks. Please resolve this thread when you're ready.
| - 'NULL' | ||
| - USER_DEFINED_TYPE | ||
| - TABLE_TYPE | ||
| - GEOMETRY |
There was a problem hiding this comment.
Thanks for pointing to #2373 for the UI client regeneration; that works for me, so I'm happy to leave the generated UI client out of this server PR.
Settled from our side, thanks. Please resolve this thread when you're ready.
| public void migrate(Context context) throws SQLException { | ||
| Connection connection = context.getConnection(); | ||
| DatabaseKind kind = DatabaseKind.of(connection); | ||
| String name = requireSingleConstraintName(connection, kind); |
There was a problem hiding this comment.
Thanks for explaining the intent: one schema-changing statement per step is the right idea, and since this is only a wording nit on the description, I'm happy to leave it as is (if you touch the text again, "schema-changing statement" would match what the Java steps do).
Settled from our side, thanks. Please resolve this thread when you're ready.
| // PostgreSQL's definition starts with "CHECK"; the others give the bare clause. | ||
| String clause = rs.getString(2).replaceAll("\\s+", " ").trim(); | ||
| checks.add("check %s %s".formatted(table, clause.replaceFirst("^(?i)check ", ""))); | ||
| String enforced = |
There was a problem hiding this comment.
Thanks for tying the NOT ENFORCED detection back to the earlier blocker thread. Refusing to start when a UC check is disabled makes sense to me, so I'm happy to leave the compatibility note as a nit and go with your reasoning here.
Settled from our side, thanks. Please resolve this thread when you're ready.
| - 'NULL' | ||
| - USER_DEFINED_TYPE | ||
| - TABLE_TYPE | ||
| - GEOMETRY |
There was a problem hiding this comment.
Thanks for pointing out that the concern covers the whole enum and that the new values were appended. I checked at this head: the base-to-head change to api/all.yaml only adds GEOMETRY and GEOGRAPHY after TABLE_TYPE, so the existing ordinals are unchanged and the new ones are 22 and 23. You're right, and I'm happy to leave this as is.
Settled from our side, thanks. Please resolve this thread when you're ready.
551cd8e to
91d62df
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Follow-up to our approval, which stands. The cross-table name check added at this head refuses a valid upgrade. A CHECK on uc_functions renamed to uc_function_params_type_name_range makes preflight refuse V19, although V18 drops that CHECK before V19 needs the name. The refusal is clean (the version stays at 16), but the upgrade cannot proceed. I reproduced this on H2 at this head. The preflight does not simulate Java drop steps, because stepScript returns empty for them.
Docs: docs/server/upgrades.md has no entry for a MySQL CHECK shown as not enforced, though the PR description says the refusal has repair guidance there. Could that entry be added?
| available.add(constraintKey(table, created.group(1))); | ||
| String name = created.group(1).toLowerCase(Locale.ROOT); | ||
| String key = constraintKey(table, name); | ||
| String holder = alterTable ? existingConstraintHolder(available, table, name) : null; |
There was a problem hiding this comment.
[AI Assisted] Here the cross-table check refuses a valid upgrade. V18 drops the CHECK that was renamed to uc_function_params_type_name_range before V19 needs the name, but the simulation does not apply Java drop steps (stepScript returns empty for them), so the name stays in available. Could the simulation treat the Java drop as removing the name? The refusal is clean (the version stays at 16), so this is not a half-applied upgrade. Found with a probe on H2 at this head.
There was a problem hiding this comment.
Done — DropRangeCheckMigration.verifySingleMatch now returns the matched constraint name and simulate() removes it from available (and the MySQL CHECK set) when the Java drop step runs, with a regression test in SchemaMigratorTest.allowsUpgradeWhenRenamedOldCheckIsDroppedBeforeLaterStepReusesItsName.
| } | ||
| String suffix = "." + name.toLowerCase(Locale.ROOT); | ||
| return available.stream() | ||
| .filter(k -> k.endsWith(suffix)) |
There was a problem hiding this comment.
[AI Assisted] On MySQL, constraintKeys() has no CONSTRAINT_TYPE filter, so this suffix match also counts primary key, unique and foreign key names from other tables. A foreign key named uc_functions_data_type_range on another table would refuse V17, although MySQL accepts the CHECK. Found by reading the code, not reproduced. Could CHECK names be compared only against other CHECK constraints on MySQL?
There was a problem hiding this comment.
Done — on MySQL, cross-table CHECK collisions in existingConstraintHolder() now query CONSTRAINT_TYPE = 'CHECK' only (while still checking same-table constraints of any kind), with a regression test in SchemaMigratorTest.allowsMysqlCheckWhenAnotherTableHasForeignKeyOfSameName.
|
/review |
91d62df to
a73b991
Compare
|
Rebased onto |
|
/review |
Add GEOMETRY and GEOGRAPHY to ColumnTypeName in api/all.yaml (appended so existing ordinals stay unchanged). Widen the ordinal CHECK constraints on uc_functions.data_type and uc_function_params.type_name from 0..21 to 0..23 across H2, PostgreSQL, and MySQL: - V24 / V26 (SQL): add named CHECK (0..23) constraints on uc_functions and uc_function_params. - V25 / V27 (Java migrations): look up and drop the old unnamed 0..21 CHECK constraints by clause so upgrades work on both fresh and repaired databases. Update SchemaMigrator, MigrationStepRulesTest, docs/server/upgrades.md, and schema-effects for all three databases, and add SdkFunctionCRUDTest coverage for GEOMETRY and GEOGRAPHY function parameters and return types. Signed-off-by: Timothy Wang <[email protected]>
a73b991 to
b609f6d
Compare
🥞 Stacked PR
Use this link to review incremental changes.
PR Checklist
docsis updated (upgrade repair notes indocs/server/upgrades.md; CLI/table docs in [CLI/UI/Docs] Support and document geometry and geography columns #2373)Description of changes
Adds
GEOMETRYandGEOGRAPHYtoColumnTypeNameinapi/all.yaml, appended at the end so existing enum ordinals do not change.Because
uc_functions.data_typeanduc_function_params.type_namestoreColumnTypeNameas integer ordinals under unnamedCHECK (0..21)constraints from the 0.7.0 baseline, this PR also widens both checks to0..23across H2, PostgreSQL, and MySQL in four single-statement steps:V17andV19add namedCHECK (0..23)constraints, andV18andV20(Flyway Java migrations) look up and drop the old unnamed0..21constraints by clause (DROP CHECKon MySQL) so upgrades work on both fresh and repaired databases. Upgrade preflight refuses duplicate/missing range checks, occupieduc_*constraint names, and disabled (NOT ENFORCED) MySQL checks, with operator repair guidance indocs/server/upgrades.md.Tested with
BaselineMatchesEntitiesTest,MigrationStepRulesTest,SchemaMigratorTest,CheckMigrationStepsScriptTest,SchemaGateTest,SchemaSnapshotTest, andSdkFunctionCRUDTest(including parameterized geo types andlistFunctions) on H2, PostgreSQL 18, and MySQL 8.