Skip to content
Closed
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
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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -129,6 +130,7 @@
import org.openmetadata.service.logging.SwitchableEventLayoutFactory;
import org.openmetadata.service.migration.MigrationValidationClient;
import org.openmetadata.service.migration.api.MigrationWorkflow;
import org.openmetadata.service.migration.utils.MySqlCollationCheck;
import org.openmetadata.service.resources.CollectionRegistry;
import org.openmetadata.service.resources.apps.AppMapper;
import org.openmetadata.service.resources.apps.AppMarketPlaceMapper;
Expand Down Expand Up @@ -1122,6 +1124,7 @@ public Integer dropCreate() {
try {
promptUserForDelete();
parseConfig();
verifyMySqlCollation(MySqlCollationCheck::verifyDatabaseDefault);
LOG.info("Deleting all the OpenMetadata tables.");
dropAllTables();
LOG.info("Running the Native Migrations.");
Expand Down Expand Up @@ -1317,6 +1320,7 @@ public Integer migrate(
try {
LOG.info("Migrating the OpenMetadata Schema.");
parseConfig();
verifyMySqlCollation(MySqlCollationCheck::verify);
validateAndRunSystemDataMigrations(force);
LOG.info("Running Flowable schema upgrade.");
WorkflowHandler.initialize(config, true);
Expand Down Expand Up @@ -3600,6 +3604,13 @@ private void promptUserForDelete() {
}
}

private void verifyMySqlCollation(Consumer<Jdbi> collationCheck) {
ConnectionType connType = ConnectionType.from(config.getDataSourceFactory().getDriverClass());
if (connType == ConnectionType.MYSQL) {
collationCheck.accept(jdbi);
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved
}

private void validateAndRunSystemDataMigrations(boolean force) {
ConnectionType connType = ConnectionType.from(config.getDataSourceFactory().getDriverClass());
DatasourceConfig.initialize(connType.label);
Expand Down
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);
}
}
Loading