This is an automated email from the ASF dual-hosted git repository.
diqiu50 pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/branch-1.3 by this push:
new 9e6da71940 [Cherry-pick to branch-1.3] [#12787] fix(clickhouse):
preserve SET index parameters on table load (#12826) (#14901)
9e6da71940 is described below
commit 9e6da7194029e6cdca77f6c475452bb1ebcba149
Author: Yuhui <[email protected]>
AuthorDate: Wed Nov 11 22:45:57 2026 +0800
[Cherry-pick to branch-1.3] [#12787] fix(clickhouse): preserve SET index
parameters on table load (#12826) (#14901)
**Cherry-pick Information:**
- Original commit: 93e487707ccf86e16e6dff2dc78c8673ea4cc5fa
- Target branch: `branch-1.3`
- Status: ✅ Conflicts resolved
- Note: Only the SET index part is backported. The
`ngrambf_v1`/`tokenbf_v1` index types (#12026) do not exist on this
branch, so bloom-filter parameter parsing is left out and the related
unit tests use SET or `minmax` indexes instead.
Signed-off-by: jiangxt2 <[email protected]>
Co-authored-by: StormSpirit <[email protected]>
---
.../operations/ClickHouseTableOperations.java | 204 +++++++++++-
.../integration/test/CatalogClickHouseIT.java | 117 +++++++
.../TestClickHouseTableOperationsUnit.java | 361 +++++++++++++++++++++
3 files changed, 665 insertions(+), 17 deletions(-)
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.java
index 92564dcf05..398d11316b 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
@@ -31,6 +31,7 @@ import static
org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
@@ -99,6 +100,19 @@ public class ClickHouseTableOperations extends
JdbcTableOperations {
/** Default GRANULARITY for data skipping indexes, matching ClickHouse's own
default. */
private static final long DEFAULT_INDEX_GRANULARITY = 1;
+ private static final BigInteger MIN_SET_MAX_VALUES = BigInteger.ZERO;
+ private static final BigInteger MAX_SET_MAX_VALUES =
BigInteger.valueOf(Integer.MAX_VALUE);
+ private static final String SET_MAX_VALUES_RANGE =
+ "[%s, %s]".formatted(MIN_SET_MAX_VALUES, MAX_SET_MAX_VALUES);
+ private static final Pattern SET_MAX_VALUES_PATTERN =
Pattern.compile("[+-]?[0-9]+");
+
+ private static final String SECONDARY_INDEX_QUERY =
+ "SELECT name, type, type_full, expr, granularity FROM
system.data_skipping_indices "
+ + "WHERE database = ? AND table = ? ORDER BY name";
+ private static final String LEGACY_SECONDARY_INDEX_QUERY =
+ "SELECT name, type, expr, granularity FROM system.data_skipping_indices "
+ + "WHERE database = ? AND table = ? ORDER BY name";
+
private static final Set<ENGINE> GENERIC_ENGINE_PARAMETER_ENGINES =
Collections.unmodifiableSet(
EnumSet.of(
@@ -1713,33 +1727,47 @@ public class ClickHouseTableOperations extends
JdbcTableOperations {
private List<Index> getSecondaryIndexes(
Connection connection, String databaseName, String tableName) throws
SQLException {
+ try {
+ return querySecondaryIndexes(
+ connection, databaseName, tableName, SECONDARY_INDEX_QUERY, true);
+ } catch (SQLException e) {
+ if (!isMissingTypeFullColumn(e)) {
+ throw e;
+ }
+ LOG.warn(
+ "ClickHouse server does not expose
system.data_skipping_indices.type_full; "
+ + "falling back to the legacy secondary-index query for {}.{}",
+ databaseName,
+ tableName);
+ return querySecondaryIndexes(
+ connection, databaseName, tableName, LEGACY_SECONDARY_INDEX_QUERY,
false);
+ }
+ }
+
+ private List<Index> querySecondaryIndexes(
+ Connection connection,
+ String databaseName,
+ String tableName,
+ String query,
+ boolean includesTypeFull)
+ throws SQLException {
List<Index> secondaryIndexes = new ArrayList<>();
- try (PreparedStatement preparedStatement =
- connection.prepareStatement(
- "SELECT name, type, expr, granularity FROM
system.data_skipping_indices "
- + "WHERE database = ? AND table = ? ORDER BY name")) {
+ try (PreparedStatement preparedStatement =
connection.prepareStatement(query)) {
preparedStatement.setString(1, databaseName);
preparedStatement.setString(2, tableName);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
String name = resultSet.getString("name");
String type = resultSet.getString("type");
+ String parameterSource = includesTypeFull ?
resultSet.getString("type_full") : type;
+ String parameterSourceName = includesTypeFull ? "type_full" :
"legacy type";
String expression = resultSet.getString("expr");
long granularity = resultSet.getLong("granularity");
+ Index.IndexType indexType;
+ String[][] fields;
try {
- String[][] fields = parseIndexFields(expression);
- if (ArrayUtils.isEmpty(fields)) {
- continue;
- }
- // Only include granularity in properties when it differs from the
default,
- // so that indexes created without explicit granularity have empty
properties
- // and match the original creation state (avoids false
index-change diffs).
- Map<String, String> properties =
- granularity == DEFAULT_INDEX_GRANULARITY
- ? Map.of()
- : Map.of(GRANULARITY, String.valueOf(granularity));
- secondaryIndexes.add(
- Indexes.of(getClickHouseIndexType(type), name, fields,
properties));
+ indexType = getClickHouseIndexType(type);
+ fields = parseIndexFields(expression);
} catch (IllegalArgumentException e) {
LOG.warn(
"Skip unsupported data skipping index {} for {}.{} with
expression {}",
@@ -1747,7 +1775,50 @@ public class ClickHouseTableOperations extends
JdbcTableOperations {
databaseName,
tableName,
expression);
+ continue;
}
+ if (ArrayUtils.isEmpty(fields)) {
+ continue;
+ }
+
+ Map<String, String> setProperties = Collections.emptyMap();
+ if (indexType == Index.IndexType.DATA_SKIPPING_SET) {
+ try {
+ setProperties =
+ parseSetPropertiesForQuery(indexType, parameterSource, name,
!includesTypeFull);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(
+ "Failed to load data skipping index '%s' from %s.%s with %s
'%s': %s"
+ .formatted(
+ name,
+ databaseName,
+ tableName,
+ parameterSourceName,
+ parameterSource,
+ e.getMessage()),
+ e);
+ }
+ if (!includesTypeFull
+ && setProperties.isEmpty()
+ && !StringUtils.contains(parameterSource, "(")) {
+ LOG.warn(
+ "Legacy ClickHouse metadata does not expose SET max-values
parameters for "
+ + "SET index '{}' on {}.{}; loaded Index.properties() is
incomplete",
+ name,
+ databaseName,
+ tableName);
+ }
+ }
+
+ // Only include granularity in properties when it differs from the
default,
+ // so that indexes created without explicit granularity have empty
properties
+ // and match the original creation state (avoids false index-change
diffs).
+ Map<String, String> properties = new HashMap<>();
+ if (granularity != DEFAULT_INDEX_GRANULARITY) {
+ properties.put(GRANULARITY, String.valueOf(granularity));
+ }
+ properties.putAll(setProperties);
+ secondaryIndexes.add(Indexes.of(indexType, name, fields,
properties));
}
}
}
@@ -1755,6 +1826,22 @@ public class ClickHouseTableOperations extends
JdbcTableOperations {
return secondaryIndexes;
}
+ private static boolean isMissingTypeFullColumn(SQLException exception) {
+ for (SQLException current = exception; current != null; current =
current.getNextException()) {
+ for (Throwable cause = current; cause != null; cause = cause.getCause())
{
+ String message = StringUtils.lowerCase(cause.getMessage());
+ if (message != null
+ && message.contains("type_full")
+ && (message.contains("unknown")
+ || message.contains("missing")
+ || message.contains("column"))) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
/**
* Maps a ClickHouse data skipping index type string to the corresponding
Gravitino {@link
* Index.IndexType}. Returns {@code DATA_SKIPPING_MINMAX} for blank/null
input (ClickHouse
@@ -1789,6 +1876,89 @@ public class ClickHouseTableOperations extends
JdbcTableOperations {
}
}
+ /**
+ * Parses the single positional parameter returned by ClickHouse for a SET
data skipping index.
+ *
+ * @param indexType the mapped Gravitino index type
+ * @param typeFull the complete ClickHouse index type expression
+ * @param indexName the index name for validation messages
+ * @return the SET index properties, or an empty map for non-SET index types
and {@code set(0)}
+ * @throws IllegalArgumentException if a SET index has malformed or
out-of-range parameters
+ */
+ @VisibleForTesting
+ static Map<String, String> parseSetProperties(
+ Index.IndexType indexType, String typeFull, String indexName) {
+ if (indexType != Index.IndexType.DATA_SKIPPING_SET) {
+ return Collections.emptyMap();
+ }
+
+ String normalizedTypeFull = StringUtils.trimToEmpty(typeFull);
+ int paramsStart = normalizedTypeFull.indexOf('(');
+ int paramsEnd = normalizedTypeFull.lastIndexOf(')');
+ Preconditions.checkArgument(
+ paramsStart > 0 && paramsEnd == normalizedTypeFull.length() - 1,
+ "Invalid SET metadata '%s' for index '%s'",
+ typeFull,
+ indexName);
+ Preconditions.checkArgument(
+ StringUtils.equalsIgnoreCase(
+ DATA_SKIPPING_SET, normalizedTypeFull.substring(0,
paramsStart).trim()),
+ "SET metadata '%s' does not match SET index '%s'",
+ typeFull,
+ indexName);
+
+ String[] params = normalizedTypeFull.substring(paramsStart + 1,
paramsEnd).split(",", -1);
+ Preconditions.checkArgument(
+ params.length == 1,
+ "Invalid SET metadata '%s' for SET index '%s': expected one parameter
but got %s",
+ typeFull,
+ indexName,
+ params.length);
+
+ String rawValue = params[0].trim();
+ Preconditions.checkArgument(
+ !rawValue.isEmpty(),
+ "Invalid SET metadata '%s' for SET index '%s': set_max_values is
required",
+ typeFull,
+ indexName);
+ Preconditions.checkArgument(
+ SET_MAX_VALUES_PATTERN.matcher(rawValue).matches(),
+ "Invalid SET metadata '%s' for SET index '%s': set_max_values '%s' is
not a valid decimal integer",
+ typeFull,
+ indexName,
+ rawValue);
+ BigInteger value;
+ try {
+ value = new BigInteger(rawValue);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ "Invalid SET metadata '%s' for SET index '%s': set_max_values '%s'
is not a valid decimal integer"
+ .formatted(typeFull, indexName, rawValue),
+ e);
+ }
+
+ if (value.compareTo(MIN_SET_MAX_VALUES) < 0 ||
value.compareTo(MAX_SET_MAX_VALUES) > 0) {
+ throw new IllegalArgumentException(
+ "Invalid SET metadata '%s' for SET index '%s': set_max_values '%s'
is outside supported range %s"
+ .formatted(typeFull, indexName, rawValue, SET_MAX_VALUES_RANGE));
+ }
+ if (value.equals(MIN_SET_MAX_VALUES)) {
+ return Collections.emptyMap();
+ }
+ return Map.of(SET_MAX_VALUES, value.toString());
+ }
+
+ private static Map<String, String> parseSetPropertiesForQuery(
+ Index.IndexType indexType,
+ String parameterSource,
+ String indexName,
+ boolean allowBareLegacyType) {
+ if (allowBareLegacyType && !StringUtils.contains(parameterSource, "(")) {
+ return Collections.emptyMap();
+ }
+ return parseSetProperties(indexType, parameterSource, indexName);
+ }
+
private String buildDataSkippingIndexDdl(
String indexName, String fieldStr, String typeName, int granularity) {
Preconditions.checkArgument(
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.java
index 8891377e4b..d737376109 100644
---
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.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.catalog.clickhouse.integration.test;
+import static
org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.IndexConstants.GRANULARITY;
+import static
org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.IndexConstants.SET_MAX_VALUES;
import static
org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE;
import static
org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE.MERGETREE;
import static
org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE.REPLACINGMERGETREE;
@@ -616,6 +618,121 @@ public class CatalogClickHouseIT extends BaseIT {
&& Arrays.deepEquals(idx.fieldNames(), new String[][]
{{"user_id"}})));
}
+ @Test
+ void testSetIndexParameterReadbackLifecycle() {
+ TableCatalog tableCatalog = catalog.asTableCatalog();
+ Column[] columns =
+ new Column[] {
+ Column.of("id", Types.LongType.get(), "id", false, false,
DEFAULT_VALUE_NOT_SET),
+ Column.of("value", Types.StringType.get(), "value", false, false,
DEFAULT_VALUE_NOT_SET)
+ };
+ SortOrder[] sortOrders = getSortOrders("id");
+ Map<String, String> setProperties = Map.of(SET_MAX_VALUES, "100",
GRANULARITY, "3");
+
+ String tableName = GravitinoITUtils.genRandomName("set_readback");
+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, tableName);
+ tableCatalog.createTable(
+ tableIdentifier,
+ columns,
+ "SET index readback",
+ createProperties(),
+ Transforms.EMPTY_TRANSFORM,
+ Distributions.NONE,
+ sortOrders,
+ new Index[] {
+ Indexes.of(
+ Index.IndexType.DATA_SKIPPING_SET,
+ "idx_set",
+ new String[][] {{"value"}},
+ setProperties)
+ });
+
+ Table loaded = tableCatalog.loadTable(tableIdentifier);
+ assertSetIndexMetadata(loaded, "idx_set", setProperties);
+ assertSetIndexDdl(tableName, "set(100)", "GRANULARITY 3");
+ Index[] loadedIndexes = loaded.index();
+
+ String recreatedTableName =
GravitinoITUtils.genRandomName("set_recreated");
+ NameIdentifier recreatedIdentifier = NameIdentifier.of(schemaName,
recreatedTableName);
+ tableCatalog.createTable(
+ recreatedIdentifier,
+ columns,
+ "SET index recreated",
+ createProperties(),
+ Transforms.EMPTY_TRANSFORM,
+ Distributions.NONE,
+ sortOrders,
+ loadedIndexes);
+ Table recreated = tableCatalog.loadTable(recreatedIdentifier);
+ assertSetIndexMetadata(recreated, "idx_set", setProperties);
+ assertSetIndexDdl(recreatedTableName, "set(100)", "GRANULARITY 3");
+
+ tableCatalog.alterTable(
+ tableIdentifier,
+ TableChange.addIndex(
+ Index.IndexType.DATA_SKIPPING_SET,
+ "idx_set_alter",
+ new String[][] {{"value"}},
+ setProperties));
+ Table altered = tableCatalog.loadTable(tableIdentifier);
+ assertSetIndexMetadata(altered, "idx_set_alter", setProperties);
+ assertSetIndexDdl(tableName, "set(100)", "GRANULARITY 3");
+
+ String defaultTableName = GravitinoITUtils.genRandomName("set_default");
+ NameIdentifier defaultIdentifier = NameIdentifier.of(schemaName,
defaultTableName);
+ tableCatalog.createTable(
+ defaultIdentifier,
+ columns,
+ "SET index default",
+ createProperties(),
+ Transforms.EMPTY_TRANSFORM,
+ Distributions.NONE,
+ sortOrders,
+ new Index[] {
+ Indexes.of(
+ Index.IndexType.DATA_SKIPPING_SET, "idx_set_default", new
String[][] {{"value"}})
+ });
+ Table defaultLoaded = tableCatalog.loadTable(defaultIdentifier);
+ assertSetIndexMetadata(defaultLoaded, "idx_set_default", Map.of());
+ assertSetIndexDdl(defaultTableName, "set(0)");
+
+ String nativeTableName = GravitinoITUtils.genRandomName("set_native");
+ clickhouseService.executeQuery(
+ String.format(
+ "CREATE TABLE `%s`.`%s` ("
+ + " `id` UInt64,"
+ + " `value` String,"
+ + " INDEX `idx_native_set` `value` TYPE set(100) GRANULARITY
3"
+ + ") ENGINE = MergeTree ORDER BY id",
+ schemaName, nativeTableName));
+ Table nativeLoaded = tableCatalog.loadTable(NameIdentifier.of(schemaName,
nativeTableName));
+ assertSetIndexMetadata(nativeLoaded, "idx_native_set", setProperties);
+ }
+
+ private void assertSetIndexMetadata(
+ Table table, String indexName, Map<String, String> expectedProperties) {
+ Index index =
+ Arrays.stream(table.index())
+ .filter(candidate -> Objects.equals(indexName, candidate.name()))
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("Missing index " +
indexName));
+ Assertions.assertEquals(Index.IndexType.DATA_SKIPPING_SET, index.type());
+ Assertions.assertArrayEquals(new String[][] {{"value"}},
index.fieldNames());
+ Assertions.assertEquals(expectedProperties, index.properties());
+ }
+
+ private void assertSetIndexDdl(String tableName, String...
expectedFragments) {
+ String createSql =
+ clickhouseService.executeQueryForResult(
+ String.format("SHOW CREATE TABLE `%s`.`%s`", schemaName,
tableName));
+ String normalizedCreateSql = createSql.replaceAll("\\s+", "");
+ for (String expectedFragment : expectedFragments) {
+ Assertions.assertTrue(
+ normalizedCreateSql.contains(expectedFragment.replaceAll("\\s+",
"")),
+ "SHOW CREATE TABLE should contain " + expectedFragment + ": " +
createSql);
+ }
+ }
+
@Test
void testCreateAndLoadWithCustomGranularity() {
String table = GravitinoITUtils.genRandomName("granularity_roundtrip");
diff --git
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsUnit.java
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsUnit.java
index 83b4ca9f9e..f74667d142 100644
---
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsUnit.java
+++
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperationsUnit.java
@@ -787,6 +787,308 @@ public class TestClickHouseTableOperationsUnit {
Assertions.assertTrue(columnSql.contains("COMMENT COLUMN `id` ''"),
columnSql);
}
+ @Test
+ void testParseSetPropertiesNormalizesValuesAndOmitsDefault() {
+ Assertions.assertEquals(
+ Map.of("set_max_values", "100"),
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_SET, " set ( 00100 ) ", "idx_set"));
+ Assertions.assertTrue(
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_SET, "set(0)", "idx_set")
+ .isEmpty());
+ Assertions.assertTrue(
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_MINMAX, "minmax", "idx_minmax")
+ .isEmpty());
+ }
+
+ @Test
+ void testParseSetPropertiesAcceptsIntegerMaxValue() {
+ Assertions.assertEquals(
+ Map.of("set_max_values", String.valueOf(Integer.MAX_VALUE)),
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_SET, "set(" + Integer.MAX_VALUE +
")", "idx_set"));
+ }
+
+ @Test
+ void testParseSetPropertiesRejectsValuesOutsideIntegerRange() {
+ for (String value : List.of("-1", "2147483648", "18446744073709551615")) {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_SET, "set(" + value + ")",
"idx_set"));
+ Assertions.assertTrue(exception.getMessage().contains("outside supported
range"));
+ Assertions.assertTrue(exception.getMessage().contains(value));
+ Assertions.assertTrue(exception.getMessage().contains("[0,
2147483647]"));
+ Assertions.assertTrue(exception.getMessage().contains("idx_set"));
+ }
+ }
+
+ @Test
+ void testParseSetPropertiesRejectsMalformedMetadata() {
+ for (String typeFull : List.of("set()", "set(100, 200)", "set(abc)",
"set(100")) {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_SET, typeFull, "idx_bad"));
+ Assertions.assertTrue(exception.getMessage().contains("idx_bad"));
+ }
+
+ IllegalArgumentException wrongTypeException =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ ClickHouseTableOperations.parseSetProperties(
+ Index.IndexType.DATA_SKIPPING_SET, "tokenbf_v1(100)",
"idx_bad"));
+ Assertions.assertTrue(wrongTypeException.getMessage().contains("idx_bad"));
+ }
+
+ @Test
+ void testGetIndexesFailsOnOutOfRangeSetMetadata() throws Exception {
+ for (String value : List.of("2147483648", "18446744073709551615")) {
+ IllegalArgumentException exception =
getIndexesFailureForSetTypeFull("set(" + value + ")");
+ Assertions.assertTrue(exception.getMessage().contains("idx_overflow"));
+ Assertions.assertTrue(exception.getMessage().contains("type_full"));
+ Assertions.assertTrue(exception.getMessage().contains(value));
+ Assertions.assertTrue(exception.getMessage().contains("outside supported
range"));
+ Assertions.assertTrue(exception.getMessage().contains("[0,
2147483647]"));
+ }
+ }
+
+ @Test
+ void testGetIndexesReadsSetPropertiesWithGranularity() throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement secondaryStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet secondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(secondaryRs.next()).thenReturn(true, false);
+ Mockito.when(secondaryStmt.executeQuery()).thenReturn(secondaryRs);
+ Mockito.when(secondaryRs.getString("name")).thenReturn("idx_set");
+ Mockito.when(secondaryRs.getString("type")).thenReturn("set");
+ Mockito.when(secondaryRs.getString("type_full")).thenReturn("set(100)");
+ Mockito.when(secondaryRs.getString("expr")).thenReturn("col_1");
+ Mockito.when(secondaryRs.getLong("granularity")).thenReturn(3L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(secondaryStmt);
+
+ List<Index> indexes = ops.callGetIndexes(connection, "db", "tbl");
+
+ Assertions.assertEquals(1, indexes.size());
+ Assertions.assertEquals(
+ Map.of("set_max_values", "100", "granularity", "3"),
indexes.get(0).properties());
+ }
+
+ @Test
+ void testGetIndexesSkipsUnsupportedExpressionForSetIndex() throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement secondaryStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet secondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(secondaryRs.next()).thenReturn(true, true, false);
+ Mockito.when(secondaryStmt.executeQuery()).thenReturn(secondaryRs);
+ Mockito.when(secondaryRs.getString("name")).thenReturn("idx_valid",
"idx_set_bad_expr");
+ Mockito.when(secondaryRs.getString("type")).thenReturn("set", "set");
+ Mockito.when(secondaryRs.getString("type_full")).thenReturn("set(100)",
"set(100)");
+ Mockito.when(secondaryRs.getString("expr")).thenReturn("col_2",
"cityHash64(col_3) % 16");
+ Mockito.when(secondaryRs.getLong("granularity")).thenReturn(1L, 1L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(secondaryStmt);
+
+ List<Index> indexes = ops.callGetIndexes(connection, "db", "tbl");
+
+ Assertions.assertEquals(1, indexes.size());
+ Assertions.assertEquals("idx_valid", indexes.get(0).name());
+ Assertions.assertEquals(Index.IndexType.DATA_SKIPPING_SET,
indexes.get(0).type());
+ Assertions.assertArrayEquals(new String[][] {{"col_2"}},
indexes.get(0).fieldNames());
+ Assertions.assertEquals(Map.of("set_max_values", "100"),
indexes.get(0).properties());
+ Assertions.assertFalse(
+ indexes.stream().anyMatch(index ->
"idx_set_bad_expr".equals(index.name())));
+ }
+
+ @Test
+ void testGetIndexesFailsOnMalformedSetMetadataWithSupportedExpression()
throws Exception {
+ IllegalArgumentException exception =
getIndexesFailureForSetMetadata("set(abc)", "col_1");
+
+
Assertions.assertTrue(exception.getMessage().contains("idx_bad_set_metadata"));
+ Assertions.assertTrue(exception.getMessage().contains("type_full"));
+ Assertions.assertTrue(exception.getMessage().contains("set(abc)"));
+ Assertions.assertTrue(exception.getMessage().contains("SET metadata"));
+ }
+
+ @Test
+ void
testGetIndexesSkipsUnsupportedExpressionBeforeParsingOutOfRangeSetMetadata()
+ throws Exception {
+ List<Index> indexes = getIndexesForSetMetadata("set(2147483648)",
"cityHash64(col_1) % 16");
+
+ Assertions.assertTrue(indexes.isEmpty());
+ }
+
+ @Test
+ void testGetIndexesFailsOnMalformedLegacySetMetadata() throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement modernSecondaryStmt =
Mockito.mock(PreparedStatement.class);
+ PreparedStatement legacySecondaryStmt =
Mockito.mock(PreparedStatement.class);
+ ResultSet legacySecondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(modernSecondaryStmt.executeQuery())
+ .thenThrow(new SQLException("Unknown identifier 'type_full'"));
+
Mockito.when(legacySecondaryStmt.executeQuery()).thenReturn(legacySecondaryRs);
+ Mockito.when(legacySecondaryRs.next()).thenReturn(true, false);
+
Mockito.when(legacySecondaryRs.getString("name")).thenReturn("idx_legacy_bad");
+ Mockito.when(legacySecondaryRs.getString("type")).thenReturn("set(abc)");
+ Mockito.when(legacySecondaryRs.getString("expr")).thenReturn("col_1");
+ Mockito.when(legacySecondaryRs.getLong("granularity")).thenReturn(1L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(modernSecondaryStmt)
+ .thenReturn(legacySecondaryStmt);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
ops.callGetIndexes(connection, "db", "tbl"));
+ Assertions.assertTrue(exception.getMessage().contains("idx_legacy_bad"));
+ Assertions.assertTrue(exception.getMessage().contains("legacy type"));
+ Assertions.assertTrue(exception.getMessage().contains("set(abc)"));
+ Assertions.assertTrue(exception.getMessage().contains("SET metadata"));
+ Assertions.assertFalse(exception.getMessage().contains("type_full"));
+ }
+
+ @Test
+ void testGetIndexesFallsBackWhenTypeFullColumnIsMissing() throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement modernSecondaryStmt =
Mockito.mock(PreparedStatement.class);
+ PreparedStatement legacySecondaryStmt =
Mockito.mock(PreparedStatement.class);
+ ResultSet legacySecondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(modernSecondaryStmt.executeQuery())
+ .thenThrow(new SQLException("Unknown identifier 'type_full'"));
+
Mockito.when(legacySecondaryStmt.executeQuery()).thenReturn(legacySecondaryRs);
+ Mockito.when(legacySecondaryRs.next()).thenReturn(true, false);
+ Mockito.when(legacySecondaryRs.getString("name")).thenReturn("idx_legacy");
+ Mockito.when(legacySecondaryRs.getString("type")).thenReturn("minmax");
+ Mockito.when(legacySecondaryRs.getString("expr")).thenReturn("col_1");
+ Mockito.when(legacySecondaryRs.getLong("granularity")).thenReturn(1L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(modernSecondaryStmt)
+ .thenReturn(legacySecondaryStmt);
+
+ List<Index> indexes = ops.callGetIndexes(connection, "db", "tbl");
+
+ Assertions.assertEquals(1, indexes.size());
+ Assertions.assertEquals(Index.IndexType.DATA_SKIPPING_MINMAX,
indexes.get(0).type());
+ Assertions.assertTrue(indexes.get(0).properties().isEmpty());
+ }
+
+ @Test
+ void testGetIndexesFallsBackAndReadsLegacySetParameters() throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement modernSecondaryStmt =
Mockito.mock(PreparedStatement.class);
+ PreparedStatement legacySecondaryStmt =
Mockito.mock(PreparedStatement.class);
+ ResultSet legacySecondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(modernSecondaryStmt.executeQuery())
+ .thenThrow(new SQLException("Unknown identifier 'type_full'"));
+
Mockito.when(legacySecondaryStmt.executeQuery()).thenReturn(legacySecondaryRs);
+ Mockito.when(legacySecondaryRs.next()).thenReturn(true, true, false);
+ Mockito.when(legacySecondaryRs.getString("name"))
+ .thenReturn("idx_legacy_set", "idx_legacy_bare");
+ Mockito.when(legacySecondaryRs.getString("type")).thenReturn("set(100)",
"set");
+ Mockito.when(legacySecondaryRs.getString("expr")).thenReturn("col_1",
"col_2");
+ Mockito.when(legacySecondaryRs.getLong("granularity")).thenReturn(1L, 1L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(modernSecondaryStmt)
+ .thenReturn(legacySecondaryStmt);
+
+ List<Index> indexes = ops.callGetIndexes(connection, "db", "tbl");
+
+ Assertions.assertEquals(2, indexes.size());
+ Index parameterized =
+ indexes.stream()
+ .filter(index -> "idx_legacy_set".equals(index.name()))
+ .findFirst()
+ .orElseThrow();
+ Assertions.assertEquals("idx_legacy_set", parameterized.name());
+ Assertions.assertEquals(Index.IndexType.DATA_SKIPPING_SET,
parameterized.type());
+ Assertions.assertEquals(Map.of("set_max_values", "100"),
parameterized.properties());
+
+ Index bare =
+ indexes.stream()
+ .filter(index -> "idx_legacy_bare".equals(index.name()))
+ .findFirst()
+ .orElseThrow();
+ Assertions.assertEquals("idx_legacy_bare", bare.name());
+ Assertions.assertEquals(Index.IndexType.DATA_SKIPPING_SET, bare.type());
+ Assertions.assertTrue(bare.properties().isEmpty());
+ }
+
+ @Test
+ void testGetIndexesDoesNotFallbackForOtherSqlErrors() throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement secondaryStmt = Mockito.mock(PreparedStatement.class);
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(secondaryStmt.executeQuery())
+ .thenThrow(new SQLException("Connection reset by peer"));
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(secondaryStmt);
+
+ GravitinoRuntimeException exception =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class, () ->
ops.callGetIndexes(connection, "db", "tbl"));
+ Assertions.assertTrue(exception.getCause() instanceof SQLException);
+ Mockito.verify(connection,
Mockito.times(2)).prepareStatement(Mockito.anyString());
+ }
+
@Test
void testClearCommentsWithNullOnCluster() {
ExposedClickHouseTableOperations ops =
@@ -845,4 +1147,63 @@ public class TestClickHouseTableOperationsUnit {
this.updateStatement = updateStatement;
}
}
+
+ private IllegalArgumentException getIndexesFailureForSetTypeFull(String
typeFull)
+ throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement secondaryStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet secondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(secondaryRs.next()).thenReturn(true, false);
+ Mockito.when(secondaryStmt.executeQuery()).thenReturn(secondaryRs);
+ Mockito.when(secondaryRs.getString("name")).thenReturn("idx_overflow");
+ Mockito.when(secondaryRs.getString("type")).thenReturn("set");
+ Mockito.when(secondaryRs.getString("type_full")).thenReturn(typeFull);
+ Mockito.when(secondaryRs.getString("expr")).thenReturn("col_1");
+ Mockito.when(secondaryRs.getLong("granularity")).thenReturn(1L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(secondaryStmt);
+
+ return Assertions.assertThrows(
+ IllegalArgumentException.class, () -> ops.callGetIndexes(connection,
"db", "tbl"));
+ }
+
+ private List<Index> getIndexesForSetMetadata(String typeFull, String
expression)
+ throws Exception {
+ ExposedClickHouseTableOperations ops = newOps();
+ PreparedStatement primaryKeyStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet primaryKeyRs = Mockito.mock(ResultSet.class);
+ PreparedStatement secondaryStmt = Mockito.mock(PreparedStatement.class);
+ ResultSet secondaryRs = Mockito.mock(ResultSet.class);
+
+ Mockito.when(primaryKeyRs.next()).thenReturn(false);
+ Mockito.when(primaryKeyStmt.executeQuery()).thenReturn(primaryKeyRs);
+ Mockito.when(secondaryRs.next()).thenReturn(true, false);
+ Mockito.when(secondaryStmt.executeQuery()).thenReturn(secondaryRs);
+
Mockito.when(secondaryRs.getString("name")).thenReturn("idx_bad_set_metadata");
+ Mockito.when(secondaryRs.getString("type")).thenReturn("set");
+ Mockito.when(secondaryRs.getString("type_full")).thenReturn(typeFull);
+ Mockito.when(secondaryRs.getString("expr")).thenReturn(expression);
+ Mockito.when(secondaryRs.getLong("granularity")).thenReturn(1L);
+
+ Connection connection = Mockito.mock(Connection.class);
+ Mockito.when(connection.prepareStatement(Mockito.anyString()))
+ .thenReturn(primaryKeyStmt)
+ .thenReturn(secondaryStmt);
+
+ return ops.callGetIndexes(connection, "db", "tbl");
+ }
+
+ private IllegalArgumentException getIndexesFailureForSetMetadata(
+ String typeFull, String expression) throws Exception {
+ return Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
getIndexesForSetMetadata(typeFull, expression));
+ }
}