diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java index f867b682..63772a1b 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java @@ -405,6 +405,82 @@ default String createIndex(String indexName, TableReference table, List if (columnNames == null || columnNames.isEmpty()) { throw new IllegalArgumentException("columnNames must not be empty for CREATE INDEX"); } + return indexStatement(indexName, table, columnNames.stream().map(IndexColumn::ascending).toList(), unique, + ifNotExists); + } + + /** A column of an index and the order the index sorts it in. */ + record IndexColumn(String name, boolean descending) { + + public IndexColumn { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("index column name must not be blank"); + } + } + + /** A column the index sorts ascending, the default order. */ + public static IndexColumn ascending(String name) { + return new IndexColumn(name, false); + } + + /** A column the index sorts descending. */ + public static IndexColumn descending(String name) { + return new IndexColumn(name, true); + } + } + + /** + * An index: its name, its table, its columns in order with the order each sorts in, whether it + * is unique, and the condition on its rows for a partial index, or {@code null}. + */ + record IndexDefinition(String name, TableReference table, List columns, boolean unique, + String condition) { + + public IndexDefinition { + if (columns == null || columns.isEmpty()) { + throw new IllegalArgumentException("columns must not be empty for CREATE INDEX"); + } + columns = List.copyOf(columns); + } + } + + /** + * {@code CREATE [UNIQUE] INDEX [IF NOT EXISTS] idx ON schema.table (col1 DESC, col2, …) [WHERE condition]}: + * an index whose columns each sort ascending or descending. An ascending column is written + * without an order, as SQL sorts by default. + * + * @return empty for a descending column where the database keeps no order in an index + * ({@link #supportsDescendingIndexColumns()} is false), and for a condition where it has + * no partial indexes ({@link #supportsFilteredIndexes()} is false) + */ + default Optional createIndex(IndexDefinition index, boolean ifNotExists) { + if (index.columns().stream().noneMatch(IndexColumn::descending)) { + return createIndex(index.name(), index.table(), + index.columns().stream().map(IndexColumn::name).toList(), index.unique(), index.condition(), + ifNotExists); + } + if (!supportsDescendingIndexColumns()) { + return Optional.empty(); + } + String statement = indexStatement(index.name(), index.table(), index.columns(), index.unique(), + ifNotExists); + if (index.condition() == null || index.condition().isBlank()) { + return Optional.of(statement); + } + return supportsFilteredIndexes() ? Optional.of(statement + " WHERE " + index.condition()) : Optional.empty(); + } + + /** + * @return true if an index keeps the order of a column it sorts descending + * ({@code CREATE INDEX … (col DESC)}); false where the database has no index DDL or takes + * {@code DESC} and ignores it + */ + default boolean supportsDescendingIndexColumns() { + return false; + } + + private String indexStatement(String indexName, TableReference table, List columns, boolean unique, + boolean ifNotExists) { StringBuilder sb = new StringBuilder("CREATE "); if (unique) sb.append("UNIQUE "); @@ -415,10 +491,12 @@ default String createIndex(String indexName, TableReference table, List sb.append(quoteIdentifier(indexName)); sb.append(" ON ").append(qualified(table)); sb.append(" ("); - for (int i = 0; i < columnNames.size(); i++) { + for (int i = 0; i < columns.size(); i++) { if (i > 0) sb.append(", "); - sb.append(quoteIdentifier(columnNames.get(i))); + sb.append(quoteIdentifier(columns.get(i).name())); + if (columns.get(i).descending()) + sb.append(" DESC"); } sb.append(")"); return sb.toString(); diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DescendingIndexStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DescendingIndexStatementsTest.java new file mode 100644 index 00000000..4e8bae49 --- /dev/null +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DescendingIndexStatementsTest.java @@ -0,0 +1,99 @@ +/* + * 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.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexColumn; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexDefinition; +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 index {@code ix} on {@code s.t (a DESC, b)}. A dialect whose + * database keeps no order in an index writes nothing for it and says so by + * {@link DdlGenerator#supportsDescendingIndexColumns()}; an index of ascending columns is the plain + * index of every dialect. + */ +class DescendingIndexStatementsTest { + + private static final TableReference TABLE = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "s")), "t"); + + private static final IndexDefinition DESCENDING = new IndexDefinition("ix", TABLE, + List.of(IndexColumn.descending("a"), IndexColumn.ascending("b")), false, null); + + private static final IndexDefinition ASCENDING = new IndexDefinition("ix", TABLE, + List.of(IndexColumn.ascending("a"), IndexColumn.ascending("b")), false, null); + + static Stream dialects() { + String quoted = "CREATE INDEX \"ix\" ON \"s\".\"t\" (\"a\" DESC, \"b\")"; + String backticked = "CREATE INDEX `ix` ON `s`.`t` (`a` DESC, `b`)"; + return Stream.of(of("postgresql", new PostgreSqlDialect(), quoted), + of("oracle", new OracleDialect(), quoted), + of("mssql", new MicrosoftSqlServerDialect(), quoted), + of("mysql", new MySqlDialect(), backticked), + of("mysql 5.7", new MySqlDialect(version(5, 7)), null), + of("mariadb", new MariaDBDialect(), backticked), + of("mariadb 10.6", new MariaDBDialect(version(10, 6)), null), + of("h2", new H2Dialect(), quoted), + of("sqlite", new SqliteDialect(), quoted), + of("derby", new DerbyDialect(), quoted), + of("duckdb", new DuckDbDialect(), null), + of("clickhouse", new ClickHouseDialect(), null), + of("hive", new HiveDialect(), null), + of("impala", new ImpalaDialect(), null), + of("ansi", new AnsiDialect(), null)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("dialects") + void anIndexWithADescendingColumn(Dialect dialect, String expected) { + DdlGenerator ddl = dialect.ddlGenerator(); + + assertThat(ddl.supportsDescendingIndexColumns()).as("supportsDescendingIndexColumns") + .isEqualTo(expected != null); + assertThat(ddl.createIndex(DESCENDING, false)).isEqualTo(Optional.ofNullable(expected)); + assertThat(ddl.createIndex(ASCENDING, false)) + .contains(ddl.createIndex("ix", TABLE, List.of("a", "b"), false, false)); + } + + private static Arguments of(String name, Dialect dialect, String expected) { + return Arguments.of(Named.of(name, dialect), expected); + } + + private static DialectInitData version(int major, int minor) { + return DialectInitData.ansiDefaults().withVersion(major, minor); + } +} diff --git a/dialect/db/derby/src/main/java/org/eclipse/daanse/sql/dialect/db/derby/DerbyDialect.java b/dialect/db/derby/src/main/java/org/eclipse/daanse/sql/dialect/db/derby/DerbyDialect.java index 282ad175..9f7e1e13 100644 --- a/dialect/db/derby/src/main/java/org/eclipse/daanse/sql/dialect/db/derby/DerbyDialect.java +++ b/dialect/db/derby/src/main/java/org/eclipse/daanse/sql/dialect/db/derby/DerbyDialect.java @@ -375,4 +375,10 @@ public java.util.Optional commentOnColumn(TableReference table, String c org.eclipse.daanse.sql.model.schema.ColumnMetaData currentMeta) { return java.util.Optional.empty(); } + + /** Derby keeps the order of each column of an index. */ + @Override + public boolean supportsDescendingIndexColumns() { + return true; + } } diff --git a/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java b/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java index 0f31da4d..c9c1a00c 100644 --- a/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java +++ b/dialect/db/h2/src/main/java/org/eclipse/daanse/sql/dialect/db/h2/H2Dialect.java @@ -317,4 +317,10 @@ public Optional createUser(String userName, boolean ifNotExists) { return Optional.of("CREATE USER " + (ifNotExists ? "IF NOT EXISTS " : "") + quoteIdentifier(userName) + " SALT X'' HASH X''"); } + + /** H2 keeps the order of each column of an index. */ + @Override + public boolean supportsDescendingIndexColumns() { + return true; + } } diff --git a/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java b/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java index 31004e1e..2f9cbd6c 100644 --- a/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java +++ b/dialect/db/mariadb/src/main/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBDialect.java @@ -181,4 +181,13 @@ public boolean supportsUsers() { return org.eclipse.daanse.sql.dialect.api.DialectVersion.UNKNOWN.equals(dialectVersion) || dialectVersion.atLeast(new org.eclipse.daanse.sql.dialect.api.DialectVersion(10, 4, 2)); } + + /** + * MariaDB keeps a descending index column from 10.8; before, it took {@code DESC} and ignored it. + * A dialect made without a connection takes such a version. + */ + @Override + public boolean supportsDescendingIndexColumns() { + return dialectVersion.isUnknownOrAtLeast(10, 8); + } } diff --git a/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBGeneratorsRoundTripTest.java b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBGeneratorsRoundTripTest.java index f3f9be07..2d55e3cb 100644 --- a/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBGeneratorsRoundTripTest.java +++ b/dialect/db/mariadb/src/test/java/org/eclipse/daanse/sql/dialect/db/mariadb/MariaDBGeneratorsRoundTripTest.java @@ -29,6 +29,7 @@ import org.eclipse.daanse.sql.dialect.api.DialectInitData; 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.IndexRoundTrip; import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip; import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal; import org.eclipse.daanse.sql.jdbc.metadata.MariaDbMetadataProvider; @@ -126,4 +127,11 @@ void user_is_created_given_a_role_and_dropped() throws SQLException { DatabasePrincipal.KIND_USER, users, "rt_user", "rt_role"); } } + + /** An index the dialect writes with a descending column is read back with the order of each column. */ + @Test + void descending_index_column_is_created_and_read_back() throws SQLException { + IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new MariaDbMetadataProvider(), users, + "ix_users_desc", "name", "id"); + } } diff --git a/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java b/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java index 048cea30..745c9b9e 100644 --- a/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java +++ b/dialect/db/mssqlserver/src/main/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerDialect.java @@ -937,4 +937,10 @@ private static String principalNamed(String name) { public boolean supportsFilteredIndexes() { return true; } + + /** SQL Server keeps the order of each key column of an index. */ + @Override + public boolean supportsDescendingIndexColumns() { + return true; + } } diff --git a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsRoundTripTest.java b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsRoundTripTest.java index 1854de64..5eab6702 100644 --- a/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsRoundTripTest.java +++ b/dialect/db/mssqlserver/src/test/java/org/eclipse/daanse/sql/dialect/db/mssqlserver/MicrosoftSqlServerGeneratorsRoundTripTest.java @@ -33,6 +33,7 @@ import org.eclipse.daanse.sql.dialect.api.DialectInitData; 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.IndexRoundTrip; 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; @@ -190,4 +191,11 @@ void filtered_index_is_created_and_read_back() throws SQLException { s.execute("DELETE FROM [dbo].[users] WHERE name = 'same'"); } } + + /** An index the dialect writes with a descending column is read back with the order of each column. */ + @Test + void descending_index_column_is_created_and_read_back() throws SQLException { + IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new MicrosoftSqlServerMetadataProvider(), + users, "ix_users_desc", "name", "id"); + } } diff --git a/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java b/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java index ac84b606..3aa7f2f9 100644 --- a/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java +++ b/dialect/db/mysql/src/main/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlDialect.java @@ -878,4 +878,13 @@ public Optional createUser(String userName, boolean ifNotExists) { return Optional.of("CREATE USER " + (ifNotExists ? "IF NOT EXISTS " : "") + quoteIdentifier(userName) + " ACCOUNT LOCK"); } + + /** + * MySQL keeps a descending index column from 8.0; before, it took {@code DESC} and ignored it. A + * dialect made without a connection takes such a version. + */ + @Override + public boolean supportsDescendingIndexColumns() { + return dialectVersion.isUnknownOrAtLeast(8, 0); + } } diff --git a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsRoundTripTest.java b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsRoundTripTest.java index 7800f186..13ebc827 100644 --- a/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsRoundTripTest.java +++ b/dialect/db/mysql/src/test/java/org/eclipse/daanse/sql/dialect/db/mysql/MySqlGeneratorsRoundTripTest.java @@ -27,6 +27,7 @@ import org.eclipse.daanse.sql.dialect.api.DialectInitData; 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.IndexRoundTrip; import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip; import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal; import org.eclipse.daanse.sql.jdbc.metadata.MySqlMetadataProvider; @@ -133,4 +134,11 @@ void user_is_created_given_a_role_and_dropped() throws SQLException { DatabasePrincipal.KIND_UNKNOWN, users, "rt_user", "rt_role"); } } + + /** An index the dialect writes with a descending column is read back with the order of each column. */ + @Test + void descending_index_column_is_created_and_read_back() throws SQLException { + IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new MySqlMetadataProvider(), users, + "ix_users_desc", "name", "id"); + } } diff --git a/dialect/db/oracle/src/main/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleDialect.java b/dialect/db/oracle/src/main/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleDialect.java index 9b45c240..deb77f5c 100644 --- a/dialect/db/oracle/src/main/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleDialect.java +++ b/dialect/db/oracle/src/main/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleDialect.java @@ -897,4 +897,10 @@ public Optional createMaterializedView(TableReference view, String selec public Optional dropMaterializedView(TableReference view, boolean ifExists) { return super.dropMaterializedView(view, ifExists && dialectVersion.atLeast(23, 0)); } + + /** Oracle keeps a descending column as a function-based index column. */ + @Override + public boolean supportsDescendingIndexColumns() { + return true; + } } diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java index 5a28633e..fb9c3a67 100644 --- a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java @@ -29,6 +29,7 @@ import org.eclipse.daanse.sql.dialect.api.DialectInitData; 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.IndexRoundTrip; import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip; import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal; import org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider; @@ -171,4 +172,11 @@ void materialized_view_is_created_read_back_and_dropped() throws SQLException { .noneMatch(mv -> mv.view().name().equals("MV_USERS")); } } + + /** An index the dialect writes with a descending column is read back with the order of each column. */ + @Test + void descending_index_column_is_created_and_read_back() throws SQLException { + IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new OracleMetadataProvider(), users, + "IX_USERS_DESC", "NAME", "ID"); + } } diff --git a/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java b/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java index d1256aff..c3302551 100644 --- a/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java +++ b/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java @@ -568,4 +568,10 @@ public boolean supportsMaterializedViews() { public boolean supportsFilteredIndexes() { return true; } + + /** PostgreSQL keeps the order of each column of a B-tree index. */ + @Override + public boolean supportsDescendingIndexColumns() { + return true; + } } diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlGeneratorsRoundTripTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlGeneratorsRoundTripTest.java index 4b12d8e2..28809db1 100644 --- a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlGeneratorsRoundTripTest.java +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlGeneratorsRoundTripTest.java @@ -31,6 +31,7 @@ import org.eclipse.daanse.sql.dialect.api.DialectInitData; 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.IndexRoundTrip; 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; @@ -174,4 +175,11 @@ void filtered_index_is_created_and_read_back() throws SQLException { s.execute("DELETE FROM \"public\".\"users\" WHERE name = 'same'"); } } + + /** An index the dialect writes with a descending column is read back with the order of each column. */ + @Test + void descending_index_column_is_created_and_read_back() throws SQLException { + IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new PostgreSqlMetadataProvider(), USERS, + "ix_users_desc", "name", "id"); + } } diff --git a/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java b/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java index db70b4f5..5492a1f7 100644 --- a/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java +++ b/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java @@ -330,4 +330,10 @@ public java.util.Optional commentOnColumn(TableReference table, String c public boolean supportsFilteredIndexes() { return dialectVersion.isUnknownOrAtLeast(3, 8); } + + /** SQLite keeps the order of each column of an index. */ + @Override + public boolean supportsDescendingIndexColumns() { + return true; + } } diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteGeneratorsRoundTripTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteGeneratorsRoundTripTest.java index 55329b14..9ee0e8f9 100644 --- a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteGeneratorsRoundTripTest.java +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteGeneratorsRoundTripTest.java @@ -29,6 +29,8 @@ import org.eclipse.daanse.sql.model.schema.SchemaReference; import org.eclipse.daanse.sql.model.schema.TableReference; import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexColumn; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexDefinition; import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator; import org.eclipse.daanse.sql.dialect.api.generator.PaginationGenerator.PreparedPaging; import org.junit.jupiter.api.AfterAll; @@ -126,4 +128,24 @@ void filtered_index_is_created() throws SQLException { s.execute("DELETE FROM \"users\" WHERE name = 'same'"); } } + + /** An index the dialect writes with a descending column keeps the order of each column. */ + @Test + void descending_index_column_is_created() throws SQLException { + TableReference table = new TableReference(Optional.empty(), "users", TableReference.TYPE_TABLE); + IndexDefinition index = new IndexDefinition("ix_users_desc", table, + List.of(IndexColumn.descending("name"), IndexColumn.ascending("id")), false, null); + try (Statement s = conn.createStatement()) { + s.execute(dialect.ddlGenerator().createIndex(index, false).orElseThrow()); + List columns = new java.util.ArrayList<>(); + try (ResultSet rs = s.executeQuery( + "SELECT name, \"desc\" FROM pragma_index_xinfo('ix_users_desc') WHERE \"key\" = 1 ORDER BY seqno")) { + while (rs.next()) { + columns.add(rs.getString(1) + (rs.getInt(2) == 1 ? " DESC" : " ASC")); + } + } + assertThat(columns).containsExactly("name DESC", "id ASC"); + s.execute("DROP INDEX \"ix_users_desc\""); + } + } } diff --git a/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/IndexRoundTrip.java b/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/IndexRoundTrip.java new file mode 100644 index 00000000..b4dbf693 --- /dev/null +++ b/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/IndexRoundTrip.java @@ -0,0 +1,62 @@ +/* + * 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.testsupport; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexColumn; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.IndexDefinition; +import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo; +import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfoItem; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; + +/** + * An index on a database as a dialect writes it, read back by the metadata provider and dropped. + */ +public final class IndexRoundTrip { + + private IndexRoundTrip() { + // static helpers only + } + + /** + * Creates the index {@code index} on {@code table (first DESC, second)}, reads it back, expects + * the first column descending and the second ascending, in that order, and drops it. Names are + * compared without regard to case, as some databases fold them. + */ + public static void assertDescendingIndexRoundTrip(Connection conn, DdlGenerator ddl, MetadataProvider provider, + TableReference table, String index, String first, String second) throws SQLException { + IndexDefinition definition = new IndexDefinition(index, table, + List.of(IndexColumn.descending(first), IndexColumn.ascending(second)), false, null); + try (Statement s = conn.createStatement()) { + s.execute(ddl.createIndex(definition, false).orElseThrow()); + String schema = table.schema().map(SchemaReference::name).orElse(null); + List items = provider.getAllIndexInfo(conn, null, schema).orElseThrow().stream() + .filter(info -> info.tableReference().name().equalsIgnoreCase(table.name())) + .flatMap((IndexInfo info) -> info.indexInfoItems().stream()) + .filter(item -> item.indexName().filter(index::equalsIgnoreCase).isPresent()) + .sorted(Comparator.comparingInt(IndexInfoItem::ordinalPosition)).toList(); + assertThat(items).extracting(item -> item.column().orElseThrow().name().toLowerCase(Locale.ROOT) + " " + + item.ascending().map(ascending -> ascending ? "ASC" : "DESC").orElse("?")) + .containsExactly(first.toLowerCase(Locale.ROOT) + " DESC", second.toLowerCase(Locale.ROOT) + " ASC"); + s.execute(ddl.dropIndex(index, table, false)); + } + } +} diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataProvider.java index 18a3324d..3ca0eb51 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataProvider.java @@ -446,7 +446,7 @@ public Optional> getAllIndexInfo(Connection connection, String c throws SQLException { String sql = """ SELECT i.TABLE_NAME, i.INDEX_NAME, i.INDEX_TYPE_NAME, i.IS_GENERATED, - ic.COLUMN_NAME, ic.ORDINAL_POSITION, ic.IS_UNIQUE, + ic.COLUMN_NAME, ic.ORDINAL_POSITION, ic.IS_UNIQUE, ic.ORDERING_SPECIFICATION, i.TABLE_SCHEMA, i.TABLE_CATALOG FROM INFORMATION_SCHEMA.INDEXES i JOIN INFORMATION_SCHEMA.INDEX_COLUMNS ic @@ -472,6 +472,7 @@ public Optional> getAllIndexInfo(Connection connection, String c int ordinalPosition = rs.getInt("ORDINAL_POSITION"); boolean isUnique = rs.getBoolean("IS_UNIQUE"); boolean isGenerated = rs.getBoolean("IS_GENERATED"); + String ordering = rs.getString("ORDERING_SPECIFICATION"); TableReference tableRef = tableRefs.computeIfAbsent(tableName, k -> { Optional oSchema = Optional @@ -485,8 +486,7 @@ public Optional> getAllIndexInfo(Connection connection, String c IndexInfoItem.IndexType indexType = mapH2IndexType(indexTypeName); IndexInfoItem item = new IndexInfoItemRecord(Optional.ofNullable(indexName), indexType, colRef, - ordinalPosition, Optional.empty(), // H2 doesn't expose ASC/DESC in - // INFORMATION_SCHEMA.INDEXES + ordinalPosition, Optional.ofNullable(ordering).map(o -> !"DESC".equalsIgnoreCase(o)), 0L, // cardinality not available here 0L, // pages not available here Optional.empty(), // filter condition diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataProvider.java index 37fcf52b..b15d442c 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataProvider.java @@ -457,7 +457,8 @@ public Optional> getAllExportedKeys(Connection connection, Str public Optional> getAllIndexInfo(Connection connection, String catalog, String schema) throws SQLException { String sql = """ - SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX, NON_UNIQUE, INDEX_TYPE, CARDINALITY + SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX, NON_UNIQUE, INDEX_TYPE, CARDINALITY, + COLLATION FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX """; @@ -473,7 +474,8 @@ public Optional> getAllIndexInfo(Connection connection, String c String tableName = rs.getString("TABLE_NAME"); String indexName = rs.getString("INDEX_NAME"); IndexRow row = new IndexRow(rs.getString("COLUMN_NAME"), rs.getInt("SEQ_IN_INDEX"), - rs.getBoolean("NON_UNIQUE"), rs.getString("INDEX_TYPE"), rs.getLong("CARDINALITY")); + rs.getBoolean("NON_UNIQUE"), rs.getString("INDEX_TYPE"), rs.getLong("CARDINALITY"), + rs.getString("COLLATION")); tableRefs.computeIfAbsent(tableName, k -> new TableReference( Optional.of(new SchemaReference(Optional.empty(), schemaName)), k)); tableIndexMap.computeIfAbsent(tableName, k -> new LinkedHashMap<>()) @@ -494,9 +496,9 @@ public Optional> getAllIndexInfo(Connection connection, String c for (IndexRow row : rows) { Optional colRef = Optional.ofNullable(row.column()) .map(cn -> new ColumnReference(Optional.of(tableRef), cn)); - // STATISTICS has no ASC/DESC, no pages and no filter condition + // STATISTICS has no pages and no filter condition allItems.add(new IndexInfoItemRecord(Optional.ofNullable(indexName), - mapIndexType(row.indexType()), colRef, row.seqInIndex(), Optional.empty(), + mapIndexType(row.indexType()), colRef, row.seqInIndex(), row.ascending(), row.cardinality(), 0L, Optional.empty(), !row.nonUnique(), madeForForeignKey)); } } @@ -505,8 +507,17 @@ public Optional> getAllIndexInfo(Connection connection, String c return Optional.of(List.copyOf(result)); } - /** One row of {@code information_schema.STATISTICS}: a column of an index. */ - private record IndexRow(String column, int seqInIndex, boolean nonUnique, String indexType, long cardinality) { + /** + * One row of {@code information_schema.STATISTICS}: a column of an index. Its collation is + * {@code A} for ascending, {@code D} for descending (MySQL 8, MariaDB 10.8) and none where the + * index keeps no order. + */ + private record IndexRow(String column, int seqInIndex, boolean nonUnique, String indexType, long cardinality, + String collation) { + + Optional ascending() { + return Optional.ofNullable(collation).map(c -> !"D".equalsIgnoreCase(c)); + } } /** The columns of each foreign key of a schema, in order, by the key's table and name. */ diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataProvider.java index 1ee07afc..0f80fc38 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataProvider.java @@ -404,7 +404,8 @@ public Optional> getAllExportedKeys(Connection connection, Str public Optional> getAllIndexInfo(Connection connection, String catalog, String schema) throws SQLException { String sql = """ - SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX, NON_UNIQUE, INDEX_TYPE, CARDINALITY + SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX, NON_UNIQUE, INDEX_TYPE, CARDINALITY, + COLLATION FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX """; @@ -420,7 +421,8 @@ public Optional> getAllIndexInfo(Connection connection, String c String tableName = rs.getString("TABLE_NAME"); String indexName = rs.getString("INDEX_NAME"); IndexRow row = new IndexRow(rs.getString("COLUMN_NAME"), rs.getInt("SEQ_IN_INDEX"), - rs.getBoolean("NON_UNIQUE"), rs.getString("INDEX_TYPE"), rs.getLong("CARDINALITY")); + rs.getBoolean("NON_UNIQUE"), rs.getString("INDEX_TYPE"), rs.getLong("CARDINALITY"), + rs.getString("COLLATION")); tableRefs.computeIfAbsent(tableName, k -> new TableReference( Optional.of(new SchemaReference(Optional.empty(), schemaName)), k)); tableIndexMap.computeIfAbsent(tableName, k -> new LinkedHashMap<>()) @@ -441,9 +443,9 @@ public Optional> getAllIndexInfo(Connection connection, String c for (IndexRow row : rows) { Optional colRef = Optional.ofNullable(row.column()) .map(cn -> new ColumnReference(Optional.of(tableRef), cn)); - // STATISTICS has no ASC/DESC, no pages and no filter condition + // STATISTICS has no pages and no filter condition allItems.add(new IndexInfoItemRecord(Optional.ofNullable(indexName), - mapMySqlIndexType(row.indexType()), colRef, row.seqInIndex(), Optional.empty(), + mapMySqlIndexType(row.indexType()), colRef, row.seqInIndex(), row.ascending(), row.cardinality(), 0L, Optional.empty(), !row.nonUnique(), madeForForeignKey)); } } @@ -452,8 +454,17 @@ public Optional> getAllIndexInfo(Connection connection, String c return Optional.of(List.copyOf(result)); } - /** One row of {@code information_schema.STATISTICS}: a column of an index. */ - private record IndexRow(String column, int seqInIndex, boolean nonUnique, String indexType, long cardinality) { + /** + * One row of {@code information_schema.STATISTICS}: a column of an index. Its collation is + * {@code A} for ascending, {@code D} for descending (MySQL 8, MariaDB 10.8) and none where the + * index keeps no order. + */ + private record IndexRow(String column, int seqInIndex, boolean nonUnique, String indexType, long cardinality, + String collation) { + + Optional ascending() { + return Optional.ofNullable(collation).map(c -> !"D".equalsIgnoreCase(c)); + } } /** The columns of each foreign key of a schema, in order, by the key's table and name. */ diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataProvider.java index 48e9ab41..62ffa88d 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataProvider.java @@ -515,11 +515,14 @@ public Optional> getAllExportedKeys(Connection connection, Str @Override public Optional> getAllIndexInfo(Connection connection, String catalog, String schema) throws SQLException { + // COLUMN_EXPRESSION is a LONG: it comes last and is read last String sql = """ SELECT i.INDEX_NAME, i.INDEX_TYPE, i.TABLE_NAME, i.UNIQUENESS, - ic.COLUMN_NAME, ic.COLUMN_POSITION, ic.DESCEND + ic.COLUMN_NAME, ic.COLUMN_POSITION, ic.DESCEND, ie.COLUMN_EXPRESSION FROM ALL_INDEXES i JOIN ALL_IND_COLUMNS ic ON i.OWNER = ic.INDEX_OWNER AND i.INDEX_NAME = ic.INDEX_NAME + LEFT JOIN ALL_IND_EXPRESSIONS ie ON ie.INDEX_OWNER = ic.INDEX_OWNER + AND ie.INDEX_NAME = ic.INDEX_NAME AND ie.COLUMN_POSITION = ic.COLUMN_POSITION WHERE i.TABLE_OWNER = ? ORDER BY i.TABLE_NAME, i.INDEX_NAME, ic.COLUMN_POSITION """; String schemaName = resolveSchema(schema, connection); @@ -536,6 +539,10 @@ public Optional> getAllIndexInfo(Connection connection, String c String columnName = rs.getString("COLUMN_NAME"); int columnPosition = rs.getInt("COLUMN_POSITION"); String descend = rs.getString("DESCEND"); + String expression = rs.getString("COLUMN_EXPRESSION"); + if ("DESC".equalsIgnoreCase(descend)) { + columnName = descendingColumn(columnName, expression); + } IndexInfoItem.IndexType mappedType = mapOracleIndexType(indexType); boolean isUnique = "UNIQUE".equalsIgnoreCase(uniqueness); @@ -566,6 +573,22 @@ public Optional> getAllIndexInfo(Connection connection, String c } + /** + * The column of a descending index column. Oracle keeps it as a function-based column with a + * system name ({@code SYS_NC00005$}) and the column as its expression, quoted ({@code "QTY"}); + * an expression that is no plain column leaves the system name. + */ + static String descendingColumn(String systemName, String expression) { + if (expression != null) { + String e = expression.strip(); + if (e.length() > 2 && e.startsWith("\"") && e.endsWith("\"") && e.indexOf('"', 1) == e.length() - 1) { + return e.substring(1, e.length() - 1); + } + } + return systemName; + } + + @Override public List getAllViewDefinitions(Connection connection, String catalog, String schema) throws SQLException { diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataContractTest.java index e40e8119..0ecc98f0 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataContractTest.java @@ -60,6 +60,12 @@ protected boolean keepsTextLength() { return false; } + /** DuckDB takes {@code DESC} in an index and drops it. */ + @Override + protected boolean keepsDescendingIndexColumns() { + return false; + } + @Override protected boolean keepsConstraintNames() { return false; diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviderContract.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviderContract.java index f257eebc..06236047 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviderContract.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviderContract.java @@ -59,7 +59,8 @@ * CHECK ck_orders_id (id > 0), CHECK without a name (qty > 0), id and qty NOT NULL, * INDEX ix_orders_ordered_on (ordered_on), * UNIQUE INDEX ux_orders_product_day (product_id, ordered_on), - * INDEX ix_orders_large (qty) WHERE qty > 10, where the database has partial indexes + * INDEX ix_orders_large (qty) WHERE qty > 10, where the database has partial indexes, + * INDEX ix_orders_qty_desc (qty DESC, id) * 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 @@ -184,6 +185,11 @@ protected List createFilteredIndex() { return List.of(); } + /** Whether the database keeps the order of an index column that sorts descending. */ + protected boolean keepsDescendingIndexColumns() { + return true; + } + /** Whether the database makes an index of its own for a foreign key whose columns have none. */ protected boolean makesForeignKeyIndexes() { return false; @@ -294,6 +300,7 @@ private List fixture() { sql.add("CREATE VIEW " + sales + ".v_orders AS SELECT id, qty FROM " + sales + ".orders"); sql.addAll(createMaterializedView()); sql.addAll(createFilteredIndex()); + sql.add("CREATE INDEX " + indexName(sales, "ix_orders_qty_desc") + " ON " + sales + ".orders (qty DESC, id)"); sql.addAll(createChildren()); if (sequences()) { sql.add(createSequence(sales + ".seq_unlimited", false)); @@ -444,6 +451,21 @@ void anIndexWithTheConditionOnItsRows() throws SQLException { .hasValueSatisfying(condition -> assertThat(condition).containsIgnoringCase("qty").contains("10"))); } + /** An index with a descending column is reported with the order of each of its columns. */ + @Test + void anIndexWithTheOrderOfItsColumns() throws SQLException { + assumeTrue(keepsDescendingIndexColumns(), "the database keeps no order in an index"); + + List items = provider.getAllIndexInfo(connection, null, sales()).orElseThrow().stream() + .filter(index -> is(index.tableReference(), sales(), "orders")) + .flatMap(index -> index.indexInfoItems().stream()).toList(); + + assertThat(index(items, "ix_orders_qty_desc")) + .extracting(item -> name(item.column().orElseThrow()) + " " + + item.ascending().map(ascending -> ascending ? "ASC" : "DESC").orElse("?")) + .containsExactly("qty DESC", "id ASC"); + } + @Test void viewWithItsQuery() throws SQLException { var views = provider.getAllViewDefinitions(connection, null, sales());