From c89eb4d7f679f7654723bea315547dc32f09fd69 Mon Sep 17 00:00:00 2001 From: dbulahov Date: Mon, 23 Nov 2026 18:21:57 +0300 Subject: [PATCH] dialect(mysql): version checks and fixes, tested on MySQL in Docker The dialect wrote SQL that MySQL refused or that lost data. Each case is now run against the server, on the versions around its boundary: - PERCENTILE_DISC/CONT: none on any version; MySQL has no such functions and refused WITHIN GROUP with a syntax error - regular expressions in SQL from 8.0, whose REGEXP is ICU's; 5.7's Henry Spencer REGEXP refused (?-i), \A and \z, and the expression is matched in Java there - upsert without update columns: ON DUPLICATE KEY UPDATE key = key, insert-or-ignore as UpsertSpec says, not a plain INSERT that failed with "Duplicate entry" - upsert with update columns: the row alias from 8.0.19, INSERT ... AS new_row ... UPDATE col = new_row.col, instead of VALUES(col), which 8.0.20 deprecates with warning 1287; VALUES(col) before; a dialect without a version writes the alias - GROUP_CONCAT: the separator a string literal of its own, a quote or a backslash in it no longer ends it; NULLS FIRST/LAST, which MySQL has not, as an order of col IS NULL before the column; a list longer than group_concat_max_len is cut, as the Javadoc now says - triggers: WHEN, which MySQL has not, as an IF around the body; no FOR EACH STATEMENT, which MySQL has not either and a row trigger cannot stand in for: UnsupportedOperationException - RENAME INDEX from 5.7; before, renameIndex gives null - a column renamed before 8.0 with CHANGE keeps its AUTO_INCREMENT and its COMMENT; a generated column is not renamed Tested as they were: users from 5.7.8, roles from 8.0, recursive CTEs from 8.0, descending index columns from 8.0, the order by an alias from 5.7. The Docker tests are in the container package and run with -Dintegration.docker=true on MySQL 5.6, 5.7, 8.0, 8.4 and 9. Their server has a my.cnf of its own: Testcontainers' default sets Signed-off-by: --- .../sql/dialect/api/DialectInitData.java | 6 +- .../sql/dialect/api/DialectVersion.java | 13 ++ .../db/common/DialectInitDataVersionTest.java | 63 +++++++ .../dialect/db/mariadb/MariaDBDialect.java | 19 ++ .../MariaDBVersionCapabilitiesTest.java | 15 +- .../container/MariaDBPercentileTest.java | 96 ++++++++++ .../sql/dialect/db/mysql/MySqlDialect.java | 170 ++++++++++++++++-- .../dialect/db/mysql/MySqlGeneratorsTest.java | 13 +- .../container/MySqlDescendingIndexTest.java | 126 +++++++++++++ .../db/mysql/container/MySqlListAggTest.java | 132 ++++++++++++++ .../container/MySqlMergeGeneratorTest.java | 120 +++++++++++++ .../container/MySqlOrderByAliasTest.java | 94 ++++++++++ .../mysql/container/MySqlPercentileTest.java | 86 +++++++++ .../container/MySqlRecursiveCteTest.java | 106 +++++++++++ .../container/MySqlRegularExpressionTest.java | 104 +++++++++++ .../container/MySqlRenameColumnTest.java | 142 +++++++++++++++ .../mysql/container/MySqlRenameIndexTest.java | 108 +++++++++++ .../db/mysql/container/MySqlRolesTest.java | 114 ++++++++++++ .../MySqlTriggerStatementScopeTest.java | 106 +++++++++++ .../mysql/container/MySqlTriggerWhenTest.java | 110 ++++++++++++ .../container/MySqlUpsertValuesTest.java | 128 +++++++++++++ .../db/mysql/container/MySqlUsersTest.java | 105 +++++++++++ .../src/test/resources/mysql-conf/my.cnf | 16 ++ 23 files changed, 1972 insertions(+), 20 deletions(-) create mode 100644 dialect/db/common/src/test/java/org/eclipse/daanse/sql/dialect/db/common/DialectInitDataVersionTest.java create mode 100644 dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBPercentileTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlDescendingIndexTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlListAggTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlMergeGeneratorTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlOrderByAliasTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlPercentileTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRecursiveCteTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRegularExpressionTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameColumnTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameIndexTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRolesTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerStatementScopeTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerWhenTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUpsertValuesTest.java create mode 100644 dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUsersTest.java create mode 100644 dialect/db/mysql/src/test/resources/mysql-conf/my.cnf diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectInitData.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectInitData.java index 1ac24ccd..771e3322 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectInitData.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectInitData.java @@ -156,10 +156,12 @@ private static String nullToEmpty(String s) { /** * {@link DialectVersion} view of {@link #databaseMajorVersion} / - * {@link #databaseMinorVersion}. + * {@link #databaseMinorVersion}, with the patch of {@link #productVersion} where that names the same major and + * minor: a check of a patch ({@code 5.7.8}, {@code 8.0.19}) took every version of its minor for its {@code .0} + * before. */ public DialectVersion version() { - return new DialectVersion(databaseMajorVersion, databaseMinorVersion); + return DialectVersion.of(databaseMajorVersion, databaseMinorVersion, productVersion); } /** Returns a copy with a different {@link IdentifierQuotingPolicy}. */ diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectVersion.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectVersion.java index a4486920..979d7d06 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectVersion.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/DialectVersion.java @@ -75,6 +75,19 @@ public int compareTo(DialectVersion o) { return ORDER.compare(this, o); } + /** + * The version of a major and a minor, with the patch of {@code productVersion} where that is a version of the + * same major and minor ({@code 8.0.44} of 8.0: 8.0.44); else the patch is 0, as of a product version that names + * another version ({@code 5.5.5-10.11.6-MariaDB} of 10.11). No major and no minor is {@link #UNKNOWN}. + */ + static DialectVersion of(int major, int minor, String productVersion) { + if (major <= 0 && minor <= 0) { + return UNKNOWN; + } + boolean same = productVersion != null && productVersion.startsWith(major + "." + minor + "."); + return new DialectVersion(major, minor, same ? parsePatch(productVersion) : 0); + } + private static int parsePatch(String productVersion) { if (productVersion == null) { return 0; diff --git a/dialect/db/common/src/test/java/org/eclipse/daanse/sql/dialect/db/common/DialectInitDataVersionTest.java b/dialect/db/common/src/test/java/org/eclipse/daanse/sql/dialect/db/common/DialectInitDataVersionTest.java new file mode 100644 index 00000000..66b86f09 --- /dev/null +++ b/dialect/db/common/src/test/java/org/eclipse/daanse/sql/dialect/db/common/DialectInitDataVersionTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.common; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Set; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.DialectVersion; +import org.eclipse.daanse.sql.dialect.api.IdentifierQuotingPolicy; +import org.junit.jupiter.api.Test; + +/** + * The version a dialect checks carries the patch of the product version, where that names the same major and minor: + * a check of a patch ({@code 5.7.8}, {@code 8.0.19}) took every version of its minor for its {@code .0} before. + */ +class DialectInitDataVersionTest { + + private static DialectInitData init(String productVersion, int major, int minor) { + return new DialectInitData("`", "MySQL", productVersion, major, minor, Set.of(), true, 0, Set.of(), + IdentifierQuotingPolicy.ALWAYS); + } + + @Test + void the_patch_of_the_product_version() { + assertThat(init("8.0.44", 8, 0).version()).isEqualTo(new DialectVersion(8, 0, 44)); + assertThat(init("5.7.44-log", 5, 7).version()).isEqualTo(new DialectVersion(5, 7, 44)); + assertThat(init("11.4.2-MariaDB-ubu2404", 11, 4).version()).isEqualTo(new DialectVersion(11, 4, 2)); + assertThat(init("16.4 (Debian 16.4-1.pgdg120+2)", 16, 4).version()).isEqualTo(new DialectVersion(16, 4, 0)); + } + + @Test + void a_check_of_a_patch() { + DialectVersion v8018 = init("8.0.18", 8, 0).version(); + DialectVersion v8019 = init("8.0.19", 8, 0).version(); + assertThat(v8018.atLeast(new DialectVersion(8, 0, 19))).isFalse(); + assertThat(v8019.atLeast(new DialectVersion(8, 0, 19))).isTrue(); + assertThat(init("5.7.7", 5, 7).version().atLeast(new DialectVersion(5, 7, 8))).isFalse(); + assertThat(init("5.7.44", 5, 7).version().atLeast(new DialectVersion(5, 7, 8))).isTrue(); + assertThat(v8019.atLeast(8, 0)).as("a check of a minor as before").isTrue(); + } + + @Test + void no_patch_of_a_product_version_that_names_another_version() { + assertThat(init("5.5.5-10.11.6-MariaDB", 10, 11).version()).isEqualTo(new DialectVersion(10, 11, 0)); + assertThat(init("8.0.44", 8, 0).withVersion(5, 7).version()).as("withVersion names another version") + .isEqualTo(new DialectVersion(5, 7, 0)); + } + + @Test + void no_version_is_unknown() { + assertThat(DialectInitData.ansiDefaults().version()).isEqualTo(DialectVersion.UNKNOWN); + assertThat(init("8.0.44", 0, 0).version()).isEqualTo(DialectVersion.UNKNOWN); + } +} diff --git a/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java b/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java index a93d586a..c875e8fa 100644 --- a/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java +++ b/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java @@ -104,6 +104,16 @@ protected boolean supportsNativeRenameColumn() { return dialectVersion.isUnknownOrAtLeast(10, 5); } + /** + * MariaDB's {@code RENAME INDEX} landed in 10.5.2, with {@code RENAME COLUMN}: not MySQL's 5.7, which every + * MariaDB 10 and 11 would pass. A dialect made without a connection takes such a version. + */ + @Override + public boolean supportsRenameIndex() { + return org.eclipse.daanse.sql.dialect.api.DialectVersion.UNKNOWN.equals(dialectVersion) + || dialectVersion.atLeast(new org.eclipse.daanse.sql.dialect.api.DialectVersion(10, 5, 2)); + } + @Override public boolean supportsRenameSequence() { return dialectVersion.isUnknownOrAtLeast(10, 5); @@ -196,4 +206,13 @@ public boolean supportsDescendingIndexColumns() { protected boolean createOrReplaceRoutine() { return true; } + + /** + * MariaDB has no alias of the row an upsert would insert: its update columns read it with + * {@code VALUES(col)}, on every version. + */ + @Override + protected boolean upsertRowAlias() { + return false; + } } diff --git a/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBVersionCapabilitiesTest.java b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBVersionCapabilitiesTest.java index 6841ef68..84dca7ef 100644 --- a/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBVersionCapabilitiesTest.java +++ b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBVersionCapabilitiesTest.java @@ -33,11 +33,16 @@ void twoDigitMajorIsAtLeast57ForOrderByAlias() { assertTrue(dialect(10, 6).requiresOrderByAlias()); } + /** + * MariaDB has the percentiles as window functions only, with an OVER clause; as an aggregate of a group, as the + * dialect writes them, it refuses them on every version (MariaDBPercentileTest runs them against the server). + */ @Test - void twoDigitMajorSupportsPercentiles() { - assertTrue(dialect(11, 4).supportsPercentileDisc()); - assertTrue(dialect(11, 4).supportsPercentileCont()); - assertTrue(dialect(10, 6).supportsPercentileDisc()); + void noPercentilesOfAGroupOnAnyVersion() { + assertFalse(dialect(11, 4).supportsPercentileDisc()); + assertFalse(dialect(11, 4).supportsPercentileCont()); + assertFalse(dialect(10, 6).supportsPercentileDisc()); + assertTrue(dialect(11, 4).generatePercentileCont(0.5, false, "t", "v").isEmpty()); } @Test @@ -49,7 +54,5 @@ void twoDigitMajorAllowsFromQuery() { void oldMySqlStyleVersionsStillGateCorrectly() { assertFalse(dialect(5, 6).requiresOrderByAlias()); assertTrue(dialect(5, 7).requiresOrderByAlias()); - assertFalse(dialect(5, 7).supportsPercentileDisc()); - assertTrue(dialect(8, 0).supportsPercentileDisc()); } } diff --git a/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBPercentileTest.java b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBPercentileTest.java new file mode 100644 index 00000000..29cfed26 --- /dev/null +++ b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/container/MariaDBPercentileTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mariadb.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mariadb.MariaDBDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MariaDBContainer; + +/** + * MariaDB has {@code PERCENTILE_DISC} and {@code PERCENTILE_CONT … WITHIN GROUP} as window functions, with an + * {@code OVER} clause, from 10.3.3. The dialect writes a percentile as an aggregate of a group, without one, and is + * built from a live connection: where it offers a percentile, the server must compute it as such an aggregate, per + * group too; where the server takes it as a window function only, as every version here does, the dialect must offer + * none and write none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MariaDBPercentileTest { + + /** Group a: 10, 20, 30, 40 and a NULL that every aggregate leaves out; group b: 5. */ + private static final List SETUP = List.of("CREATE TABLE nums(grp VARCHAR(1), v INT)", + "INSERT INTO nums VALUES ('a', 30), ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5)"); + + @ParameterizedTest(name = "mariadb:{0} -> percentiles {1}") + @CsvSource({ "10.4, false", "10.6, false", "10.11, false", "11.4, false" }) + void percentile(String tag, boolean expected) throws Exception { + try (MariaDBContainer db = new MariaDBContainer<>("mariadb:" + tag).withDatabaseName("rt") + .withUsername("rt").withPassword("rt")) { + db.start(); + try (Connection c = db.createConnection(""); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MariaDBDialect dialect = new MariaDBDialect(DialectInitData.fromConnection(c)); + + assertThat(rows(st, "SELECT DISTINCT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY v)" + + " OVER (PARTITION BY grp) FROM nums WHERE grp = 'a'")) + .as("MariaDB has the percentile as a window function").containsExactly("25"); + + assertThat(dialect.supportsPercentileDisc()).as("supportsPercentileDisc").isEqualTo(expected); + assertThat(dialect.supportsPercentileCont()).as("supportsPercentileCont").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.generatePercentileDisc(0.5, false, "nums", "v")).isEmpty(); + assertThat(dialect.generatePercentileCont(0.5, false, "nums", "v")).isEmpty(); + assertThatThrownBy(() -> rows(st, + "SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY v) FROM nums WHERE grp = 'a'")) + .as("not as an aggregate of a group").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> rows(st, + "SELECT PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY v) FROM nums WHERE grp = 'a'")) + .as("not as an aggregate of a group").isInstanceOf(SQLException.class); + return; + } + + String disc = dialect.generatePercentileDisc(0.5, false, "nums", "v").orElseThrow(); + String cont = dialect.generatePercentileCont(0.5, false, "nums", "v").orElseThrow(); + assertThat(rows(st, "SELECT " + disc + " FROM nums WHERE grp = 'a'")).containsExactly("20"); + assertThat(rows(st, "SELECT " + cont + " FROM nums WHERE grp = 'a'")).containsExactly("25"); + assertThat(rows(st, "SELECT CONCAT(grp, '=', " + cont + ") FROM nums GROUP BY grp ORDER BY grp")) + .as("per group").containsExactly("a=25", "b=5"); + } + } + } + + /** The first column of each row; a number without the zeros of its fraction. */ + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(Optional.ofNullable(rs.getString(1)) + .map(s -> s.contains(".") ? s.replaceAll("0+$", "").replaceAll("\\.$", "") : s).orElse(null)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java b/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java index 05d535c7..daba89cd 100644 --- a/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java +++ b/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java @@ -47,6 +47,7 @@ import org.eclipse.daanse.sql.dialect.api.generator.StatementHint; import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PagingParam; import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PreparedPaging; +import org.eclipse.daanse.sql.model.sql.NullsOrder; import org.eclipse.daanse.sql.model.sql.OrderedColumn; import org.eclipse.daanse.sql.dialect.db.common.AbstractJdbcDialect; import org.eclipse.daanse.sql.dialect.db.common.DialectUtil; @@ -179,9 +180,24 @@ public PreparedPaging paginatePrepared(boolean withLimit, boolean withOffset) { return local; } + /** The alias of the row an upsert would insert, which its update columns read. */ + private static final String UPSERT_ROW_ALIAS = "new_row"; + + /** + * Whether an upsert reads the row it would insert by an alias, {@code INSERT … VALUES (…) AS new_row ON DUPLICATE + * KEY UPDATE col = new_row.col}: from MySQL 8.0.19. 8.0.20 deprecates the {@code VALUES(col)} of before, with + * warning 1287. Overridden by {@code MariaDBDialect}, which has no such alias. A dialect made without a connection + * takes such a version. + */ + protected boolean upsertRowAlias() { + return org.eclipse.daanse.sql.dialect.api.DialectVersion.UNKNOWN.equals(dialectVersion) + || dialectVersion.atLeast(new org.eclipse.daanse.sql.dialect.api.DialectVersion(8, 0, 19)); + } + /** - * MySQL/MariaDB: - * {@code INSERT ... ON DUPLICATE KEY UPDATE col = VALUES(col), ...}. + * MySQL/MariaDB: {@code INSERT … ON DUPLICATE KEY UPDATE col = new_row.col, …} where + * {@link #upsertRowAlias()} says so, else {@code col = VALUES(col)}; without update columns + * {@code ON DUPLICATE KEY UPDATE key = key}, which leaves the row of a key that is there. */ @Override public org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator mergeGenerator() { @@ -208,13 +224,30 @@ public java.util.Optional upsert(UpsertSpec spec, java.util.List sb.append(values.get(i)); } sb.append(")"); - if (!spec.updateColumns().isEmpty()) { + if (spec.updateColumns().isEmpty()) { + // insert-or-ignore: a key that is there sets itself, and the row is left. Not INSERT IGNORE, + // which takes a NULL in a NOT NULL column, a value too long or a missing foreign key as a + // warning too, and writes a row the statement did not ask for + String key = quoteIdentifier(spec.keyColumns().get(0)).toString(); + sb.append(" ON DUPLICATE KEY UPDATE ").append(key).append(" = ").append(key); + } else { + boolean alias = upsertRowAlias(); + String row = quoteIdentifier(UPSERT_ROW_ALIAS).toString(); + if (alias) { + sb.append(" AS ").append(row); + } sb.append(" ON DUPLICATE KEY UPDATE "); boolean first = true; for (String c : spec.updateColumns()) { if (!first) sb.append(", "); - sb.append(quoteIdentifier(c)).append(" = VALUES(").append(quoteIdentifier(c)).append(")"); + String col = quoteIdentifier(c).toString(); + sb.append(col).append(" = "); + if (alias) { + sb.append(row).append('.').append(col); + } else { + sb.append("VALUES(").append(col).append(")"); + } first = false; } } @@ -410,13 +443,25 @@ private enum Scope { SESSION, GLOBAL } + /** + * From MySQL 8.0, whose REGEXP is ICU's (from 8.0.4, the first 8.0 released being 8.0.11) and reads the + * {@code (?-i)}, {@code \A}, {@code \z} and {@code (?:…)} the condition is written with. Before, REGEXP is Henry + * Spencer's, which refuses them ("repetition-operator operand invalid") and has no {@code \d}, {@code \w} or + * {@code \s} of a Java expression either: the expression is then matched in Java, not in SQL. MariaDB's PCRE + * reads them, and every MariaDB 10 and 11 passes the version. A dialect made without a connection takes such a + * version. + */ @Override public boolean allowsRegularExpressionInWhereClause() { - return true; + return dialectVersion.isUnknownOrAtLeast(8, 0); } + /** Empty where {@link #allowsRegularExpressionInWhereClause()} says no, and of an expression Java cannot read. */ @Override public Optional generateRegularExpression(String source, String javaRegex) { + if (!allowsRegularExpressionInWhereClause()) { + return Optional.empty(); + } try { Pattern.compile(javaRegex); } catch (PatternSyntaxException e) { @@ -567,30 +612,79 @@ public boolean supportsBitAggregation(BitOperation operation) { return true; // MySQL supports all bit operations } + /** {@code PERCENTILE_DISC(p) WITHIN GROUP (ORDER BY c)} where {@link #supportsPercentileDisc()} says so. */ @Override public java.util.Optional generatePercentileDisc(double percentile, boolean desc, String tableName, String columnName) { + if (!supportsPercentileDisc()) { + return java.util.Optional.empty(); + } return java.util.Optional .of((buildPercentileFunction("PERCENTILE_DISC", percentile, desc, tableName, columnName)).toString()); } + /** {@code PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY c)} where {@link #supportsPercentileCont()} says so. */ @Override public java.util.Optional generatePercentileCont(double percentile, boolean desc, String tableName, String columnName) { + if (!supportsPercentileCont()) { + return java.util.Optional.empty(); + } return java.util.Optional .of((buildPercentileFunction("PERCENTILE_CONT", percentile, desc, tableName, columnName)).toString()); } + /** + * MySQL has no {@code PERCENTILE_DISC}, as an aggregate or otherwise: 8.4 refuses + * {@code WITHIN GROUP (ORDER BY …)} with a syntax error, on 8.0 and 9 too. MariaDB has them as window functions + * only, with an OVER clause, and refuses them as an aggregate of a group the same way. + */ @Override public boolean supportsPercentileDisc() { - // Numeric compare — see requiresOrderByAlias (MariaDB "10.x"/"11.x" vs "8.0"). - return dialectVersion.isUnknownOrAtLeast(8, 0); + return false; } + /** As {@link #supportsPercentileDisc()}: MySQL has no {@code PERCENTILE_CONT}. */ @Override public boolean supportsPercentileCont() { - // Numeric compare — see requiresOrderByAlias (MariaDB "10.x"/"11.x" vs "8.0"). - return dialectVersion.isUnknownOrAtLeast(8, 0); + return false; + } + + /** + * {@code GROUP_CONCAT(DISTINCT operand ORDER BY … SEPARATOR 's')}, the separator a string literal of its own, a + * quote and a backslash in it escaped. The list is cut at the session's {@code group_concat_max_len}, 1024 bytes + * unless the connection sets more ({@code SET SESSION group_concat_max_len = …}), with only warning 1260 to say + * so: no expression of the list can lift it. + */ + /** + * The columns of an order, a column's NULLs first or last as asked: MySQL and MariaDB have no + * {@code NULLS FIRST | LAST} and refuse it with a syntax error, so the order of {@code col IS NULL} comes first, + * {@code col IS NULL DESC, col} for NULLS FIRST and {@code col IS NULL ASC, col} for NULLS LAST. + */ + @Override + public CharSequence buildOrderedColumnsClause(List columns) { + StringBuilder buf = new StringBuilder(64); + if (columns == null) { + return buf; + } + boolean first = true; + for (OrderedColumn c : columns) { + if (!first) { + buf.append(", "); + } + StringBuilder name = new StringBuilder(); + if (c.tableName() != null) { + quoteIdentifier(name, c.tableName(), c.columnName()); + } else { + quoteIdentifier(name, c.columnName()); + } + c.nullsOrder().ifPresent(no -> buf.append(name).append(" IS NULL") + .append(no == NullsOrder.FIRST ? " DESC" : " ASC").append(", ")); + buf.append(name); + c.sortDirection().ifPresent(dir -> buf.append(' ').append(dir.name())); + first = false; + } + return buf; } @Override @@ -608,7 +702,8 @@ public java.util.Optional generateListAgg(CharSequence operand, boolean buf.append(buildOrderedColumnsClause(columns)); } if (separator != null) { - buf.append(" SEPARATOR '").append(separator).append("'"); + buf.append(" SEPARATOR "); + quoteStringLiteral(buf, separator); } buf.append(")"); // GROUP_CONCAT(DISTINCT cate_id ORDER BY cate_id ASC SEPARATOR ' ') @@ -635,6 +730,38 @@ public boolean supportsListAgg() { return true; } + // -------------------- Triggers -------------------- + + /** + * MySQL and MariaDB have no WHEN in {@code CREATE TRIGGER}: a trigger with a condition fires for every row and + * runs its body where the condition holds, {@code FOR EACH ROW BEGIN IF (condition) THEN body; END IF; END}. The + * body is one statement, a {@code BEGIN … END} block or a {@code CALL}, a closing semicolon left out; JDBC sends the + * compound statement as one, without a client's delimiter. + * + *

+ * MySQL and MariaDB have row triggers only: {@code FOR EACH STATEMENT} is a syntax error, and a row trigger does + * not fire once for a statement (not at all for one of no rows), so none is written. + * + * @throws UnsupportedOperationException of {@link Trigger.TriggerScope#STATEMENT} + */ + @Override + public String createTrigger(String triggerName, Trigger.TriggerTiming timing, Trigger.TriggerEvent event, + TableReference table, Trigger.TriggerScope scope, String whenCondition, String body, boolean orReplace) { + if (scope == Trigger.TriggerScope.STATEMENT) { + throw new UnsupportedOperationException("MySQL and MariaDB have row triggers only: FOR EACH STATEMENT of " + + triggerName + " cannot be written"); + } + if (whenCondition == null || whenCondition.isBlank() || body == null || body.isBlank()) { + return super.createTrigger(triggerName, timing, event, table, scope, whenCondition, body, orReplace); + } + String statement = body.strip(); + while (statement.endsWith(";")) { + statement = statement.substring(0, statement.length() - 1).stripTrailing(); + } + String guarded = "BEGIN IF (" + whenCondition + ") THEN " + statement + "; END IF; END"; + return super.createTrigger(triggerName, timing, event, table, scope, null, guarded, orReplace); + } + // -------------------- Trigger procedures -------------------- @Override @@ -779,7 +906,11 @@ public String renameColumn(TableReference table, String oldName, String newName) /** * MySQL 8.0+: delegates to the metadata-free form. Before 8.0: * {@code ALTER TABLE t CHANGE old new } — needs - * {@code currentMeta} to restate the column's full definition. + * {@code currentMeta} to restate the column's full definition. CHANGE replaces the whole column, so the + * definition carries what the metadata knows of it: type, NOT NULL, DEFAULT, AUTO_INCREMENT and COMMENT. A + * generated column is not renamed (null): the metadata has no expression to generate it by, and CHANGE would + * make it a plain one. What the metadata does not carry, UNSIGNED, a character set or collation of the column's + * own, ON UPDATE, is lost; RENAME COLUMN keeps it. */ @Override public String renameColumn(TableReference table, String oldName, String newName, ColumnMetaData currentMeta) { @@ -792,6 +923,9 @@ public String renameColumn(TableReference table, String oldName, String newName, if (currentMeta == null) { throw new IllegalArgumentException("currentMeta must not be null for the CHANGE-based rename fallback"); } + if (currentMeta.generatedColumn() == ColumnMetaData.GeneratedColumn.YES) { + return null; + } StringBuilder sb = new StringBuilder("ALTER TABLE ").append(qualified(table)).append(" CHANGE ") .append(quoteIdentifier(oldName)).append(' ').append(quoteIdentifier(newName)).append(' ') .append(nativeType(currentMeta)); @@ -799,9 +933,23 @@ public String renameColumn(TableReference table, String oldName, String newName, sb.append(" NOT NULL"); } currentMeta.columnDefault().ifPresent(d -> sb.append(" DEFAULT ").append(d)); + if (currentMeta.autoIncrement() == ColumnMetaData.AutoIncrement.YES) { + sb.append(" AUTO_INCREMENT"); + } + currentMeta.remarks().filter(r -> !r.isEmpty()).ifPresent(r -> sb.append(" COMMENT ").append(mysqlLiteral(r))); return sb.toString(); } + /** + * MySQL renames an index from 5.7; 5.6 refuses {@code RENAME INDEX} with a syntax error, and an index is + * not renamed there ({@link #renameIndex} gives null). Overridden by {@code MariaDBDialect}, whose 10.x + * numbering would always pass 5.7. A dialect made without a connection takes such a version. + */ + @Override + public boolean supportsRenameIndex() { + return dialectVersion.isUnknownOrAtLeast(5, 7); + } + /** * MySQL: {@code ALTER TABLE x RENAME INDEX old TO new} — index names are * table-scoped. diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsTest.java index a0ab1802..c8fd14d5 100644 --- a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsTest.java +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsTest.java @@ -95,12 +95,23 @@ void pagination_offset_only_uses_huge_limit_trick() { .isEqualTo(" LIMIT 40, 18446744073709551615"); } + /** A dialect without a version takes a current MySQL, and reads the row by its alias, as 8.0.19 does. */ @Test void upsert_on_duplicate_key_update() { MergeGenerator.UpsertSpec spec = upsertSpec(table("test", "USERS"), "ID", "NAME"); String sql = d.mergeGenerator().upsert(spec, List.of("1", "'foo'")).orElseThrow(); assertThat(sql).contains("INSERT INTO `test`.`USERS`") - .contains("ON DUPLICATE KEY UPDATE `NAME` = VALUES(`NAME`)"); + .contains("VALUES (1, 'foo') AS `new_row` ON DUPLICATE KEY UPDATE `NAME` = `new_row`.`NAME`"); + } + + /** Before 8.0.19 the row is read with VALUES(col). */ + @Test + void upsert_on_duplicate_key_update_before_8_0_19() { + MySqlDialect d57 = new MySqlDialect(org.eclipse.daanse.sql.dialect.api.DialectInitData.ansiDefaults() + .withQuoteIdentifierString("`").withVersion(5, 7)); + MergeGenerator.UpsertSpec spec = upsertSpec(table("test", "USERS"), "ID", "NAME"); + String sql = d57.mergeGenerator().upsert(spec, List.of("1", "'foo'")).orElseThrow(); + assertThat(sql).contains("ON DUPLICATE KEY UPDATE `NAME` = VALUES(`NAME`)").doesNotContain("new_row"); } @Test diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlDescendingIndexTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlDescendingIndexTest.java new file mode 100644 index 00000000..2ea33141 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlDescendingIndexTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexColumn; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexDefinition; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL keeps a descending column of an index from 8.0; 5.7 takes {@code DESC} and builds the column ascending. The + * dialect is built from a live connection: from 8.0 on the index it writes keeps each column's order, and an order by + * the same directions reads the index without a sort; on 5.7 it writes no index with a descending column, for the + * server would keep it ascending without a word; an ascending index it writes on every version. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlDescendingIndexTest { + + private static final TableReference USERS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "users", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of("CREATE TABLE users(id INT PRIMARY KEY, name VARCHAR(20))", + "INSERT INTO users VALUES (1, 'a'), (2, 'b'), (3, 'b'), (4, 'c')"); + + /** name descending, then id ascending. */ + private static final IndexDefinition MIXED = new IndexDefinition("ix_name_desc", USERS, + List.of(IndexColumn.descending("name"), IndexColumn.ascending("id")), false, null); + private static final IndexDefinition ASCENDING = new IndexDefinition("ix_name_asc", USERS, + List.of(IndexColumn.ascending("name")), false, null); + + /** + * The order of each column of an index, A or D, as SHOW INDEX gives it: information_schema.STATISTICS has no + * COLLATION on 5.7, NULL for every column. + */ + private static List order(Statement st, String index) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery("SHOW INDEX FROM users WHERE Key_name = '" + index + "'")) { + while (rs.next()) { + out.add(rs.getString("Column_name") + ":" + rs.getString("Collation")); + } + } + return out; + } + + @ParameterizedTest(name = "mysql:{0} -> descending {1}") + @CsvSource({ "5.7, false", "8.0, true", "8.4, true", "9, true" }) + void descending_index(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsDescendingIndexColumns()).as("supportsDescendingIndexColumns") + .isEqualTo(expected); + + st.execute(dialect.createIndex(ASCENDING, false).orElseThrow()); + assertThat(order(st, "ix_name_asc")).as("an ascending index").containsExactly("name:A"); + + if (!expected) { + assertThat(dialect.createIndex(MIXED, false)).as("no descending column on 5.7").isEmpty(); + st.execute("CREATE INDEX ix_hand ON users (name DESC, id)"); + assertThat(order(st, "ix_hand")).as("5.7 takes DESC and keeps the column ascending") + .containsExactly("name:A", "id:A"); + return; + } + + String sql = dialect.createIndex(MIXED, false).orElseThrow(); + assertThat(sql).contains("DESC"); + st.execute(sql); + assertThat(order(st, "ix_name_desc")).as("each column's order kept") + .containsExactly("name:D", "id:A"); + + // EXPLAIN of 9 is a tree unless asked for the table, which has Extra + String byIndex = "SELECT name, id FROM users FORCE INDEX (ix_name_desc) ORDER BY name DESC, id ASC"; + assertThat(String.join(" ", rows(st, "EXPLAIN FORMAT=TRADITIONAL " + byIndex, "Extra"))).as("read in the index's order") + .doesNotContain("filesort"); + assertThat(rows(st, byIndex.replace("SELECT name, id", "SELECT CONCAT(name, id)"))) + .containsExactly("c4", "b2", "b3", "a1"); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + return rows(st, sql, null); + } + + private static List rows(Statement st, String sql, String column) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(column == null ? rs.getString(1) : rs.getString(column)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlListAggTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlListAggTest.java new file mode 100644 index 00000000..f9ac2625 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlListAggTest.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.sql.NullsOrder; +import org.eclipse.daanse.sql.model.sql.OrderedColumn; +import org.eclipse.daanse.sql.model.sql.SortDirection; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL lists the values of a group with {@code GROUP_CONCAT(DISTINCT x ORDER BY … SEPARATOR 's')}. The dialect is + * built from a live connection, and the list it writes must come out of the server in the order asked for, the NULLs + * of an order column first or last as asked, without the NULL values, DISTINCT kept, with any separator, of a column + * of any type and per group. A list longer than the session's group_concat_max_len, 1024 bytes unless the connection + * sets more, is cut with warning 1260: no expression of the list lifts it, so no list here is that long. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlListAggTest { + + /** Group a: alice 20, bob 30, bob 10, a NULL name of 40; group b: dave 5. */ + private static final List SETUP = List.of( + "CREATE TABLE emp(dept VARCHAR(1), name VARCHAR(10), salary INT)", + "INSERT INTO emp VALUES ('a', 'bob', 30), ('a', NULL, 40), ('a', 'alice', 20), ('a', 'bob', 10)," + + " ('b', 'dave', 5)"); + + @ParameterizedTest(name = "mysql:{0}") + @ValueSource(strings = { "5.7", "8.0", "8.4", "9" }) + void list_agg(String tag) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsListAgg()).isTrue(); + + assertThat(list(st, dialect, "name", false, ", ", order("name", SortDirection.ASC))) + .as("ordered by the value, the NULL left out").isEqualTo("alice, bob, bob"); + assertThat(list(st, dialect, "name", false, ", ", order("salary", SortDirection.DESC))) + .as("ordered by another column").isEqualTo("bob, alice, bob"); + assertThat(list(st, dialect, "name", false, ", ", + List.of(new OrderedColumn("name", "emp", SortDirection.ASC)))) + .as("a column of the table").isEqualTo("alice, bob, bob"); + + assertThat(sorted(list(st, dialect, "name", true, ",", List.of()))) + .as("DISTINCT without an order").containsExactly("alice", "bob"); + assertThat(list(st, dialect, "name", true, ",", order("name", SortDirection.ASC))) + .as("DISTINCT with an order: MySQL keeps both").isEqualTo("alice,bob"); + + assertThat(list(st, dialect, "name", false, null, order("name", SortDirection.ASC))) + .as("no separator is a comma").isEqualTo("alice,bob,bob"); + assertThat(list(st, dialect, "name", false, "'", order("name", SortDirection.ASC))) + .as("a quote as separator").isEqualTo("alice'bob'bob"); + assertThat(list(st, dialect, "name", false, "\\", order("name", SortDirection.ASC))) + .as("a backslash as separator").isEqualTo("alice\\bob\\bob"); + + assertThat(list(st, dialect, "salary", false, ",", order("salary", SortDirection.ASC))) + .as("an INT column").isEqualTo("10,20,30,40"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("NULLS FIRST, then a second column").isEqualTo("40,20,10,30"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.LAST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("NULLS LAST, then a second column").isEqualTo("20,10,30,40"); + + String perDept = dialect.generateListAgg("name", false, ",", null, null, + order("name", SortDirection.ASC)).orElseThrow(); + assertThat(rows(st, "SELECT dept, " + perDept + " FROM emp GROUP BY dept ORDER BY dept")) + .as("per group").containsExactly("a=alice,bob,bob", "b=dave"); + } + } + } + + private static List order(String column, SortDirection direction) { + return List.of(new OrderedColumn(column, null, direction)); + } + + private static String list(Statement st, MySqlDialect dialect, String operand, boolean distinct, String separator, + List columns) throws SQLException { + String agg = dialect.generateListAgg(operand, distinct, separator, null, null, columns).orElseThrow(); + try (ResultSet rs = st.executeQuery("SELECT " + agg + " FROM emp WHERE dept = 'a'")) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + agg, e); + } + } + + private static List sorted(String list) { + return Arrays.stream(list.split(",")).sorted().toList(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getString(2)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlMergeGeneratorTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlMergeGeneratorTest.java new file mode 100644 index 00000000..5e3ebb43 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlMergeGeneratorTest.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator.UpsertSpec; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * An upsert inserts a row of a new key and, of a key that is there, updates the update columns; without update columns + * it leaves that row as it is, insert-or-ignore, as {@link UpsertSpec} says. The dialect is built from a live + * connection, and its upsert must do so on the server: of a single key and of a composite one, without an error on the + * key that is there. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlMergeGeneratorTest { + + private static final SchemaReference RT = new SchemaReference(Optional.empty(), "rt"); + private static final TableReference PRODUCTS = new TableReference(Optional.of(RT), "products", + TableReference.TYPE_TABLE); + private static final TableReference STOCK = new TableReference(Optional.of(RT), "stock", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of( + "CREATE TABLE products(id INT PRIMARY KEY, name VARCHAR(20), price INT)", + "CREATE TABLE stock(store VARCHAR(10), product INT, qty INT, PRIMARY KEY (store, product))", + "INSERT INTO products VALUES (1, 'apple', 10)", "INSERT INTO stock VALUES ('north', 1, 5)"); + + private static final UpsertSpec UPDATE_PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"), + List.of("id", "name", "price"), List.of("name", "price")); + private static final UpsertSpec IGNORE_PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"), + List.of("id", "name", "price"), List.of()); + private static final UpsertSpec IGNORE_STOCK = new UpsertSpec(STOCK, List.of("store", "product"), + List.of("store", "product", "qty"), List.of()); + + @ParameterizedTest(name = "mysql:{0}") + @ValueSource(strings = { "5.7", "8.0", "8.4", "9" }) + void upsert(String tag) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MergeGenerator merge = new MySqlDialect(DialectInitData.fromConnection(c)).mergeGenerator(); + assertThat(merge.supportsMerge()).isTrue(); + + st.execute(sql(merge, UPDATE_PRODUCT, "2", "'banana'", "7")); + st.execute(sql(merge, UPDATE_PRODUCT, "1", "'apple'", "12")); + assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id")) + .as("with update columns: a new key inserted, the one there updated") + .containsExactly("1|apple|12", "2|banana|7"); + + String ignoreThere = sql(merge, IGNORE_PRODUCT, "1", "'cherry'", "99"); + st.execute(ignoreThere); + assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id")) + .as("without update columns the row of a key that is there is left: " + ignoreThere) + .containsExactly("1|apple|12", "2|banana|7"); + + st.execute(sql(merge, IGNORE_PRODUCT, "3", "'cherry'", "99")); + assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id")) + .as("without update columns a new key is inserted") + .containsExactly("1|apple|12", "2|banana|7", "3|cherry|99"); + + st.execute(sql(merge, IGNORE_STOCK, "'north'", "1", "8")); + st.execute(sql(merge, IGNORE_STOCK, "'south'", "1", "3")); + assertThat(rows(st, "SELECT store, product, qty FROM stock ORDER BY store")) + .as("a composite key, without update columns").containsExactly("north|1|5", "south|1|3"); + } + } + } + + private static String sql(MergeGenerator merge, UpsertSpec spec, String... values) { + return merge.upsert(spec, List.of(values)).orElseThrow(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + int n = rs.getMetaData().getColumnCount(); + while (rs.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= n; i++) { + if (i > 1) + row.append('|'); + row.append(rs.getString(i)); + } + out.add(row.toString()); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlOrderByAliasTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlOrderByAliasTest.java new file mode 100644 index 00000000..61b16472 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlOrderByAliasTest.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * From MySQL 5.7, whose default sql_mode has ONLY_FULL_GROUP_BY, a {@code SELECT DISTINCT} may be ordered only by what + * it selects: an order by a column it does not select fails with error 3065. The dialect is built from a live + * connection, and where it says an order must use the aliases of the select list, an order by such a column must fail + * and the order by the alias must not; where it does not, both must run. The order by an alias, its NULLs first or + * last as the dialect writes them, runs on every version. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlOrderByAliasTest { + + private static final List SETUP = List.of("CREATE TABLE t(name VARCHAR(10), grp VARCHAR(1))", + "INSERT INTO t VALUES ('b', 'x'), (NULL, 'x'), ('a', 'y'), ('b', 'y')"); + + /** Ordered by a column the DISTINCT does not select. */ + private static final String BY_EXPRESSION = "SELECT DISTINCT UPPER(t.name) AS c0 FROM t ORDER BY t.name"; + + /** The same order, by the alias of a column the DISTINCT selects. */ + private static final String BY_ALIAS = "SELECT DISTINCT UPPER(t.name) AS c0, t.name AS c1 FROM t ORDER BY c1"; + + @ParameterizedTest(name = "mysql:{0} -> requires the alias {1}") + @CsvSource({ "5.6, false", "5.7, true", "8.0, true", "8.4, true", "9, true" }) + void order_by_alias(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.requiresOrderByAlias()).as("requiresOrderByAlias").isEqualTo(expected); + if (expected) { + assertThat(dialect.allowsOrderByAlias()).as("an alias is allowed where it is required").isTrue(); + assertThatThrownBy(() -> rows(st, BY_EXPRESSION)) + .as("an order by a column the DISTINCT does not select").isInstanceOf(SQLException.class) + .hasMessageContaining("not in SELECT list"); + } else { + assertThat(rows(st, BY_EXPRESSION)).as("5.6 orders by any column").containsExactly(null, "A", + "B"); + } + assertThat(rows(st, BY_ALIAS)).as("the order by the alias").containsExactly(null, "A", "B"); + + String nullsLast = dialect.generateOrderByNulls("c1", true, true).toString(); + assertThat(rows(st, "SELECT DISTINCT UPPER(t.name) AS c0, t.name AS c1 FROM t ORDER BY " + nullsLast)) + .as("the alias, its NULLs last: " + nullsLast).containsExactly("A", "B", null); + String nullsFirst = dialect.generateOrderByNulls("c1", false, false).toString(); + assertThat(rows(st, "SELECT DISTINCT UPPER(t.name) AS c0, t.name AS c1 FROM t ORDER BY " + nullsFirst)) + .as("the alias descending, its NULLs first: " + nullsFirst).containsExactly(null, "B", "A"); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlPercentileTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlPercentileTest.java new file mode 100644 index 00000000..24b9b4c3 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlPercentileTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL has no {@code PERCENTILE_DISC} and no {@code PERCENTILE_CONT … WITHIN GROUP}, as an aggregate or otherwise. The + * dialect is built from a live connection: where it offers a percentile, the server must compute the right value of + * it; where the server has none, the dialect must offer none and write none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlPercentileTest { + + /** 10, 20, 30, 40 and a NULL that every aggregate leaves out. */ + private static final String CREATE = "CREATE TABLE nums(v INT)"; + private static final String INSERT = "INSERT INTO nums VALUES (30), (10), (NULL), (40), (20)"; + + @ParameterizedTest(name = "mysql:{0} -> percentiles {1}") + @CsvSource({ "5.7, false", "8.0, false", "8.4, false", "9, false" }) + void percentile(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + st.execute(CREATE); + st.execute(INSERT); + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsPercentileDisc()).as("supportsPercentileDisc").isEqualTo(expected); + assertThat(dialect.supportsPercentileCont()).as("supportsPercentileCont").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.generatePercentileDisc(0.5, false, "nums", "v")).isEmpty(); + assertThat(dialect.generatePercentileCont(0.5, false, "nums", "v")).isEmpty(); + assertThatThrownBy(() -> value(st, "SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY v) FROM nums")) + .as("the server knows no PERCENTILE_CONT").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> value(st, "SELECT PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY v) FROM nums")) + .as("the server knows no PERCENTILE_DISC").isInstanceOf(SQLException.class); + return; + } + + assertValue(st, dialect.generatePercentileDisc(0.5, false, "nums", "v"), 20); + assertValue(st, dialect.generatePercentileDisc(0.5, true, "nums", "v"), 30); + assertValue(st, dialect.generatePercentileCont(0.5, false, "nums", "v"), 25); + assertValue(st, dialect.generatePercentileCont(0.25, false, null, "v"), 17.5); + } + } + } + + private static void assertValue(Statement st, Optional percentile, double expected) throws SQLException { + assertThat(percentile).isPresent(); + assertThat(value(st, "SELECT " + percentile.get() + " FROM nums")).as(percentile.get()).isEqualTo(expected); + } + + private static double value(Statement st, String sql) throws SQLException { + try (ResultSet rs = st.executeQuery(sql)) { + assertThat(rs.next()).isTrue(); + return rs.getDouble(1); + } + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRecursiveCteTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRecursiveCteTest.java new file mode 100644 index 00000000..4eb7a079 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRecursiveCteTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.CteGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.CteGenerator.Cte; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL has common table expressions from 8.0, recursive ones too: {@code WITH RECURSIVE}. The dialect is built from a + * live connection: from 8.0 on the WITH clause it writes runs on the server, a recursive one counting and walking a + * tree, without RECURSIVE a recursive one failing, two of one clause the second reading the first. On 5.7 it says it has + * no recursive ones and writes no RECURSIVE; 5.7 has no WITH at all, which no flag of the dialect says. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlRecursiveCteTest { + + /** A tree: ceo above a and b, a above c, c above d. */ + private static final List SETUP = List.of("CREATE TABLE emp(id INT PRIMARY KEY, boss INT, name VARCHAR(10))", + "INSERT INTO emp VALUES (1, NULL, 'ceo'), (2, 1, 'a'), (3, 1, 'b'), (4, 2, 'c'), (5, 4, 'd')"); + + private static final List NUMBERS = List + .of(new Cte("nums", "SELECT 1 AS n UNION ALL SELECT n + 1 FROM nums WHERE n < 5")); + + private static final List TREE = List.of(new Cte("tree", + "SELECT id, name, 0 AS depth FROM emp WHERE boss IS NULL" + + " UNION ALL SELECT e.id, e.name, t.depth + 1 FROM emp e JOIN tree t ON e.boss = t.id")); + + /** Two of one clause, not recursive, the second reading the first. */ + private static final List BOSSES = List.of( + new Cte("bosses", "SELECT DISTINCT boss FROM emp WHERE boss IS NOT NULL"), + new Cte("named", "SELECT e.name FROM emp e JOIN bosses b ON e.id = b.boss")); + + @ParameterizedTest(name = "mysql:{0} -> recursive {1}") + @CsvSource({ "5.7, false", "8.0, true", "8.4, true", "9, true" }) + void recursive_cte(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + CteGenerator cte = new MySqlDialect(DialectInitData.fromConnection(c)).cteGenerator(); + + assertThat(cte.supportsRecursiveCte()).as("supportsRecursiveCte").isEqualTo(expected); + assertThat(cte.withClause(List.of(), true)).as("no expressions, no clause").isEmpty(); + assertThat(cte.withClause(NUMBERS, true).startsWith("WITH RECURSIVE ")).as("RECURSIVE written") + .isEqualTo(expected); + + if (!expected) { + assertThatThrownBy(() -> rows(st, cte.withClause(BOSSES, false) + "SELECT name FROM named")) + .as("5.7 knows no WITH, not recursive either; no flag says so") + .isInstanceOf(SQLException.class).hasMessageContaining("syntax"); + return; + } + + assertThat(rows(st, cte.withClause(NUMBERS, true) + "SELECT SUM(n) FROM nums")) + .as("counting to 5").containsExactly("15"); + assertThat(rows(st, cte.withClause(TREE, true) + + "SELECT CONCAT(name, ':', depth) FROM tree ORDER BY depth, name")) + .as("walking the tree").containsExactly("ceo:0", "a:1", "b:1", "c:2", "d:3"); + assertThatThrownBy(() -> rows(st, cte.withClause(NUMBERS, false) + "SELECT SUM(n) FROM nums")) + .as("a recursive one without RECURSIVE").isInstanceOf(SQLException.class) + .hasMessageContaining("nums"); + assertThat(rows(st, cte.withClause(BOSSES, false) + "SELECT name FROM named ORDER BY name")) + .as("two of one clause, the second reading the first").containsExactly("a", "c", "ceo"); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRegularExpressionTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRegularExpressionTest.java new file mode 100644 index 00000000..7b3de56a --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRegularExpressionTest.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MDX {@code MATCHES} is Java's {@code Pattern.matches}: the whole value, case-sensitive unless the expression says + * {@code (?i)}. The dialect is built from a live connection, and the condition it writes must pick on the server the + * rows Java would: anchored at both ends, the case kept or ignored as asked, whatever collation the column has, a dot + * escaped, a NULL never; and an expression Java cannot read gives no condition. Before MySQL 8.0.4 REGEXP is Henry + * Spencer's, which knows none of the ICU constructs the condition needs: the dialect must write none, and leave the + * expression to be matched in Java. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlRegularExpressionTest { + + /** The server's default collation, case-insensitive (latin1_swedish_ci on 5.7, utf8mb4_0900_ai_ci from 8.0). */ + private static final String CREATE = "CREATE TABLE words(id INT PRIMARY KEY, w VARCHAR(20))"; + private static final String INSERT = """ + INSERT INTO words VALUES (1, 'apple'), (2, 'Apple'), (3, 'APPLE'), (4, 'pineapple'), (5, 'banana'), + (6, 'a.b'), (7, 'axb'), (8, NULL)"""; + + private static final List EXPRESSIONS = List.of("apple", "a.*", "(?i)a.*", "(?i)apple", ".*apple", "A.*", + "a\\.b", "[a-c].*", "ban(an)+a", "apple|banana"); + + @ParameterizedTest(name = "mysql:{0} -> in SQL {1}") + @CsvSource({ "5.7, false", "8.0, true", "8.4, true", "9, true" }) + void regular_expression(String tag, boolean inSql) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + st.execute(CREATE); + st.execute(INSERT); + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.allowsRegularExpressionInWhereClause()).isEqualTo(inSql); + + if (!inSql) { + for (String javaRegex : EXPRESSIONS) { + assertThat(dialect.regexGenerator().generateRegularExpression("w", javaRegex)) + .as(javaRegex + " is not written for Henry Spencer's REGEXP").isEmpty(); + } + assertThatThrownBy(() -> st.executeQuery("SELECT w FROM words WHERE w REGEXP '(?-i)\\\\A(?:a)\\\\z'")) + .as("5.7 refuses the ICU constructs").isInstanceOf(SQLException.class) + .hasMessageContaining("repetition-operator operand invalid"); + return; + } + + assertMatches(st, dialect, "apple", "apple"); + assertMatches(st, dialect, "a.*", "apple", "a.b", "axb"); + assertMatches(st, dialect, "(?i)a.*", "apple", "Apple", "APPLE", "a.b", "axb"); + assertMatches(st, dialect, "(?i)apple", "apple", "Apple", "APPLE"); + assertMatches(st, dialect, ".*apple", "apple", "pineapple"); + assertMatches(st, dialect, "A.*", "Apple", "APPLE"); + assertMatches(st, dialect, "a\\.b", "a.b"); + assertMatches(st, dialect, "[a-c].*", "apple", "banana", "a.b", "axb"); + assertMatches(st, dialect, "ban(an)+a", "banana"); + assertMatches(st, dialect, "apple|banana", "apple", "banana"); + + assertThat(dialect.regexGenerator().generateRegularExpression("w", "a(")).as("not a Java expression") + .isEmpty(); + } + } + } + + private static void assertMatches(Statement st, MySqlDialect dialect, String javaRegex, String... expected) + throws SQLException { + String condition = dialect.regexGenerator().generateRegularExpression("w", javaRegex).orElseThrow() + .toString(); + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery("SELECT w FROM words WHERE " + condition + " ORDER BY id")) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + assertThat(out).as(javaRegex + " -> " + condition).containsExactly(expected); + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameColumnTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameColumnTest.java new file mode 100644 index 00000000..c965a383 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameColumnTest.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.JDBCType; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnMetaDataRecord; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData.AutoIncrement; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData.GeneratedColumn; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData.Nullability; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL renames a column with {@code RENAME COLUMN} from 8.0, which changes the name only. Before, the dialect writes + * {@code CHANGE old new }, which replaces the whole column with the definition it is given, from the + * column's metadata. The dialect is built from a live connection, and the column it renames must keep, on every + * version, its type, its nullability, its default, its comment, its AUTO_INCREMENT and its values; without the + * metadata it renames from 8.0 on, and writes no rename before. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlRenameColumnTest { + + private static final TableReference T = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "t", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of(""" + CREATE TABLE t(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, + note VARCHAR(20) NOT NULL DEFAULT 'n/a' COMMENT 'the note', + price DECIMAL(10,2) NULL)""", "INSERT INTO t(note, price) VALUES ('x', 1.50), (DEFAULT, NULL)"); + + private static final ColumnMetaData ID = meta(JDBCType.INTEGER, OptionalInt.empty(), OptionalInt.empty(), + Nullability.NO_NULLS, null, null, AutoIncrement.YES); + private static final ColumnMetaData NOTE = meta(JDBCType.VARCHAR, OptionalInt.of(20), OptionalInt.empty(), + Nullability.NO_NULLS, "'n/a'", "the note", AutoIncrement.NO); + private static final ColumnMetaData PRICE = meta(JDBCType.DECIMAL, OptionalInt.of(10), OptionalInt.of(2), + Nullability.NULLABLE, null, null, AutoIncrement.NO); + + /** Type, nullability, default, extra and comment of each column, in order. */ + private static final String COLUMNS = """ + SELECT CONCAT_WS('|', COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, IFNULL(COLUMN_DEFAULT, '-'), + IF(EXTRA = '', '-', EXTRA), IF(COLUMN_COMMENT = '', '-', COLUMN_COMMENT)) + FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'rt' AND TABLE_NAME = 't' ORDER BY ORDINAL_POSITION"""; + + @ParameterizedTest(name = "mysql:{0} -> RENAME COLUMN {1}") + @CsvSource({ "5.7, false", "8.0, true", "8.4, true", "9, true" }) + void rename_column(String tag, boolean renameColumn) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsRenameColumn()).isTrue(); + + String withoutMeta = dialect.renameColumn(T, "price", "cost"); + if (renameColumn) { + assertThat(withoutMeta).contains("RENAME COLUMN"); + st.execute(withoutMeta); + st.execute(dialect.renameColumn(T, "cost", "price")); + } else { + assertThat(withoutMeta).as("no rename without the metadata before 8.0").isNull(); + } + + rename(st, dialect, "note", "remark", NOTE); + rename(st, dialect, "price", "cost", PRICE); + rename(st, dialect, "id", "key_id", ID); + + assertThat(rows(st, COLUMNS)).as("each column renamed, and kept whole").containsExactly( + "key_id|int(11)|NO|-|auto_increment|-".replace("int(11)", intType(st)), + "remark|varchar(20)|NO|n/a|-|the note", "cost|decimal(10,2)|YES|-|-|-"); + assertThat(rows(st, "SELECT CONCAT_WS('|', key_id, remark, IFNULL(cost, '-')) FROM t ORDER BY key_id")) + .as("the values kept").containsExactly("1|x|1.50", "2|n/a|-"); + st.execute("INSERT INTO t(remark) VALUES ('y')"); + assertThat(rows(st, "SELECT MAX(key_id) FROM t")).as("AUTO_INCREMENT kept").containsExactly("3"); + } + } + } + + /** The dialect's rename with the column's metadata, run. */ + private static void rename(Statement st, MySqlDialect dialect, String from, String to, ColumnMetaData meta) + throws SQLException { + String sql = dialect.renameColumn(T, from, to, meta); + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + /** MySQL 8.0.19 and later write INT without its display width. */ + private static String intType(Statement st) throws SQLException { + return rows(st, "SELECT COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'rt'" + + " AND TABLE_NAME = 't' AND ORDINAL_POSITION = 1").get(0); + } + + private static ColumnMetaData meta(JDBCType type, OptionalInt size, OptionalInt scale, Nullability nullability, + String columnDefault, String remarks, AutoIncrement autoIncrement) { + return new ColumnMetaDataRecord(type, type.getName(), size, scale, OptionalInt.empty(), nullability, + OptionalInt.empty(), Optional.ofNullable(remarks), Optional.ofNullable(columnDefault), autoIncrement, + GeneratedColumn.NO); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameIndexTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameIndexTest.java new file mode 100644 index 00000000..10abc6e1 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRenameIndexTest.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL renames an index with {@code ALTER TABLE t RENAME INDEX old TO new} since 5.7. The dialect is built from a + * live connection: from 5.7 on the index it renames keeps its columns and its uniqueness under the new name; on 5.6 it + * writes no rename ({@code null}, as {@code supportsRenameIndex()} says), for the server would refuse it. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlRenameIndexTest { + + private static final TableReference USERS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "users", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of( + "CREATE TABLE users(id INT PRIMARY KEY, name VARCHAR(20), email VARCHAR(40))", + "CREATE INDEX idx_name ON users(name)", "CREATE UNIQUE INDEX uq_email ON users(email)"); + + /** Name, column and uniqueness of the table's indexes but the primary key, by name. */ + private static final String INDEXES = """ + SELECT CONCAT(INDEX_NAME, ':', COLUMN_NAME, ':', IF(NON_UNIQUE = 0, 'unique', 'plain')) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = 'rt' AND TABLE_NAME = 'users' AND INDEX_NAME <> 'PRIMARY' + ORDER BY INDEX_NAME"""; + + @ParameterizedTest(name = "mysql:{0} -> RENAME INDEX {1}") + @CsvSource({ "5.6, false", "5.7, true", "8.0, true", "8.4, true", "9, true" }) + void rename_index(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsRenameIndex()).as("supportsRenameIndex").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.renameIndex("idx_name", "idx_user_name", USERS)).as("no rename on 5.6") + .isNull(); + assertThatThrownBy(() -> st.execute("ALTER TABLE users RENAME INDEX idx_name TO idx_user_name")) + .as("MySQL 5.6 knows no RENAME INDEX").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax"); + return; + } + + st.execute(dialect.renameIndex("idx_name", "idx_user_name", USERS)); + st.execute(dialect.renameIndex("uq_email", "uq_user_email", USERS)); + assertThat(rows(st, INDEXES)).as("the new names, the columns and the uniqueness kept") + .containsExactly("idx_user_name:name:plain", "uq_user_email:email:unique"); + + st.execute("INSERT INTO users VALUES (1, 'a', 'a@x')"); + assertThatThrownBy(() -> st.execute("INSERT INTO users VALUES (2, 'b', 'a@x')")) + .as("the renamed unique index still unique").isInstanceOf(SQLException.class) + .hasMessageContaining("uq_user_email"); + + assertThatThrownBy(() -> st.execute(dialect.renameIndex("idx_name", "idx_again", USERS))) + .as("the old name is gone").isInstanceOf(SQLException.class); + + assertThatThrownBy(() -> dialect.renameIndex("idx_user_name", "x", null)) + .as("an index of no table").isInstanceOf(IllegalArgumentException.class); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRolesTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRolesTest.java new file mode 100644 index 00000000..b32da40f --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlRolesTest.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL has roles from 8.0: {@code CREATE ROLE [IF NOT EXISTS]}, {@code DROP ROLE [IF EXISTS]}, a role granted to a + * user, with the admin option too, and revoked. The dialect is built from a live connection: from 8.0 on the role it + * creates is there, holds a privilege, gives it to the user it is granted to and is dropped, and IF [NOT] EXISTS spares + * an error; on 5.7 it writes no role, for the server would refuse the statement. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlRolesTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "items", TableReference.TYPE_TABLE); + + @ParameterizedTest(name = "mysql:{0} -> roles {1}") + @CsvSource({ "5.7, false", "8.0, true", "8.4, true", "9, true" }) + void roles(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + // root may create roles and users and read mysql.user; the container's user may not + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), "root", my.getPassword()); + Statement st = c.createStatement()) { + st.execute("CREATE TABLE items(id INT)"); + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsRoles()).as("supportsRoles").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.createRole("rt_role", false)).as("no role on 5.7").isEmpty(); + assertThat(dialect.createRole("rt_role", true)).as("no role on 5.7").isEmpty(); + assertThat(dialect.dropRole("rt_role", true)).as("no role on 5.7").isEmpty(); + assertThatThrownBy(() -> st.execute("CREATE ROLE rt_role")) + .as("MySQL 5.7 knows no CREATE ROLE").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax"); + return; + } + + st.execute(dialect.createRole("rt_role", false).orElseThrow()); + assertThat(rows(st, "SELECT CONCAT(user, '@', host) FROM mysql.user WHERE user = 'rt_role'")) + .as("the role").containsExactly("rt_role@%"); + assertThatThrownBy(() -> st.execute(dialect.createRole("rt_role", false).orElseThrow())) + .as("a second one of the name").isInstanceOf(SQLException.class) + .hasMessageContaining("CREATE ROLE"); + st.execute(dialect.createRole("rt_role", true).orElseThrow()); + + st.execute(dialect.grantTablePrivilege("SELECT", ITEMS, "rt_role", false)); + st.execute(dialect.createUser("rt_user", false).orElseThrow()); + st.execute(dialect.grantRole("rt_role", "rt_user", false)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("the role granted to the user") + .contains("GRANT `rt_role`@`%` TO `rt_user`@`%`"); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user USING rt_role"))) + .as("the user holds the role's privilege").contains("GRANT SELECT ON `rt`.`items`"); + + st.execute(dialect.revokeRole("rt_role", "rt_user")); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("revoked") + .doesNotContain("rt_role"); + st.execute(dialect.grantRole("rt_role", "rt_user", true)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("with the admin option") + .contains("GRANT `rt_role`@`%` TO `rt_user`@`%` WITH ADMIN OPTION"); + + st.execute(dialect.dropRole("rt_role", false).orElseThrow()); + assertThat(rows(st, "SELECT user FROM mysql.user WHERE user = 'rt_role'")).as("dropped").isEmpty(); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("the grant gone with the role") + .doesNotContain("rt_role"); + assertThatThrownBy(() -> st.execute(dialect.dropRole("rt_role", false).orElseThrow())) + .as("a missing one").isInstanceOf(SQLException.class).hasMessageContaining("DROP ROLE"); + st.execute(dialect.dropRole("rt_role", true).orElseThrow()); + st.execute(dialect.dropUser("rt_user", true).orElseThrow()); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerStatementScopeTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerStatementScopeTest.java new file mode 100644 index 00000000..cd628152 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerStatementScopeTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerScope; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL and MariaDB have row triggers only, {@code FOR EACH ROW}: {@code FOR EACH STATEMENT} is a syntax error, and a + * trigger that fires once for a statement cannot be written with a row trigger. The dialect is built from a live + * connection, and it must write no statement trigger, as it writes nothing it cannot ({@code UnsupportedOperationException}), + * by its own body or calling a procedure, while a row trigger is created and fires once per row. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlTriggerStatementScopeTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "items", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of("CREATE TABLE items(id INT)", + "CREATE TABLE audit(op VARCHAR(10))"); + + @ParameterizedTest(name = "mysql:{0}") + @ValueSource(strings = { "5.7", "8.0", "8.4", "9" }) + void statement_scope(String tag) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThatThrownBy(() -> st.execute( + "CREATE TRIGGER rt.t AFTER INSERT ON rt.items FOR EACH STATEMENT INSERT INTO audit VALUES ('x')")) + .as("the server knows no FOR EACH STATEMENT").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax"); + + for (TriggerTiming timing : List.of(TriggerTiming.BEFORE, TriggerTiming.AFTER)) { + for (TriggerEvent event : TriggerEvent.values()) { + assertThatThrownBy(() -> dialect.createTrigger("items_stmt", timing, event, ITEMS, + TriggerScope.STATEMENT, null, "INSERT INTO audit VALUES ('x')")) + .as(timing + " " + event + " FOR EACH STATEMENT") + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> dialect.createTrigger("items_stmt", timing, event, ITEMS, + TriggerScope.STATEMENT, "1 = 1", "INSERT INTO audit VALUES ('x')")) + .as(timing + " " + event + " FOR EACH STATEMENT with a condition") + .isInstanceOf(UnsupportedOperationException.class); + } + } + st.execute(dialect.createTriggerProcedure("log_it", "rt", + "BEGIN INSERT INTO audit VALUES ('call'); END").orElseThrow()); + assertThatThrownBy(() -> dialect.createTriggerUsingProcedure("items_stmt", "rt", TriggerTiming.AFTER, + TriggerEvent.DELETE, ITEMS, TriggerScope.STATEMENT, null, "log_it")) + .as("calling a procedure FOR EACH STATEMENT").isInstanceOf(UnsupportedOperationException.class); + + st.execute(dialect.createTrigger("items_row", TriggerTiming.AFTER, TriggerEvent.INSERT, ITEMS, + TriggerScope.ROW, null, "INSERT INTO audit VALUES ('row')")); + st.execute("INSERT INTO items VALUES (1), (2)"); + assertThat(rows(st, "SELECT op FROM audit")).as("a row trigger, once per row") + .containsExactly("row", "row"); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerWhenTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerWhenTest.java new file mode 100644 index 00000000..76b6aa70 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlTriggerWhenTest.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerScope; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * A trigger with a WHEN condition fires only for the rows the condition holds of. MySQL has no WHEN in + * {@code CREATE TRIGGER}. The dialect is built from a live connection, and the trigger it writes with a condition must + * be created on the server and fire as the condition says: before an insert with a body of its own, after an update + * comparing OLD and NEW, and after a delete calling a procedure. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlTriggerWhenTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "items", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of("CREATE TABLE items(id INT, mark VARCHAR(10), qty INT)", + "CREATE TABLE audit(op VARCHAR(10), item_id INT)"); + + @ParameterizedTest(name = "mysql:{0}") + @ValueSource(strings = { "5.7", "8.0", "8.4", "9" }) + void trigger_when(String tag) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + execute(st, dialect.createTrigger("items_big", TriggerTiming.BEFORE, TriggerEvent.INSERT, ITEMS, + TriggerScope.ROW, "NEW.qty > 10", "SET NEW.mark = 'big'")); + st.execute("INSERT INTO items VALUES (1, NULL, 5), (2, NULL, 20)"); + assertThat(rows(st, "SELECT CONCAT(id, ':', IFNULL(mark, '-')) FROM items ORDER BY id")) + .as("BEFORE INSERT, where the condition holds only").containsExactly("1:-", "2:big"); + + execute(st, dialect.createTrigger("items_audit", TriggerTiming.AFTER, TriggerEvent.UPDATE, ITEMS, + TriggerScope.ROW, "NOT (OLD.mark <=> NEW.mark)", + "INSERT INTO audit VALUES ('UPDATE', NEW.id)")); + st.execute("UPDATE items SET mark = 'big' WHERE id = 2"); + assertThat(rows(st, "SELECT op FROM audit")).as("AFTER UPDATE, the mark the same: nothing").isEmpty(); + st.execute("UPDATE items SET mark = 'x' WHERE id IN (1, 2)"); + assertThat(rows(st, "SELECT CONCAT(op, ':', item_id) FROM audit ORDER BY item_id")) + .as("AFTER UPDATE, the mark changed, once per row").containsExactly("UPDATE:1", "UPDATE:2"); + + st.execute("DELETE FROM audit"); + execute(st, dialect.createTriggerProcedure("log_delete", "rt", + "BEGIN INSERT INTO audit VALUES ('DELETE', NULL); END").orElseThrow()); + execute(st, dialect.createTriggerUsingProcedure("items_delete", "rt", TriggerTiming.AFTER, + TriggerEvent.DELETE, ITEMS, TriggerScope.ROW, "OLD.qty > 10", "log_delete")); + st.execute("DELETE FROM items WHERE id = 1"); + assertThat(rows(st, "SELECT op FROM audit")).as("AFTER DELETE of a small one: no call").isEmpty(); + st.execute("DELETE FROM items WHERE id = 2"); + assertThat(rows(st, "SELECT op FROM audit")).as("AFTER DELETE of a big one: the procedure called") + .containsExactly("DELETE"); + } + } + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUpsertValuesTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUpsertValuesTest.java new file mode 100644 index 00000000..1f30f446 --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUpsertValuesTest.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator.UpsertSpec; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * An upsert of a key that is there sets each update column to the value the statement would have inserted. MySQL + * reads that value with {@code VALUES(col)} in {@code ON DUPLICATE KEY UPDATE}, which 8.0.20 deprecates for the row + * alias of 8.0.19, {@code INSERT … AS new … UPDATE col = new.col}, with warning 1287. The dialect is built from a live + * connection, and its upsert must update the update columns only, of a single key and of a composite one, and the + * server must warn of nothing: the alias from 8.0.19, {@code VALUES(col)} before. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlUpsertValuesTest { + + private static final SchemaReference RT = new SchemaReference(Optional.empty(), "rt"); + private static final TableReference PRODUCTS = new TableReference(Optional.of(RT), "products", + TableReference.TYPE_TABLE); + private static final TableReference STOCK = new TableReference(Optional.of(RT), "stock", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of( + "CREATE TABLE products(id INT PRIMARY KEY, name VARCHAR(20), price INT, note VARCHAR(20))", + "CREATE TABLE stock(store VARCHAR(10), product INT, qty INT, PRIMARY KEY (store, product))", + "INSERT INTO products VALUES (1, 'apple', 10, 'kept')", "INSERT INTO stock VALUES ('north', 1, 5)"); + + /** note is inserted but not updated: a key that is there keeps it. */ + private static final UpsertSpec PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"), + List.of("id", "name", "price", "note"), List.of("name", "price")); + private static final UpsertSpec ONE_COLUMN = new UpsertSpec(PRODUCTS, List.of("id"), List.of("id", "price"), + List.of("price")); + private static final UpsertSpec STOCK_QTY = new UpsertSpec(STOCK, List.of("store", "product"), + List.of("store", "product", "qty"), List.of("qty")); + + @ParameterizedTest(name = "mysql:{0} -> row alias {1}") + @CsvSource({ "5.7, false", "8.0, true", "8.4, true", "9, true" }) + void upsert_values(String tag, boolean alias) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), my.getUsername(), my.getPassword()); + Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + MergeGenerator merge = new MySqlDialect(DialectInitData.fromConnection(c)).mergeGenerator(); + + upsert(st, merge, alias, PRODUCT, "1", "'apple'", "12", "'new'"); + assertThat(rows(st, "SELECT id, name, price, note FROM products ORDER BY id")) + .as("the update columns updated, note kept").containsExactly("1|apple|12|kept"); + + upsert(st, merge, alias, PRODUCT, "2", "'banana'", "7", "'fresh'"); + assertThat(rows(st, "SELECT id, name, price, note FROM products ORDER BY id")) + .as("a new key inserted with every column").containsExactly("1|apple|12|kept", "2|banana|7|fresh"); + + upsert(st, merge, alias, ONE_COLUMN, "2", "8"); + assertThat(rows(st, "SELECT id, name, price, note FROM products ORDER BY id")) + .as("one update column").containsExactly("1|apple|12|kept", "2|banana|8|fresh"); + + upsert(st, merge, alias, STOCK_QTY, "'north'", "1", "9"); + upsert(st, merge, alias, STOCK_QTY, "'south'", "1", "3"); + assertThat(rows(st, "SELECT store, product, qty FROM stock ORDER BY store")).as("a composite key") + .containsExactly("north|1|9", "south|1|3"); + } + } + } + + /** Runs the dialect's upsert, written with the row alias or VALUES(col), and asserts the server warned of nothing. */ + private static void upsert(Statement st, MergeGenerator merge, boolean alias, UpsertSpec spec, String... values) + throws SQLException { + String sql = merge.upsert(spec, List.of(values)).orElseThrow(); + assertThat(sql).as("the row alias").contains(alias ? "AS `new_row`" : "VALUES(`"); + assertThat(sql).as("the row alias").doesNotContain(alias ? "VALUES(`" : "new_row"); + st.clearWarnings(); + st.execute(sql); + List warnings = new ArrayList<>(); + for (SQLWarning w = st.getWarnings(); w != null; w = w.getNextWarning()) { + warnings.add(w.getErrorCode() + ": " + w.getMessage()); + } + assertThat(warnings).as("warnings of " + sql).isEmpty(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + int n = rs.getMetaData().getColumnCount(); + while (rs.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= n; i++) { + if (i > 1) + row.append('|'); + row.append(rs.getString(i)); + } + out.add(row.toString()); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUsersTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUsersTest.java new file mode 100644 index 00000000..f6408c7b --- /dev/null +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/container/MySqlUsersTest.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.mysql.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.MySQLContainer; + +/** + * MySQL creates a user without a password, locked, with {@code CREATE USER [IF NOT EXISTS] x ACCOUNT LOCK}, and drops + * it with {@code DROP USER [IF EXISTS] x}, from 5.7.8. The dialect is built from a live connection, its version with + * its patch: from 5.7.8 on the user it creates is there, locked, cannot log in, takes a privilege and is dropped, and + * IF [NOT] EXISTS spares an error; on 5.6 it writes no user, for the server would refuse the statement. The images of + * 5.7.7 to 5.7.9 are no longer served, so 5.7 is its latest, 5.7.44: before a version kept its patch, every 5.7 was + * taken for 5.7.0, and had no users. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlUsersTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "rt")), "items", TableReference.TYPE_TABLE); + + @ParameterizedTest(name = "mysql:{0} -> users {1}") + @CsvSource({ "5.6, false", "5.7, true", "8.0, true", "8.4, true", "9, true" }) + void users(String tag, boolean expected) throws Exception { + // the server's own configuration: Testcontainers' default sets innodb_log_file_size, which MySQL 9 refuses + try (MySQLContainer my = new MySQLContainer<>("mysql:" + tag).withConfigurationOverride("mysql-conf") + .withDatabaseName("rt").withUsername("rt").withPassword("rt")) { + my.start(); + // root may create users and read mysql.user; the container's user may not + try (Connection c = DriverManager.getConnection(my.getJdbcUrl(), "root", my.getPassword()); + Statement st = c.createStatement()) { + st.execute("CREATE TABLE items(id INT)"); + MySqlDialect dialect = new MySqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsUsers()).as("supportsUsers").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.createUser("rt_user", true)).as("no user on 5.6").isEmpty(); + assertThat(dialect.dropUser("rt_user", true)).as("no user on 5.6").isEmpty(); + assertThatThrownBy(() -> st.execute("CREATE USER IF NOT EXISTS rt_user ACCOUNT LOCK")) + .as("5.6 knows neither IF NOT EXISTS nor ACCOUNT LOCK").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax"); + return; + } + + st.execute(dialect.createUser("rt_user", false).orElseThrow()); + assertThat(rows(st, "SELECT CONCAT(user, '@', host, ':', account_locked) FROM mysql.user" + + " WHERE user = 'rt_user'")).as("the user, of any host, locked").containsExactly("rt_user@%:Y"); + + assertThatThrownBy(() -> DriverManager.getConnection(my.getJdbcUrl(), "rt_user", "").close()) + .as("a locked user without a password does not log in").isInstanceOf(SQLException.class); + + assertThatThrownBy(() -> st.execute(dialect.createUser("rt_user", false).orElseThrow())) + .as("a second one of the name").isInstanceOf(SQLException.class) + .hasMessageContaining("CREATE USER"); + st.execute(dialect.createUser("rt_user", true).orElseThrow()); + + st.execute(dialect.grantTablePrivilege("SELECT", ITEMS, "rt_user", false)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("a privilege of the user") + .contains("GRANT SELECT ON `rt`.`items`"); + + st.execute(dialect.dropUser("rt_user", false).orElseThrow()); + assertThat(rows(st, "SELECT user FROM mysql.user WHERE user = 'rt_user'")).as("dropped").isEmpty(); + assertThatThrownBy(() -> st.execute(dialect.dropUser("rt_user", false).orElseThrow())) + .as("a missing one").isInstanceOf(SQLException.class).hasMessageContaining("DROP USER"); + st.execute(dialect.dropUser("rt_user", true).orElseThrow()); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/mysql/src/test/resources/mysql-conf/my.cnf b/dialect/db/mysql/src/test/resources/mysql-conf/my.cnf new file mode 100644 index 00000000..9fbf9568 --- /dev/null +++ b/dialect/db/mysql/src/test/resources/mysql-conf/my.cnf @@ -0,0 +1,16 @@ +# Copyright (c) 2026 Contributors to the Eclipse Foundation. +# +# This program and the accompanying materials are made +# available under the terms of the Eclipse Public License 2.0 +# which is available at https://www.eclipse.org/legal/epl-2.0/ +# +# SPDX-License-Identifier: EPL-2.0 + +# A minimal server configuration for the Docker tests: Testcontainers' default sets innodb_log_file_size, +# which MySQL 9 no longer knows and refuses to start with. +# +# log_bin_trust_function_creators: from 8.0 binary logging is on, and a user without SUPER, as the tests' user is, +# may create a trigger or a function only with it. +[mysqld] +skip-name-resolve +log_bin_trust_function_creators = 1