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
19 changes: 19 additions & 0 deletions dialect/db/duckdb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,24 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<!-- Container tests: the DuckDB CLI of a given version, run in Docker. -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.21.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<environmentVariables>
<DOCKER_HOST>${env.DOCKER_HOST}</DOCKER_HOST>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -373,28 +373,38 @@ public java.util.Optional<String> loadFromDelimitedFile(
};
}

/**
* {@code STRING_AGG([DISTINCT] operand, 'separator' ORDER BY ...)}; without a separator DuckDB joins with a comma.
* A DISTINCT aggregate may only be ordered by its own argument ("ORDER BY expressions must appear in the argument
* list"): DISTINCT is kept where every order column is the operand, and left out where the list is ordered by
* another column. A quote in the separator is doubled.
*/
@Override
public java.util.Optional<String> generateListAgg(CharSequence operand, boolean distinct, String separator,
String coalesce, String onOverflowTruncate, List<OrderedColumn> columns) {
boolean ordered = columns != null && !columns.isEmpty();
StringBuilder buf = new StringBuilder(64);
buf.append("STRING_AGG");
buf.append("( ");
if (distinct && (columns == null || columns.isEmpty())) { // DISTINCT has error if we have ORDER BY for duckDb
buf.append("STRING_AGG(");
if (distinct && (!ordered || ordersByOperandOnly(operand, columns))) {
buf.append("DISTINCT ");
}
buf.append(operand);
if (separator != null) {
buf.append(", '").append(separator).append("' ");
buf.append(", '").append(separator.replace("'", "''")).append("'");
}

if (columns != null && !columns.isEmpty()) {
buf.append("ORDER BY ");
buf.append(buildOrderedColumnsClause(columns));
if (ordered) {
buf.append(" ORDER BY ").append(buildOrderedColumnsClause(columns));
}
buf.append(")");
// STRING_AGG(name, ', ' ORDER BY hire_date)
return java.util.Optional.of(buf.toString());
}

return java.util.Optional.of((buf).toString());
/** Whether every order column is the operand, as a name, a quoted name or a quoted name of its table. */
private boolean ordersByOperandOnly(CharSequence operand, List<OrderedColumn> columns) {
String op = operand.toString().trim();
return columns.stream()
.allMatch(c -> op.equals(c.columnName()) || op.equals(quoteIdentifier(c.columnName()))
|| (c.tableName() != null && op.equals(quoteIdentifier(c.tableName(), c.columnName()))));
}


Expand All @@ -417,33 +427,23 @@ public boolean supportsBitAggregation(BitOperation operation) {
return true; // DucDb supports all bit operations
}

/**
* {@code PERCENTILE_DISC(p) WITHIN GROUP (ORDER BY col [DESC])}, the standard form, which DuckDB reads; its own
* {@code quantile_disc(col, p)} takes no order, so a descending percentile came out ascending.
*/
@Override
public java.util.Optional<String> generatePercentileDisc(double percentile, boolean desc, String tableName,
String columnName) {
return java.util.Optional
.of((buildPercentileFunction("quantile_disc", percentile, desc, tableName, columnName)).toString());
.of(buildPercentileFunction("PERCENTILE_DISC", percentile, desc, tableName, columnName).toString());
}

/** {@code PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY col [DESC])}, as {@link #generatePercentileDisc}. */
@Override
public java.util.Optional<String> generatePercentileCont(double percentile, boolean desc, String tableName,
String columnName) {
return java.util.Optional
.of((buildPercentileFunction("quantile_cont", percentile, desc, tableName, columnName)).toString());
}

public StringBuilder buildPercentileFunction(String functionName, double percentile, boolean desc, String tableName,
String columnName) {
StringBuilder buf = new StringBuilder(64);
buf.append(functionName).append("(");
if (tableName != null) {
quoteIdentifier(buf, tableName, columnName);
} else {
quoteIdentifier(buf, columnName);
}
buf.append(", ");
buf.append(percentile);
buf.append(")");
return buf;
.of(buildPercentileFunction("PERCENTILE_CONT", percentile, desc, tableName, columnName).toString());
}

/** The n-th value of the group's rows in their order: an ordered list, its n-th element (V-82). */
Expand Down Expand Up @@ -483,6 +483,12 @@ public boolean supportsNthValue() {
return true;
}

/** The NULL values are left out of the list with {@code FILTER (WHERE v IS NOT NULL)}. */
@Override
public boolean supportsNthValueIgnoreNulls() {
return true;
}

@Override
public boolean supportsListAgg() {
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* 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.duckdb.container;

import static org.assertj.core.api.Assertions.assertThat;

import java.sql.JDBCType;
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.db.duckdb.DuckDbDialect;
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.CsvSource;

/**
* DuckDB adds no foreign key and no check to an existing table, in any version from 1.0 on, and adds a unique
* constraint only from 2.0 on, and then only while no other table refers to the table; so the dialect adds none of
* them later and declares them in {@code CREATE TABLE}. The CLI of each version runs what the dialect writes, in
* Docker, and the dialect is built for the version the CLI reports: the {@code CREATE TABLE} with a unique constraint,
* a check and a foreign key holds the rows that keep them and refuses those that break them; a foreign key keeps only
* the actions DuckDB knows, RESTRICT and NO ACTION, and leaves CASCADE out, which the server refuses; the
* {@code ALTER TABLE … ADD} forms are refused, the unique one from 2.0 on only with a table that refers to it.
*/
@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
class DuckDbAddConstraintTest {

private static final Optional<SchemaReference> MAIN = Optional.of(new SchemaReference(Optional.empty(), "main"));
private static final TableReference CUSTOMER = new TableReference(MAIN, "customer");
private static final TableReference ORDERS = new TableReference(MAIN, "orders");

@ParameterizedTest(name = "duckdb:{0} -> ADD UNIQUE later {1}")
@CsvSource({ "1.0.0, false", "1.1.3, false", "1.2.2, false", "1.3.2, false", "1.4.4, false", "1.5.6, false",
"2.0.0, true", "2.0.1, true" })
void addConstraint(String tag, boolean uniqueLater) {
DuckDbDialect dialect = DuckDbCli.dialect(tag);
DdlGenerator ddl = dialect.ddlGenerator();

assertThat(ddl.supportsAddForeignKeyConstraint()).as("supportsAddForeignKeyConstraint").isFalse();
assertThat(ddl.supportsAddUniqueConstraint()).as("supportsAddUniqueConstraint").isFalse();
assertThat(ddl.supportsAddCheckConstraint()).as("supportsAddCheckConstraint").isFalse();

// declared in CREATE TABLE, the constraints hold
String customer = ddl.createTable(CUSTOMER, List.of(column(CUSTOMER, "id", JDBCType.INTEGER),
column(CUSTOMER, "email", JDBCType.VARCHAR), column(CUSTOMER, "n", JDBCType.INTEGER)),
pk(CUSTOMER),
List.of(ddl.uniqueConstraintClause("uc_email", List.of("email")),
ddl.checkConstraintClause("ck_n", "\"n\" > 0")),
false);
String fk = ddl.foreignKeyClause("fk_orders_customer", List.of("cid"), CUSTOMER, List.of("id"), "RESTRICT",
"NO ACTION");
assertThat(fk).endsWith(" ON DELETE RESTRICT ON UPDATE NO ACTION");
String orders = ddl.createTable(ORDERS, List.of(column(ORDERS, "id", JDBCType.INTEGER),
column(ORDERS, "cid", JDBCType.INTEGER)), pk(ORDERS), List.of(fk), false);
String setup = customer + "; " + orders + "; INSERT INTO customer VALUES (1, 'a@x', 1), (2, 'b@x', 2);"
+ " INSERT INTO orders VALUES (10, 1), (11, NULL);";

DuckDbCli.Result kept = DuckDbCli.run(tag, setup + " SELECT 'customers ' || count(*) FROM customer;"
+ " SELECT 'orders ' || count(*) FROM orders;");
assertThat(kept.failed()).as(kept.err() + " in " + customer + "; " + orders).isFalse();
assertThat(kept.out()).as("the rows that keep the constraints").containsExactly("customers 2", "orders 2");

assertRefused(tag, setup + " INSERT INTO customer VALUES (3, 'a@x', 3);", "Constraint Error",
"a second email");
assertRefused(tag, setup + " INSERT INTO customer VALUES (3, 'c@x', 0);", "Constraint Error",
"n not above 0");
assertRefused(tag, setup + " INSERT INTO orders VALUES (12, 99);", "Constraint Error",
"an order of no customer");
assertRefused(tag, setup + " DELETE FROM customer WHERE id = 1;", "Constraint Error",
"a customer an order refers to");

// CASCADE is left out, which the server refuses
String cascade = ddl.foreignKeyClause("fk_c", List.of("cid"), CUSTOMER, List.of("id"), "CASCADE", "SET NULL");
assertThat(cascade).doesNotContain(" ON DELETE").doesNotContain(" ON UPDATE");
DuckDbCli.Result withoutCascade = DuckDbCli.run(tag, customer + "; CREATE TABLE r(id INTEGER, cid INTEGER, "
+ cascade + "); SELECT 'ok';");
assertThat(withoutCascade.failed()).as(withoutCascade.err() + " in " + cascade).isFalse();
assertRefused(tag, customer + "; CREATE TABLE r(cid INTEGER REFERENCES customer(id) ON DELETE CASCADE);",
"CASCADE", "ON DELETE CASCADE");

// ALTER TABLE … ADD: no foreign key and no check in any version
String plain = "CREATE TABLE customer(id INTEGER PRIMARY KEY, email VARCHAR, n INTEGER);"
+ " CREATE TABLE orders(id INTEGER, cid INTEGER);";
assertRefused(tag, plain + " " + ddl.addForeignKeyConstraint(ORDERS, "fk_orders_customer", List.of("cid"),
CUSTOMER, List.of("id"), null, null) + ";", "Not implemented", "ADD FOREIGN KEY");
assertRefused(tag, plain + " " + ddl.addCheckConstraint(CUSTOMER, "ck_n", "\"n\" > 0") + ";",
"Not implemented", "ADD CHECK");

// ALTER TABLE … ADD UNIQUE: from 2.0 on, and then only while no table refers to it
String addUnique = ddl.addUniqueConstraint(CUSTOMER, "uc_email", List.of("email")) + ";";
String referring = " CREATE TABLE r(cid INTEGER REFERENCES customer(id));";
if (uniqueLater) {
DuckDbCli.Result added = DuckDbCli.run(tag, plain + " INSERT INTO customer VALUES (1, 'a@x', 1); "
+ addUnique + " SELECT 'added';");
assertThat(added.failed()).as(added.err()).isFalse();
assertRefused(tag, plain + " " + addUnique + " INSERT INTO customer VALUES (1, 'a@x', 1), (2, 'a@x', 2);",
"Constraint Error", "the unique constraint added later holds");
assertRefused(tag, plain + referring + " " + addUnique, "Dependency Error",
"ADD UNIQUE to a table another refers to");
} else {
assertRefused(tag, plain + " " + addUnique, "Not implemented", "ADD UNIQUE before 2.0");
}
}

private static void assertRefused(String tag, String sql, String error, String what) {
DuckDbCli.Result r = DuckDbCli.run(tag, sql);
assertThat(r.failed()).as(what + " is refused: " + sql).isTrue();
assertThat(r.err()).as(what).contains(error);
}

private static PrimaryKeyRecord pk(TableReference table) {
return new PrimaryKeyRecord(table, List.of(new ColumnReference(Optional.of(table), "id")), Optional.empty());
}

private static ColumnDefinition column(TableReference table, String name, JDBCType type) {
return new ColumnDefinitionRecord(new ColumnReference(Optional.of(table), name),
new ColumnMetaDataRecord(type, type.getName(),
type == JDBCType.VARCHAR ? OptionalInt.of(50) : OptionalInt.empty(), OptionalInt.empty(),
OptionalInt.empty(), ColumnMetaData.Nullability.NULLABLE, OptionalInt.empty(),
Optional.empty(), Optional.empty(), ColumnMetaData.AutoIncrement.UNKNOWN,
ColumnMetaData.GeneratedColumn.UNKNOWN));
}
}
Original file line number Diff line number Diff line change
@@ -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.duckdb.container;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.LinkedHashMap;
import java.util.Map;

import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
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.ValueSource;

/**
* DuckDB has {@code bit_and}, {@code bit_or} and {@code bit_xor}, in every version from 1.0 on, and the dialect writes
* NAND, NOR and NXOR as their complement {@code ~(…)}. The CLI of each version runs what the dialect writes, in Docker,
* and the dialect is built for the version the CLI reports: every operation is offered and computes the right value,
* of an INTEGER column and of a BIGINT column past 32 bits, leaving out the NULL, per group, and NULL for a group of
* NULLs alone.
*/
@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
class DuckDbBitAggregationTest {

/**
* Group a: 14 = 1110, 11 = 1011, 7 = 0111 and a NULL; group b: 5 alone; group c: a NULL alone. The BIGINT column
* holds the same values shifted by 40 bits.
*/
private static final String SETUP = "CREATE TABLE flags(g VARCHAR, v INTEGER, w BIGINT);"
+ " INSERT INTO flags VALUES ('a', 14, 14::BIGINT << 40), ('a', 11, 11::BIGINT << 40), ('a', NULL, NULL),"
+ " ('a', 7, 7::BIGINT << 40), ('b', 5, 5::BIGINT << 40), ('c', NULL, NULL);";

/** AND = 0010, OR = 1111, XOR = 0010; NAND, NOR and NXOR are their bitwise complements. */
private static final Map<BitOperation, Long> EXPECTED = Map.of(BitOperation.AND, 2L, BitOperation.OR, 15L,
BitOperation.XOR, 2L, BitOperation.NAND, ~2L, BitOperation.NOR, ~15L, BitOperation.NXOR, ~2L);

@ParameterizedTest(name = "duckdb:{0}")
@ValueSource(strings = { "1.0.0", "1.1.3", "1.2.2", "1.3.2", "1.4.4", "1.5.6", "2.0.1" })
void bitAggregation(String tag) {
DuckDbDialect dialect = DuckDbCli.dialect(tag);

StringBuilder sql = new StringBuilder(SETUP);
Map<String, String> generated = new LinkedHashMap<>();
for (BitOperation op : BitOperation.values()) {
assertThat(dialect.supportsBitAggregation(op)).as(op + " supported").isTrue();
String v = dialect.generateBitAggregation(op, "v").orElseThrow();
String w = dialect.generateBitAggregation(op, "w").orElseThrow();
generated.put(op.name(), v);
sql.append(" SELECT '").append(op).append("', ").append(v).append(", ").append(w)
.append(" FROM flags WHERE g = 'a';");
sql.append(" SELECT '").append(op).append(" per group ' || g, COALESCE(CAST(").append(v)
.append(" AS VARCHAR), 'null') FROM flags GROUP BY g ORDER BY g;");
}

DuckDbCli.Result r = DuckDbCli.run(tag, sql.toString());
assertThat(r.failed()).as("every operation runs: " + r.err() + " in " + generated).isFalse();
Map<String, String> got = new LinkedHashMap<>();
for (String line : r.out()) {
int bar = line.indexOf('|');
got.put(line.substring(0, bar), line.substring(bar + 1));
}

for (BitOperation op : BitOperation.values()) {
long expected = EXPECTED.get(op);
long b = op == BitOperation.AND || op == BitOperation.OR || op == BitOperation.XOR ? 5L : ~5L;
assertThat(got.get(op.name())).as(op + ": " + generated.get(op.name()) + ", INTEGER and BIGINT")
.isEqualTo(expected + "|" + bigint(op));
assertThat(got.get(op + " per group a")).as(op + " per group").isEqualTo(Long.toString(expected));
assertThat(got.get(op + " per group b")).as(op + " of one value").isEqualTo(Long.toString(b));
assertThat(got.get(op + " per group c")).as(op + " of NULLs alone").isEqualTo("null");
}
}

/** The value of the operation on the BIGINT column: the values shifted by 40 bits. */
private static long bigint(BitOperation op) {
long and = 2L << 40, or = 15L << 40, xor = 2L << 40;
return switch (op) {
case AND -> and;
case OR -> or;
case XOR -> xor;
case NAND -> ~and;
case NOR -> ~or;
case NXOR -> ~xor;
};
}
}
Loading
Loading