Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/all.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1792,6 +1792,8 @@ components:
- 'NULL'
- USER_DEFINED_TYPE
- TABLE_TYPE
- GEOMETRY

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.

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:

Could we release and select a compatible Python reader before these values appear in shared schemas?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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.

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed — leaving UI client regeneration out of this server PR; UI updates live in #2373.

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.

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.

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.

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:

Would a JDBC read of the stored ordinal in testGeoTypesInFunctions, or an ordinal assertion on the enum, work for you?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

That applies to the entire ColumnTypeName enum, not just GEOMETRY and GEOGRAPHY; the new values are appended at the end to preserve existing ordinals.

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.

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.

Comment thread
timothyw553 marked this conversation as resolved.
Resolved
- GEOGRAPHY
ColumnInfo:
type: object
properties:
Expand Down
54 changes: 34 additions & 20 deletions dev/check-migration-steps.sh
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env bash
Comment thread
timothyw553 marked this conversation as resolved.
Resolved
#
# Fails when HEAD edits, deletes or renames a schema migration step, or a step's effect file, that
# exists on <base-ref>. Databases already ran those steps, and the effect files tell
# --upgrade-schema what they did, so a change to the schema must be a new step.
# Fails when a new step's version is not above every step on <base-ref> for that database:
# Fails when HEAD edits, deletes or renames a schema migration step (SQL or Java), the shared Java
# migration helper, or a step's effect file that exists on <base-ref>. Databases already ran those
# steps, and the effect files tell --upgrade-schema what they did, so a change to the schema must
# be a new step.
# 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.
Expand All @@ -25,49 +26,62 @@ base_branch=${2:-}

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
Comment thread
timothyw553 marked this conversation as resolved.
Resolved
java_step_glob="$java_steps_dir/V*.java"
java_helper="$java_steps_dir/DropRangeCheckMigration.java"

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.

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:

Would freezing only the V*.java steps keep the guarantee you wanted, while leaving the dialect code free to change?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Freezing DropRangeCheckMigration.java is intentional so merged Java migration behavior cannot silently drift; a future backend addition can explicitly update the guard if needed.

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.

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.


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")
changed=$(git diff --diff-filter=MDRT --name-status "$merge_base" HEAD -- \
"$steps_dir" "$effects_dir" "$java_step_glob" "$java_helper")
if [[ -n "$changed" ]]; then
echo "These merged migration steps or effect files changed since $1:" >&2
echo "These merged migration steps, helpers, or effect files changed since $1:" >&2
echo "$changed" >&2
echo "Merged steps can't change; add a new step under $steps_dir/<db>/ instead." >&2
echo "Merged steps can't change; add a new step instead." >&2
exit 1
fi
echo "No merged migration step or effect file changed since $1."
echo "No merged migration step, helper, or effect file changed since $1."

# A release branch takes no new steps at all, so say that before checking their numbers.
added=$(git diff --diff-filter=A --name-only "$merge_base" HEAD -- "$steps_dir" "$effects_dir")
added=$(git diff --diff-filter=A --name-only "$merge_base" HEAD -- \
"$steps_dir" "$effects_dir" "$java_step_glob")
if [[ -n "$added" && "$base_branch" == branch-* ]]; then
echo "These migration steps are new on the release branch $base_branch:" >&2
echo "$added" >&2
echo "Release branches take no new steps; add the step on main." >&2
exit 1
fi

# The version of a step file name V<version>__<description>.sql.
version_of() { basename "$1" | sed -n 's/^V\([0-9]*\)__.*/\1/p'; }
# The version of a step file name V<version>__<description>.(sql|java) or effect file V<version>.txt.
version_of_step() { basename "$1" | sed -n 's/^V\([0-9]*\)__.*/\1/p'; }
version_of_effect() { basename "$1" | sed -n 's/^V\([0-9]*\)\.txt$/\1/p'; }

added_steps=$(git diff --diff-filter=A --name-only "$merge_base" HEAD -- "$steps_dir")
# 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" \

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.

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.

Suggested change
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:

Could we list the migration directory and let version_of_step select the versioned files?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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.

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.

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:

Could the script list the Java directory and let version_of_step select the versioned files?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Duplicate of discussion_r4744726774 — see reply there.

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.

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.

| 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")

