diff --git a/dialect/db/duckdb/pom.xml b/dialect/db/duckdb/pom.xml
index 46af7aab..6682bb83 100644
--- a/dialect/db/duckdb/pom.xml
+++ b/dialect/db/duckdb/pom.xml
@@ -52,5 +52,24 @@
${project.version}
test
+
+
+ org.testcontainers
+ junit-jupiter
+ 1.21.4
+ test
+
+
+
+
+ maven-surefire-plugin
+
+
+ ${env.DOCKER_HOST}
+
+
+
+
+
diff --git a/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java b/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java
index 86b9fbd5..eca295e8 100644
--- a/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java
+++ b/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java
@@ -373,28 +373,38 @@ public java.util.Optional 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 generateListAgg(CharSequence operand, boolean distinct, String separator,
String coalesce, String onOverflowTruncate, List 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 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()))));
}
@@ -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 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 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). */
@@ -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;
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbAddConstraintTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbAddConstraintTest.java
new file mode 100644
index 00000000..1f51ea08
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbAddConstraintTest.java
@@ -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 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));
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbBitAggregationTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbBitAggregationTest.java
new file mode 100644
index 00000000..6c32d927
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbBitAggregationTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ */
+package org.eclipse.daanse.sql.dialect.db.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 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 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 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;
+ };
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbBulkLoadTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbBulkLoadTest.java
new file mode 100644
index 00000000..fa344d01
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbBulkLoadTest.java
@@ -0,0 +1,174 @@
+/*
+ * 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.nio.file.Path;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.eclipse.daanse.sql.dialect.api.generator.BulkLoadGenerator;
+import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
+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 loads a delimited file itself with {@code INSERT INTO t (cols) SELECT * FROM read_csv(…)}, in every version
+ * from 1.0 on. The CLI of each version runs the statement the dialect writes, in Docker, on files put into the
+ * container, and the dialect is built for the version the CLI reports. Files have the CSV importer's form: a line of
+ * the column names and a line of their SQL types before the data, the NULL literal {@code NULL}. Every value must
+ * arrive as the file has it, in the type of its column: a text of leading zeros or of a number stays the text, quoted
+ * values keep their delimiters and quotes, the NULL literal is NULL; with a semicolon, a tab or a quote as delimiter,
+ * a quote in the file's path and in the NULL literal, no line or one line before the data, a column of the table left
+ * to its default, and past the rows read to guess the types. A blank line is left out; a comment line of {@code #} is
+ * left out from 1.1 on, while 1.0 refuses the file, so the importer loads it row by row.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class DuckDbBulkLoadTest {
+
+ private static final Optional MAIN = Optional.of(new SchemaReference(Optional.empty(), "main"));
+
+ @ParameterizedTest(name = "duckdb:{0} -> comment lines left out {1}")
+ @CsvSource({ "1.0.0, false", "1.1.3, true", "1.2.2, true", "1.3.2, true", "1.4.4, true", "1.5.6, true",
+ "2.0.1, true" })
+ void bulkLoad(String tag, boolean commentsLeftOut) {
+ DuckDbDialect dialect = DuckDbCli.dialect(tag);
+ BulkLoadGenerator bulk = dialect.bulkLoadGenerator();
+ assertThat(bulk.supportsBulkLoad()).as("supportsBulkLoad").isTrue();
+
+ Map files = new LinkedHashMap<>();
+ StringBuilder sql = new StringBuilder();
+ Map expected = new LinkedHashMap<>();
+
+ // the importer's form, values the guessing of types could change, quoted values
+ files.put("/data/items.csv", "id,code,price,label,day,flag\n"
+ + "INTEGER,VARCHAR,DECIMAL(10,2),VARCHAR,DATE,SMALLINT\n"
+ + "1,007,1.50,\"a, b\",2024-01-05,1\n"
+ + "2,NULL,2.00,\"say \"\"hi\"\"\",NULL,0\n"
+ + "3,0042,NULL,1.50,2024-02-29,NULL\n");
+ String load = load(bulk, "items", List.of("id", "code", "price", "label", "day", "flag"), "/data/items.csv",
+ ',', 2, "NULL");
+ assertThat(load).isEqualTo("INSERT INTO \"main\".\"items\" (\"id\", \"code\", \"price\", \"label\", \"day\","
+ + " \"flag\") SELECT * FROM read_csv('/data/items.csv', header=false, skip=2, delim=',',"
+ + " nullstr='NULL')");
+ sql.append("CREATE TABLE items(id INTEGER, code VARCHAR, price DECIMAL(10,2), label VARCHAR, day DATE,"
+ + " flag SMALLINT); ").append(load).append(";");
+ read(sql, "items", "id || '|' || " + shown("code") + " || '|' || " + shown("price") + " || '|' || label"
+ + " || '|' || " + shown("day") + " || '|' || " + shown("flag"), "id");
+ expected.put("items", "1|007|1.50|a, b|2024-01-05|1;2|null|2.00|say \"hi\"|null|0;3|0042|null|1.50|2024-02-29|null");
+
+ // a semicolon, a tab and a quote as delimiter
+ files.put("/data/semi.csv", "a;b\nINTEGER;VARCHAR\n1;it's\n2;x\n");
+ table(sql, bulk, "semi", "/data/semi.csv", ';', 2, "NULL");
+ expected.put("semi", "1|it's;2|x");
+ files.put("/data/tab.csv", "a\tb\nINTEGER\tVARCHAR\n1\tp q\n");
+ table(sql, bulk, "tab", "/data/tab.csv", '\t', 2, "NULL");
+ expected.put("tab", "1|p q");
+ files.put("/data/quote.csv", "a'b\nINTEGER'VARCHAR\n1'x\n2'NULL\n");
+ table(sql, bulk, "quote", "/data/quote.csv", '\'', 2, "NULL");
+ expected.put("quote", "1|x;2|null");
+
+ // a quote in the path, other NULL literals, a quote among them
+ files.put("/data/o'brien dir/f.csv", "a,b\nINTEGER,VARCHAR\n5,y\n");
+ table(sql, bulk, "path", "/data/o'brien dir/f.csv", ',', 2, "NULL");
+ expected.put("path", "5|y");
+ files.put("/data/backslash.csv", "a,b\nINTEGER,VARCHAR\n1,\\N\n2,NULL\n");
+ table(sql, bulk, "backslash", "/data/backslash.csv", ',', 2, "\\N");
+ expected.put("backslash", "1|null;2|NULL");
+ files.put("/data/na.csv", "a,b\nINTEGER,VARCHAR\n1,n'a\n2,z\n");
+ table(sql, bulk, "na", "/data/na.csv", ',', 2, "n'a");
+ expected.put("na", "1|null;2|z");
+
+ // no line and one line before the data
+ files.put("/data/none.csv", "1,x\n2,y\n");
+ table(sql, bulk, "none", "/data/none.csv", ',', 0, "NULL");
+ expected.put("none", "1|x;2|y");
+ files.put("/data/one.csv", "a,b\n1,x\n");
+ table(sql, bulk, "one", "/data/one.csv", ',', 1, "NULL");
+ expected.put("one", "1|x");
+
+ // a column of the table not in the file keeps its default
+ files.put("/data/extra.csv", "a,b\nINTEGER,VARCHAR\n1,x\n");
+ sql.append(" CREATE TABLE extra(a INTEGER, b VARCHAR, loaded VARCHAR DEFAULT 'yes'); ")
+ .append(load(bulk, "extra", List.of("a", "b"), "/data/extra.csv", ',', 2, "NULL")).append(";");
+ read(sql, "extra", "a || '|' || b || '|' || loaded", "a");
+ expected.put("extra", "1|x|yes");
+
+ // a text first past the rows read to guess the types
+ files.put("/data/big.csv", "a,b\nINTEGER,VARCHAR\n"
+ + IntStream.range(0, 30000).mapToObj(i -> i + "," + i).collect(Collectors.joining("\n"))
+ + "\n30000,abc\n");
+ sql.append(" CREATE TABLE big(a INTEGER, b VARCHAR); ")
+ .append(load(bulk, "big", List.of("a", "b"), "/data/big.csv", ',', 2, "NULL")).append(";")
+ .append(" SELECT 'big=' || count(*) || '|' || max(a) || '|' || (SELECT b FROM big WHERE a = 30000)")
+ .append(" FROM big;");
+ expected.put("big", "30001|30000|abc");
+
+ // a blank line
+ files.put("/data/blank.csv", "a,b\nINTEGER,VARCHAR\n1,x\n\n2,y\n");
+ table(sql, bulk, "blank", "/data/blank.csv", ',', 2, "NULL");
+ expected.put("blank", "1|x;2|y");
+
+ DuckDbCli.Result r = DuckDbCli.run(tag, sql.toString(), files);
+ assertThat(r.failed()).as("every file loads: " + r.err()).isFalse();
+ Map got = new LinkedHashMap<>();
+ for (String line : r.out()) {
+ int eq = line.indexOf('=');
+ got.put(line.substring(0, eq), line.substring(eq + 1));
+ }
+ assertThat(got).as("the rows of every file").containsExactlyEntriesOf(expected);
+
+ // a comment line: left out from 1.1 on; 1.0 refuses the file
+ String comment = "a,b\nINTEGER,VARCHAR\n1,x\n# a comment\n2,y\n";
+ StringBuilder commented = new StringBuilder();
+ table(commented, bulk, "commented", "/data/commented.csv", ',', 2, "NULL");
+ DuckDbCli.Result c = DuckDbCli.run(tag, commented.toString(), Map.of("/data/commented.csv", comment));
+ if (commentsLeftOut) {
+ assertThat(c.failed()).as(c.err()).isFalse();
+ assertThat(c.out()).as("the comment line left out").containsExactly("commented=1|x;2|y");
+ } else {
+ assertThat(c.failed()).as("1.0 refuses a file with a comment line").isTrue();
+ assertThat(c.err()).contains("sniffing");
+ }
+ }
+
+ /** A table of an INTEGER a and a VARCHAR b, the file loaded into it, and its rows read. */
+ private static void table(StringBuilder sql, BulkLoadGenerator bulk, String name, String file, char delimiter,
+ int skip, String nullLiteral) {
+ sql.append(" CREATE TABLE \"").append(name).append("\"(a INTEGER, b VARCHAR); ")
+ .append(load(bulk, name, List.of("a", "b"), file, delimiter, skip, nullLiteral)).append(";");
+ read(sql, name, "a || '|' || " + shown("b"), "a");
+ }
+
+ private static String load(BulkLoadGenerator bulk, String table, List columns, String file,
+ char delimiter, int skip, String nullLiteral) {
+ return bulk.loadFromDelimitedFile(new TableReference(MAIN, table), columns, Path.of(file), delimiter, skip,
+ nullLiteral).orElseThrow();
+ }
+
+ /** One line, {@code name=} and the rows, each as the expression gives it, joined with ; in their order. */
+ private static void read(StringBuilder sql, String name, String row, String order) {
+ sql.append(" SELECT '").append(name).append("=' || string_agg(").append(row).append(", ';' ORDER BY ")
+ .append(order).append(") FROM \"").append(name).append("\";");
+ }
+
+ /** The CLI writes NULL as an empty field in 1.0 and as NULL later: a NULL is shown as null. */
+ private static String shown(String column) {
+ return "COALESCE(CAST(" + column + " AS VARCHAR), 'null')";
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbCli.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbCli.java
new file mode 100644
index 00000000..a6290a96
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbCli.java
@@ -0,0 +1,98 @@
+/*
+ * 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 java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.OutputFrame.OutputType;
+import org.testcontainers.containers.startupcheck.StartupCheckStrategy;
+import org.testcontainers.images.builder.Transferable;
+
+import com.github.dockerjava.api.DockerClient;
+
+/**
+ * The DuckDB CLI of a given version, run in Docker ({@code duckdb/duckdb:}, the CLI alone, without a shell).
+ * DuckDB is embedded and serves no connection: each call runs its statements in a database in memory and exits, so
+ * every call sets up its own tables. The CLI stops at the first statement that fails.
+ */
+final class DuckDbCli {
+
+ private static final Pattern VERSION = Pattern.compile("v(\\d+)\\.(\\d+)\\.\\d+");
+
+ /** What a call printed, and how it exited. */
+ record Result(long exitCode, List out, String err) {
+
+ /**
+ * Whether a statement failed: the CLI of 1.2.0 to 1.2.2 exits with 0 on an error too, so its message on
+ * stderr counts as well.
+ */
+ boolean failed() {
+ return exitCode != 0 || err.contains("Error:");
+ }
+ }
+
+ private DuckDbCli() {
+ }
+
+ /**
+ * Runs the statements and gives the lines of their rows, one value per line ({@code -list}, no header), without
+ * blank lines; a NULL is an empty line in 1.0 and NULL later.
+ */
+ static Result run(String tag, String sql) {
+ return run(tag, sql, Map.of());
+ }
+
+ /** {@link #run(String, String)} with files put into the container first, each at its absolute path. */
+ static Result run(String tag, String sql, Map files) {
+ try (GenericContainer> duck = new GenericContainer<>("duckdb/duckdb:" + tag)
+ .withCommand("/duckdb", "-list", "-noheader", "-c", sql).withStartupCheckStrategy(new Exited())) {
+ files.forEach((path, content) -> duck.withCopyToContainer(
+ Transferable.of(content.getBytes(StandardCharsets.UTF_8)), path));
+ duck.start();
+ long exitCode = duck.getCurrentContainerInfo().getState().getExitCodeLong();
+ List out = duck.getLogs(OutputType.STDOUT).lines().filter(l -> !l.isBlank()).toList();
+ return new Result(exitCode, out, duck.getLogs(OutputType.STDERR));
+ }
+ }
+
+ /** The version the CLI of the tag reports, checked against the tag: {@code v1.2.2} for {@code 1.2.2}. */
+ static DuckDbDialect dialect(String tag) {
+ Result r = run(tag, "SELECT version();");
+ String version = r.out().get(0);
+ Matcher m = VERSION.matcher(version);
+ if (r.failed() || !m.matches() || !version.equals("v" + tag)) {
+ throw new IllegalStateException("duckdb:" + tag + " reports " + r.out() + r.err());
+ }
+ return new DuckDbDialect(DialectInitData.ansiDefaults().withVersion(Integer.parseInt(m.group(1)),
+ Integer.parseInt(m.group(2))));
+ }
+
+ /** Started once the container has exited, whatever its exit code: a failed statement is a result too. */
+ private static final class Exited extends StartupCheckStrategy {
+
+ Exited() {
+ withTimeout(Duration.ofMinutes(2));
+ }
+
+ @Override
+ public StartupStatus checkStartupState(DockerClient dockerClient, String containerId) {
+ return "exited".equals(getCurrentState(dockerClient, containerId).getStatus()) ? StartupStatus.SUCCESSFUL
+ : StartupStatus.NOT_YET_KNOWN;
+ }
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbGroupingSetsTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbGroupingSetsTest.java
new file mode 100644
index 00000000..1426c7d1
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbGroupingSetsTest.java
@@ -0,0 +1,65 @@
+/*
+ * 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.List;
+
+import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * DuckDB has {@code GROUPING SETS}, {@code ROLLUP}, {@code CUBE} and {@code GROUPING()} in every version from 1.0 on.
+ * DuckDB is embedded and serves no connection: the CLI of each version runs the statements in Docker, and the dialect
+ * is built for the version the CLI reports. On every version {@code supportsGroupingSets()} says yes, and the
+ * statements give a row per grouping set, its total and its {@code GROUPING()} bits.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class DuckDbGroupingSetsTest {
+
+ private static final String SETUP = "CREATE TABLE sales(region VARCHAR, product VARCHAR, amount INT);"
+ + " INSERT INTO sales VALUES ('EU', 'A', 10), ('EU', 'B', 20), ('US', 'A', 30);";
+
+ /** The CLI writes NULL as an empty field in 1.0 and as NULL later: a total's key is written as *. */
+ private static final String KEYS = "COALESCE(region, '*'), COALESCE(product, '*')";
+
+ @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 groupingSets(String tag) {
+ DuckDbDialect dialect = DuckDbCli.dialect(tag);
+
+ assertThat(dialect.supportsGroupingSets()).as("supportsGroupingSets").isTrue();
+
+ String grouping = dialect.functionGenerator().generateGrouping("region") + ", "
+ + dialect.functionGenerator().generateGrouping("product");
+ assertThat(rows(tag, SETUP + " SELECT " + KEYS + ", SUM(amount), " + grouping + " FROM sales"
+ + " GROUP BY GROUPING SETS ((region, product), (region), ()) ORDER BY 1, 2;"))
+ .as("GROUPING SETS, with GROUPING()").containsExactly("*|*|60|1|1", "EU|*|30|0|1", "EU|A|10|0|0",
+ "EU|B|20|0|0", "US|*|30|0|1", "US|A|30|0|0");
+
+ assertThat(rows(tag, SETUP + " SELECT " + KEYS + ", SUM(amount) FROM sales"
+ + " GROUP BY ROLLUP (region, product) ORDER BY 1, 2;"))
+ .as("ROLLUP").containsExactly("*|*|60", "EU|*|30", "EU|A|10", "EU|B|20", "US|*|30", "US|A|30");
+
+ assertThat(rows(tag, SETUP + " SELECT " + KEYS + ", SUM(amount) FROM sales"
+ + " GROUP BY CUBE (region, product) ORDER BY 1, 2;"))
+ .as("CUBE, a total for each product too").containsExactly("*|*|60", "*|A|40", "*|B|20", "EU|*|30",
+ "EU|A|10", "EU|B|20", "US|*|30", "US|A|30");
+ }
+
+ private static List rows(String tag, String sql) {
+ DuckDbCli.Result r = DuckDbCli.run(tag, sql);
+ assertThat(r.failed()).as(r.err()).isFalse();
+ return r.out();
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbListAggTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbListAggTest.java
new file mode 100644
index 00000000..4f1e7b25
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbListAggTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
+import org.eclipse.daanse.sql.model.sql.NullsOrder;
+import org.eclipse.daanse.sql.model.sql.OrderedColumn;
+import org.eclipse.daanse.sql.model.sql.SortDirection;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * DuckDB lists the values of a group with {@code STRING_AGG([DISTINCT] x, 's' ORDER BY …)}, in every version from 1.0
+ * on. The CLI of each version runs the lists the dialect writes, in Docker, and the dialect is built for the version
+ * the CLI reports: each list must come out in the order asked for, the NULLs of an order column first or last as
+ * asked, without the NULL values, with any separator, a quote too, of a column of any type and per group. DISTINCT is
+ * kept with an order by the value itself; with an order by another column DuckDB refuses DISTINCT ("ORDER BY
+ * expressions must appear in the argument list"), and the dialect leaves it out.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class DuckDbListAggTest {
+
+ /** Group a: alice 20, bob 30, bob 10, a NULL name of 40; group b: dave 5. */
+ private static final String SETUP = "CREATE TABLE emp(dept VARCHAR, name VARCHAR, salary INT);"
+ + " INSERT INTO emp VALUES ('a', 'bob', 30), ('a', NULL, 40), ('a', 'alice', 20), ('a', 'bob', 10),"
+ + " ('b', 'dave', 5);";
+
+ @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 listAgg(String tag) {
+ DuckDbDialect dialect = DuckDbCli.dialect(tag);
+ assertThat(dialect.supportsListAgg()).as("supportsListAgg").isTrue();
+
+ Map lists = new LinkedHashMap<>();
+ lists.put("by value", list(dialect, "name", false, ", ", order("name", SortDirection.ASC)));
+ lists.put("by another column", list(dialect, "name", false, ", ", order("salary", SortDirection.DESC)));
+ lists.put("by a column of the table", list(dialect, "name", false, ", ",
+ List.of(new OrderedColumn("name", "emp", SortDirection.ASC))));
+ lists.put("DISTINCT", list(dialect, "name", true, ",", List.of()));
+ lists.put("DISTINCT by value", list(dialect, "name", true, ",", order("name", SortDirection.ASC)));
+ lists.put("DISTINCT by another column", list(dialect, "name", true, ",", order("salary", SortDirection.ASC)));
+ lists.put("no separator", list(dialect, "name", false, null, order("name", SortDirection.ASC)));
+ lists.put("a quote", list(dialect, "name", false, "'", order("name", SortDirection.ASC)));
+ lists.put("a backslash", list(dialect, "name", false, "\\", order("name", SortDirection.ASC)));
+ lists.put("an INT column", list(dialect, "salary", false, ",", order("salary", SortDirection.ASC)));
+ lists.put("NULLS FIRST", list(dialect, "salary", false, ",",
+ List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), Optional.of(NullsOrder.FIRST)),
+ new OrderedColumn("salary", null, SortDirection.ASC))));
+ lists.put("NULLS LAST", list(dialect, "salary", false, ",",
+ List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), Optional.of(NullsOrder.LAST)),
+ new OrderedColumn("salary", null, SortDirection.ASC))));
+
+ StringBuilder sql = new StringBuilder(SETUP);
+ lists.forEach((label, agg) -> sql.append(" SELECT '").append(label).append("=' || ").append(agg)
+ .append(" FROM emp WHERE dept = 'a';"));
+ String perDept = list(dialect, "name", false, ",", order("name", SortDirection.ASC));
+ sql.append(" SELECT 'per group ' || dept || '=' || ").append(perDept)
+ .append(" FROM emp GROUP BY dept ORDER BY dept;");
+
+ DuckDbCli.Result r = DuckDbCli.run(tag, sql.toString());
+ assertThat(r.failed()).as("every list runs: " + r.err() + " in " + lists).isFalse();
+ Map got = new LinkedHashMap<>();
+ for (String line : r.out()) {
+ int eq = line.indexOf('=');
+ got.put(line.substring(0, eq), line.substring(eq + 1));
+ }
+
+ assertThat(got.get("by value")).as("ordered by the value, the NULL left out").isEqualTo("alice, bob, bob");
+ assertThat(got.get("by another column")).as("ordered by another column").isEqualTo("bob, alice, bob");
+ assertThat(got.get("by a column of the table")).as("a column of the table").isEqualTo("alice, bob, bob");
+ assertThat(sorted(got.get("DISTINCT"))).as("DISTINCT without an order").containsExactly("alice", "bob");
+ assertThat(got.get("DISTINCT by value")).as("DISTINCT with an order by the value: both kept")
+ .isEqualTo("alice,bob");
+ assertThat(got.get("DISTINCT by another column")).as("DISTINCT left out with an order by another column")
+ .isEqualTo("bob,alice,bob");
+ assertThat(got.get("no separator")).as("no separator is a comma").isEqualTo("alice,bob,bob");
+ assertThat(got.get("a quote")).as("a quote as separator").isEqualTo("alice'bob'bob");
+ assertThat(got.get("a backslash")).as("a backslash as separator").isEqualTo("alice\\bob\\bob");
+ assertThat(got.get("an INT column")).as("an INT column").isEqualTo("10,20,30,40");
+ assertThat(got.get("NULLS FIRST")).as("NULLS FIRST, then a second column").isEqualTo("40,20,10,30");
+ assertThat(got.get("NULLS LAST")).as("NULLS LAST, then a second column").isEqualTo("20,10,30,40");
+ assertThat(got.get("per group a")).as("per group").isEqualTo("alice,bob,bob");
+ assertThat(got.get("per group b")).as("per group").isEqualTo("dave");
+
+ DuckDbCli.Result refused = DuckDbCli.run(tag,
+ SETUP + " SELECT STRING_AGG(DISTINCT name, ',' ORDER BY salary) FROM emp;");
+ assertThat(refused.failed()).as("DISTINCT ordered by another column is refused").isTrue();
+ assertThat(refused.err()).contains("ORDER BY expressions must appear in the argument list");
+ }
+
+ private static List order(String column, SortDirection direction) {
+ return List.of(new OrderedColumn(column, null, direction));
+ }
+
+ private static String list(DuckDbDialect dialect, String operand, boolean distinct, String separator,
+ List columns) {
+ return dialect.generateListAgg(operand, distinct, separator, null, null, columns).orElseThrow();
+ }
+
+ private static List sorted(String list) {
+ return Arrays.stream(list.split(",")).sorted().toList();
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbNthValueContainerTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbNthValueContainerTest.java
new file mode 100644
index 00000000..9089c620
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbNthValueContainerTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ */
+package org.eclipse.daanse.sql.dialect.db.duckdb.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
+import org.eclipse.daanse.sql.model.sql.NullsOrder;
+import org.eclipse.daanse.sql.model.sql.OrderedColumn;
+import org.eclipse.daanse.sql.model.sql.SortDirection;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * DuckDB gives the n-th value of a group as the n-th element of its ordered list,
+ * {@code list_extract(list(v ORDER BY …) [FILTER (WHERE v IS NOT NULL)], n)}, in every version from 1.0 on: an
+ * aggregate over the rows of the group, not the window {@code NTH_VALUE … OVER} (V-82). The CLI of each version runs
+ * what the dialect writes, in Docker, and the dialect is built for the version the CLI reports: the n-th value must
+ * follow the order asked for, ascending, descending, NULLs of an order column first or last, a column named with its
+ * table; it counts the NULL values or leaves them out as asked; n below 1 is 1; past the end it is NULL; and it is
+ * per group.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class DuckDbNthValueContainerTest {
+
+ /** Group a in the order of o: NULL, 20, 30, NULL, 50; group b: 7; group c: a NULL o of 9, then 8. */
+ private static final String SETUP = "CREATE TABLE t(g VARCHAR, o INT, v INT);"
+ + " INSERT INTO t VALUES ('a', 3, 30), ('a', 1, NULL), ('a', 5, 50), ('a', 2, 20), ('a', 4, NULL),"
+ + " ('b', 1, 7), ('c', NULL, 9), ('c', 1, 8);";
+
+ @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 nthValue(String tag) {
+ DuckDbDialect dialect = DuckDbCli.dialect(tag);
+ assertThat(dialect.supportsNthValue()).as("supportsNthValue").isTrue();
+ assertThat(dialect.supportsNthValueIgnoreNulls()).as("supportsNthValueIgnoreNulls").isTrue();
+
+ List byO = List.of(new OrderedColumn("o", null, SortDirection.ASC));
+ List byODesc = List.of(new OrderedColumn("o", null, SortDirection.DESC));
+ Map nth = new LinkedHashMap<>();
+ nth.put("1st", nth(dialect, false, 1, byO));
+ nth.put("1st ignoring NULLs", nth(dialect, true, 1, byO));
+ nth.put("2nd", nth(dialect, false, 2, byO));
+ nth.put("2nd ignoring NULLs", nth(dialect, true, 2, byO));
+ nth.put("5th", nth(dialect, false, 5, byO));
+ nth.put("3rd ignoring NULLs", nth(dialect, true, 3, byO));
+ nth.put("4th ignoring NULLs, past the end", nth(dialect, true, 4, byO));
+ nth.put("6th, past the end", nth(dialect, false, 6, byO));
+ nth.put("0th is the 1st", nth(dialect, true, 0, byO));
+ nth.put("no n is the 1st", nth(dialect, true, null, byO));
+ nth.put("1st descending", nth(dialect, false, 1, byODesc));
+ nth.put("2nd descending ignoring NULLs", nth(dialect, true, 2, byODesc));
+ nth.put("1st by a column of the table", nth(dialect, true, 1,
+ List.of(new OrderedColumn("o", "t", SortDirection.ASC))));
+
+ StringBuilder sql = new StringBuilder(SETUP);
+ nth.forEach((label, agg) -> sql.append(" SELECT '").append(label).append("', ").append(shown(agg))
+ .append(" FROM t WHERE g = 'a';"));
+ nullsOrder(sql, dialect, "NULLS FIRST", NullsOrder.FIRST);
+ nullsOrder(sql, dialect, "NULLS LAST", NullsOrder.LAST);
+ sql.append(" SELECT 'per group ' || g, ").append(shown(nth(dialect, true, 1, byO)))
+ .append(" FROM t GROUP BY g ORDER BY g;");
+
+ DuckDbCli.Result r = DuckDbCli.run(tag, sql.toString());
+ assertThat(r.failed()).as("every n-th value runs: " + r.err() + " in " + nth).isFalse();
+ Map got = new LinkedHashMap<>();
+ for (String line : r.out()) {
+ int bar = line.indexOf('|');
+ got.put(line.substring(0, bar), line.substring(bar + 1));
+ }
+
+ assertThat(got.get("1st")).as("the NULLs counted: " + nth.get("1st")).isEqualTo("null");
+ assertThat(got.get("1st ignoring NULLs")).as(nth.get("1st ignoring NULLs")).isEqualTo("20");
+ assertThat(got.get("2nd")).isEqualTo("20");
+ assertThat(got.get("2nd ignoring NULLs")).isEqualTo("30");
+ assertThat(got.get("5th")).isEqualTo("50");
+ assertThat(got.get("3rd ignoring NULLs")).isEqualTo("50");
+ assertThat(got.get("4th ignoring NULLs, past the end")).isEqualTo("null");
+ assertThat(got.get("6th, past the end")).isEqualTo("null");
+ assertThat(got.get("0th is the 1st")).isEqualTo("20");
+ assertThat(got.get("no n is the 1st")).isEqualTo("20");
+ assertThat(got.get("1st descending")).isEqualTo("50");
+ assertThat(got.get("2nd descending ignoring NULLs")).isEqualTo("30");
+ assertThat(got.get("1st by a column of the table")).isEqualTo("20");
+ assertThat(got.get("NULLS FIRST")).as("the row of a NULL order first").isEqualTo("9");
+ assertThat(got.get("NULLS LAST")).as("the row of a NULL order last").isEqualTo("8");
+ assertThat(got.get("per group a")).isEqualTo("20");
+ assertThat(got.get("per group b")).isEqualTo("7");
+ assertThat(got.get("per group c")).isEqualTo("8");
+ }
+
+ /** The first value of group c, its order column NULL in one row, the NULLs of o first or last. */
+ private static void nullsOrder(StringBuilder sql, DuckDbDialect dialect, String label, NullsOrder nulls) {
+ String agg = nth(dialect, false, 1,
+ List.of(new OrderedColumn("o", null, Optional.of(SortDirection.ASC), Optional.of(nulls))));
+ sql.append(" SELECT '").append(label).append("', ").append(shown(agg)).append(" FROM t WHERE g = 'c';");
+ }
+
+ private static String nth(DuckDbDialect dialect, boolean ignoreNulls, Integer n, List columns) {
+ return dialect.generateNthValueAgg("v", ignoreNulls, n, columns).orElseThrow();
+ }
+
+ /** The CLI writes NULL as an empty field in 1.0 and as NULL later: a NULL is shown as null. */
+ private static String shown(String agg) {
+ return "COALESCE(CAST(" + agg + " AS VARCHAR), 'null')";
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbPercentileTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbPercentileTest.java
new file mode 100644
index 00000000..c9581ed4
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbPercentileTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * DuckDB has {@code PERCENTILE_DISC} and {@code PERCENTILE_CONT … WITHIN GROUP (ORDER BY …)}, in every version from 1.0
+ * on. The CLI of each version runs the percentiles the dialect writes, in Docker, and the dialect is built for the
+ * version the CLI reports: each must give the right value, ascending and descending, of a column named with its table
+ * or without, at the ends of the range too, leaving out the NULL, and per group.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class DuckDbPercentileTest {
+
+ /** 10, 20, 30, 40 and a NULL that every aggregate leaves out in group a; 5 alone in group b. */
+ private static final String SETUP = "CREATE TABLE nums(g VARCHAR, v INT);"
+ + " INSERT INTO nums VALUES ('a', 30), ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5);";
+
+ @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 percentile(String tag) {
+ DuckDbDialect dialect = DuckDbCli.dialect(tag);
+ assertThat(dialect.supportsPercentileDisc()).as("supportsPercentileDisc").isTrue();
+ assertThat(dialect.supportsPercentileCont()).as("supportsPercentileCont").isTrue();
+
+ Map percentiles = new LinkedHashMap<>();
+ percentiles.put("disc 0.5", dialect.generatePercentileDisc(0.5, false, "nums", "v").orElseThrow());
+ percentiles.put("disc 0.5 desc", dialect.generatePercentileDisc(0.5, true, "nums", "v").orElseThrow());
+ percentiles.put("disc 0.25 desc", dialect.generatePercentileDisc(0.25, true, null, "v").orElseThrow());
+ percentiles.put("disc 0", dialect.generatePercentileDisc(0, false, "nums", "v").orElseThrow());
+ percentiles.put("disc 1", dialect.generatePercentileDisc(1, false, "nums", "v").orElseThrow());
+ percentiles.put("cont 0.5", dialect.generatePercentileCont(0.5, false, "nums", "v").orElseThrow());
+ percentiles.put("cont 0.25", dialect.generatePercentileCont(0.25, false, null, "v").orElseThrow());
+ percentiles.put("cont 0.25 desc", dialect.generatePercentileCont(0.25, true, "nums", "v").orElseThrow());
+ percentiles.put("cont 1", dialect.generatePercentileCont(1, true, "nums", "v").orElseThrow());
+
+ StringBuilder sql = new StringBuilder(SETUP);
+ percentiles.forEach((label, p) -> sql.append(" SELECT '").append(label).append("', ").append(p)
+ .append(" FROM nums WHERE g = 'a';"));
+ sql.append(" SELECT 'per group ' || g, ").append(percentiles.get("cont 0.5"))
+ .append(" FROM nums GROUP BY g ORDER BY g;");
+
+ DuckDbCli.Result r = DuckDbCli.run(tag, sql.toString());
+ assertThat(r.failed()).as("every percentile runs: " + r.err() + " in " + percentiles).isFalse();
+ Map got = new LinkedHashMap<>();
+ for (String line : r.out()) {
+ int bar = line.indexOf('|');
+ got.put(line.substring(0, bar), Double.parseDouble(line.substring(bar + 1)));
+ }
+
+ assertThat(got.get("disc 0.5")).as(percentiles.get("disc 0.5")).isEqualTo(20);
+ assertThat(got.get("disc 0.5 desc")).as("descending: " + percentiles.get("disc 0.5 desc")).isEqualTo(30);
+ assertThat(got.get("disc 0.25 desc")).as("descending, the column alone").isEqualTo(40);
+ assertThat(got.get("disc 0")).as("the least").isEqualTo(10);
+ assertThat(got.get("disc 1")).as("the greatest").isEqualTo(40);
+ assertThat(got.get("cont 0.5")).as(percentiles.get("cont 0.5")).isEqualTo(25);
+ assertThat(got.get("cont 0.25")).as("the column alone").isEqualTo(17.5);
+ assertThat(got.get("cont 0.25 desc")).as("descending: " + percentiles.get("cont 0.25 desc"))
+ .isEqualTo(32.5);
+ assertThat(got.get("cont 1")).as("descending, the end: the least").isEqualTo(10);
+ assertThat(got.get("per group a")).as("per group").isEqualTo(25);
+ assertThat(got.get("per group b")).as("per group, one value").isEqualTo(5);
+ }
+}
diff --git a/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbRenameTest.java b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbRenameTest.java
new file mode 100644
index 00000000..f4adf2da
--- /dev/null
+++ b/dialect/db/duckdb/src/test/java/org/eclipse/daanse/sql/dialect/db/duckdb/container/DuckDbRenameTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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.Optional;
+
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator;
+import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
+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;
+
+/**
+ * DuckDB renames a table ({@code ALTER TABLE … RENAME TO}) and a column ({@code ALTER TABLE … RENAME COLUMN}), and
+ * renames neither an index nor a constraint, in every version from 1.0 on: up to 1.5 it says "Not implemented", from 2.0
+ * it reads no such statement. The CLI of each version runs what the dialect writes, in Docker, and the dialect is
+ * built for the version the CLI reports: a table and a column it renames keep their rows under the new name, and the
+ * old name is gone; a table with an index, or a column of one, is refused with a "Dependency Error", as the dialect
+ * says; an index and a constraint it renames not, and the server refuses the statement.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class DuckDbRenameTest {
+
+ private static final String SETUP = "CREATE TABLE emp(id INT PRIMARY KEY, name VARCHAR,"
+ + " CONSTRAINT ck_id CHECK (id > 0)); INSERT INTO emp VALUES (1, 'ann'), (2, 'bob');";
+
+ private static final TableReference EMP = new TableReference(
+ Optional.of(new SchemaReference(Optional.empty(), "main")), "emp", TableReference.TYPE_TABLE);
+
+ @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 rename(String tag) {
+ DuckDbDialect dialect = DuckDbCli.dialect(tag);
+ DdlGenerator ddl = dialect.ddlGenerator();
+
+ assertThat(ddl.supportsRenameTable()).as("supportsRenameTable").isTrue();
+ assertThat(ddl.supportsRenameColumn()).as("supportsRenameColumn").isTrue();
+ assertThat(ddl.supportsRenameIndex()).as("supportsRenameIndex").isFalse();
+ assertThat(ddl.supportsRenameConstraint()).as("supportsRenameConstraint").isFalse();
+
+ // a table and a column, renamed, keep their rows; the old names are gone
+ String renameColumn = ddl.renameColumn(EMP, "name", "full_name");
+ assertThat(renameColumn).isEqualTo("ALTER TABLE \"main\".\"emp\" RENAME COLUMN \"name\" TO \"full_name\"");
+ String renameTable = ddl.renameTable(EMP, "staff");
+ assertThat(renameTable).isEqualTo("ALTER TABLE \"main\".\"emp\" RENAME TO \"staff\"");
+ DuckDbCli.Result renamed = DuckDbCli.run(tag, SETUP + " " + renameColumn + "; " + renameTable + ";"
+ + " SELECT id || '=' || full_name FROM main.staff ORDER BY id;"
+ + " SELECT 'tables ' || string_agg(table_name, ',' ORDER BY table_name)"
+ + " FROM information_schema.tables WHERE table_schema = 'main';"
+ + " SELECT 'columns ' || string_agg(column_name, ',' ORDER BY ordinal_position)"
+ + " FROM information_schema.columns WHERE table_name = 'staff';");
+ assertThat(renamed.failed()).as(renamed.err()).isFalse();
+ assertThat(renamed.out()).as("the rows under the new names, the old names gone")
+ .containsExactly("1=ann", "2=bob", "tables staff", "columns id,full_name");
+
+ // a table with an index, and a column of it, are refused: the dependency the dialect's javadoc names
+ String index = " CREATE INDEX ix_name ON emp(name);";
+ assertRefused(tag, SETUP + index + " " + renameTable + ";", "Dependency Error", "a table with an index");
+ assertRefused(tag, SETUP + index + " " + ddl.renameColumn(EMP, "name", "nm") + ";", "Dependency Error",
+ "a column with an index");
+
+ // an index and a constraint: not written, and the server refuses the statement
+ assertThat(ddl.renameIndex("ix_name", "ix_full_name", EMP)).as("no index rename").isNull();
+ assertThat(ddl.renameConstraint(EMP, "ck_id", "ck_positive")).as("no constraint rename").isNull();
+ assertRefused(tag, SETUP + index + " ALTER INDEX ix_name RENAME TO ix_full_name;", "Error",
+ "ALTER INDEX … RENAME");
+ assertRefused(tag, SETUP + " ALTER TABLE emp RENAME CONSTRAINT ck_id TO ck_positive;", "Error",
+ "RENAME CONSTRAINT");
+ }
+
+ 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").isTrue();
+ assertThat(r.err()).as(what).contains(error);
+ }
+}
diff --git a/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java b/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java
index 23e9d3fc..ed1e2dc8 100644
--- a/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java
+++ b/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java
@@ -33,6 +33,7 @@
import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode;
import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition;
import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.SequenceDefinition;
import org.eclipse.daanse.sql.model.schema.ColumnDefinition;
import org.eclipse.daanse.sql.model.schema.ColumnMetaData;
@@ -42,7 +43,9 @@
import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming;
import org.eclipse.daanse.sql.dialect.api.generator.KnownFunction;
import org.eclipse.daanse.sql.dialect.api.generator.StatementHint;
+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.eclipse.daanse.sql.dialect.db.common.AbstractJdbcDialect;
import org.eclipse.daanse.sql.dialect.db.common.DialectUtil;
@@ -208,8 +211,10 @@ public java.util.Optional upsert(UpsertSpec spec, java.util.List
if (values == null || values.size() != spec.insertColumns().size()) {
throw new IllegalArgumentException("values must match insertColumns in length");
}
+ // HOLDLOCK: without it two connections upserting the same new key at once both find no row and both
+ // insert, and one fails on the primary key (Msg 2627, on 2017 and 2019 in a database run)
StringBuilder sb = new StringBuilder("MERGE INTO ").append(qualified(spec.target()))
- .append(" AS T USING (VALUES (");
+ .append(" WITH (HOLDLOCK) AS T USING (VALUES (");
for (int i = 0; i < values.size(); i++) {
if (i > 0)
sb.append(", ");
@@ -318,13 +323,18 @@ public String createSchema(String schemaName, boolean ifNotExists) {
+ "') EXEC('CREATE SCHEMA " + quoteIdentifier(schemaName) + "')";
}
+ /**
+ * With {@code ifExists}, guarded by {@code OBJECT_ID(…, 'U')}, which reads before 2016 too. The name it reads is
+ * the quoted one, as a literal: a name of a quote broke the statement, one of a dot or a blank was read as
+ * another name.
+ */
@Override
public String dropTable(String schemaName, String tableName, boolean ifExists) {
+ String quoted = quoteIdentifier(schemaName, tableName);
if (!ifExists) {
- return "DROP TABLE " + quoteIdentifier(schemaName, tableName);
+ return "DROP TABLE " + quoted;
}
- return "IF OBJECT_ID('" + (schemaName == null ? "" : schemaName + ".") + tableName
- + "', 'U') IS NOT NULL DROP TABLE " + quoteIdentifier(schemaName, tableName);
+ return "IF OBJECT_ID(" + nLiteral(quoted) + ", N'U') IS NOT NULL DROP TABLE " + quoted;
}
@Override
@@ -486,28 +496,33 @@ yield new StringBuilder("DATEFROMPARTS(").append(arguments.get(0)).append(", ").
};
}
+ /**
+ * No percentile aggregate: SQL Server has {@code PERCENTILE_DISC} and {@code PERCENTILE_CONT … WITHIN GROUP} only
+ * as window functions, which "must have an OVER clause" (Msg 10753, on 2017 to 2025); a window in a grouped query
+ * runs over the groups, not over the rows of one group, so it is no answer either. The measure is refused, as the
+ * n-th value is.
+ */
@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());
+ return java.util.Optional.empty();
}
+ /** No percentile aggregate, as {@link #generatePercentileDisc}. */
@Override
public java.util.Optional generatePercentileCont(double percentile, boolean desc, String tableName,
String columnName) {
- return java.util.Optional
- .of((buildPercentileFunction("PERCENTILE_CONT", percentile, desc, tableName, columnName)).toString());
+ return java.util.Optional.empty();
}
@Override
public boolean supportsPercentileDisc() {
- return true;
+ return false;
}
@Override
public boolean supportsPercentileCont() {
- return true;
+ return false;
}
/**
@@ -536,26 +551,38 @@ public java.util.Optional generateListAgg(CharSequence operand, boolean
// declined, so the engine names the refusal instead of sending SQL the server rejects
return java.util.Optional.empty();
}
+ // the operand as NVARCHAR(MAX): of a type of a length, the list stops at 8000 bytes (Msg 9829); a number
+ // and a Unicode text are written whole too
StringBuilder buf = new StringBuilder(64);
- buf.append("STRING_AGG");
- buf.append("( ");
- buf.append(operand);
- buf.append(", '");
- if (separator != null) {
- buf.append(separator);
- } else {
- buf.append(", ");
- }
- buf.append("'");
- buf.append(")");
+ buf.append("STRING_AGG(CONVERT(NVARCHAR(MAX), ").append(operand).append("), N'")
+ .append((separator != null ? separator : ", ").replace("'", "''")).append("')");
if (columns != null && !columns.isEmpty()) {
- buf.append(" WITHIN GROUP (ORDER BY ");
- buf.append(buildOrderedColumnsClause(columns));
- buf.append(")");
+ buf.append(" WITHIN GROUP (ORDER BY ").append(orderedColumns(columns)).append(")");
}
- // STRING_AGG(CONVERT (NVARCHAR (MAX), EmailAddress), ';') WITHIN GROUP (ORDER
- // BY EmailAddress ASC)
- return java.util.Optional.of((buf).toString());
+ return java.util.Optional.of(buf.toString());
+ }
+
+ /**
+ * The order of the list. SQL Server knows no {@code NULLS FIRST/LAST} ("Incorrect syntax near 'NULLS'"): where
+ * a column asks for one, its NULLs are ranked with the dialect's CASE.
+ */
+ private CharSequence orderedColumns(List columns) {
+ StringBuilder buf = new StringBuilder(64);
+ for (OrderedColumn c : columns) {
+ if (!buf.isEmpty()) {
+ buf.append(", ");
+ }
+ String expr = c.tableName() != null ? quoteIdentifier(c.tableName(), c.columnName())
+ : quoteIdentifier(c.columnName());
+ boolean ascending = c.sortDirection().map(d -> d != SortDirection.DESC).orElse(true);
+ if (c.nullsOrder().isPresent()) {
+ buf.append(generateOrderItem(expr, true, ascending, c.nullsOrder().get() == NullsOrder.LAST));
+ } else {
+ buf.append(expr);
+ c.sortDirection().ifPresent(d -> buf.append(' ').append(d.name()));
+ }
+ }
+ return buf;
}
/**
@@ -591,6 +618,11 @@ public String createTrigger(String triggerName, org.eclipse.daanse.sql.model.sch
if (body == null || body.isBlank()) {
throw new IllegalArgumentException("body must not be blank for SQL Server CREATE TRIGGER");
}
+ if (whenCondition != null && !whenCondition.isBlank()) {
+ // left out, the trigger fired for every row the condition did not hold of too (database run 2017 to 2025)
+ throw new UnsupportedOperationException("SQL Server has no WHEN condition on a trigger; write the"
+ + " condition into the trigger's body, over the inserted and deleted rows: " + whenCondition);
+ }
StringBuilder sb = new StringBuilder("CREATE TRIGGER ");
sb.append(quoteIdentifier(triggerName));
sb.append(" ON ").append(qualified(table));
@@ -824,6 +856,22 @@ public String revokeExecute(String schemaName, String routineName, boolean isFun
+ quoteIdentifier(grantee);
}
+ /**
+ * SQL Server knows no {@code CREATE SEQUENCE IF NOT EXISTS} ("Incorrect syntax near the keyword 'IF'"): with
+ * {@code ifNotExists} the statement is guarded by the schema's sequences, as a user is by the principals. A
+ * schema of {@code null} is the user's default one.
+ */
+ @Override
+ public Optional createSequence(SequenceDefinition seq, boolean ifNotExists) {
+ Optional create = super.createSequence(seq, false);
+ if (!ifNotExists || create.isEmpty()) {
+ return create;
+ }
+ String schema = seq.schemaName() != null ? "SCHEMA_ID(" + nLiteral(seq.schemaName()) + ")" : "SCHEMA_ID()";
+ return Optional.of("IF NOT EXISTS (SELECT 1 FROM sys.sequences WHERE name = " + nLiteral(seq.name())
+ + " AND schema_id = " + schema + ") " + create.get());
+ }
+
/** SQL Server: {@code EXEC sp_rename 'schema.seq', 'new'}. */
@Override
public Optional renameSequence(String schemaName, String name, String newName) {
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsTest.java
index 7c09aa4e..357265ae 100644
--- a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsTest.java
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsTest.java
@@ -78,7 +78,7 @@ void output_star() {
void merge_into_using_values() {
MergeGenerator.UpsertSpec spec = upsertSpec(table("dbo", "USERS"), "ID", "NAME");
String sql = d.mergeGenerator().upsert(spec, List.of("1", "'foo'")).orElseThrow();
- assertThat(sql).contains("MERGE INTO \"dbo\".\"USERS\" AS T USING (VALUES (1, 'foo')) AS S")
+ assertThat(sql).contains("MERGE INTO \"dbo\".\"USERS\" WITH (HOLDLOCK) AS T USING (VALUES (1, 'foo')) AS S")
.contains("WHEN MATCHED THEN UPDATE SET T.\"NAME\" = S.\"NAME\"")
.contains("WHEN NOT MATCHED THEN INSERT");
}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlCreateFunctionTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlCreateFunctionTest.java
new file mode 100644
index 00000000..21dacc17
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlCreateFunctionTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server creates a function with {@code CREATE FUNCTION s.f (@a INT) RETURNS INT AS body}, and replaces one with
+ * {@code CREATE OR ALTER FUNCTION} from 2016 on, so in every version Docker serves, 2017 to 2025. The dialect is built
+ * from a live connection: the function it creates is called; created again without {@code orReplace} it is refused as
+ * there; with it the new body is taken and the function stays the same object, so a right granted on it is kept, where
+ * a drop and a new create would lose it. A function of no parameters, an inline function of a table and a parameter
+ * named with its {@code @} are written as SQL Server reads them; a function of an OUT parameter, of no return type or
+ * of a body in another language is not written.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlCreateFunctionTest {
+
+ private static final String DOUBLED = "BEGIN RETURN @a * 2 END";
+ private static final String TRIPLED = "BEGIN RETURN @a * 3 END";
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void createFunction(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ st.execute("CREATE TABLE nums(v INT)");
+ st.execute("INSERT INTO nums VALUES (1), (2), (3)");
+
+ String create = dialect.createFunction(twice(DOUBLED), false).orElseThrow();
+ assertThat(create).isEqualTo("CREATE FUNCTION \"dbo\".\"twice\"(@a INT) RETURNS INT AS " + DOUBLED);
+ st.execute(create);
+ assertThat(value(st, "SELECT dbo.twice(21)")).as("called").isEqualTo("42");
+ assertThatThrownBy(() -> st.execute(create)).as("created again without orReplace")
+ .isInstanceOf(SQLException.class).hasMessageContaining("already an object named");
+
+ // a right granted on it, and the object it is
+ st.execute("CREATE USER reader WITHOUT LOGIN");
+ st.execute("GRANT EXECUTE ON dbo.twice TO reader");
+ String objectId = value(st, "SELECT OBJECT_ID('dbo.twice')");
+
+ String replace = dialect.createFunction(twice(TRIPLED), true).orElseThrow();
+ assertThat(replace).as("orReplace").startsWith("CREATE OR ALTER FUNCTION \"dbo\".\"twice\"(@a INT)");
+ st.execute(replace);
+ assertThat(value(st, "SELECT dbo.twice(21)")).as("the new body taken").isEqualTo("63");
+ assertThat(value(st, "SELECT OBJECT_ID('dbo.twice')")).as("the same object").isEqualTo(objectId);
+ assertThat(rows(st, "SELECT permission_name FROM sys.database_permissions"
+ + " WHERE major_id = OBJECT_ID('dbo.twice') AND grantee_principal_id = USER_ID('reader')"))
+ .as("the right granted on it kept").containsExactly("EXECUTE");
+ st.execute(dialect.createFunction(twice(DOUBLED), true).orElseThrow());
+ assertThat(value(st, "SELECT dbo.twice(21)")).as("replaced again").isEqualTo("42");
+
+ // no parameters; an inline function of a table; a parameter named with its @
+ st.execute(dialect.createFunction(new RoutineDefinition("dbo", "answer", List.of(), "INT", "tsql",
+ "BEGIN RETURN 42 END"), false).orElseThrow());
+ assertThat(value(st, "SELECT dbo.answer()")).as("no parameters").isEqualTo("42");
+ st.execute(dialect.createFunction(new RoutineDefinition("dbo", "above",
+ List.of(RoutineParameter.in("@min", "INT")), "TABLE", "tsql",
+ "RETURN (SELECT v FROM dbo.nums WHERE v > @min)"), false).orElseThrow());
+ assertThat(rows(st, "SELECT v FROM dbo.above(1) ORDER BY v")).as("an inline function of a table")
+ .containsExactly("2", "3");
+
+ // not written: an OUT parameter, no return type, another language
+ assertThat(dialect.createFunction(new RoutineDefinition("dbo", "f",
+ List.of(new RoutineParameter("a", ParameterMode.OUT, "INT")), "INT", "tsql", DOUBLED), false))
+ .as("an OUT parameter").isEmpty();
+ assertThat(dialect.createFunction(new RoutineDefinition("dbo", "f",
+ List.of(RoutineParameter.in("a", "INT")), null, "tsql", DOUBLED), false))
+ .as("no return type").isEmpty();
+ assertThat(dialect.createFunction(new RoutineDefinition("dbo", "f",
+ List.of(RoutineParameter.in("a", "INT")), "INT", "plpgsql", DOUBLED), false))
+ .as("another language").isEmpty();
+
+ // dropped by its signature
+ st.execute(dialect.dropFunction(new RoutineSignature("dbo", "twice", List.of("INT")), false)
+ .orElseThrow());
+ assertThat(value(st, "SELECT COALESCE(CAST(OBJECT_ID('dbo.twice') AS VARCHAR), 'gone')"))
+ .as("dropped").isEqualTo("gone");
+ }
+ }
+ }
+
+ private static RoutineDefinition twice(String body) {
+ return new RoutineDefinition("dbo", "twice", List.of(RoutineParameter.in("a", "INT")), "INT", "tsql", body);
+ }
+
+ private static String value(Statement st, String sql) throws SQLException {
+ try (ResultSet rs = st.executeQuery(sql)) {
+ assertThat(rs.next()).isTrue();
+ return rs.getString(1);
+ }
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ while (rs.next()) {
+ out.add(rs.getString(1));
+ }
+ }
+ return out;
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlCreateProcedureTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlCreateProcedureTest.java
new file mode 100644
index 00000000..04d812c0
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlCreateProcedureTest.java
@@ -0,0 +1,141 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server creates a procedure with {@code CREATE PROCEDURE s.p @n INT, @total INT OUTPUT AS body}, and replaces one
+ * with {@code CREATE OR ALTER PROCEDURE} from 2016 on, so in every version Docker serves, 2017 to 2025. The dialect is
+ * built from a live connection: the procedure it creates is called, an OUT and an INOUT parameter, both OUTPUT ones,
+ * carrying their values back; created again without {@code orReplace} it is refused as there; with it the new body is
+ * taken and the procedure stays the same object, so a right granted on it is kept. A procedure of no parameters that
+ * returns rows is written as SQL Server reads it; a procedure of a body in another language is not written.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlCreateProcedureTest {
+
+ private static final String ADD = "BEGIN SET @total = @total + @n; SET @doubled = @n * 2 END";
+ private static final String ADD_TWICE = "BEGIN SET @total = @total + 2 * @n; SET @doubled = @n * 2 END";
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void createProcedure(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ st.execute("CREATE TABLE nums(v INT)");
+ st.execute("INSERT INTO nums VALUES (1), (2), (3)");
+
+ String create = dialect.createProcedure(addTo(ADD), false).orElseThrow();
+ assertThat(create).isEqualTo("CREATE PROCEDURE \"dbo\".\"add_to\" @n INT, @total INT OUTPUT,"
+ + " @doubled INT OUTPUT AS " + ADD);
+ st.execute(create);
+ assertThat(call(c)).as("called: the INOUT and the OUT value back").containsExactly(42, 4);
+ assertThatThrownBy(() -> st.execute(create)).as("created again without orReplace")
+ .isInstanceOf(SQLException.class).hasMessageContaining("already an object named");
+
+ // a right granted on it, and the object it is
+ st.execute("CREATE USER runner WITHOUT LOGIN");
+ st.execute("GRANT EXECUTE ON dbo.add_to TO runner");
+ String objectId = value(st, "SELECT OBJECT_ID('dbo.add_to')");
+
+ String replace = dialect.createProcedure(addTo(ADD_TWICE), true).orElseThrow();
+ assertThat(replace).as("orReplace").startsWith("CREATE OR ALTER PROCEDURE \"dbo\".\"add_to\" @n INT");
+ st.execute(replace);
+ assertThat(call(c)).as("the new body taken").containsExactly(44, 4);
+ assertThat(value(st, "SELECT OBJECT_ID('dbo.add_to')")).as("the same object").isEqualTo(objectId);
+ assertThat(rows(st, "SELECT permission_name FROM sys.database_permissions"
+ + " WHERE major_id = OBJECT_ID('dbo.add_to') AND grantee_principal_id = USER_ID('runner')"))
+ .as("the right granted on it kept").containsExactly("EXECUTE");
+
+ // no parameters, rows returned
+ String listing = dialect.createProcedure(new RoutineDefinition("dbo", "list_nums", List.of(), null,
+ "tsql", "SELECT v FROM dbo.nums ORDER BY v"), false).orElseThrow();
+ assertThat(listing)
+ .isEqualTo("CREATE PROCEDURE \"dbo\".\"list_nums\" AS SELECT v FROM dbo.nums ORDER BY v");
+ st.execute(listing);
+ assertThat(rows(st, "EXEC dbo.list_nums")).as("no parameters, rows returned")
+ .containsExactly("1", "2", "3");
+
+ // not written: a body in another language
+ assertThat(dialect.createProcedure(new RoutineDefinition("dbo", "p", List.of(), null, "plpgsql",
+ "BEGIN END"), false)).as("another language").isEmpty();
+
+ // dropped by its signature
+ st.execute(dialect.dropProcedure(new RoutineSignature("dbo", "add_to", List.of("INT", "INT", "INT")),
+ false).orElseThrow());
+ assertThat(value(st, "SELECT COALESCE(CAST(OBJECT_ID('dbo.add_to') AS VARCHAR), 'gone')"))
+ .as("dropped").isEqualTo("gone");
+ }
+ }
+ }
+
+ /** add_to(@n IN, @total INOUT, @doubled OUT). */
+ private static RoutineDefinition addTo(String body) {
+ return new RoutineDefinition("dbo", "add_to", List.of(RoutineParameter.in("n", "INT"),
+ new RoutineParameter("total", ParameterMode.INOUT, "INT"),
+ new RoutineParameter("doubled", ParameterMode.OUT, "INT")), null, "tsql", body);
+ }
+
+ /** Calls add_to with n = 2 and total = 40; the total and the doubled n it gives back. */
+ private static List call(Connection c) throws SQLException {
+ try (CallableStatement cs = c.prepareCall("{call dbo.add_to(?, ?, ?)}")) {
+ cs.setInt(1, 2);
+ cs.setInt(2, 40);
+ cs.registerOutParameter(2, Types.INTEGER);
+ cs.registerOutParameter(3, Types.INTEGER);
+ cs.execute();
+ return List.of(cs.getInt(2), cs.getInt(3));
+ }
+ }
+
+ private static String value(Statement st, String sql) throws SQLException {
+ try (ResultSet rs = st.executeQuery(sql)) {
+ assertThat(rs.next()).isTrue();
+ return rs.getString(1);
+ }
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ while (rs.next()) {
+ out.add(rs.getString(1));
+ }
+ }
+ return out;
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropFunctionIfExistsTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropFunctionIfExistsTest.java
new file mode 100644
index 00000000..2cbf50b0
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropFunctionIfExistsTest.java
@@ -0,0 +1,97 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server drops a function only if it exists, {@code DROP FUNCTION IF EXISTS s.f}, from 2016 on, so in every version
+ * Docker serves, 2017 to 2025. The dialect is built from a live connection: it writes IF EXISTS, names the function by
+ * its name alone, for SQL Server has no overloads, and the function it drops is gone; a second drop with IF EXISTS
+ * passes, without it fails (Msg 3701). IF EXISTS spares no other error: a function a schema-bound view uses is not
+ * dropped, and the drop of a name a procedure holds fails ("is a procedure") and leaves it.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlDropFunctionIfExistsTest {
+
+ private static final RoutineSignature TWICE = new RoutineSignature("dbo", "twice", List.of("INT"));
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void dropFunctionIfExists(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ String create = dialect.createFunction(new RoutineDefinition("dbo", "twice",
+ List.of(RoutineParameter.in("a", "INT")), "INT", "tsql", "BEGIN RETURN @a * 2 END"), false)
+ .orElseThrow();
+
+ String drop = dialect.dropFunction(TWICE, true).orElseThrow();
+ assertThat(drop).as("IF EXISTS, the name alone").isEqualTo("DROP FUNCTION IF EXISTS \"dbo\".\"twice\"");
+ String plain = dialect.dropFunction(TWICE, false).orElseThrow();
+ assertThat(plain).isEqualTo("DROP FUNCTION \"dbo\".\"twice\"");
+
+ st.execute(create);
+ assertThat(exists(st, "twice", "FN")).as("created").isTrue();
+ st.execute(drop);
+ assertThat(exists(st, "twice", "FN")).as("dropped").isFalse();
+ st.execute(drop);
+ assertThatThrownBy(() -> st.execute(plain)).as("a missing one without IF EXISTS")
+ .isInstanceOf(SQLException.class).hasMessageContaining("does not exist");
+
+ // a function a schema-bound view uses (the function bound too, which the dialect does not write):
+ // IF EXISTS spares no other error
+ st.execute("CREATE FUNCTION dbo.twice(@a INT) RETURNS INT WITH SCHEMABINDING AS BEGIN RETURN @a * 2 END");
+ st.execute("CREATE VIEW dbo.doubled WITH SCHEMABINDING AS SELECT dbo.twice(21) AS v");
+ assertThatThrownBy(() -> st.execute(drop)).as("used by a schema-bound view")
+ .isInstanceOf(SQLException.class).hasMessageContaining("referenced by");
+ assertThat(exists(st, "twice", "FN")).as("left").isTrue();
+ st.execute("DROP VIEW dbo.doubled");
+ st.execute(drop);
+ assertThat(exists(st, "twice", "FN")).as("dropped once the view is").isFalse();
+
+ // a procedure of the name: IF EXISTS does not pass over it, the drop fails and leaves it
+ st.execute("CREATE PROCEDURE dbo.twice AS SELECT 1");
+ assertThatThrownBy(() -> st.execute(drop)).as("a procedure of the name")
+ .isInstanceOf(SQLException.class).hasMessageContaining("is a procedure");
+ assertThat(exists(st, "twice", "P")).as("the procedure of the name left").isTrue();
+ }
+ }
+ }
+
+ private static boolean exists(Statement st, String name, String type) throws SQLException {
+ try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM sys.objects WHERE schema_id = SCHEMA_ID('dbo')"
+ + " AND name = '" + name + "' AND type = '" + type + "'")) {
+ rs.next();
+ return rs.getInt(1) > 0;
+ }
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropIfExistsTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropIfExistsTest.java
new file mode 100644
index 00000000..2c749af9
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropIfExistsTest.java
@@ -0,0 +1,129 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Optional;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.eclipse.daanse.sql.model.schema.TableReference;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server drops a table, a view, an index and a schema only if it exists from 2016 on, so in every version Docker
+ * serves, 2017 to 2025. The dialect is built from a live connection: each drop it writes with {@code ifExists} drops
+ * what is there and passes on what is not, where the drop without it fails; a table whose name holds a quote, a dot or
+ * a blank is dropped too, and a view of the table's name is no table and is left. IF EXISTS spares no other error: a
+ * schema that holds a table is not dropped.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlDropIfExistsTest {
+
+ private static final SchemaReference DBO = new SchemaReference(Optional.empty(), "dbo");
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void dropIfExists(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ DdlGenerator ddl = dialect.ddlGenerator();
+
+ assertThat(dialect.supportsDropTableIfExists()).as("supportsDropTableIfExists").isTrue();
+ assertThat(dialect.supportsDropViewIfExists()).as("supportsDropViewIfExists").isTrue();
+ assertThat(dialect.supportsDropIndexIfExists()).as("supportsDropIndexIfExists").isTrue();
+ assertThat(dialect.supportsDropSchemaIfExists()).as("supportsDropSchemaIfExists").isTrue();
+
+ // DROP TABLE, of plain names and of names holding a quote, a dot, a blank
+ for (String name : List.of("items", "it's", "a.b", "order details")) {
+ String quoted = dialect.quoteIdentifier("dbo", name);
+ String drop = dialect.dropTable("dbo", name, true);
+ st.execute("CREATE TABLE " + quoted + " (id INT)");
+ assertThat(exists(st, name, "U")).as("created: " + name).isTrue();
+ st.execute(drop);
+ assertThat(exists(st, name, "U")).as("dropped: " + drop).isFalse();
+ st.execute(drop);
+ assertThatThrownBy(() -> st.execute(dialect.dropTable("dbo", name, false)))
+ .as("a missing one without IF EXISTS: " + name).isInstanceOf(SQLException.class);
+ }
+ st.execute("CREATE TABLE dbo.base (id INT)");
+ st.execute("CREATE VIEW dbo.notatable AS SELECT id FROM dbo.base");
+ st.execute(dialect.dropTable("dbo", "notatable", true));
+ assertThat(exists(st, "notatable", "V")).as("a view of the name is no table, and left").isTrue();
+
+ // DROP VIEW
+ TableReference view = new TableReference(Optional.of(DBO), "notatable", TableReference.TYPE_VIEW);
+ String dropView = ddl.dropView(view, true);
+ assertThat(dropView).isEqualTo("DROP VIEW IF EXISTS \"dbo\".\"notatable\"");
+ st.execute(dropView);
+ assertThat(exists(st, "notatable", "V")).as("the view dropped").isFalse();
+ st.execute(dropView);
+ assertThatThrownBy(() -> st.execute(ddl.dropView(view, false))).as("a missing view without IF EXISTS")
+ .isInstanceOf(SQLException.class);
+
+ // DROP INDEX … ON table
+ TableReference base = new TableReference(Optional.of(DBO), "base", TableReference.TYPE_TABLE);
+ st.execute("CREATE INDEX ix_id ON dbo.base (id)");
+ String dropIndex = ddl.dropIndex("ix_id", base, true);
+ assertThat(dropIndex).isEqualTo("DROP INDEX IF EXISTS \"ix_id\" ON \"dbo\".\"base\"");
+ st.execute(dropIndex);
+ assertThat(count(st, "SELECT COUNT(*) FROM sys.indexes WHERE name = 'ix_id'")).as("the index dropped")
+ .isZero();
+ st.execute(dropIndex);
+ assertThatThrownBy(() -> st.execute(ddl.dropIndex("ix_id", base, false)))
+ .as("a missing index without IF EXISTS").isInstanceOf(SQLException.class);
+
+ // DROP SCHEMA: an empty one dropped; one that holds a table not
+ st.execute(dialect.createSchema("rt", true));
+ String dropSchema = dialect.dropSchema("rt", true, false);
+ assertThat(dropSchema).isEqualTo("DROP SCHEMA IF EXISTS \"rt\"");
+ st.execute("CREATE TABLE rt.t (id INT)");
+ assertThatThrownBy(() -> st.execute(dropSchema)).as("a schema that holds a table")
+ .isInstanceOf(SQLException.class).hasMessageContaining("referenced by object");
+ st.execute("DROP TABLE rt.t");
+ st.execute(dropSchema);
+ assertThat(count(st, "SELECT COUNT(*) FROM sys.schemas WHERE name = 'rt'")).as("the schema dropped")
+ .isZero();
+ st.execute(dropSchema);
+ assertThatThrownBy(() -> st.execute(dialect.dropSchema("rt", false, false)))
+ .as("a missing schema without IF EXISTS").isInstanceOf(SQLException.class);
+ }
+ }
+ }
+
+ private static boolean exists(Statement st, String name, String type) throws SQLException {
+ return count(st, "SELECT COUNT(*) FROM sys.objects WHERE schema_id = SCHEMA_ID('dbo') AND name = N'"
+ + name.replace("'", "''") + "' AND type = '" + type + "'") > 0;
+ }
+
+ private static int count(Statement st, String sql) throws SQLException {
+ try (ResultSet rs = st.executeQuery(sql)) {
+ rs.next();
+ return rs.getInt(1);
+ }
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropProcedureIfExistsTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropProcedureIfExistsTest.java
new file mode 100644
index 00000000..ea08a4c6
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropProcedureIfExistsTest.java
@@ -0,0 +1,92 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server drops a procedure only if it exists, {@code DROP PROCEDURE IF EXISTS s.p}, from 2016 on, so in every
+ * version Docker serves, 2017 to 2025. The dialect is built from a live connection: it writes IF EXISTS, names the
+ * procedure by its name alone, for SQL Server has no overloads, and the procedure it drops is gone; a second drop with
+ * IF EXISTS passes, without it fails (Msg 3701). IF EXISTS spares no other error: the drop of a name a function holds
+ * fails and leaves it. The trigger procedures' drop by schema and name writes the same statement.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlDropProcedureIfExistsTest {
+
+ private static final RoutineSignature ADD_TO = new RoutineSignature("dbo", "add_to", List.of("INT", "INT"));
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void dropProcedureIfExists(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ String create = dialect.createProcedure(new RoutineDefinition("dbo", "add_to",
+ List.of(RoutineParameter.in("n", "INT"),
+ new RoutineParameter("total", ParameterMode.INOUT, "INT")),
+ null, "tsql", "BEGIN SET @total = @total + @n END"), false).orElseThrow();
+
+ String drop = dialect.dropProcedure(ADD_TO, true).orElseThrow();
+ assertThat(drop).as("IF EXISTS, the name alone")
+ .isEqualTo("DROP PROCEDURE IF EXISTS \"dbo\".\"add_to\"");
+ String plain = dialect.dropProcedure(ADD_TO, false).orElseThrow();
+ assertThat(plain).isEqualTo("DROP PROCEDURE \"dbo\".\"add_to\"");
+ assertThat(dialect.dropProcedure("add_to", "dbo", true)).as("the drop by schema and name")
+ .contains(drop);
+ assertThat(dialect.dropProcedure("add_to", "dbo", false)).contains(plain);
+
+ st.execute(create);
+ assertThat(exists(st, "P")).as("created").isTrue();
+ st.execute(drop);
+ assertThat(exists(st, "P")).as("dropped").isFalse();
+ st.execute(drop);
+ assertThatThrownBy(() -> st.execute(plain)).as("a missing one without IF EXISTS")
+ .isInstanceOf(SQLException.class).hasMessageContaining("does not exist");
+
+ // a function of the name: IF EXISTS does not pass over it, the drop fails and leaves it
+ st.execute("CREATE FUNCTION dbo.add_to(@n INT) RETURNS INT AS BEGIN RETURN @n END");
+ assertThatThrownBy(() -> st.execute(drop)).as("a function of the name")
+ .isInstanceOf(SQLException.class).hasMessageContaining("is a function");
+ assertThat(exists(st, "FN")).as("the function of the name left").isTrue();
+ }
+ }
+ }
+
+ private static boolean exists(Statement st, String type) throws SQLException {
+ try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM sys.objects WHERE schema_id = SCHEMA_ID('dbo')"
+ + " AND name = 'add_to' AND type = '" + type + "'")) {
+ rs.next();
+ return rs.getInt(1) > 0;
+ }
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropTriggerProcedureTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropTriggerProcedureTest.java
new file mode 100644
index 00000000..dd9e0cab
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlDropTriggerProcedureTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ */
+package org.eclipse.daanse.sql.dialect.db.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Optional;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.eclipse.daanse.sql.model.schema.TableReference;
+import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent;
+import org.eclipse.daanse.sql.model.schema.Trigger.TriggerScope;
+import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server drops a trigger procedure, by schema and name, with {@code DROP PROCEDURE [IF EXISTS] s.p}; IF EXISTS
+ * from 2016 on, so in every version Docker serves, 2017 to 2025. The dialect is built from a live connection: the
+ * procedure {@code createTriggerProcedure} writes is dropped, of a schema, of none and of a blank one, which name it in
+ * the user's default schema, and of a name holding a quote and a blank; a second drop passes with IF EXISTS, fails
+ * without it. A procedure a trigger calls is dropped too, for SQL Server resolves the call when the trigger fires:
+ * the trigger then fails the statement it fires on.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlDropTriggerProcedureTest {
+
+ private static final TableReference ITEMS = new TableReference(
+ Optional.of(new SchemaReference(Optional.empty(), "dbo")), "items", TableReference.TYPE_TABLE);
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void dropTriggerProcedure(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ st.execute("CREATE TABLE items(id INT)");
+ st.execute("CREATE TABLE audit(op VARCHAR(10))");
+
+ // of a schema, of none, of a blank one; of a name holding a quote and a blank
+ assertThat(dialect.dropProcedure("log_it", "dbo", true))
+ .contains("DROP PROCEDURE IF EXISTS \"dbo\".\"log_it\"");
+ assertThat(dialect.dropProcedure("log_it", null, true)).contains("DROP PROCEDURE IF EXISTS \"log_it\"");
+ assertThat(dialect.dropProcedure("log_it", " ", false)).contains("DROP PROCEDURE \"log_it\"");
+ for (String schema : new String[] { "dbo", null, "" }) {
+ for (String name : new String[] { "log_it", "it's a proc" }) {
+ st.execute(dialect.createTriggerProcedure(name, schema,
+ "BEGIN INSERT INTO dbo.audit VALUES ('call') END").orElseThrow());
+ assertThat(exists(st, name)).as("created: " + schema + "." + name).isTrue();
+ String drop = dialect.dropProcedure(name, schema, true).orElseThrow();
+ st.execute(drop);
+ assertThat(exists(st, name)).as("dropped: " + drop).isFalse();
+ st.execute(drop);
+ assertThatThrownBy(() -> st.execute(dialect.dropProcedure(name, schema, false).orElseThrow()))
+ .as("a missing one without IF EXISTS: " + drop).isInstanceOf(SQLException.class)
+ .hasMessageContaining("does not exist");
+ }
+ }
+
+ // a procedure a trigger calls: dropped, and the trigger then fails the statement it fires on
+ st.execute(dialect.createTriggerProcedure("log_it", "dbo",
+ "BEGIN INSERT INTO dbo.audit VALUES ('call') END").orElseThrow());
+ st.execute(dialect.createTriggerUsingProcedure("items_insert", "dbo", TriggerTiming.AFTER,
+ TriggerEvent.INSERT, ITEMS, TriggerScope.STATEMENT, null, "log_it"));
+ st.execute("INSERT INTO items VALUES (1)");
+ assertThat(count(st, "SELECT COUNT(*) FROM audit")).as("the trigger calls it").isEqualTo(1);
+ st.execute(dialect.dropProcedure("log_it", "dbo", true).orElseThrow());
+ assertThat(exists(st, "log_it")).as("dropped though a trigger calls it").isFalse();
+ assertThatThrownBy(() -> st.execute("INSERT INTO items VALUES (2)"))
+ .as("the trigger fails the insert").isInstanceOf(SQLException.class)
+ .hasMessageContaining("Could not find stored procedure");
+ assertThat(count(st, "SELECT COUNT(*) FROM items")).as("the insert undone").isEqualTo(1);
+ }
+ }
+ }
+
+ private static boolean exists(Statement st, String name) throws SQLException {
+ return count(st, "SELECT COUNT(*) FROM sys.procedures WHERE schema_id = SCHEMA_ID('dbo') AND name = N'"
+ + name.replace("'", "''") + "'") > 0;
+ }
+
+ private static int count(Statement st, String sql) throws SQLException {
+ try (ResultSet rs = st.executeQuery(sql)) {
+ rs.next();
+ return rs.getInt(1);
+ }
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlListAggTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlListAggTest.java
new file mode 100644
index 00000000..54fad0b2
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlListAggTest.java
@@ -0,0 +1,158 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.eclipse.daanse.sql.model.sql.NullsOrder;
+import org.eclipse.daanse.sql.model.sql.OrderedColumn;
+import org.eclipse.daanse.sql.model.sql.SortDirection;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server lists the values of a group with {@code STRING_AGG(x, 's') WITHIN GROUP (ORDER BY …)}, from 2017 on, so
+ * in every version Docker serves. The dialect is built from a live connection, and the list it writes must come out of
+ * the server in the order asked for, without the NULL values, with any separator, a quote too, of a column of any
+ * type, of Unicode text, longer than 8000 bytes, and per group. SQL Server knows no {@code NULLS FIRST/LAST}: the
+ * dialect ranks the NULLs of an order column with a CASE. It knows no {@code STRING_AGG(DISTINCT …)} either, and the
+ * dialect writes none. The lists are read per group: SQL Server 2017 to 2022 ordered a list over the rows of a
+ * {@code WHERE} without {@code GROUP BY} wrongly at times, a fault of its plan.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlListAggTest {
+
+ /** Group a: alice 20, bob 30, bob 10, a NULL name of 40; group b: dave 5. */
+ private static final List SETUP = List.of(
+ "CREATE TABLE emp(dept VARCHAR(1), name VARCHAR(10), salary INT, uname NVARCHAR(10))",
+ "INSERT INTO emp VALUES ('a', 'bob', 30, N'ö'), ('a', NULL, 40, NULL), ('a', 'alice', 20, N'日本'),"
+ + " ('a', 'bob', 10, N'ä'), ('b', 'dave', 5, N'x')",
+ "CREATE TABLE big(s VARCHAR(100))",
+ "INSERT INTO big SELECT TOP 200 REPLICATE('x', 100) FROM sys.all_objects");
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void listAgg(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ for (String sql : SETUP) {
+ st.execute(sql);
+ }
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ assertThat(dialect.supportsListAgg()).isTrue();
+
+ assertThat(list(st, dialect, "name", ", ", order("name", SortDirection.ASC)))
+ .as("ordered by the value, the NULL left out").isEqualTo("alice, bob, bob");
+ assertThat(list(st, dialect, "name", ", ", order("salary", SortDirection.DESC)))
+ .as("ordered by another column").isEqualTo("bob, alice, bob");
+ assertThat(list(st, dialect, "name", ", ",
+ List.of(new OrderedColumn("name", "emp", SortDirection.ASC))))
+ .as("a column of the table").isEqualTo("alice, bob, bob");
+ assertThat(Arrays.stream(list(st, dialect, "name", ",", List.of()).split(",")).sorted())
+ .as("without an order").containsExactly("alice", "bob", "bob");
+
+ assertThat(list(st, dialect, "name", null, order("name", SortDirection.ASC)))
+ .as("no separator is a comma and a space").isEqualTo("alice, bob, bob");
+ assertThat(list(st, dialect, "name", "'", order("name", SortDirection.ASC)))
+ .as("a quote as separator").isEqualTo("alice'bob'bob");
+ assertThat(list(st, dialect, "name", "\\", order("name", SortDirection.ASC)))
+ .as("a backslash as separator").isEqualTo("alice\\bob\\bob");
+ assertThat(list(st, dialect, "name", " · ", order("name", SortDirection.ASC)))
+ .as("a separator out of ASCII").isEqualTo("alice · bob · bob");
+
+ assertThat(list(st, dialect, "salary", ",", order("salary", SortDirection.ASC)))
+ .as("an INT column").isEqualTo("10,20,30,40");
+ assertThat(list(st, dialect, "uname", ",", order("salary", SortDirection.ASC)))
+ .as("Unicode text").isEqualTo("ä,日本,ö");
+ assertThat(list(st, dialect, "salary", ",",
+ List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC),
+ Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC))))
+ .as("NULLS FIRST, then a second column").isEqualTo("40,20,10,30");
+ assertThat(list(st, dialect, "salary", ",",
+ List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC),
+ Optional.of(NullsOrder.LAST)), new OrderedColumn("salary", null, SortDirection.ASC))))
+ .as("NULLS LAST, then a second column").isEqualTo("20,10,30,40");
+ assertThat(list(st, dialect, "salary", ",",
+ List.of(new OrderedColumn("name", null, Optional.of(SortDirection.DESC),
+ Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC))))
+ .as("descending, NULLS FIRST").isEqualTo("40,10,30,20");
+
+ String longList = dialect.generateListAgg("s", false, ",", null, null, List.of()).orElseThrow();
+ assertThat(value(st, "SELECT LEN(" + longList + ") FROM big")).as("longer than 8000 bytes")
+ .isEqualTo("20199");
+ assertThatThrownBy(() -> value(st, "SELECT LEN(STRING_AGG(s, ',')) FROM big"))
+ .as("the operand left as it is stops at 8000 bytes").isInstanceOf(SQLException.class)
+ .hasMessageContaining("8000 bytes");
+
+ String perDept = dialect.generateListAgg("name", false, ",", null, null,
+ order("name", SortDirection.ASC)).orElseThrow();
+ assertThat(rows(st, "SELECT dept, " + perDept + " FROM emp GROUP BY dept ORDER BY dept"))
+ .as("per group").containsExactly("a=alice,bob,bob", "b=dave");
+
+ assertThat(dialect.generateListAgg("name", true, ",", null, null, List.of()))
+ .as("no DISTINCT list").isEmpty();
+ assertThatThrownBy(() -> value(st, "SELECT STRING_AGG(DISTINCT name, ',') FROM emp"))
+ .as("SQL Server knows no STRING_AGG(DISTINCT …)").isInstanceOf(SQLException.class);
+ }
+ }
+ }
+
+ private static List order(String column, SortDirection direction) {
+ return List.of(new OrderedColumn(column, null, direction));
+ }
+
+ private static String list(Statement st, MicrosoftSqlServerDialect dialect, String operand, String separator,
+ List columns) throws SQLException {
+ String agg = dialect.generateListAgg(operand, false, separator, null, null, columns).orElseThrow();
+ try {
+ // per group, as the engine lists: a list over all rows of a WHERE alone came out in the wrong order on 2017
+ // to 2022 (ORDER BY salary DESC gave 10,20,30,40), though not with GROUP BY or OPTION (RECOMPILE), nor on
+ // 2025, a fault of the server's plan the dialect cannot write around
+ return value(st, "SELECT " + agg + " FROM emp WHERE dept = 'a' GROUP BY dept");
+ } catch (SQLException e) {
+ throw new SQLException(e.getMessage() + " in " + agg, e);
+ }
+ }
+
+ private static String value(Statement st, String sql) throws SQLException {
+ try (ResultSet rs = st.executeQuery(sql)) {
+ assertThat(rs.next()).isTrue();
+ return rs.getString(1);
+ }
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ while (rs.next()) {
+ out.add(rs.getString(1) + "=" + rs.getString(2));
+ }
+ }
+ return out;
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlMergeGeneratorTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlMergeGeneratorTest.java
new file mode 100644
index 00000000..e5b59c5c
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlMergeGeneratorTest.java
@@ -0,0 +1,183 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator;
+import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator.UpsertSpec;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.eclipse.daanse.sql.model.schema.TableReference;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server upserts with {@code MERGE INTO … USING (VALUES …) … WHEN MATCHED … WHEN NOT MATCHED …}, from 2008 on, so in
+ * every version Docker serves, 2017 to 2025. An upsert inserts a row of a new key and, of a key that is there, updates
+ * the update columns; without update columns it leaves that row as it is, insert-or-ignore, as {@link UpsertSpec}
+ * says. The dialect is built from a live connection, and its upsert must do so on the server: of a single key and of a
+ * composite one, of a quote and Unicode in a value, and of the same new keys upserted at once by several connections,
+ * each key once and without an error.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlMergeGeneratorTest {
+
+ private static final SchemaReference DBO = new SchemaReference(Optional.empty(), "dbo");
+ private static final TableReference PRODUCTS = new TableReference(Optional.of(DBO), "products",
+ TableReference.TYPE_TABLE);
+ private static final TableReference STOCK = new TableReference(Optional.of(DBO), "stock",
+ TableReference.TYPE_TABLE);
+ private static final TableReference HITS = new TableReference(Optional.of(DBO), "hits", TableReference.TYPE_TABLE);
+
+ private static final List SETUP = List.of(
+ "CREATE TABLE products(id INT PRIMARY KEY, name NVARCHAR(20), price INT)",
+ "CREATE TABLE stock(store VARCHAR(10), product INT, qty INT, PRIMARY KEY (store, product))",
+ "CREATE TABLE hits(k INT PRIMARY KEY, n INT)",
+ "INSERT INTO products VALUES (1, 'apple', 10)", "INSERT INTO stock VALUES ('north', 1, 5)");
+
+ private static final UpsertSpec UPDATE_PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"),
+ List.of("id", "name", "price"), List.of("name", "price"));
+ private static final UpsertSpec IGNORE_PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"),
+ List.of("id", "name", "price"), List.of());
+ private static final UpsertSpec IGNORE_STOCK = new UpsertSpec(STOCK, List.of("store", "product"),
+ List.of("store", "product", "qty"), List.of());
+ private static final UpsertSpec UPDATE_STOCK = new UpsertSpec(STOCK, List.of("store", "product"),
+ List.of("store", "product", "qty"), List.of("qty"));
+ private static final UpsertSpec UPDATE_HIT = new UpsertSpec(HITS, List.of("k"), List.of("k", "n"), List.of("n"));
+
+ private static final int THREADS = 8;
+ private static final int KEYS = 100;
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void upsert(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ for (String sql : SETUP) {
+ st.execute(sql);
+ }
+ MergeGenerator merge = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c))
+ .mergeGenerator();
+ assertThat(merge.supportsMerge()).isTrue();
+
+ st.execute(sql(merge, UPDATE_PRODUCT, "2", "'banana'", "7"));
+ st.execute(sql(merge, UPDATE_PRODUCT, "1", "'apple'", "12"));
+ assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id"))
+ .as("with update columns: a new key inserted, the one there updated")
+ .containsExactly("1|apple|12", "2|banana|7");
+
+ String ignoreThere = sql(merge, IGNORE_PRODUCT, "1", "'cherry'", "99");
+ st.execute(ignoreThere);
+ assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id"))
+ .as("without update columns the row of a key that is there is left: " + ignoreThere)
+ .containsExactly("1|apple|12", "2|banana|7");
+ st.execute(sql(merge, IGNORE_PRODUCT, "3", "'cherry'", "99"));
+ assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id"))
+ .as("without update columns a new key is inserted")
+ .containsExactly("1|apple|12", "2|banana|7", "3|cherry|99");
+
+ st.execute(sql(merge, UPDATE_PRODUCT, "4", "N'it''s 日本'", "1"));
+ assertThat(rows(st, "SELECT name FROM products WHERE id = 4")).as("a quote and Unicode in a value")
+ .containsExactly("it's 日本");
+
+ st.execute(sql(merge, IGNORE_STOCK, "'north'", "1", "8"));
+ st.execute(sql(merge, IGNORE_STOCK, "'south'", "1", "3"));
+ assertThat(rows(st, "SELECT store, product, qty FROM stock ORDER BY store"))
+ .as("a composite key, without update columns").containsExactly("north|1|5", "south|1|3");
+ st.execute(sql(merge, UPDATE_STOCK, "'north'", "1", "9"));
+ st.execute(sql(merge, UPDATE_STOCK, "'north'", "2", "4"));
+ assertThat(rows(st, "SELECT store, product, qty FROM stock ORDER BY store, product"))
+ .as("a composite key, with update columns")
+ .containsExactly("north|1|9", "north|2|4", "south|1|3");
+
+ List errors = concurrently(ms, merge);
+ assertThat(errors).as("the same new keys upserted at once by " + THREADS + " connections").isEmpty();
+ assertThat(rows(st, "SELECT COUNT(*), COUNT(DISTINCT k) FROM hits")).as("each key once")
+ .containsExactly(KEYS + "|" + KEYS);
+ }
+ }
+ }
+
+ /** Every connection upserts the keys 1 to KEYS, all starting together; the errors they met. */
+ private static List concurrently(MSSQLServerContainer> ms, MergeGenerator merge) throws Exception {
+ List errors = Collections.synchronizedList(new ArrayList<>());
+ CountDownLatch start = new CountDownLatch(1);
+ ExecutorService pool = Executors.newFixedThreadPool(THREADS);
+ try {
+ List> done = new ArrayList<>();
+ for (int t = 0; t < THREADS; t++) {
+ int thread = t;
+ done.add(pool.submit(() -> {
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(),
+ ms.getPassword()); Statement st = c.createStatement()) {
+ start.await();
+ for (int k = 1; k <= KEYS; k++) {
+ try {
+ st.execute(sql(merge, UPDATE_HIT, Integer.toString(k), Integer.toString(thread)));
+ } catch (SQLException e) {
+ errors.add("key " + k + ": " + e.getMessage());
+ }
+ }
+ }
+ return null;
+ }));
+ }
+ start.countDown();
+ for (Future> f : done) {
+ f.get();
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ return errors;
+ }
+
+ private static String sql(MergeGenerator merge, UpsertSpec spec, String... values) {
+ return merge.upsert(spec, List.of(values)).orElseThrow();
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ int n = rs.getMetaData().getColumnCount();
+ while (rs.next()) {
+ StringBuilder row = new StringBuilder();
+ for (int i = 1; i <= n; i++) {
+ if (i > 1)
+ row.append('|');
+ row.append(rs.getString(i));
+ }
+ out.add(row.toString());
+ }
+ }
+ return out;
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlPercentileTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlPercentileTest.java
new file mode 100644
index 00000000..27627914
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlPercentileTest.java
@@ -0,0 +1,98 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server has {@code PERCENTILE_DISC} and {@code PERCENTILE_CONT … WITHIN GROUP} only as window functions, in every
+ * version Docker serves, 2017 to 2025: as an aggregate the server refuses them, "must have an OVER clause" (Msg
+ * 10753), in a grouped query too. The dialect is built from a live connection: it offers no percentile and writes none,
+ * so a measure of one is refused rather than sent to the server. The window form works, over a partition of the rows,
+ * which a grouped query cannot take for its groups.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlPercentileTest {
+
+ /** Group a: 10, 20, 30, 40 and a NULL that every percentile leaves out; group b: 5 alone. */
+ private static final List SETUP = List.of("CREATE TABLE nums(g VARCHAR(1), v INT)",
+ "INSERT INTO nums VALUES ('a', 30), ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5)");
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void percentile(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ for (String sql : SETUP) {
+ st.execute(sql);
+ }
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+
+ assertThat(dialect.supportsPercentileDisc()).as("supportsPercentileDisc").isFalse();
+ assertThat(dialect.supportsPercentileCont()).as("supportsPercentileCont").isFalse();
+ assertThat(dialect.generatePercentileDisc(0.5, false, "nums", "v")).as("no PERCENTILE_DISC").isEmpty();
+ assertThat(dialect.generatePercentileDisc(0.5, true, null, "v")).as("no PERCENTILE_DISC").isEmpty();
+ assertThat(dialect.generatePercentileCont(0.5, false, "nums", "v")).as("no PERCENTILE_CONT").isEmpty();
+ assertThat(dialect.generatePercentileCont(0.25, true, null, "v")).as("no PERCENTILE_CONT").isEmpty();
+
+ for (String f : List.of("PERCENTILE_DISC", "PERCENTILE_CONT")) {
+ assertThatThrownBy(() -> rows(st, "SELECT " + f + "(0.5) WITHIN GROUP (ORDER BY v) FROM nums"))
+ .as(f + " as an aggregate").isInstanceOf(SQLException.class)
+ .hasMessageContaining("must have an OVER clause");
+ assertThatThrownBy(() -> rows(st,
+ "SELECT g, " + f + "(0.5) WITHIN GROUP (ORDER BY v) FROM nums GROUP BY g"))
+ .as(f + " in a grouped query").isInstanceOf(SQLException.class)
+ .hasMessageContaining("must have an OVER clause");
+ }
+
+ assertThat(rows(st, "SELECT DISTINCT g, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY v)"
+ + " OVER (PARTITION BY g), PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY v DESC)"
+ + " OVER (PARTITION BY g) FROM nums ORDER BY g"))
+ .as("the window form, over a partition").containsExactly("a|20|32.5", "b|5|5.0");
+ }
+ }
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ int n = rs.getMetaData().getColumnCount();
+ while (rs.next()) {
+ StringBuilder row = new StringBuilder();
+ for (int i = 1; i <= n; i++) {
+ if (i > 1)
+ row.append('|');
+ row.append(rs.getString(i));
+ }
+ out.add(row.toString());
+ }
+ }
+ return out;
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlSequenceTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlSequenceTest.java
new file mode 100644
index 00000000..7d5ac169
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlSequenceTest.java
@@ -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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator;
+import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.SequenceDefinition;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server has sequences from 2012 on, so in every version Docker serves, 2017 to 2025. The dialect is built from a
+ * live connection: the sequence it creates gives its values from {@code NEXT VALUE FOR}, with its start, increment,
+ * bounds, cycle and cache, also as the default of a column; created again it is refused, with {@code ifNotExists} it
+ * is left as it is; renamed it goes on counting, unless a column's default uses it; dropped it is gone, a second
+ * drop passing with IF EXISTS only. A sequence of no options starts, as SQL Server's do, at the least BIGINT, not at
+ * 1.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlSequenceTest {
+
+ /** 10, 15, 20, then round to 10 again. */
+ private static final SequenceDefinition CYCLING = new SequenceDefinition("dbo", "cycling", 10L, 5L, 10L, 20L,
+ true, 3L);
+ /** 1, 2, then no more. */
+ private static final SequenceDefinition BOUNDED = new SequenceDefinition("dbo", "bounded", 1L, 1L, 1L, 2L, false,
+ null);
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void sequences(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ DdlGenerator ddl = dialect.ddlGenerator();
+ assertThat(ddl.supportsSequences()).as("supportsSequences").isTrue();
+
+ // options: start, increment, bounds, cycle, cache
+ String cycling = ddl.createSequence(CYCLING, false).orElseThrow();
+ assertThat(cycling).isEqualTo("CREATE SEQUENCE \"dbo\".\"cycling\" START WITH 10 INCREMENT BY 5"
+ + " MINVALUE 10 MAXVALUE 20 CYCLE CACHE 3");
+ st.execute(cycling);
+ String next = ddl.nextValueFor("dbo", "cycling").orElseThrow();
+ assertThat(values(st, next, 4)).as("start, increment, round at the bound")
+ .containsExactly("10", "15", "20", "10");
+
+ st.execute(ddl.createSequence(BOUNDED, false).orElseThrow());
+ String nextBounded = ddl.nextValueFor("dbo", "bounded").orElseThrow();
+ assertThat(values(st, nextBounded, 2)).containsExactly("1", "2");
+ assertThatThrownBy(() -> values(st, nextBounded, 1)).as("NO CYCLE past the bound")
+ .isInstanceOf(SQLException.class).hasMessageContaining("minimum or maximum value");
+
+ // no options: SQL Server's own start, the least BIGINT
+ st.execute(ddl.createSequence(SequenceDefinition.of("dbo", "plain"), false).orElseThrow());
+ assertThat(values(st, ddl.nextValueFor("dbo", "plain").orElseThrow(), 1))
+ .as("no options: the least BIGINT").containsExactly(Long.toString(Long.MIN_VALUE));
+
+ // the default of a column
+ st.execute("CREATE TABLE items(id INT DEFAULT (" + next + "), name VARCHAR(10))");
+ st.execute("INSERT INTO items(name) VALUES ('a'), ('b')");
+ assertThat(rows(st, "SELECT CAST(id AS VARCHAR) + '|' + name FROM items ORDER BY name"))
+ .as("the default of a column").containsExactly("15|a", "20|b");
+
+ // created again: refused; with ifNotExists left as it is
+ assertThatThrownBy(() -> st.execute(cycling)).as("created again")
+ .isInstanceOf(SQLException.class).hasMessageContaining("already an object named");
+ String ifNotExists = ddl.createSequence(CYCLING, true).orElseThrow();
+ st.execute(ifNotExists);
+ assertThat(values(st, next, 1)).as("with ifNotExists left as it is: " + ifNotExists)
+ .containsExactly("10");
+
+ // renamed, it goes on counting; one a column's default uses is not renamed
+ assertThatThrownBy(() -> st.execute(ddl.renameSequence("dbo", "cycling", "renamed").orElseThrow()))
+ .as("a sequence a column's default uses").isInstanceOf(SQLException.class)
+ .hasMessageContaining("enforced dependencies");
+ st.execute("DROP SEQUENCE IF EXISTS dbo.bounded");
+ st.execute(ddl.createSequence(BOUNDED, false).orElseThrow());
+ assertThat(values(st, nextBounded, 1)).containsExactly("1");
+ st.execute(ddl.renameSequence("dbo", "bounded", "renamed").orElseThrow());
+ assertThat(values(st, ddl.nextValueFor("dbo", "renamed").orElseThrow(), 1)).as("renamed")
+ .containsExactly("2");
+ assertThatThrownBy(() -> values(st, nextBounded, 1)).as("the old name gone")
+ .isInstanceOf(SQLException.class);
+
+ // dropped
+ String drop = ddl.dropSequence("dbo", "renamed", true).orElseThrow();
+ assertThat(drop).isEqualTo("DROP SEQUENCE IF EXISTS \"dbo\".\"renamed\"");
+ st.execute(drop);
+ assertThat(rows(st, "SELECT name FROM sys.sequences WHERE name = 'renamed'")).as("dropped").isEmpty();
+ st.execute(drop);
+ assertThatThrownBy(() -> st.execute(ddl.dropSequence("dbo", "renamed", false).orElseThrow()))
+ .as("a missing one without IF EXISTS").isInstanceOf(SQLException.class)
+ .hasMessageContaining("does not exist");
+ }
+ }
+ }
+
+ /** The next n values of the sequence, one statement each. */
+ private static List values(Statement st, String next, int n) throws SQLException {
+ List out = new ArrayList<>();
+ for (int i = 0; i < n; i++) {
+ out.addAll(rows(st, "SELECT " + next));
+ }
+ return out;
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ while (rs.next()) {
+ out.add(rs.getString(1));
+ }
+ }
+ return out;
+ }
+}
diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlTriggerProcedureTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlTriggerProcedureTest.java
new file mode 100644
index 00000000..afd8ed9d
--- /dev/null
+++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/container/MsSqlTriggerProcedureTest.java
@@ -0,0 +1,121 @@
+/*
+ * 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.mssqlserver.container;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+import org.eclipse.daanse.sql.dialect.api.DialectInitData;
+import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.eclipse.daanse.sql.model.schema.TableReference;
+import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent;
+import org.eclipse.daanse.sql.model.schema.Trigger.TriggerScope;
+import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.testcontainers.containers.MSSQLServerContainer;
+
+/**
+ * SQL Server runs a trigger procedure from a trigger of {@code AS EXEC proc}. The dialect is built from a live
+ * connection: the procedure it writes is created, and created again replaced; the trigger it writes calls it after
+ * an insert, an update and a delete. SQL Server has no {@code WHEN} on a trigger: the dialect refuses a condition, for
+ * left out the trigger fired for every row it did not hold of too; written into the body over the deleted rows, it
+ * calls the procedure only where it holds.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class MsSqlTriggerProcedureTest {
+
+ private static final TableReference ITEMS = new TableReference(
+ Optional.of(new SchemaReference(Optional.empty(), "dbo")), "items", TableReference.TYPE_TABLE);
+
+ @ParameterizedTest(name = "mssql/server:{0}")
+ @ValueSource(strings = { "2017-latest", "2019-latest", "2022-latest", "2025-latest" })
+ void triggerProcedure(String tag) throws Exception {
+ try (MSSQLServerContainer> ms = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:" + tag)
+ .acceptLicense()) {
+ ms.start();
+ try (Connection c = DriverManager.getConnection(ms.getJdbcUrl(), ms.getUsername(), ms.getPassword());
+ Statement st = c.createStatement()) {
+ MicrosoftSqlServerDialect dialect = new MicrosoftSqlServerDialect(DialectInitData.fromConnection(c));
+ st.execute("CREATE TABLE items(id INT, qty INT)");
+ st.execute("CREATE TABLE audit(op VARCHAR(10))");
+
+ // the procedure, created and replaced
+ String proc = dialect.createTriggerProcedure("log_it", "dbo",
+ "BEGIN INSERT INTO dbo.audit VALUES ('v1') END").orElseThrow();
+ assertThat(proc).isEqualTo("CREATE OR ALTER PROCEDURE \"dbo\".\"log_it\" AS BEGIN INSERT INTO"
+ + " dbo.audit VALUES ('v1') END");
+ st.execute(proc);
+ st.execute(dialect.createTriggerProcedure("log_it", "dbo",
+ "BEGIN INSERT INTO dbo.audit VALUES ('call') END").orElseThrow());
+
+ // after an insert, an update, a delete
+ for (TriggerEvent event : List.of(TriggerEvent.INSERT, TriggerEvent.UPDATE, TriggerEvent.DELETE)) {
+ st.execute(dialect.createTriggerUsingProcedure("items_" + event.name().toLowerCase(), "dbo",
+ TriggerTiming.AFTER, event, ITEMS, TriggerScope.STATEMENT, null, "log_it"));
+ }
+ st.execute("INSERT INTO items VALUES (1, 5)");
+ assertThat(rows(st, "SELECT op FROM audit")).as("after an insert, the replaced body")
+ .containsExactly("call");
+ st.execute("UPDATE items SET qty = 6");
+ st.execute("DELETE FROM items");
+ assertThat(rows(st, "SELECT COUNT(*) FROM audit")).as("after an update and a delete")
+ .containsExactly("3");
+ for (TriggerEvent event : List.of(TriggerEvent.INSERT, TriggerEvent.UPDATE, TriggerEvent.DELETE)) {
+ st.execute("DROP TRIGGER items_" + event.name().toLowerCase());
+ }
+
+ // a condition of the trigger: SQL Server has no WHEN, and the dialect refuses it rather than leave it
+ // out, which fired the trigger for every row the condition did not hold of too
+ assertThatThrownBy(() -> dialect.createTriggerUsingProcedure("items_big_delete", "dbo",
+ TriggerTiming.AFTER, TriggerEvent.DELETE, ITEMS, TriggerScope.ROW, "OLD.qty > 10", "log_it"))
+ .as("a condition, with a procedure").isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("OLD.qty > 10");
+ assertThatThrownBy(() -> dialect.createTrigger("items_big", TriggerTiming.AFTER, TriggerEvent.INSERT,
+ ITEMS, TriggerScope.ROW, "NEW.qty > 10", "AS INSERT INTO dbo.audit VALUES ('big')"))
+ .as("a condition, with a body").isInstanceOf(UnsupportedOperationException.class);
+
+ // the condition written into the body, over the deleted rows, as the refusal says
+ st.execute("DELETE FROM audit");
+ st.execute("INSERT INTO items VALUES (1, 5), (2, 20)");
+ st.execute(dialect.createTrigger("items_big_delete", TriggerTiming.AFTER, TriggerEvent.DELETE, ITEMS,
+ TriggerScope.STATEMENT, null,
+ "AS IF EXISTS (SELECT 1 FROM deleted WHERE qty > 10) EXEC dbo.log_it"));
+ st.execute("DELETE FROM items WHERE id = 1");
+ assertThat(rows(st, "SELECT COUNT(*) FROM audit")).as("a small one deleted: no call")
+ .containsExactly("0");
+ st.execute("DELETE FROM items WHERE id = 2");
+ assertThat(rows(st, "SELECT COUNT(*) FROM audit")).as("a big one deleted: the procedure called")
+ .containsExactly("1");
+ }
+ }
+ }
+
+ private static List rows(Statement st, String sql) throws SQLException {
+ List out = new ArrayList<>();
+ try (ResultSet rs = st.executeQuery(sql)) {
+ while (rs.next()) {
+ out.add(rs.getString(1));
+ }
+ }
+ return out;
+ }
+}