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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions dialect/db/h2/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,72 @@
<version>${revision}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.daanse</groupId>
<artifactId>org.eclipse.daanse.sql.jdbc.record</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<!-- Version tests (versions package, -Dintegration.docker=true): the jar of each H2 version, each loaded in a
class loader of its own. H2 is embedded, so no container is needed. -->
<profile>
<id>h2-versions</id>
<activation>
<property>
<name>integration.docker</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.7.0</version>
<executions>
<execution>
<id>h2-versions</id>
<phase>generate-test-resources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/h2-versions</outputDirectory>
<artifactItems>
<artifactItem>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</artifactItem>
<artifactItem>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.0.206</version>
</artifactItem>
<artifactItem>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</artifactItem>
<artifactItem>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
</artifactItem>
<artifactItem>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -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')}.
*
* <p>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).
* <p>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<String> generateRegularExpression(String source, String javaRegex) {
Expand All @@ -55,26 +56,14 @@ public Optional<String> 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());
}
Expand Down Expand Up @@ -131,71 +120,106 @@ 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<String> 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<String> 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<String> generatePercentileCont(double percentile, boolean desc, String tableName,
String columnName) {
return java.util.Optional
.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<String> generateListAgg(CharSequence operand, boolean distinct, String separator,
String coalesce, String onOverflowTruncate, List<OrderedColumn> 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());
}

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -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);
}
}
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<BitOperation, String> 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));
}
}
}
}
Loading
Loading