World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#9757] feat(catalogs): Support Clickhouse ITs and docs (#9878)
Qi Yuf87777fa3dcf
diff --git a/.github/workflows/backend-integration-test-action.yml b/.github/workflows/backend-integration-test-action.ymlindex 9bc3f4ec1b..3b1d82a843 100644--- a/.github/workflows/backend-integration-test-action.yml+++ b/.github/workflows/backend-integration-test-action.yml@@ -24,7 +24,7 @@ on:jobs:start-runner:name: JDK${{ inputs.java-version }}-${{ inputs.test-mode }}-${{ inputs.backend }}- runs-on: ubuntu-latest+ runs-on: ubuntu-22.04timeout-minutes: 90env:PLATFORM: ${{ inputs.architecture }}diff --git a/.github/workflows/backend-integration-test.yml b/.github/workflows/backend-integration-test.ymlindex b1b99ca818..376a3920d6 100644--- a/.github/workflows/backend-integration-test.yml+++ b/.github/workflows/backend-integration-test.yml@@ -13,7 +13,7 @@ concurrency:jobs:changes:- runs-on: ubuntu-latest+ runs-on: ubuntu-22.04steps:- uses: actions/checkout@v4- uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36diff --git a/.github/workflows/flink-integration-test-action.yml b/.github/workflows/flink-integration-test-action.ymlindex 92b2dd9867..881057969a 100644--- a/.github/workflows/flink-integration-test-action.yml+++ b/.github/workflows/flink-integration-test-action.yml@@ -17,7 +17,7 @@ jobs:start-runner:name: JDK${{ inputs.java-version }}runs-on: ubuntu-latest- timeout-minutes: 30+ timeout-minutes: 60env:PLATFORM: ${{ inputs.architecture }}steps:diff --git a/build.gradle.kts b/build.gradle.ktsindex 4fb1cec99a..8b9d6d95a1 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -219,7 +219,7 @@ allprojects {param.systemProperty("gravitino.log.path", "build/${project.name}-integration-test.log")project.delete("build/${project.name}-integration-test.log")if (testMode == "deploy") {- param.environment("GRAVITINO_HOME", project.rootDir.path + "/distribution/package")+ param.environment("GRAVITINO_HOME", project.rootDir.path + "/distribution/package-all")val useWebV2 = System.getenv("GRAVITINO_USE_WEB_V2")?.toBoolean() == trueval webWarPath = if (useWebV2) {project.rootDir.path + "/distribution/package/web-v2/gravitino-web-${project.version}.war"diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/build.gradle.kts b/catalogs-contrib/catalog-jdbc-clickhouse/build.gradle.ktsindex a42652835a..8f519f8ccf 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/build.gradle.kts+++ b/catalogs-contrib/catalog-jdbc-clickhouse/build.gradle.kts@@ -54,6 +54,9 @@ dependencies {testImplementation(libs.junit.jupiter.api)testImplementation(libs.junit.jupiter.params)testImplementation(libs.lz4.java)+ testImplementation(libs.mockito.core)+ testImplementation(libs.mysql.driver)+ testImplementation(libs.postgresql.driver)testImplementation(libs.testcontainers)testImplementation(libs.testcontainers.clickhouse)diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/ClickHouseCatalog.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/ClickHouseCatalog.javaindex 03d9650d58..7f0cb50864 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/ClickHouseCatalog.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/ClickHouseCatalog.java@@ -18,17 +18,21 @@*/package org.apache.gravitino.catalog.clickhouse;+import java.util.Map;import org.apache.gravitino.catalog.clickhouse.converter.ClickHouseColumnDefaultValueConverter;import org.apache.gravitino.catalog.clickhouse.converter.ClickHouseExceptionConverter;import org.apache.gravitino.catalog.clickhouse.converter.ClickHouseTypeConverter;+import org.apache.gravitino.catalog.clickhouse.operations.ClickHouseCatalogOperations;import org.apache.gravitino.catalog.clickhouse.operations.ClickHouseDatabaseOperations;import org.apache.gravitino.catalog.clickhouse.operations.ClickHouseTableOperations;import org.apache.gravitino.catalog.jdbc.JdbcCatalog;+import org.apache.gravitino.catalog.jdbc.JdbcCatalogOperations;import org.apache.gravitino.catalog.jdbc.converter.JdbcColumnDefaultValueConverter;import org.apache.gravitino.catalog.jdbc.converter.JdbcExceptionConverter;import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;import org.apache.gravitino.catalog.jdbc.operation.JdbcDatabaseOperations;import org.apache.gravitino.catalog.jdbc.operation.JdbcTableOperations;+import org.apache.gravitino.connector.CatalogOperations;import org.apache.gravitino.connector.PropertiesMetadata;import org.apache.gravitino.connector.capability.Capability;@@ -39,6 +43,19 @@ public class ClickHouseCatalog extends JdbcCatalog {return "jdbc-clickhouse";}+ @Override+ protected CatalogOperations newOps(Map<String, String> config) {+ JdbcTypeConverter jdbcTypeConverter = createJdbcTypeConverter();+ JdbcCatalogOperations ops =+ new ClickHouseCatalogOperations(+ createExceptionConverter(),+ jdbcTypeConverter,+ createJdbcDatabaseOperations(),+ createJdbcTableOperations(),+ createJdbcColumnDefaultValueConverter());+ return ops;+ }+@Overrideprotected JdbcExceptionConverter createExceptionConverter() {return new ClickHouseExceptionConverter();diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseCatalogOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseCatalogOperations.javanew file mode 100644index 0000000000..01631f3337--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseCatalogOperations.java@@ -0,0 +1,61 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.catalog.clickhouse.operations;++import java.sql.Driver;+import java.sql.DriverManager;+import org.apache.gravitino.catalog.jdbc.JdbcCatalogOperations;+import org.apache.gravitino.catalog.jdbc.converter.JdbcColumnDefaultValueConverter;+import org.apache.gravitino.catalog.jdbc.converter.JdbcExceptionConverter;+import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;+import org.apache.gravitino.catalog.jdbc.operation.JdbcDatabaseOperations;+import org.apache.gravitino.catalog.jdbc.operation.JdbcTableOperations;++public class ClickHouseCatalogOperations extends JdbcCatalogOperations {++ public ClickHouseCatalogOperations(+ JdbcExceptionConverter exceptionConverter,+ JdbcTypeConverter jdbcTypeConverter,+ JdbcDatabaseOperations databaseOperation,+ JdbcTableOperations tableOperation,+ JdbcColumnDefaultValueConverter columnDefaultValueConverter) {+ super(+ exceptionConverter,+ jdbcTypeConverter,+ databaseOperation,+ tableOperation,+ columnDefaultValueConverter);+ }++ @Override+ public void close() {+ super.close();++ // deregister ClickHouse JDBC driver to prevent memory leak in long-running applications+ try {+ Driver clickhouseDriver =+ DriverManager.getDriver("jdbc:clickhouse://dummy_address:8443/default");+ deregisterDriver(clickhouseDriver);+ } catch (java.sql.SQLException e) {+ // log and ignore+ System.err.println("Failed to deregister ClickHouse JDBC driver: " + e.getMessage());+ }+ }+}diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseDatabaseOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseDatabaseOperations.javaindex 9cdcdcd58c..7ae9a76de8 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseDatabaseOperations.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseDatabaseOperations.java@@ -32,6 +32,7 @@ import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.StringIdentifier;import org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.ClusterConstants;import org.apache.gravitino.catalog.jdbc.operation.JdbcDatabaseOperations;+import org.apache.gravitino.catalog.jdbc.utils.JdbcConnectorUtils;public class ClickHouseDatabaseOperations extends JdbcDatabaseOperations {@@ -100,6 +101,35 @@ public class ClickHouseDatabaseOperations extends JdbcDatabaseOperations {return createDatabaseSql.toString();}+ @Override+ public void create(String databaseName, String comment, Map<String, String> properties) {+ LOG.info("Beginning to create database {}", databaseName);+ String originComment = StringIdentifier.removeIdFromComment(comment);+ if (!supportSchemaComment() && StringUtils.isNotEmpty(originComment)) {+ throw new UnsupportedOperationException(+ "Doesn't support setting schema comment: " + originComment);+ }++ try (final Connection connection = getConnection()) {+ connection.setCatalog(createSysDatabaseNameSet().iterator().next());+ JdbcConnectorUtils.executeUpdate(+ connection, generateCreateDatabaseSql(databaseName, comment, properties));+ LOG.info("Finished creating database {}", databaseName);+ } catch (final SQLException se) {+ throw this.exceptionMapper.toGravitinoException(se);+ }+ }++ @Override+ protected void dropDatabase(String databaseName, boolean cascade) {+ try (final Connection connection = getConnection()) {+ connection.setCatalog(createSysDatabaseNameSet().iterator().next());+ JdbcConnectorUtils.executeUpdate(connection, generateDropDatabaseSql(databaseName, cascade));+ } catch (final SQLException se) {+ throw this.exceptionMapper.toGravitinoException(se);+ }+ }+private boolean onCluster(Map<String, String> dbProperties) {if (MapUtils.isEmpty(dbProperties)) {return false;diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.javaindex e364c89505..9858f59f65 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java@@ -22,6 +22,7 @@ import static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.IndexCimport static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.IndexConstants.DATA_SKIPPING_MINMAX_VALUE;import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.CLICKHOUSE_ENGINE_KEY;import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE_PROPERTY_ENTRY;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.GRAVITINO_ENGINE_KEY;import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;import com.google.common.annotations.VisibleForTesting;@@ -31,6 +32,7 @@ import java.sql.DatabaseMetaData;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;+import java.sql.Statement;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -38,6 +40,8 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;+import java.util.regex.Matcher;+import java.util.regex.Pattern;import java.util.stream.Collectors;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.MapUtils;@@ -57,12 +61,16 @@ import org.apache.gravitino.catalog.jdbc.utils.JdbcConnectorUtils;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.Expression;+import org.apache.gravitino.rel.expressions.FunctionExpression;import org.apache.gravitino.rel.expressions.NamedReference;+import org.apache.gravitino.rel.expressions.UnparsedExpression;import org.apache.gravitino.rel.expressions.distributions.Distribution;import org.apache.gravitino.rel.expressions.distributions.Distributions;import org.apache.gravitino.rel.expressions.sorts.NullOrdering;import org.apache.gravitino.rel.expressions.sorts.SortDirection;import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.sorts.SortOrders;import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.expressions.transforms.Transforms;import org.apache.gravitino.rel.indexes.Index;@@ -72,6 +80,15 @@ public class ClickHouseTableOperations extends JdbcTableOperations {private static final String CLICKHOUSE_NOT_SUPPORT_NESTED_COLUMN_MSG ="Clickhouse does not support nested column names.";+ private static final Pattern ORDER_BY_PATTERN =+ Pattern.compile("ORDER\\s+BY\\s+([^\\n]+)", Pattern.CASE_INSENSITIVE);+ private static final Pattern PARTITION_BY_PATTERN =+ Pattern.compile("PARTITION\\s+BY\\s+([^\\n]+)", Pattern.CASE_INSENSITIVE);+ private static final Pattern ON_CLUSTER_PATTERN =+ Pattern.compile("(?i)\\bON\\s+CLUSTER\\s+`?([^`\\s(]+)`?");+ private static final Pattern DISTRIBUTED_ENGINE_PATTERN =+ Pattern.compile(+ "(?i)^Distributed\\(([^,]+),\\s*([^,]+),\\s*([^,]+),\\s*(.+)\\)$", Pattern.DOTALL);private static final String QUERY_INDEXES_SQL ="""@@ -93,8 +110,7 @@ public class ClickHouseTableOperations extends JdbcTableOperations {protected List<Index> getIndexes(Connection connection, String databaseName, String tableName) {// cause clickhouse not impl getPrimaryKeys yet, ref:// https://github.com/ClickHouse/clickhouse-java/issues/1625- String sql =- QUERY_INDEXES_SQL.formatted(quoteIdentifier(databaseName), quoteIdentifier(tableName));+ String sql = QUERY_INDEXES_SQL.formatted(databaseName, tableName);try (PreparedStatement preparedStatement = connection.prepareStatement(sql);ResultSet resultSet = preparedStatement.executeQuery()) {@@ -112,6 +128,11 @@ public class ClickHouseTableOperations extends JdbcTableOperations {}}+ @Override+ public boolean supportsTableSortOrder() {+ return true;+ }+@Overrideprotected String generateCreateTableSql(String tableName,@@ -214,9 +235,16 @@ public class ClickHouseTableOperations extends JdbcTableOperations {return;}- String settings =+ Map<String, String> settingMap =properties.entrySet().stream().filter(entry -> entry.getKey().startsWith(TableConstants.SETTINGS_PREFIX))+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));+ if (MapUtils.isEmpty(settingMap)) {+ return;+ }++ String settings =+ settingMap.entrySet().stream().map(entry ->entry.getKey().substring(TableConstants.SETTINGS_PREFIX.length())@@ -226,7 +254,7 @@ public class ClickHouseTableOperations extends JdbcTableOperations {sqlBuilder.append(settings);}- private static void appendOrderBy(+ private void appendOrderBy(SortOrder[] sortOrders,StringBuilder sqlBuilder,ClickHouseTablePropertiesMetadata.ENGINE engine) {@@ -248,28 +276,33 @@ public class ClickHouseTableOperations extends JdbcTableOperations {"ORDER BY clause is required for engine: " + engine.getValue());}- if (sortOrders.length > 1) {- throw new UnsupportedOperationException(- "Currently ClickHouse does not support sortOrders with more than 1 element");- }+ List<String> orderBySql = new ArrayList<>();+ for (SortOrder sortOrder : sortOrders) {+ NullOrdering nullOrdering = sortOrder.nullOrdering();+ SortDirection sortDirection = sortOrder.direction();+ if (nullOrdering != null) {+ LOG.warn(+ "ClickHouse currently does not support nullOrdering: {}, and will ignore it",+ nullOrdering);+ }- NullOrdering nullOrdering = sortOrders[0].nullOrdering();- SortDirection sortDirection = sortOrders[0].direction();- if (nullOrdering != null && sortDirection != null) {- // ClickHouse does not support NULLS FIRST/LAST now.- LOG.warn(- "ClickHouse currently does not support nullOrdering: {}, and will ignore it",- nullOrdering);+ String exprSql = toOrderBySql(sortOrder.expression());+ if (sortDirection == SortDirection.DESCENDING) {+ exprSql = exprSql + " DESC";+ }+ orderBySql.add(exprSql);}- sqlBuilder.append("\n ORDER BY `%s`\n".formatted(sortOrders[0].expression()));+ String renderedOrderBy =+ orderBySql.size() == 1 ? orderBySql.get(0) : "(" + String.join(", ", orderBySql) + ")";+ sqlBuilder.append("\n ORDER BY ").append(renderedOrderBy).append("\n");}private ClickHouseTablePropertiesMetadata.ENGINE appendTableEngine(Map<String, String> properties, StringBuilder sqlBuilder, JdbcColumn[] columns) {ClickHouseTablePropertiesMetadata.ENGINE engine = ENGINE_PROPERTY_ENTRY.getDefaultValue();if (MapUtils.isNotEmpty(properties)) {- String userSetEngine = properties.get(CLICKHOUSE_ENGINE_KEY);+ String userSetEngine = properties.get(GRAVITINO_ENGINE_KEY);if (StringUtils.isNotEmpty(userSetEngine)) {engine = ClickHouseTablePropertiesMetadata.ENGINE.fromString(userSetEngine);}@@ -302,6 +335,11 @@ public class ClickHouseTableOperations extends JdbcTableOperations {Preconditions.checkArgument(StringUtils.isNotBlank(remoteTable), "Remote table must be specified for Distributed");+ // User must ensure the sharding key is a trusted value.+ // TODO(yuqi) WE need to check the columns in shard keys should be integer and not nullable,+ // as clickhouse distributed table requires the sharding key to be integer and not nullable.+ // We can add this validation after we support user defined sharding key in index, as we can+ // reuse the index field definition for validation.Preconditions.checkArgument(StringUtils.isNotBlank(shardingKey), "Sharding key must be specified for Distributed");@@ -479,7 +517,35 @@ public class ClickHouseTableOperations extends JdbcTableOperations {new HashMap<String, String>() {{put(COMMENT, resultSet.getString(COMMENT));- put(CLICKHOUSE_ENGINE_KEY, resultSet.getString(CLICKHOUSE_ENGINE_KEY));+ String engine = resultSet.getString(CLICKHOUSE_ENGINE_KEY);+ put(GRAVITINO_ENGINE_KEY, engine);+ String createSql = parseShowCreateTableSql(connection, tableName);+ Matcher onClusterMatcher = ON_CLUSTER_PATTERN.matcher(createSql);+ if (onClusterMatcher.find()) {+ put(ClusterConstants.ON_CLUSTER, String.valueOf(true));+ put(ClusterConstants.CLUSTER_NAME, unquote(onClusterMatcher.group(1)));+ } else {+ put(ClusterConstants.ON_CLUSTER, String.valueOf(false));+ }++ if (StringUtils.equalsIgnoreCase(engine, ENGINE.DISTRIBUTED.getValue())) {+ String engineFull = resultSet.getString("engine_full");+ Matcher distributedEngineMatcher =+ DISTRIBUTED_ENGINE_PATTERN.matcher(StringUtils.trimToEmpty(engineFull));+ if (distributedEngineMatcher.matches()) {+ String distributedClusterName = unquote(distributedEngineMatcher.group(1));+ put(ClusterConstants.CLUSTER_NAME, distributedClusterName);+ put(+ DistributedTableConstants.REMOTE_DATABASE,+ unquote(distributedEngineMatcher.group(2)));+ put(+ DistributedTableConstants.REMOTE_TABLE,+ unquote(distributedEngineMatcher.group(3)));+ put(+ DistributedTableConstants.SHARDING_KEY,+ StringUtils.trim(distributedEngineMatcher.group(4)));+ }+ }}});}@@ -491,6 +557,49 @@ public class ClickHouseTableOperations extends JdbcTableOperations {}}+ @Override+ public JdbcTable load(String databaseName, String tableName) throws NoSuchTableException {+ try (Connection connection = getConnection(databaseName)) {+ ResultSet tables = getTable(connection, databaseName, tableName);+ JdbcTable.Builder jdbcTableBuilder = getTableBuilder(tables, databaseName, tableName);++ List<JdbcColumn> jdbcColumns = new ArrayList<>();+ ResultSet columns = getColumns(connection, databaseName, tableName);+ while (columns.next()) {+ JdbcColumn.Builder columnBuilder = getColumnBuilder(columns, databaseName, tableName);+ if (columnBuilder != null) {+ boolean autoIncrement = getAutoIncrementInfo(columns);+ columnBuilder.withAutoIncrement(autoIncrement);+ jdbcColumns.add(columnBuilder.build());+ }+ }+ jdbcTableBuilder.withColumns(jdbcColumns.toArray(new JdbcColumn[0]));++ List<Index> indexes = getIndexes(connection, databaseName, tableName);+ jdbcTableBuilder.withIndexes(indexes.toArray(new Index[0]));++ ShowCreateTableMetadata metadata = parseShowCreateTable(connection, tableName);+ Transform[] partitioning = metadata.partitioning;+ if (ArrayUtils.isEmpty(partitioning)) {+ partitioning = getTablePartitioning(connection, databaseName, tableName);+ }+ jdbcTableBuilder.withPartitioning(partitioning);+ jdbcTableBuilder.withSortOrders(metadata.sortOrders);++ Distribution distribution = getDistributionInfo(connection, databaseName, tableName);+ jdbcTableBuilder.withDistribution(distribution);++ Map<String, String> tableProperties = getTableProperties(connection, tableName);+ jdbcTableBuilder.withProperties(tableProperties);++ correctJdbcTableFields(connection, databaseName, tableName, jdbcTableBuilder);++ return jdbcTableBuilder.withTableOperation(this).build();+ } catch (SQLException e) {+ throw exceptionMapper.toGravitinoException(e);+ }+ }+@Overrideprotected Transform[] getTablePartitioning(Connection connection, String databaseName, String tableName) throws SQLException {@@ -874,6 +983,146 @@ public class ClickHouseTableOperations extends JdbcTableOperations {return ClickHouseTableSqlUtils.parsePartitioning(partitionKey);}+ private ShowCreateTableMetadata parseCreateStatement(String createSql) {+ ShowCreateTableMetadata metadata = new ShowCreateTableMetadata();+ if (StringUtils.isBlank(createSql)) {+ return metadata;+ }++ Matcher orderMatcher = ORDER_BY_PATTERN.matcher(createSql);+ if (orderMatcher.find()) {+ metadata.sortOrders = parseOrderByClause(orderMatcher.group(1));+ }++ Matcher partitionMatcher = PARTITION_BY_PATTERN.matcher(createSql);+ if (partitionMatcher.find()) {+ metadata.partitioning = parsePartitioning(partitionMatcher.group(1));+ }++ return metadata;+ }++ private ShowCreateTableMetadata parseShowCreateTable(Connection connection, String tableName)+ throws SQLException {+ String createSql = parseShowCreateTableSql(connection, tableName);+ return parseCreateStatement(createSql);+ }++ private String parseShowCreateTableSql(Connection connection, String tableName)+ throws SQLException {+ String sql = "SHOW CREATE TABLE " + quoteIdentifier(tableName);+ try (Statement statement = connection.createStatement();+ ResultSet resultSet = statement.executeQuery(sql)) {+ if (resultSet.next()) {+ return resultSet.getString(1);+ }+ throw new SQLException("SHOW CREATE TABLE returned no rows for " + tableName);+ }+ }++ private String unquote(String value) {+ String trimmed = StringUtils.trimToEmpty(value);+ if (StringUtils.length(trimmed) >= 2) {+ char first = trimmed.charAt(0);+ char last = trimmed.charAt(trimmed.length() - 1);+ if ((first == '\'' && last == '\'') || (first == '`' && last == '`')) {+ return trimmed.substring(1, trimmed.length() - 1);+ }+ }+ return trimmed;+ }++ private SortOrder[] parseOrderByClause(String orderClause) {+ if (StringUtils.isBlank(orderClause)) {+ return SortOrders.NONE;+ }+ String trimmed = orderClause.trim();+ if (trimmed.startsWith("(") && trimmed.endsWith(")")) {+ trimmed = trimmed.substring(1, trimmed.length() - 1);+ }++ List<String> expressions = splitExpressions(trimmed);+ List<SortOrder> sortOrders = new ArrayList<>();+ for (String expression : expressions) {+ Expression sortExpr = toSortExpression(expression);+ sortOrders.add(SortOrders.of(sortExpr, SortDirection.ASCENDING));+ }+ return sortOrders.toArray(new SortOrder[0]);+ }++ private List<String> splitExpressions(String expressionList) {+ List<String> expressions = new ArrayList<>();+ StringBuilder current = new StringBuilder();+ int depth = 0;+ for (int i = 0; i < expressionList.length(); i++) {+ char ch = expressionList.charAt(i);+ if (ch == '(') {+ depth++;+ } else if (ch == ')') {+ depth--;+ } else if (ch == ',' && depth == 0) {+ expressions.add(current.toString());+ current.setLength(0);+ continue;+ }+ current.append(ch);+ }+ if (current.length() > 0) {+ expressions.add(current.toString());+ }+ return expressions;+ }++ private Expression toSortExpression(String expression) {+ String trimmed = StringUtils.trim(expression);+ if (StringUtils.isBlank(trimmed)) {+ return UnparsedExpression.of(expression);+ }+ String unquoted = trimmed;+ if (StringUtils.startsWith(unquoted, "`") && StringUtils.endsWith(unquoted, "`")) {+ unquoted = unquoted.substring(1, unquoted.length() - 1);+ }+ if (unquoted.matches("[A-Za-z_][A-Za-z0-9_]*")) {+ return NamedReference.field(unquoted);+ }++ int firstParen = unquoted.indexOf('(');+ int lastParen = unquoted.lastIndexOf(')');+ if (firstParen > 0 && lastParen > firstParen) {+ String funcName = unquoted.substring(0, firstParen).trim();+ if (funcName.matches("[A-Za-z_][A-Za-z0-9_]*")) {+ String argsString = unquoted.substring(firstParen + 1, lastParen);+ List<String> args = splitExpressions(argsString);+ Expression[] parsedArgs =+ args.stream().map(this::toSortExpression).toArray(Expression[]::new);+ return FunctionExpression.of(funcName, parsedArgs);+ }+ }++ return UnparsedExpression.of(trimmed);+ }++ private String toOrderBySql(Expression expression) {+ if (expression instanceof NamedReference) {+ String[] parts = ((NamedReference) expression).fieldName();+ return "`" + String.join("`.`", parts) + "`";+ } else if (expression instanceof FunctionExpression) {+ FunctionExpression func = (FunctionExpression) expression;+ return func.functionName()+ + Arrays.stream(func.arguments())+ .map(this::toOrderBySql)+ .collect(Collectors.joining(", ", "(", ")"));+ } else if (expression instanceof UnparsedExpression) {+ return ((UnparsedExpression) expression).unparsedExpression();+ }+ return expression.toString();+ }++ private static final class ShowCreateTableMetadata {+ private Transform[] partitioning = Transforms.EMPTY_TRANSFORM;+ private SortOrder[] sortOrders = SortOrders.NONE;+ }+@VisibleForTestingString[][] parseIndexFields(String expression) {return ClickHouseTableSqlUtils.parseIndexFields(expression);diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/AuditCatalogClickHouseIT.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/AuditCatalogClickHouseIT.javanew file mode 100644index 0000000000..9416dc7b4c--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/AuditCatalogClickHouseIT.java@@ -0,0 +1,188 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.catalog.clickhouse.integration.test;++import static org.apache.gravitino.catalog.clickhouse.ClickHouseUtils.getSortOrders;+import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;++import com.google.common.collect.Maps;+import java.io.IOException;+import java.sql.SQLException;+import java.util.Collections;+import java.util.Map;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.CatalogChange;+import org.apache.gravitino.Configs;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.auth.AuthenticatorType;+import org.apache.gravitino.catalog.clickhouse.integration.test.service.ClickHouseService;+import org.apache.gravitino.catalog.jdbc.config.JdbcConfig;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.integration.test.container.ClickHouseContainer;+import org.apache.gravitino.integration.test.container.ContainerSuite;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.gravitino.integration.test.util.TestDatabaseName;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.types.Types;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;++@Tag("gravitino-docker-test")+public class AuditCatalogClickHouseIT extends BaseIT {+ private static final ContainerSuite containerSuite = ContainerSuite.getInstance();+ public static final String metalakeName =+ GravitinoITUtils.genRandomName("audit_clickhouse_metalake");+ private static final String expectUser = System.getProperty("user.name");+ protected static TestDatabaseName TEST_DB_NAME;+ private static final String provider = "jdbc-clickhouse";++ private static ClickHouseService clickhouseService;+ private static ClickHouseContainer CLICKHOUSE_CONTAINER;+ private static GravitinoMetalake metalake;++ @BeforeAll+ public void startIntegrationTest() throws Exception {+ Map<String, String> configs = Maps.newHashMap();+ configs.put(Configs.AUTHENTICATORS.getKey(), AuthenticatorType.SIMPLE.name().toLowerCase());+ registerCustomConfigs(configs);+ super.startIntegrationTest();++ containerSuite.startClickHouseContainer(+ TestDatabaseName.CLICKHOUSE_AUDIT_CATALOG_CLICKHOUSE_IT);+ CLICKHOUSE_CONTAINER = containerSuite.getClickHouseContainer();+ TEST_DB_NAME = TestDatabaseName.CLICKHOUSE_AUDIT_CATALOG_CLICKHOUSE_IT;+ clickhouseService =+ new ClickHouseService(containerSuite.getClickHouseContainer(), TEST_DB_NAME);+ createMetalake();+ }++ @AfterAll+ public void stopIntegrationTest() throws IOException, InterruptedException {+ client.dropMetalake(metalakeName, true);+ clickhouseService.close();+ super.stopIntegrationTest();+ }++ @Test+ public void testAuditCatalog() throws Exception {+ String catalogName = GravitinoITUtils.genRandomName("audit_clickhouse_catalog");+ Catalog catalog = createCatalog(catalogName);++ Assertions.assertEquals(expectUser, catalog.auditInfo().creator());+ Assertions.assertEquals(catalog.auditInfo().creator(), catalog.auditInfo().lastModifier());+ Assertions.assertEquals(+ catalog.auditInfo().createTime(), catalog.auditInfo().lastModifiedTime());+ catalog = metalake.alterCatalog(catalogName, CatalogChange.setProperty("key1", "value1"));+ Assertions.assertEquals(expectUser, catalog.auditInfo().creator());+ Assertions.assertEquals(expectUser, catalog.auditInfo().lastModifier());++ metalake.dropCatalog(catalogName, true);+ }++ @Test+ public void testAuditSchema() throws Exception {+ String catalogName = GravitinoITUtils.genRandomName("audit_clickhouse_schema_catalog");+ String schemaName = GravitinoITUtils.genRandomName("audit_clickhouse_schema");+ Catalog catalog = createCatalog(catalogName);+ Map<String, String> prop = Maps.newHashMap();+ Schema schema = catalog.asSchemas().createSchema(schemaName, null, prop);+ Assertions.assertEquals(expectUser, schema.auditInfo().creator());+ Assertions.assertNull(schema.auditInfo().lastModifier());++ catalog.asSchemas().dropSchema(schemaName, true);+ metalake.dropCatalog(catalogName, true);+ }++ @Test+ public void testAuditTable() throws Exception {+ String catalogName = GravitinoITUtils.genRandomName("audit_clickhouse_table_catalog");+ String schemaName = GravitinoITUtils.genRandomName("audit_clickhouse_table_schema");+ String tableName = GravitinoITUtils.genRandomName("audit_clickhouse_table");+ Catalog catalog = createCatalog(catalogName);+ Map<String, String> properties = Maps.newHashMap();++ Column col1 =+ Column.of(+ "col_1", Types.IntegerType.get(), "col_1_comment", false, false, DEFAULT_VALUE_NOT_SET);++ catalog.asSchemas().createSchema(schemaName, null, properties);+ Table table =+ catalog+ .asTableCatalog()+ .createTable(+ NameIdentifier.of(schemaName, tableName),+ new Column[] {col1},+ "comment",+ properties,+ null,+ null,+ getSortOrders("col_1"));+ Assertions.assertEquals(expectUser, table.auditInfo().creator());+ Assertions.assertNull(table.auditInfo().lastModifier());+ table =+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.addColumn(new String[] {"col_4"}, Types.StringType.get()));+ Assertions.assertEquals(expectUser, table.auditInfo().creator());+ Assertions.assertEquals(expectUser, table.auditInfo().lastModifier());++ catalog.asTableCatalog().dropTable(NameIdentifier.of(schemaName, tableName));+ catalog.asSchemas().dropSchema(schemaName, true);+ metalake.dropCatalog(catalogName, true);+ }++ private static Catalog createCatalog(String catalogName) throws SQLException {+ Map<String, String> catalogProperties = Maps.newHashMap();++ catalogProperties.put(+ JdbcConfig.JDBC_URL.getKey(),+ StringUtils.substring(+ CLICKHOUSE_CONTAINER.getJdbcUrl(TEST_DB_NAME),+ 0,+ CLICKHOUSE_CONTAINER.getJdbcUrl(TEST_DB_NAME).lastIndexOf("/")));+ catalogProperties.put(+ JdbcConfig.JDBC_DRIVER.getKey(), CLICKHOUSE_CONTAINER.getDriverClassName(TEST_DB_NAME));+ catalogProperties.put(JdbcConfig.USERNAME.getKey(), CLICKHOUSE_CONTAINER.getUsername());+ catalogProperties.put(JdbcConfig.PASSWORD.getKey(), CLICKHOUSE_CONTAINER.getPassword());++ return metalake.createCatalog(+ catalogName, Catalog.Type.RELATIONAL, provider, "comment", catalogProperties);+ }++ private void createMetalake() {+ GravitinoMetalake[] gravitinoMetalakes = client.listMetalakes();+ Assertions.assertEquals(0, gravitinoMetalakes.length);++ client.createMetalake(metalakeName, "comment", Collections.emptyMap());+ GravitinoMetalake loadMetalake = client.loadMetalake(metalakeName);+ Assertions.assertEquals(metalakeName, loadMetalake.name());+ metalake = loadMetalake;+ }+}diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/CatalogClickHouseClusterIT.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/CatalogClickHouseClusterIT.javanew file mode 100644index 0000000000..43a6146106--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/CatalogClickHouseClusterIT.java@@ -0,0 +1,359 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.gravitino.catalog.clickhouse.integration.test;++import static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.ClusterConstants.CLUSTER_NAME;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.ClusterConstants.ON_CLUSTER;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.DistributedTableConstants.REMOTE_DATABASE;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.DistributedTableConstants.REMOTE_TABLE;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.DistributedTableConstants.SHARDING_KEY;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.GRAVITINO_ENGINE_KEY;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseUtils.getSortOrders;+import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;++import com.google.common.collect.Maps;+import java.nio.file.Paths;+import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.ResultSet;+import java.sql.Statement;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.Schema;+import org.apache.gravitino.catalog.clickhouse.integration.test.service.ClickHouseService;+import org.apache.gravitino.catalog.jdbc.config.JdbcConfig;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.integration.test.container.ClickHouseContainer;+import org.apache.gravitino.integration.test.container.ContainerSuite;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.gravitino.integration.test.util.TestDatabaseName;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableCatalog;+import org.apache.gravitino.rel.expressions.distributions.Distribution;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.types.Types;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.api.TestInstance.Lifecycle;++@Tag("gravitino-docker-test")+@TestInstance(Lifecycle.PER_CLASS)+public class CatalogClickHouseClusterIT extends BaseIT {+ private static final ContainerSuite containerSuite = ContainerSuite.getInstance();+ private static final String provider = "jdbc-clickhouse";++ private final String metalakeName = GravitinoITUtils.genRandomName("ck_cluster_metalake");+ private final String catalogName = GravitinoITUtils.genRandomName("ck_cluster_catalog");+ private final String schemaName = GravitinoITUtils.genRandomName("ck_cluster_schema");+ private final String localTableName = GravitinoITUtils.genRandomName("ck_cluster_local");+ private final String distributedTableName = GravitinoITUtils.genRandomName("ck_cluster_dist");+ private final String nonClusterTableName = GravitinoITUtils.genRandomName("ck_non_cluster_local");+ private final String sqlClusterLocalTableName =+ GravitinoITUtils.genRandomName("ck_sql_cluster_local");+ private final String sqlClusterDistributedTableName =+ GravitinoITUtils.genRandomName("ck_sql_cluster_dist");+ private final String sqlNonClusterLocalTableName =+ GravitinoITUtils.genRandomName("ck_sql_non_cluster_local");+ private final String sqlNonClusterDistributedTableName =+ GravitinoITUtils.genRandomName("ck_sql_non_cluster_dist");+ private final String tableComment = "cluster_table_comment";++ private GravitinoMetalake metalake;+ private Catalog catalog;+ private ClickHouseService clickHouseService;+ private ClickHouseContainer clickHouseClusterContainer;+ private final TestDatabaseName TEST_DB_NAME = TestDatabaseName.CLICKHOUSE_CLUSTER_CLICKHOUSE_IT;++ @BeforeAll+ public void startup() {+ String remoteServersConfig =+ Paths.get("src", "test", "resources", "remote_servers.xml").toAbsolutePath().toString();+ containerSuite.startClickHouseClusterContainer(TEST_DB_NAME, remoteServersConfig);+ clickHouseClusterContainer = containerSuite.getClickHouseClusterContainer();++ clickHouseService = new ClickHouseService(clickHouseClusterContainer, TEST_DB_NAME);+ createMetalake();+ createCatalog();+ createSchema();+ }++ @AfterAll+ public void stop() {+ clearTableAndSchema();+ metalake.disableCatalog(catalogName);+ metalake.dropCatalog(catalogName, true);+ client.disableMetalake(metalakeName);+ client.dropMetalake(metalakeName, true);+ clickHouseService.close();+ }++ private void clearTableAndSchema() {+ NameIdentifier[] nameIdentifiers =+ catalog.asTableCatalog().listTables(Namespace.of(schemaName));+ for (NameIdentifier nameIdentifier : nameIdentifiers) {+ catalog.asTableCatalog().dropTable(nameIdentifier);+ }+ catalog.asSchemas().dropSchema(schemaName, false);+ }++ private void createMetalake() {+ client.createMetalake(metalakeName, "cluster metalake", Collections.emptyMap());+ metalake = client.loadMetalake(metalakeName);+ }++ private void createCatalog() {+ Map<String, String> catalogProperties = Maps.newHashMap();++ catalogProperties.put(+ JdbcConfig.JDBC_URL.getKey(),+ StringUtils.substring(+ clickHouseClusterContainer.getJdbcUrl(TEST_DB_NAME),+ 0,+ clickHouseClusterContainer.getJdbcUrl(TEST_DB_NAME).lastIndexOf("/")));+ try {+ catalogProperties.put(+ JdbcConfig.JDBC_DRIVER.getKey(),+ clickHouseClusterContainer.getDriverClassName(TEST_DB_NAME));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ catalogProperties.put(JdbcConfig.USERNAME.getKey(), clickHouseClusterContainer.getUsername());+ catalogProperties.put(JdbcConfig.PASSWORD.getKey(), clickHouseClusterContainer.getPassword());++ catalog =+ metalake.createCatalog(+ catalogName, Catalog.Type.RELATIONAL, provider, "cluster catalog", catalogProperties);+ }++ private void createSchema() {+ Schema createdSchema =+ catalog.asSchemas().createSchema(schemaName, null, Collections.emptyMap());+ Schema loadSchema = catalog.asSchemas().loadSchema(schemaName);+ Assertions.assertEquals(createdSchema.name(), loadSchema.name());+ }++ private Column[] createColumns() {+ // TODO( check hash field)+ Column col1 =+ Column.of(+ "col_1",+ Types.IntegerType.get(),+ "col_1_comment",+ false,+ false,+ Literals.integerLiteral(0));+ Column col2 = Column.of("col_2", Types.DateType.get(), "col_2_comment");+ Column col3 =+ Column.of(+ "col_3", Types.StringType.get(), "col_3_comment", false, false, DEFAULT_VALUE_NOT_SET);+ return new Column[] {col1, col2, col3};+ }++ private Map<String, String> clusterMergeTreeProperties() {+ Map<String, String> properties = new HashMap<>();+ properties.put(GRAVITINO_ENGINE_KEY, ENGINE.MERGETREE.getValue());+ properties.put(CLUSTER_NAME, ClickHouseContainer.DEFAULT_CLUSTER_NAME);+ properties.put(ON_CLUSTER, String.valueOf(true));+ return properties;+ }++ private Map<String, String> distributedProperties(String remoteTable) {+ Map<String, String> properties = new HashMap<>();+ properties.put(GRAVITINO_ENGINE_KEY, ENGINE.DISTRIBUTED.getValue());+ properties.put(CLUSTER_NAME, ClickHouseContainer.DEFAULT_CLUSTER_NAME);+ properties.put(ON_CLUSTER, String.valueOf(true));+ properties.put(REMOTE_DATABASE, schemaName);+ properties.put(REMOTE_TABLE, remoteTable);+ properties.put(SHARDING_KEY, "cityHash64(col_1)");+ return properties;+ }++ @Test+ public void testCreateDistributedTableOnCluster() throws Exception {+ Column[] columns = createColumns();+ NameIdentifier localTableIdent = NameIdentifier.of(schemaName, localTableName);+ NameIdentifier distributedTableIdent = NameIdentifier.of(schemaName, distributedTableName);+ Distribution distribution = Distributions.NONE;+ Transform[] partitioning = Transforms.EMPTY_TRANSFORM;+ TableCatalog tableCatalog = catalog.asTableCatalog();++ Table localTable =+ tableCatalog.createTable(+ localTableIdent,+ columns,+ tableComment,+ clusterMergeTreeProperties(),+ partitioning,+ distribution,+ getSortOrders("col_3"));++ Assertions.assertTrue(localTable != null && localTable.name().equals(localTableName));+ Table loadedLocalTable = tableCatalog.loadTable(localTableIdent);+ Assertions.assertEquals(+ ENGINE.MERGETREE.getValue(), loadedLocalTable.properties().get(GRAVITINO_ENGINE_KEY));+ Assertions.assertEquals("false", loadedLocalTable.properties().get(ON_CLUSTER));+ Assertions.assertFalse(loadedLocalTable.properties().containsKey(CLUSTER_NAME));++ Table distributedTable =+ tableCatalog.createTable(+ distributedTableIdent,+ columns,+ tableComment,+ distributedProperties(localTableName),+ partitioning,+ distribution,+ null);+ Assertions.assertTrue(+ distributedTable != null && distributedTable.name().equals(distributedTableName));+ Table loadedDistributedTable = tableCatalog.loadTable(distributedTableIdent);+ Assertions.assertEquals(+ ENGINE.DISTRIBUTED.getValue(),+ loadedDistributedTable.properties().get(GRAVITINO_ENGINE_KEY));+ Assertions.assertEquals("false", loadedDistributedTable.properties().get(ON_CLUSTER));+ Assertions.assertEquals(+ ClickHouseContainer.DEFAULT_CLUSTER_NAME,+ loadedDistributedTable.properties().get(CLUSTER_NAME));+ Assertions.assertEquals(schemaName, loadedDistributedTable.properties().get(REMOTE_DATABASE));+ Assertions.assertEquals(localTableName, loadedDistributedTable.properties().get(REMOTE_TABLE));++ NameIdentifier nonClusterTableIdent = NameIdentifier.of(schemaName, nonClusterTableName);+ Table nonClusterTable =+ tableCatalog.createTable(+ nonClusterTableIdent,+ columns,+ tableComment,+ Collections.singletonMap(GRAVITINO_ENGINE_KEY, ENGINE.MERGETREE.getValue()),+ partitioning,+ distribution,+ getSortOrders("col_3"));+ Assertions.assertTrue(+ nonClusterTable != null && nonClusterTable.name().equals(nonClusterTableName));+ Table loadedNonClusterTable = tableCatalog.loadTable(nonClusterTableIdent);+ Assertions.assertEquals(+ ENGINE.MERGETREE.getValue(), loadedNonClusterTable.properties().get(GRAVITINO_ENGINE_KEY));+ Assertions.assertEquals("false", loadedNonClusterTable.properties().get(ON_CLUSTER));+ Assertions.assertFalse(loadedNonClusterTable.properties().containsKey(CLUSTER_NAME));++ try (Connection connection =+ DriverManager.getConnection(+ clickHouseClusterContainer.getJdbcUrl(TEST_DB_NAME),+ clickHouseClusterContainer.getUsername(),+ clickHouseClusterContainer.getPassword());+ Statement statement = connection.createStatement()) {+ statement.execute(+ String.format(+ "INSERT INTO `%s`.`%s` VALUES (1, toDate('2020-01-01'), 'inserted')",+ schemaName, localTableName));+ try (ResultSet resultSet =+ statement.executeQuery(+ String.format("SELECT count() FROM `%s`.`%s`", schemaName, distributedTableName))) {+ Assertions.assertTrue(resultSet.next());+ Assertions.assertEquals(1L, resultSet.getLong(1));+ }+ }+ }++ @Test+ public void testLoadSqlCreatedLocalAndDistributedTableProperties() {+ clickHouseService.executeQuery(+ String.format(+ "CREATE TABLE `%s`.`%s` ON CLUSTER `%s` ("+ + "col_1 Int32, col_2 Date, col_3 String) "+ + "ENGINE = MergeTree ORDER BY col_1",+ schemaName, sqlClusterLocalTableName, ClickHouseContainer.DEFAULT_CLUSTER_NAME));++ clickHouseService.executeQuery(+ String.format(+ "CREATE TABLE `%s`.`%s` ON CLUSTER `%s` AS `%s`.`%s` "+ + "ENGINE = Distributed('%s', '%s', '%s', cityHash64(col_1))",+ schemaName,+ sqlClusterDistributedTableName,+ ClickHouseContainer.DEFAULT_CLUSTER_NAME,+ schemaName,+ sqlClusterLocalTableName,+ ClickHouseContainer.DEFAULT_CLUSTER_NAME,+ schemaName,+ sqlClusterLocalTableName));++ clickHouseService.executeQuery(+ String.format(+ "CREATE TABLE `%s`.`%s` (col_1 Int32, col_2 Date, col_3 String) "+ + "ENGINE = MergeTree ORDER BY col_1",+ schemaName, sqlNonClusterLocalTableName));++ clickHouseService.executeQuery(+ String.format(+ "CREATE TABLE `%s`.`%s` AS `%s`.`%s` "+ + "ENGINE = Distributed('%s', '%s', '%s', cityHash64(col_1))",+ schemaName,+ sqlNonClusterDistributedTableName,+ schemaName,+ sqlNonClusterLocalTableName,+ ClickHouseContainer.DEFAULT_CLUSTER_NAME,+ schemaName,+ sqlNonClusterLocalTableName));++ TableCatalog tableCatalog = catalog.asTableCatalog();+ Table sqlLocalTable =+ tableCatalog.loadTable(NameIdentifier.of(schemaName, sqlClusterLocalTableName));+ Assertions.assertEquals(+ ENGINE.MERGETREE.getValue(), sqlLocalTable.properties().get(GRAVITINO_ENGINE_KEY));+ Assertions.assertEquals("false", sqlLocalTable.properties().get(ON_CLUSTER));++ Table sqlDistributedTable =+ tableCatalog.loadTable(NameIdentifier.of(schemaName, sqlClusterDistributedTableName));+ Assertions.assertEquals(+ ENGINE.DISTRIBUTED.getValue(), sqlDistributedTable.properties().get(GRAVITINO_ENGINE_KEY));+ Assertions.assertEquals("false", sqlDistributedTable.properties().get(ON_CLUSTER));+ Assertions.assertEquals(+ ClickHouseContainer.DEFAULT_CLUSTER_NAME,+ sqlDistributedTable.properties().get(CLUSTER_NAME));+ Assertions.assertEquals(schemaName, sqlDistributedTable.properties().get(REMOTE_DATABASE));+ Assertions.assertEquals(+ sqlClusterLocalTableName, sqlDistributedTable.properties().get(REMOTE_TABLE));++ Table sqlNonClusterDistributedTable =+ tableCatalog.loadTable(NameIdentifier.of(schemaName, sqlNonClusterDistributedTableName));+ Assertions.assertEquals(+ ENGINE.DISTRIBUTED.getValue(),+ sqlNonClusterDistributedTable.properties().get(GRAVITINO_ENGINE_KEY));+ Assertions.assertEquals("false", sqlNonClusterDistributedTable.properties().get(ON_CLUSTER));+ Assertions.assertEquals(+ ClickHouseContainer.DEFAULT_CLUSTER_NAME,+ sqlNonClusterDistributedTable.properties().get(CLUSTER_NAME));+ Assertions.assertEquals(+ schemaName, sqlNonClusterDistributedTable.properties().get(REMOTE_DATABASE));+ Assertions.assertEquals(+ sqlNonClusterLocalTableName, sqlNonClusterDistributedTable.properties().get(REMOTE_TABLE));+ }+}diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/CatalogClickHouseIT.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/CatalogClickHouseIT.javanew file mode 100644index 0000000000..6afda5c453--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/CatalogClickHouseIT.java@@ -0,0 +1,1873 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.clickhouse.integration.test;++import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE.MERGETREE;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.GRAVITINO_ENGINE_KEY;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseUtils.getSortOrders;+import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;+import static org.junit.jupiter.api.Assertions.assertThrows;++import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Maps;+import com.google.common.collect.Sets;+import java.io.IOException;+import java.sql.SQLException;+import java.time.LocalDate;+import java.util.Arrays;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+import java.util.Objects;+import java.util.Set;+import java.util.stream.Collectors;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.CatalogChange;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.Schema;+import org.apache.gravitino.SupportsSchemas;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.catalog.clickhouse.integration.test.service.ClickHouseService;+import org.apache.gravitino.catalog.jdbc.config.JdbcConfig;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.integration.test.container.ClickHouseContainer;+import org.apache.gravitino.integration.test.container.ContainerSuite;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.gravitino.integration.test.util.ITUtils;+import org.apache.gravitino.integration.test.util.TestDatabaseName;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableCatalog;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.FunctionExpression;+import org.apache.gravitino.rel.expressions.FunctionExpression.FuncExpressionImpl;+import org.apache.gravitino.rel.expressions.NamedReference;+import org.apache.gravitino.rel.expressions.UnparsedExpression;+import org.apache.gravitino.rel.expressions.distributions.Distribution;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.expressions.sorts.SortDirection;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.sorts.SortOrders;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.indexes.Index;+import org.apache.gravitino.rel.indexes.Indexes;+import org.apache.gravitino.rel.types.Decimal;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.utils.RandomNameUtils;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.api.TestInstance.Lifecycle;+import org.junit.jupiter.api.condition.EnabledIf;++@Tag("gravitino-docker-test")+@TestInstance(Lifecycle.PER_CLASS)+public class CatalogClickHouseIT extends BaseIT {+ private static final ContainerSuite containerSuite = ContainerSuite.getInstance();+ private static final String provider = "jdbc-clickhouse";++ public String metalakeName = GravitinoITUtils.genRandomName("clickhouse_it_metalake");+ public String catalogName = GravitinoITUtils.genRandomName("clickhouse_it_catalog");+ public String schemaName = GravitinoITUtils.genRandomName("clickhouse_it_schema");+ public String tableName = GravitinoITUtils.genRandomName("clickhouse_it_table");+ public String alertTableName = "alert_table_name";+ public String table_comment = "table_comment";++ public String schema_comment = "test schema";+ public String CLICKHOUSE_COL_NAME1 = "clickhouse_col_name1";+ public String CLICKHOUSE_COL_NAME2 = "clickhouse_col_name2";+ public String CLICKHOUSE_COL_NAME3 = "clickhouse_col_name3";+ public String CLICKHOUSE_COL_NAME4 = "clickhouse_col_name4";+ public String CLICKHOUSE_COL_NAME5 = "clickhouse_col_name5";++ private GravitinoMetalake metalake;++ protected Catalog catalog;++ private ClickHouseService clickhouseService;++ private ClickHouseContainer CLICKHOUSE_CONTAINER;++ private TestDatabaseName TEST_DB_NAME;++ boolean supportColumnDefaultValueExpression() {+ return true;+ }++ @BeforeAll+ public void startup() throws IOException, SQLException {+ TEST_DB_NAME = TestDatabaseName.CLICKHOUSE_CATALOG_CLICKHOUSE_IT;++ containerSuite.startClickHouseContainer(TEST_DB_NAME);+ CLICKHOUSE_CONTAINER = containerSuite.getClickHouseContainer();++ clickhouseService = new ClickHouseService(CLICKHOUSE_CONTAINER, TEST_DB_NAME);+ createMetalake();+ createCatalog();+ createSchema();+ }++ @AfterAll+ public void stop() {+ clearTableAndSchema();+ metalake.disableCatalog(catalogName);+ metalake.dropCatalog(catalogName, true);+ client.disableMetalake(metalakeName);+ client.dropMetalake(metalakeName, true);+ clickhouseService.close();+ }++ @AfterEach+ public void resetSchema() {+ clearTableAndSchema();+ createSchema();+ }++ private void clearTableAndSchema() {+ NameIdentifier[] nameIdentifiers =+ catalog.asTableCatalog().listTables(Namespace.of(schemaName));+ for (NameIdentifier nameIdentifier : nameIdentifiers) {+ catalog.asTableCatalog().dropTable(nameIdentifier);+ }+ catalog.asSchemas().dropSchema(schemaName, false);+ }++ private void createMetalake() {+ GravitinoMetalake[] gravitinoMetalakes = client.listMetalakes();+ Assertions.assertEquals(0, gravitinoMetalakes.length);++ client.createMetalake(metalakeName, "comment", Collections.emptyMap());+ GravitinoMetalake loadMetalake = client.loadMetalake(metalakeName);+ Assertions.assertEquals(metalakeName, loadMetalake.name());++ metalake = loadMetalake;+ }++ private void createCatalog() throws SQLException {+ Map<String, String> catalogProperties = Maps.newHashMap();++ catalogProperties.put(+ JdbcConfig.JDBC_URL.getKey(),+ StringUtils.substring(+ CLICKHOUSE_CONTAINER.getJdbcUrl(TEST_DB_NAME),+ 0,+ CLICKHOUSE_CONTAINER.getJdbcUrl(TEST_DB_NAME).lastIndexOf("/")));+ catalogProperties.put(+ JdbcConfig.JDBC_DRIVER.getKey(), CLICKHOUSE_CONTAINER.getDriverClassName(TEST_DB_NAME));+ catalogProperties.put(JdbcConfig.USERNAME.getKey(), CLICKHOUSE_CONTAINER.getUsername());+ catalogProperties.put(JdbcConfig.PASSWORD.getKey(), CLICKHOUSE_CONTAINER.getPassword());++ Catalog createdCatalog =+ metalake.createCatalog(+ catalogName, Catalog.Type.RELATIONAL, provider, "comment", catalogProperties);+ Catalog loadCatalog = metalake.loadCatalog(catalogName);+ Assertions.assertEquals(createdCatalog, loadCatalog);++ catalog = loadCatalog;+ }++ private void createSchema() {+ Map<String, String> prop = Maps.newHashMap();+ Schema createdSchema = null;+ try {+ createdSchema = catalog.asSchemas().createSchema(schemaName, schema_comment, prop);+ } catch (Exception ex) {+ throw new RuntimeException("Create schema failed: " + ex.getMessage(), ex);+ }++ Schema loadSchema = catalog.asSchemas().loadSchema(schemaName);+ Assertions.assertEquals(createdSchema.name(), loadSchema.name());+ prop.forEach((key, value) -> Assertions.assertEquals(loadSchema.properties().get(key), value));+ }++ private Column[] createColumns() {+ Column col1 = Column.of(CLICKHOUSE_COL_NAME1, Types.IntegerType.get(), "col_1_comment");+ Column col2 = Column.of(CLICKHOUSE_COL_NAME2, Types.DateType.get(), "col_2_comment");+ Column col3 =+ Column.of(+ CLICKHOUSE_COL_NAME3,+ Types.StringType.get(),+ "col_3_comment",+ false,+ false,+ DEFAULT_VALUE_NOT_SET);++ return new Column[] {col1, col2, col3};+ }++ private Column[] createColumnsWithDefaultValue() {+ return new Column[] {+ Column.of(+ CLICKHOUSE_COL_NAME1,+ Types.FloatType.get(),+ "col_1_comment",+ false,+ false,+ Literals.of("1.23", Types.FloatType.get())),+ Column.of(+ CLICKHOUSE_COL_NAME2,+ Types.TimestampType.withoutTimeZone(),+ "col_2_comment",+ false,+ false,+ FunctionExpression.of("now")),+ Column.of(+ CLICKHOUSE_COL_NAME3,+ Types.VarCharType.of(255),+ "col_3_comment",+ true,+ false,+ Literals.NULL),+ Column.of(+ CLICKHOUSE_COL_NAME4,+ Types.IntegerType.get(),+ "col_4_comment",+ false,+ false,+ Literals.of("1000", Types.IntegerType.get())),+ Column.of(+ CLICKHOUSE_COL_NAME5,+ Types.DecimalType.of(3, 2),+ "col_5_comment",+ true,+ false,+ Literals.of("1.23", Types.DecimalType.of(3, 2)))+ };+ }++ private Map<String, String> createProperties() {+ Map<String, String> properties = Maps.newHashMap();+ properties.put(GRAVITINO_ENGINE_KEY, MERGETREE.getValue());+ return properties;+ }++ @Test+ void testOperationClickhouseSchema() {+ SupportsSchemas schemas = catalog.asSchemas();+ Namespace namespace = Namespace.of(metalakeName, catalogName);+ // list schema check.+ String[] nameIdentifiers = schemas.listSchemas();+ Set<String> schemaNames = Sets.newHashSet(nameIdentifiers);+ Assertions.assertTrue(schemaNames.contains(schemaName));++ NameIdentifier[] clickhouseNamespaces = clickhouseService.listSchemas(namespace);+ schemaNames =+ Arrays.stream(clickhouseNamespaces).map(NameIdentifier::name).collect(Collectors.toSet());+ Assertions.assertTrue(schemaNames.contains(schemaName));++ // create schema check.+ String testSchemaName = GravitinoITUtils.genRandomName("test_schema_1");+ NameIdentifier schemaIdent = NameIdentifier.of(metalakeName, catalogName, testSchemaName);+ schemas.createSchema(testSchemaName, schema_comment, Collections.emptyMap());+ nameIdentifiers = schemas.listSchemas();+ schemaNames = Sets.newHashSet(nameIdentifiers);+ Assertions.assertTrue(schemaNames.contains(testSchemaName));++ clickhouseNamespaces = clickhouseService.listSchemas(namespace);+ schemaNames =+ Arrays.stream(clickhouseNamespaces).map(NameIdentifier::name).collect(Collectors.toSet());+ Assertions.assertTrue(schemaNames.contains(testSchemaName));++ Map<String, String> emptyMap = Collections.emptyMap();+ Assertions.assertThrows(+ RuntimeException.class,+ () -> {+ schemas.createSchema(testSchemaName, schema_comment, emptyMap);+ });++ // drop schema check.+ schemas.dropSchema(testSchemaName, false);+ Assertions.assertThrows(NoSuchSchemaException.class, () -> schemas.loadSchema(testSchemaName));+ Assertions.assertThrows(+ NoSuchSchemaException.class, () -> clickhouseService.loadSchema(schemaIdent));++ nameIdentifiers = schemas.listSchemas();+ schemaNames = Sets.newHashSet(nameIdentifiers);+ Assertions.assertFalse(schemaNames.contains(testSchemaName));+ Assertions.assertFalse(schemas.dropSchema("no-exits", false));+ TableCatalog tableCatalog = catalog.asTableCatalog();++ // create failed check.+ NameIdentifier table = NameIdentifier.of(testSchemaName, "test_table");+ Assertions.assertThrows(+ NotFoundException.class,+ () ->+ tableCatalog.createTable(+ table,+ createColumns(),+ table_comment,+ createProperties(),+ null,+ Distributions.NONE,+ getSortOrders(CLICKHOUSE_COL_NAME3)));+ // drop schema failed check.+ Assertions.assertFalse(schemas.dropSchema(schemaIdent.name(), true));+ Assertions.assertFalse(schemas.dropSchema(schemaIdent.name(), false));+ Assertions.assertFalse(() -> tableCatalog.dropTable(table));+ clickhouseNamespaces = clickhouseService.listSchemas(Namespace.empty());+ schemaNames =+ Arrays.stream(clickhouseNamespaces).map(NameIdentifier::name).collect(Collectors.toSet());+ Assertions.assertTrue(schemaNames.contains(schemaName));+ }++ @Test+ void testCreateAndLoadClickhouseTable() {+ // Create table from Gravitino API+ Column[] columns = createColumns();++ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, tableName);+ Distribution distribution = Distributions.NONE;++ Transform[] partitioning = Transforms.EMPTY_TRANSFORM;++ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ partitioning,+ distribution,+ getSortOrders(CLICKHOUSE_COL_NAME3));++ Table loadTable = tableCatalog.loadTable(tableIdentifier);+ Assertions.assertEquals(tableName, loadTable.name());+ Assertions.assertEquals(table_comment, loadTable.comment());+ Map<String, String> resultProp = loadTable.properties();+ for (Map.Entry<String, String> entry : properties.entrySet()) {+ Assertions.assertTrue(resultProp.containsKey(entry.getKey()));+ Assertions.assertEquals(entry.getValue(), resultProp.get(entry.getKey()));+ }+ Assertions.assertEquals(loadTable.columns().length, columns.length);+ for (int i = 0; i < columns.length; i++) {+ ITUtils.assertColumn(columns[i], loadTable.columns()[i]);+ }+ }++ @Test+ void testCreateTableWithComplexOrderBy() {+ Column[] columns =+ new Column[] {+ Column.of(+ CLICKHOUSE_COL_NAME1,+ Types.IntegerType.get(),+ "col_1_comment",+ false,+ false,+ DEFAULT_VALUE_NOT_SET),+ Column.of(+ CLICKHOUSE_COL_NAME2,+ Types.DateType.get(),+ "col_2_comment",+ false,+ false,+ DEFAULT_VALUE_NOT_SET),+ Column.of(+ CLICKHOUSE_COL_NAME3,+ Types.StringType.get(),+ "col_3_comment",+ false,+ false,+ DEFAULT_VALUE_NOT_SET)+ };+ String name = GravitinoITUtils.genRandomName("order_by_table");+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, name);+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ SortOrder[] sortOrders =+ new SortOrder[] {+ SortOrders.of(NamedReference.field("clickhouse_col_name1"), SortDirection.ASCENDING),+ SortOrders.of(+ FunctionExpression.of("toDate", NamedReference.field("clickhouse_col_name2")),+ SortDirection.ASCENDING)+ };++ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ sortOrders);+ Table loaded = tableCatalog.loadTable(tableIdentifier);+ Assertions.assertEquals(2, loaded.sortOrder().length);+ Assertions.assertTrue(loaded.sortOrder()[0].expression() instanceof NamedReference);+ Assertions.assertTrue(loaded.sortOrder()[1].expression() instanceof FuncExpressionImpl);+ }++ @Test+ void testLoadTableFromShowCreateParsing() {+ String name = GravitinoITUtils.genRandomName("show_create_table");+ clickhouseService.executeQuery(+ String.format(+ "CREATE TABLE `%s`.`%s` (\n"+ + " `id` UInt64,\n"+ + " `event_time` DateTime,\n"+ + " `user_id` UInt64,\n"+ + " `region` String,\n"+ + " `amount` Float64,\n"+ + " PRIMARY KEY user_id,\n"+ + " INDEX idx_amount amount TYPE minmax GRANULARITY 1\n"+ + ")\n"+ + "ENGINE = MergeTree\n"+ + "PARTITION BY toYYYYMM(event_time)\n"+ + "ORDER BY (user_id, toYYYYMM(event_time), region)",+ schemaName, name));++ Table loaded = catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, name));+ SortOrder[] sortOrders = loaded.sortOrder();+ Assertions.assertEquals(3, sortOrders.length);+ Assertions.assertTrue(sortOrders[0].expression() instanceof NamedReference);+ Assertions.assertArrayEquals(+ new String[] {"user_id"}, ((NamedReference) sortOrders[0].expression()).fieldName());+ Assertions.assertTrue(sortOrders[1].expression() instanceof FuncExpressionImpl);++ Assertions.assertEquals(+ FunctionExpression.of("toYYYYMM", NamedReference.field("event_time")),+ sortOrders[1].expression());+ Assertions.assertTrue(sortOrders[2].expression() instanceof NamedReference);+ Assertions.assertArrayEquals(+ new String[] {"region"}, ((NamedReference) sortOrders[2].expression()).fieldName());++ Transform[] partitioning = loaded.partitioning();+ Assertions.assertEquals(1, partitioning.length);+ Assertions.assertEquals(Transforms.NAME_OF_MONTH, partitioning[0].name());+ Assertions.assertArrayEquals(+ new String[] {"event_time"}, ((NamedReference) partitioning[0].arguments()[0]).fieldName());++ Index[] indexes = loaded.index();+ Assertions.assertTrue(+ Arrays.stream(indexes)+ .anyMatch(+ idx ->+ idx.type() == Index.IndexType.PRIMARY_KEY+ && Arrays.deepEquals(idx.fieldNames(), new String[][] {{"user_id"}})));+ Assertions.assertTrue(+ Arrays.stream(indexes)+ .anyMatch(+ idx ->+ idx.type() == Index.IndexType.DATA_SKIPPING_MINMAX+ && Arrays.deepEquals(idx.fieldNames(), new String[][] {{"amount"}})));+ }++ @Test+ void testCreateAndLoadWithPartitionSortAndIndexes() {+ String table = GravitinoITUtils.genRandomName("meta_roundtrip");+ NameIdentifier ident = NameIdentifier.of(schemaName, table);+ Column[] cols =+ new Column[] {+ Column.of("id", Types.LongType.get(), "id"),+ Column.of(+ "event_time",+ Types.TimestampType.withoutTimeZone(),+ "ts",+ false,+ false,+ DEFAULT_VALUE_NOT_SET),+ Column.of("user_id", Types.LongType.get(), "user", false, false, DEFAULT_VALUE_NOT_SET),+ Column.of("amount", Types.FloatType.get(), "amt")+ };++ Transform[] partitioning = new Transform[] {Transforms.identity("event_time")};+ SortOrder[] sortOrders =+ new SortOrder[] {+ SortOrders.of(NamedReference.field("user_id"), SortDirection.ASCENDING),+ SortOrders.of(+ FunctionExpression.of("toDate", NamedReference.field("event_time")),+ SortDirection.ASCENDING)+ };+ Index[] indexes =+ new Index[] {+ Indexes.primary(Indexes.DEFAULT_PRIMARY_KEY_NAME, new String[][] {{"user_id"}}),+ Indexes.of(+ Index.IndexType.DATA_SKIPPING_MINMAX, "idx_amount", new String[][] {{"amount"}})+ };++ catalog+ .asTableCatalog()+ .createTable(+ ident,+ cols,+ "roundtrip meta",+ createProperties(),+ partitioning,+ Distributions.NONE,+ sortOrders,+ indexes);++ Table loaded = catalog.asTableCatalog().loadTable(ident);+ Assertions.assertEquals(1, loaded.partitioning().length);+ Assertions.assertEquals(+ "event_time", ((NamedReference) loaded.partitioning()[0].arguments()[0]).fieldName()[0]);++ Assertions.assertEquals(2, loaded.sortOrder().length);+ Assertions.assertTrue(loaded.sortOrder()[0].expression() instanceof NamedReference);+ Assertions.assertEquals(+ "user_id", ((NamedReference) loaded.sortOrder()[0].expression()).fieldName()[0]);++ Assertions.assertTrue(loaded.sortOrder()[1].expression() instanceof FuncExpressionImpl);+ Assertions.assertEquals(+ "toDate", ((FuncExpressionImpl) loaded.sortOrder()[1].expression()).functionName());+ Assertions.assertEquals(+ 1, ((FuncExpressionImpl) loaded.sortOrder()[1].expression()).arguments().length);++ Index[] loadedIndexes = loaded.index();+ Assertions.assertTrue(+ Arrays.stream(loadedIndexes)+ .anyMatch(+ idx ->+ idx.type() == Index.IndexType.PRIMARY_KEY+ && Arrays.deepEquals(idx.fieldNames(), new String[][] {{"user_id"}})));+ Assertions.assertTrue(+ Arrays.stream(loadedIndexes)+ .anyMatch(+ idx ->+ idx.type() == Index.IndexType.DATA_SKIPPING_MINMAX+ && Arrays.deepEquals(idx.fieldNames(), new String[][] {{"amount"}})));+ }++ @Test+ void testColumnNameWithKeyWords() {+ // Create table from Gravitino API+ Column[] columns = {+ Column.of("integer", Types.IntegerType.get(), "integer", false, false, DEFAULT_VALUE_NOT_SET),+ Column.of("long", Types.LongType.get(), "long"),+ Column.of("float", Types.FloatType.get(), "float"),+ Column.of("double", Types.DoubleType.get(), "double"),+ Column.of("decimal", Types.DecimalType.of(10, 3), "decimal"),+ Column.of("date", Types.DateType.get(), "date"),+ Column.of("time", Types.TimeType.get(), "time")+ };++ String name = GravitinoITUtils.genRandomName("table") + "_keyword";+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, name);+ Distribution distribution = Distributions.NONE;++ Transform[] partitioning = Transforms.EMPTY_TRANSFORM;++ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ Table createdTable =+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ partitioning,+ distribution,+ getSortOrders("integer"));+ Assertions.assertEquals(createdTable.name(), name);+ }++ @Test+ // ClickHouse support column default value expression after 8.0.13+ // see https://dev.clickhouse.com/doc/refman/8.0/en/data-type-defaults.html+ @EnabledIf("supportColumnDefaultValueExpression")+ void testColumnDefaultValue() {+ Column col1 =+ Column.of(+ CLICKHOUSE_COL_NAME1,+ Types.IntegerType.get(),+ "col_1_comment",+ false,+ false,+ FunctionExpression.of("rand"));+ Column col2 =+ Column.of(+ CLICKHOUSE_COL_NAME2,+ Types.TimestampType.withoutTimeZone(),+ "col_2_comment",+ false,+ false,+ FunctionExpression.of("now"));+ Column col3 =+ Column.of(+ CLICKHOUSE_COL_NAME3,+ Types.VarCharType.of(255),+ "col_3_comment",+ true,+ false,+ Literals.NULL);+ Column col4 =+ Column.of(+ CLICKHOUSE_COL_NAME4, Types.StringType.get(), "col_4_comment", false, false, null);+ Column col5 =+ Column.of(+ CLICKHOUSE_COL_NAME5,+ Types.VarCharType.of(255),+ "col_5_comment",+ true,+ false,+ Literals.stringLiteral("now()"));++ Column[] newColumns = new Column[] {col1, col2, col3, col4, col5};++ NameIdentifier tableIdent =+ NameIdentifier.of(schemaName, GravitinoITUtils.genRandomName("clickhouse_it_table"));+ catalog+ .asTableCatalog()+ .createTable(+ tableIdent,+ newColumns,+ null,+ ImmutableMap.of(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(CLICKHOUSE_COL_NAME1));+ Table createdTable = catalog.asTableCatalog().loadTable(tableIdent);+ Assertions.assertEquals(+ UnparsedExpression.of("rand()"), createdTable.columns()[0].defaultValue());+ Assertions.assertEquals(+ UnparsedExpression.of("now()"), createdTable.columns()[1].defaultValue());+ Assertions.assertEquals(Literals.NULL, createdTable.columns()[2].defaultValue());+ Assertions.assertEquals(DEFAULT_VALUE_NOT_SET, createdTable.columns()[3].defaultValue());+ Assertions.assertEquals(+ Literals.stringLiteral("now()"), createdTable.columns()[4].defaultValue());+ }++ @Test+ // see https://dev.clickhouse.com/doc/refman/8.0/en/data-type-defaults.html+ @EnabledIf("supportColumnDefaultValueExpression")+ void testColumnDefaultValueConverter() {+ // test convert from ClickHouse to Gravitino+ String tableName = GravitinoITUtils.genRandomName("test_default_value");+ String fullTableName = schemaName + "." + tableName;+ String sql =+ "CREATE TABLE "+ + fullTableName+ + " (\n"+ + " int_col_1 int default 0x01AF,\n"+ + " int_col_2 int default (rand()),\n"+ + " int_col_3 int default 3,\n"+ + " unsigned_int_col_1 INT UNSIGNED default 1,\n"+ + " unsigned_bigint_col_1 BIGINT(20) UNSIGNED default 0,\n"+ + " double_col_1 double default 123.45,\n"+ + " varchar20_col_1 varchar(20) default '10',\n"+ + " varchar100_col_1 varchar(100) default 'now()',\n"+ + " varchar200_col_1 varchar(200) default 'curdate()',\n"+ + " varchar200_col_2 varchar(200) default (today()),\n"+ + " varchar200_col_3 varchar(200) default (now()),\n"+ + " datetime_col_1 datetime default now(),\n"+ + " datetime_col_2 datetime default now(),\n"+ + " datetime_col_3 datetime default null,\n"+ + " datetime_col_4 datetime default 19830905,\n"+ + " date_col_1 date default (today()),\n"+ + " date_col_2 date,\n"+ + " date_col_3 date DEFAULT (today() + INTERVAL 1 YEAR),\n"+ + " date_col_4 date DEFAULT (today()),\n"+ + " date_col_5 date DEFAULT '2024-04-01',\n"+ + " timestamp_col_1 timestamp default '2012-12-31 11:30:45',\n"+ + " timestamp_col_2 timestamp default 19830905,\n"+ + " timestamp_col_3 timestamp(6) default now(),\n"+ + " decimal_6_2_col_1 decimal(6, 2) default 1.2,\n"+ + " bit_col_1 bit default '1'\n"+ + ") order by int_col_1;\n";++ clickhouseService.executeQuery(sql);+ Table loadedTable =+ catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, tableName));++ for (Column column : loadedTable.columns()) {+ // try {+ switch (column.name()) {+ case "int_col_1":+ Assertions.assertEquals(Literals.integerLiteral(431), column.defaultValue());+ break;+ case "int_col_2":+ Assertions.assertEquals(UnparsedExpression.of("rand()"), column.defaultValue());+ break;+ case "int_col_3":+ Assertions.assertEquals(Literals.integerLiteral(3), column.defaultValue());+ break;+ case "unsigned_int_col_1":+ Assertions.assertEquals(Literals.unsignedIntegerLiteral(1L), column.defaultValue());+ break;+ case "unsigned_bigint_col_1":+ Assertions.assertEquals(+ Literals.unsignedLongLiteral(Decimal.of("0")), column.defaultValue());+ break;+ case "double_col_1":+ Assertions.assertEquals(Literals.doubleLiteral(123.45), column.defaultValue());+ break;+ case "varchar20_col_1":+ Assertions.assertEquals(Literals.stringLiteral("10"), column.defaultValue());+ break;+ case "varchar100_col_1":+ Assertions.assertEquals(Literals.stringLiteral("now()"), column.defaultValue());+ break;+ case "varchar200_col_1":+ Assertions.assertEquals(Literals.stringLiteral("curdate()"), column.defaultValue());+ break;+ case "varchar200_col_2":+ Assertions.assertEquals(Literals.stringLiteral("today()"), column.defaultValue());+ break;+ case "varchar200_col_3":+ Assertions.assertEquals(Literals.stringLiteral("now()"), column.defaultValue());+ break;+ case "datetime_col_1":+ case "datetime_col_2":+ Assertions.assertEquals(UnparsedExpression.of("now()"), column.defaultValue());+ break;+ case "datetime_col_3":+ Assertions.assertEquals(Literals.NULL, column.defaultValue());+ break;+ case "datetime_col_4":+ Assertions.assertEquals(UnparsedExpression.of("19830905"), column.defaultValue());+ break;+ case "date_col_1":+ Assertions.assertEquals(UnparsedExpression.of("today()"), column.defaultValue());+ break;+ case "date_col_2":+ Assertions.assertEquals(DEFAULT_VALUE_NOT_SET, column.defaultValue());+ break;+ case "date_col_3":+ Assertions.assertEquals(+ UnparsedExpression.of("today() + toIntervalYear(1)"), column.defaultValue());+ break;+ case "date_col_4":+ Assertions.assertEquals(UnparsedExpression.of("today()"), column.defaultValue());+ break;+ case "date_col_5":+ Assertions.assertEquals(+ Literals.dateLiteral(LocalDate.of(2024, 4, 1)), column.defaultValue());+ break;+ case "timestamp_col_1":+ Assertions.assertEquals(+ Literals.timestampLiteral("2012-12-31T11:30:45"), column.defaultValue());+ break;+ case "timestamp_col_2":+ Assertions.assertEquals(UnparsedExpression.of("19830905"), column.defaultValue());+ break;+ case "timestamp_col_3":+ Assertions.assertEquals(UnparsedExpression.of("now()"), column.defaultValue());+ break;+ case "decimal_6_2_col_1":+ Assertions.assertEquals(+ Literals.decimalLiteral(Decimal.of("1.2", 6, 2)), column.defaultValue());+ break;+ case "bit_col_1":+ Assertions.assertEquals(+ Literals.unsignedLongLiteral(Decimal.of("1")), column.defaultValue());+ break;+ default:+ Assertions.fail(+ "Unexpected column name: "+ + column.name()+ + ", default value: "+ + column.defaultValue());+ }+ }+ }++ @Test+ void testColumnTypeConverter() {+ // test convert from ClickHouse to Gravitino+ String tableName = GravitinoITUtils.genRandomName("test_type_converter");+ String fullTableName = schemaName + "." + tableName;+ String sql =+ "CREATE TABLE "+ + fullTableName+ + " (\n"+ + " tinyint_col tinyint,\n"+ + " smallint_col smallint,\n"+ + " int_col int,\n"+ + " bigint_col bigint,\n"+ + " float_col float,\n"+ + " double_col double,\n"+ + " date_col date,\n"+ + " time_col time,\n"+ + " timestamp_col timestamp,\n"+ + " datetime_col datetime,\n"+ + " decimal_6_2_col decimal(6, 2),\n"+ + " varchar20_col varchar(20),\n"+ + " text_col text,\n"+ + " blob_col blob\n"+ + ") order by tinyint_col;\n";++ clickhouseService.executeQuery(sql);+ Table loadedTable =+ catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, tableName));++ for (Column column : loadedTable.columns()) {+ switch (column.name()) {+ case "tinyint_col":+ Assertions.assertEquals(Types.ByteType.get(), column.dataType());+ break;+ case "smallint_col":+ Assertions.assertEquals(Types.ShortType.get(), column.dataType());+ break;+ case "int_col":+ Assertions.assertEquals(Types.IntegerType.get(), column.dataType());+ break;+ case "bigint_col":+ Assertions.assertEquals(Types.LongType.get(), column.dataType());+ break;+ case "float_col":+ Assertions.assertEquals(Types.FloatType.get(), column.dataType());+ break;+ case "double_col":+ Assertions.assertEquals(Types.DoubleType.get(), column.dataType());+ break;+ case "date_col":+ Assertions.assertEquals(Types.DateType.get(), column.dataType());+ break;+ case "time_col":+ Assertions.assertEquals(Types.LongType.get(), column.dataType());+ break;+ case "timestamp_col":+ Assertions.assertEquals(Types.TimestampType.withoutTimeZone(0), column.dataType());+ break;+ case "datetime_col":+ Assertions.assertEquals(Types.TimestampType.withoutTimeZone(0), column.dataType());+ break;+ case "decimal_6_2_col":+ Assertions.assertEquals(Types.DecimalType.of(6, 2), column.dataType());+ break;+ case "varchar20_col":+ Assertions.assertEquals(Types.StringType.get(), column.dataType());+ break;+ case "text_col":+ Assertions.assertEquals(Types.StringType.get(), column.dataType());+ break;+ case "binary_col":+ Assertions.assertEquals(Types.BinaryType.get(), column.dataType());+ break;+ case "blob_col":+ Assertions.assertEquals(Types.StringType.get(), column.dataType());+ break;+ default:+ Assertions.fail("Unexpected column name: " + column.name());+ }+ }+ }++ @Test+ void testAlterAndDropClickhouseTable() {+ Column[] columns = createColumns();+ catalog+ .asTableCatalog()+ .createTable(+ NameIdentifier.of(schemaName, tableName),+ columns,+ table_comment,+ createProperties(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(CLICKHOUSE_COL_NAME3));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.rename(alertTableName),+ TableChange.updateComment(table_comment + "_new"));+ });++ catalog+ .asTableCatalog()+ .alterTable(NameIdentifier.of(schemaName, tableName), TableChange.rename(alertTableName));++ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, alertTableName),+ TableChange.updateComment(table_comment + "_new"));++ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, alertTableName),+ TableChange.addColumn(new String[] {"col_4"}, Types.StringType.get()));++ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, alertTableName),+ TableChange.renameColumn(new String[] {CLICKHOUSE_COL_NAME2}, "col_2_new"));++ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, alertTableName),+ TableChange.updateColumnType(+ new String[] {CLICKHOUSE_COL_NAME1}, Types.IntegerType.get()));++ Table table = catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, alertTableName));+ Assertions.assertEquals(alertTableName, table.name());++ Assertions.assertEquals(CLICKHOUSE_COL_NAME1, table.columns()[0].name());+ Assertions.assertEquals(Types.IntegerType.get(), table.columns()[0].dataType());++ Assertions.assertEquals("col_2_new", table.columns()[1].name());+ Assertions.assertEquals(Types.DateType.get(), table.columns()[1].dataType());+ Assertions.assertEquals("col_2_comment", table.columns()[1].comment());++ Assertions.assertEquals(CLICKHOUSE_COL_NAME3, table.columns()[2].name());+ Assertions.assertEquals(Types.StringType.get(), table.columns()[2].dataType());+ Assertions.assertEquals("col_3_comment", table.columns()[2].comment());++ Assertions.assertEquals("col_4", table.columns()[3].name());+ Assertions.assertEquals(Types.StringType.get(), table.columns()[3].dataType());+ Assertions.assertNull(table.columns()[3].comment());+ Assertions.assertNotNull(table.auditInfo());+ Assertions.assertNotNull(table.auditInfo().createTime());+ Assertions.assertNotNull(table.auditInfo().creator());+ Assertions.assertNotNull(table.auditInfo().lastModifiedTime());+ Assertions.assertNotNull(table.auditInfo().lastModifier());++ Column col1 =+ Column.of("name", Types.StringType.get(), "comment", false, false, DEFAULT_VALUE_NOT_SET);+ Column col2 = Column.of("address", Types.StringType.get(), "comment");+ Column col3 = Column.of("date_of_birth", Types.DateType.get(), "comment");++ Column[] newColumns = new Column[] {col1, col2, col3};+ NameIdentifier tableIdentifier =+ NameIdentifier.of(schemaName, GravitinoITUtils.genRandomName("CatalogJdbcIT_table"));+ catalog+ .asTableCatalog()+ .createTable(+ tableIdentifier,+ newColumns,+ table_comment,+ ImmutableMap.of(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("name"));++ TableCatalog tableCatalog = catalog.asTableCatalog();+ TableChange change =+ TableChange.updateColumnPosition(+ new String[] {"no_column"}, TableChange.ColumnPosition.first());+ NotFoundException notFoundException =+ assertThrows(+ NotFoundException.class, () -> tableCatalog.alterTable(tableIdentifier, change));+ Assertions.assertTrue(notFoundException.getMessage().contains("no_column"));++ catalog+ .asTableCatalog()+ .alterTable(+ tableIdentifier,+ TableChange.updateColumnPosition(+ new String[] {col1.name()}, TableChange.ColumnPosition.after(col2.name())));++ Table updateColumnPositionTable = catalog.asTableCatalog().loadTable(tableIdentifier);++ Column[] updateCols = updateColumnPositionTable.columns();+ Assertions.assertEquals(3, updateCols.length);+ Assertions.assertEquals(col2.name(), updateCols[0].name());+ Assertions.assertEquals(col1.name(), updateCols[1].name());+ Assertions.assertEquals(col3.name(), updateCols[2].name());++ Assertions.assertDoesNotThrow(+ () ->+ catalog+ .asTableCatalog()+ .alterTable(+ tableIdentifier,+ TableChange.deleteColumn(new String[] {col3.name()}, true),+ TableChange.deleteColumn(new String[] {col2.name()}, true)));+ Table delColTable = catalog.asTableCatalog().loadTable(tableIdentifier);+ Assertions.assertEquals(1, delColTable.columns().length);+ Assertions.assertEquals(col1.name(), delColTable.columns()[0].name());++ Assertions.assertDoesNotThrow(+ () -> {+ catalog.asTableCatalog().dropTable(tableIdentifier);+ });+ }++ @Test+ void testRecreateSchemaAndTable() {+ TableCatalog tableCatalog = catalog.asTableCatalog();+ Column[] columns = createColumns();+ String recreateTableName = GravitinoITUtils.genRandomName("recreate_table");+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, recreateTableName);++ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ createProperties(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(CLICKHOUSE_COL_NAME3));++ String updatedComment = table_comment + "_updated";+ tableCatalog.alterTable(tableIdentifier, TableChange.updateComment(updatedComment));++ Table loadedTable = tableCatalog.loadTable(tableIdentifier);+ Assertions.assertEquals(recreateTableName, loadedTable.name());+ Assertions.assertEquals(updatedComment, loadedTable.comment());++ Assertions.assertTrue(tableCatalog.dropTable(tableIdentifier));+ Assertions.assertFalse(tableCatalog.tableExists(tableIdentifier));++ String recreatedComment = table_comment + "_recreated";+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ recreatedComment,+ createProperties(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(CLICKHOUSE_COL_NAME3));++ Table recreatedTable = tableCatalog.loadTable(tableIdentifier);+ Assertions.assertEquals(recreateTableName, recreatedTable.name());+ Assertions.assertEquals(recreatedComment, recreatedTable.comment());+ Assertions.assertEquals(columns.length, recreatedTable.columns().length);++ SupportsSchemas schemaSupport = catalog.asSchemas();+ String recreateSchemaName = GravitinoITUtils.genRandomName("recreate_schema");+ Map<String, String> schemaProperties = ImmutableMap.of();++ schemaSupport.createSchema(recreateSchemaName, schema_comment, schemaProperties);++ Assertions.assertTrue(schemaSupport.dropSchema(recreateSchemaName, true));+ Assertions.assertFalse(schemaSupport.schemaExists(recreateSchemaName));++ schemaSupport.createSchema(recreateSchemaName, schema_comment, schemaProperties);+ schemaSupport.loadSchema(recreateSchemaName);++ schemaSupport.dropSchema(recreateSchemaName, true);+ tableCatalog.dropTable(tableIdentifier);+ }++ @Test+ void testUpdateColumnDefaultValue() {+ Column[] columns = createColumnsWithDefaultValue();+ Table table =+ catalog+ .asTableCatalog()+ .createTable(+ NameIdentifier.of(schemaName, tableName),+ columns,+ null,+ ImmutableMap.of(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(CLICKHOUSE_COL_NAME1));++ Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, table.auditInfo().creator());+ Assertions.assertNull(table.auditInfo().lastModifier());++ // Change default value of float+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[0].name()}, Literals.of("1.2345", Types.FloatType.get())));++ // Change default value of timestamp to function expression+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[1].name()}, FunctionExpression.of("now")));+ // Change default value of varchar+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[2].name()}, Literals.of("hello", Types.VarCharType.of(255))));++ // Change default value of int+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[3].name()}, Literals.of("2000", Types.IntegerType.get())));+ // Change default value of decimal+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[4].name()}, Literals.of("2.34", Types.DecimalType.of(3, 2))));++ // Change default value of all columns at once+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[0].name()}, Literals.of("1.2345", Types.FloatType.get())),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[1].name()}, FunctionExpression.of("now")),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[2].name()}, Literals.of("hello", Types.VarCharType.of(255))),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[3].name()}, Literals.of("2000", Types.IntegerType.get())),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[4].name()}, Literals.of("2.34", Types.DecimalType.of(3, 2))));++ // Change default value of all columns at once again to make sure multiple alter table with+ // updateColumnDefaultValue works well together+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[0].name()}, Literals.of("1.2345", Types.FloatType.get())),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[1].name()}, FunctionExpression.of("now")),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[2].name()}, Literals.of("hello", Types.VarCharType.of(255))),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[3].name()}, Literals.of("2000", Types.IntegerType.get())),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[4].name()}, Literals.of("2.34", Types.DecimalType.of(3, 2))));++ // Change default value of all columns at once again with different values to make sure multiple+ // alter table with updateColumnDefaultValue works well together+ catalog+ .asTableCatalog()+ .alterTable(+ NameIdentifier.of(schemaName, tableName),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[0].name()}, Literals.of("1.2345", Types.FloatType.get())),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[1].name()}, FunctionExpression.of("now")),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[2].name()}, Literals.of("hello", Types.VarCharType.of(255))),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[3].name()}, Literals.of("2000", Types.IntegerType.get())),+ TableChange.updateColumnDefaultValue(+ new String[] {columns[4].name()}, Literals.of("2.34", Types.DecimalType.of(3, 2))));++ table = catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, tableName));++ Assertions.assertEquals(+ Literals.of("1.2345", Types.FloatType.get()), table.columns()[0].defaultValue());+ Assertions.assertEquals(UnparsedExpression.of("now()"), table.columns()[1].defaultValue());+ Assertions.assertEquals(+ Literals.of("hello", Types.StringType.get()), table.columns()[2].defaultValue());+ Assertions.assertEquals(+ Literals.of("2000", Types.IntegerType.get()), table.columns()[3].defaultValue());+ Assertions.assertEquals(+ Literals.of("2.34", Types.DecimalType.of(3, 2)), table.columns()[4].defaultValue());+ }++ @Test+ void testDropClickHouseDatabase() {+ String schemaName = GravitinoITUtils.genRandomName("clickhouse_schema").toLowerCase();+ String tableName = GravitinoITUtils.genRandomName("clickhouse_table").toLowerCase();++ catalog+ .asSchemas()+ .createSchema(schemaName, null, ImmutableMap.<String, String>builder().build());++ catalog+ .asTableCatalog()+ .createTable(+ NameIdentifier.of(schemaName, tableName),+ createColumns(),+ "Created by Gravitino client",+ ImmutableMap.<String, String>builder().build(),+ getSortOrders(CLICKHOUSE_COL_NAME3));++ // Try to drop a database, and cascade equals to false, it should not be+ // allowed.+ Throwable excep =+ Assertions.assertThrows(+ RuntimeException.class, () -> catalog.asSchemas().dropSchema(schemaName, false));+ Assertions.assertTrue(excep.getMessage().contains("the value of cascade should be true."));++ // Check the database still exists+ catalog.asSchemas().loadSchema(schemaName);++ // Try to drop a database, and cascade equals to true, it should be allowed.+ catalog.asSchemas().dropSchema(schemaName, true);+ // Check database has been dropped+ SupportsSchemas schemas = catalog.asSchemas();+ Assertions.assertThrows(+ NoSuchSchemaException.class,+ () -> {+ schemas.loadSchema(schemaName);+ });+ }++ @Test+ public void testSchemaComment() {+ final String testSchemaName = GravitinoITUtils.genRandomName("test");+ Assertions.assertDoesNotThrow(+ () -> {+ catalog.asSchemas().createSchema(testSchemaName, "comment", null);+ });++ // test null comment+ String testSchemaName2 = GravitinoITUtils.genRandomName("test");+ Schema schema = catalog.asSchemas().createSchema(testSchemaName2, "", null);+ Assertions.assertTrue(StringUtils.isEmpty(schema.comment()));+ schema = catalog.asSchemas().loadSchema(testSchemaName2);+ Assertions.assertTrue(StringUtils.isEmpty(schema.comment()));+ catalog.asSchemas().dropSchema(testSchemaName2, true);+ }++ @Test+ public void testBackQuoteTable() {+ Column col1 = Column.of("create", Types.LongType.get(), "id", false, false, null);+ Column col2 = Column.of("delete", Types.ByteType.get(), "yes", false, false, null);+ Column col3 = Column.of("show", Types.DateType.get(), "comment", false, false, null);+ Column col4 = Column.of("status", Types.VarCharType.of(255), "code", false, false, null);+ Column[] newColumns = new Column[] {col1, col2, col3, col4};+ TableCatalog tableCatalog = catalog.asTableCatalog();+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, "table");+ Assertions.assertDoesNotThrow(+ () ->+ tableCatalog.createTable(+ tableIdentifier,+ newColumns,+ table_comment,+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("create"),+ Indexes.EMPTY_INDEXES));++ Assertions.assertDoesNotThrow(() -> tableCatalog.loadTable(tableIdentifier));++ Assertions.assertDoesNotThrow(+ () ->+ tableCatalog.alterTable(+ tableIdentifier,+ TableChange.addColumn(+ new String[] {"int"},+ Types.StringType.get(),+ TableChange.ColumnPosition.after("status"))));++ Assertions.assertDoesNotThrow(+ () ->+ tableCatalog.alterTable(+ tableIdentifier, TableChange.renameColumn(new String[] {"int"}, "varchar")));++ Assertions.assertDoesNotThrow(+ () ->+ tableCatalog.alterTable(+ tableIdentifier, TableChange.deleteColumn(new String[] {"varchar"}, true)));++ Assertions.assertDoesNotThrow(() -> tableCatalog.dropTable(tableIdentifier));+ }++ @Test+ void testClickHouseSpecialTableName() {+ // Test create many indexes with name success.+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();++ String t1_name = "t112";+ Column t1_col = Column.of(t1_name, Types.LongType.get(), "id", false, false, null);+ Column[] columns = {t1_col};++ Index[] t1_indexes = {Indexes.primary("PRIMARY", new String[][] {{t1_name}})};++ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, t1_name);+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("t112"),+ t1_indexes);++ String t2_name = "t212";+ Column t2_col = Column.of(t2_name, Types.LongType.get(), "id", false, false, null);+ Index[] t2_indexes = {Indexes.primary("PRIMARY", new String[][] {{t2_name}})};+ columns = new Column[] {t2_col};+ tableIdentifier = NameIdentifier.of(schemaName, t2_name);+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(t2_name),+ t2_indexes);++ String t3_name = "t_12";+ Column t3_col = Column.of(t3_name, Types.LongType.get(), "id", false, false, null);+ Index[] t3_indexes = {Indexes.primary("PRIMARY", new String[][] {{t3_name}})};+ columns = new Column[] {t3_col};+ tableIdentifier = NameIdentifier.of(schemaName, t3_name);+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(t3_name),+ t3_indexes);++ String t4_name = "_1__";+ Column t4_col = Column.of(t4_name, Types.LongType.get(), "id", false, false, null);+ Index[] t4_indexes = {Indexes.primary("PRIMARY", new String[][] {{t4_name}})};+ columns = new Column[] {t4_col};+ tableIdentifier = NameIdentifier.of(schemaName, t4_name);+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders(t4_name),+ t4_indexes);++ Table t1 = tableCatalog.loadTable(NameIdentifier.of(schemaName, t1_name));+ Arrays.stream(t1.columns()).anyMatch(c -> Objects.equals(c.name(), "t112"));+ ITUtils.assertionsTableInfo(+ t1_name,+ table_comment,+ Arrays.asList(t1_col),+ properties,+ null,+ Transforms.EMPTY_TRANSFORM,+ t1);++ Table t2 = tableCatalog.loadTable(NameIdentifier.of(schemaName, t2_name));+ Arrays.stream(t2.columns()).anyMatch(c -> Objects.equals(c.name(), "t212"));+ ITUtils.assertionsTableInfo(+ t2_name,+ table_comment,+ Arrays.asList(t2_col),+ properties,+ t2_indexes,+ Transforms.EMPTY_TRANSFORM,+ t2);++ Table t3 = tableCatalog.loadTable(NameIdentifier.of(schemaName, t3_name));+ Arrays.stream(t3.columns()).anyMatch(c -> Objects.equals(c.name(), "t_12"));+ ITUtils.assertionsTableInfo(+ t3_name,+ table_comment,+ Arrays.asList(t3_col),+ properties,+ t3_indexes,+ Transforms.EMPTY_TRANSFORM,+ t3);++ Table t4 = tableCatalog.loadTable(NameIdentifier.of(schemaName, t4_name));+ Arrays.stream(t4.columns()).anyMatch(c -> Objects.equals(c.name(), "_1__"));+ ITUtils.assertionsTableInfo(+ t4_name,+ table_comment,+ Arrays.asList(t4_col),+ properties,+ t4_indexes,+ Transforms.EMPTY_TRANSFORM,+ t4);+ }++ @Test+ void testClickHouseIllegalTableName() {+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ String table_name = "t123";++ String t1_name = table_name + "`; DROP TABLE important_table; -- ";+ Column t1_col = Column.of(t1_name, Types.LongType.get(), "id", false, false, null);+ Column[] columns = {t1_col};+ Index[] t1_indexes = {Indexes.unique("u1_key", new String[][] {{t1_name}})};+ NameIdentifier tableIdentifier =+ NameIdentifier.of(metalakeName, catalogName, schemaName, t1_name);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ tableCatalog.createTable(+ tableIdentifier,+ columns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ new SortOrder[0],+ t1_indexes);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asTableCatalog().dropTable(tableIdentifier);+ });++ String t2_name = table_name + "`; SLEEP(10); -- ";+ Column t2_col = Column.of(t2_name, Types.LongType.get(), "id", false, false, null);+ Index[] t2_indexes = {Indexes.unique("u2_key", new String[][] {{t2_name}})};+ Column[] columns2 = new Column[] {t2_col};+ NameIdentifier tableIdentifier2 =+ NameIdentifier.of(metalakeName, catalogName, schemaName, t2_name);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ tableCatalog.createTable(+ tableIdentifier2,+ columns2,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ new SortOrder[0],+ t2_indexes);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asTableCatalog().dropTable(tableIdentifier2);+ });++ String t3_name =+ table_name + "`; UPDATE Users SET password = 'newpassword' WHERE username = 'admin'; -- ";+ Column t3_col = Column.of(t3_name, Types.LongType.get(), "id", false, false, null);+ Index[] t3_indexes = {Indexes.unique("u3_key", new String[][] {{t3_name}})};+ Column[] columns3 = new Column[] {t3_col};+ NameIdentifier tableIdentifier3 =+ NameIdentifier.of(metalakeName, catalogName, schemaName, t3_name);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ tableCatalog.createTable(+ tableIdentifier3,+ columns3,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ new SortOrder[0],+ t3_indexes);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asTableCatalog().dropTable(tableIdentifier3);+ });++ String invalidInput = StringUtils.repeat("a", 65);+ Column t4_col = Column.of(invalidInput, Types.LongType.get(), "id", false, false, null);+ Index[] t4_indexes = {Indexes.unique("u4_key", new String[][] {{invalidInput}})};+ Column[] columns4 = new Column[] {t4_col};+ NameIdentifier tableIdentifier4 =+ NameIdentifier.of(metalakeName, catalogName, schemaName, invalidInput);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ tableCatalog.createTable(+ tableIdentifier4,+ columns4,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ new SortOrder[0],+ t4_indexes);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asTableCatalog().dropTable(tableIdentifier4);+ });+ }++ @Test+ void testClickHouseTableNameCaseSensitive() {+ Column col1 = Column.of("col_1", Types.LongType.get(), "id", false, false, null);+ Column col2 = Column.of("col_2", Types.ByteType.get(), "yes", false, false, null);+ Column col3 = Column.of("col_3", Types.DateType.get(), "comment", false, false, null);+ Column col4 = Column.of("col_4", Types.StringType.get(), "code", false, false, null);+ Column col5 = Column.of("col_5", Types.StringType.get(), "config", false, false, null);+ Column[] newColumns = new Column[] {col1, col2, col3, col4, col5};++ Index[] indexes = new Index[0];++ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, "tableName");+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ Table createdTable =+ tableCatalog.createTable(+ tableIdentifier,+ newColumns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("col_1"),+ indexes);+ ITUtils.assertionsTableInfo(+ "tableName",+ table_comment,+ Arrays.asList(newColumns),+ properties,+ indexes,+ Transforms.EMPTY_TRANSFORM,+ createdTable);+ Table table = tableCatalog.loadTable(tableIdentifier);+ ITUtils.assertionsTableInfo(+ "tableName",+ table_comment,+ Arrays.asList(newColumns),+ properties,+ indexes,+ Transforms.EMPTY_TRANSFORM,+ table);++ // Test create table with same name but different case+ NameIdentifier tableIdentifier2 = NameIdentifier.of(schemaName, "TABLENAME");++ Table tableAgain =+ Assertions.assertDoesNotThrow(+ () ->+ tableCatalog.createTable(+ tableIdentifier2,+ newColumns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("col_1"),+ indexes));+ Assertions.assertEquals("TABLENAME", tableAgain.name());++ table = tableCatalog.loadTable(tableIdentifier2);+ ITUtils.assertionsTableInfo(+ "TABLENAME",+ table_comment,+ Arrays.asList(newColumns),+ properties,+ indexes,+ Transforms.EMPTY_TRANSFORM,+ table);+ }++ @Test+ void testNameSpec() {+ // test operate illegal schema name from ClickHouse+ String testSchemaName = "//";+ String sql = String.format("CREATE DATABASE `%s`", testSchemaName);+ clickhouseService.executeQuery(sql);++ Schema schema = catalog.asSchemas().loadSchema(testSchemaName);+ Assertions.assertEquals(testSchemaName, schema.name());++ String[] schemaIdents = catalog.asSchemas().listSchemas();+ Assertions.assertTrue(Arrays.stream(schemaIdents).anyMatch(s -> s.equals(testSchemaName)));++ Assertions.assertTrue(catalog.asSchemas().dropSchema(testSchemaName, false));+ Assertions.assertFalse(catalog.asSchemas().schemaExists(testSchemaName));++ // test operate illegal table name from ClickHouse+ clickhouseService.executeQuery(sql);+ String testTableName = "//";+ sql =+ String.format("CREATE TABLE `%s`.`%s` (id int) order by id", testSchemaName, testTableName);+ clickhouseService.executeQuery(sql);+ NameIdentifier tableIdent = NameIdentifier.of(testSchemaName, testTableName);++ Table table = catalog.asTableCatalog().loadTable(tableIdent);+ Assertions.assertEquals(testTableName, table.name());++ NameIdentifier[] tableIdents =+ catalog.asTableCatalog().listTables(Namespace.of(testSchemaName));+ Assertions.assertTrue(Arrays.stream(tableIdents).anyMatch(t -> t.name().equals(testTableName)));++ Assertions.assertTrue(catalog.asTableCatalog().dropTable(tableIdent));+ Assertions.assertFalse(catalog.asTableCatalog().tableExists(tableIdent));+ Assertions.assertThrows(+ UnsupportedOperationException.class,+ () -> {+ catalog.asTableCatalog().purgeTable(tableIdent);+ });+ catalog.asSchemas().dropSchema(testSchemaName, true);++ // sql injection+ String schemaName = RandomNameUtils.genRandomName("ct_db");+ Map<String, String> properties = new HashMap<>();+ String comment = null;++ // should throw an exception with string that might contain SQL injection+ String sqlInjection = schemaName + "`; DROP TABLE important_table; -- ";+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().createSchema(sqlInjection, comment, properties);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().dropSchema(sqlInjection, false);+ });++ String sqlInjection1 = schemaName + "`; SLEEP(10); -- ";+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().createSchema(sqlInjection1, comment, properties);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().dropSchema(sqlInjection1, false);+ });++ String sqlInjection2 =+ schemaName + "`; UPDATE Users SET password = 'newpassword' WHERE username = 'admin'; -- ";+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().createSchema(sqlInjection2, comment, properties);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().dropSchema(sqlInjection2, false);+ });++ // should throw an exception with input that has more than 64 characters+ String invalidInput = StringUtils.repeat("a", 65);+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().createSchema(invalidInput, comment, properties);+ });+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> {+ catalog.asSchemas().dropSchema(invalidInput, false);+ });+ }++ @Test+ void testClickHouseSchemaNameCaseSensitive() {+ Column col1 = Column.of("col_1", Types.LongType.get(), "id", false, false, null);+ Column col2 = Column.of("col_2", Types.VarCharType.of(255), "code", false, false, null);+ Column col3 = Column.of("col_3", Types.VarCharType.of(255), "config", false, false, null);+ Column[] newColumns = new Column[] {col1, col2, col3};++ String[] schemas = {"db_", "db_1", "db_2", "db12"};+ SupportsSchemas schemaSupport = catalog.asSchemas();++ for (String schema : schemas) {+ schemaSupport.createSchema(schema, null, Collections.emptyMap());+ Assertions.assertNotNull(schemaSupport.loadSchema(schema));+ }++ Set<String> schemaNames = Sets.newHashSet(schemaSupport.listSchemas());++ Assertions.assertTrue(schemaNames.containsAll(Arrays.asList(schemas)));++ String tableName = "test1";+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();++ for (String schema : schemas) {+ tableCatalog.createTable(+ NameIdentifier.of(schema, tableName),+ newColumns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("col_1"),+ null);+ tableCatalog.createTable(+ NameIdentifier.of(schema, GravitinoITUtils.genRandomName("test2")),+ newColumns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("col_1"),+ Indexes.EMPTY_INDEXES);+ }++ for (String schema : schemas) {+ NameIdentifier[] nameIdentifiers = tableCatalog.listTables(Namespace.of(schema));+ Assertions.assertEquals(2, nameIdentifiers.length);+ Assertions.assertTrue(+ Arrays.stream(nameIdentifiers)+ .map(NameIdentifier::name)+ .collect(Collectors.toSet())+ .stream()+ .anyMatch(n -> n.equals(tableName)));+ }++ for (String schema : schemas) {+ schemaSupport.dropSchema(schema, true);+ }+ }++ @Test+ void testUnparsedTypeConverter() {+ String tableName = GravitinoITUtils.genRandomName("test_unparsed_type");+ clickhouseService.executeQuery(+ String.format(+ "CREATE TABLE %s.%s (bit_col IPv4) order by bit_col ;", schemaName, tableName));+ Table loadedTable =+ catalog.asTableCatalog().loadTable(NameIdentifier.of(schemaName, tableName));+ Assertions.assertEquals(Types.ExternalType.of("IPv4"), loadedTable.columns()[0].dataType());+ }++ @Test+ void testAddColumnDefaultValue() {+ Column col1 = Column.of("col_1", Types.LongType.get(), "uid", false, false, null);+ Column col2 = Column.of("col_2", Types.ByteType.get(), "yes", true, false, null);+ Column col3 = Column.of("col_3", Types.StringType.get(), "comment", true, false, null);+ String tableName = "default_value_table";+ Column[] newColumns = new Column[] {col1, col2, col3};++ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, tableName);+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ tableCatalog.createTable(+ tableIdentifier,+ newColumns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("col_1"),+ Indexes.EMPTY_INDEXES);++ Column col4 =+ Column.of("col_4", Types.LongType.get(), "col4", true, false, DEFAULT_VALUE_NOT_SET);+ tableCatalog.alterTable(+ tableIdentifier,+ TableChange.addColumn(+ new String[] {col4.name()},+ col4.dataType(),+ col4.comment(),+ TableChange.ColumnPosition.defaultPos()));++ Table table = tableCatalog.loadTable(tableIdentifier);+ newColumns = new Column[] {col1, col2, col3, col4};++ ITUtils.assertionsTableInfo(+ tableName,+ table_comment,+ Arrays.asList(newColumns),+ properties,+ Indexes.EMPTY_INDEXES,+ Transforms.EMPTY_TRANSFORM,+ table);+ }++ @Test+ public void testClickHouseIntegerTypes() {+ Column col1 = Column.of("col_1", Types.ByteType.get(), "byte type", false, false, null);+ Column col2 =+ Column.of("col_2", Types.ByteType.unsigned(), "byte unsigned type", true, false, null);+ Column col3 = Column.of("col_3", Types.ShortType.get(), "short type", true, false, null);+ Column col4 =+ Column.of("col_4", Types.ShortType.unsigned(), "short unsigned type ", true, false, null);+ Column col5 = Column.of("col_5", Types.IntegerType.get(), "integer type", true, false, null);+ Column col6 =+ Column.of(+ "col_6", Types.IntegerType.unsigned(), "integer unsigned type", true, false, null);+ Column col7 = Column.of("col_7", Types.LongType.get(), "long type", true, false, null);+ Column col8 =+ Column.of("col_8", Types.LongType.unsigned(), "long unsigned type", true, false, null);+ String tableName = "default_integer_types_table";+ Column[] newColumns = new Column[] {col1, col2, col3, col4, col5, col6, col7, col8};++ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, tableName);+ Map<String, String> properties = createProperties();+ TableCatalog tableCatalog = catalog.asTableCatalog();+ tableCatalog.createTable(+ tableIdentifier,+ newColumns,+ table_comment,+ properties,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ getSortOrders("col_1"),+ Indexes.EMPTY_INDEXES);++ Table table = tableCatalog.loadTable(tableIdentifier);+ Assertions.assertEquals(8, table.columns().length);+ Column[] columns = table.columns();+ Assertions.assertEquals(columns[0].dataType().simpleString(), "byte");+ Assertions.assertEquals(columns[1].dataType().simpleString(), "byte unsigned");+ Assertions.assertEquals(columns[2].dataType().simpleString(), "short");+ Assertions.assertEquals(columns[3].dataType().simpleString(), "short unsigned");+ Assertions.assertEquals(columns[4].dataType().simpleString(), "integer");+ Assertions.assertEquals(columns[5].dataType().simpleString(), "integer unsigned");+ Assertions.assertEquals(columns[6].dataType().simpleString(), "long");+ Assertions.assertEquals(columns[7].dataType().simpleString(), "long unsigned");+ }++ @Test+ void testAlterCatalogProperties() throws SQLException {+ Map<String, String> catalogProperties = Maps.newHashMap();+ String testCatalogName = GravitinoITUtils.genRandomName("clickhouse_it_catalog");++ catalogProperties.put(+ JdbcConfig.JDBC_URL.getKey(),+ StringUtils.substring(+ CLICKHOUSE_CONTAINER.getJdbcUrl(TEST_DB_NAME),+ 0,+ CLICKHOUSE_CONTAINER.getJdbcUrl(TEST_DB_NAME).lastIndexOf("/")));+ catalogProperties.put(+ JdbcConfig.JDBC_DRIVER.getKey(), CLICKHOUSE_CONTAINER.getDriverClassName(TEST_DB_NAME));+ catalogProperties.put(JdbcConfig.USERNAME.getKey(), CLICKHOUSE_CONTAINER.getUsername());++ String password = CLICKHOUSE_CONTAINER.getPassword();+ String wrongPassword = password + "wrong";+ catalogProperties.put(JdbcConfig.PASSWORD.getKey(), wrongPassword);++ metalake.createCatalog(+ testCatalogName, Catalog.Type.RELATIONAL, provider, "comment", catalogProperties);+ Catalog loadCatalog = metalake.loadCatalog(testCatalogName);++ Assertions.assertThrows(+ Exception.class, () -> loadCatalog.asSchemas().createSchema("test", "", null));+ Catalog newLoadedCatalog =+ metalake.alterCatalog(+ testCatalogName, CatalogChange.setProperty(JdbcConfig.PASSWORD.getKey(), password));++ Assertions.assertDoesNotThrow(+ () -> newLoadedCatalog.asSchemas().createSchema("test", "", null));++ loadCatalog.asSchemas().dropSchema("test", true);+ metalake.dropCatalog(testCatalogName, true);+ }+}diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/service/ClickHouseService.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/service/ClickHouseService.javanew file mode 100644index 0000000000..d71d920801--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/integration/test/service/ClickHouseService.java@@ -0,0 +1,111 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.clickhouse.integration.test.service;++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 org.apache.commons.lang3.ArrayUtils;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.catalog.jdbc.JdbcSchema;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.integration.test.container.ClickHouseContainer;+import org.apache.gravitino.integration.test.util.TestDatabaseName;+import org.apache.gravitino.meta.AuditInfo;++public class ClickHouseService {++ private Connection connection;++ public ClickHouseService(ClickHouseContainer clickhouseContainer, TestDatabaseName testDBName) {+ String username = clickhouseContainer.getUsername();+ String password = clickhouseContainer.getPassword();++ try {+ connection =+ DriverManager.getConnection(+ StringUtils.substring(+ clickhouseContainer.getJdbcUrl(testDBName),+ 0,+ clickhouseContainer.getJdbcUrl(testDBName).lastIndexOf("/")),+ username,+ password);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ public NameIdentifier[] listSchemas(Namespace namespace) {+ List<String> databases = new ArrayList<>();+ try (Statement statement = connection.createStatement();+ ResultSet resultSet = statement.executeQuery("SHOW DATABASES")) {+ while (resultSet.next()) {+ databases.add(resultSet.getString(1));+ }+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ return databases.stream()+ .map(s -> NameIdentifier.of(ArrayUtils.add(namespace.levels(), s)))+ .toArray(NameIdentifier[]::new);+ }++ public JdbcSchema loadSchema(NameIdentifier schemaIdent) {+ String databaseName = schemaIdent.name();+ String query = "SELECT * FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?";+ try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {+ preparedStatement.setString(1, databaseName);++ // Execute the query+ try (ResultSet resultSet = preparedStatement.executeQuery()) {+ if (!resultSet.next()) {+ throw new NoSuchSchemaException(+ "Database %s could not be found in information_schema.SCHEMATA", databaseName);+ }+ String schemaName = resultSet.getString("SCHEMA_NAME");+ return JdbcSchema.builder().withName(schemaName).withAuditInfo(AuditInfo.EMPTY).build();+ }+ } catch (final SQLException se) {+ throw new RuntimeException(se);+ }+ }++ public void executeQuery(String sql) {+ try (Statement statement = connection.createStatement()) {+ statement.execute(sql);+ } catch (SQLException e) {+ throw new RuntimeException(e);+ }+ }++ public void close() {+ try {+ connection.close();+ } catch (SQLException e) {+ // ignore+ }+ }+}diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseCatalogOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseCatalogOperations.javaindex 317f6cc3eb..db5fd9ea30 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseCatalogOperations.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseCatalogOperations.java@@ -19,8 +19,11 @@package org.apache.gravitino.catalog.clickhouse.operations;import java.sql.SQLException;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.Namespace;import org.apache.gravitino.catalog.clickhouse.ClickHouseCatalog;import org.apache.gravitino.catalog.jdbc.JdbcCatalogOperations;+import org.apache.gravitino.connector.CatalogInfo;import org.junit.jupiter.api.Tag;import org.junit.jupiter.api.Test;@@ -31,6 +34,17 @@ public class TestClickHouseCatalogOperations extends TestClickHouse {public void testCheckJDBCDriver() throws SQLException {JdbcCatalogOperations catalogOperations =new JdbcCatalogOperations(null, null, DATABASE_OPERATIONS, TABLE_OPERATIONS, null);- catalogOperations.initialize(getClickHouseCatalogProperties(), null, new ClickHouseCatalog());+ CatalogInfo catalogInfo =+ new CatalogInfo(+ 1L,+ "clickhouse_catalog",+ Catalog.Type.RELATIONAL,+ "clickhouse",+ "",+ getClickHouseCatalogProperties(),+ null,+ Namespace.of("default"));+ catalogOperations.initialize(+ getClickHouseCatalogProperties(), catalogInfo, new ClickHouseCatalog());}}diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseDatabaseOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseDatabaseOperations.javaindex 44e7b7ff61..8b2fb1f23c 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseDatabaseOperations.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseDatabaseOperations.java@@ -18,14 +18,18 @@*/package org.apache.gravitino.catalog.clickhouse.operations;+import java.sql.Connection;+import java.sql.Statement;import java.util.Collections;import java.util.HashMap;import java.util.Map;+import javax.sql.DataSource;import org.apache.gravitino.catalog.clickhouse.ClickHouseConfig;import org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.ClusterConstants;import org.apache.gravitino.catalog.jdbc.converter.JdbcExceptionConverter;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;+import org.mockito.Mockito;public class TestClickHouseDatabaseOperations {@@ -71,6 +75,25 @@ public class TestClickHouseDatabaseOperations {Assertions.assertEquals("CREATE DATABASE `db_name` ON CLUSTER `ck_cluster`", sql);}+ @Test+ void testCreateUsesSystemCatalogBeforeExecution() throws Exception {+ DataSource dataSource = Mockito.mock(DataSource.class);+ Connection connection = Mockito.mock(Connection.class);+ Statement statement = Mockito.mock(Statement.class);++ Mockito.when(dataSource.getConnection()).thenReturn(connection);+ Mockito.when(connection.createStatement()).thenReturn(statement);+ Mockito.when(statement.executeUpdate(Mockito.anyString())).thenReturn(0);++ ClickHouseDatabaseOperations ops = new ClickHouseDatabaseOperations();+ ops.initialize(dataSource, new JdbcExceptionConverter(), new HashMap<>());++ ops.create("new_db", null, Collections.emptyMap());++ Mockito.verify(connection).setCatalog("information_schema");+ Mockito.verify(statement).executeUpdate("CREATE DATABASE `new_db`");+ }+@Testvoid testGenerateDropDatabaseSqlWithoutCluster() {Map<String, String> conf = new HashMap<>();diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.javaindex 5ebe7dc4b3..753b4110f1 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java@@ -19,6 +19,7 @@package org.apache.gravitino.catalog.clickhouse.operations;import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.CLICKHOUSE_ENGINE_KEY;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.GRAVITINO_ENGINE_KEY;import static org.apache.gravitino.catalog.clickhouse.ClickHouseUtils.getSortOrders;import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;@@ -873,7 +874,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {Indexes.EMPTY_INDEXES,getSortOrders("col_1"));JdbcTable load = TABLE_OPERATIONS.load(TEST_DB_NAME.toString(), testTable1);- Assertions.assertEquals("MergeTree", load.properties().get(CLICKHOUSE_ENGINE_KEY));+ Assertions.assertEquals("MergeTree", load.properties().get(GRAVITINO_ENGINE_KEY));}@Test@@ -942,8 +943,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {new SortOrder[0]));// MergeTree only supports single sortOrders- Assertions.assertThrows(- UnsupportedOperationException.class,+ Assertions.assertDoesNotThrow(() ->ops.buildCreateSql("t1",@@ -962,7 +962,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {logEngineProps.put(TableConstants.ENGINE_UPPER, ClickHouseTablePropertiesMetadata.ENGINE.LOG.getValue());Assertions.assertThrows(- UnsupportedOperationException.class,+ IllegalArgumentException.class,() ->ops.buildCreateSql("t1",@@ -974,7 +974,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {indexes,null));Assertions.assertThrows(- UnsupportedOperationException.class,+ IllegalArgumentException.class,() ->ops.buildCreateSql("t1",@@ -984,7 +984,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {new Transform[0],Distributions.NONE,indexes,- ClickHouseUtils.getSortOrders("c1")));+ null));// Settings and comment retainedMap<String, String> props = new HashMap<>();diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsCluster.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsCluster.javaindex b5088ad951..7117d379cd 100644--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsCluster.java+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsCluster.java@@ -18,7 +18,7 @@*/package org.apache.gravitino.catalog.clickhouse.operations;-import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.CLICKHOUSE_ENGINE_KEY;+import static org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.GRAVITINO_ENGINE_KEY;import java.util.HashMap;import java.util.Map;@@ -67,7 +67,7 @@ class TestClickHouseTableOperationsCluster {Map<String, String> props = new HashMap<>();props.put(ClusterConstants.CLUSTER_NAME, "ck_cluster");props.put(ClusterConstants.ON_CLUSTER, "true");- props.put(CLICKHOUSE_ENGINE_KEY, "Distributed");+ props.put(GRAVITINO_ENGINE_KEY, "Distributed");props.put(DistributedTableConstants.REMOTE_DATABASE, "remote_db");props.put(DistributedTableConstants.REMOTE_TABLE, "remote_table");props.put(DistributedTableConstants.SHARDING_KEY, "`user_id`");@@ -117,7 +117,7 @@ class TestClickHouseTableOperationsCluster {Map<String, String> props = new HashMap<>();props.put(ClusterConstants.CLUSTER_NAME, "ck_cluster");props.put(ClusterConstants.ON_CLUSTER, "true");- props.put(CLICKHOUSE_ENGINE_KEY, "Distributed");+ props.put(GRAVITINO_ENGINE_KEY, "Distributed");props.put(DistributedTableConstants.REMOTE_DATABASE, "remote_db");props.put(DistributedTableConstants.REMOTE_TABLE, "remote_table");props.put(DistributedTableConstants.SHARDING_KEY, "user");@@ -150,7 +150,7 @@ class TestClickHouseTableOperationsCluster {Map<String, String> props = new HashMap<>();props.put(ClusterConstants.CLUSTER_NAME, "ck_cluster");props.put(ClusterConstants.ON_CLUSTER, "true");- props.put(CLICKHOUSE_ENGINE_KEY, "Distributed");+ props.put(GRAVITINO_ENGINE_KEY, "Distributed");props.put(DistributedTableConstants.REMOTE_DATABASE, "remote_db");props.put(DistributedTableConstants.REMOTE_TABLE, "remote_table");props.put(DistributedTableConstants.SHARDING_KEY, "rand()");@@ -180,7 +180,7 @@ class TestClickHouseTableOperationsCluster {Map<String, String> props = new HashMap<>();props.put(ClusterConstants.CLUSTER_NAME, "ck_cluster");- props.put(CLICKHOUSE_ENGINE_KEY, "Distributed");+ props.put(GRAVITINO_ENGINE_KEY, "Distributed");props.put(DistributedTableConstants.REMOTE_DATABASE, "remote_db");props.put(DistributedTableConstants.REMOTE_TABLE, "remote_table");props.put(DistributedTableConstants.SHARDING_KEY, "user_id");diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/resources/log4j2.properties b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/resources/log4j2.propertiesnew file mode 100644index 0000000000..c3c0b1186b--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/resources/log4j2.properties@@ -0,0 +1,70 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++# Set to debug or trace if log4j initialization is failing+status = info++# Name of the configuration+name = ConsoleLogConfig++# Console appender configuration+appender.console.type = Console+appender.console.name = consoleLogger+appender.console.layout.type = PatternLayout+appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n++# Log files location+property.logPath = ${sys:gravitino.log.path:-build/catalog-jdbc-clickhouse-integration-test.log}++# File appender configuration+appender.file.type = File+appender.file.name = fileLogger+appender.file.fileName = ${logPath}+appender.file.layout.type = PatternLayout+appender.file.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n++# Root logger level+rootLogger.level = info++# Root logger referring to console and file appenders+rootLogger.appenderRef.stdout.ref = consoleLogger+rootLogger.appenderRef.file.ref = fileLogger++# File appender configuration for testcontainers+appender.testcontainersFile.type = File+appender.testcontainersFile.name = testcontainersLogger+appender.testcontainersFile.fileName = build/testcontainers.log+appender.testcontainersFile.layout.type = PatternLayout+appender.testcontainersFile.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c - %m%n++# Logger for testcontainers+logger.testcontainers.name = org.testcontainers+logger.testcontainers.level = debug+logger.testcontainers.appenderRef.file.ref = testcontainersLogger++logger.tc.name = tc+logger.tc.level = debug+logger.tc.appenderRef.file.ref = testcontainersLogger++logger.docker.name = com.github.dockerjava+logger.docker.level = warn+logger.docker.appenderRef.file.ref = testcontainersLogger++logger.http.name = com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.wire+logger.http.level = off\ No newline at end of filediff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/resources/remote_servers.xml b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/resources/remote_servers.xmlnew file mode 100644index 0000000000..0b791ea3be--- /dev/null+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/resources/remote_servers.xml@@ -0,0 +1,39 @@+<!--+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<clickhouse>+ <remote_servers>+ <gravitino_cluster>+ <shard>+ <replica>+ <host>gravitino-ci-clickhouse-cluster</host>+ <port>9000</port>+ </replica>+ </shard>+ </gravitino_cluster>+ </remote_servers>+ <zookeeper>+ <node>+ <host>${ZOOKEEPER_HOST}</host>+ <port>${ZOOKEEPER_PORT}</port>+ </node>+ </zookeeper>+ <macros>+ <shard>01</shard>+ <replica>replica01</replica>+ </macros>+</clickhouse>diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.javaindex 6974797cc3..b70abc354d 100644--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalogOperations.java@@ -371,6 +371,7 @@ public class JdbcCatalogOperations implements CatalogOperations, SupportsSchemas.withName(tableName).withColumns(load.columns()).withAuditInfo(load.auditInfo())+ .withSortOrders(load.sortOrder()).withComment(comment).withProperties(properties).withDistribution(load.distribution())@@ -450,8 +451,13 @@ public class JdbcCatalogOperations implements CatalogOperations, SupportsSchemasSortOrder[] sortOrders,Index[] indexes)throws NoSuchSchemaException, TableAlreadyExistsException {- Preconditions.checkArgument(- null == sortOrders || sortOrders.length == 0, "jdbc-catalog does not support sort orders");+ JdbcTableOperations jdbcTableOperations = (JdbcTableOperations) tableOperation;+ if (!jdbcTableOperations.supportsTableSortOrder()) {+ Preconditions.checkArgument(+ null == sortOrders || sortOrders.length == 0,+ "The current JDBC connector: %s does not support sort orders",+ jdbcTableOperations.getClass().getName());+ }StringIdentifier identifier = StringIdentifier.fromProperties(properties);Preconditions.checkArgument(identifier != null, GRAVITINO_ATTRIBUTE_DOES_NOT_EXIST_MSG);@@ -483,7 +489,8 @@ public class JdbcCatalogOperations implements CatalogOperations, SupportsSchemasresultProperties,partitioning,distribution,- indexes);+ indexes,+ sortOrders);return JdbcTable.builder().withAuditInfo(diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcDatabaseOperations.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcDatabaseOperations.javaindex 87642f7c4f..68f9d97bae 100644--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcDatabaseOperations.java+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcDatabaseOperations.java@@ -69,6 +69,10 @@ public abstract class JdbcDatabaseOperations implements DatabaseOperation {}try (final Connection connection = getConnection()) {+ if (connection.getCatalog().equals(databaseName)) {+ connection.setCatalog(createSysDatabaseNameSet().iterator().next());+ }+JdbcConnectorUtils.executeUpdate(connection, generateCreateDatabaseSql(databaseName, comment, properties));LOG.info("Finished creating database {}", databaseName);diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.javaindex 7af4c94b0c..5e4e5b52fd 100644--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java@@ -143,8 +143,7 @@ public abstract class JdbcTableOperations implements TableOperation {throws TableAlreadyExistsException {LOG.info("Attempting to create table {} in database {}", tableName, databaseName);try (Connection connection = getConnection(databaseName)) {- JdbcConnectorUtils.executeUpdate(- connection,+ String sql =generateCreateTableSql(tableName,columns,@@ -153,8 +152,10 @@ public abstract class JdbcTableOperations implements TableOperation {partitioning,distribution,indexes,- sortOrders));- LOG.info("Created table {} in database {}", tableName, databaseName);+ sortOrders);++ JdbcConnectorUtils.executeUpdate(connection, sql);+ LOG.info("Created table {} in database {} with SQL:\n{}", tableName, databaseName, sql);} catch (final SQLException se) {throw this.exceptionMapper.toGravitinoException(se);}@@ -234,6 +235,10 @@ public abstract class JdbcTableOperations implements TableOperation {return builder;}+ public boolean supportsTableSortOrder() {+ return false;+ }+@Overridepublic JdbcTable load(String databaseName, String tableName) throws NoSuchTableException {// We should handle case sensitivity and wild card issue in some catalog tables, take MySQLdiff --git a/catalogs/catalog-jdbc-common/src/test/resources/log4j2.properties b/catalogs/catalog-jdbc-common/src/test/resources/log4j2.propertiesnew file mode 100644index 0000000000..c3c0b1186b--- /dev/null+++ b/catalogs/catalog-jdbc-common/src/test/resources/log4j2.properties@@ -0,0 +1,70 @@+#+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+#++# Set to debug or trace if log4j initialization is failing+status = info++# Name of the configuration+name = ConsoleLogConfig++# Console appender configuration+appender.console.type = Console+appender.console.name = consoleLogger+appender.console.layout.type = PatternLayout+appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n++# Log files location+property.logPath = ${sys:gravitino.log.path:-build/catalog-jdbc-clickhouse-integration-test.log}++# File appender configuration+appender.file.type = File+appender.file.name = fileLogger+appender.file.fileName = ${logPath}+appender.file.layout.type = PatternLayout+appender.file.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n++# Root logger level+rootLogger.level = info++# Root logger referring to console and file appenders+rootLogger.appenderRef.stdout.ref = consoleLogger+rootLogger.appenderRef.file.ref = fileLogger++# File appender configuration for testcontainers+appender.testcontainersFile.type = File+appender.testcontainersFile.name = testcontainersLogger+appender.testcontainersFile.fileName = build/testcontainers.log+appender.testcontainersFile.layout.type = PatternLayout+appender.testcontainersFile.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c - %m%n++# Logger for testcontainers+logger.testcontainers.name = org.testcontainers+logger.testcontainers.level = debug+logger.testcontainers.appenderRef.file.ref = testcontainersLogger++logger.tc.name = tc+logger.tc.level = debug+logger.tc.appenderRef.file.ref = testcontainersLogger++logger.docker.name = com.github.dockerjava+logger.docker.level = warn+logger.docker.appenderRef.file.ref = testcontainersLogger++logger.http.name = com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.wire+logger.http.level = off\ No newline at end of filediff --git a/common/src/main/java/org/apache/gravitino/dto/rel/expressions/FuncExpressionDTO.java b/common/src/main/java/org/apache/gravitino/dto/rel/expressions/FuncExpressionDTO.javaindex 200006fdf9..fa160cad6b 100644--- a/common/src/main/java/org/apache/gravitino/dto/rel/expressions/FuncExpressionDTO.java+++ b/common/src/main/java/org/apache/gravitino/dto/rel/expressions/FuncExpressionDTO.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.dto.rel.expressions;+import java.util.Arrays;import lombok.EqualsAndHashCode;import org.apache.gravitino.rel.expressions.Expression;import org.apache.gravitino.rel.expressions.FunctionExpression;@@ -64,6 +65,22 @@ public class FuncExpressionDTO implements FunctionExpression, FunctionArg {return ArgType.FUNCTION;}+ /**+ * @return The string representation of the function expression.+ */+ @Override+ public String toString() {+ if (functionArgs.length == 0) {+ return functionName + "()";+ }++ return functionName+ + "("+ + String.join(+ ", ", Arrays.stream(functionArgs).map(Object::toString).toArray(String[]::new))+ + ")";+ }+/** Builder for {@link FuncExpressionDTO}. */public static class Builder {private String functionName;diff --git a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.javaindex 17e610223f..8bd6bda85b 100644--- a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java+++ b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java@@ -606,8 +606,10 @@ public class DTOConverters {if (Literals.NULL.equals(expression)) {return LiteralDTO.NULL;}++ Object value = ((Literal) expression).value();return LiteralDTO.builder()- .withValue((((Literal) expression).value().toString()))+ .withValue(value == null ? null : value.toString()).withDataType(((Literal) expression).dataType()).build();} else if (expression instanceof NamedReference.FieldReference) {diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.javaindex e320decaac..dc06c0702f 100644--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java@@ -30,6 +30,7 @@ import com.github.benmanes.caffeine.cache.Cache;import com.github.benmanes.caffeine.cache.Caffeine;import com.github.benmanes.caffeine.cache.Scheduler;import com.google.common.base.Preconditions;+import com.google.common.collect.ImmutableSet;import com.google.common.collect.Iterables;import com.google.common.collect.Lists;import com.google.common.collect.Maps;@@ -115,6 +116,9 @@ public class CatalogManager implements CatalogDispatcher, Closeable {private static final Logger LOG = LoggerFactory.getLogger(CatalogManager.class);+ private static final Set<String> CONTRIB_CATALOGS_TYPES =+ ImmutableSet.of("jdbc-oceanbase", "jdbc-clickhouse");+/** Wrapper class for a catalog instance and its class loader. */public static class CatalogWrapper {@@ -1115,6 +1119,19 @@ public class CatalogManager implements CatalogDispatcher, Closeable {if (pkg != null) {confPath = String.join(File.separator, pkg, "conf");} else if (testEnv) {+ if (CONTRIB_CATALOGS_TYPES.contains(provider)) {+ confPath =+ String.join(+ File.separator,+ gravitinoHome,+ "catalogs-contrib",+ "catalog-" + provider,+ "build",+ "resources",+ "main");+ return confPath;+ }+confPath =String.join(File.separator,@@ -1141,6 +1158,18 @@ public class CatalogManager implements CatalogDispatcher, Closeable {pkgPath = String.join(File.separator, pkg, "libs");} else if (testEnv) {// In test, the catalog package is under the build directory.+ if (CONTRIB_CATALOGS_TYPES.contains(provider)) {+ pkgPath =+ String.join(+ File.separator,+ gravitinoHome,+ "catalogs-contrib",+ "catalog-" + provider,+ "build",+ "libs");+ return pkgPath;+ }+pkgPath =String.join(File.separator, gravitinoHome, "catalogs", "catalog-" + provider, "build", "libs");diff --git a/docs/index.md b/docs/index.mdindex 922eb94423..80e5b4a723 100644--- a/docs/index.md+++ b/docs/index.md@@ -87,6 +87,7 @@ Gravitino currently supports the following catalogs:* [**PostgreSQL catalog**](./jdbc-postgresql-catalog.md)* [**OceanBase catalog**](./jdbc-oceanbase-catalog.md)* [**StarRocks catalog**](./jdbc-starrocks-catalog.md)+* [**ClickHouse catalog**](./jdbc-clickhouse-catalog.md)\** [**Lakehouse generic catalog**](./lakehouse-generic-catalog.md)If you want to operate table and partition statistics, you can refer to the [document](./manage-statistics-in-gravitino.md).@@ -137,6 +138,7 @@ Gravitino supports different catalogs to manage the metadata in different source* [Paimon catalog](./lakehouse-paimon-catalog.md): a complete guide to using Gravitino to manage Apache Paimon data.* [PostgreSQL catalog](./jdbc-postgresql-catalog.md): a complete guide to using Gravitino to manage PostgreSQL data.* [OceanBase catalog](./jdbc-oceanbase-catalog.md): a complete guide to using Gravitino to manage OceanBase data.+* [ClickHouse catalog](./jdbc-clickhouse-catalog.md): a complete guide to using Gravitino to manage ClickHouse data.* [Lakehouse generic catalog](./lakehouse-generic-catalog.md): a complete guide to using Gravitino to manage lakehouse data sources.### Governancediff --git a/docs/jdbc-clickhouse-catalog.md b/docs/jdbc-clickhouse-catalog.mdnew file mode 100644index 0000000000..394c10b989--- /dev/null+++ b/docs/jdbc-clickhouse-catalog.md@@ -0,0 +1,328 @@+---+title: "ClickHouse catalog"+slug: /jdbc-clickhouse-catalog+keywords:+- jdbc+- clickhouse+- metadata+license: "This software is licensed under the Apache License version 2.0."+---++import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++## Introduction++Apache Gravitino can manage ClickHouse metadata through a JDBC catalog. This document describes the capabilities and limitations of the ClickHouse catalog, as well as the supported operations and properties for catalogs, schemas, and tables.++:::caution+ClickHouse catalog is not included in the standard Gravitino server distribution due to the large size of the ClickHouse JDBC driver and potential licensing issues. To use the ClickHouse catalog, you can build from source code, and refer to document [how-to-build](./how-to-build.md) for more details.+:::++## Catalog++### Catalog capabilities++| Item | Description |+|-------------------|---------------------------------------------------------------------------------------------------------|+| Scope | One catalog maps to one ClickHouse instance |+| Metadata/DDL | Supports JDBC-based metadata management and DDL |+| Column defaults | Supports column default values |+| Drivers | Requires user-provided ClickHouse JDBC driver in `catalogs-contrib/catalog-jdbc-clickhouse/libs` |+| Supported version | All the codes are tested by ClickHouse `24.8.14`, but should be compatible with other versions as well. |++### Catalog properties++You can pass any JDBC pool property that Gravitino does not define by adding the `gravitino.bypass.` prefix (for example `gravitino.bypass.maxWaitMillis`). See [commons-dbcp configuration](https://commons.apache.org/proper/commons-dbcp/configuration.html) for details.++When using the JDBC catalog you must provide `jdbc-url`, `jdbc-driver`, `jdbc-user`, and `jdbc-password`. Common catalog properties are listed [here](./gravitino-server-config.md#apache-gravitino-catalog-properties-configuration); ClickHouse adds no extra catalog-scoped keys.++| Configuration item | Description | Default value | Required | Since Version |+|-------------------------|-----------------------------------------------------------------------------|---------------|----------|---------------|+| `jdbc-url` | JDBC URL, for example `jdbc:clickhouse://localhost:8123` | (none) | Yes | 1.2.0 |+| `jdbc-driver` | JDBC driver class, for example `com.clickhouse.jdbc.ClickHouseDriver` | (none) | Yes | 1.2.0 |+| `jdbc-user` | JDBC user name | (none) | Yes | 1.2.0 |+| `jdbc-password` | JDBC password | (none) | Yes | 1.2.0 |+| `jdbc.pool.min-size` | Minimum pool size | `2` | No | 1.2.0 |+| `jdbc.pool.max-size` | Maximum pool size | `10` | No | 1.2.0 |+| `jdbc.pool.max-wait-ms` | Max wait time for a connection | `30000` | No | 1.2.0 |++### Create a ClickHouse catalog++The following example creates a ClickHouse catalog with the required JDBC properties and optional connection pool settings. Note that the `jdbc-driver` class must be available in the Gravitino classpath (for example by placing the ClickHouse JDBC driver JAR in `catalogs/catalog-jdbc-clickhouse/libs`).+Description about some of the properties:+- provider: must be `jdbc-clickhouse` for Gravitino to recognize the catalog as ClickHouse;+- type: must be `RELATIONAL` since ClickHouse is a relational database;+++<Tabs groupId="language" queryString>+<TabItem value="shell" label="Shell">++```shell+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \+-H "Content-Type: application/json" -d '{+ "name": "ck",+ "type": "RELATIONAL",+ "comment": "ClickHouse catalog",+ "provider": "jdbc-clickhouse",+ "properties": {+ "jdbc-url": "jdbc:clickhouse://localhost:8123",+ "jdbc-driver": "com.clickhouse.jdbc.ClickHouseDriver",+ "jdbc-user": "default",+ "jdbc-password": "password"+ }+}' http://localhost:8090/api/metalakes/metalake/catalogs+```++</TabItem>+<TabItem value="java" label="Java">++```java+GravitinoClient client = GravitinoClient.builder("http://localhost:8090")+ .withMetalake("metalake")+ .build();++Map<String, String> ckProps = ImmutableMap.<String, String>builder()+ .put("jdbc-url", "jdbc:clickhouse://localhost:8123")+ .put("jdbc-driver", "com.clickhouse.jdbc.ClickHouseDriver")+ .put("jdbc-user", "default")+ .put("jdbc-password", "password")+ .build();++Catalog catalog =+ client.createCatalog("ck", Catalog.Type.RELATIONAL, "jdbc-clickhouse", "ClickHouse catalog", ckProps);+```++</TabItem>+</Tabs>++See [Manage Relational Metadata Using Gravitino](./manage-relational-metadata-using-gravitino.md#catalog-operations) for other catalog operations.++## Schema++### Schema capabilities++| Item | Description |+|--------------|--------------------------------------------------------------------|+| Mapping | Gravitino schema maps to a ClickHouse database |+| Operations | Create / drop / load / list (ClickHouse supports cascade drop) |+| Comments | Schema comments supported |+| Cluster mode | Optional `ON CLUSTER` for creation when `cluster-name` is provided |++### Schema properties++| Property Name | Description | Default Value | Required | Immutable | Since version |+|----------------|------------------------------------------------------------------------------------|---------------|----------|-----------|---------------|+| `on-cluster` | Use `ON CLUSTER` when creating the database | `false` | No | No | 1.2.0 |+| `cluster-name` | Cluster name used with `ON CLUSTER` (must align with table-level cluster settings) | (none) | No | No | 1.2.0 |++### Create a schema++<Tabs groupId="language" queryString>+<TabItem value="shell" label="Shell">++```shell+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \+-H "Content-Type: application/json" -d '{+ "name": "sales",+ "comment": "Sales database",+ "properties": {+ "on-cluster": "true",+ "cluster-name": "ck_cluster"+ }+}' http://localhost:8090/api/metalakes/metalake/catalogs/ck/schemas+```++</TabItem>+<TabItem value="java" label="Java">++```java+Catalog catalog = client.loadCatalog("ck");+Schema schema = catalog.asTableCatalog()+ .createSchema("sales", "Sales database",+ ImmutableMap.of("on-cluster", "true", "cluster-name", "ck_cluster"));+```++</TabItem>+</Tabs>++See [Manage Relational Metadata Using Gravitino](./manage-relational-metadata-using-gravitino.md#schema-operations) for more schema operations.++## Table++### Table capabilities++| Area | Details |+|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|+| Mapping | Gravitino table maps to a ClickHouse table |+| Engines | Local engines: MergeTree family (`MergeTree` default, `ReplacingMergeTree`, `SummingMergeTree`, `AggregatingMergeTree`, `CollapsingMergeTree`, `VersionedCollapsingMergeTree`, `GraphiteMergeTree`), Tiny/Stripe/Log, Memory, File, Null, Set, Join, View, Buffer, KeeperMap, etc. Distributed engine supports cluster mode with remote database/table and sharding key. |+| Ordering/Partition | MergeTree-family requires exactly one `ORDER BY` column; only single-column identity `PARTITION BY` is supported on MergeTree engines. Other engines reject `ORDER BY`/`PARTITION BY`. |+| Indexes | Primary key; data-skipping indexes `DATA_SKIPPING_MINMAX` and `DATA_SKIPPING_BLOOM_FILTER` (fixed granularities). |+| Distribution | Gravitino enforces `Distributions.NONE`; no custom distribution strategies. |+| Column defaults | Supported. |+| Unsupported | Engine change after creation; removing table properties; auto-increment columns. |++### Table column types++| Gravitino Type | ClickHouse Type |+|---------------------|----------------------------------------|+| `Byte` | `Int8` |+| `Unsigned Byte` | `UInt8` |+| `Short` | `Int16` |+| `Unsigned Short` | `UInt16` |+| `Integer` | `Int32` |+| `Unsigned Integer` | `UInt32` |+| `Long` | `Int64` |+| `Unsigned Long` | `UInt64` |+| `Float` | `Float32` |+| `Double` | `Float64` |+| `Decimal(p,s)` | `Decimal(p,s)` |+| `String`/`VarChar` | `String` |+| `FixedChar(n)` | `FixedString(n)` |+| `Date` | `Date` |+| `Timestamp[(p)]` | `DateTime` (precision defaults to `0`) |+| `BOOLEAN` | `Bool` |+| `UUID` | `UUID` |++Other ClickHouse types are exposed as [External Type](./manage-relational-metadata-using-gravitino.md#external-type).++### Table properties++:::note+- `settings.*` keys are passed to the ClickHouse `SETTINGS` clause verbatim.+- The `engine` value is immutable after creation.+:::++| Property Name | Description | Default Value | Required | Reserved | Immutable | Since version |+|----------------------------|----------------------------------------------------------------------------------------------------------|---------------|----------|----------|-----------|---------------|+| `engine` | Table engine (for example `MergeTree`, `ReplacingMergeTree`, `Distributed`, `Memory`, etc.) | `MergeTree` | No | No | Yes | 1.2.0 |+| `cluster-name` | Cluster name used with `ON CLUSTER` and Distributed engine | (none) | No\* | No | No | 1.2.0 |+| `on-cluster` | Use `ON CLUSTER` when creating the table | (none) | No | No | No | 1.2.0 |+| `cluster-remote-database` | Remote database for `Distributed` engine | (none) | No\*\* | No | No | 1.2.0 |+| `cluster-remote-table` | Remote table for `Distributed` engine | (none) | No\*\* | No | No | 1.2.0 |+| `cluster-sharding-key` | Sharding key for `Distributed` engine (expression allowed; referenced columns must be non-null integral) | (none) | No\*\* | No | No | 1.2.0 |+| `settings.<name>` | ClickHouse engine setting forwarded as `SETTINGS <name>=<value>` | (none) | No | No | No | 1.2.0 |++\* Required when `on-cluster=true` or `engine=Distributed`.+\*\* Required when `engine=Distributed`.++### Table indexes++- `PRIMARY_KEY`+- Data-skipping indexes:+ - `DATA_SKIPPING_MINMAX` (`GRANULARITY` fixed to 1)+ - `DATA_SKIPPING_BLOOM_FILTER` (`GRANULARITY` fixed to 3)++### Partitioning, sorting, and distribution++- `ORDER BY`: required for MergeTree-family engines and only columns identity are supported;+ - Accept format: `id`, `(id, name)`, `(func(id), name)`, `func(id)`;+ - Reject format: `(id + 1)`, `(func(id) + 1)`, etc.++- `PARTITION BY`: single-column identity and some functions are supported only, and only for MergeTree-family engines. For example `PARTITION BY created_at` or `PARTITION BY toYYYYMM(created_at)` are supported, but `PARTITION BY (created_at + 1)` are not supported.+ In all, the following partitioning expressions are supported:+ - Identity: `PARTITION BY column_name`+ - Functions: `PARTITION BY toDate(column_name)`, `PARTITION BY toYear(column_name)`, `PARTITION BY toYYYYMM(column_name)`. Other functions are not supported.+ - Not support: `PARTITION BY (column_name + 1)`, `PARTITION BY (toYear(column_name) + 1)`, etc. (Note: ClickHouse itself does support arbitrary partitioning expressions, but Gravitino currently only supports the above patterns for partitioning).++- Distribution: fixed to `Distributions.NONE`. For a `Distributed` engine table, you can specify the sharding key and remote database/table through table properties to fulfill the same use cases. We will later consider adding more flexible distribution strategies if there is demand.++### Create a table++The following example creates a `MergeTree` table with `ORDER BY`, partitioning, indexes, comments, and properties including `ON CLUSTER`. Note that the `engine` property is required for MergeTree-family tables, and that the cluster properties must align with the schema-level cluster settings if `on-cluster=true`.++This is a create table statement that would be executed in ClickHouse to create the corresponding table:+```sql+CREATE TABLE sales.orders ON CLUSTER ck_cluster (+ order_id Int32,+ user_id Int32,+ amount Decimal(18,2),+ created_at DateTime,+ primary key (order_id),+) ENGINE = MergeTree order BY order_id PARTITION BY created_at;++```++The same table can be created through the API as follows:++<Tabs groupId="language" queryString>+<TabItem value="shell" label="Shell">++```shell+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \+-H "Content-Type: application/json" -d '{+ "name": "orders",+ "comment": "Orders table",+ "columns": [+ {"name": "order_id", "type": "int", "nullable": false},+ {"name": "user_id", "type": "int", "nullable": false},+ {"name": "amount", "type": "decimal(18,2)", "nullable": false},+ {"name": "created_at", "type": "timestamp", "nullable": false}+ ],+ "properties": {+ "engine": "MergeTree",+ "on-cluster": "true",+ "cluster-name": "ck_cluster"+ },+ "sortOrders": [+ {"expression": "order_id", "direction": "ASCENDING"}+ ],+ "partitioning": ["created_at"],+ "indexes": [+ {"indexType": "primary_key", "name": "pk_order", "fieldNames": [["order_id"]]}+ ]+}' http://localhost:8090/api/metalakes/metalake/catalogs/ck/schemas/sales/tables+```++</TabItem>+<TabItem value="java" label="Java">++```java+TableCatalog tableCatalog = client.loadCatalog("ck").asTableCatalog();++Column[] columns = new Column[] {+ Column.of("order_id", Types.IntegerType.get(), "Order ID", false),+ Column.of("user_id", Types.IntegerType.get(), "User ID", false),+ Column.of("amount", Types.DecimalType.of(18, 2), "Amount", false),+ Column.of("created_at", Types.TimestampType.withoutTimeZone(), "Created time", false)+};++Index[] indexes =+ new Index[] {Indexes.of(Index.IndexType.PRIMARY_KEY, "pk_order", new String[][] {{"order_id"}})};++SortOrder[] sortOrders =+ new SortOrder[] {SortOrder.builder("order_id").withDirection(SortDirection.ASCENDING).build()};++Transform[] partitions = new Transform[] {Transforms.identity("created_at")};++tableCatalog.createTable(+ NameIdentifier.of("sales", "orders"),+ columns,+ "Orders table",+ ImmutableMap.of("engine", "MergeTree", "on-cluster", "true", "cluster-name", "ck_cluster"),+ partitions,+ Distributions.NONE,+ indexes,+ sortOrders);+```++</TabItem>+</Tabs>++### Table operations++Supported:+- Create table with engine, `ORDER BY`, optional partition, indexes, comments, default values, and `SETTINGS`.+- Add column (with nullable flag, default, comment, position).+- Rename column.+- Update column type/comment/default/position/nullability.+- Delete columns (with `IF EXISTS` support).+- Add primary or data-skipping indexes; drop data-skipping indexes.+- Update table comment.++Unsupported:+- Changing engine after creation.+- Removing table properties or arbitrary `ALTER TABLE ... SETTINGS`.+- Auto-increment columns.++See [Manage Relational Metadata Using Gravitino](./manage-relational-metadata-using-gravitino.md#table-operations) for common JDBC semantics.diff --git a/docs/manage-relational-metadata-using-gravitino.md b/docs/manage-relational-metadata-using-gravitino.mdindex bf58831e8f..b8237ce687 100644--- a/docs/manage-relational-metadata-using-gravitino.md+++ b/docs/manage-relational-metadata-using-gravitino.md@@ -24,6 +24,7 @@ For more details, please refer to the related doc.- [**Apache Doris**](./jdbc-doris-catalog.md)- [**StarRocks**](./jdbc-starrocks-catalog.md)- [**OceanBase**](./jdbc-oceanbase-catalog.md)+- [**ClickHouse**](./jdbc-clickhouse-catalog.md)- [**Apache Iceberg**](./lakehouse-iceberg-catalog.md)- [**Apache Paimon**](./lakehouse-paimon-catalog.md)- [**Apache Hudi**](./lakehouse-hudi-catalog.md)@@ -123,6 +124,7 @@ Currently, Gravitino supports the following catalog providers:| `jdbc-doris` | [Doris catalog property](./jdbc-doris-catalog.md#catalog-properties) || `jdbc-oceanbase` | [OceanBase catalog property](./jdbc-oceanbase-catalog.md#catalog-properties) || `jdbc-starrocks` | [StarRocks catalog property](./jdbc-starrocks-catalog.md#catalog-properties) |+| `jdbc-clickhouse` | [ClickHouse catalog property](./jdbc-clickhouse-catalog.md#catalog-properties) || `lakehouse-generic` | [Lakehouse generic catalog property](./lakehouse-generic-catalog.md#catalog-properties) |### Load a catalog@@ -497,17 +499,18 @@ catalog.as_schemas().create_schema(name="schema",Currently, Gravitino supports the following schema property:-| Catalog provider | Schema property |-|---------------------|------------------------------------------------------------------------------|-| `hive` | [Hive schema property](./apache-hive-catalog.md#schema-properties) |-| `lakehouse-iceberg` | [Iceberg scheme property](./lakehouse-iceberg-catalog.md#schema-properties) |-| `lakehouse-paimon` | [Paimon scheme property](./lakehouse-paimon-catalog.md#schema-properties) |-| `lakehouse-hudi` | [Hudi scheme property](./lakehouse-hudi-catalog.md#schema-properties) |-| `jdbc-mysql` | [MySQL schema property](./jdbc-mysql-catalog.md#schema-properties) |-| `jdbc-postgresql` | [PostgreSQL schema property](./jdbc-postgresql-catalog.md#schema-properties) |-| `jdbc-doris` | [Doris schema property](./jdbc-doris-catalog.md#schema-properties) |-| `jdbc-oceanbase` | [OceanBase schema property](./jdbc-oceanbase-catalog.md#schema-properties) |-| `jdbc-starrocks` | [StarRocks schema property](./jdbc-starrocks-catalog.md#schema-properties) |+| Catalog provider | Schema property |+|---------------------|---------------------------------------------------------------------------------------|+| `hive` | [Hive schema property](./apache-hive-catalog.md#schema-properties) |+| `lakehouse-iceberg` | [Iceberg scheme property](./lakehouse-iceberg-catalog.md#schema-properties) |+| `lakehouse-paimon` | [Paimon scheme property](./lakehouse-paimon-catalog.md#schema-properties) |+| `lakehouse-hudi` | [Hudi scheme property](./lakehouse-hudi-catalog.md#schema-properties) |+| `jdbc-mysql` | [MySQL schema property](./jdbc-mysql-catalog.md#schema-properties) |+| `jdbc-postgresql` | [PostgreSQL schema property](./jdbc-postgresql-catalog.md#schema-properties) |+| `jdbc-doris` | [Doris schema property](./jdbc-doris-catalog.md#schema-properties) |+| `jdbc-oceanbase` | [OceanBase schema property](./jdbc-oceanbase-catalog.md#schema-properties) |+| `jdbc-starrocks` | [StarRocks schema property](./jdbc-starrocks-catalog.md#schema-properties) |+| `jdbc-clickhouse` | [ClickHouse schema property](./jdbc-clickhouse-catalog.md#schema-properties) || `lakehouse-generic` | [Lakehouse generic schema property](./lakehouse-generic-catalog.md#schema-properties) |### Load a schema@@ -977,18 +980,19 @@ When defining a table column, you can specify a [literal](./expression.md#literaThe following is a table of the column default value that Gravitino supports for different catalogs:-| Catalog provider | Supported default value |-|---------------------|-------------------------|-| `hive` | ✘ |-| `lakehouse-iceberg` | ✘ |-| `lakehouse-paimon` | ✘ |-| `lakehouse-hudi` | ✘ |-| `jdbc-mysql` | ✔ |-| `jdbc-postgresql` | ✔ |-| `jdbc-doris` | ✔ |-| `jdbc-oceanbase` | ✔ |-| `jdbc-starrocks` | ✔ |-| `lakehouse-generic` | ✘ |+| Catalog provider | Supported default value |+|----------------------|-------------------------|+| `hive` | ✘ |+| `lakehouse-iceberg` | ✘ |+| `lakehouse-paimon` | ✘ |+| `lakehouse-hudi` | ✘ |+| `jdbc-mysql` | ✔ |+| `jdbc-postgresql` | ✔ |+| `jdbc-doris` | ✔ |+| `jdbc-oceanbase` | ✔ |+| `jdbc-starrocks` | ✔ |+| `jdbc-clickhouse` | ✔ |+| `lakehouse-generic` | ✘ |#### Table column auto-increment@@ -1006,24 +1010,26 @@ The following table shows the column auto-increment that Gravitino supports for| `jdbc-doris` | ✘ || `jdbc-oceanbase` | ✔([limitations](./jdbc-oceanbase-catalog.md#table-column-auto-increment)) || `jdbc-starrocks` | ✔ |-| `lakehouse-generic` | ✘ |+| `jdbc-clickhouse` | ✘ |+| `lakehouse-generic` | ✘ |#### Table property and type mappingThe following is the table property that Gravitino supports:-| Catalog provider | Table property | Type mapping |-|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|-| `hive` | [Hive table property](./apache-hive-catalog.md#table-properties) | [Hive type mapping](./apache-hive-catalog.md#table-column-types) |-| `lakehouse-iceberg` | [Iceberg table property](./lakehouse-iceberg-catalog.md#table-properties) | [Iceberg type mapping](./lakehouse-iceberg-catalog.md#table-column-types) |-| `lakehouse-paimon` | [Paimon table property](./lakehouse-paimon-catalog.md#table-properties) | [Paimon type mapping](./lakehouse-paimon-catalog.md#table-column-types) |-| `lakehouse-hudi` | [Hudi table property](./lakehouse-hudi-catalog.md#table-properties) | [Hudi type mapping](./lakehouse-hudi-catalog.md#table-column-types) |-| `jdbc-mysql` | [MySQL table property](./jdbc-mysql-catalog.md#table-properties) | [MySQL type mapping](./jdbc-mysql-catalog.md#table-column-types) |-| `jdbc-postgresql` | [PostgreSQL table property](./jdbc-postgresql-catalog.md#table-properties) | [PostgreSQL type mapping](./jdbc-postgresql-catalog.md#table-column-types) |-| `jdbc-doris` | [Doris table property](./jdbc-doris-catalog.md#table-properties) | [Doris type mapping](./jdbc-doris-catalog.md#table-column-types) |-| `jdbc-oceanbase` | [OceanBase table property](./jdbc-oceanbase-catalog.md#table-properties) | [OceanBase type mapping](./jdbc-oceanbase-catalog.md#table-column-types) |-| `jdbc-starrocks` | [StarRocks table property](./jdbc-starrocks-catalog.md#table-properties) | [StarRocks type mapping](./jdbc-starrocks-catalog.md#table-column-types) |-| `lakehouse-generic` | Lakehouse generic table property depends on specific table implementation, for Lance table, please refer to [doc](./lakehouse-generic-lance-table.md#table-properties), other table format, please refer to related docs. | Lakehouse generic type mapping. Similar to table properties, for Lance table, please refer to [docs](./lakehouse-generic-lance-table.md#data-type-mappings) |+| Catalog provider | Table property | Type mapping |+|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|+| `hive` | [Hive table property](./apache-hive-catalog.md#table-properties) | [Hive type mapping](./apache-hive-catalog.md#table-column-types) |+| `lakehouse-iceberg` | [Iceberg table property](./lakehouse-iceberg-catalog.md#table-properties) | [Iceberg type mapping](./lakehouse-iceberg-catalog.md#table-column-types) |+| `lakehouse-paimon` | [Paimon table property](./lakehouse-paimon-catalog.md#table-properties) | [Paimon type mapping](./lakehouse-paimon-catalog.md#table-column-types) |+| `lakehouse-hudi` | [Hudi table property](./lakehouse-hudi-catalog.md#table-properties) | [Hudi type mapping](./lakehouse-hudi-catalog.md#table-column-types) |+| `jdbc-mysql` | [MySQL table property](./jdbc-mysql-catalog.md#table-properties) | [MySQL type mapping](./jdbc-mysql-catalog.md#table-column-types) |+| `jdbc-postgresql` | [PostgreSQL table property](./jdbc-postgresql-catalog.md#table-properties) | [PostgreSQL type mapping](./jdbc-postgresql-catalog.md#table-column-types) |+| `jdbc-doris` | [Doris table property](./jdbc-doris-catalog.md#table-properties) | [Doris type mapping](./jdbc-doris-catalog.md#table-column-types) |+| `jdbc-oceanbase` | [OceanBase table property](./jdbc-oceanbase-catalog.md#table-properties) | [OceanBase type mapping](./jdbc-oceanbase-catalog.md#table-column-types) |+| `jdbc-starrocks` | [StarRocks table property](./jdbc-starrocks-catalog.md#table-properties) | [StarRocks type mapping](./jdbc-starrocks-catalog.md#table-column-types) |+| `jdbc-clickhouse` | [ClickHouse table property](./jdbc-clickhouse-catalog.md#table-properties) | [ClickHouse type mapping](./jdbc-clickhouse-catalog.md#table-column-types) |+| `lakehouse-generic` | Lakehouse generic table property depends on specific table implementation, for Lance table, please refer to [doc](./lakehouse-generic-lance-table.md#table-properties), other table format, please refer to related docs. | Lakehouse generic type mapping. Similar to table properties, for Lance table, please refer to [docs](./lakehouse-generic-lance-table.md#data-type-mappings) |#### Table partitioning, distribution, sort ordering and indexesdiff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ClickHouseContainer.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ClickHouseContainer.javaindex c41425f0fc..b24196ee4a 100644--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ClickHouseContainer.java+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ClickHouseContainer.java@@ -20,6 +20,7 @@ package org.apache.gravitino.integration.test.container;import static java.lang.String.format;+import com.google.common.collect.ImmutableMap;import com.google.common.collect.ImmutableSet;import java.sql.Connection;import java.sql.DriverManager;@@ -43,8 +44,12 @@ public class ClickHouseContainer extends BaseContainer {public static final String DEFAULT_IMAGE = "clickhouse:24.8.14";public static final String HOST_NAME = "gravitino-ci-clickhouse";public static final int CLICKHOUSE_PORT = 8123;+ public static final int CLICKHOUSE_NATIVE_PORT = 9000;public static final String USER_NAME = "default";public static final String PASSWORD = "default";+ public static final String DEFAULT_CLUSTER_NAME = "gravitino_cluster";+ public static final String ZOOKEEPER_HOST_KEY = "ZOOKEEPER_HOST";+ public static final String ZOOKEEPER_PORT_KEY = "ZOOKEEPER_PORT";public static Builder builder() {return new Builder();@@ -116,7 +121,8 @@ public class ClickHouseContainer extends BaseContainer {LOG.info(String.format("clickHouse container database %s has been created", testDatabaseName));} catch (Exception e) {- LOG.error(e.getMessage(), e);+ throw new RuntimeException(+ "Failed to create database on clickHouse container: " + e.getMessage(), e);}}@@ -141,18 +147,61 @@ public class ClickHouseContainer extends BaseContainer {return DriverManager.getDriver(getJdbcUrl(testDatabaseName)).getClass().getName();}+ public void createDatabaseOnCluster(TestDatabaseName testDatabaseName, String clusterName) {+ String clickHouseJdbcUrl =+ StringUtils.substring(+ getJdbcUrl(testDatabaseName), 0, getJdbcUrl(testDatabaseName).lastIndexOf("/"));++ try (Connection connection =+ DriverManager.getConnection(clickHouseJdbcUrl, USER_NAME, getPassword());+ Statement statement = connection.createStatement()) {++ String query =+ String.format(+ "CREATE DATABASE IF NOT EXISTS %s ON CLUSTER %s;", testDatabaseName, clusterName);+ statement.execute(query);+ LOG.info(+ String.format(+ "clickHouse cluster database %s has been created with cluster %s",+ testDatabaseName, clusterName));+ } catch (Exception e) {+ throw new RuntimeException(+ "Failed to create database on clickHouse cluster: " + e.getMessage(), e);+ }+ }+public static class Builder extends BaseContainer.Builder<Builder, ClickHouseContainer> {+ private String remoteServersConfigPath;+private Builder() {this.image = DEFAULT_IMAGE;this.hostName = HOST_NAME;this.exposePorts = ImmutableSet.of(CLICKHOUSE_PORT);}+ public Builder withRemoteServersConfig(String configPath) {+ this.remoteServersConfigPath = configPath;+ return this;+ }+@Overridepublic ClickHouseContainer build() {+ ImmutableSet<Integer> ports =+ remoteServersConfigPath == null+ ? ImmutableSet.copyOf(exposePorts)+ : ImmutableSet.of(CLICKHOUSE_PORT, CLICKHOUSE_NATIVE_PORT);+ ImmutableMap<String, String> mountFiles =+ remoteServersConfigPath == null+ ? ImmutableMap.copyOf(filesToMount)+ : ImmutableMap.<String, String>builder()+ .putAll(filesToMount)+ .put(+ "/etc/clickhouse-server/config.d/remote_servers.xml", remoteServersConfigPath)+ .build();+return new ClickHouseContainer(- image, hostName, exposePorts, extraHosts, filesToMount, envVars, network);+ image, hostName, ports, extraHosts, mountFiles, envVars, network);}}}diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.javaindex f52c0ca064..ede2d33766 100644--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java@@ -30,11 +30,17 @@ import java.io.Closeable;import java.io.IOException;import java.net.InetAddress;import java.nio.ByteBuffer;+import java.nio.charset.StandardCharsets;+import java.nio.file.FileSystems;+import java.nio.file.Files;+import java.nio.file.Paths;+import java.nio.file.attribute.PosixFilePermission;import java.util.EnumMap;import java.util.List;import java.util.Map;import java.util.NoSuchElementException;import java.util.Objects;+import java.util.Set;import org.apache.gravitino.integration.test.util.CloseableGroup;import org.apache.gravitino.integration.test.util.CommandExecutor;import org.apache.gravitino.integration.test.util.ITUtils;@@ -76,6 +82,8 @@ public class ContainerSuite implements Closeable {new EnumMap<>(PGImageName.class);private static volatile OceanBaseContainer oceanBaseContainer;private static volatile ClickHouseContainer clickHouseContainer;+ private static volatile ClickHouseContainer clickHouseClusterContainer;+ private static volatile ZooKeeperContainer zooKeeperContainer;private static volatile GravitinoLocalStackContainer gravitinoLocalStackContainer;@@ -560,10 +568,98 @@ public class ContainerSuite implements Closeable {}}+ public void startClickHouseClusterContainer(+ TestDatabaseName testDatabaseName, String remoteServersTemplatePath) {+ if (clickHouseClusterContainer == null) {+ synchronized (ContainerSuite.class) {+ if (clickHouseClusterContainer == null) {+ initIfNecessary();+ startZooKeeperContainer();+ String zkHost = zooKeeperContainer.getContainerIpAddress();+ String resolvedConfigPath = prepareRemoteServersConfig(remoteServersTemplatePath, zkHost);+ ClickHouseContainer.Builder clickHouseBuilder =+ ClickHouseContainer.builder()+ .withHostName("gravitino-ci-clickhouse-cluster")+ .withEnvVars(+ ImmutableMap.<String, String>builder()+ .put("CLICKHOUSE_PASSWORD", ClickHouseContainer.PASSWORD)+ .build())+ .withRemoteServersConfig(resolvedConfigPath)+ .withExposePorts(+ ImmutableSet.of(+ ClickHouseContainer.CLICKHOUSE_PORT,+ ClickHouseContainer.CLICKHOUSE_NATIVE_PORT))+ .withNetwork(network);++ ClickHouseContainer container = closer.register(clickHouseBuilder.build());+ container.start();+ clickHouseClusterContainer = container;+ }+ }+ }+ synchronized (ClickHouseContainer.class) {+ clickHouseClusterContainer.createDatabaseOnCluster(+ testDatabaseName, ClickHouseContainer.DEFAULT_CLUSTER_NAME);+ }+ }++ private String prepareRemoteServersConfig(String templatePath, String zkHost) {+ try {+ String content =+ new String(Files.readAllBytes(Paths.get(templatePath)), StandardCharsets.UTF_8);+ String replaced =+ content+ .replace("${ZOOKEEPER_HOST}", zkHost)+ .replace("${ZOOKEEPER_PORT}", String.valueOf(ZooKeeperContainer.ZK_PORT));+ java.nio.file.Path tempFile = Files.createTempFile("remote_servers", ".xml").toAbsolutePath();+ Files.writeString(tempFile, replaced);+ // Change the access mode of temFile to 644 to avoid permission issues when ClickHouse+ // container read the file.+ if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {+ Files.setPosixFilePermissions(+ tempFile,+ Set.of(+ PosixFilePermission.OWNER_READ,+ PosixFilePermission.OWNER_WRITE,+ PosixFilePermission.GROUP_READ,+ PosixFilePermission.OTHERS_READ));+ }+ return tempFile.toString();+ } catch (IOException e) {+ throw new RuntimeException("Failed to prepare remote_servers.xml", e);+ }+ }++ public void startZooKeeperContainer() {+ if (zooKeeperContainer == null) {+ synchronized (ContainerSuite.class) {+ if (zooKeeperContainer == null) {+ initIfNecessary();+ ZooKeeperContainer.Builder zkBuilder =+ ZooKeeperContainer.builder()+ .withHostName(ZooKeeperContainer.HOST_NAME)+ .withExposePorts(ImmutableSet.of(ZooKeeperContainer.ZK_PORT))+ .withNetwork(network);+ ZooKeeperContainer container = closer.register(zkBuilder.build());+ container.start();+ zooKeeperContainer = container;+ }+ }+ }+ }+public ClickHouseContainer getClickHouseContainer() {return clickHouseContainer;}+ public ClickHouseContainer getClickHouseClusterContainer() {+ return clickHouseClusterContainer;+ }++ public ZooKeeperContainer getZooKeeperContainer() {+ return zooKeeperContainer;+ }+public GravitinoLocalStackContainer getLocalStackContainer() {return gravitinoLocalStackContainer;}diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ZooKeeperContainer.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ZooKeeperContainer.javanew file mode 100644index 0000000000..73125773da--- /dev/null+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ZooKeeperContainer.java@@ -0,0 +1,82 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.gravitino.integration.test.container;++import com.google.common.collect.ImmutableSet;+import java.time.Duration;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;+import org.testcontainers.containers.Network;++public class ZooKeeperContainer extends BaseContainer {+ private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperContainer.class);++ public static final String DEFAULT_IMAGE = "zookeeper:3.8.0";+ public static final String HOST_NAME = "gravitino-ci-zookeeper";+ public static final int ZK_PORT = 2181;++ public static Builder builder() {+ return new Builder();+ }++ protected ZooKeeperContainer(+ String image,+ String hostName,+ Set<Integer> ports,+ Map<String, String> extraHosts,+ Map<String, String> filesToMount,+ Map<String, String> envVars,+ Optional<Network> network) {+ super(image, hostName, ports, extraHosts, filesToMount, envVars, network);+ }++ @Override+ protected void setupContainer() {+ super.setupContainer();+ withStartupTimeout(Duration.ofMinutes(2));+ withLogConsumer(new PrintingContainerLog(String.format("%-14s| ", "zookeeper")));+ }++ @Override+ protected boolean checkContainerStatus(int retryLimit) {+ // Testcontainers wait strategy already ensures the port is ready.+ LOG.info("ZooKeeper container started");+ return true;+ }++ public String getZkConnectString() {+ return String.format("%s:%d", getContainerIpAddress(), ZK_PORT);+ }++ public static class Builder extends BaseContainer.Builder<Builder, ZooKeeperContainer> {+ private Builder() {+ this.image = DEFAULT_IMAGE;+ this.hostName = HOST_NAME;+ this.exposePorts = ImmutableSet.of(ZK_PORT);+ }++ @Override+ public ZooKeeperContainer build() {+ return new ZooKeeperContainer(+ image, hostName, exposePorts, extraHosts, filesToMount, envVars, network);+ }+ }+}diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.javaindex d6be20683d..73ec2fa3ce 100644--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java@@ -110,16 +110,20 @@ public class BaseIT {protected boolean ignoreLanceAuxRestService = true;- public String DOWNLOAD_MYSQL_JDBC_DRIVER_URL =+ public static String DOWNLOAD_MYSQL_JDBC_DRIVER_URL ="https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.26/mysql-connector-java-8.0.26.jar";public static final String DOWNLOAD_POSTGRESQL_JDBC_DRIVER_URL ="https://jdbc.postgresql.org/download/postgresql-42.7.0.jar";+ public static final String DOWNLOAD_CLICKHOUSE_JDBC_DRIVER_URL =+ "https://repo1.maven.org/maven2/com/clickhouse/clickhouse-jdbc/0.7.1/clickhouse-jdbc-0.7.1-all.jar";+public static final Map<String, Pattern> SUPPORTED_CLEAN_CONFLICTS_DRIVER_TYPES =ImmutableMap.of("mysql", Pattern.compile("mysql-connector-java-([\\d.]+)\\.jar"),- "postgresql", Pattern.compile("postgresql-([\\d.]+)\\.jar"));+ "postgresql", Pattern.compile("postgresql-([\\d.]+)\\.jar"),+ "clickhouse", Pattern.compile("clickhouse-jdbc-([\\d.]+)(-all)?\\.jar"));private TestDatabaseName META_DATA;private MySQLContainer MYSQL_CONTAINER;@@ -194,7 +198,11 @@ public class BaseIT {}private void setupJdbcDrivers() throws IOException {- String[] driverUrls = {DOWNLOAD_MYSQL_JDBC_DRIVER_URL, DOWNLOAD_POSTGRESQL_JDBC_DRIVER_URL};+ String[] driverUrls = {+ DOWNLOAD_MYSQL_JDBC_DRIVER_URL,+ DOWNLOAD_POSTGRESQL_JDBC_DRIVER_URL,+ DOWNLOAD_CLICKHOUSE_JDBC_DRIVER_URL+ };String[] dirs = getJdbcDriverDownloadDirs();downloadJdbcDrivers(driverUrls, dirs);cleanJdbcDriverConflicts(driverUrls, dirs);diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.javaindex dd5ac8ea61..06ecb30154 100644--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.java+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.java@@ -119,6 +119,7 @@ public enum TestDatabaseName {CLICKHOUSE_CLICKHOUSE_ABSTRACT_IT,CLICKHOUSE_CATALOG_CLICKHOUSE_IT,CLICKHOUSE_AUDIT_CATALOG_CLICKHOUSE_IT,+ CLICKHOUSE_CLUSTER_CLICKHOUSE_IT,/** Represents the PostgreSQL database for partition statistics integration tests. */PG_TEST_PARTITION_STATS {