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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,32 @@ default String createIndex(String indexName, TableReference table, List<String>
return sb.toString();
}

/**
* {@code CREATE [UNIQUE] INDEX [IF NOT EXISTS] idx ON schema.table (cols) WHERE condition}: a
* partial index, over the rows the condition holds for only; a unique one is unique among those
* rows. The condition is written as given. Without a condition this is the index
* {@link #createIndex(String, TableReference, List, boolean, boolean)} writes.
*
* @return empty for a condition where the database has no partial indexes
* ({@link #supportsFilteredIndexes()} is false)
*/
default Optional<String> createIndex(String indexName, TableReference table, List<String> columnNames,
boolean unique, String condition, boolean ifNotExists) {
String index = createIndex(indexName, table, columnNames, unique, ifNotExists);
if (condition == null || condition.isBlank()) {
return Optional.of(index);
}
if (!supportsFilteredIndexes()) {
return Optional.empty();
}
return Optional.of(index + " WHERE " + condition);
}

/** @return true if an index may have a condition on its rows ({@code CREATE INDEX … WHERE}) */
default boolean supportsFilteredIndexes() {
return false;
}

/** {@code DROP INDEX [IF EXISTS] idx}. SQL-99 form (no {@code ON table}). */
default String dropIndex(String indexName, boolean ifExists) {
StringBuilder sb = new StringBuilder("DROP INDEX ");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright (c) 2026 Contributors to the Eclipse Foundation.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.daanse.sql.dialect.db.consistencytest;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import org.eclipse.daanse.sql.dialect.api.Dialect;
import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator;
import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect;
import org.eclipse.daanse.sql.dialect.db.common.AnsiDialect;
import org.eclipse.daanse.sql.dialect.db.derby.DerbyDialect;
import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect;
import org.eclipse.daanse.sql.dialect.db.h2.H2Dialect;
import org.eclipse.daanse.sql.dialect.db.hive.HiveDialect;
import org.eclipse.daanse.sql.dialect.db.impala.ImpalaDialect;
import org.eclipse.daanse.sql.dialect.db.mariadb.MariaDBDialect;
import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect;
import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect;
import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect;
import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect;
import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect;
import org.eclipse.daanse.sql.model.schema.SchemaReference;
import org.eclipse.daanse.sql.model.schema.TableReference;
import org.junit.jupiter.api.Named;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

/**
* What each dialect writes for the unique index {@code ix} on {@code s.t (a)} over the rows where
* {@code a > 0}. A dialect whose database has no partial indexes writes nothing for it and says so
* by {@link DdlGenerator#supportsFilteredIndexes()}; without a condition every dialect writes its
* plain index.
*/
class FilteredIndexStatementsTest {

private static final TableReference TABLE = new TableReference(
Optional.of(new SchemaReference(Optional.empty(), "s")), "t");

private static final String CONDITION = "a > 0";

static Stream<Arguments> dialects() {
String partial = "CREATE UNIQUE INDEX \"ix\" ON \"s\".\"t\" (\"a\") WHERE a > 0";
return Stream.of(of("postgresql", new PostgreSqlDialect(), partial),
of("mssql", new MicrosoftSqlServerDialect(), partial),
of("sqlite", new SqliteDialect(), partial),
of("oracle", new OracleDialect(), null),
of("mysql", new MySqlDialect(), null),
of("mariadb", new MariaDBDialect(), null),
of("h2", new H2Dialect(), null),
of("clickhouse", new ClickHouseDialect(), null),
of("duckdb", new DuckDbDialect(), null),
of("derby", new DerbyDialect(), null),
of("hive", new HiveDialect(), null),
of("impala", new ImpalaDialect(), null),
of("ansi", new AnsiDialect(), null));
}

@ParameterizedTest(name = "{0}")
@MethodSource("dialects")
void anIndexOverTheRowsOfACondition(Dialect dialect, String expected) {
DdlGenerator ddl = dialect.ddlGenerator();

assertThat(ddl.supportsFilteredIndexes()).as("supportsFilteredIndexes").isEqualTo(expected != null);
assertThat(ddl.createIndex("ix", TABLE, List.of("a"), true, CONDITION, false))
.isEqualTo(Optional.ofNullable(expected));
assertThat(ddl.createIndex("ix", TABLE, List.of("a"), true, null, false))
.contains(ddl.createIndex("ix", TABLE, List.of("a"), true, false));
}

private static Arguments of(String name, Dialect dialect, String expected) {
return Arguments.of(Named.of(name, dialect), expected);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -928,4 +928,13 @@ public Optional<String> dropUser(String userName, boolean ifExists) {
private static String principalNamed(String name) {
return "SELECT 1 FROM sys.database_principals WHERE name = " + nLiteral(name);
}

/**
* SQL Server: a filtered index, {@code CREATE INDEX … WHERE condition}; the condition compares
* columns with constants only.
*/
@Override
public boolean supportsFilteredIndexes() {
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
package org.eclipse.daanse.sql.dialect.db.mssqlserver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertExecuteUpdateAffected;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstIntEquals;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstStringEquals;
Expand All @@ -33,6 +34,7 @@
import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator;
import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PreparedPaging;
import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo;
import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
Expand Down Expand Up @@ -166,4 +168,26 @@ void user_is_created_given_a_role_and_dropped() throws SQLException {
UserRoundTrip.assertUserRoundTrip(conn, dialect.ddlGenerator(), new MicrosoftSqlServerMetadataProvider(),
DatabasePrincipal.KIND_USER, users, "rt_user", "rt_role");
}

/**
* A unique index over the rows of a condition holds among those rows only, and the metadata
* provider reads its condition back.
*/
@Test
void filtered_index_is_created_and_read_back() throws SQLException {
String create = dialect.ddlGenerator().createIndex("ux_users_big", users, List.of("name"), true, "id > 100",
false).orElseThrow();
try (Statement s = conn.createStatement()) {
s.execute(create);
s.execute("INSERT INTO [dbo].[users] VALUES (31, 'same'), (32, 'same'), (301, 'same')");
assertThatThrownBy(() -> s.execute("INSERT INTO [dbo].[users] VALUES (302, 'same')"))
.isInstanceOf(SQLException.class);
assertThat(new MicrosoftSqlServerMetadataProvider().getAllIndexInfo(conn, null, "dbo").orElseThrow())
.flatExtracting(IndexInfo::indexInfoItems)
.filteredOn(item -> item.indexName().filter("ux_users_big"::equals).isPresent()).singleElement()
.satisfies(item -> assertThat(item.filterCondition().orElseThrow()).contains("[id]>(100)"));
s.execute(dialect.ddlGenerator().dropIndex("ux_users_big", users, false));
s.execute("DELETE FROM [dbo].[users] WHERE name = 'same'");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -562,4 +562,10 @@ public Optional<String> createUser(String userName, boolean ifNotExists) {
public boolean supportsMaterializedViews() {
return true;
}

/** PostgreSQL: a partial index, {@code CREATE INDEX … WHERE condition}. */
@Override
public boolean supportsFilteredIndexes() {
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
package org.eclipse.daanse.sql.dialect.db.postgresql;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertExecuteUpdateAffected;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstIntEquals;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstStringEquals;
Expand All @@ -31,6 +32,7 @@
import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator;
import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PreparedPaging;
import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo;
import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
import org.eclipse.daanse.sql.jdbc.metadata.PostgreSqlMetadataProvider;
import org.junit.jupiter.api.AfterAll;
Expand Down Expand Up @@ -150,4 +152,26 @@ void materialized_view_is_created_read_back_and_dropped() throws SQLException {
.noneMatch(mv -> mv.view().name().equals("mv_users"));
}
}

/**
* A unique index over the rows of a condition holds among those rows only, and the metadata
* provider reads its condition back.
*/
@Test
void filtered_index_is_created_and_read_back() throws SQLException {
String create = dialect.ddlGenerator().createIndex("ux_users_big", USERS, List.of("name"), true, "id > 100",
false).orElseThrow();
try (Statement s = conn.createStatement()) {
s.execute(create);
s.execute("INSERT INTO \"public\".\"users\" VALUES (31, 'same'), (32, 'same'), (301, 'same')");
assertThatThrownBy(() -> s.execute("INSERT INTO \"public\".\"users\" VALUES (302, 'same')"))
.isInstanceOf(SQLException.class);
assertThat(new PostgreSqlMetadataProvider().getAllIndexInfo(conn, null, "public").orElseThrow())
.flatExtracting(IndexInfo::indexInfoItems)
.filteredOn(item -> item.indexName().filter("ux_users_big"::equals).isPresent()).singleElement()
.satisfies(item -> assertThat(item.filterCondition().orElseThrow()).contains("id > 100"));
s.execute(dialect.ddlGenerator().dropIndex("ux_users_big", USERS, false));
s.execute("DELETE FROM \"public\".\"users\" WHERE name = 'same'");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -321,4 +321,13 @@ public java.util.Optional<String> commentOnColumn(TableReference table, String c
org.eclipse.daanse.sql.model.schema.ColumnMetaData currentMeta) {
return java.util.Optional.empty();
}

/**
* SQLite: a partial index, {@code CREATE INDEX … WHERE condition}, from 3.8.0; a dialect made
* without a connection takes such a version.
*/
@Override
public boolean supportsFilteredIndexes() {
return dialectVersion.isUnknownOrAtLeast(3, 8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
package org.eclipse.daanse.sql.dialect.db.sqlite;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertExecuteUpdateAffected;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstIntEquals;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstStringEquals;
Expand All @@ -18,6 +19,7 @@

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
Expand Down Expand Up @@ -100,4 +102,28 @@ void returning_clause_returns_inserted_id() throws SQLException {
String returning = dialect.returningGenerator().returning(List.of("id")).orElseThrow();
assertFirstIntEquals(conn, "INSERT INTO \"users\" (id, name) VALUES (99, 'returned')" + returning, 99);
}

/**
* A unique index over the rows of a condition holds among those rows only; SQLite keeps it as a
* partial index. SQLite takes no schema before the table of an index.
*/
@Test
void filtered_index_is_created() throws SQLException {
TableReference table = new TableReference(Optional.empty(), "users", TableReference.TYPE_TABLE);
String create = dialect.ddlGenerator().createIndex("ux_users_big", table, List.of("name"), true, "id > 100",
false).orElseThrow();
try (Statement s = conn.createStatement()) {
s.execute(create);
s.execute("INSERT INTO \"users\" VALUES (31, 'same'), (32, 'same'), (301, 'same')");
assertThatThrownBy(() -> s.execute("INSERT INTO \"users\" VALUES (302, 'same')"))
.isInstanceOf(SQLException.class);
try (ResultSet rs = s.executeQuery("SELECT \"partial\" FROM pragma_index_list('users')"
+ " WHERE name = 'ux_users_big'")) {
assertThat(rs.next()).isTrue();
assertThat(rs.getInt(1)).as("partial").isEqualTo(1);
}
s.execute("DROP INDEX \"ux_users_big\"");
s.execute("DELETE FROM \"users\" WHERE name = 'same'");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -540,13 +540,14 @@ ORDER BY OBJECT_NAME(fk.referenced_object_id), fk.name, fkc.constraint_column_id
}


/** The indexes of a schema; a filtered index with its condition as SQL Server keeps it. */
@Override
public Optional<List<IndexInfo>> getAllIndexInfo(Connection connection, String catalog, String schema)
throws SQLException {
String sql = """
SELECT i.name AS index_name, i.type_desc AS index_type, i.is_unique,
OBJECT_NAME(i.object_id) AS table_name, c.name AS column_name,
ic.key_ordinal, ic.is_descending_key
ic.key_ordinal, ic.is_descending_key, i.filter_definition
FROM sys.indexes i
JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
Expand All @@ -568,6 +569,7 @@ ORDER BY OBJECT_NAME(i.object_id), i.name, ic.key_ordinal
String columnName = rs.getString("column_name");
int ordinalPosition = rs.getInt("key_ordinal");
boolean isDescending = rs.getBoolean("is_descending_key");
String filterDefinition = rs.getString("filter_definition");

IndexInfoItem.IndexType mappedType = mapMssqlIndexType(indexType);

Expand All @@ -581,7 +583,8 @@ ORDER BY OBJECT_NAME(i.object_id), i.name, ic.key_ordinal
.map(cn -> new ColumnReference(Optional.of(tableRef), cn));

IndexInfoItem item = new IndexInfoItemRecord(Optional.ofNullable(indexName), mappedType, colRef,
ordinalPosition, Optional.of(!isDescending), 0L, 0L, Optional.empty(), isUnique);
ordinalPosition, Optional.of(!isDescending), 0L, 0L, Optional.ofNullable(filterDefinition),
isUnique);

tableIndexes.computeIfAbsent(tableName, k -> new ArrayList<>()).add(item);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
* sales.orders PK (id), FK fk_orders_product (product_id) → stock.product,
* CHECK ck_orders_id (id &gt; 0), CHECK without a name (qty &gt; 0), id and qty NOT NULL,
* INDEX ix_orders_ordered_on (ordered_on),
* UNIQUE INDEX ux_orders_product_day (product_id, ordered_on)
* UNIQUE INDEX ux_orders_product_day (product_id, ordered_on),
* INDEX ix_orders_large (qty) WHERE qty &gt; 10, where the database has partial indexes
* sales.order_line PK (order_id, line_no), FK fk_order_line_orders (order_id) → sales.orders
* sales.child_bare PK (id), FK fk_child_bare (orders_id) → sales.orders, no index of its own
* sales.child_indexed
Expand Down Expand Up @@ -174,6 +175,15 @@ protected List<String> createMaterializedView() {
return List.of();
}

/**
* The statements that create the partial index {@code ix_orders_large} on the column {@code qty}
* of the orders, over the rows where {@code qty > 10}; none where the database has no partial
* indexes.
*/
protected List<String> createFilteredIndex() {
return List.of();
}

/** Whether the database makes an index of its own for a foreign key whose columns have none. */
protected boolean makesForeignKeyIndexes() {
return false;
Expand Down Expand Up @@ -283,6 +293,7 @@ private List<String> fixture() {
+ ".orders (product_id, ordered_on)");
sql.add("CREATE VIEW " + sales + ".v_orders AS SELECT id, qty FROM " + sales + ".orders");
sql.addAll(createMaterializedView());
sql.addAll(createFilteredIndex());
sql.addAll(createChildren());
if (sequences()) {
sql.add(createSequence(sales + ".seq_unlimited", false));
Expand Down Expand Up @@ -420,6 +431,19 @@ void anIndexTheDatabaseMadeForAForeignKeyIsMarked() throws SQLException {
});
}

/** A partial index is reported with the condition on its rows, where the database has them. */
@Test
void anIndexWithTheConditionOnItsRows() throws SQLException {
assumeFalse(createFilteredIndex().isEmpty(), "the database has no partial indexes");

List<IndexInfo> indexes = provider.getAllIndexInfo(connection, null, sales()).orElseThrow();
List<IndexInfoItem> items = indexes.stream().filter(index -> is(index.tableReference(), sales(), "orders"))
.flatMap(index -> index.indexInfoItems().stream()).toList();

assertThat(index(items, "ix_orders_large")).allSatisfy(item -> assertThat(item.filterCondition())
.hasValueSatisfying(condition -> assertThat(condition).containsIgnoringCase("qty").contains("10")));
}

@Test
void viewWithItsQuery() throws SQLException {
var views = provider.getAllViewDefinitions(connection, null, sales());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ protected Connection open() throws Exception {
return DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword());
}

@Override
protected List<String> createFilteredIndex() {
return List.of("CREATE INDEX ix_orders_large ON sales.orders (qty) WHERE qty > 10");
}

@Override
protected MetadataProvider provider() {
return new MicrosoftSqlServerMetadataProvider();
Expand Down
Loading
Loading