From 3cdc154ef0341f775f1854dfdffb2df43e06679d Mon Sep 17 00:00:00 2001 From: dbulahov Date: Wed, 25 Nov 2026 16:10:05 +0300 Subject: [PATCH] dialect(clickhouse): version checks and fixes, tested on ClickHouse in Docker Checked on clickhouse/clickhouse-server 21.3 to 26.6 in Docker; images before 21.3 are published only as yandex/clickhouse-server and are not used. DdlGenerator (dialect api): - supportsMaterializedViews: a refreshable ClickHouse materialized view (24.10) keeps the result of its query; the classic one does not ClickHouseDialect: - generateListAgg: arrayStringConcat over the group's rows, sorted per key, stable, DESC and NULLS FIRST/LAST kept, DISTINCT, any separator; groupArrayArray, written before, takes arrays only and failed with Code 43 on every version - generateNthValueAgg, supportsNthValue, supportsNthValueIgnoreNulls: the n-th of the group's sorted rows, NULL past the end; were refused - generatePercentileDisc/Cont, supportsPercentileDisc/Cont: computed on the sorted group; no quantile gives the discrete one, and 21.x's quantileExactInclusive gives the 2nd value for p = 1 - paginationGenerator: LIMIT n OFFSET m; OFFSET ... FETCH failed without ORDER BY on every version (Code 628), FETCH alone on 21.x - castGenerator: ClickHouse type names; supportsTryCast, tryCast as accurateCastOrNull, a boolean before 24.3 as true/false/1/0, else NULL (22.x and 23.x threw on what is no boolean) - allowsRegularExpressionInWhereClause, generateRegularExpression: match(s, '(?-s)\A(?:...)\z') on RE2; none for lookaround, back references, possessive, class intersection, which RE2 refuses or reads otherwise; Java's u flag taken out - supportsGroupingSets: from 22.9; 22.6 leaves the rows unsorted, 22.6 to 22.8 give GROUPING() the other way round - cteGenerator: RECURSIVE from 24.4, on the new analyzer only - supportsRenameColumn: from 20.4 - supportsUsers, supportsRoles: from 20.4; createUser gives no user where supportsUsers says no - commentOnTable: MODIFY COMMENT from 21.11; supportsCommentOnView, a view's comment and its columns' from 22.1, 21.11 and 21.12 write metadata they cannot read again and the server does not start - supportsAtomicMultiRenameTable: false, RENAME TABLE a TO b, c TO d undoes nothing when a later rename fails; renameTables writes one statement per rename - supportsCreateOrReplaceView: stays false, documented: ClickHouse's OR REPLACE replaces a table too, its rows gone - supportsMaterializedViews: from 24.10, REFRESH AFTER 10 YEAR, a refresh on demand in effect; dropped with DROP VIEW - unionDistinctKeyword: UNION DISTINCT from 21.1, documented Container tests, the dialect built from a live connection: - ClickHouseContainers: the image of a tag, the driver's V1 before 21.11, which sends no async_insert - ClickHouseListAggTest, ClickHouseNthValueTest, ClickHousePercentileTest, ClickHouseOffsetTest, ClickHouseTryCastTest, ClickHouseRegularExpressionTest (rows as Java's Pattern.matches), ClickHouseGroupingSetsTest, ClickHouseRecursiveCteTest, ClickHouseUnionDistinctTest, ClickHouseRenameColumnTest, ClickHouseUsersTest, ClickHouseRolesTest, ClickHouseCommentOnTableTest, ClickHouseCommentOnColumnTest, ClickHouseAtomicMultiRenameTableTest, ClickHouseCreateOrReplaceViewTest, ClickHouseMaterializedViewTest - ClickHouseDialectTest, ClickHouseAlterRenameOfflineTest, ViewCommentStatementsTest, MaterializedViewStatementsTest: the new statements and flags Signed-off-by: --- .../dialect/api/generator/DdlGenerator.java | 4 +- dialect/db/clickhouse/pom.xml | 20 + .../db/clickhouse/ClickHouseDialect.java | 444 ++++++++++++++++-- .../db/clickhouse/ClickHouseDialectTest.java | 9 +- .../ClickHouseAtomicMultiRenameTableTest.java | 120 +++++ .../ClickHouseCommentOnColumnTest.java | 131 ++++++ .../ClickHouseCommentOnTableTest.java | 131 ++++++ .../container/ClickHouseContainers.java | 41 ++ .../ClickHouseCreateOrReplaceViewTest.java | 106 +++++ .../container/ClickHouseGroupingSetsTest.java | 121 +++++ .../container/ClickHouseListAggTest.java | 142 ++++++ .../ClickHouseMaterializedViewTest.java | 125 +++++ .../container/ClickHouseNthValueTest.java | 120 +++++ .../container/ClickHouseOffsetTest.java | 126 +++++ .../container/ClickHousePercentileTest.java | 116 +++++ .../container/ClickHouseRecursiveCteTest.java | 111 +++++ .../ClickHouseRegularExpressionTest.java | 131 ++++++ .../container/ClickHouseRenameColumnTest.java | 105 +++++ .../container/ClickHouseRolesTest.java | 133 ++++++ .../container/ClickHouseTryCastTest.java | 122 +++++ .../ClickHouseUnionDistinctTest.java | 87 ++++ .../container/ClickHouseUsersTest.java | 120 +++++ .../ClickHouseAlterRenameOfflineTest.java | 10 +- .../MaterializedViewStatementsTest.java | 12 +- .../ViewCommentStatementsTest.java | 4 +- 25 files changed, 2542 insertions(+), 49 deletions(-) create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseAtomicMultiRenameTableTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnColumnTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnTableTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseContainers.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCreateOrReplaceViewTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseGroupingSetsTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseListAggTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseMaterializedViewTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseNthValueTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseOffsetTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHousePercentileTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRecursiveCteTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRegularExpressionTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRenameColumnTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRolesTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseTryCastTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUnionDistinctTest.java create mode 100644 dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUsersTest.java diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java index 59e0a08c..71b728b1 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java @@ -615,9 +615,9 @@ default Optional dropMaterializedView(TableReference view, boolean ifExi /** * @return true if {@code createMaterializedView} / {@code dropMaterializedView} render - * statements. An indexed view (SQL Server) is a view with an index, and a ClickHouse + * statements. An indexed view (SQL Server) is a view with an index, and a classic ClickHouse * materialized view feeds a table from the rows inserted into another; neither keeps the - * result of its query, so neither is one. + * result of its query, so neither is one. A refreshable one of ClickHouse (24.10) is. */ default boolean supportsMaterializedViews() { return false; diff --git a/dialect/db/clickhouse/pom.xml b/dialect/db/clickhouse/pom.xml index 8a668233..ed134408 100644 --- a/dialect/db/clickhouse/pom.xml +++ b/dialect/db/clickhouse/pom.xml @@ -46,5 +46,25 @@ biz.aQute.bnd biz.aQute.bndlib + + + com.clickhouse + clickhouse-jdbc + 0.9.8 + all + test + + + org.testcontainers + clickhouse + 1.21.4 + test + + + org.testcontainers + junit-jupiter + 1.21.4 + test + diff --git a/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java b/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java index 753d4e14..1cd0ccca 100644 --- a/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java +++ b/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java @@ -22,8 +22,11 @@ import java.util.Optional; import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.dialect.api.generator.AggregationGenerator; import org.eclipse.daanse.sql.model.sql.BitOperation; +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; public class ClickHouseDialect extends AbstractJdbcDialect { @@ -142,6 +145,225 @@ public ClickHouseDialect(org.eclipse.daanse.sql.dialect.api.DialectInitData init super(init); } + /** What RE2 has not of a Java expression: lookaround, back references, atomic and possessive, class intersection, + * Java's own escapes and flags. Of an escaped backslash it may say so too: that expression is matched in Java. */ + private static final java.util.regex.Pattern NOT_RE2 = java.util.regex.Pattern.compile( + "\\(\\?[=!<>]|\\\\[1-9]|\\\\k<|[*+?}]\\+|&&|\\\\[ZGRXhHV]|\\(\\?[a-zA-Z-]*[xdUc][a-zA-Z-]*[:)]"); + + /** + * Yes, on every version: {@code match} is RE2's, which reads the {@code \A}, {@code \z}, {@code (?:…)}, + * {@code (?i)} and {@code (?-s)} the condition is written with, and {@code \Q…\E}, {@code \d}, {@code \w}, + * {@code \s} and {@code \p{L}} of a Java expression. + */ + @Override + public boolean allowsRegularExpressionInWhereClause() { + return true; + } + + /** + * {@code s IS NOT NULL AND match(s, '(?-s)\A(?:…)\z')}: MDX {@code MATCHES} is Java's {@code Pattern.matches}, + * the whole value, so the expression is anchored at both ends; RE2's dot takes a line break, as Java's does not, + * unless {@code (?-s)} says so. Empty of an expression Java cannot read, and of one with what RE2 has not + * ({@link #NOT_RE2}), which the server would refuse: it is then matched in Java. RE2's {@code (?i)} folds the + * case of letters beyond ASCII too, which Java's does only with {@code (?u)}. + */ + @Override + public Optional generateRegularExpression(String source, String javaRegex) { + try { + java.util.regex.Pattern.compile(javaRegex); + } catch (java.util.regex.PatternSyntaxException e) { + return Optional.empty(); + } + if (NOT_RE2.matcher(javaRegex).find()) { + return Optional.empty(); + } + String regex = withoutUnicodeCaseFlag( + org.eclipse.daanse.sql.dialect.db.common.DialectUtil.cleanUnicodeAwareCaseFlag(javaRegex)); + StringBuilder sb = new StringBuilder(); + sb.append(source).append(" IS NOT NULL AND match(").append(source).append(", "); + quoteStringLiteral(sb, "(?-s)\\A(?:" + regex + ")\\z"); + sb.append(')'); + return Optional.of(sb.toString()); + } + + private static final java.util.regex.Pattern FLAG_GROUP = java.util.regex.Pattern + .compile("\\(\\?([a-zA-Z-]+)([:)])"); + + /** + * Java's {@code u} taken out of each flag group, {@code (?iu)} to {@code (?i)}: RE2 knows no {@code u}, and its + * {@code (?i)} folds the case beyond ASCII as Java's does with {@code u}. A group left without a flag goes, or + * becomes {@code (?:}. + */ + private static String withoutUnicodeCaseFlag(String regex) { + java.util.regex.Matcher m = FLAG_GROUP.matcher(regex); + StringBuilder out = new StringBuilder(); + while (m.find()) { + String flags = m.group(1).replace("u", ""); + String group = flags.isEmpty() || "-".equals(flags) ? (":".equals(m.group(2)) ? "(?:" : "") + : "(?" + flags + m.group(2); + m.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(group)); + } + m.appendTail(out); + return out.toString(); + } + + /** + * Casts with ClickHouse's own type names, and a cast that gives NULL where the value does not fit: + * {@code accurateCastOrNull(x, 'T')}, on every version. It is NULL for what does not parse, for what overflows + * ({@code CAST(300 AS Int8)} gives 44), and for what would lose part of itself ({@code 3.7} as {@code Int32}); + * a date of a month or day out of range it takes as 1970-01-01 or the next month, and a too large Float64 as inf. + * {@code accurateCastOrNull(…, 'Bool')} throws on what is no boolean on 22.x and 23.x and takes {@code 'true'} + * for NULL on 21.12: before 24.3 a boolean is {@code true}, {@code false}, {@code 1} or {@code 0}, else NULL. + */ + @Override + public org.eclipse.daanse.sql.dialect.api.generator.CastGenerator castGenerator() { + boolean boolType = dialectVersion.isUnknownOrAtLeast(21, 12); + boolean boolTryCast = dialectVersion.isUnknownOrAtLeast(24, 3); + return new org.eclipse.daanse.sql.dialect.api.generator.CastGenerator() { + @Override + public String nativeType(org.eclipse.daanse.sql.model.type.Datatype type) { + return switch (type) { + case VARCHAR, BINARY -> "String"; + case INTEGER -> "Int32"; + case BIGINT -> "Int64"; + case SMALLINT -> "Int16"; + case FLOAT, DOUBLE -> "Float64"; + case REAL -> "Float32"; + case NUMERIC, DECIMAL -> "Decimal(38, 10)"; + case BOOLEAN -> boolType ? "Bool" : "UInt8"; + case DATE -> "Date"; + case TIMESTAMP -> "DateTime64(3)"; + case UUID -> "UUID"; + default -> type.getValue().toUpperCase(java.util.Locale.ROOT); + }; + } + + @Override + public boolean supportsTryCast() { + return true; + } + + @Override + public String tryCast(String expr, org.eclipse.daanse.sql.model.type.Datatype type) { + if (type == org.eclipse.daanse.sql.model.type.Datatype.BOOLEAN && !boolTryCast) { + String s = "lower(toString(" + expr + "))"; + return "if(" + s + " IN ('true', 'false', '1', '0'), " + s + " IN ('true', '1'), NULL)"; + } + return "accurateCastOrNull(" + expr + ", '" + nativeType(type) + "')"; + } + }; + } + + /** + * From 24.10, a refreshable materialized view: it computes its query when it is created and keeps the rows until + * it is refreshed ({@code SYSTEM REFRESH VIEW}), as the contract asks. 24.3 and 24.8 refuse one without an + * experimental setting (Code 344), 23.8 knows no {@code REFRESH}; the classic ClickHouse materialized view feeds a + * table from the rows inserted into another and keeps no result of its query. The dialect has it refresh only after ten + * years, a refresh on demand in effect. The first refresh runs in the background as the view is created: a read + * at once may find it empty, {@code SYSTEM WAIT VIEW} waits for it. A dialect made without a connection takes + * such a version. + */ + @Override + public boolean supportsMaterializedViews() { + return dialectVersion.isUnknownOrAtLeast(24, 10); + } + + /** + * {@code CREATE MATERIALIZED VIEW [IF NOT EXISTS] v REFRESH AFTER 10 YEAR ENGINE = MergeTree() ORDER BY tuple() + * AS …}: the rows kept in a MergeTree table of their own (see {@link #supportsMaterializedViews}). + */ + @Override + public Optional createMaterializedView(TableReference view, String selectSql, boolean ifNotExists) { + if (!supportsMaterializedViews()) { + return Optional.empty(); + } + if (selectSql == null || selectSql.isBlank()) { + throw new IllegalArgumentException("selectSql must not be blank for CREATE MATERIALIZED VIEW"); + } + return Optional.of("CREATE MATERIALIZED VIEW " + (ifNotExists ? "IF NOT EXISTS " : "") + qualified(view) + + " REFRESH AFTER 10 YEAR ENGINE = MergeTree() ORDER BY tuple() AS " + selectSql); + } + + /** {@code DROP VIEW [IF EXISTS] v}: ClickHouse has no {@code DROP MATERIALIZED VIEW} (a syntax error). */ + @Override + public Optional dropMaterializedView(TableReference view, boolean ifExists) { + if (!supportsMaterializedViews()) { + return Optional.empty(); + } + return Optional.of("DROP VIEW " + (ifExists ? "IF EXISTS " : "") + qualified(view)); + } + + /** + * {@code LIMIT n OFFSET m}, {@code LIMIT n}, {@code OFFSET m}, on every version, with an ORDER BY or without. The + * standard {@code OFFSET m ROWS FETCH NEXT n ROWS ONLY} is refused without an ORDER BY on every version (a syntax + * error on 21.x, Code 628 on 23.8 and later), and {@code FETCH} without {@code OFFSET} on 21.x; MySQL's huge limit + * for an offset alone gives no row at all on 26.6. The parameters of the prepared form go in that order too. + */ + @Override + public org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator paginationGenerator() { + return new org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator() { + @Override + public String paginate(java.util.OptionalLong limit, java.util.OptionalLong offset) { + StringBuilder sb = new StringBuilder(); + limit.ifPresent(l -> { + if (l < 0) { + throw new IllegalArgumentException("limit must be >= 0"); + } + sb.append(" LIMIT ").append(l); + }); + offset.ifPresent(o -> { + if (o < 0) { + throw new IllegalArgumentException("offset must be >= 0"); + } + sb.append(" OFFSET ").append(o); + }); + return sb.toString(); + } + + @Override + public PreparedPaging paginatePrepared(boolean withLimit, boolean withOffset) { + if (withLimit && withOffset) { + return new PreparedPaging("LIMIT ? OFFSET ?", List.of(PagingParam.LIMIT, PagingParam.OFFSET)); + } else if (withLimit) { + return new PreparedPaging("LIMIT ?", List.of(PagingParam.LIMIT)); + } else if (withOffset) { + return new PreparedPaging("OFFSET ?", List.of(PagingParam.OFFSET)); + } + return new PreparedPaging("", List.of()); + } + }; + } + + /** + * {@code WITH RECURSIVE} from 24.4; 24.3 and before refuse it with a syntax error (Code 62), and the dialect writes + * no RECURSIVE there. A recursive expression runs on the new analyzer only, on by default from 24.3: a session + * that turns it off ({@code allow_experimental_analyzer = 0}) refuses one, which no flag of the dialect can say. + * Expressions that are not recursive run on every version. A dialect made without a connection takes such a + * version. + */ + @Override + public org.eclipse.daanse.sql.dialect.api.generator.CteGenerator cteGenerator() { + boolean recursive = dialectVersion.isUnknownOrAtLeast(24, 4); + return new org.eclipse.daanse.sql.dialect.api.generator.CteGenerator() { + @Override + public boolean supportsRecursiveCte() { + return recursive; + } + }; + } + + /** + * From 22.9. {@code GROUP BY GROUPING SETS} comes with 22.6, but 22.6 leaves the rows of one unsorted by an + * {@code ORDER BY}, and 22.6 to 22.8 give {@code GROUPING()} the other way round, 1 for a column grouped by, until + * 22.9 turns {@code force_grouping_standard_compatibility} on. A total's key of a column that is not Nullable is + * the type's default, '' or 0, not NULL, unless the session sets {@code group_by_use_nulls = 1}: + * {@code GROUPING()} tells it from a value. A dialect made without a connection takes such a version. + */ + @Override + public boolean supportsGroupingSets() { + return dialectVersion.isUnknownOrAtLeast(22, 9); + } + @Override public boolean supportsSequences() { return false; @@ -158,12 +380,27 @@ public boolean supportsRenameIndex() { return false; // skipping indexes: only DROP INDEX / ADD INDEX } + /** + * {@code ALTER TABLE … RENAME COLUMN} from 20.4; 20.3 refuses it with a syntax error (Code 62), and + * {@code renameColumn} then gives {@code null}. A dialect made without a connection takes such a version. + */ + @Override + public boolean supportsRenameColumn() { + return dialectVersion.isUnknownOrAtLeast(20, 4); + } + /** ClickHouse has no constraint rename. */ @Override public boolean supportsRenameConstraint() { return false; } + /** + * No, though ClickHouse takes {@code CREATE OR REPLACE VIEW} on every version from 21.3 on, the first of the + * images run: it replaces whatever is there under the name, a table too, which it drops with its rows, where + * MySQL, Oracle and PostgreSQL refuse to replace anything but a view. With {@code orReplace} the dialect writes a + * plain {@code CREATE VIEW}, which fails on anything there of the name and drops no table. + */ @Override public boolean supportsCreateOrReplaceView() { return false; @@ -179,6 +416,10 @@ public boolean requiresDrillthroughMaxRowsInLimit() { * {@code union_default_mode} setting is empty (the default): * {@code Code: 558 DB::Exception: Expected ALL or DISTINCT in SelectWithUnion * query}. Spell the duplicate-eliminating union explicitly. + * + *

+ * {@code UNION DISTINCT} comes with 21.1. Before, ClickHouse has only {@code UNION ALL} and refuses both + * spellings with a syntax error (Code 62): no keyword eliminates duplicates there. */ @Override public String unionDistinctKeyword() { @@ -222,31 +463,144 @@ public boolean supportsBitAggregation(BitOperation operation) { return true; // ClickHouse supports all bit operations } + /** + * {@code arrayStringConcat(…, 'sep')} over the values of the group. + * + *

+ * ClickHouse has no ordered string aggregate: {@code groupConcat} comes only with 24.8 and takes no + * {@code ORDER BY}, and {@code groupArrayArray}, written here before, takes arrays and refused a column of + * anything else (Code 43). Without an order the list is {@code groupArray} ({@code groupUniqArray} for DISTINCT), + * which leaves the NULLs out. With an order the group's rows are sorted by the columns, the NULL values + * dropped (see {@link #sortedRows}). DISTINCT keeps the first place of a value. Every function used is in every + * ClickHouse from 21.8 on. + */ @Override public java.util.Optional generateListAgg(CharSequence operand, boolean distinct, String separator, String coalesce, String onOverflowTruncate, List columns) { - StringBuilder buf = new StringBuilder(64); - buf.append("groupArrayArray"); - buf.append("( "); - buf.append(operand); - buf.append(")"); - // groupArrayArray(page_visits) - return java.util.Optional.of((buf).toString()); + StringBuilder sep = new StringBuilder(); + quoteStringLiteral(sep, separator == null ? "," : separator); + String values; + if (columns == null || columns.isEmpty()) { + values = "arrayMap(_v -> toString(_v), " + (distinct ? "groupUniqArray(" : "groupArray(") + operand + + "))"; + } else { + String sorted = sortedRows(operand, true, columns); + values = "arrayMap(_r -> toString(assumeNotNull(tupleElement(_r, 1))), " + sorted + ")"; + if (distinct) { + values = "arrayDistinct(" + values + ")"; + } + } + return java.util.Optional.of("arrayStringConcat(" + values + ", " + sep + ")"); } /** - * No ordered array aggregate to pick the n-th value from; the window function NTH_VALUE runs over the groups of - * a grouped query, not over the rows of one group, so it is no answer either (V-82). The measure is refused. + * The n-th value of the rows of the group, in the order of the columns: the n-th element of the group's rows + * sorted as {@link #generateListAgg} sorts them, the NULL values counted or left out as asked. An aggregate, not + * the window function {@code nth_value … OVER}, which in a grouped query runs over the groups (V-82). n counts + * from 1, below 1 is 1; a group with fewer values gives NULL, not the type's default an array gives past its end. + * Every function used is in every ClickHouse from 21.8 on. */ @Override public java.util.Optional generateNthValueAgg(CharSequence operand, boolean ignoreNulls, Integer n, List columns) { - return java.util.Optional.empty(); + int nth = AggregationGenerator.nthIndex(n); + return java.util.Optional.of("arrayMap(_a -> if(length(_a) >= " + nth + ", tupleElement(_a[" + nth + + "], 1), NULL), [" + sortedRows(operand, ignoreNulls, columns) + "])[1]"); } @Override public boolean supportsNthValue() { - return false; + return true; + } + + @Override + public boolean supportsNthValueIgnoreNulls() { + return true; + } + + /** + * The rows of the group as {@code tuple(operand, key1, …)}, sorted by the columns, the rows of a NULL operand left + * out where asked. ClickHouse has no ORDER BY in an aggregate: the group is collected with {@code groupArray}, and + * sorted once per key, the last key first. {@code arraySort} is not stable, so each pass breaks ties by the place + * in the pass before; {@code arrayReverseSort} is how a key sorts descending whatever its type. The NULLs of a key + * go last unless the column asks for them first, as in ClickHouse's own {@code ORDER BY}. + */ + private String sortedRows(CharSequence operand, boolean dropNullOperands, List columns) { + List keys = columns == null ? List.of() : columns; + StringBuilder rows = new StringBuilder("groupArray(tuple(").append(operand); + for (OrderedColumn c : keys) { + rows.append(", "); + if (c.tableName() != null) { + quoteIdentifier(rows, c.tableName(), c.columnName()); + } else { + quoteIdentifier(rows, c.columnName()); + } + } + rows.append("))"); + String sorted = dropNullOperands ? "arrayFilter(_r -> isNotNull(tupleElement(_r, 1)), " + rows + ")" + : rows.toString(); + for (int k = keys.size() - 1; k >= 0; k--) { + OrderedColumn c = keys.get(k); + boolean desc = c.sortDirection().orElse(SortDirection.ASC) == SortDirection.DESC; + boolean nullsFirst = c.nullsOrder().orElse(NullsOrder.LAST) == NullsOrder.FIRST; + String key = "tupleElement(_r, " + (k + 2) + ")"; + // arraySort puts the lower flag first, arrayReverseSort the higher one + String flag = (nullsFirst != desc ? "isNotNull(" : "isNull(") + key + ")"; + sorted = "arrayMap(_a -> " + (desc ? "arrayReverseSort" : "arraySort") + "((_r, _i) -> (" + flag + + ", assumeNotNull(" + key + "), " + (desc ? "-_i" : "_i") + "), _a, arrayEnumerate(_a)), [" + + sorted + "])[1]"; + } + return sorted; + } + + /** + * {@code PERCENTILE_DISC(p) WITHIN GROUP (ORDER BY c)}: the first value of the sorted group whose cumulative share + * reaches p, the {@code max(1, ceil(p n))}-th of the group's n values that are not NULL. ClickHouse has no such + * aggregate, and none of its quantiles gives it: {@code quantileExactLow(0.25)} of 10, 20, 30, 40 is 20, not 10. + * An empty group gives NULL. Every function used is in every ClickHouse from 21.3 on. + */ + @Override + public java.util.Optional generatePercentileDisc(double percentile, boolean desc, String tableName, + String columnName) { + return java.util.Optional.of("arrayMap(_a -> if(length(_a) = 0, NULL, _a[toUInt64(greatest(1, ceil(" + + percentile + " * length(_a))))]), [" + sortedGroup(desc, tableName, columnName) + "])[1]"); + } + + /** + * {@code PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY c)}: the value at {@code 1 + p (n - 1)} of the sorted group, + * interpolated between its two neighbours. {@code quantileExactInclusive(p)} is that from 23.8, but 21.x gives + * the 2nd value for p = 1; the dialect computes it on the sorted group on every version. An empty group gives + * NULL. + */ + @Override + public java.util.Optional generatePercentileCont(double percentile, boolean desc, String tableName, + String columnName) { + String lo = "_a[toUInt64(floor(_r))]"; + String hi = "_a[toUInt64(ceil(_r))]"; + return java.util.Optional.of("arrayMap(_a -> if(length(_a) = 0, NULL, arrayMap(_r -> " + lo + + " + (_r - floor(_r)) * (" + hi + " - " + lo + "), [1 + " + percentile + " * (length(_a) - 1)])[1]), [" + + sortedGroup(desc, tableName, columnName) + "])[1]"); + } + + @Override + public boolean supportsPercentileDisc() { + return true; + } + + @Override + public boolean supportsPercentileCont() { + return true; + } + + /** The group's values that are not NULL, sorted ascending or descending: {@code groupArray} leaves NULLs out. */ + private String sortedGroup(boolean desc, String tableName, String columnName) { + StringBuilder col = new StringBuilder(); + if (tableName != null) { + quoteIdentifier(col, tableName, columnName); + } else { + quoteIdentifier(col, columnName); + } + return (desc ? "arrayReverseSort(" : "arraySort(") + "groupArray(" + col + "))"; } @Override @@ -278,42 +632,39 @@ public String renameView(TableReference view, String newName) { .append(quoteIdentifier(newName)).toString(); } - /** {@code RENAME TABLE a TO b, c TO d} — one atomic statement. */ - @Override - public List renameTables(List renames) { - if (renames == null || renames.isEmpty()) { - return List.of(); - } - StringBuilder sb = new StringBuilder("RENAME TABLE "); - for (int i = 0; i < renames.size(); i++) { - if (i > 0) { - sb.append(", "); - } - TableRename r = renames.get(i); - sb.append(qualified(r.table())).append(" TO ").append(quoteIdentifier(r.newName())); - } - return List.of(sb.toString()); - } - + /** + * No. ClickHouse takes {@code RENAME TABLE a TO b, c TO d} as one statement, but runs the renames one after the + * other and undoes none when a later one fails: the tables renamed before stay renamed, on every version and in + * an Atomic database too. Only {@code EXCHANGE TABLES} swaps atomically, which a list of renames does not say. + * {@code renameTables} writes one {@code RENAME TABLE} per rename, as it says where there is no atomicity. + */ @Override public boolean supportsAtomicMultiRenameTable() { - return true; + return false; } - /** {@code ALTER TABLE t MODIFY COMMENT '…'}; {@code null} clears it. */ + /** + * {@code ALTER TABLE t MODIFY COMMENT '…'}, for a view too ({@link #supportsCommentOnView}); {@code null} clears + * it. {@code MODIFY COMMENT} comes with 21.11, 21.10 refuses it with a syntax error (Code 62); before, no comment + * is written. A dialect made without a connection takes such a version. + */ @Override public java.util.Optional commentOnTable(TableReference table, String comment) { - if (TableReference.TYPE_VIEW.equals(table.type())) { + boolean view = TableReference.TYPE_VIEW.equals(table.type()); + if (view ? !supportsCommentOnView() : !dialectVersion.isUnknownOrAtLeast(21, 11)) { return java.util.Optional.empty(); } return java.util.Optional.of("ALTER TABLE " + qualified(table) + " MODIFY COMMENT " + chLiteral(comment)); } - /** {@code ALTER TABLE t COMMENT COLUMN c '…'}; {@code null} clears it. */ + /** + * {@code ALTER TABLE t COMMENT COLUMN c '…'}; {@code null} clears it. A view's column from 22.1, as the comment + * of a view ({@link #supportsCommentOnView}). + */ @Override public java.util.Optional commentOnColumn(TableReference table, String columnName, String comment, org.eclipse.daanse.sql.model.schema.ColumnMetaData currentMeta) { - if (TableReference.TYPE_VIEW.equals(table.type())) { + if (TableReference.TYPE_VIEW.equals(table.type()) && !supportsCommentOnView()) { return java.util.Optional.empty(); } return java.util.Optional.of("ALTER TABLE " + qualified(table) + " COMMENT COLUMN " @@ -335,21 +686,42 @@ public boolean supportsNamedPrimaryKey() { * ClickHouse lets a user without a password in from any host, so a user is created with no host * to come from, {@code CREATE USER "x" HOST NONE}, and logs in once it is altered to have a * password and hosts. + * + *

+ * Users, as all access control by SQL, come with 20.4. A dialect made without a connection takes such a version. */ @Override public boolean supportsUsers() { - return true; + return dialectVersion.isUnknownOrAtLeast(20, 4); + } + + /** + * Roles, {@code CREATE ROLE [IF NOT EXISTS]}, {@code DROP ROLE [IF EXISTS]}, granted to a user with the admin + * option too, come with 20.4, as all access control by SQL. A dialect made without a connection takes such a + * version. + */ + @Override + public boolean supportsRoles() { + return dialectVersion.isUnknownOrAtLeast(20, 4); } @Override public Optional createUser(String userName, boolean ifNotExists) { + if (!supportsUsers()) { + return Optional.empty(); + } return Optional.of("CREATE USER " + (ifNotExists ? "IF NOT EXISTS " : "") + quoteIdentifier(userName) + " HOST NONE"); } - /** ClickHouse sets a comment with {@code ALTER TABLE … MODIFY COMMENT}, which takes no view. */ + /** + * From 22.1. {@code ALTER TABLE … MODIFY COMMENT} takes a view as a table from 21.11, and {@code COMMENT COLUMN} + * a view's column, but 21.11 and 21.12 write the comment of a view after its query into the view's metadata, + * which they cannot read again: the next ALTER of the view fails with a syntax error in its {@code .sql} file, + * and the server does not start again. A dialect made without a connection takes such a version. + */ @Override public boolean supportsCommentOnView() { - return false; + return dialectVersion.isUnknownOrAtLeast(22, 1); } } diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialectTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialectTest.java index 64f71530..5a6ab183 100644 --- a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialectTest.java +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialectTest.java @@ -57,8 +57,9 @@ void testRequiresDrillthroughMaxRowsInLimit() { @Test void capability_flags_reflect_clickhouse_constraints() { - // ClickHouse: no FK / sequences, no DROP CONSTRAINT IF EXISTS, no - // CREATE OR REPLACE VIEW. Most other IF EXISTS forms ARE supported. + // ClickHouse: no FK / sequences, no DROP CONSTRAINT IF EXISTS, no CREATE OR + // REPLACE VIEW (it would replace a table too, rows and all). Most other + // IF EXISTS forms ARE supported. assertFalse(dialect.supportsSequences()); assertFalse(dialect.supportsDropConstraintIfExists()); assertFalse(dialect.supportsCreateOrReplaceView()); @@ -152,7 +153,7 @@ class WindowFunctionTests { @Test void testSupportsNthValue() { - assertFalse(dialect.supportsNthValue()); // V-82: no ordered array aggregate, the window form ran over the groups + assertTrue(dialect.supportsNthValue()); // an aggregate over the sorted rows of the group (V-82) } @Test @@ -163,7 +164,7 @@ void testSupportsListAgg() { @Test void testGenerateListAgg() { String result = dialect.generateListAgg("column1", false, null, null, null, null).orElseThrow(); - assertEquals("groupArrayArray( column1)", result); + assertEquals("arrayStringConcat(arrayMap(_v -> toString(_v), groupArray(column1)), ',')", result); } } diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseAtomicMultiRenameTableTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseAtomicMultiRenameTableTest.java new file mode 100644 index 00000000..6483d90e --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseAtomicMultiRenameTableTest.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.clickhouse.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.api.generator.DdlGenerator.TableRename; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse takes {@code RENAME TABLE a TO b, c TO d} as one statement, but runs the renames one after the other and + * undoes none when a later one fails, in an Atomic database too, the default on every version here: the statement is + * not atomic, and the dialect says so. Its {@code renameTables} writes one {@code RENAME TABLE} per rename, which, + * run in order, swap two tables through a third name, their rows going with them, and rename a view as a table. A + * view reads its table by name, the table there under that name after a swap. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseAtomicMultiRenameTableTest { + + private static final List SETUP = List.of( + "CREATE TABLE a(x Int32) ENGINE = MergeTree() ORDER BY x", + "CREATE TABLE b(x Int32) ENGINE = MergeTree() ORDER BY x", + "CREATE TABLE c(x Int32) ENGINE = MergeTree() ORDER BY x", + "INSERT INTO a VALUES (1)", "INSERT INTO b VALUES (2)", "INSERT INTO c VALUES (3)", + "CREATE VIEW v AS SELECT x FROM a"); + + private static final String TABLES = "SELECT name FROM system.tables WHERE database = currentDatabase()" + + " ORDER BY name"; + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void multi_rename(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + assertThat(rows(st, "SELECT engine FROM system.databases WHERE name = currentDatabase()")) + .as("an Atomic database").containsExactly("Atomic"); + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsAtomicMultiRenameTable()).as("supportsAtomicMultiRenameTable").isFalse(); + + assertThatThrownBy(() -> st.execute("RENAME TABLE a TO a2, b TO c")) + .as("the second rename fails, c is there").isInstanceOf(SQLException.class); + assertThat(rows(st, TABLES)).as("the first one is not undone: not atomic") + .containsExactly("a2", "b", "c", "v"); + st.execute("RENAME TABLE a2 TO a"); + + List swap = dialect.renameTables(List.of(new TableRename(table("a"), "tmp"), + new TableRename(table("b"), "a"), new TableRename(table("tmp"), "b"))); + assertThat(swap).as("one statement per rename").hasSize(3) + .allSatisfy(sql -> assertThat(sql).startsWith("RENAME TABLE ").doesNotContain(",")); + for (String sql : swap) { + execute(st, sql); + } + assertThat(rows(st, TABLES)).as("the same tables").containsExactly("a", "b", "c", "v"); + assertThat(rows(st, "SELECT toString(x) FROM a")).as("a holds b's rows").containsExactly("2"); + assertThat(rows(st, "SELECT toString(x) FROM b")).as("b holds a's rows").containsExactly("1"); + + for (String sql : dialect.renameTables(List.of(new TableRename(table("c"), "c2"), + new TableRename(new TableReference(Optional.empty(), "v", TableReference.TYPE_VIEW), "v2")))) { + execute(st, sql); + } + assertThat(rows(st, TABLES)).as("a table and a view renamed").containsExactly("a", "b", "c2", "v2"); + assertThat(rows(st, "SELECT toString(x) FROM v2")).as("the renamed view reads a, by its name") + .containsExactly("2"); + assertThat(rows(st, "SELECT toString(x) FROM c2")).as("c2 holds c's rows").containsExactly("3"); + + assertThat(dialect.renameTables(List.of())).as("nothing to rename").isEmpty(); + } + } + } + + private static TableReference table(String name) { + return new TableReference(Optional.empty(), name, TableReference.TYPE_TABLE); + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnColumnTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnColumnTest.java new file mode 100644 index 00000000..0ec78375 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnColumnTest.java @@ -0,0 +1,131 @@ +/* + * 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.clickhouse.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse sets the comment of a column with {@code ALTER TABLE t COMMENT COLUMN c '…'}, which changes the comment + * only, on every version here; the column of a view from 22.1 (21.11 and 21.12 write a view's comments into metadata + * they cannot read again, see {@link ClickHouseCommentOnTableTest}). The dialect is built from a live connection: the + * comment it writes, with a quote and a backslash in it, is the column's, on a column of the sorting key and a + * Nullable one too, stays when the table is detached and attached again, and a {@code null} clears it; the column + * keeps its type, its default and its values. From 22.1 on so for a view's column; before, it writes none there. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseCommentOnColumnTest { + + private static final TableReference T = new TableReference(Optional.empty(), "t", TableReference.TYPE_TABLE); + private static final TableReference V = new TableReference(Optional.empty(), "v", TableReference.TYPE_VIEW); + + private static final List SETUP = List.of(""" + CREATE TABLE t(id Int32, note String DEFAULT 'n/a', price Nullable(Decimal(10, 2))) + ENGINE = MergeTree() ORDER BY id""", "INSERT INTO t(id, note, price) VALUES (1, 'x', 1.5), (2, 'y', NULL)", + "CREATE VIEW v AS SELECT id, note FROM t"); + + private static final String COMMENT = "it's a \\ comment"; + + /** Name, type, default and comment of each column of the table, in its order. */ + private static final String COLUMNS = """ + SELECT concat(name, '|', type, '|', if(default_expression = '', '-', default_expression), '|', + if(comment = '', '-', comment)) + FROM system.columns WHERE database = currentDatabase() AND table = '%s'"""; + + @ParameterizedTest(name = "clickhouse:{0} -> view column {1}") + @CsvSource({ "21.3, false", "21.8, false", "21.12, false", "22.1, true", "23.8, true", "24.8, true", + "25.8, true", "26.6, true" }) + void comment_on_column(String tag, boolean onView) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + + execute(st, dialect.commentOnColumn(T, "note", COMMENT, null).orElseThrow()); + execute(st, dialect.commentOnColumn(T, "id", "the key", null).orElseThrow()); + execute(st, dialect.commentOnColumn(T, "price", "may be null", null).orElseThrow()); + assertThat(rows(st, COLUMNS.formatted("t"))).as("each comment, the column kept whole") + .containsExactly("id|Int32|-|the key", "note|String|'n/a'|" + COMMENT, + "price|Nullable(Decimal(10, 2))|-|may be null"); + + st.execute("DETACH TABLE t"); + st.execute("ATTACH TABLE t"); + assertThat(rows(st, COLUMNS.formatted("t"))).as("kept when the table is attached again") + .contains("note|String|'n/a'|" + COMMENT); + + execute(st, dialect.commentOnColumn(T, "note", "another", null).orElseThrow()); + execute(st, dialect.commentOnColumn(T, "id", null, null).orElseThrow()); + assertThat(rows(st, COLUMNS.formatted("t"))).as("replaced, and null clears it") + .containsExactly("id|Int32|-|-", "note|String|'n/a'|another", + "price|Nullable(Decimal(10, 2))|-|may be null"); + assertThat(rows(st, "SELECT concat(toString(id), '|', note, '|', ifNull(toString(toFloat64(price))," + + " '-')) FROM t ORDER BY id")).as("the values kept").containsExactly("1|x|1.5", "2|y|-"); + st.execute("INSERT INTO t(id) VALUES (3)"); + assertThat(rows(st, "SELECT note FROM t WHERE id = 3")).as("the default kept").containsExactly("n/a"); + + if (!onView) { + assertThat(dialect.commentOnColumn(V, "note", COMMENT, null)).as("no comment on a view's column" + + " before 22.1").isEmpty(); + return; + } + execute(st, dialect.commentOnColumn(V, "note", COMMENT, null).orElseThrow()); + assertThat(rows(st, COLUMNS.formatted("v"))).as("a view's column's comment") + .containsExactly("id|Int32|-|-", "note|String|-|" + COMMENT); + st.execute("DETACH TABLE v"); + st.execute("ATTACH TABLE v"); + assertThat(rows(st, COLUMNS.formatted("v"))).as("read again when the view is attached") + .containsExactly("id|Int32|-|-", "note|String|-|" + COMMENT); + assertThat(rows(st, "SELECT note FROM v ORDER BY id")).as("the view still reads") + .containsExactly("x", "y", "n/a"); + execute(st, dialect.commentOnColumn(V, "note", null, null).orElseThrow()); + assertThat(rows(st, COLUMNS.formatted("v"))).as("null clears a view's column's") + .containsExactly("id|Int32|-|-", "note|String|-|-"); + } + } + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnTableTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnTableTest.java new file mode 100644 index 00000000..98faac3f --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCommentOnTableTest.java @@ -0,0 +1,131 @@ +/* + * 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.clickhouse.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.clickhouse.ClickHouseDialect; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse sets the comment of a table with {@code ALTER TABLE t MODIFY COMMENT '…'} from 21.11; 21.10 refuses it + * with a syntax error. It takes a view there as a table, and the column of a view in {@code COMMENT COLUMN}, but 21.11 + * and 21.12 write the comment of a view into metadata they cannot read again: the next ALTER of the view fails, and + * the server does not start again; 22.1 reads it. The dialect is built from a live connection: from 21.11 on the + * comment it writes, with a quote and a backslash in it, is the table's, stays with it when it is detached and + * attached again, and a {@code null} clears it; from 22.1 on so for a view and a view's column, which then still + * takes an ALTER and is read again when attached. Before, it writes no comment there. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseCommentOnTableTest { + + private static final TableReference T = new TableReference(Optional.empty(), "t", TableReference.TYPE_TABLE); + private static final TableReference V = new TableReference(Optional.empty(), "v", TableReference.TYPE_VIEW); + + private static final List SETUP = List.of( + "CREATE TABLE t(id Int32) ENGINE = MergeTree() ORDER BY id", + "CREATE VIEW v AS SELECT id FROM t"); + + private static final String COMMENT = "it's a \\ comment"; + + @ParameterizedTest(name = "clickhouse:{0} -> table {1}, view {2}") + @CsvSource({ "21.8, false, false", "21.10, false, false", "21.11, true, false", "21.12, true, false", + "22.1, true, true", "23.8, true, true", "24.8, true, true", "25.8, true, true", "26.6, true, true" }) + void comment_on_table(String tag, boolean onTable, boolean onView) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsCommentOnView()).as("supportsCommentOnView").isEqualTo(onView); + + if (!onView) { + assertThat(dialect.commentOnTable(V, COMMENT)).as("no comment on a view before 22.1").isEmpty(); + assertThat(dialect.commentOnColumn(V, "id", COMMENT, null)).as("nor on a view's column") + .isEmpty(); + } + if (!onTable) { + assertThat(dialect.commentOnTable(T, COMMENT)).as("no comment before 21.11").isEmpty(); + assertThatThrownBy(() -> st.execute("ALTER TABLE t MODIFY COMMENT 'x'")) + .as("the server refuses it").isInstanceOf(SQLException.class) + .hasMessageContaining("Syntax error"); + return; + } + + execute(st, dialect.commentOnTable(T, COMMENT).orElseThrow()); + assertThat(comment(st, "t")).as("the comment, quote and backslash kept").isEqualTo(COMMENT); + st.execute("DETACH TABLE t"); + st.execute("ATTACH TABLE t"); + assertThat(comment(st, "t")).as("kept when the table is attached again").isEqualTo(COMMENT); + execute(st, dialect.commentOnTable(T, "another").orElseThrow()); + assertThat(comment(st, "t")).as("replaced").isEqualTo("another"); + execute(st, dialect.commentOnTable(T, null).orElseThrow()); + assertThat(comment(st, "t")).as("null clears it").isEmpty(); + if (!onView) { + return; + } + + execute(st, dialect.commentOnTable(V, COMMENT).orElseThrow()); + assertThat(comment(st, "v")).as("a view's comment").isEqualTo(COMMENT); + execute(st, dialect.commentOnColumn(V, "id", COMMENT, null).orElseThrow()); + assertThat(rows(st, "SELECT comment FROM system.columns WHERE database = currentDatabase()" + + " AND table = 'v' AND name = 'id'")).as("a view's column's comment").containsExactly(COMMENT); + st.execute("DETACH TABLE v"); + st.execute("ATTACH TABLE v"); + assertThat(comment(st, "v")).as("a view's, read again when attached").isEqualTo(COMMENT); + execute(st, dialect.commentOnTable(V, null).orElseThrow()); + assertThat(comment(st, "v")).as("null clears a view's").isEmpty(); + } + } + } + + private static String comment(Statement st, String table) throws SQLException { + List rows = rows(st, + "SELECT comment FROM system.tables WHERE database = currentDatabase() AND name = '" + table + "'"); + assertThat(rows).hasSize(1); + return rows.get(0); + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseContainers.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseContainers.java new file mode 100644 index 00000000..f23a2579 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseContainers.java @@ -0,0 +1,41 @@ +/* + * 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.clickhouse.container; + +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** What the Docker tests of the ClickHouse dialect share. */ +final class ClickHouseContainers { + + private ClickHouseContainers() { + } + + /** A container of the server of the image tag, from {@code clickhouse/clickhouse-server} (21.3 and later). */ + static ClickHouseContainer container(String tag) { + return new ClickHouseContainer("clickhouse/clickhouse-server:" + tag); + } + + /** + * The JDBC URL of the container for a server of the image tag. The driver's default implementation sends + * {@code async_insert} with every DDL and INSERT, a setting ClickHouse has from 21.11 on; an older server refuses + * it with Code 115 and the driver reports a 404. Its V1 implementation does not send it. + */ + static String jdbcUrl(ClickHouseContainer ch, String tag) { + return before(tag, 21, 11) ? ch.getJdbcUrl() + "?clickhouse.jdbc.v1=true" : ch.getJdbcUrl(); + } + + /** Whether the image tag names a version before {@code major.minor}. */ + static boolean before(String tag, int major, int minor) { + String[] v = tag.split("\\."); + int tagMajor = Integer.parseInt(v[0]); + int tagMinor = v.length > 1 ? Integer.parseInt(v[1]) : 0; + return tagMajor < major || (tagMajor == major && tagMinor < minor); + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCreateOrReplaceViewTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCreateOrReplaceViewTest.java new file mode 100644 index 00000000..ed1bf44c --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseCreateOrReplaceViewTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.clickhouse.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.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse takes {@code CREATE OR REPLACE VIEW} on every version here, but replaces whatever is there under the + * name, a table too, which it drops with its rows; MySQL, Oracle and PostgreSQL refuse to replace anything but a view. + * The dialect is built from a live connection and says it has no {@code CREATE OR REPLACE VIEW}: with + * {@code orReplace} it writes a plain {@code CREATE VIEW}, which creates the view where there is none, fails on a + * view of the name, and on a table of the name, which keeps its rows. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseCreateOrReplaceViewTest { + + private static final TableReference V = new TableReference(Optional.empty(), "v", TableReference.TYPE_VIEW); + + private static final List SETUP = List.of("CREATE TABLE t(x Int32) ENGINE = MergeTree() ORDER BY x", + "INSERT INTO t VALUES (1), (2)", "CREATE TABLE u(x Int32) ENGINE = MergeTree() ORDER BY x", + "INSERT INTO u VALUES (3)"); + + private static final String ENGINES = "SELECT concat(name, '|', engine) FROM system.tables" + + " WHERE database = currentDatabase() ORDER BY name"; + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void create_or_replace_view(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsCreateOrReplaceView()).as("supportsCreateOrReplaceView").isFalse(); + + String create = dialect.createView(V, "SELECT x FROM t", true); + assertThat(create).as("a plain CREATE VIEW").startsWith("CREATE VIEW ").doesNotContain("REPLACE"); + execute(st, create); + assertThat(rows(st, "SELECT toString(x) FROM v ORDER BY x")).as("created where there is none") + .containsExactly("1", "2"); + assertThatThrownBy(() -> st.execute(dialect.createView(V, "SELECT x * 10 AS x FROM t", true))) + .as("a view of the name").isInstanceOf(SQLException.class); + + TableReference table = new TableReference(Optional.empty(), "t", TableReference.TYPE_VIEW); + assertThatThrownBy(() -> st.execute(dialect.createView(table, "SELECT 1 AS x", true))) + .as("a table of the name").isInstanceOf(SQLException.class); + assertThat(rows(st, "SELECT toString(x) FROM t ORDER BY x")).as("the table keeps its rows") + .containsExactly("1", "2"); + + // why: the server's own OR REPLACE replaces a view, and a table as well, its rows gone + st.execute("CREATE OR REPLACE VIEW v AS SELECT x * 10 AS x FROM t"); + assertThat(rows(st, "SELECT toString(x) FROM v ORDER BY x")).as("OR REPLACE replaces a view") + .containsExactly("10", "20"); + st.execute("CREATE OR REPLACE VIEW u AS SELECT 1 AS x"); + assertThat(rows(st, ENGINES)).as("and a table, dropped for a view") + .containsExactly("t|MergeTree", "u|View", "v|View"); + } + } + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseGroupingSetsTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseGroupingSetsTest.java new file mode 100644 index 00000000..2bc981d3 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseGroupingSetsTest.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.clickhouse.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.ResultSetMetaData; +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.clickhouse.ClickHouseDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has {@code GROUP BY GROUPING SETS} from 22.6, but 22.6 leaves its rows unsorted by an {@code ORDER BY}, + * and 22.6 to 22.8 give {@code GROUPING()} the other way round; 22.9 gives it as the standard does. The dialect is + * built from a live connection: from 22.9 on {@code supportsGroupingSets()} says yes, and the statements give a row + * per grouping set, its total and its {@code GROUPING()} bits, with the dialect's {@code GROUPING()}, and ROLLUP and + * CUBE too; before, it says no. A total's key of a column that is not Nullable is the type's default, not NULL, + * unless {@code group_by_use_nulls = 1}, under which 24.8 and 25.8 refuse {@code GROUPING()}. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseGroupingSetsTest { + + private static final List SETUP = List.of( + "CREATE TABLE sales(region Nullable(String), product Nullable(String), amount Int32)" + + " ENGINE = MergeTree() ORDER BY tuple()", + "INSERT INTO sales VALUES ('EU', 'A', 10), ('EU', 'B', 20), ('US', 'A', 30)", + "CREATE TABLE plain(region String, amount Int32) ENGINE = MergeTree() ORDER BY tuple()", + "INSERT INTO plain VALUES ('EU', 10), ('US', 30)"); + + /** A total's key as *. */ + private static final String KEYS = "ifNull(region, '*'), ifNull(product, '*')"; + + @ParameterizedTest(name = "clickhouse:{0} -> grouping sets {1}") + @CsvSource({ "21.8, false", "22.3, false", "22.6, false", "22.8, false", "22.9, true", "23.8, true", + "24.8, true", "25.8, true", "26.6, true" }) + void grouping_sets(String tag, boolean expected) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsGroupingSets()).as("supportsGroupingSets").isEqualTo(expected); + + String grouping = dialect.functionGenerator().generateGrouping("region") + ", " + + dialect.functionGenerator().generateGrouping("product"); + String sets = "SELECT " + KEYS + ", sum(amount), " + grouping + " FROM sales" + + " GROUP BY GROUPING SETS ((region, product), (region), ()) ORDER BY 1, 2"; + if (!expected) { + if (tag.startsWith("21.") || tag.equals("22.3")) { + assertThatThrownBy(() -> st.executeQuery(sets)).as("no GROUPING SETS before 22.6") + .isInstanceOf(SQLException.class).hasMessageContaining("Syntax error"); + } else { + assertThat(rows(st, sets)).as("22.6 to 22.8 run it, not as the standard does") + .isNotEqualTo(STANDARD); + } + return; + } + + assertThat(rows(st, sets)).as("GROUPING SETS, with GROUPING()").containsExactlyElementsOf(STANDARD); + assertThat(rows(st, "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(st, "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"); + + String plain = "SELECT region, sum(amount), " + dialect.functionGenerator().generateGrouping("region") + + " FROM plain GROUP BY GROUPING SETS ((region), ()) ORDER BY 3, 1"; + assertThat(rows(st, plain)).as("a total's key of a column not Nullable: '', told by GROUPING()") + .containsExactly("EU|10|0", "US|30|0", "|40|1"); + // without GROUPING(): 24.8 and 25.8 refuse it under group_by_use_nulls (BAD_ARGUMENTS) + assertThat(rows(st, "SELECT region, sum(amount) FROM plain GROUP BY GROUPING SETS ((region), ())" + + " ORDER BY 1 NULLS LAST SETTINGS group_by_use_nulls = 1")).as("NULL with group_by_use_nulls") + .containsExactly("EU|10", "US|30", "null|40"); + } + } + } + + /** Each grouping set's rows, sorted, with the GROUPING() bits of the standard. */ + private static final List STANDARD = List.of("*|*|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"); + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + ResultSetMetaData md = rs.getMetaData(); + while (rs.next()) { + List row = new ArrayList<>(); + for (int i = 1; i <= md.getColumnCount(); i++) { + row.add(String.valueOf(rs.getString(i))); + } + out.add(String.join("|", row)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseListAggTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseListAggTest.java new file mode 100644 index 00000000..ab441fda --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseListAggTest.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.clickhouse.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has no ordered string aggregate on every version ({@code groupConcat} only from 24.8, and with no + * {@code ORDER BY} in it). The dialect is built from a live connection, and the list it writes must come out of the + * server as a string, in the order asked for, the NULLs of an order column first or last as asked, without the NULL + * values, DISTINCT kept, with any separator, of a column of any type and per group. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseListAggTest { + + /** 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 String, name Nullable(String), salary Int32) ENGINE = MergeTree() ORDER BY tuple()", + "INSERT INTO emp VALUES ('a', 'bob', 30), ('a', NULL, 40), ('a', 'alice', 20), ('a', 'bob', 10)," + + " ('b', 'dave', 5)"); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.8", "23.8", "24.8", "25.8", "26.6" }) + void list_agg(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsListAgg()).isTrue(); + + assertThat(list(st, dialect, "name", false, ", ", order("name", SortDirection.ASC))) + .as("ordered by the value, the NULL left out").isEqualTo("alice, bob, bob"); + assertThat(list(st, dialect, "name", false, ", ", order("salary", SortDirection.DESC))) + .as("ordered by another column").isEqualTo("bob, alice, bob"); + assertThat(list(st, dialect, "name", false, ", ", + List.of(new OrderedColumn("name", "emp", SortDirection.ASC)))) + .as("a column of the table").isEqualTo("alice, bob, bob"); + + assertThat(sorted(list(st, dialect, "name", false, ",", List.of()))) + .as("no order").containsExactly("alice", "bob", "bob"); + assertThat(sorted(list(st, dialect, "name", true, ",", List.of()))) + .as("DISTINCT without an order").containsExactly("alice", "bob"); + assertThat(list(st, dialect, "name", true, ",", order("name", SortDirection.ASC))) + .as("DISTINCT with an order").isEqualTo("alice,bob"); + assertThat(list(st, dialect, "name", true, ",", order("salary", SortDirection.ASC))) + .as("DISTINCT ordered by another column: the first place of a value") + .isEqualTo("bob,alice"); + + assertThat(list(st, dialect, "name", false, null, order("name", SortDirection.ASC))) + .as("no separator is a comma").isEqualTo("alice,bob,bob"); + assertThat(list(st, dialect, "name", false, "'", order("name", SortDirection.ASC))) + .as("a quote as separator").isEqualTo("alice'bob'bob"); + assertThat(list(st, dialect, "name", false, "\\", order("name", SortDirection.ASC))) + .as("a backslash as separator").isEqualTo("alice\\bob\\bob"); + + assertThat(list(st, dialect, "salary", false, ",", order("salary", SortDirection.ASC))) + .as("an Int32 column").isEqualTo("10,20,30,40"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("NULLS FIRST, then a second column").isEqualTo("40,20,10,30"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.LAST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("NULLS LAST, then a second column").isEqualTo("20,10,30,40"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.DESC), + Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("DESC NULLS FIRST, then a second column ASC").isEqualTo("40,10,30,20"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.DESC), + Optional.of(NullsOrder.LAST)), new OrderedColumn("salary", null, SortDirection.DESC)))) + .as("DESC NULLS LAST, then a second column DESC").isEqualTo("30,10,20,40"); + + String perDept = dialect.generateListAgg("name", false, ",", null, null, + order("name", SortDirection.ASC)).orElseThrow(); + assertThat(rows(st, "SELECT dept, " + perDept + " FROM emp GROUP BY dept ORDER BY dept")) + .as("per group").containsExactly("a=alice,bob,bob", "b=dave"); + } + } + } + + private static List order(String column, SortDirection direction) { + return List.of(new OrderedColumn(column, null, direction)); + } + + private static String list(Statement st, ClickHouseDialect dialect, String operand, boolean distinct, + String separator, List columns) throws SQLException { + String agg = dialect.generateListAgg(operand, distinct, separator, null, null, columns).orElseThrow(); + try (ResultSet rs = st.executeQuery("SELECT " + agg + " FROM emp WHERE dept = 'a'")) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + agg, e); + } + } + + private static List sorted(String list) { + return Arrays.stream(list.split(",")).sorted().toList(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getString(2)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseMaterializedViewTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseMaterializedViewTest.java new file mode 100644 index 00000000..8414f452 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseMaterializedViewTest.java @@ -0,0 +1,125 @@ +/* + * 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.clickhouse.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.clickhouse.ClickHouseDialect; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has refreshable materialized views from 24.10 (24.3 and 24.8 refuse one without an experimental setting, + * 23.8 knows no REFRESH): the view computes its query when it is created, in the background, and keeps the rows until + * it is refreshed. The dialect is built from a live connection: from 24.10 on the view it creates keeps the rows of + * its creation, refreshes on demand only, the next refresh years away, fails on a second one of the name, is left as + * it is with IF NOT EXISTS, and is dropped; before, it writes none. The classic materialized view, on every version, + * keeps no result of its query: the rows there before it was created are not in it. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseMaterializedViewTest { + + private static final TableReference TOTALS = new TableReference(Optional.empty(), "region_totals", + TableReference.TYPE_VIEW); + + private static final String SELECT = "SELECT region, sum(amount) AS total FROM sales GROUP BY region"; + private static final String READ = "SELECT concat(region, '=', toString(total)) FROM region_totals" + + " ORDER BY region"; + + @ParameterizedTest(name = "clickhouse:{0} -> materialized views {1}") + @CsvSource({ "23.8, false", "24.8, false", "24.10, true", "24.12, true", "25.3, true", "25.8, true", + "26.6, true" }) + void materialized_view(String tag, boolean expected) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + st.execute("CREATE TABLE sales(region String, amount Int32) ENGINE = MergeTree() ORDER BY tuple()"); + st.execute("INSERT INTO sales VALUES ('EU', 10), ('EU', 20), ('US', 30)"); + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsMaterializedViews()).as("supportsMaterializedViews").isEqualTo(expected); + + st.execute("CREATE MATERIALIZED VIEW classic ENGINE = MergeTree() ORDER BY tuple() AS " + SELECT); + assertThat(rows(st, "SELECT toString(count()) FROM classic")) + .as("a classic one keeps no result of its query").containsExactly("0"); + + if (!expected) { + assertThat(dialect.createMaterializedView(TOTALS, SELECT, false)).as("none before 24.10") + .isEmpty(); + assertThat(dialect.dropMaterializedView(TOTALS, true)).as("none before 24.10").isEmpty(); + assertThatThrownBy(() -> st.execute("CREATE MATERIALIZED VIEW region_totals REFRESH AFTER" + + " 10 YEAR ENGINE = MergeTree() ORDER BY tuple() AS " + SELECT)) + .as("the server refuses a refreshable one").isInstanceOf(SQLException.class); + return; + } + + String create = dialect.createMaterializedView(TOTALS, SELECT, false).orElseThrow(); + assertThat(create).isEqualTo("CREATE MATERIALIZED VIEW " + dialect.quoteIdentifier("region_totals") + + " REFRESH AFTER 10 YEAR ENGINE = MergeTree() ORDER BY tuple() AS " + SELECT); + execute(st, create); + st.execute("SYSTEM WAIT VIEW region_totals"); + assertThat(rows(st, READ)).as("the rows of its creation").containsExactly("EU=30", "US=30"); + + st.execute("INSERT INTO sales VALUES ('US', 5)"); + assertThat(rows(st, READ)).as("kept until it is refreshed").containsExactly("EU=30", "US=30"); + assertThat(rows(st, "SELECT toString(toYear(next_refresh_time) - toYear(now()) >= 9)" + + " FROM system.view_refreshes WHERE view = 'region_totals'")) + .as("the next refresh years away").containsExactly("1"); + st.execute("SYSTEM REFRESH VIEW region_totals"); + st.execute("SYSTEM WAIT VIEW region_totals"); + assertThat(rows(st, READ)).as("refreshed").containsExactly("EU=30", "US=35"); + + assertThatThrownBy(() -> st.execute(create)).as("a second one of the name") + .isInstanceOf(SQLException.class); + execute(st, dialect.createMaterializedView(TOTALS, "SELECT 'x' AS region, 1 AS total", true) + .orElseThrow()); + assertThat(rows(st, READ)).as("IF NOT EXISTS left it").containsExactly("EU=30", "US=35"); + + execute(st, dialect.dropMaterializedView(TOTALS, false).orElseThrow()); + assertThatThrownBy(() -> rows(st, READ)).as("dropped").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> st.execute(dialect.dropMaterializedView(TOTALS, false).orElseThrow())) + .as("a missing one").isInstanceOf(SQLException.class); + execute(st, dialect.dropMaterializedView(TOTALS, true).orElseThrow()); + } + } + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseNthValueTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseNthValueTest.java new file mode 100644 index 00000000..edcdb7db --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseNthValueTest.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.clickhouse.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has no ordered array aggregate: the dialect gives the n-th value of a group as the n-th element of the + * group's rows, collected with {@code groupArray} and sorted by the columns, on every version here: an aggregate over + * the rows of the group, not the window {@code nth_value … OVER} (V-82). The dialect is built from a live connection, + * and 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, not the type's default; and it is per group. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseNthValueTest { + + /** 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 List SETUP = List.of( + "CREATE TABLE t(g String, o Nullable(Int32), v Nullable(Int32)) ENGINE = MergeTree() ORDER BY tuple()", + "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)"); + + private static final List BY_O = List.of(new OrderedColumn("o", null, SortDirection.ASC)); + private static final List BY_O_DESC = List.of(new OrderedColumn("o", null, SortDirection.DESC)); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.8", "23.8", "24.8", "25.8", "26.6" }) + void nth_value(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect d = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(d.supportsNthValue()).as("supportsNthValue").isTrue(); + assertThat(d.supportsNthValueIgnoreNulls()).as("supportsNthValueIgnoreNulls").isTrue(); + + assertThat(nth(st, d, false, 1, BY_O, "a")).as("the NULLs counted").isNull(); + assertThat(nth(st, d, true, 1, BY_O, "a")).as("1st ignoring NULLs").isEqualTo("20"); + assertThat(nth(st, d, false, 2, BY_O, "a")).as("2nd").isEqualTo("20"); + assertThat(nth(st, d, true, 2, BY_O, "a")).as("2nd ignoring NULLs").isEqualTo("30"); + assertThat(nth(st, d, false, 5, BY_O, "a")).as("5th").isEqualTo("50"); + assertThat(nth(st, d, true, 3, BY_O, "a")).as("3rd ignoring NULLs").isEqualTo("50"); + assertThat(nth(st, d, true, 4, BY_O, "a")).as("4th ignoring NULLs, past the end").isNull(); + assertThat(nth(st, d, false, 6, BY_O, "a")).as("6th, past the end").isNull(); + assertThat(nth(st, d, true, 0, BY_O, "a")).as("0th is the 1st").isEqualTo("20"); + assertThat(nth(st, d, true, null, BY_O, "a")).as("no n is the 1st").isEqualTo("20"); + assertThat(nth(st, d, false, 1, BY_O_DESC, "a")).as("1st descending").isEqualTo("50"); + assertThat(nth(st, d, true, 2, BY_O_DESC, "a")).as("2nd descending ignoring NULLs") + .isEqualTo("30"); + assertThat(nth(st, d, true, 1, List.of(new OrderedColumn("o", "t", SortDirection.ASC)), "a")) + .as("1st by a column of the table").isEqualTo("20"); + assertThat(nth(st, d, false, 1, List.of(new OrderedColumn("o", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.FIRST))), "c")).as("the row of a NULL order first").isEqualTo("9"); + assertThat(nth(st, d, false, 1, List.of(new OrderedColumn("o", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.LAST))), "c")).as("the row of a NULL order last").isEqualTo("8"); + assertThat(nth(st, d, false, 1, List.of(new OrderedColumn("o", null, Optional.of(SortDirection.DESC), + Optional.of(NullsOrder.FIRST))), "c")).as("descending, NULLs first").isEqualTo("9"); + assertThat(nth(st, d, true, 1, List.of(), "b")).as("no order, one value").isEqualTo("7"); + + String perGroup = d.generateNthValueAgg("v", true, 1, BY_O).orElseThrow(); + assertThat(rows(st, "SELECT concat(g, '=', ifNull(toString(" + perGroup + "), 'null')) FROM t" + + " GROUP BY g ORDER BY g")).as("per group").containsExactly("a=20", "b=7", "c=8"); + + String nonNull = d.generateNthValueAgg("toInt32(ifNull(v, 0))", false, 9, BY_O).orElseThrow(); + assertThat(rows(st, "SELECT toString(" + nonNull + ") FROM t WHERE g = 'a'")) + .as("past the end of a column not Nullable: NULL, not 0").containsExactly((String) null); + } + } + } + + private static String nth(Statement st, ClickHouseDialect d, boolean ignoreNulls, Integer n, + List columns, String group) throws SQLException { + String agg = d.generateNthValueAgg("v", ignoreNulls, n, columns).orElseThrow(); + List rows = rows(st, "SELECT toString(" + agg + ") FROM t WHERE g = '" + group + "'"); + assertThat(rows).hasSize(1); + return rows.get(0); + } + + 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)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseOffsetTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseOffsetTest.java new file mode 100644 index 00000000..5e55f0e8 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseOffsetTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.clickhouse.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.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalLong; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PagingParam; +import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PreparedPaging; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse skips and limits rows with {@code LIMIT n OFFSET m}, {@code LIMIT n} and {@code OFFSET m} on every + * version, with an ORDER BY or without; the standard {@code OFFSET m ROWS FETCH NEXT n ROWS ONLY} it refuses without + * an ORDER BY, on every version. The dialect is built from a live connection, and the paging it writes must skip and + * limit the rows of a sorted query and count them in one that is not, limit to no row, skip past the end, and run + * with its parameters bound in the order it gives. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseOffsetTest { + + private static final String SORTED = "SELECT toString(x) FROM t ORDER BY x"; + private static final String UNSORTED = "SELECT x FROM t"; + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void offset(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + st.execute("CREATE TABLE t(x Int32) ENGINE = MergeTree() ORDER BY tuple()"); + st.execute("INSERT INTO t SELECT toInt32(number) FROM numbers(10)"); + PaginationGenerator p = new ClickHouseDialect(DialectInitData.fromConnection(c)) + .paginationGenerator(); + assertThat(p.supportsOffset()).as("supportsOffset").isTrue(); + assertThat(p.selectPrefix(OptionalLong.of(3), OptionalLong.of(2))).as("a trailing clause").isEmpty(); + + assertThat(rows(st, SORTED + paging(p, 3, 2))).as("skip 2, take 3").containsExactly("2", "3", "4"); + assertThat(rows(st, SORTED + paging(p, 3, null))).as("take 3").containsExactly("0", "1", "2"); + assertThat(rows(st, SORTED + paging(p, null, 7))).as("skip 7").containsExactly("7", "8", "9"); + assertThat(rows(st, SORTED + paging(p, 0, null))).as("take none").isEmpty(); + assertThat(rows(st, SORTED + paging(p, 3, 9))).as("fewer left").containsExactly("9"); + assertThat(rows(st, SORTED + paging(p, 3, 20))).as("skip past the end").isEmpty(); + assertThat(rows(st, SORTED + paging(p, null, null))).as("no paging").hasSize(10); + + assertThat(count(st, UNSORTED + paging(p, 3, 2))).as("without ORDER BY: skip and take").isEqualTo(3); + assertThat(count(st, UNSORTED + paging(p, null, 7))).as("without ORDER BY: skip").isEqualTo(3); + assertThat(count(st, UNSORTED + paging(p, 4, null))).as("without ORDER BY: take").isEqualTo(4); + assertThatThrownBy(() -> rows(st, UNSORTED + " OFFSET 2 ROWS FETCH NEXT 3 ROWS ONLY")) + .as("the standard form without ORDER BY, which the dialect does not write") + .isInstanceOf(SQLException.class); + + assertThat(prepared(c, p, 3L, 2L)).as("prepared, skip 2, take 3").containsExactly("2", "3", "4"); + assertThat(prepared(c, p, 3L, null)).as("prepared, take 3").containsExactly("0", "1", "2"); + assertThat(prepared(c, p, null, 7L)).as("prepared, skip 7").containsExactly("7", "8", "9"); + } + } + } + + private static String paging(PaginationGenerator p, Integer limit, Integer offset) { + return p.paginate(limit == null ? OptionalLong.empty() : OptionalLong.of(limit), + offset == null ? OptionalLong.empty() : OptionalLong.of(offset)); + } + + /** The prepared form, its parameters bound in the order it gives. */ + private static List prepared(Connection c, PaginationGenerator p, Long limit, Long offset) + throws SQLException { + PreparedPaging paging = p.paginatePrepared(limit != null, offset != null); + String sql = SORTED + " " + paging.clause(); + try (PreparedStatement ps = c.prepareStatement(sql)) { + int i = 1; + for (PagingParam param : paging.order()) { + ps.setLong(i++, param == PagingParam.LIMIT ? limit : offset); + } + List out = new ArrayList<>(); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static long count(Statement st, String sql) throws SQLException { + return Long.parseLong(rows(st, "SELECT toString(count()) FROM (" + sql + ")").get(0)); + } + + 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)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHousePercentileTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHousePercentileTest.java new file mode 100644 index 00000000..9bbb6995 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHousePercentileTest.java @@ -0,0 +1,116 @@ +/* + * 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.clickhouse.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.within; + +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.clickhouse.ClickHouseDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has no {@code PERCENTILE_DISC} and no {@code PERCENTILE_CONT … WITHIN GROUP}, and none of its quantiles + * gives the discrete one; {@code quantileExactInclusive}, the continuous one, gives the 2nd value for p = 1 on 21.x. + * The dialect computes both on the sorted values of the group, on every version. Built from a live connection, its + * percentiles must give what the standard says: the discrete one a value of the group, the continuous one interpolated, + * ascending and descending, the NULLs left out, p at its ends, per group, and NULL for a group of no value. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHousePercentileTest { + + /** Group a: 10, 20, 30, 40 and a NULL that every aggregate leaves out; group b: 5; group c: only a NULL. */ + private static final List SETUP = List.of( + "CREATE TABLE nums(g String, v Nullable(Int32)) ENGINE = MergeTree() ORDER BY tuple()", + "INSERT INTO nums VALUES ('a', 30), ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5), ('c', NULL)"); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void percentile(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect d = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(d.supportsPercentileDisc()).as("supportsPercentileDisc").isTrue(); + assertThat(d.supportsPercentileCont()).as("supportsPercentileCont").isTrue(); + assertThatThrownBy(() -> rows(st, "SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY v) FROM nums")) + .as("the server knows no WITHIN GROUP").isInstanceOf(SQLException.class); + + assertThat(disc(st, d, 0.5, false, "nums")).as("disc 0.5").isEqualTo(20); + assertThat(disc(st, d, 0.25, false, "nums")).as("disc 0.25: cume_dist of 10 is 0.25").isEqualTo(10); + assertThat(disc(st, d, 0.7, false, null)).as("disc 0.7, the column alone").isEqualTo(30); + assertThat(disc(st, d, 0, false, "nums")).as("disc 0, the least").isEqualTo(10); + assertThat(disc(st, d, 1, false, "nums")).as("disc 1, the greatest").isEqualTo(40); + assertThat(disc(st, d, 0.5, true, "nums")).as("disc 0.5 descending").isEqualTo(30); + assertThat(disc(st, d, 0.25, true, null)).as("disc 0.25 descending").isEqualTo(40); + + assertThat(cont(st, d, 0.5, false, "nums")).as("cont 0.5").isEqualTo(25); + assertThat(cont(st, d, 0.25, false, null)).as("cont 0.25, the column alone").isEqualTo(17.5); + assertThat(cont(st, d, 0.7, false, "nums")).as("cont 0.7").isCloseTo(31, within(1e-9)); + assertThat(cont(st, d, 0, false, "nums")).as("cont 0, the least").isEqualTo(10); + assertThat(cont(st, d, 1, false, "nums")).as("cont 1, the greatest, which 21.x's own gets wrong") + .isEqualTo(40); + assertThat(cont(st, d, 0.25, true, "nums")).as("cont 0.25 descending").isEqualTo(32.5); + assertThat(cont(st, d, 1, true, "nums")).as("descending, the end: the least").isEqualTo(10); + + String perGroup = "SELECT concat(g, '=', ifNull(toString(%s), 'null')) FROM nums GROUP BY g ORDER BY g"; + assertThat(rows(st, perGroup.formatted(d.generatePercentileCont(0.5, false, null, "v").orElseThrow()))) + .as("cont per group, one value, no value").containsExactly("a=25", "b=5", "c=null"); + assertThat(rows(st, perGroup.formatted(d.generatePercentileDisc(0.5, false, null, "v").orElseThrow()))) + .as("disc per group, one value, no value").containsExactly("a=20", "b=5", "c=null"); + } + } + } + + private static double disc(Statement st, ClickHouseDialect d, double p, boolean desc, String table) + throws SQLException { + return value(st, d.generatePercentileDisc(p, desc, table, "v").orElseThrow()); + } + + private static double cont(Statement st, ClickHouseDialect d, double p, boolean desc, String table) + throws SQLException { + return value(st, d.generatePercentileCont(p, desc, table, "v").orElseThrow()); + } + + /** The percentile of group a. */ + private static double value(Statement st, String percentile) throws SQLException { + List rows = rows(st, "SELECT toString(" + percentile + ") FROM nums WHERE g = 'a'"); + assertThat(rows).as(percentile).hasSize(1); + return Double.parseDouble(rows.get(0)); + } + + 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)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRecursiveCteTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRecursiveCteTest.java new file mode 100644 index 00000000..95e92539 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRecursiveCteTest.java @@ -0,0 +1,111 @@ +/* + * 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.clickhouse.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.CteGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.CteGenerator.Cte; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has common table expressions on every version here, recursive ones from 24.4: {@code WITH RECURSIVE}, + * on the new analyzer only, which is on by default from 24.3. The dialect is built from a live connection: from 24.4 + * on the WITH clause it writes runs on the server, a recursive one counting and walking a tree, without RECURSIVE a + * recursive one failing, and fails as well where the session turns the analyzer off; before, it says it has no + * recursive ones and writes no RECURSIVE, which the server would refuse. Two of one clause, the second reading the + * first, run on every version. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseRecursiveCteTest { + + /** A tree: ceo above a and b, a above c, c above d. */ + private static final List SETUP = List.of( + "CREATE TABLE emp(id Int32, boss Nullable(Int32), name String) ENGINE = MergeTree() ORDER BY id", + "INSERT INTO emp VALUES (1, NULL, 'ceo'), (2, 1, 'a'), (3, 1, 'b'), (4, 2, 'c'), (5, 4, 'd')"); + + private static final List NUMBERS = List + .of(new Cte("nums", "SELECT 1 AS n UNION ALL SELECT n + 1 FROM nums WHERE n < 5")); + + private static final List TREE = List.of(new Cte("tree", + "SELECT id, name, 0 AS depth FROM emp WHERE boss IS NULL" + + " UNION ALL SELECT e.id, e.name, t.depth + 1 FROM emp e JOIN tree t ON e.boss = t.id")); + + /** Two of one clause, not recursive, the second reading the first. */ + private static final List BOSSES = List.of( + new Cte("bosses", "SELECT DISTINCT boss FROM emp WHERE boss IS NOT NULL"), + new Cte("named", "SELECT e.name FROM emp e JOIN bosses b ON e.id = b.boss")); + + @ParameterizedTest(name = "clickhouse:{0} -> recursive {1}") + @CsvSource({ "21.8, false", "23.8, false", "24.3, false", "24.4, true", "24.8, true", "25.8, true", + "26.6, true" }) + void recursive_cte(String tag, boolean expected) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + CteGenerator cte = new ClickHouseDialect(DialectInitData.fromConnection(c)).cteGenerator(); + + assertThat(cte.supportsRecursiveCte()).as("supportsRecursiveCte").isEqualTo(expected); + assertThat(cte.withClause(List.of(), true)).as("no expressions, no clause").isEmpty(); + assertThat(cte.withClause(NUMBERS, true).startsWith("WITH RECURSIVE ")).as("RECURSIVE written") + .isEqualTo(expected); + assertThat(rows(st, cte.withClause(BOSSES, false) + "SELECT name FROM named ORDER BY name")) + .as("two of one clause, the second reading the first").containsExactly("a", "c", "ceo"); + + if (!expected) { + assertThatThrownBy(() -> rows(st, "WITH RECURSIVE " + NUMBERS.get(0).name() + " AS (" + + NUMBERS.get(0).body() + ") SELECT sum(n) FROM nums")) + .as("the server refuses RECURSIVE before 24.4").isInstanceOf(SQLException.class) + .hasMessageContaining("Syntax error"); + return; + } + + assertThat(rows(st, cte.withClause(NUMBERS, true) + "SELECT toString(sum(n)) FROM nums")) + .as("counting to 5").containsExactly("15"); + assertThat(rows(st, cte.withClause(TREE, true) + + "SELECT concat(name, ':', toString(depth)) FROM tree ORDER BY depth, name")) + .as("walking the tree").containsExactly("ceo:0", "a:1", "b:1", "c:2", "d:3"); + assertThatThrownBy(() -> rows(st, cte.withClause(NUMBERS, false) + "SELECT sum(n) FROM nums")) + .as("a recursive one without RECURSIVE").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> rows(st, cte.withClause(NUMBERS, true) + + "SELECT sum(n) FROM nums SETTINGS allow_experimental_analyzer = 0")) + .as("not on the old analyzer").isInstanceOf(SQLException.class); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRegularExpressionTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRegularExpressionTest.java new file mode 100644 index 00000000..6a1aabe8 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRegularExpressionTest.java @@ -0,0 +1,131 @@ +/* + * 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.clickhouse.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.regex.Pattern; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * MDX {@code MATCHES} is Java's {@code Pattern.matches}: the whole value, case-sensitive unless the expression says + * {@code (?i)}, a dot no line break. ClickHouse's {@code match} is RE2's, on every version. The dialect is built from + * a live connection, and the condition it writes must pick on the server the rows Java picks: anchored at both ends, + * the case kept or ignored, a dot escaped or taking no line break, {@code \Q…\E}, {@code \d}, {@code \w}, a NULL never. + * An expression with what RE2 has not, lookaround, a back reference, a possessive quantifier, which the server + * refuses, or a class intersection, which it reads otherwise, gives no condition, nor one Java cannot read: it is + * matched in Java. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseRegularExpressionTest { + + private static final List WORDS = Arrays.asList("apple", "Apple", "APPLE", "pineapple", "banana", "a.b", + "axb", "a\nb", "a+b", "a1 b", null); + + private static final List EXPRESSIONS = List.of("apple", "a.*", "(?i)a.*", "(?i)apple", ".*apple", "A.*", + "a\\.b", "a.b", "[a-c].*", "ban(an)+a", "apple|banana", "\\Qa+b\\E", "\\w\\d\\s\\w", "(?s)a.b", + "(?iu)APPLE", "(?i:a)pple"); + + /** What RE2 has not, which the server refuses. */ + private static final List NOT_RE2 = List.of("a(?=p).*", "(?<=a)pple", "(a)\\1.*", "a++pple", + "(?>a)pple"); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void regular_expression(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + st.execute("CREATE TABLE words(id Int32, w Nullable(String)) ENGINE = MergeTree() ORDER BY id"); + StringBuilder insert = new StringBuilder("INSERT INTO words VALUES "); + for (int i = 0; i < WORDS.size(); i++) { + String w = WORDS.get(i); + insert.append(i == 0 ? "" : ", ").append('(').append(i).append(", ") + .append(w == null ? "NULL" : "'" + w.replace("\n", "\\n") + "'").append(')'); + } + st.execute(insert.toString()); + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.allowsRegularExpressionInWhereClause()).isTrue(); + + for (String javaRegex : EXPRESSIONS) { + assertMatchesAsJava(st, dialect, javaRegex); + } + assertThat(matching(st, dialect, "a.b")).as("a dot takes no line break").doesNotContain("a\nb"); + + for (String javaRegex : NOT_RE2) { + assertThat(dialect.regexGenerator().generateRegularExpression("w", javaRegex)) + .as(javaRegex + " has what RE2 has not").isEmpty(); + StringBuilder raw = new StringBuilder("SELECT w FROM words WHERE match(w, "); + dialect.quoteStringLiteral(raw, javaRegex); + assertThatThrownBy(() -> st.executeQuery(raw.append(")").toString())) + .as("the server refuses " + javaRegex).isInstanceOf(SQLException.class); + } + String intersection = "[a-z&&[^b]]+"; + assertThat(dialect.regexGenerator().generateRegularExpression("w", intersection)) + .as("a class intersection").isEmpty(); + assertThat(rows(st, "SELECT toString(match('apple', '\\\\A(?:" + intersection + ")\\\\z'))")) + .as("RE2 takes it, and reads it otherwise than Java, which matches apple").containsExactly("0"); + assertThat(dialect.regexGenerator().generateRegularExpression("w", "a(")).as("not a Java expression") + .isEmpty(); + } + } + } + + /** The rows the condition picks are the rows Java's {@code Pattern.matches} picks. */ + private static void assertMatchesAsJava(Statement st, ClickHouseDialect dialect, String javaRegex) + throws SQLException { + Pattern p = Pattern.compile(javaRegex); + List java = WORDS.stream().filter(w -> w != null && p.matcher(w).matches()).toList(); + assertThat(java).as(javaRegex + " picks some row").isNotEmpty(); + assertThat(matching(st, dialect, javaRegex)).as(javaRegex + " as Java").containsExactlyElementsOf(java); + } + + 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; + } + + private static List matching(Statement st, ClickHouseDialect dialect, String javaRegex) + throws SQLException { + String condition = dialect.regexGenerator().generateRegularExpression("w", javaRegex).orElseThrow() + .toString(); + String sql = "SELECT w FROM words WHERE " + condition + " ORDER BY id"; + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRenameColumnTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRenameColumnTest.java new file mode 100644 index 00000000..cadd7677 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRenameColumnTest.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.clickhouse.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.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse renames a column with {@code ALTER TABLE … RENAME COLUMN} from 20.4, which changes the name only. The + * dialect is built from a live connection, and the column it renames must keep its type, its nullability, its + * default, its comment and its values. A column of the sorting key cannot be renamed on any version. The images of + * {@code clickhouse/clickhouse-server} begin with 21.3, so the boundary itself is not run here. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseRenameColumnTest { + + private static final TableReference T = new TableReference(Optional.empty(), "t", TableReference.TYPE_TABLE); + + private static final List SETUP = List.of(""" + CREATE TABLE t(id Int32, note String DEFAULT 'n/a' COMMENT 'the note', price Nullable(Decimal(10, 2))) + ENGINE = MergeTree() ORDER BY id""", "INSERT INTO t(id, note, price) VALUES (1, 'x', 1.50)", + "INSERT INTO t(id, price) VALUES (2, NULL)"); + + /** Name, type, default and comment of each column, in the order of the table. */ + private static final String COLUMNS = """ + SELECT concat(name, '|', type, '|', if(default_expression = '', '-', default_expression), '|', + if(comment = '', '-', comment)) + FROM system.columns WHERE database = currentDatabase() AND table = 't'"""; + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void rename_column(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement db = c.createStatement()) { + for (String sql : SETUP) { + db.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsRenameColumn()).isTrue(); + + rename(db, dialect, "note", "remark"); + rename(db, dialect, "price", "cost"); + + assertThat(rows(db, COLUMNS)).as("each column renamed, and kept whole").containsExactly( + "id|Int32|-|-", "remark|String|'n/a'|the note", "cost|Nullable(Decimal(10, 2))|-|-"); + assertThat(rows(db, "SELECT concat(toString(id), '|', remark, '|', ifNull(toString(toFloat64(cost))," + + " '-')) FROM t ORDER BY id")).as("the values kept").containsExactly("1|x|1.5", "2|n/a|-"); + db.execute("INSERT INTO t(id) VALUES (3)"); + assertThat(rows(db, "SELECT remark FROM t WHERE id = 3")).as("the default kept") + .containsExactly("n/a"); + + String key = dialect.renameColumn(T, "id", "key_id"); + assertThatThrownBy(() -> db.execute(key)).as("a column of the sorting key") + .isInstanceOf(SQLException.class); + } + } + } + + /** The dialect's rename, run. */ + private static void rename(Statement db, ClickHouseDialect dialect, String from, String to) throws SQLException { + String sql = dialect.renameColumn(T, from, to); + assertThat(sql).contains("RENAME COLUMN"); + try { + db.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement db, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = db.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRolesTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRolesTest.java new file mode 100644 index 00000000..f4144597 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseRolesTest.java @@ -0,0 +1,133 @@ +/* + * 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.clickhouse.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.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has roles from 20.4 (access control by SQL): {@code CREATE ROLE [IF NOT EXISTS]}, + * {@code DROP ROLE [IF EXISTS]}, a role granted to a user, with the admin option too, and revoked. The dialect is + * built from a live connection, and the role it creates must be there, hold a privilege, give it to the user it is + * granted to, which then reads what it could not before, and be dropped, the grant going with it; IF [NOT] EXISTS + * spares an error. The images of {@code clickhouse/clickhouse-server} begin with 21.3, so the boundary itself is not + * run here. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseRolesTest { + + private static final TableReference ITEMS = new TableReference(Optional.empty(), "items", + TableReference.TYPE_TABLE); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void roles(String tag) throws Exception { + // the container's user may manage roles and users only with access management turned on + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.withEnv("CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT", "1"); + ch.start(); + String url = ClickHouseContainers.jdbcUrl(ch, tag); + try (Connection c = DriverManager.getConnection(url, ch.getUsername(), ch.getPassword()); + Statement st = c.createStatement()) { + st.execute("CREATE TABLE items(id Int32) ENGINE = MergeTree() ORDER BY id"); + st.execute("INSERT INTO items VALUES (1)"); + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsRoles()).as("supportsRoles").isTrue(); + + execute(st, dialect.createRole("rt_role", false).orElseThrow()); + assertThat(rows(st, "SELECT name FROM system.roles WHERE name = 'rt_role'")).as("the role") + .containsExactly("rt_role"); + assertThatThrownBy(() -> st.execute(dialect.createRole("rt_role", false).orElseThrow())) + .as("a second one of the name").isInstanceOf(SQLException.class); + execute(st, dialect.createRole("rt_role", true).orElseThrow()); + + execute(st, dialect.grantTablePrivilege("SELECT", ITEMS, "rt_role", false)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_role"))).as("a privilege of the role") + .contains("GRANT SELECT ON default.items TO rt_role"); + + // a user that logs in, to read with what the role gives it + execute(st, dialect.createUser("rt_user", false).orElseThrow()); + st.execute("ALTER USER rt_user IDENTIFIED WITH plaintext_password BY 'pw' HOST ANY"); + assertThatThrownBy(() -> select(url)).as("the user alone may not read") + .isInstanceOf(SQLException.class); + + execute(st, dialect.grantRole("rt_role", "rt_user", false)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("the role granted to the user") + .contains("GRANT rt_role TO rt_user").doesNotContain("ADMIN OPTION"); + assertThat(select(url)).as("the user reads with the role's privilege").isEqualTo("1"); + + execute(st, dialect.revokeRole("rt_role", "rt_user")); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("revoked") + .doesNotContain("rt_role"); + assertThatThrownBy(() -> select(url)).as("the user no longer reads") + .isInstanceOf(SQLException.class); + execute(st, dialect.grantRole("rt_role", "rt_user", true)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("with the admin option") + .contains("GRANT rt_role TO rt_user WITH ADMIN OPTION"); + + execute(st, dialect.dropRole("rt_role", false).orElseThrow()); + assertThat(rows(st, "SELECT name FROM system.roles WHERE name = 'rt_role'")).as("dropped") + .isEmpty(); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("the grant gone with the role") + .doesNotContain("rt_role"); + assertThatThrownBy(() -> select(url)).as("nor the privilege left to the user") + .isInstanceOf(SQLException.class); + assertThatThrownBy(() -> st.execute(dialect.dropRole("rt_role", false).orElseThrow())) + .as("a missing one").isInstanceOf(SQLException.class); + execute(st, dialect.dropRole("rt_role", true).orElseThrow()); + execute(st, dialect.dropUser("rt_user", true).orElseThrow()); + } + } + } + + /** The table as rt_user reads it, logged in anew, so that it holds its grants of now. */ + private static String select(String url) throws SQLException { + try (Connection c = DriverManager.getConnection(url, "rt_user", "pw"); Statement st = c.createStatement(); + ResultSet rs = st.executeQuery("SELECT toString(id) FROM items")) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseTryCastTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseTryCastTest.java new file mode 100644 index 00000000..29ccf40e --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseTryCastTest.java @@ -0,0 +1,122 @@ +/* + * 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.clickhouse.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.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.CastGenerator; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +import org.eclipse.daanse.sql.model.type.Datatype; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * ClickHouse casts with {@code accurateCastOrNull(x, 'T')} to NULL what does not fit, on every version: what does not + * parse, what overflows, what would lose a part of itself; a plain {@code CAST} wraps an overflow round. The dialect is + * built from a live connection: its casts, in ClickHouse's own type names, run for every type it maps, and its try + * cast gives the value where it fits and NULL where it does not, a boolean too, which ClickHouse's own + * {@code accurateCastOrNull} gets wrong before 24.3. A date of a month out of range ClickHouse does not take for one + * that does not fit. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseTryCastTest { + + /** Each type the dialect maps, with a value of it. */ + private static final List VALUES = List.of(new Object[] { Datatype.VARCHAR, "'abc'", "abc" }, + new Object[] { Datatype.BINARY, "'abc'", "abc" }, new Object[] { Datatype.INTEGER, "'42'", "42" }, + new Object[] { Datatype.BIGINT, "'9000000000'", "9000000000" }, + new Object[] { Datatype.SMALLINT, "'-7'", "-7" }, new Object[] { Datatype.DOUBLE, "'2.5'", "2.5" }, + new Object[] { Datatype.FLOAT, "'2.5'", "2.5" }, new Object[] { Datatype.REAL, "'2.5'", "2.5" }, + new Object[] { Datatype.DECIMAL, "'12.345'", "12.345" }, + new Object[] { Datatype.NUMERIC, "'12.345'", "12.345" }, + new Object[] { Datatype.DATE, "'2020-02-03'", "2020-02-03" }, + new Object[] { Datatype.TIMESTAMP, "'2020-02-03 04:05:06.789'", "2020-02-03 04:05:06.789" }, + new Object[] { Datatype.UUID, "'6ba7b810-9dad-11d1-80b4-00c04fd430c8'", + "6ba7b810-9dad-11d1-80b4-00c04fd430c8" }); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "21.12", "23.8", "24.3", "24.8", "25.8", "26.6" }) + void try_cast(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + CastGenerator g = new ClickHouseDialect(DialectInitData.fromConnection(c)).castGenerator(); + assertThat(g.supportsTryCast()).as("supportsTryCast").isTrue(); + + for (Object[] v : VALUES) { + Datatype type = (Datatype) v[0]; + String literal = (String) v[1]; + String expected = (String) v[2]; + // a Decimal as its number: 21.x writes it with its scale's zeros + String shown = type == Datatype.DECIMAL || type == Datatype.NUMERIC ? "toString(toFloat64(%s))" + : "toString(%s)"; + assertThat(one(st, shown.formatted(g.cast(literal, type)))).as("CAST AS " + type) + .isEqualTo(expected); + assertThat(one(st, shown.formatted(g.tryCast(literal, type)))).as("try cast " + type) + .isEqualTo(expected); + } + + assertThat(one(st, g.tryCast("'abc'", Datatype.INTEGER))).as("no number").isNull(); + assertThat(one(st, g.tryCast("'3000000000'", Datatype.INTEGER))).as("too large for Int32").isNull(); + assertThat(one(st, g.tryCast("300", Datatype.SMALLINT) + " IS NULL")).as("300 fits Int16") + .isEqualTo("0"); + assertThat(one(st, g.tryCast("100000", Datatype.SMALLINT))).as("too large for Int16").isNull(); + assertThat(one(st, "toString(CAST(100000 AS Int16))")).as("a plain CAST wraps it round") + .isEqualTo("-31072"); + assertThat(one(st, g.tryCast("3.7", Datatype.INTEGER))).as("a part of it lost").isNull(); + assertThat(one(st, g.tryCast("'x'", Datatype.DECIMAL))).as("no decimal").isNull(); + assertThat(one(st, g.tryCast("'abc'", Datatype.DATE))).as("no date").isNull(); + assertThat(one(st, g.tryCast("'abc'", Datatype.TIMESTAMP))).as("no timestamp").isNull(); + assertThat(one(st, g.tryCast("'zz'", Datatype.UUID))).as("no UUID").isNull(); + assertThat(one(st, g.tryCast("NULL", Datatype.INTEGER))).as("NULL").isNull(); + assertThat(one(st, "toString(" + g.tryCast("'2020-13-45'", Datatype.DATE) + ")")) + .as("a month out of range is no NULL to ClickHouse").isNotNull(); + + for (String yes : List.of("'true'", "'1'", "1")) { + assertThat(one(st, "toString(toUInt8(" + g.tryCast(yes, Datatype.BOOLEAN) + "))")) + .as("true: " + yes).isEqualTo("1"); + } + for (String no : List.of("'false'", "'0'", "0")) { + assertThat(one(st, "toString(toUInt8(" + g.tryCast(no, Datatype.BOOLEAN) + "))")) + .as("false: " + no).isEqualTo("0"); + } + assertThat(one(st, g.tryCast("'yes?'", Datatype.BOOLEAN))).as("no boolean, and no error") + .isNull(); + + st.execute("CREATE TABLE t(s Nullable(String)) ENGINE = MergeTree() ORDER BY tuple()"); + st.execute("INSERT INTO t VALUES ('1'), ('x'), (NULL), ('40')"); + assertThat(one(st, "toString(sum(" + g.tryCast("s", Datatype.INTEGER) + ")) FROM t")) + .as("over a column, what does not fit left out").isEqualTo("41"); + } + } + } + + /** The one value of {@code SELECT expr}, NULL as null. */ + private static String one(Statement st, String expr) throws SQLException { + String sql = "SELECT " + expr; + try (ResultSet rs = st.executeQuery(sql)) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUnionDistinctTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUnionDistinctTest.java new file mode 100644 index 00000000..e37769d5 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUnionDistinctTest.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.clickhouse.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.clickhouse.ClickHouseDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.clickhouse.ClickHouseContainer; + +/** + * The duplicate-eliminating UNION as the dialect spells it. ClickHouse refuses a bare {@code UNION} while the + * server's {@code union_default_mode} is empty, as it is by default: Code 558, Expected ALL or DISTINCT. The dialect + * is built from a live connection, and the union it writes must run and leave each row once, also over a column + * with NULLs and with three inputs. An ORDER BY after the last input orders that input only, not the union (EXPLAIN + * SYNTAX puts it into the last SELECT): the union is ordered from an outer SELECT. {@code UNION DISTINCT} comes with + * 21.1; the images of {@code clickhouse/clickhouse-server} begin with 21.3. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseUnionDistinctTest { + + /** a: 1, 2, 2, NULL; b: 2, 3, NULL. */ + private static final List SETUP = List.of( + "CREATE TABLE a(x Nullable(Int32)) ENGINE = MergeTree() ORDER BY tuple()", + "CREATE TABLE b(x Nullable(Int32)) ENGINE = MergeTree() ORDER BY tuple()", + "INSERT INTO a VALUES (1), (2), (2), (NULL)", + "INSERT INTO b VALUES (2), (3), (NULL)"); + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void union_distinct(String tag) throws Exception { + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.start(); + try (Connection c = DriverManager.getConnection(ClickHouseContainers.jdbcUrl(ch, tag), ch.getUsername(), + ch.getPassword()); Statement st = c.createStatement()) { + for (String sql : SETUP) { + st.execute(sql); + } + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + String union = " " + dialect.unionDistinctKeyword() + " "; + + assertThatThrownBy(() -> st.executeQuery("SELECT x FROM a UNION SELECT x FROM b")) + .as("the bare UNION the dialect avoids").isInstanceOf(SQLException.class); + + assertThat(values(st, "SELECT x FROM (SELECT x FROM a" + union + "SELECT x FROM b) ORDER BY x")) + .as("each row once, one NULL").containsExactly("1", "2", "3", null); + assertThat(values(st, "SELECT x FROM (SELECT x FROM a" + union + "SELECT x FROM b" + union + + "SELECT toNullable(toInt32(4))) ORDER BY x")) + .as("three inputs").containsExactly("1", "2", "3", "4", null); + assertThat(values(st, "SELECT x FROM (SELECT x FROM a WHERE x = 2" + union + + "SELECT x FROM a WHERE x = 2)")) + .as("duplicates within one input").containsExactly("2"); + } + } + } + + private static List values(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUsersTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUsersTest.java new file mode 100644 index 00000000..d62e46f9 --- /dev/null +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/container/ClickHouseUsersTest.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.clickhouse.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.clickhouse.ClickHouseDialect; +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.clickhouse.ClickHouseContainer; + +/** + * ClickHouse has users from 20.4 (access control by SQL), and lets a user without a password in from any host: the + * dialect creates a user with no host to come from, {@code CREATE USER [IF NOT EXISTS] "x" HOST NONE}, and drops it + * with {@code DROP USER [IF EXISTS] "x"}. The dialect is built from a live connection, and the user it creates must + * be there, without a password and a host, not log in, take a privilege, log in once an administrator gives it a + * password and a host, and be dropped; IF [NOT] EXISTS spares an error. The images of + * {@code clickhouse/clickhouse-server} begin with 21.3, so the boundary itself is not run here. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class ClickHouseUsersTest { + + private static final TableReference ITEMS = new TableReference(Optional.empty(), "items", + TableReference.TYPE_TABLE); + + /** Authentication and the number of hosts of the user; auth_type is an array from 25.x, a value before. */ + private static final String USER = """ + SELECT concat(name, '|', replaceRegexpAll(toString(auth_type), '[^a-z_]', ''), '|', + toString(length(host_ip) + length(host_names) + length(host_names_regexp) + length(host_names_like))) + FROM system.users WHERE name = 'rt_user'"""; + + @ParameterizedTest(name = "clickhouse:{0}") + @ValueSource(strings = { "21.3", "21.8", "23.8", "24.8", "25.8", "26.6" }) + void users(String tag) throws Exception { + // the container's user may manage users only with access management turned on + try (ClickHouseContainer ch = ClickHouseContainers.container(tag)) { + ch.withEnv("CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT", "1"); + ch.start(); + String url = ClickHouseContainers.jdbcUrl(ch, tag); + try (Connection c = DriverManager.getConnection(url, ch.getUsername(), ch.getPassword()); + Statement st = c.createStatement()) { + st.execute("CREATE TABLE items(id Int32) ENGINE = MergeTree() ORDER BY id"); + st.execute("INSERT INTO items VALUES (1)"); + ClickHouseDialect dialect = new ClickHouseDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsUsers()).as("supportsUsers").isTrue(); + + execute(st, dialect.createUser("rt_user", false).orElseThrow()); + assertThat(rows(st, USER)).as("the user, without a password and without a host") + .containsExactly("rt_user|no_password|0"); + assertThatThrownBy(() -> select(url, "rt_user", "")) + .as("a user without a host does not log in").isInstanceOf(SQLException.class); + + assertThatThrownBy(() -> st.execute(dialect.createUser("rt_user", false).orElseThrow())) + .as("a second one of the name").isInstanceOf(SQLException.class); + execute(st, dialect.createUser("rt_user", true).orElseThrow()); + + execute(st, dialect.grantTablePrivilege("SELECT", ITEMS, "rt_user", false)); + assertThat(String.join(" ", rows(st, "SHOW GRANTS FOR rt_user"))).as("a privilege of the user") + .contains("GRANT SELECT ON default.items TO rt_user"); + + st.execute("ALTER USER rt_user IDENTIFIED WITH plaintext_password BY 'pw' HOST ANY"); + assertThat(select(url, "rt_user", "pw")).as("logs in once given a password and a host, and reads") + .isEqualTo("1"); + + execute(st, dialect.dropUser("rt_user", false).orElseThrow()); + assertThat(rows(st, USER)).as("dropped").isEmpty(); + assertThatThrownBy(() -> st.execute(dialect.dropUser("rt_user", false).orElseThrow())) + .as("a missing one").isInstanceOf(SQLException.class); + execute(st, dialect.dropUser("rt_user", true).orElseThrow()); + } + } + } + + /** The table as the user reads it, which logs it in: the driver may not ask the server before. */ + private static String select(String url, String user, String password) throws SQLException { + try (Connection c = DriverManager.getConnection(url, user, password); Statement st = c.createStatement(); + ResultSet rs = st.executeQuery("SELECT toString(id) FROM items")) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } + } + + private static void execute(Statement st, String sql) throws SQLException { + try { + st.execute(sql); + } catch (SQLException e) { + throw new SQLException(e.getMessage() + " in " + sql, e); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/sqlgen/ClickHouseAlterRenameOfflineTest.java b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/sqlgen/ClickHouseAlterRenameOfflineTest.java index 21eaaae0..ede14c46 100644 --- a/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/sqlgen/ClickHouseAlterRenameOfflineTest.java +++ b/dialect/db/clickhouse/src/test/java/org/eclipse/daanse/sql/dialect/db/clickhouse/sqlgen/ClickHouseAlterRenameOfflineTest.java @@ -22,8 +22,8 @@ /** * ClickHouse has no {@code ALTER TABLE ... RENAME TO} — table and view rename - * both go through the standalone {@code RENAME TABLE} statement, which also - * batches multiple pairs into one atomic statement. There is no b-tree index + * both go through the standalone {@code RENAME TABLE} statement, one per pair: + * a statement of several pairs is not atomic in ClickHouse. There is no b-tree index * DDL and no constraint rename; column rename is the SQL-99 default. */ class ClickHouseAlterRenameOfflineTest { @@ -49,12 +49,12 @@ void renameView_uses_the_same_RENAME_TABLE_form() { } @Test - void renameTables_emits_one_atomic_RENAME_TABLE_statement() { - assertThat(dialect.ddlGenerator().supportsAtomicMultiRenameTable()).isTrue(); + void renameTables_emits_one_RENAME_TABLE_statement_per_pair() { + assertThat(dialect.ddlGenerator().supportsAtomicMultiRenameTable()).isFalse(); assertThat(dialect.ddlGenerator().renameTables(List.of( new TableRename(TBL_A, "B"), new TableRename(TBL_B, "C")))) - .containsExactly("RENAME TABLE \"PUBLIC\".\"A\" TO \"B\", \"PUBLIC\".\"B\" TO \"C\""); + .containsExactly("RENAME TABLE \"PUBLIC\".\"A\" TO \"B\"", "RENAME TABLE \"PUBLIC\".\"B\" TO \"C\""); } @Test diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/MaterializedViewStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/MaterializedViewStatementsTest.java index 6e41c25e..a2e92f53 100644 --- a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/MaterializedViewStatementsTest.java +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/MaterializedViewStatementsTest.java @@ -75,7 +75,9 @@ static Stream dialects() { of("mysql", new MySqlDialect(), Expected.none()), of("mariadb", new MariaDBDialect(), Expected.none()), of("h2", new H2Dialect(), Expected.none()), - of("clickhouse", new ClickHouseDialect(), Expected.none()), + of("clickhouse, no version", new ClickHouseDialect(), clickhouse()), + of("clickhouse 24.10", new ClickHouseDialect(version(24, 10)), clickhouse()), + of("clickhouse 24.8", new ClickHouseDialect(version(24, 8)), Expected.none()), of("duckdb", new DuckDbDialect(), Expected.none()), of("sqlite", new SqliteDialect(), Expected.none()), of("derby", new DerbyDialect(), Expected.none()), @@ -98,6 +100,14 @@ void createAndDropAMaterializedView(Dialect dialect, Expected expected) { assertThat(ddl.dropMaterializedView(VIEW, true)).isEqualTo(Optional.ofNullable(expected.dropIfExists())); } + /** A refreshable materialized view, refreshed on demand in effect; ClickHouse drops it as a view. */ + private static Expected clickhouse() { + String rest = " REFRESH AFTER 10 YEAR ENGINE = MergeTree() ORDER BY tuple() AS " + QUERY; + return new Expected("CREATE MATERIALIZED VIEW \"s\".\"mv\"" + rest, + "CREATE MATERIALIZED VIEW IF NOT EXISTS \"s\".\"mv\"" + rest, "DROP VIEW \"s\".\"mv\"", + "DROP VIEW IF EXISTS \"s\".\"mv\""); + } + private static Arguments of(String name, Dialect dialect, Expected expected) { return Arguments.of(Named.of(name, dialect), expected); } diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java index 0927fc4d..6f98ad24 100644 --- a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java @@ -68,7 +68,9 @@ static Stream dialects() { "IF EXISTS (SELECT 1 FROM sys.extended_properties WHERE class = 1 AND major_id = OBJECT_ID(N'\"s\".\"v\"') AND minor_id = COLUMNPROPERTY(OBJECT_ID(N'\"s\".\"v\"'), N'c', 'ColumnId') AND name = N'MS_Description') EXEC sys.sp_updateextendedproperty @name = N'MS_Description', @value = N'it''s', @level0type = N'SCHEMA', @level0name = N's', @level1type = N'VIEW', @level1name = N'v', @level2type = N'COLUMN', @level2name = N'c' ELSE EXEC sys.sp_addextendedproperty @name = N'MS_Description', @value = N'it''s', @level0type = N'SCHEMA', @level0name = N's', @level1type = N'VIEW', @level1name = N'v', @level2type = N'COLUMN', @level2name = N'c'")), of("mysql", new MySqlDialect(), Expected.none()), of("mariadb", new MariaDBDialect(), Expected.none()), - of("clickhouse", new ClickHouseDialect(), Expected.none()), + of("clickhouse", new ClickHouseDialect(), + new Expected("ALTER TABLE \"s\".\"v\" MODIFY COMMENT 'it\\'s'", + "ALTER TABLE \"s\".\"v\" COMMENT COLUMN \"c\" 'it\\'s'")), of("hive", new HiveDialect(), Expected.none()), of("impala", new ImpalaDialect(), Expected.none()), of("sqlite", new SqliteDialect(), Expected.none()),