diff --git a/dialect/db/h2/pom.xml b/dialect/db/h2/pom.xml index 79b9e29..70717c6 100644 --- a/dialect/db/h2/pom.xml +++ b/dialect/db/h2/pom.xml @@ -57,5 +57,72 @@ ${revision} test + + org.eclipse.daanse + org.eclipse.daanse.sql.jdbc.record + ${project.version} + test + + + + + h2-versions + + + integration.docker + true + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.7.0 + + + h2-versions + generate-test-resources + + copy + + + ${project.build.directory}/h2-versions + + + com.h2database + h2 + 1.4.200 + + + com.h2database + h2 + 2.0.206 + + + com.h2database + h2 + 2.1.214 + + + com.h2database + h2 + 2.2.224 + + + com.h2database + h2 + 2.3.232 + + + + + + + + + + diff --git a/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java b/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java index c9c1a00..02730ae 100644 --- a/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java +++ b/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java @@ -38,13 +38,14 @@ public boolean allowsRegularExpressionInWhereClause() { } /** - * {@code source IS NOT NULL AND REGEXP_LIKE(source, pattern[, flags])}. + * {@code source IS NOT NULL AND REGEXP_LIKE(source, '\A(?:javaRegex)\z')}. * - *

H2 evaluates REGEXP_LIKE with java.util.regex FIND semantics, while - * the MDX MATCHES operator is anchored ({@code Pattern.matches}) — the - * pattern is therefore wrapped in {@code \A(?:...)\z} so the SQL result - * equals the calc engine's. Embedded flags are extracted BEFORE anchoring - * (they only match at the start of the expression). + *

H2 evaluates REGEXP_LIKE with java.util.regex, on every version from 1.4.200 on, with FIND semantics, while + * the MDX MATCHES operator is anchored ({@code Pattern.matches}): the expression is wrapped in {@code \A(?:…)\z} + * and otherwise passed as it is, Java's to Java. Its flags stay inside it, where Java reads them for the rest of + * the group: taking them out to REGEXP_LIKE's flags, as before, lost {@code s} and {@code u}, and {@code \Q…\E}, + * unquoted before, quotes as it does in Java. H2 folds the case beyond ASCII under {@code (?i)}, as Java does only + * with {@code u}: {@code (?-u)} before the expression turns that off. */ @Override public Optional generateRegularExpression(String source, String javaRegex) { @@ -55,26 +56,14 @@ public Optional generateRegularExpression(String source, String javaRege return Optional.empty(); } javaRegex = org.eclipse.daanse.sql.dialect.db.common.DialectUtil.cleanUnicodeAwareCaseFlag(javaRegex); - StringBuilder mappedFlags = new StringBuilder(); - String[][] mapping = new String[][] { { "c", "c" }, { "i", "i" }, { "m", "m" } }; - javaRegex = extractEmbeddedFlags(javaRegex, mapping, mappedFlags); - - final java.util.regex.Matcher escapeMatcher = - org.eclipse.daanse.sql.dialect.db.common.DialectUtil.ESCAPE_PATTERN.matcher(javaRegex); - while (escapeMatcher.find()) { - javaRegex = javaRegex.replace(escapeMatcher.group(1), escapeMatcher.group(2)); - } final StringBuilder sb = new StringBuilder(); sb.append(source); sb.append(" IS NOT NULL AND "); sb.append("REGEXP_LIKE("); sb.append(source); sb.append(", "); - quoteStringLiteral(sb, "\\A(?:" + javaRegex + ")\\z"); - if (mappedFlags.length() > 0) { - sb.append(", "); - quoteStringLiteral(sb, mappedFlags.toString()); - } + // H2 compiles with UNICODE_CASE: (?-u) gives Java's ASCII-only (?i) back, an (?iu) inside turns it on again + quoteStringLiteral(sb, "(?-u)\\A(?:" + javaRegex + ")\\z"); sb.append(")"); return Optional.of(sb.toString()); } @@ -131,32 +120,58 @@ protected boolean supportsNullsOrdering() { // Unified BitOperation methods + /** + * {@code BIT_AND_AGG}, {@code BIT_OR_AGG}, {@code BIT_XOR_AGG}, {@code BIT_NAND_AGG}, {@code BIT_NOR_AGG} and + * {@code BIT_XNOR_AGG} from H2 2.0. 1.4 has {@code BIT_AND} and {@code BIT_OR} only, and no aggregate of the + * others ("Function not found"): those are refused there. A dialect made without a connection takes such a + * version. + */ @Override public java.util.Optional generateBitAggregation(BitOperation operation, CharSequence operand) { - StringBuilder buf = new StringBuilder(64); - StringBuilder result = switch (operation) { - case AND -> buf.append("BIT_AND_AGG(").append(operand).append(")"); - case OR -> buf.append("BIT_OR_AGG(").append(operand).append(")"); - case XOR -> buf.append("BIT_XOR_AGG(").append(operand).append(")"); - case NAND -> buf.append("BIT_NAND_AGG(").append(operand).append(")"); - case NOR -> buf.append("BIT_NOR_AGG(").append(operand).append(")"); - case NXOR -> buf.append("BIT_XNOR_AGG(").append(operand).append(")"); + if (!supportsBitAggregation(operation)) { + return java.util.Optional.empty(); + } + boolean agg = dialectVersion.isUnknownOrAtLeast(2, 0); + String function = switch (operation) { + case AND -> agg ? "BIT_AND_AGG(" : "BIT_AND("; + case OR -> agg ? "BIT_OR_AGG(" : "BIT_OR("; + case XOR -> "BIT_XOR_AGG("; + case NAND -> "BIT_NAND_AGG("; + case NOR -> "BIT_NOR_AGG("; + case NXOR -> "BIT_XNOR_AGG("; }; - return java.util.Optional.of(result.toString()); + return java.util.Optional.of(function + operand + ")"); } @Override public boolean supportsBitAggregation(BitOperation operation) { - return true; // H2 supports all bit operations + return dialectVersion.isUnknownOrAtLeast(2, 0) || operation == BitOperation.AND + || operation == BitOperation.OR; } + /** + * The first value of the sorted group whose cumulative share reaches p, the {@code max(1, ceil(p n))}-th of its n + * values that are not NULL, as the standard has it: the element of the group's sorted {@code ARRAY_AGG}, sliced + * out with a NULL appended, so that a group of no value gives NULL. H2's own {@code PERCENTILE_DISC}, in every + * version from 1.4.200 on, takes the nearest of the positions {@code p (n - 1)}, a half rounded down: 20, not 10, + * at 0.25 of 10, 20, 30, 40, and 2, not 1, at 0.1 of 1 to 10. The p is an exact numeric in H2, CEILING of 0.3 * 10 + * is 3. + */ @Override public java.util.Optional generatePercentileDisc(double percentile, boolean desc, String tableName, String columnName) { - return java.util.Optional - .of((buildPercentileFunction("PERCENTILE_DISC", percentile, desc, tableName, columnName)).toString()); + StringBuilder col = new StringBuilder(); + if (tableName != null) { + quoteIdentifier(col, tableName, columnName); + } else { + quoteIdentifier(col, columnName); + } + String k = "GREATEST(1, CAST(CEILING(" + percentile + " * COUNT(" + col + ")) AS INT))"; + return java.util.Optional.of("(ARRAY_SLICE(ARRAY_AGG(" + col + " ORDER BY " + col + (desc ? " DESC" : "") + + ") FILTER (WHERE " + col + " IS NOT NULL), " + k + ", " + k + ") || ARRAY[NULL])[1]"); } + /** H2's own {@code PERCENTILE_CONT}, which interpolates as the standard does, on every version from 1.4.200 on. */ @Override public java.util.Optional generatePercentileCont(double percentile, boolean desc, String tableName, String columnName) { @@ -164,38 +179,47 @@ public java.util.Optional generatePercentileCont(double percentile, bool .of((buildPercentileFunction("PERCENTILE_CONT", percentile, desc, tableName, columnName)).toString()); } + /** + * {@code LISTAGG([DISTINCT] x, 'sep' [ON OVERFLOW TRUNCATE 'filler' WITHOUT COUNT]) [WITHIN GROUP (ORDER BY …)]}, + * the separator and the stand-in of a NULL as string literals: a quote in them ended the literal before. Without a + * separator {@code ', '}. {@code ON OVERFLOW TRUNCATE} from H2 2.0, a syntax error in 1.4: there the list is not + * truncated. 1.4 orders a {@code WITHIN GROUP} by one expression only, without {@code NULLS FIRST} or + * {@code NULLS LAST} (a syntax error after the first): a list in the order of more columns, or with an order of + * its NULLs, is refused there. A dialect made without a connection takes such a version. + */ @Override public java.util.Optional generateListAgg(CharSequence operand, boolean distinct, String separator, String coalesce, String onOverflowTruncate, List columns) { + if (!dialectVersion.isUnknownOrAtLeast(2, 0) && columns != null + && (columns.size() > 1 || columns.stream().anyMatch(c -> c.nullsOrder().isPresent()))) { + return java.util.Optional.empty(); + } StringBuilder buf = new StringBuilder(64); - buf.append("LISTAGG"); - buf.append("( "); + buf.append("LISTAGG( "); if (distinct) { buf.append("DISTINCT "); } if (coalesce != null) { - buf.append("COALESCE(").append(operand).append(", '").append(coalesce).append("')"); + buf.append("COALESCE(").append(operand).append(", "); + quoteStringLiteral(buf, coalesce); + buf.append(")"); } else { buf.append(operand); } - buf.append(", '"); - if (separator != null) { - buf.append(separator); - } else { - buf.append(", "); - } - buf.append("'"); - if (onOverflowTruncate != null) { - buf.append(" ON OVERFLOW TRUNCATE '").append(onOverflowTruncate).append("' WITHOUT COUNT)"); - } else { - buf.append(")"); + buf.append(", "); + quoteStringLiteral(buf, separator != null ? separator : ", "); + if (onOverflowTruncate != null && dialectVersion.isUnknownOrAtLeast(2, 0)) { + buf.append(" ON OVERFLOW TRUNCATE "); + quoteStringLiteral(buf, onOverflowTruncate); + buf.append(" WITHOUT COUNT"); } + buf.append(")"); if (columns != null && !columns.isEmpty()) { buf.append(" WITHIN GROUP (ORDER BY "); buf.append(buildOrderedColumnsClause(columns)); buf.append(")"); } - return java.util.Optional.of((buf).toString()); + return java.util.Optional.of(buf.toString()); } /** @@ -242,6 +266,25 @@ public String grantRole(String roleName, String grantee, boolean withAdminOption return "GRANT " + quoteIdentifier(roleName) + " TO " + quoteIdentifier(grantee); } + /** + * No recursive one: H2 runs {@code WITH RECURSIVE n(k) AS (…)} only with the list of its columns, in every + * version ("Column not found" without, a syntax error in 2.3), and an expression of the generator has no such + * list. Expressions that are not recursive run on every version. + */ + @Override + public org.eclipse.daanse.sql.dialect.api.generator.CteGenerator cteGenerator() { + return new org.eclipse.daanse.sql.dialect.api.generator.CteGenerator() { + @Override + public boolean supportsRecursiveCte() { + return false; + } + }; + } + + /** + * {@code LIMIT n [OFFSET m]}, an offset alone {@code OFFSET m ROWS}, on every version from 1.4.200 on: H2 2.x + * refuses {@code LIMIT -1} ("Invalid value -1 for parameter result FETCH"). + */ @Override public org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator paginationGenerator() { var local = cachedPaginationGenerator; @@ -258,14 +301,13 @@ public String paginate(java.util.OptionalLong limit, java.util.OptionalLong offs if (l < 0) throw new IllegalArgumentException("limit must be >= 0"); sb.append(" LIMIT ").append(l); - } else { - sb.append(" LIMIT -1"); } if (offset.isPresent()) { long o = offset.getAsLong(); if (o < 0) throw new IllegalArgumentException("offset must be >= 0"); - sb.append(" OFFSET ").append(o); + // an offset alone: OFFSET n ROWS; LIMIT -1, written before, H2 2.x refuses + sb.append(" OFFSET ").append(o).append(limit.isPresent() ? "" : " ROWS"); } return sb.toString(); } diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2DialectTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2DialectTest.java index 7c94432..70e3d77 100644 --- a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2DialectTest.java +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2DialectTest.java @@ -90,9 +90,9 @@ void testGenerateRegularExpression_InvalidRegex() { void testGenerateRegularExpression_CaseInsensitive() { String sql = dialect.regexGenerator() .generateRegularExpression("table.column", "(?i)|(?u).*a.*").orElseThrow(); - // pattern anchored: MDX MATCHES is Pattern.matches, H2 REGEXP_LIKE finds + // pattern anchored: MDX MATCHES is Pattern.matches, H2 REGEXP_LIKE finds; the flag stays in the pattern assertEquals( - "table.column IS NOT NULL AND REGEXP_LIKE(table.column, '\\A(?:.*a.*)\\z', 'i')", + "table.column IS NOT NULL AND REGEXP_LIKE(table.column, '(?-u)\\A(?:(?i).*a.*)\\z')", sql); } @@ -101,7 +101,7 @@ void testGenerateRegularExpression_CaseSensitive() { String sql = dialect.regexGenerator() .generateRegularExpression("table.column", ".*a.*").orElseThrow(); assertEquals( - "table.column IS NOT NULL AND REGEXP_LIKE(table.column, '\\A(?:.*a.*)\\z')", + "table.column IS NOT NULL AND REGEXP_LIKE(table.column, '(?-u)\\A(?:.*a.*)\\z')", sql); } } @@ -310,9 +310,10 @@ class PercentileGenerationTests { @Test void testGeneratePercentileDisc() { + // the standard's discrete percentile on the sorted group: H2's own PERCENTILE_DISC is the nearest rank String result = dialect.generatePercentileDisc(0.5, false, "table1", "column1").orElseThrow(); - assertTrue(result.contains("PERCENTILE_DISC")); - assertTrue(result.contains("0.5")); + assertTrue(result.contains("ARRAY_AGG")); + assertTrue(result.contains("CEILING(0.5 * COUNT(")); } @Test diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2BitAggregationTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2BitAggregationTest.java new file mode 100644 index 0000000..49a0dab --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2BitAggregationTest.java @@ -0,0 +1,55 @@ +/* + * 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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.EnumMap; +import java.util.Map; + +import org.eclipse.daanse.sql.model.sql.BitOperation; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * H2 has the bitwise aggregates {@code BIT_AND_AGG}, {@code BIT_OR_AGG}, {@code BIT_XOR_AGG}, {@code BIT_NAND_AGG}, + * {@code BIT_NOR_AGG} and {@code BIT_XNOR_AGG} from 2.0; 1.4 has {@code BIT_AND} and {@code BIT_OR} only. The dialect + * is built from a live connection of each version, and each aggregate it offers must give the bits of 6, 3 and 5; + * those 1.4 has not, it offers not. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2BitAggregationTest { + + /** 6, 3 and 5: AND 0, OR 7, XOR 0; NAND, NOR and XNOR their complements. */ + private static final Map EXPECTED = new EnumMap<>(Map.of(BitOperation.AND, "0", + BitOperation.OR, "7", BitOperation.XOR, "0", BitOperation.NAND, "-1", BitOperation.NOR, "-8", + BitOperation.NXOR, "-1")); + + @ParameterizedTest(name = "h2 {0} -> all six {1}") + @CsvSource({ "1.4.200, false", "2.0.206, true", "2.1.214, true", "2.2.224, true", "2.3.232, true" }) + void bitAggregation(String version, boolean allSix) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + h2.execute("CREATE TABLE T(X INT)"); + h2.execute("INSERT INTO T VALUES (6), (3), (5), (NULL)"); + for (BitOperation op : BitOperation.values()) { + boolean offered = allSix || op == BitOperation.AND || op == BitOperation.OR; + assertThat(h2.dialect().supportsBitAggregation(op)).as("supports " + op).isEqualTo(offered); + if (!offered) { + assertThat(h2.dialect().generateBitAggregation(op, "X")).as(op + " not before 2.0").isEmpty(); + continue; + } + String agg = h2.dialect().generateBitAggregation(op, "X").orElseThrow(); + assertThat(h2.rows("SELECT CAST(" + agg + " AS VARCHAR) FROM T")).as(op + ": " + agg) + .containsExactly(EXPECTED.get(op)); + } + } + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2DdlTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2DdlTest.java new file mode 100644 index 0000000..854449d --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2DdlTest.java @@ -0,0 +1,199 @@ +/* + * 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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.DatabaseMetaData; +import java.sql.JDBCType; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +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.api.generator.DdlGenerator.SequenceDefinition; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnDefinitionRecord; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnMetaDataRecord; +import org.eclipse.daanse.sql.jdbc.record.schema.PrimaryKeyRecord; +import org.eclipse.daanse.sql.model.schema.ColumnDefinition; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData; +import org.eclipse.daanse.sql.model.schema.ColumnReference; +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; + +/** + * The DDL of the H2 dialect, on every version from 1.4.200 on: a schema, tables with a named primary key, unique, + * check and foreign key constraints added later, a descending index, a view replaced, renames of a constraint, an + * index, a view, a column and a table, a sequence, and the drops, IF [NOT] EXISTS and CASCADE among them. The dialect + * is built from a live connection of each version, and each statement it writes must run there and do what it says, + * read back through the driver's metadata, which reads alike on 1.4 and 2.x. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2DdlTest { + + private static final Optional S1 = Optional.of(new SchemaReference(Optional.empty(), "S1")); + private static final TableReference A = new TableReference(S1, "A", TableReference.TYPE_TABLE); + private static final TableReference B = new TableReference(S1, "B", TableReference.TYPE_TABLE); + private static final TableReference V = new TableReference(S1, "V", TableReference.TYPE_VIEW); + + @ParameterizedTest(name = "h2 {0}") + @ValueSource(strings = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }) + void ddl(String version) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + DdlGenerator ddl = h2.dialect().ddlGenerator(); + DatabaseMetaData md = h2.connection().getMetaData(); + + // a schema, IF NOT EXISTS twice + h2.execute(ddl.createSchema("S1", true)); + h2.execute(ddl.createSchema("S1", true)); + assertThat(names(md.getSchemas(null, "S1"), "TABLE_SCHEM")).as("the schema").containsExactly("S1"); + + // tables, a named primary key, IF NOT EXISTS twice + String createA = ddl.createTable(A, List.of(column(A, "ID", JDBCType.INTEGER, false), + column(A, "EMAIL", JDBCType.VARCHAR, true), column(A, "N", JDBCType.INTEGER, true)), + new PrimaryKeyRecord(A, List.of(new ColumnReference(Optional.of(A), "ID")), Optional.of("PK_A")), + true); + h2.execute(createA); + h2.execute(createA); + h2.execute(ddl.createTable(B, List.of(column(B, "ID", JDBCType.INTEGER, false), + column(B, "AID", JDBCType.INTEGER, true)), null, false)); + assertThat(names(md.getPrimaryKeys(null, "S1", "A"), "PK_NAME")).as("the named primary key") + .containsExactly("PK_A"); + + // constraints added later hold + h2.execute(ddl.addUniqueConstraint(A, "UQ_EMAIL", List.of("EMAIL"))); + h2.execute(ddl.addCheckConstraint(A, "CK_N", "\"N\" > 0")); + h2.execute(ddl.addForeignKeyConstraint(B, "FK_B_A", List.of("AID"), A, List.of("ID"), "CASCADE", null)); + h2.execute("INSERT INTO S1.A VALUES (1, 'a@x', 1), (2, 'b@x', 2)"); + h2.execute("INSERT INTO S1.B VALUES (10, 1), (11, 2), (12, NULL)"); + assertRefused(h2, "INSERT INTO S1.A VALUES (3, 'a@x', 3)", "a second email"); + assertRefused(h2, "INSERT INTO S1.A VALUES (3, 'c@x', 0)", "n not above 0"); + assertRefused(h2, "INSERT INTO S1.B VALUES (13, 99)", "of no A"); + h2.execute("DELETE FROM S1.A WHERE ID = 1"); + assertThat(h2.rows("SELECT CAST(COUNT(*) AS VARCHAR) FROM S1.B")).as("ON DELETE CASCADE") + .containsExactly("2"); + assertThat(names(md.getImportedKeys(null, "S1", "B"), "FK_NAME")).as("the foreign key") + .containsExactly("FK_B_A"); + + // a constraint renamed and dropped, IF EXISTS + h2.execute(ddl.renameConstraint(A, "CK_N", "CK_N2")); + assertRefused(h2, ddl.dropConstraint(A, "CK_N", false), "the old name of the renamed check"); + assertRefused(h2, "INSERT INTO S1.A VALUES (4, 'd@x', 0)", "the renamed check still holds"); + h2.execute(ddl.dropConstraint(A, "CK_N2", true)); + h2.execute(ddl.dropConstraint(A, "CK_N2", true)); + h2.execute("INSERT INTO S1.A VALUES (4, 'd@x', 0)"); + + // indexes: IF NOT EXISTS twice, a descending column, a rename, IF EXISTS + h2.execute(ddl.createIndex("IX_N", A, List.of("N"), false, true)); + h2.execute(ddl.createIndex("IX_N", A, List.of("N"), false, true)); + h2.execute(ddl.createIndex(new IndexDefinition("IX_D", A, + List.of(IndexColumn.ascending("ID"), new IndexColumn("EMAIL", true)), false, null), false) + .orElseThrow()); + assertThat(indexColumns(md, "IX_D")).as("the descending column").containsExactly("ID:A", "EMAIL:D"); + h2.execute(ddl.renameIndex("IX_N", "IX_N2", A)); + assertThat(indexColumns(md, "IX_N2")).as("the renamed index").containsExactly("N:A"); + assertThat(indexColumns(md, "IX_N")).as("not under its old name").isEmpty(); + h2.execute(ddl.dropIndex("IX_N2", A, true)); + h2.execute(ddl.dropIndex("IX_N2", A, true)); + assertThat(indexColumns(md, "IX_N2")).as("dropped").isEmpty(); + + // a view, replaced, renamed, dropped, IF EXISTS + h2.execute(ddl.createView(V, "SELECT \"ID\" FROM \"S1\".\"A\"", false)); + assertRefused(h2, ddl.createView(V, "SELECT \"ID\" FROM \"S1\".\"A\"", false), "a second view"); + h2.execute(ddl.createView(V, "SELECT \"ID\", \"N\" FROM \"S1\".\"A\"", true)); + assertThat(names(md.getColumns(null, "S1", "V", null), "COLUMN_NAME")).as("replaced, its columns too") + .containsExactly("ID", "N"); + h2.execute(ddl.renameView(V, "V2")); + assertThat(h2.rows("SELECT CAST(COUNT(*) AS VARCHAR) FROM S1.V2")).as("the renamed view reads") + .containsExactly("2"); + h2.execute(ddl.dropView(new TableReference(S1, "V2", TableReference.TYPE_VIEW), true)); + h2.execute(ddl.dropView(new TableReference(S1, "V2", TableReference.TYPE_VIEW), true)); + + // a column and a table renamed + h2.execute(ddl.renameColumn(A, "N", "QTY")); + assertThat(names(md.getColumns(null, "S1", "A", null), "COLUMN_NAME")).as("the renamed column") + .containsExactly("ID", "EMAIL", "QTY"); + h2.execute(ddl.renameTable(B, "B2")); + assertThat(h2.rows("SELECT CAST(COUNT(*) AS VARCHAR) FROM S1.B2")).as("the renamed table, its rows") + .containsExactly("2"); + + // a sequence: start, increment, cycle; IF NOT EXISTS, IF EXISTS + assertThat(ddl.supportsSequences()).isTrue(); + h2.execute(ddl.createSequence(new SequenceDefinition("S1", "SEQ", 10L, 5L, 10L, 20L, true, null), true) + .orElseThrow()); + h2.execute(ddl.createSequence(SequenceDefinition.of("S1", "SEQ"), true).orElseThrow()); + List values = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + values.addAll(h2.rows("SELECT CAST(NEXT VALUE FOR S1.SEQ AS VARCHAR)")); + } + assertThat(values).as("from 10 by 5 to 20, then round").containsExactly("10", "15", "20", "10"); + h2.execute(ddl.dropSequence("S1", "SEQ", true).orElseThrow()); + h2.execute(ddl.dropSequence("S1", "SEQ", true).orElseThrow()); + assertRefused(h2, "SELECT NEXT VALUE FOR S1.SEQ", "the dropped sequence"); + + // drops: a table with a view on it, CASCADE; IF EXISTS; the schema, CASCADE + h2.execute(ddl.createView(V, "SELECT \"ID\" FROM \"S1\".\"A\"", false)); + h2.execute(ddl.dropTable(A, true, true)); + assertThat(names(md.getTables(null, "S1", null, null), "TABLE_NAME")).as("A and its view gone") + .containsExactly("B2"); + h2.execute(ddl.dropTable(A, true)); + h2.execute(ddl.dropSchema("S1", true, true)); + assertThat(names(md.getSchemas(null, "S1"), "TABLE_SCHEM")).as("the schema gone, B2 with it").isEmpty(); + h2.execute(ddl.dropSchema("S1", true, false)); + } + } + + private static void assertRefused(H2Versions.Session h2, String sql, String what) { + assertThatThrownBy(() -> h2.execute(sql)).as(what + ": " + sql).isInstanceOf(SQLException.class); + } + + /** The columns of the index, in order, each with A or D. */ + private static List indexColumns(DatabaseMetaData md, String index) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = md.getIndexInfo(null, "S1", "A", false, false)) { + while (rs.next()) { + if (index.equals(rs.getString("INDEX_NAME"))) { + out.add(rs.getShort("ORDINAL_POSITION") - 1, rs.getString("COLUMN_NAME") + ":" + + rs.getString("ASC_OR_DESC")); + } + } + } + return out; + } + + private static List names(ResultSet rs, String column) throws SQLException { + List out = new ArrayList<>(); + try (rs) { + while (rs.next()) { + out.add(rs.getString(column)); + } + } + return out; + } + + private static ColumnDefinition column(TableReference table, String name, JDBCType type, boolean nullable) { + return new ColumnDefinitionRecord(new ColumnReference(Optional.of(table), name), + new ColumnMetaDataRecord(type, type.getName(), + type == JDBCType.VARCHAR ? OptionalInt.of(20) : OptionalInt.empty(), OptionalInt.empty(), + OptionalInt.empty(), nullable ? ColumnMetaData.Nullability.NULLABLE + : ColumnMetaData.Nullability.NO_NULLS, + OptionalInt.empty(), Optional.empty(), Optional.empty(), ColumnMetaData.AutoIncrement.UNKNOWN, + ColumnMetaData.GeneratedColumn.UNKNOWN)); + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2ListAggTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2ListAggTest.java new file mode 100644 index 0000000..4e0e11b --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2ListAggTest.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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.db.h2.H2Dialect; +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.CsvSource; + +/** + * H2 lists the values of a group with {@code LISTAGG(x, 'sep') WITHIN GROUP (ORDER BY …)} on every version from + * 1.4.200 on, with {@code ON OVERFLOW TRUNCATE} from 2.0. The dialect is built from a live connection of each version, + * and the list it writes must come in the order asked for, the NULLs of an order column first or last as asked, + * without the NULL values, or with their stand-in, DISTINCT kept, with any separator, a quote and a backslash too, and + * per group; the overflow clause only where H2 reads it. 1.4 orders WITHIN GROUP by one expression only, without + * NULLS FIRST/LAST: a list in the order of more, or of its NULLs, the dialect does not write there; the n-th value's + * ARRAY_AGG takes both on every version. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2ListAggTest { + + @ParameterizedTest(name = "h2 {0} -> ON OVERFLOW {1}") + @CsvSource({ "1.4.200, false", "2.0.206, true", "2.1.214, true", "2.2.224, true", "2.3.232, true" }) + void listAgg(String version, boolean overflow) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + h2.execute("CREATE TABLE EMP(DEPT VARCHAR(1), NAME VARCHAR(10), SALARY INT)"); + h2.execute("INSERT INTO EMP VALUES ('a', 'bob', 30), ('a', NULL, 40), ('a', 'alice', 20), ('a', 'bob', 10)," + + " ('b', 'dave', 5)"); + H2Dialect d = h2.dialect(); + assertThat(d.supportsListAgg()).isTrue(); + + assertThat(list(h2, "NAME", false, ", ", null, order("NAME", SortDirection.ASC))) + .as("ordered, the NULL left out").isEqualTo("alice, bob, bob"); + assertThat(list(h2, "NAME", false, ", ", null, order("SALARY", SortDirection.DESC))) + .as("ordered by another column").isEqualTo("bob, alice, bob"); + assertThat(list(h2, "NAME", true, ";", null, order("NAME", SortDirection.ASC))) + .as("DISTINCT").isEqualTo("alice;bob"); + assertThat(list(h2, "NAME", false, "'", null, order("NAME", SortDirection.ASC))) + .as("a quote as separator").isEqualTo("alice'bob'bob"); + assertThat(list(h2, "NAME", false, "\\", null, order("NAME", SortDirection.ASC))) + .as("a backslash as separator").isEqualTo("alice\\bob\\bob"); + assertThat(list(h2, "NAME", false, null, null, order("NAME", SortDirection.ASC))) + .as("no separator: H2's comma and blank").isEqualTo("alice, bob, bob"); + assertThat(list(h2, "NAME", false, ",", "it's", List.of(new OrderedColumn("SALARY", null, + SortDirection.ASC)))).as("the NULL's stand-in, a quote in it").isEqualTo("bob,alice,bob,it's"); + List nullsFirst = List.of(new OrderedColumn("NAME", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.FIRST)), new OrderedColumn("SALARY", null, SortDirection.ASC)); + List nullsLast = List.of(new OrderedColumn("NAME", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.LAST)), new OrderedColumn("SALARY", null, SortDirection.ASC)); + if (overflow) { + assertThat(list(h2, "SALARY", false, ",", null, nullsFirst)).as("NULLS FIRST, then a second column") + .isEqualTo("40,20,10,30"); + assertThat(list(h2, "SALARY", false, ",", null, nullsLast)).as("NULLS LAST, then a second column") + .isEqualTo("20,10,30,40"); + } else { + assertThat(d.generateListAgg("SALARY", false, ",", null, null, nullsFirst)) + .as("1.4: no order of the NULLs, nor a second column, in WITHIN GROUP").isEmpty(); + assertThat(d.generateListAgg("SALARY", false, ",", null, null, order("NAME", SortDirection.ASC) + .stream().toList())).as("one column, no order of its NULLs").isPresent(); + } + + // the n-th value's ARRAY_AGG takes NULLS FIRST/LAST on every version + for (NullsOrder nulls : NullsOrder.values()) { + String nth = d.generateNthValueAgg("SALARY", false, 1, List.of(new OrderedColumn("NAME", null, + Optional.of(SortDirection.ASC), Optional.of(nulls)))).orElseThrow(); + assertThat(h2.rows("SELECT CAST(" + nth + " AS VARCHAR) FROM EMP WHERE DEPT = 'a'")) + .as("the 1st value, NULLS " + nulls + ": " + nth) + .containsExactly(nulls == NullsOrder.FIRST ? "40" : "20"); + } + + String truncated = d.generateListAgg("NAME", false, ",", null, "...", order("NAME", SortDirection.ASC)) + .orElseThrow(); + assertThat(truncated.contains("ON OVERFLOW TRUNCATE")).as("the overflow clause").isEqualTo(overflow); + assertThat(h2.rows("SELECT " + truncated + " FROM EMP WHERE DEPT = 'a'")).as("runs: " + truncated) + .containsExactly("alice,bob,bob"); + + String perDept = d.generateListAgg("NAME", false, ",", null, null, order("NAME", SortDirection.ASC)) + .orElseThrow(); + assertThat(h2.rows("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(H2Versions.Session h2, String operand, boolean distinct, String separator, + String coalesce, List columns) throws Exception { + String agg = h2.dialect().generateListAgg(operand, distinct, separator, coalesce, null, columns).orElseThrow(); + List rows = h2.rows("SELECT " + agg + " FROM EMP WHERE DEPT = 'a'"); + assertThat(rows).as(agg).hasSize(1); + return rows.get(0); + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2PaginationTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2PaginationTest.java new file mode 100644 index 0000000..9223da7 --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2PaginationTest.java @@ -0,0 +1,93 @@ +/* + * 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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalLong; + +import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PagingParam; +import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PreparedPaging; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * H2 limits and skips rows with {@code LIMIT n OFFSET m} and {@code LIMIT n}, an offset alone with + * {@code OFFSET m ROWS}, on every version from 1.4.200 on; {@code LIMIT -1}, which the dialect wrote for an offset + * alone, H2 2.x refuses. The dialect is built from a live connection of each version, and the paging it writes must + * skip and limit the rows, limit to none, skip past the end, and run with its parameters bound in the order it gives. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2PaginationTest { + + private static final String SORTED = "SELECT CAST(X AS VARCHAR) FROM T ORDER BY X"; + + @ParameterizedTest(name = "h2 {0}") + @ValueSource(strings = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }) + void pagination(String version) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + h2.execute("CREATE TABLE T(X INT)"); + h2.execute("INSERT INTO T VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)"); + PaginationGenerator p = h2.dialect().paginationGenerator(); + assertThat(p.supportsOffset()).isTrue(); + + assertThat(h2.rows(SORTED + paging(p, 3, 2))).as("skip 2, take 3").containsExactly("2", "3", "4"); + assertThat(h2.rows(SORTED + paging(p, 3, null))).as("take 3").containsExactly("0", "1", "2"); + assertThat(h2.rows(SORTED + paging(p, null, 7))).as("skip 7, an offset alone").containsExactly("7", "8", + "9"); + assertThat(h2.rows(SORTED + paging(p, 0, null))).as("take none").isEmpty(); + assertThat(h2.rows(SORTED + paging(p, null, 20))).as("skip past the end").isEmpty(); + assertThat(h2.rows(SORTED + paging(p, null, null))).as("no paging").hasSize(10); + assertThat(h2.rows("SELECT COUNT(*) FROM (SELECT X FROM T" + paging(p, null, 4) + ")")) + .as("an offset alone without ORDER BY").containsExactly("6"); + + assertThat(prepared(h2, p, 3L, 2L)).as("prepared, skip 2, take 3").containsExactly("2", "3", "4"); + assertThat(prepared(h2, p, 3L, null)).as("prepared, take 3").containsExactly("0", "1", "2"); + assertThat(prepared(h2, p, null, 7L)).as("prepared, skip 7").containsExactly("7", "8", "9"); + + if (!version.startsWith("1.")) { + assertThatThrownBy(() -> h2.rows(SORTED + " LIMIT -1 OFFSET 7")).as("LIMIT -1, refused by 2.x") + .isInstanceOf(SQLException.class); + } + } + } + + private static String paging(PaginationGenerator p, Integer limit, Integer offset) { + return p.paginate(limit == null ? OptionalLong.empty() : OptionalLong.of(limit), + offset == null ? OptionalLong.empty() : OptionalLong.of(offset)); + } + + private static List prepared(H2Versions.Session h2, PaginationGenerator p, Long limit, Long offset) + throws SQLException { + PreparedPaging paging = p.paginatePrepared(limit != null, offset != null); + String sql = SORTED + " " + paging.clause(); + try (PreparedStatement ps = h2.connection().prepareStatement(sql)) { + int i = 1; + for (PagingParam param : paging.order()) { + ps.setLong(i++, param == PagingParam.LIMIT ? limit : offset); + } + List out = new ArrayList<>(); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2PercentileTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2PercentileTest.java new file mode 100644 index 0000000..2dcd410 --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2PercentileTest.java @@ -0,0 +1,101 @@ +/* + * 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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +import java.util.List; + +import org.eclipse.daanse.sql.dialect.db.h2.H2Dialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * H2 has {@code PERCENTILE_DISC} and {@code PERCENTILE_CONT … WITHIN GROUP (ORDER BY …)} on every version from + * 1.4.200 on; its discrete one takes the nearest of the positions p (n - 1), not the standard's first value whose + * cumulative share reaches p, and the dialect computes it on the sorted group. Built from a live connection of each + * version, its percentiles must give what the standard says: the discrete one a value of the group, the first whose + * cumulative share reaches p, the continuous one interpolated, ascending and descending, the NULLs left out, p at its + * ends, a column named with its table, per group, and NULL for a group of no value. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2PercentileTest { + + @ParameterizedTest(name = "h2 {0}") + @ValueSource(strings = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }) + void percentile(String version) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + // group a: 10, 20, 30, 40 and a NULL every aggregate leaves out; b: 5; c: only a NULL + h2.execute("CREATE TABLE NUMS(G VARCHAR(1), V INT)"); + h2.execute("INSERT INTO NUMS VALUES ('a', 30), ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5)," + + " ('c', NULL)"); + H2Dialect d = h2.dialect(); + assertThat(d.supportsPercentileDisc()).isTrue(); + assertThat(d.supportsPercentileCont()).isTrue(); + + assertThat(disc(h2, 0.5, false, "NUMS")).as("disc 0.5").isEqualTo(20); + assertThat(disc(h2, 0.25, false, null)).as("disc 0.25: cume_dist of 10 is 0.25").isEqualTo(10); + assertThat(disc(h2, 0.7, false, null)).as("disc 0.7").isEqualTo(30); + assertThat(disc(h2, 0, false, null)).as("disc 0, the least").isEqualTo(10); + assertThat(disc(h2, 1, false, null)).as("disc 1, the greatest").isEqualTo(40); + assertThat(disc(h2, 0.5, true, null)).as("disc 0.5 descending").isEqualTo(30); + assertThat(disc(h2, 0.25, true, "NUMS")).as("disc 0.25 descending").isEqualTo(40); + + // 1 to 10, where H2's own discrete percentile is one off at 0.1, 0.2 and 0.3 + h2.execute("CREATE TABLE TEN(V INT)"); + h2.execute("INSERT INTO TEN SELECT X FROM SYSTEM_RANGE(1, 10)"); + for (double[] pv : new double[][] { { 0.1, 1 }, { 0.2, 2 }, { 0.25, 3 }, { 0.3, 3 }, { 0.5, 5 }, + { 0.75, 8 }, { 0.9, 9 }, { 1, 10 } }) { + String disc = d.generatePercentileDisc(pv[0], false, null, "V").orElseThrow(); + assertThat(h2.rows("SELECT CAST(" + disc + " AS VARCHAR) FROM TEN")).as("disc " + pv[0] + " of 1..10") + .containsExactly(String.valueOf((int) pv[1])); + } + assertThat(h2.rows("SELECT CAST(PERCENTILE_DISC(0.1) WITHIN GROUP (ORDER BY V) AS VARCHAR) FROM TEN")) + .as("H2's own, the nearest of the positions p (n - 1)").containsExactly("2"); + + assertThat(cont(h2, 0.5, false, "NUMS")).as("cont 0.5").isEqualTo(25); + assertThat(cont(h2, 0.25, false, null)).as("cont 0.25").isEqualTo(17.5); + assertThat(cont(h2, 0.7, false, null)).as("cont 0.7").isCloseTo(31, within(1e-9)); + assertThat(cont(h2, 0, false, null)).as("cont 0, the least").isEqualTo(10); + assertThat(cont(h2, 1, false, null)).as("cont 1, the greatest").isEqualTo(40); + assertThat(cont(h2, 0.25, true, null)).as("cont 0.25 descending").isEqualTo(32.5); + assertThat(cont(h2, 1, true, "NUMS")).as("descending, the end: the least").isEqualTo(10); + + String perGroup = "SELECT G || '=' || COALESCE(CAST(%s AS VARCHAR), 'null') FROM NUMS GROUP BY G" + + " ORDER BY G"; + assertThat(h2.rows(perGroup.formatted(d.generatePercentileDisc(0.5, false, null, "V").orElseThrow()))) + .as("disc per group, one value, no value").containsExactly("a=20", "b=5", "c=null"); + List cont = h2.rows(perGroup.formatted(d.generatePercentileCont(0.5, false, null, "V") + .orElseThrow())); + assertThat(cont).as("cont per group, one value, no value").hasSize(3); + assertThat(Double.parseDouble(cont.get(0).substring(2))).isEqualTo(25); + assertThat(Double.parseDouble(cont.get(1).substring(2))).isEqualTo(5); + assertThat(cont.get(2)).isEqualTo("c=null"); + } + } + + private static double disc(H2Versions.Session h2, double p, boolean desc, String table) throws Exception { + return value(h2, h2.dialect().generatePercentileDisc(p, desc, table, "V").orElseThrow()); + } + + private static double cont(H2Versions.Session h2, double p, boolean desc, String table) throws Exception { + return value(h2, h2.dialect().generatePercentileCont(p, desc, table, "V").orElseThrow()); + } + + /** The percentile of group a. */ + private static double value(H2Versions.Session h2, String percentile) throws Exception { + List rows = h2.rows("SELECT CAST(" + percentile + " AS VARCHAR) FROM NUMS WHERE G = 'a'"); + assertThat(rows).as(percentile).hasSize(1); + assertThat(rows.get(0)).as(percentile).isNotNull(); + return Double.parseDouble(rows.get(0)); + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2RecursiveCteTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2RecursiveCteTest.java new file mode 100644 index 0000000..043a24a --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2RecursiveCteTest.java @@ -0,0 +1,59 @@ +/* + * 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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.generator.CteGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.CteGenerator.Cte; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * H2 runs a recursive common table expression only with the list of its columns, {@code WITH RECURSIVE n(k) AS (…)}, + * in every version; without, "Column not found", in 2.3 a syntax error. An expression of the generator has no such + * list: the dialect built from a live connection of each version says it has no recursive ones and writes no + * RECURSIVE. Two expressions of one clause, the second reading the first, run on every version. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2RecursiveCteTest { + + private static final List NUMBERS = List + .of(new Cte("N", "SELECT 1 AS K UNION ALL SELECT K + 1 FROM N WHERE K < 5")); + + @ParameterizedTest(name = "h2 {0}") + @ValueSource(strings = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }) + void recursiveCte(String version) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + h2.execute("CREATE TABLE EMP(ID INT, BOSS INT, NAME VARCHAR(10))"); + h2.execute("INSERT INTO EMP VALUES (1, NULL, 'ceo'), (2, 1, 'a'), (3, 1, 'b'), (4, 2, 'c')"); + CteGenerator cte = h2.dialect().cteGenerator(); + assertThat(cte.supportsRecursiveCte()).as("supportsRecursiveCte").isFalse(); + assertThat(cte.withClause(NUMBERS, true)).as("no RECURSIVE written").startsWith("WITH N AS ("); + + 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")); + assertThat(h2.rows(cte.withClause(bosses, false) + "SELECT NAME FROM NAMED ORDER BY NAME")) + .as("two of one clause, the second reading the first").containsExactly("a", "ceo"); + + assertThatThrownBy(() -> h2.rows("WITH RECURSIVE N AS (SELECT 1 AS K UNION ALL SELECT K + 1 FROM N" + + " WHERE K < 5) SELECT SUM(K) FROM N")).as("RECURSIVE without the list of columns") + .isInstanceOf(SQLException.class); + assertThat(h2.rows("WITH RECURSIVE N(K) AS (SELECT 1 UNION ALL SELECT K + 1 FROM N WHERE K < 5)" + + " SELECT CAST(SUM(K) AS VARCHAR) FROM N")).as("with it, which no expression gives") + .containsExactly("15"); + } + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2RegularExpressionTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2RegularExpressionTest.java new file mode 100644 index 0000000..8cb0975 --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2RegularExpressionTest.java @@ -0,0 +1,83 @@ +/* + * 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.h2.versions; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * MDX {@code MATCHES} is Java's {@code Pattern.matches}: the whole value, by Java's own expression. H2's + * {@code REGEXP_LIKE} is java.util.regex, on every version from 1.4.200 on, and finds rather than matches. The dialect + * is built from a live connection of each version, and the condition it writes must pick the rows Java picks: anchored + * at both ends, the case kept or ignored, ASCII only or beyond with {@code u}, a flag inside the expression, a dot + * escaped or taking no line break unless {@code s}, {@code \Q…\E} quoting what is in it, lookaround, a back + * reference, a possessive quantifier, a quote in the expression, a NULL never; and an expression Java cannot read + * gives none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2RegularExpressionTest { + + private static final List WORDS = Arrays.asList("apple", "Apple", "APPLE", "pineapple", "banana", "a.b", + "axb", "a\nb", "a+b", "aab", "a1 b", "ÄPFEL", "äpfel", "it's", "aaa", null); + + private static final List EXPRESSIONS = List.of("apple", "a.*", "(?i)a.*", "(?i)apple", ".*apple", + "A.*", "a\\.b", "a.b", "(?s)a.b", "[a-c].*", "ban(an)+a", "apple|banana", "\\Qa+b\\E", "a+b", + "\\w\\d\\s\\w", "(?i:a)pple", "(?i)äpfel", "(?iu)äpfel", "a(?=p).*", "(?<=a)pple|banana", "(a)\\1.*", + "a++", "it's", "[a-z&&[^b]]+", "(?x) a p p l e"); + + @ParameterizedTest(name = "h2 {0}") + @ValueSource(strings = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }) + void regularExpression(String version) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + h2.execute("CREATE TABLE WORDS(ID INT PRIMARY KEY, W VARCHAR(20))"); + try (PreparedStatement ps = h2.connection().prepareStatement("INSERT INTO WORDS VALUES (?, ?)")) { + for (int i = 0; i < WORDS.size(); i++) { + ps.setInt(1, i); + ps.setString(2, WORDS.get(i)); + ps.addBatch(); + } + ps.executeBatch(); + } + assertThat(h2.dialect().allowsRegularExpressionInWhereClause()).isTrue(); + + for (String javaRegex : EXPRESSIONS) { + Pattern p = Pattern.compile(javaRegex); + List java = WORDS.stream().filter(w -> w != null && p.matcher(w).matches()).toList(); + String condition = h2.dialect().regexGenerator().generateRegularExpression("W", javaRegex) + .orElseThrow().toString(); + assertThat(matching(h2, condition)).as(javaRegex + " as Java: " + condition) + .containsExactlyElementsOf(java); + } + assertThat(h2.dialect().regexGenerator().generateRegularExpression("W", "a(")).as("not Java's") + .isEmpty(); + } + } + + private static List matching(H2Versions.Session h2, String condition) throws Exception { + List out = new ArrayList<>(); + try (var st = h2.statement(); ResultSet rs = st.executeQuery("SELECT W FROM WORDS WHERE " + condition + + " ORDER BY ID")) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2UsersAndRolesTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2UsersAndRolesTest.java new file mode 100644 index 0000000..2854330 --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2UsersAndRolesTest.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.h2.versions; + +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.Optional; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +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; + +/** + * H2 has users and roles on every version from 1.4.200 on, {@code IF [NOT] EXISTS} on their creation and drop, and no + * {@code WITH ADMIN OPTION} on a role's grant (a syntax error). The dialect is built from a live connection of each + * version: the user it creates, with an empty salt and hash no password hashes to, logs in with no password, takes a + * role that holds a privilege, reads what the role gives it once an administrator gives it a password, no longer once + * the role is revoked, and takes a privilege of its own; the admin option of a grant is left out; a second create and + * a drop of a missing one fail, IF [NOT] EXISTS spares the error. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class H2UsersAndRolesTest { + + private static final TableReference T = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "PUBLIC")), "T"); + + @ParameterizedTest(name = "h2 {0}") + @ValueSource(strings = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }) + void usersAndRoles(String version) throws Exception { + try (H2Versions.Session h2 = H2Versions.open(version)) { + h2.execute("CREATE TABLE PUBLIC.T(ID INT)"); + h2.execute("INSERT INTO PUBLIC.T VALUES (1)"); + DdlGenerator ddl = h2.dialect().ddlGenerator(); + assertThat(ddl.supportsUsers()).isTrue(); + assertThat(ddl.supportsRoles()).isTrue(); + + String createUser = ddl.createUser("RT_USER", false).orElseThrow(); + h2.execute(createUser); + assertRefused(h2, createUser, "a second user of the name"); + h2.execute(ddl.createUser("RT_USER", true).orElseThrow()); + for (String password : new String[] { "", "RT_USER", "sa" }) { + assertThatThrownBy(() -> h2.login("RT_USER", password).close()) + .as("no login with '" + password + "'").isInstanceOf(SQLException.class); + } + + String createRole = ddl.createRole("RT_ROLE", false).orElseThrow(); + h2.execute(createRole); + assertRefused(h2, createRole, "a second role of the name"); + h2.execute(ddl.createRole("RT_ROLE", true).orElseThrow()); + h2.execute(ddl.grantTablePrivilege("SELECT", T, "RT_ROLE", false)); + + String grant = ddl.grantRole("RT_ROLE", "RT_USER", true); + assertThat(grant).as("no admin option, which H2 has not").doesNotContain("ADMIN"); + assertRefused(h2, grant + " WITH ADMIN OPTION", "WITH ADMIN OPTION"); + h2.execute(grant); + h2.execute("ALTER USER \"RT_USER\" SET PASSWORD 'pw'"); + assertThat(count(h2)).as("the user reads with the role's privilege").isEqualTo(1); + + h2.execute(ddl.revokeRole("RT_ROLE", "RT_USER")); + assertThatThrownBy(() -> count(h2)).as("no longer once revoked").isInstanceOf(SQLException.class); + h2.execute(ddl.grantTablePrivilege("SELECT", T, "RT_USER", false)); + assertThat(count(h2)).as("a privilege of its own").isEqualTo(1); + h2.execute(ddl.revokeTablePrivilege("SELECT", T, "RT_USER")); + assertThatThrownBy(() -> count(h2)).as("revoked").isInstanceOf(SQLException.class); + + String dropRole = ddl.dropRole("RT_ROLE", false).orElseThrow(); + h2.execute(dropRole); + assertRefused(h2, dropRole, "a missing role"); + h2.execute(ddl.dropRole("RT_ROLE", true).orElseThrow()); + String dropUser = ddl.dropUser("RT_USER", false).orElseThrow(); + h2.execute(dropUser); + assertRefused(h2, dropUser, "a missing user"); + h2.execute(ddl.dropUser("RT_USER", true).orElseThrow()); + assertThatThrownBy(() -> h2.login("RT_USER", "pw").close()).as("dropped") + .isInstanceOf(SQLException.class); + } + } + + /** The rows of T as RT_USER reads them, logged in anew. */ + private static int count(H2Versions.Session h2) throws SQLException { + try (Connection c = h2.login("RT_USER", "pw"); Statement st = c.createStatement(); + ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM PUBLIC.T")) { + rs.next(); + return rs.getInt(1); + } + } + + private static void assertRefused(H2Versions.Session h2, String sql, String what) { + assertThatThrownBy(() -> h2.execute(sql)).as(what + ": " + sql).isInstanceOf(SQLException.class); + } +} diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2Versions.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2Versions.java new file mode 100644 index 0000000..357b5cc --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/versions/H2Versions.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.h2.versions; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.h2.H2Dialect; + +/** + * An H2 of a given version, in memory. H2 is embedded: each version is the jar the {@code h2-versions} profile copies + * into {@code target/h2-versions}, loaded in a class loader of its own, and the connection is that version's driver's; + * the dialect is built from it, as from a connection to a server. The H2 the module is built with, on the class path, + * is not seen. + */ +final class H2Versions { + + /** The lines of H2 the tests run on. */ + static final String[] VERSIONS = { "1.4.200", "2.0.206", "2.1.214", "2.2.224", "2.3.232" }; + + private static final AtomicInteger DATABASES = new AtomicInteger(); + + private H2Versions() { + } + + /** A connection to a database in memory of its own, of the H2 of the version, and the dialect built from it. */ + record Session(Connection connection, H2Dialect dialect, URLClassLoader loader, Driver driver, String url) + implements AutoCloseable { + + /** Another connection to the same database, as the user with the password. */ + Connection login(String user, String password) throws SQLException { + Properties props = new Properties(); + props.setProperty("user", user); + props.setProperty("password", password); + return driver.connect(url, props); + } + + Statement statement() throws SQLException { + return connection.createStatement(); + } + + /** The first column of each row, NULL as {@code null}. */ + List rows(String sql) throws SQLException { + List out = new ArrayList<>(); + try (Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } + + void execute(String sql) throws SQLException { + try (Statement st = connection.createStatement()) { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + @Override + public void close() throws SQLException, IOException { + try (loader; connection) { + // closes both + } + } + } + + static Session open(String version) throws Exception { + Path jar = Path.of("target", "h2-versions", "h2-" + version + ".jar"); + if (!Files.isRegularFile(jar)) { + throw new IllegalStateException(jar + " is missing: run with -Dintegration.docker=true, whose profile" + + " copies the jars of the H2 versions"); + } + URLClassLoader loader = new URLClassLoader(new URL[] { jar.toUri().toURL() }, + ClassLoader.getPlatformClassLoader()); + Driver driver = (Driver) Class.forName("org.h2.Driver", true, loader).getDeclaredConstructor().newInstance(); + Properties props = new Properties(); + props.setProperty("user", "sa"); + props.setProperty("password", ""); + String url = "jdbc:h2:mem:v" + DATABASES.incrementAndGet(); + Connection connection = driver.connect(url, props); + String reported = connection.getMetaData().getDatabaseProductVersion(); + if (!reported.startsWith(version)) { + connection.close(); + loader.close(); + throw new IllegalStateException("h2 " + version + " reports " + reported); + } + return new Session(connection, new H2Dialect(DialectInitData.fromConnection(connection)), loader, driver, + url); + } +}