Repository navigation
fix(migrations): stop a MySQL migration on an unsupported database collation before it changes anything #37150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
105 changes: 105 additions & 0 deletions
105
...a-service/src/main/java/org/openmetadata/service/migration/utils/MySqlCollationCheck.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| package org.openmetadata.service.migration.utils; | ||
|
|
||
| import java.util.List; | ||
| import java.util.stream.Stream; | ||
| import org.jdbi.v3.core.Handle; | ||
| import org.jdbi.v3.core.Jdbi; | ||
|
|
||
| /** | ||
| * Stops a MySQL command before it changes anything when the database uses a collation that clashes | ||
| * with the schema. Newer tables pin {@value #REQUIRED_COLLATION}, while the core tables take the | ||
| * database default, and migrations and queries compare the core id columns with ids in the newer | ||
| * tables. MySQL refuses to compare two different non-binary collations of the same character set, | ||
| * so only a utf8mb4 collation other than {@value #REQUIRED_COLLATION} or a {@code _bin} one fails: | ||
| * MySQL converts any other character set to utf8mb4, and a {@code _bin} collation wins the | ||
| * comparison. | ||
| */ | ||
| public final class MySqlCollationCheck { | ||
| public static final String REQUIRED_COLLATION = "utf8mb4_0900_ai_ci"; | ||
| private static final String CLASHING_CHARACTER_SET = "utf8mb4"; | ||
| private static final String BINARY_COLLATION_SUFFIX = "_bin"; | ||
|
|
||
| private static final String DATABASE_DEFAULT_QUERY = | ||
| "SELECT 'the database default' AS target, DEFAULT_CHARACTER_SET_NAME AS characterSet," | ||
| + " DEFAULT_COLLATION_NAME AS collation" | ||
| + " FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = DATABASE()"; | ||
|
|
||
| // Columns, not TABLE_COLLATION: ALTER TABLE ... COLLATE without CONVERT TO changes only the | ||
| // table default and leaves the columns on the old collation. | ||
| private static final String CORE_ID_COLUMNS_QUERY = | ||
| "SELECT CONCAT('column ', TABLE_NAME, '.', COLUMN_NAME) AS target," | ||
| + " CHARACTER_SET_NAME AS characterSet, COLLATION_NAME AS collation" | ||
| + " FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE()" | ||
| + " AND ((TABLE_NAME = 'entity_relationship' AND COLUMN_NAME IN ('fromId', 'toId'))" | ||
| + " OR (TABLE_NAME = 'entity_extension' AND COLUMN_NAME = 'id'))" | ||
| + " ORDER BY target"; | ||
|
|
||
| private static final String MESSAGE = | ||
| "This MySQL database uses a utf8mb4 collation that clashes with the %s tables of" | ||
| + " OpenMetadata: %s. MySQL refuses to compare two different non-binary utf8mb4" | ||
| + " collations, so the migrations and queries that compare ids across these tables would" | ||
| + " fail. Nothing has been changed. Back up the database, then move each item listed to" | ||
| + " %s: for the database default, run ALTER DATABASE `%s` CHARACTER SET utf8mb4 COLLATE" | ||
| + " %s; for a column, change its collation with ALTER TABLE ... MODIFY, keeping its type" | ||
| + " and NOT NULL. Then run the command again."; | ||
|
|
||
| private MySqlCollationCheck() {} | ||
|
|
||
| /** Checks the database default and the core id columns, before a migration. */ | ||
| public static void verify(Jdbi jdbi) { | ||
| jdbi.useHandle(handle -> stopOnClashes(handle, findClashes(handle))); | ||
| } | ||
|
|
||
| /** Checks only the database default, before drop-create recreates every table from it. */ | ||
| public static void verifyDatabaseDefault(Jdbi jdbi) { | ||
| jdbi.useHandle(handle -> stopOnClashes(handle, findDatabaseDefaultClashes(handle))); | ||
| } | ||
|
|
||
| static List<String> findClashes(Handle handle) { | ||
| return Stream.concat( | ||
| findDatabaseDefaultClashes(handle).stream(), | ||
| findClashes(handle, CORE_ID_COLUMNS_QUERY).stream()) | ||
| .toList(); | ||
| } | ||
|
|
||
| static List<String> findDatabaseDefaultClashes(Handle handle) { | ||
| return findClashes(handle, DATABASE_DEFAULT_QUERY); | ||
| } | ||
|
|
||
| private static List<String> findClashes(Handle handle, String query) { | ||
| return handle | ||
| .createQuery(query) | ||
| .map( | ||
| (row, context) -> | ||
| new Target( | ||
| row.getString("target"), | ||
| row.getString("characterSet"), | ||
| row.getString("collation"))) | ||
| .stream() | ||
| .filter(Target::clashes) | ||
| .map(target -> target.name() + " uses " + target.collation()) | ||
| .toList(); | ||
| } | ||
|
|
||
| private static void stopOnClashes(Handle handle, List<String> clashes) { | ||
| if (!clashes.isEmpty()) { | ||
| String database = handle.createQuery("SELECT DATABASE()").mapTo(String.class).one(); | ||
| throw new IllegalStateException( | ||
| String.format( | ||
| MESSAGE, | ||
| REQUIRED_COLLATION, | ||
| String.join(", ", clashes), | ||
| REQUIRED_COLLATION, | ||
| database, | ||
| REQUIRED_COLLATION)); | ||
| } | ||
| } | ||
|
|
||
| private record Target(String name, String characterSet, String collation) { | ||
| boolean clashes() { | ||
| return CLASHING_CHARACTER_SET.equals(characterSet) | ||
| && !REQUIRED_COLLATION.equals(collation) | ||
| && !collation.endsWith(BINARY_COLLATION_SUFFIX); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
181 changes: 181 additions & 0 deletions
181
...rvice/src/test/java/org/openmetadata/service/migration/utils/MySqlCollationCheckTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| package org.openmetadata.service.migration.utils; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; | ||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertFalse; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| import java.util.List; | ||
| import org.jdbi.v3.core.Jdbi; | ||
| import org.junit.jupiter.api.BeforeAll; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.params.ParameterizedTest; | ||
| import org.junit.jupiter.params.provider.MethodSource; | ||
| import org.testcontainers.containers.GenericContainer; | ||
| import org.testcontainers.junit.jupiter.Container; | ||
| import org.testcontainers.junit.jupiter.Testcontainers; | ||
| import org.testcontainers.utility.DockerImageName; | ||
|
|
||
| @Testcontainers(disabledWithoutDocker = true) | ||
| class MySqlCollationCheckTest { | ||
| private static final String PASSWORD = "collation-check-test"; | ||
| private static final String SHIPPED = MySqlCollationCheck.REQUIRED_COLLATION; | ||
| private static final String UNICODE = "utf8mb4_unicode_ci"; | ||
| private static final String GENERAL = "utf8mb4_general_ci"; | ||
| private static final List<String> COMPATIBLE_DEFAULTS = | ||
| List.of(SHIPPED, "utf8mb3_general_ci", "latin1_swedish_ci", "utf8mb4_bin"); | ||
| private static final List<String> CLASHING_COLLATIONS = List.of(UNICODE, GENERAL); | ||
| private static final List<String> CORE_ID_COLUMNS = | ||
| List.of( | ||
| "column entity_extension.id", | ||
| "column entity_relationship.fromId", | ||
| "column entity_relationship.toId"); | ||
|
|
||
| @Container | ||
| static final GenericContainer<?> MYSQL = | ||
| new GenericContainer<>(DockerImageName.parse("mysql:8.0")) | ||
| .withEnv("MYSQL_ROOT_PASSWORD", PASSWORD) | ||
| .withExposedPorts(3306); | ||
|
|
||
| @BeforeAll | ||
| static void createDatabases() { | ||
| COMPATIBLE_DEFAULTS.forEach( | ||
| collation -> createDatabaseWithCoreTables("default_" + collation, collation, "")); | ||
| CLASHING_COLLATIONS.forEach( | ||
| collation -> { | ||
| createDatabaseWithCoreTables("default_" + collation, collation, ""); | ||
| createDatabaseWithCoreTables( | ||
| "drifted_" + collation, SHIPPED, " CHARACTER SET utf8mb4 COLLATE " + collation); | ||
| }); | ||
| createDatabaseWithCoreTables("table_default_only", SHIPPED, " COLLATE " + UNICODE); | ||
| jdbi("table_default_only") | ||
| .useHandle( | ||
| handle -> { | ||
| handle.execute("ALTER TABLE entity_relationship COLLATE " + SHIPPED); | ||
| handle.execute("ALTER TABLE entity_extension COLLATE " + SHIPPED); | ||
| }); | ||
| createDatabase("empty_" + UNICODE, UNICODE); | ||
| } | ||
|
|
||
| @ParameterizedTest | ||
| @MethodSource("compatibleDefaults") | ||
| void passesOnACollationThatComparesWithTheShippedOne(String collation) { | ||
| assertDoesNotThrow(() -> MySqlCollationCheck.verify(jdbi("default_" + collation))); | ||
| } | ||
|
|
||
| @Test | ||
| void ignoresAnAsciiExtensionColumnNextToTheShippedIdColumn() { | ||
| List<String> clashes = jdbi("default_" + SHIPPED).withHandle(MySqlCollationCheck::findClashes); | ||
|
|
||
| assertEquals(List.of(), clashes); | ||
| } | ||
|
|
||
| @ParameterizedTest | ||
| @MethodSource("clashingCollations") | ||
| void reportsAClashingDatabaseDefaultAndTheCoreIdColumnsThatInheritedIt(String collation) { | ||
| List<String> clashes = | ||
| jdbi("default_" + collation).withHandle(MySqlCollationCheck::findClashes); | ||
|
|
||
| assertEquals( | ||
| List.of( | ||
| "the database default uses " + collation, | ||
| CORE_ID_COLUMNS.get(0) + " uses " + collation, | ||
| CORE_ID_COLUMNS.get(1) + " uses " + collation, | ||
| CORE_ID_COLUMNS.get(2) + " uses " + collation), | ||
| clashes); | ||
| } | ||
|
|
||
| @ParameterizedTest | ||
| @MethodSource("clashingCollations") | ||
| void reportsCoreIdColumnsThatDriftedFromTheDatabaseDefault(String collation) { | ||
| List<String> clashes = | ||
| jdbi("drifted_" + collation).withHandle(MySqlCollationCheck::findClashes); | ||
|
|
||
| assertEquals( | ||
| CORE_ID_COLUMNS.stream().map(column -> column + " uses " + collation).toList(), clashes); | ||
| } | ||
|
|
||
| @Test | ||
| void reportsColumnsLeftBehindWhenOnlyTheTableDefaultWasChanged() { | ||
| List<String> clashes = jdbi("table_default_only").withHandle(MySqlCollationCheck::findClashes); | ||
|
|
||
| assertEquals( | ||
| CORE_ID_COLUMNS.stream().map(column -> column + " uses " + UNICODE).toList(), clashes); | ||
| } | ||
|
|
||
| @ParameterizedTest | ||
| @MethodSource("clashingCollations") | ||
| void databaseDefaultCheckIgnoresDriftedTables(String collation) { | ||
| Jdbi drifted = jdbi("drifted_" + collation); | ||
|
|
||
| assertEquals(List.of(), drifted.withHandle(MySqlCollationCheck::findDatabaseDefaultClashes)); | ||
| assertDoesNotThrow(() -> MySqlCollationCheck.verifyDatabaseDefault(drifted)); | ||
| } | ||
|
|
||
| @Test | ||
| void databaseDefaultCheckStopsOnAClashingDefault() { | ||
| IllegalStateException failure = | ||
| assertThrows( | ||
| IllegalStateException.class, | ||
| () -> MySqlCollationCheck.verifyDatabaseDefault(jdbi("default_" + UNICODE))); | ||
|
|
||
| assertTrue(failure.getMessage().contains("the database default uses " + UNICODE)); | ||
| assertFalse(failure.getMessage().contains("column ")); | ||
| } | ||
|
|
||
| @Test | ||
| void stopsAFreshInstallOnAClashingDefaultWithAnActionableMessage() { | ||
| IllegalStateException failure = | ||
| assertThrows( | ||
| IllegalStateException.class, | ||
| () -> MySqlCollationCheck.verify(jdbi("empty_" + UNICODE))); | ||
|
|
||
| assertTrue(failure.getMessage().contains("the database default uses " + UNICODE)); | ||
| assertTrue(failure.getMessage().contains("ALTER DATABASE `empty_" + UNICODE + "`")); | ||
| assertTrue(failure.getMessage().contains("COLLATE " + SHIPPED)); | ||
| } | ||
|
|
||
| static List<String> compatibleDefaults() { | ||
| return COMPATIBLE_DEFAULTS; | ||
| } | ||
|
|
||
| static List<String> clashingCollations() { | ||
| return CLASHING_COLLATIONS; | ||
| } | ||
|
|
||
| private static void createDatabaseWithCoreTables( | ||
| String database, String defaultCollation, String tableCollation) { | ||
| createDatabase(database, defaultCollation); | ||
| jdbi(database) | ||
| .useHandle( | ||
| handle -> { | ||
| handle.execute( | ||
| "CREATE TABLE entity_relationship (fromId VARCHAR(36) NOT NULL," | ||
| + " toId VARCHAR(36) NOT NULL)" | ||
| + tableCollation); | ||
| handle.execute( | ||
| "CREATE TABLE entity_extension (id VARCHAR(36) NOT NULL," | ||
| + " extension VARCHAR(256) CHARACTER SET ascii COLLATE ascii_bin NOT NULL)" | ||
| + tableCollation); | ||
| }); | ||
| } | ||
|
|
||
| private static void createDatabase(String database, String collation) { | ||
| String characterSet = collation.substring(0, collation.indexOf('_')); | ||
| jdbi("mysql") | ||
| .useHandle( | ||
| handle -> | ||
| handle.execute( | ||
| "CREATE DATABASE %s CHARACTER SET %s COLLATE %s" | ||
| .formatted(database, characterSet, collation))); | ||
| } | ||
|
|
||
| private static Jdbi jdbi(String database) { | ||
| return Jdbi.create( | ||
| "jdbc:mysql://%s:%d/%s?allowPublicKeyRetrieval=true&useSSL=false" | ||
| .formatted(MYSQL.getHost(), MYSQL.getMappedPort(3306), database), | ||
| "root", | ||
| PASSWORD); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.