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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -615,9 +615,9 @@ default Optional<String> 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;
Expand Down
20 changes: 20 additions & 0 deletions dialect/db/clickhouse/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,25 @@
<groupId>biz.aQute.bnd</groupId>
<artifactId>biz.aQute.bndlib</artifactId>
</dependency>
<!-- Docker tests (container package, -Dintegration.docker=true). JUnit + assertj come from parent. -->
<dependency>
<groupId>com.clickhouse</groupId>
<artifactId>clickhouse-jdbc</artifactId>
<version>0.9.8</version>
<classifier>all</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>clickhouse</artifactId>
<version>1.21.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.21.4</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Large diffs are not rendered by default.

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

Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> 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<String> 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<String> rows(Statement st, String sql) throws SQLException {
List<String> out = new ArrayList<>();
try (ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
out.add(rs.getString(1));
}
}
return out;
}
}
Original file line number Diff line number Diff line change
@@ -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<String> 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<String> rows(Statement st, String sql) throws SQLException {
List<String> out = new ArrayList<>();
try (ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
out.add(rs.getString(1));
}
}
return out;
}
}
Loading
Loading