added_steps=$(git diff --diff-filter=A --name-only "$merge_base" HEAD -- \
"$steps_dir" "$java_step_glob")
for step in $added_steps; do
folder=$(dirname "$step")
highest=$(git ls-tree --name-only "$1" -- "$folder/" \
| while read -r f; do version_of "$f"; done | sort -n | tail -n 1)
version=$(version_of "$step")
version=$(version_of_step "$step")
if [[ ! "$version" =~ ^[0-9]+$ ]]; then
echo "The new step $step has a version that is not a whole number." >&2
echo "Name it V<number>__<description>.sql." >&2
echo "Name it V<number>__<description>.sql or V<number>__<description>.java." >&2
exit 1
fi
# 10# keeps bash from reading a leading zero (V08) as octal.
version=$((10#$version))
if [[ -n "$highest" ]]; then
highest=$((10#$highest))
fi
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
Expand Down
20 changes: 19 additions & 1 deletion docs/server/upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,17 +258,35 @@ Messages that the server prints when it refuses to start, and that `--check-sche
: An object that is not Unity Catalog's holds a name that the step needs, in a namespace that the
database shares between tables: on H2 the index names and the constraint names of a schema, and
the names of its tables, views and synonyms; on PostgreSQL the names of a schema's tables
(also partitioned ones), views, sequences and indexes, and its types (for a table's name); on MySQL the foreign key names of a database, and the names of its tables
(also partitioned ones), views, sequences and indexes, and its types (for a table's name); on MySQL
the foreign key and `CHECK` constraint names of a database, and the names of its tables
and views.
A view, a sequence or an index on another application's table never counts as Unity Catalog's,
even when its name starts with `uc_`. The step did not run. Rename that object, or give Unity
Catalog a schema of its own, then run the command again.

`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.

`Schema step <n> drops the constraint <name>, but the database has no constraint of that name`
: The step drops a constraint by name, and the name is gone, for instance because it was renamed
although the constraint's definition is unchanged. The step did not run. Restore the name, or
restore the backup, then run the command again.

`Expected exactly one CHECK constraint matching <clause> on <table>, found <names>`
: A step that drops a replaced range `CHECK` constraint found either none or more than one matching
constraint on `<table>`. The step did not run. If none was found, restore the missing `CHECK`
constraint; if several were found, drop the duplicate(s) so only one remains (or restore the
backup), then run `--upgrade-schema` again.

`unexpected check <table> <clause> not enforced`
: On MySQL, a `CHECK` constraint on `<table>` is marked `NOT ENFORCED`. Unity Catalog requires its
`CHECK` constraints to be enforced so an upgrade cannot drop an enforced constraint while leaving
only a disabled one. Re-enable it with `ALTER TABLE <table> ALTER CHECK <name> ENFORCED` (or drop
the disabled duplicate and restore the enforced constraint), then run `--upgrade-schema` again.

`The database schema differs from the schema of version <m>:`
: Followed by the differences, as above. The schema history records this release's last version,
but the schema is not the one this release's steps build: something changed it outside the steps.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package io.unitycatalog.server.migrate;

import io.unitycatalog.server.migrate.SchemaMigrator.DatabaseKind;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import javax.sql.DataSource;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Drops an unnamed ordinal-range {@code CHECK} constraint (such as {@code BETWEEN 0 AND 21}) after
* a prior step has added its wider replacement. Looks up the database-generated constraint name at
* runtime so the step works on fresh databases and on databases whose checks were repaired or
* renamed.
*/
abstract class DropRangeCheckMigration extends BaseJavaMigration {

private static final Logger LOGGER = LoggerFactory.getLogger(DropRangeCheckMigration.class);

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) = ?
""";

private final String table;
private final String column;
private final int min;
private final int max;

DropRangeCheckMigration(String table, String column, int min, int max) {
this.table = table.toLowerCase(Locale.ROOT);
this.column = column.toLowerCase(Locale.ROOT);
this.min = min;
this.max = max;
}

String table() {
return table;
}

@Override
public Integer getChecksum() {
return Objects.hash(table, column, min, max);
}

/**
* Preflight check called before running pending steps so duplicate or missing CHECK constraints
* fail before an earlier step (such as adding the wider CHECK) commits. Returns the matched
* constraint name so simulation can account for its removal.
*/
String verifySingleMatch(DataSource dataSource, DatabaseKind kind) {
try (Connection connection = dataSource.getConnection()) {
return requireSingleConstraintName(connection, kind);
} catch (SQLException e) {
throw new IllegalStateException(
"Could not check existing CHECK constraints on %s: %s".formatted(table, e.getMessage()),
e);
}
}

@Override
public void migrate(Context context) throws SQLException {
Connection connection = context.getConnection();
DatabaseKind kind = DatabaseKind.of(connection);
String name = requireSingleConstraintName(connection, kind);
Comment thread
timothyw553 marked this conversation as resolved.
Resolved

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.

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.

Suggested change
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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The description refers to one schema-changing DDL statement per step, which is accurate.

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.

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.

String dropSql = dropStatement(kind, name);
try (Statement statement = connection.createStatement()) {
statement.execute(dropSql);
}
LOGGER.info("Dropped old range check {} on {}.{} ({}..{})", name, table, column, min, max);
}

private String requireSingleConstraintName(Connection connection, DatabaseKind kind)
throws SQLException {
String expectedClause = expectedClause(kind);
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"
+ " CHECK constraint or restore the backup, then run --upgrade-schema again.")
.formatted(expectedClause, table));
}
if (names.size() > 1) {
throw new IllegalStateException(
("Expected exactly one CHECK constraint matching %s on %s, found %s. Drop the duplicate"
+ " CHECK constraint(s) so only one remains, or restore the backup, then run"
+ " --upgrade-schema again.")
.formatted(expectedClause, table, names));
}
return names.get(0);
}

private String expectedClause(DatabaseKind kind) {

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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.

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("`", "``"));
};
}
}
Loading
Loading