From b82d81fdea0d2704b05d3d426b3966e244898a39 Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Thu, 12 Nov 2026 16:31:51 +0100 Subject: [PATCH 1/7] dialect, metadata(postgresql, oracle): deferrable foreign keys A foreign key checked at the end of the transaction could not be written, as the dialect API had no DEFERRABLE, and the PostgreSQL and Oracle providers reported every key as checked at once. DdlGenerator gains the enum Deferrability (NOT_DEFERRABLE, INITIALLY_IMMEDIATE, INITIALLY_DEFERRED), foreignKeyClause(..., deferrability) and addForeignKeyConstraint(..., deferrability), which write the dialect's clause and DEFERRABLE INITIALLY IMMEDIATE or DEFERRED after it, and supportsDeferrableForeignKeys(), false by default. A key that is not deferrable is the plain clause of every dialect; a deferrable one is empty where the database checks every key at once. PostgreSQL, Oracle and SQLite write it, and Derby from 10.11. SQL Server, MySQL, MariaDB, H2 (which rejects the clause), DuckDB, ClickHouse, Hive, Impala and the ANSI dialect have none. The PostgreSQL provider now reads pg_constraint.condeferrable and condeferred, the Oracle provider ALL_CONSTRAINTS.DEFERRABLE and DEFERRED. The consistency tests check the clauses of every dialect. On PostgreSQL and Oracle a key added as initially deferred lets a child row come before its parent within a transaction and is read back as initially deferred; on SQLite the key goes into the table's definition, as SQLite adds no constraint to an existing table. The metadata contract creates such a key where the database has them and expects every other key to be reported as checked at once. Signed-off-by: Stefan Bischof --- .../dialect/api/generator/DdlGenerator.java | 58 ++++++++++ .../DeferrableForeignKeyStatementsTest.java | 101 ++++++++++++++++++ .../sql/dialect/db/derby/DerbyDialect.java | 9 ++ .../sql/dialect/db/oracle/OracleDialect.java | 6 ++ .../oracle/OracleGeneratorsRoundTripTest.java | 34 ++++++ .../db/postgresql/PostgreSqlDialect.java | 6 ++ .../PostgreSqlGeneratorsRoundTripTest.java | 33 ++++++ .../sql/dialect/db/sqlite/SqliteDialect.java | 6 ++ .../sqlite/SqliteGeneratorsRoundTripTest.java | 29 +++++ .../jdbc/metadata/OracleMetadataProvider.java | 19 +++- .../metadata/PostgreSqlMetadataProvider.java | 17 ++- .../metadata/MetadataProviderContract.java | 31 ++++++ .../metadata/OracleMetadataContractTest.java | 7 ++ .../PostgreSqlMetadataContractTest.java | 7 ++ 14 files changed, 357 insertions(+), 6 deletions(-) create mode 100644 dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DeferrableForeignKeyStatementsTest.java 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 63772a1..401eaef 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 @@ -846,6 +846,64 @@ default String foreignKeyClause(String constraintName, List fkColumns, T return sb.toString(); } + /** + * When a constraint is checked: at once, after each statement ({@link #NOT_DEFERRABLE}); or at + * the end of the transaction, where a transaction may defer it + * ({@code SET CONSTRAINTS … DEFERRED}) and by default does not ({@link #INITIALLY_IMMEDIATE}) + * or does ({@link #INITIALLY_DEFERRED}). + */ + enum Deferrability { + NOT_DEFERRABLE, INITIALLY_IMMEDIATE, INITIALLY_DEFERRED + } + + /** + * One foreign key as a table constraint, as + * {@link #foreignKeyClause(String, List, TableReference, List, String, String)} writes it, with + * {@code DEFERRABLE INITIALLY IMMEDIATE} or {@code DEFERRABLE INITIALLY DEFERRED} after it for a + * key that may be checked at the end of the transaction. + * + * @return empty for a deferrable key where the database checks every key at once + * ({@link #supportsDeferrableForeignKeys()} is false) + */ + default Optional foreignKeyClause(String constraintName, List fkColumns, + TableReference referencedTable, List referencedColumns, String onDelete, String onUpdate, + Deferrability deferrability) { + String clause = foreignKeyClause(constraintName, fkColumns, referencedTable, referencedColumns, onDelete, + onUpdate); + if (deferrability == null || deferrability == Deferrability.NOT_DEFERRABLE) { + return Optional.of(clause); + } + if (!supportsDeferrableForeignKeys()) { + return Optional.empty(); + } + return Optional.of(clause + (deferrability == Deferrability.INITIALLY_DEFERRED + ? " DEFERRABLE INITIALLY DEFERRED" + : " DEFERRABLE INITIALLY IMMEDIATE")); + } + + /** + * {@code ALTER TABLE schema.table ADD} the foreign key + * {@link #foreignKeyClause(String, List, TableReference, List, String, String, Deferrability)} + * writes. + * + * @return empty where that clause is, and where a foreign key cannot be added to an existing table + * ({@link #supportsAddForeignKeyConstraint()} is false) + */ + default Optional addForeignKeyConstraint(TableReference table, String constraintName, + List fkColumns, TableReference referencedTable, List referencedColumns, String onDelete, + String onUpdate, Deferrability deferrability) { + if (!supportsAddForeignKeyConstraint()) { + return Optional.empty(); + } + return foreignKeyClause(constraintName, fkColumns, referencedTable, referencedColumns, onDelete, onUpdate, + deferrability).map(clause -> "ALTER TABLE " + qualified(table) + " ADD " + clause); + } + + /** @return true if a foreign key may be checked at the end of the transaction ({@code DEFERRABLE}) */ + default boolean supportsDeferrableForeignKeys() { + return false; + } + /** {@code ALTER TABLE schema.table ADD CONSTRAINT name CHECK (expression)}. */ default String addCheckConstraint(TableReference table, String constraintName, String expression) { return "ALTER TABLE " + qualified(table) + " ADD " + checkConstraintClause(constraintName, expression); diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DeferrableForeignKeyStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DeferrableForeignKeyStatementsTest.java new file mode 100644 index 0000000..94d81c0 --- /dev/null +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DeferrableForeignKeyStatementsTest.java @@ -0,0 +1,101 @@ +/* + * 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.api.generator.DdlGenerator.Deferrability; +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.api.Test; +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 foreign key {@code fk} from {@code s.c (p_id)} to {@code s.p (id)} + * by when it is checked. A key checked at once is the plain clause of every dialect; a deferrable + * one is the plain clause and its deferrability, or nothing where the database checks every key at + * once, as {@link DdlGenerator#supportsDeferrableForeignKeys()} says. + */ +class DeferrableForeignKeyStatementsTest { + + private static final TableReference CHILD = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "s")), "c"); + + private static final TableReference PARENT = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "s")), "p"); + + static Stream dialects() { + return Stream.of(of("postgresql", new PostgreSqlDialect(), true), of("oracle", new OracleDialect(), true), + of("sqlite", new SqliteDialect(), true), of("derby", new DerbyDialect(), true), + of("mssql", new MicrosoftSqlServerDialect(), false), of("mysql", new MySqlDialect(), false), + of("mariadb", new MariaDBDialect(), false), of("h2", new H2Dialect(), false), + of("duckdb", new DuckDbDialect(), false), of("clickhouse", new ClickHouseDialect(), false), + of("hive", new HiveDialect(), false), of("impala", new ImpalaDialect(), false), + of("ansi", new AnsiDialect(), false)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("dialects") + void aForeignKeyByWhenItIsChecked(Dialect dialect, boolean deferrable) { + DdlGenerator ddl = dialect.ddlGenerator(); + String plain = ddl.foreignKeyClause("fk", List.of("p_id"), PARENT, List.of("id"), null, null); + + assertThat(ddl.supportsDeferrableForeignKeys()).as("supportsDeferrableForeignKeys").isEqualTo(deferrable); + assertThat(clause(ddl, Deferrability.NOT_DEFERRABLE)).contains(plain); + assertThat(clause(ddl, Deferrability.INITIALLY_DEFERRED)) + .isEqualTo(deferrable ? Optional.of(plain + " DEFERRABLE INITIALLY DEFERRED") : Optional.empty()); + assertThat(clause(ddl, Deferrability.INITIALLY_IMMEDIATE)) + .isEqualTo(deferrable ? Optional.of(plain + " DEFERRABLE INITIALLY IMMEDIATE") : Optional.empty()); + assertThat(ddl.addForeignKeyConstraint(CHILD, "fk", List.of("p_id"), PARENT, List.of("id"), null, null, + Deferrability.INITIALLY_DEFERRED)) + .isEqualTo(deferrable && ddl.supportsAddForeignKeyConstraint() + ? Optional.of(ddl.addForeignKeyConstraint(CHILD, "fk", List.of("p_id"), PARENT, List.of("id"), + null, null) + " DEFERRABLE INITIALLY DEFERRED") + : Optional.empty()); + } + + @Test + void postgresqlWritesTheKeyAndWhenItIsChecked() { + assertThat(new PostgreSqlDialect().ddlGenerator().addForeignKeyConstraint(CHILD, "fk", List.of("p_id"), PARENT, + List.of("id"), "CASCADE", null, Deferrability.INITIALLY_DEFERRED)) + .contains("ALTER TABLE \"s\".\"c\" ADD CONSTRAINT \"fk\" FOREIGN KEY (\"p_id\") REFERENCES \"s\".\"p\"" + + " (\"id\") ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED"); + } + + private static Optional clause(DdlGenerator ddl, Deferrability deferrability) { + return ddl.foreignKeyClause("fk", List.of("p_id"), PARENT, List.of("id"), null, null, deferrability); + } + + private static Arguments of(String name, Dialect dialect, boolean deferrable) { + return Arguments.of(Named.of(name, dialect), deferrable); + } +} 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 9f7e1e1..e7e7e90 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 @@ -381,4 +381,13 @@ public java.util.Optional commentOnColumn(TableReference table, String c public boolean supportsDescendingIndexColumns() { return true; } + + /** + * Derby checks a deferrable foreign key at the end of the transaction from 10.11 on; a dialect + * made without a connection takes such a version. + */ + @Override + public boolean supportsDeferrableForeignKeys() { + return dialectVersion.isUnknownOrAtLeast(10, 11); + } } 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 deb77f5..3a73fcf 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 @@ -903,4 +903,10 @@ public Optional dropMaterializedView(TableReference view, boolean ifExis public boolean supportsDescendingIndexColumns() { return true; } + + /** Oracle checks a deferrable foreign key at the end of the transaction where it is deferred. */ + @Override + public boolean supportsDeferrableForeignKeys() { + 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 fb9c3a6..b6d7be3 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 @@ -27,11 +27,13 @@ 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.Deferrability; 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.api.schema.ImportedKey; import org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -179,4 +181,36 @@ void descending_index_column_is_created_and_read_back() throws SQLException { IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new OracleMetadataProvider(), users, "IX_USERS_DESC", "NAME", "ID"); } + + /** + * A foreign key the dialect writes as checked at the end of the transaction lets a child come + * before its parent within one, and is read back as initially deferred. + */ + @Test + void deferrable_foreign_key_is_checked_at_commit_and_read_back() throws SQLException { + String schema = CONTAINER.getUsername().toUpperCase(); + TableReference parent = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), "DP", + TableReference.TYPE_TABLE); + TableReference child = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), "DC", + TableReference.TYPE_TABLE); + try (Statement s = conn.createStatement()) { + s.execute("CREATE TABLE \"" + schema + "\".\"DP\" (ID NUMBER PRIMARY KEY)"); + s.execute("CREATE TABLE \"" + schema + "\".\"DC\" (ID NUMBER PRIMARY KEY, DP_ID NUMBER)"); + s.execute(dialect.ddlGenerator().addForeignKeyConstraint(child, "FK_DC_DP", List.of("DP_ID"), parent, + List.of("ID"), null, null, Deferrability.INITIALLY_DEFERRED).orElseThrow()); + conn.setAutoCommit(false); + s.execute("INSERT INTO \"" + schema + "\".\"DC\" VALUES (1, 7)"); + s.execute("INSERT INTO \"" + schema + "\".\"DP\" VALUES (7)"); + conn.commit(); + } finally { + conn.setAutoCommit(true); + } + assertThat(new OracleMetadataProvider().getAllImportedKeys(conn, null, schema).orElseThrow()) + .filteredOn(key -> "FK_DC_DP".equals(key.name())).singleElement() + .satisfies(key -> assertThat(key.deferrability()).isEqualTo(ImportedKey.Deferrability.INITIALLY_DEFERRED)); + try (Statement s = conn.createStatement()) { + s.execute("DROP TABLE \"" + schema + "\".\"DC\""); + s.execute("DROP TABLE \"" + schema + "\".\"DP\""); + } + } } 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 c330255..a392789 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 @@ -574,4 +574,10 @@ public boolean supportsFilteredIndexes() { public boolean supportsDescendingIndexColumns() { return true; } + + /** PostgreSQL checks a deferrable foreign key at the end of the transaction where it is deferred. */ + @Override + public boolean supportsDeferrableForeignKeys() { + 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 28809db..1b14469 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 @@ -29,12 +29,14 @@ 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.Deferrability; 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; +import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey; import org.eclipse.daanse.sql.jdbc.metadata.PostgreSqlMetadataProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -182,4 +184,35 @@ void descending_index_column_is_created_and_read_back() throws SQLException { IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new PostgreSqlMetadataProvider(), USERS, "ix_users_desc", "name", "id"); } + + /** + * A foreign key the dialect writes as checked at the end of the transaction lets a child come + * before its parent within one, and is read back as initially deferred. + */ + @Test + void deferrable_foreign_key_is_checked_at_commit_and_read_back() throws SQLException { + TableReference parent = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "public")), + "dp", TableReference.TYPE_TABLE); + TableReference child = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "public")), + "dc", TableReference.TYPE_TABLE); + try (Statement s = conn.createStatement()) { + s.execute("CREATE TABLE \"public\".\"dp\" (id INT PRIMARY KEY)"); + s.execute("CREATE TABLE \"public\".\"dc\" (id INT PRIMARY KEY, dp_id INT)"); + s.execute(dialect.ddlGenerator().addForeignKeyConstraint(child, "fk_dc_dp", List.of("dp_id"), parent, + List.of("id"), null, null, Deferrability.INITIALLY_DEFERRED).orElseThrow()); + conn.setAutoCommit(false); + s.execute("INSERT INTO \"public\".\"dc\" VALUES (1, 7)"); + s.execute("INSERT INTO \"public\".\"dp\" VALUES (7)"); + conn.commit(); + } finally { + conn.setAutoCommit(true); + } + assertThat(new PostgreSqlMetadataProvider().getAllImportedKeys(conn, null, "public").orElseThrow()) + .filteredOn(key -> "fk_dc_dp".equals(key.name())).singleElement() + .satisfies(key -> assertThat(key.deferrability()).isEqualTo(ImportedKey.Deferrability.INITIALLY_DEFERRED)); + try (Statement s = conn.createStatement()) { + s.execute("DROP TABLE \"public\".\"dc\""); + s.execute("DROP TABLE \"public\".\"dp\""); + } + } } 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 5492a1f..df3b5d7 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 @@ -336,4 +336,10 @@ public boolean supportsFilteredIndexes() { public boolean supportsDescendingIndexColumns() { return true; } + + /** SQLite checks a deferrable foreign key at the end of the transaction where it is deferred. */ + @Override + public boolean supportsDeferrableForeignKeys() { + 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 9ee0e8f..5b6e9a6 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,7 @@ 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.Deferrability; 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; @@ -148,4 +149,32 @@ void descending_index_column_is_created() throws SQLException { s.execute("DROP INDEX \"ix_users_desc\""); } } + + /** + * A foreign key the dialect writes as checked at the end of the transaction lets a child come + * before its parent within one. SQLite adds no constraint to an existing table: the key goes into + * the table's definition. + */ + @Test + void deferrable_foreign_key_is_checked_at_commit() throws SQLException { + TableReference parent = new TableReference(Optional.empty(), "dp", TableReference.TYPE_TABLE); + String key = dialect.ddlGenerator().foreignKeyClause("fk_dc_dp", List.of("dp_id"), parent, List.of("id"), + null, null, Deferrability.INITIALLY_DEFERRED).orElseThrow(); + try (Statement s = conn.createStatement()) { + s.execute("PRAGMA foreign_keys = ON"); + s.execute("CREATE TABLE \"dp\" (id INTEGER PRIMARY KEY)"); + s.execute("CREATE TABLE \"dc\" (id INTEGER PRIMARY KEY, dp_id INTEGER, " + key + ")"); + conn.setAutoCommit(false); + s.execute("INSERT INTO \"dc\" VALUES (1, 7)"); + s.execute("INSERT INTO \"dp\" VALUES (7)"); + conn.commit(); + } finally { + conn.setAutoCommit(true); + } + assertFirstIntEquals(conn, "SELECT COUNT(*) FROM \"dc\"", 1); + try (Statement s = conn.createStatement()) { + s.execute("DROP TABLE \"dc\""); + s.execute("DROP TABLE \"dp\""); + } + } } 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 62ffa88..cdbfdaa 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 @@ -457,7 +457,7 @@ public Optional> getAllImportedKeys(Connection connection, Str SELECT fk.CONSTRAINT_NAME AS FK_NAME, fk.TABLE_NAME AS FK_TABLE, fk_col.COLUMN_NAME AS FK_COLUMN, pk.TABLE_NAME AS PK_TABLE, pk.OWNER AS PK_SCHEMA, fk.OWNER AS FK_SCHEMA, pk_col.COLUMN_NAME AS PK_COLUMN, fk_col.POSITION AS KEY_SEQ, - fk.DELETE_RULE, pk.CONSTRAINT_NAME AS PK_NAME + fk.DELETE_RULE, fk.DEFERRABLE, fk.DEFERRED, pk.CONSTRAINT_NAME AS PK_NAME FROM ALL_CONSTRAINTS fk JOIN ALL_CONS_COLUMNS fk_col ON fk.OWNER = fk_col.OWNER AND fk.CONSTRAINT_NAME = fk_col.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS pk ON fk.R_OWNER = pk.OWNER AND fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME @@ -489,7 +489,7 @@ public Optional> getAllExportedKeys(Connection connection, Str SELECT fk.CONSTRAINT_NAME AS FK_NAME, fk.TABLE_NAME AS FK_TABLE, fk_col.COLUMN_NAME AS FK_COLUMN, pk.TABLE_NAME AS PK_TABLE, pk.OWNER AS PK_SCHEMA, fk.OWNER AS FK_SCHEMA, pk_col.COLUMN_NAME AS PK_COLUMN, fk_col.POSITION AS KEY_SEQ, - fk.DELETE_RULE, pk.CONSTRAINT_NAME AS PK_NAME + fk.DELETE_RULE, fk.DEFERRABLE, fk.DEFERRED, pk.CONSTRAINT_NAME AS PK_NAME FROM ALL_CONSTRAINTS fk JOIN ALL_CONS_COLUMNS fk_col ON fk.OWNER = fk_col.OWNER AND fk.CONSTRAINT_NAME = fk_col.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS pk ON fk.R_OWNER = pk.OWNER AND fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME @@ -1040,7 +1040,20 @@ private ImportedKey readImportedKey(ResultSet rs) throws SQLException { // support // UPDATE // CASCADE - mapOracleDeleteRule(deleteRule), Optional.ofNullable(pkName), ImportedKey.Deferrability.NOT_DEFERRABLE); + mapOracleDeleteRule(deleteRule), Optional.ofNullable(pkName), + deferrability(rs.getString("DEFERRABLE"), rs.getString("DEFERRED"))); + } + + /** + * When a key is checked, from {@code ALL_CONSTRAINTS.DEFERRABLE} ({@code DEFERRABLE} or + * {@code NOT DEFERRABLE}) and {@code DEFERRED} ({@code DEFERRED} or {@code IMMEDIATE}). + */ + static ImportedKey.Deferrability deferrability(String deferrable, String deferred) { + if (!"DEFERRABLE".equalsIgnoreCase(deferrable)) { + return ImportedKey.Deferrability.NOT_DEFERRABLE; + } + return "DEFERRED".equalsIgnoreCase(deferred) ? ImportedKey.Deferrability.INITIALLY_DEFERRED + : ImportedKey.Deferrability.INITIALLY_IMMEDIATE; } diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java index 04fdb5e..bef714b 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java @@ -402,7 +402,8 @@ public Optional> getAllImportedKeys(Connection connection, Str SELECT con.conname AS fk_name, fk_n.nspname AS fk_schema, fk_class.relname AS fk_table, fk_att.attname AS fk_column, pk_n.nspname AS pk_schema, pk_class.relname AS pk_table, pk_att.attname AS pk_column, - cols.ord AS key_seq, con.confdeltype AS delete_rule, con.confupdtype AS update_rule + cols.ord AS key_seq, con.confdeltype AS delete_rule, con.confupdtype AS update_rule, + con.condeferrable AS is_deferrable, con.condeferred AS is_deferred FROM pg_constraint con JOIN pg_class fk_class ON fk_class.oid = con.conrelid JOIN pg_namespace fk_n ON fk_n.oid = fk_class.relnamespace @@ -437,7 +438,8 @@ public Optional> getAllExportedKeys(Connection connection, Str SELECT con.conname AS fk_name, fk_n.nspname AS fk_schema, fk_class.relname AS fk_table, fk_att.attname AS fk_column, pk_n.nspname AS pk_schema, pk_class.relname AS pk_table, pk_att.attname AS pk_column, - cols.ord AS key_seq, con.confdeltype AS delete_rule, con.confupdtype AS update_rule + cols.ord AS key_seq, con.confdeltype AS delete_rule, con.confupdtype AS update_rule, + con.condeferrable AS is_deferrable, con.condeferred AS is_deferred FROM pg_constraint con JOIN pg_class fk_class ON fk_class.oid = con.conrelid JOIN pg_namespace fk_n ON fk_n.oid = fk_class.relnamespace @@ -962,7 +964,16 @@ private ImportedKey readImportedKey(ResultSet rs) throws SQLException { ColumnReference pkColRef = new ColumnReference(Optional.of(pkTableRef), pkColumn); return new ImportedKeyRecord(pkColRef, fkColRef, fkName, keySeq, mapPgReferentialAction(updateRule), - mapPgReferentialAction(deleteRule), Optional.empty(), ImportedKey.Deferrability.NOT_DEFERRABLE); + mapPgReferentialAction(deleteRule), Optional.empty(), + deferrability(rs.getBoolean("is_deferrable"), rs.getBoolean("is_deferred"))); + } + + /** When a key is checked, from {@code pg_constraint.condeferrable} and {@code condeferred}. */ + static ImportedKey.Deferrability deferrability(boolean deferrable, boolean deferred) { + if (!deferrable) { + return ImportedKey.Deferrability.NOT_DEFERRABLE; + } + return deferred ? ImportedKey.Deferrability.INITIALLY_DEFERRED : ImportedKey.Deferrability.INITIALLY_IMMEDIATE; } 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 0623604..03c5ebf 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 @@ -62,6 +62,8 @@ * 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.late_line PK (id), FK fk_late_line_orders (orders_id) → sales.orders, checked at commit, + * where the database has deferrable keys * sales.child_bare PK (id), FK fk_child_bare (orders_id) → sales.orders, no index of its own * sales.child_indexed * PK (id), INDEX ix_child_indexed (orders_id), then FK fk_child_indexed (orders_id) @@ -185,6 +187,16 @@ protected List createFilteredIndex() { return List.of(); } + /** + * The statements that create {@code late_line} in the orders' schema, with the foreign key + * {@code fk_late_line_orders (orders_id)} to the orders that is checked at the end of the + * transaction ({@code DEFERRABLE INITIALLY DEFERRED}); none where the database checks every key + * at once. + */ + protected List createDeferrableForeignKey() { + return List.of(); + } + /** Whether the database keeps the order of an index column that sorts descending. */ protected boolean keepsDescendingIndexColumns() { return true; @@ -302,6 +314,7 @@ private List fixture() { sql.addAll(createFilteredIndex()); sql.add("CREATE INDEX " + indexName(sales, "ix_orders_qty_desc") + " ON " + sales + ".orders (qty DESC, id)"); sql.addAll(createChildren()); + sql.addAll(createDeferrableForeignKey()); if (sequences()) { sql.add(createSequence(sales + ".seq_unlimited", false)); sql.add(createSequence(sales + ".seq_limited", true)); @@ -367,6 +380,24 @@ void foreignKeyAcrossSchemasNamesTheSchemaOfEachSide() throws SQLException { } } + /** + * A foreign key is reported as checked at once, and one checked at the end of the transaction as + * initially deferred, where the database has such keys. + */ + @Test + void foreignKeyWithWhenItIsChecked() throws SQLException { + List keys = provider.getAllImportedKeys(connection, null, sales()).orElseThrow(); + + assertThat(keys).filteredOn(key -> is(key.foreignKeyColumn(), sales(), "order_line", "order_id")) + .isNotEmpty().allSatisfy(key -> assertThat(key.deferrability()) + .isEqualTo(ImportedKey.Deferrability.NOT_DEFERRABLE)); + if (!createDeferrableForeignKey().isEmpty()) { + assertThat(keys).filteredOn(key -> is(key.foreignKeyColumn(), sales(), "late_line", "orders_id")) + .singleElement().satisfies(key -> assertThat(key.deferrability()) + .isEqualTo(ImportedKey.Deferrability.INITIALLY_DEFERRED)); + } + } + @Test void uniqueConstraintWithItsColumns() throws SQLException { var constraints = provider.getAllUniqueConstraints(connection, null, stock()); diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java index b99bc26..d5214a7 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java @@ -59,6 +59,13 @@ protected List createMaterializedView() { "CREATE MATERIALIZED VIEW " + sales() + ".mv_orders AS SELECT id, qty FROM " + sales() + ".orders"); } + @Override + protected List createDeferrableForeignKey() { + return List.of("CREATE TABLE " + sales() + ".late_line (id INT NOT NULL, orders_id INT," + + " CONSTRAINT pk_late_line PRIMARY KEY (id), CONSTRAINT fk_late_line_orders FOREIGN KEY (orders_id)" + + " REFERENCES " + sales() + ".orders (id) DEFERRABLE INITIALLY DEFERRED)"); + } + @Override protected MetadataProvider provider() { return new OracleMetadataProvider(); diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java index 6effca6..9c7b1ec 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java @@ -40,6 +40,13 @@ protected List createFilteredIndex() { return List.of("CREATE INDEX ix_orders_large ON sales.orders (qty) WHERE qty > 10"); } + @Override + protected List createDeferrableForeignKey() { + return List.of("CREATE TABLE sales.late_line (id INT NOT NULL, orders_id INT," + + " CONSTRAINT pk_late_line PRIMARY KEY (id), CONSTRAINT fk_late_line_orders FOREIGN KEY (orders_id)" + + " REFERENCES sales.orders (id) DEFERRABLE INITIALLY DEFERRED)"); + } + @Override protected MetadataProvider provider() { return new PostgreSqlMetadataProvider(); From 61a580209cd444a94bbb11b6d6e51194823f336c Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Thu, 12 Nov 2026 17:26:19 +0100 Subject: [PATCH 2/7] dialect: comments on views and their columns A comment on a view was written with COMMENT ON TABLE by every dialect that takes the standard form, which PostgreSQL rejects for a view, and MySQL, MariaDB, ClickHouse and Hive wrote statements for a view that their databases do not take. commentOnTable now writes COMMENT ON VIEW for a view, and DdlGenerator gains supportsCommentOnView(), true by default. PostgreSQL, H2, DuckDB and the ANSI dialect write COMMENT ON VIEW and COMMENT ON COLUMN, Oracle COMMENT ON TABLE and COLUMN, which it takes for a view, and SQL Server the MS_Description of the view and its column. MySQL and MariaDB keep no comment on a view, ClickHouse and Hive set a comment as a property of a table, and Impala takes Hive's spelling: for a view and its columns these write nothing and say so, as do SQLite and Derby, which keep no comments at all. The consistency tests check what every dialect writes for a view and its column. On PostgreSQL, Oracle and SQL Server, and on H2, the comments the dialect writes on a view and its column are read back as the snapshot reads them. The metadata contract puts a comment on a view's column too; every provider already reported it. Signed-off-by: Stefan Bischof --- .../dialect/api/generator/DdlGenerator.java | 19 +++- .../db/clickhouse/ClickHouseDialect.java | 12 +++ .../ViewCommentStatementsTest.java | 91 +++++++++++++++++++ .../sql/dialect/db/derby/DerbyDialect.java | 6 ++ .../sql/dialect/db/h2/H2ViewCommentTest.java | 50 ++++++++++ .../sql/dialect/db/hive/HiveDialect.java | 9 ++ ...osoftSqlServerGeneratorsRoundTripTest.java | 28 ++++++ .../sql/dialect/db/mysql/MySqlDialect.java | 12 +++ .../oracle/OracleGeneratorsRoundTripTest.java | 29 ++++++ .../PostgreSqlGeneratorsRoundTripTest.java | 28 ++++++ .../sql/dialect/db/sqlite/SqliteDialect.java | 6 ++ .../metadata/MetadataProviderContract.java | 19 ++-- .../metadata/MsSqlMetadataContractTest.java | 3 +- .../metadata/OracleMetadataContractTest.java | 3 +- 14 files changed, 303 insertions(+), 12 deletions(-) create mode 100644 dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java create mode 100644 dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2ViewCommentTest.java 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 401eaef..cae27d3 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 @@ -994,13 +994,15 @@ default Optional dropProcedure(String procedureName, String schemaName, // -------------------- comments -------------------- /** - * {@code COMMENT ON TABLE schema.table IS '…'}; a {@code null} comment - * removes it ({@code IS NULL}). + * {@code COMMENT ON TABLE schema.table IS '…'}, and {@code COMMENT ON VIEW} for a view + * ({@link TableReference#TYPE_VIEW}); a {@code null} comment removes it ({@code IS NULL}). * - * @return empty when the dialect cannot store table comments + * @return empty when the dialect cannot store table comments, and for a view where it keeps none + * on a view ({@link #supportsCommentOnView()}) */ default Optional commentOnTable(TableReference table, String comment) { - return Optional.of("COMMENT ON TABLE " + qualified(table) + " IS " + commentLiteral(comment)); + String kind = TableReference.TYPE_VIEW.equals(table.type()) ? "VIEW " : "TABLE "; + return Optional.of("COMMENT ON " + kind + qualified(table) + " IS " + commentLiteral(comment)); } /** @@ -1018,6 +1020,15 @@ default Optional commentOnColumn(TableReference table, String columnName + commentLiteral(comment)); } + /** + * @return true if {@code commentOnTable} and {@code commentOnColumn} write a comment on a view + * ({@link TableReference#TYPE_VIEW}) and on a view's column; false where the database + * keeps none on a view, and both are empty for one + */ + default boolean supportsCommentOnView() { + return true; + } + /** ANSI string literal for a comment ({@code '} doubled), or {@code NULL}. */ private static String commentLiteral(String comment) { return comment == null ? "NULL" : "'" + comment.replace("'", "''") + "'"; diff --git a/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java b/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java index c774f78..753d4e1 100644 --- a/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java +++ b/dialect/db/clickhouse/src/main/java/org/eclipse/daanse/sql/dialect/db/clickhouse/ClickHouseDialect.java @@ -303,6 +303,9 @@ public boolean supportsAtomicMultiRenameTable() { /** {@code ALTER TABLE t MODIFY COMMENT '…'}; {@code null} clears it. */ @Override public java.util.Optional commentOnTable(TableReference table, String comment) { + if (TableReference.TYPE_VIEW.equals(table.type())) { + return java.util.Optional.empty(); + } return java.util.Optional.of("ALTER TABLE " + qualified(table) + " MODIFY COMMENT " + chLiteral(comment)); } @@ -310,6 +313,9 @@ public java.util.Optional commentOnTable(TableReference table, String co @Override public java.util.Optional commentOnColumn(TableReference table, String columnName, String comment, org.eclipse.daanse.sql.model.schema.ColumnMetaData currentMeta) { + if (TableReference.TYPE_VIEW.equals(table.type())) { + return java.util.Optional.empty(); + } return java.util.Optional.of("ALTER TABLE " + qualified(table) + " COMMENT COLUMN " + quoteIdentifier(columnName) + " " + chLiteral(comment)); } @@ -340,4 +346,10 @@ public Optional createUser(String userName, boolean ifNotExists) { return Optional.of("CREATE USER " + (ifNotExists ? "IF NOT EXISTS " : "") + quoteIdentifier(userName) + " HOST NONE"); } + + /** ClickHouse sets a comment with {@code ALTER TABLE … MODIFY COMMENT}, which takes no view. */ + @Override + public boolean supportsCommentOnView() { + return false; + } } diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java new file mode 100644 index 0000000..0927fc4 --- /dev/null +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/ViewCommentStatementsTest.java @@ -0,0 +1,91 @@ +/* + * 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.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 to comment on the view {@code s.v} and on its column {@code c}. A dialect + * whose database keeps no comment on a view writes nothing for either and says so by + * {@link DdlGenerator#supportsCommentOnView()}. + */ +class ViewCommentStatementsTest { + + private static final TableReference VIEW = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "s")), "v", TableReference.TYPE_VIEW); + + /** The statements expected of a dialect; both null where it keeps no comment on a view. */ + record Expected(String onView, String onColumn) { + + static Expected none() { + return new Expected(null, null); + } + } + + static Stream dialects() { + Expected standard = new Expected("COMMENT ON VIEW \"s\".\"v\" IS 'it''s'", + "COMMENT ON COLUMN \"s\".\"v\".\"c\" IS 'it''s'"); + return Stream.of(of("postgresql", new PostgreSqlDialect(), standard), + of("h2", new H2Dialect(), standard), + of("duckdb", new DuckDbDialect(), standard), + of("ansi", new AnsiDialect(), standard), + of("oracle", new OracleDialect(), new Expected("COMMENT ON TABLE \"s\".\"v\" IS 'it''s'", + "COMMENT ON COLUMN \"s\".\"v\".\"c\" IS 'it''s'")), + of("mssql", new MicrosoftSqlServerDialect(), new Expected( + "IF EXISTS (SELECT 1 FROM sys.extended_properties WHERE class = 1 AND major_id = OBJECT_ID(N'\"s\".\"v\"') AND minor_id = 0 AND name = N'MS_Description') EXEC sys.sp_updateextendedproperty @name = N'MS_Description', @value = N'it''s', @level0type = N'SCHEMA', @level0name = N's', @level1type = N'VIEW', @level1name = N'v' ELSE EXEC sys.sp_addextendedproperty @name = N'MS_Description', @value = N'it''s', @level0type = N'SCHEMA', @level0name = N's', @level1type = N'VIEW', @level1name = N'v'", + "IF EXISTS (SELECT 1 FROM sys.extended_properties WHERE class = 1 AND major_id = OBJECT_ID(N'\"s\".\"v\"') AND minor_id = COLUMNPROPERTY(OBJECT_ID(N'\"s\".\"v\"'), N'c', 'ColumnId') AND name = N'MS_Description') EXEC sys.sp_updateextendedproperty @name = N'MS_Description', @value = N'it''s', @level0type = N'SCHEMA', @level0name = N's', @level1type = N'VIEW', @level1name = N'v', @level2type = N'COLUMN', @level2name = N'c' ELSE EXEC sys.sp_addextendedproperty @name = N'MS_Description', @value = N'it''s', @level0type = N'SCHEMA', @level0name = N's', @level1type = N'VIEW', @level1name = N'v', @level2type = N'COLUMN', @level2name = N'c'")), + of("mysql", new MySqlDialect(), Expected.none()), + of("mariadb", new MariaDBDialect(), Expected.none()), + of("clickhouse", new ClickHouseDialect(), Expected.none()), + of("hive", new HiveDialect(), Expected.none()), + of("impala", new ImpalaDialect(), Expected.none()), + of("sqlite", new SqliteDialect(), Expected.none()), + of("derby", new DerbyDialect(), Expected.none())); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("dialects") + void commentsOnAViewAndItsColumn(Dialect dialect, Expected expected) { + DdlGenerator ddl = dialect.ddlGenerator(); + + assertThat(ddl.supportsCommentOnView()).as("supportsCommentOnView").isEqualTo(expected.onView() != null); + assertThat(ddl.commentOnTable(VIEW, "it's")).isEqualTo(Optional.ofNullable(expected.onView())); + assertThat(ddl.commentOnColumn(VIEW, "c", "it's", null)).isEqualTo(Optional.ofNullable(expected.onColumn())); + } + + private static Arguments of(String name, Dialect dialect, Expected expected) { + return Arguments.of(Named.of(name, dialect), expected); + } +} 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 e7e7e90..aeec173 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 @@ -390,4 +390,10 @@ public boolean supportsDescendingIndexColumns() { public boolean supportsDeferrableForeignKeys() { return dialectVersion.isUnknownOrAtLeast(10, 11); } + + /** Derby keeps no comments. */ + @Override + public boolean supportsCommentOnView() { + return false; + } } diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2ViewCommentTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2ViewCommentTest.java new file mode 100644 index 0000000..dcdd0d4 --- /dev/null +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2ViewCommentTest.java @@ -0,0 +1,50 @@ +/* + * 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.h2; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.Test; + +/** The comments the dialect writes on a view and on one of its columns are those H2 keeps. */ +class H2ViewCommentTest { + + @Test + void view_comments_are_written_and_kept() throws SQLException { + try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:h2viewcomments", "sa", ""); + Statement s = conn.createStatement()) { + H2Dialect dialect = new H2Dialect(DialectInitData.fromConnection(conn)); + TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "PUBLIC")), + "V", TableReference.TYPE_VIEW); + s.execute("CREATE TABLE PUBLIC.T (A INT, B INT)"); + s.execute("CREATE VIEW PUBLIC.V AS SELECT A, B FROM PUBLIC.T"); + s.execute(dialect.ddlGenerator().commentOnTable(view, "the view's comment").orElseThrow()); + s.execute(dialect.ddlGenerator().commentOnColumn(view, "A", "the column's comment", null).orElseThrow()); + try (ResultSet rs = conn.getMetaData().getTables(null, "PUBLIC", "V", null)) { + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("REMARKS")).isEqualTo("the view's comment"); + } + try (ResultSet rs = conn.getMetaData().getColumns(null, "PUBLIC", "V", "A")) { + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("REMARKS")).isEqualTo("the column's comment"); + } + } + } +} diff --git a/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java b/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java index 6b3924b..c165650 100644 --- a/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java +++ b/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java @@ -124,6 +124,9 @@ public String name() { /** {@code ALTER TABLE t SET TBLPROPERTIES ('comment' = '…')}; {@code null} clears it. */ @Override public java.util.Optional commentOnTable(TableReference table, String comment) { + if (TableReference.TYPE_VIEW.equals(table.type())) { + return java.util.Optional.empty(); + } String s = comment == null ? "" : comment; return java.util.Optional.of("ALTER TABLE " + qualified(table) + " SET TBLPROPERTIES ('comment' = '" + s.replace("\\", "\\\\").replace("'", "\\'") + "')"); @@ -144,4 +147,10 @@ public java.util.Optional commentOnColumn(TableReference table, String c public boolean supportsNamedPrimaryKey() { return false; } + + /** Hive (and Impala, which takes its spelling) sets a comment as a property of a table; a view is not written. */ + @Override + public boolean supportsCommentOnView() { + return false; + } } 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 5eab670..0087861 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 @@ -37,6 +37,7 @@ 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.impl.DatabaseServiceImpl; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -198,4 +199,31 @@ void descending_index_column_is_created_and_read_back() throws SQLException { IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new MicrosoftSqlServerMetadataProvider(), users, "ix_users_desc", "name", "id"); } + + /** + * The comments the dialect writes on a view and on one of its columns are read back as the + * snapshot reads them, through the metadata provider or else the JDBC driver. + */ + @Test + void view_comments_are_written_and_read_back() throws SQLException { + TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "dbo")), + "v_noted_users", TableReference.TYPE_VIEW); + DatabaseServiceImpl service = new DatabaseServiceImpl(); + MicrosoftSqlServerMetadataProvider provider = new MicrosoftSqlServerMetadataProvider(); + try (Statement s = conn.createStatement()) { + s.execute("CREATE VIEW [dbo].[v_noted_users] AS SELECT id, name FROM [dbo].[users]"); + s.execute(dialect.ddlGenerator().commentOnTable(view, "the view's comment").orElseThrow()); + s.execute(dialect.ddlGenerator().commentOnColumn(view, "name", "the column's comment", null) + .orElseThrow()); + assertThat(service.getTableDefinitions(conn, provider, null, "dbo", "v_noted_users", null)) + .filteredOn(t -> t.table().name().equals("v_noted_users")).singleElement() + .satisfies(t -> assertThat(t.tableMetaData().remarks()).contains("the view's comment")); + assertThat(service.getColumnDefinitions(conn, provider, null, "dbo", "v_noted_users", null)) + .filteredOn(c -> c.column().table().map(TableReference::name).filter("v_noted_users"::equals).isPresent() + && c.column().name().equals("name")) + .singleElement() + .satisfies(c -> assertThat(c.columnMetaData().remarks()).contains("the column's comment")); + s.execute(dialect.ddlGenerator().dropView(view, false)); + } + } } 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 3aa7f2f..0e2e730 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 @@ -707,6 +707,9 @@ public String alterColumnSetNullability(TableReference table, String columnName, /** {@code ALTER TABLE t COMMENT = '…'} — MySQL has no COMMENT ON; {@code null} clears it. */ @Override public Optional commentOnTable(TableReference table, String comment) { + if (TableReference.TYPE_VIEW.equals(table.type())) { + return Optional.empty(); + } return Optional.of("ALTER TABLE " + qualified(table) + " COMMENT = " + mysqlLiteral(comment)); } @@ -718,6 +721,9 @@ public Optional commentOnTable(TableReference table, String comment) { @Override public Optional commentOnColumn(TableReference table, String columnName, String comment, ColumnMetaData currentMeta) { + if (TableReference.TYPE_VIEW.equals(table.type())) { + return Optional.empty(); + } if (currentMeta == null) { throw new IllegalArgumentException("currentMeta must not be null for a MySQL column comment"); } @@ -887,4 +893,10 @@ public Optional createUser(String userName, boolean ifNotExists) { public boolean supportsDescendingIndexColumns() { return dialectVersion.isUnknownOrAtLeast(8, 0); } + + /** MySQL and MariaDB keep no comment on a view or its columns. */ + @Override + public boolean supportsCommentOnView() { + return false; + } } 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 b6d7be3..65ee216 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 @@ -34,6 +34,7 @@ import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip; import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal; import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey; +import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl; import org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -213,4 +214,32 @@ void deferrable_foreign_key_is_checked_at_commit_and_read_back() throws SQLExcep s.execute("DROP TABLE \"" + schema + "\".\"DP\""); } } + + /** + * The comments the dialect writes on a view and on one of its columns are read back as the + * snapshot reads them, through the metadata provider or else the JDBC driver. + */ + @Test + void view_comments_are_written_and_read_back() throws SQLException { + String schema = CONTAINER.getUsername().toUpperCase(); + TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), + "V_NOTED", TableReference.TYPE_VIEW); + DatabaseServiceImpl service = new DatabaseServiceImpl(); + OracleMetadataProvider provider = new OracleMetadataProvider(); + try (Statement s = conn.createStatement()) { + s.execute("CREATE VIEW \"" + schema + "\".\"V_NOTED\" AS SELECT ID, NAME FROM \"" + schema + "\".\"USERS\""); + s.execute(dialect.ddlGenerator().commentOnTable(view, "the view's comment").orElseThrow()); + s.execute(dialect.ddlGenerator().commentOnColumn(view, "NAME", "the column's comment", null) + .orElseThrow()); + assertThat(service.getTableDefinitions(conn, provider, null, schema, "V_NOTED", null)) + .filteredOn(t -> t.table().name().equals("V_NOTED")).singleElement() + .satisfies(t -> assertThat(t.tableMetaData().remarks()).contains("the view's comment")); + assertThat(service.getColumnDefinitions(conn, provider, null, schema, "V_NOTED", null)) + .filteredOn(c -> c.column().table().map(TableReference::name).filter("V_NOTED"::equals).isPresent() + && c.column().name().equals("NAME")) + .singleElement() + .satisfies(c -> assertThat(c.columnMetaData().remarks()).contains("the column's comment")); + s.execute(dialect.ddlGenerator().dropView(view, false)); + } + } } 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 1b14469..aa9d368 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 @@ -37,6 +37,7 @@ import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo; import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal; import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey; +import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl; import org.eclipse.daanse.sql.jdbc.metadata.PostgreSqlMetadataProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -215,4 +216,31 @@ void deferrable_foreign_key_is_checked_at_commit_and_read_back() throws SQLExcep s.execute("DROP TABLE \"public\".\"dp\""); } } + + /** + * The comments the dialect writes on a view and on one of its columns are read back as the + * snapshot reads them, through the metadata provider or else the JDBC driver. + */ + @Test + void view_comments_are_written_and_read_back() throws SQLException { + TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "public")), + "v_noted", TableReference.TYPE_VIEW); + DatabaseServiceImpl service = new DatabaseServiceImpl(); + PostgreSqlMetadataProvider provider = new PostgreSqlMetadataProvider(); + try (Statement s = conn.createStatement()) { + s.execute("CREATE VIEW \"public\".\"v_noted\" AS SELECT id, name FROM \"public\".\"users\""); + s.execute(dialect.ddlGenerator().commentOnTable(view, "the view's comment").orElseThrow()); + s.execute(dialect.ddlGenerator().commentOnColumn(view, "name", "the column's comment", null) + .orElseThrow()); + assertThat(service.getTableDefinitions(conn, provider, null, "public", "v_noted", null)) + .filteredOn(t -> t.table().name().equals("v_noted")).singleElement() + .satisfies(t -> assertThat(t.tableMetaData().remarks()).contains("the view's comment")); + assertThat(service.getColumnDefinitions(conn, provider, null, "public", "v_noted", null)) + .filteredOn(c -> c.column().table().map(TableReference::name).filter("v_noted"::equals).isPresent() + && c.column().name().equals("name")) + .singleElement() + .satisfies(c -> assertThat(c.columnMetaData().remarks()).contains("the column's comment")); + s.execute(dialect.ddlGenerator().dropView(view, false)); + } + } } 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 df3b5d7..f571320 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 @@ -342,4 +342,10 @@ public boolean supportsDescendingIndexColumns() { public boolean supportsDeferrableForeignKeys() { return true; } + + /** SQLite keeps no comments. */ + @Override + public boolean supportsCommentOnView() { + 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 03c5ebf..fba6a1d 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 @@ -91,6 +91,9 @@ abstract class MetadataProviderContract { /** The comment on the view {@code sales.v_orders}. */ protected static final String VIEW_COMMENT = "The orders in short"; + /** The comment on the column {@code qty} of the view {@code sales.v_orders}. */ + protected static final String VIEW_COLUMN_COMMENT = "How many are ordered"; + /** The comment on the function {@code sales.f_answer}. */ protected static final String FUNCTION_COMMENT = "The answer to everything"; @@ -227,13 +230,14 @@ protected List createChildren() { /** * The statements that put the comments above on {@code stock.product}, its column {@code code} - * and, where {@link #viewComments()}, the view {@code sales.v_orders}; by default - * {@code COMMENT ON}. + * and, where {@link #viewComments()}, the view {@code sales.v_orders} and its column {@code qty}; + * by default {@code COMMENT ON}. */ protected List comments() { return List.of("COMMENT ON TABLE " + stock() + ".product IS '" + PRODUCT_COMMENT + "'", "COMMENT ON COLUMN " + stock() + ".product.code IS '" + CODE_COMMENT + "'", - "COMMENT ON VIEW " + sales() + ".v_orders IS '" + VIEW_COMMENT + "'"); + "COMMENT ON VIEW " + sales() + ".v_orders IS '" + VIEW_COMMENT + "'", + "COMMENT ON COLUMN " + sales() + ".v_orders.qty IS '" + VIEW_COLUMN_COMMENT + "'"); } /** Whether the database keeps a comment on a view. */ @@ -535,16 +539,19 @@ void sequencesWithAndWithoutLimits() throws SQLException { } /** - * The comments on a table, on one of its columns and on a view, as the snapshot reads them: from - * the provider's tables and columns where it reads them itself, otherwise from the JDBC driver. + * The comments on a table, on one of its columns, on a view and on one of its columns, as the + * snapshot reads them: from the provider's tables and columns where it reads them itself, + * otherwise from the JDBC driver. */ @Test - void commentsOnATableItsColumnAndAView() throws SQLException { + void commentsOnTablesViewsAndTheirColumns() throws SQLException { assertThat(tableRemarks(stock(), "product")).as("comment on the table").contains(PRODUCT_COMMENT); assertThat(columns(stock(), "product").get("code").remarks()).as("comment on the column") .contains(CODE_COMMENT); if (viewComments()) { assertThat(tableRemarks(sales(), "v_orders")).as("comment on the view").contains(VIEW_COMMENT); + assertThat(columns(sales(), "v_orders").get("qty").remarks()).as("comment on the view's column") + .contains(VIEW_COLUMN_COMMENT); } } diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java index be169d7..e1cf592 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java @@ -51,7 +51,8 @@ protected void close() { protected List comments() { return List.of(description(PRODUCT_COMMENT, "stock", "TABLE", "product", null), description(CODE_COMMENT, "stock", "TABLE", "product", "code"), - description(VIEW_COMMENT, "sales", "VIEW", "v_orders", null)); + description(VIEW_COMMENT, "sales", "VIEW", "v_orders", null), + description(VIEW_COLUMN_COMMENT, "sales", "VIEW", "v_orders", "qty")); } @Override diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java index d5214a7..c8c23f3 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java @@ -111,7 +111,8 @@ protected String indexName(String schema, String name) { protected List comments() { return List.of("COMMENT ON TABLE STOCK.product IS '" + PRODUCT_COMMENT + "'", "COMMENT ON COLUMN STOCK.product.code IS '" + CODE_COMMENT + "'", - "COMMENT ON TABLE " + sales() + ".v_orders IS '" + VIEW_COMMENT + "'"); + "COMMENT ON TABLE " + sales() + ".v_orders IS '" + VIEW_COMMENT + "'", + "COMMENT ON COLUMN " + sales() + ".v_orders.qty IS '" + VIEW_COLUMN_COMMENT + "'"); } @Override From 6d3b2222f901cde03a40cd5b7c1a34ddc7072bde Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Thu, 12 Nov 2026 18:20:47 +0100 Subject: [PATCH 3/7] dialect, metadata: CREATE and DROP for functions and procedures A model could hold a function or a procedure, with its parameters and its body, but the dialect API could only write the grants on it, so a routine could not be written into a database. The providers read a routine's body but not the language it is written in. DdlGenerator gains the records RoutineParameter(name, mode, type), RoutineDefinition(schema, name, parameters, returnType, language, body) and RoutineSignature(schema, name, parameterTypes), the enum ParameterMode, routineLanguages(), createFunction(definition, orReplace), createProcedure(definition, orReplace), dropFunction(signature, ifExists) and dropProcedure(signature, ifExists). The body is the database's own and is written unchanged; each statement is one statement for JDBC, without a client's delimiter. A dialect writes nothing for a body in a language it does not take, or for a parameter mode its database has not. - PostgreSQL takes sql and plpgsql: the body in a dollar quote that does not occur in it, OR REPLACE, IN, OUT and INOUT parameters, and DROP with the parameter types, which names one of several overloads. - Oracle takes plsql: RETURN type AS body, IN, OUT and IN OUT, OR REPLACE, IF EXISTS from 23; a schema holds one routine of a name, so DROP names it alone. - SQL Server takes tsql: parameters as @variables, OUTPUT for OUT and INOUT in a procedure, IN only in a function, OR ALTER and DROP ... IF EXISTS from 2016. - MySQL and MariaDB take sql: the body starts with the routine's characteristics where it has them, as the database writes them; IN only in a function, OR REPLACE on MariaDB. - H2's routines are Java methods whose signature is in their source, DuckDB's macros have no types, and SQLite, Derby, ClickHouse, Hive, Impala and the ANSI dialect write no routines. Function and Procedure gain language(), and their records take it as a further component and keep their constructors without it. PostgreSQL reads pg_language, MySQL and MariaDB ROUTINE_BODY, H2 EXTERNAL_LANGUAGE; Oracle's functions and procedures are plsql and SQL Server's tsql where the module holds their text. The consistency tests check the statements of every dialect. On PostgreSQL, Oracle, SQL Server, MySQL and MariaDB a function and a procedure are created, created again where the dialect replaces them, the function is called, both are read back with their parameters, language and body, and dropped by their signature; on PostgreSQL one of two overloads is dropped by its parameter types. The metadata contract expects the language of a function's body. Signed-off-by: Stefan Bischof --- .../dialect/api/generator/DdlGenerator.java | 118 +++++++++++++ .../RoutineStatementsTest.java | 165 ++++++++++++++++++ .../dialect/db/mariadb/MariaDBDialect.java | 6 + .../MariaDBGeneratorsRoundTripTest.java | 24 +++ .../MicrosoftSqlServerDialect.java | 70 ++++++++ ...osoftSqlServerGeneratorsRoundTripTest.java | 21 +++ .../sql/dialect/db/mysql/MySqlDialect.java | 66 +++++++ .../mysql/MySqlGeneratorsRoundTripTest.java | 24 +++ .../sql/dialect/db/oracle/OracleDialect.java | 66 +++++++ .../oracle/OracleGeneratorsRoundTripTest.java | 23 +++ .../db/postgresql/PostgreSqlDialect.java | 72 ++++++++ .../PostgreSqlGeneratorsRoundTripTest.java | 46 +++++ .../db/testsupport/RoutineRoundTrip.java | 127 ++++++++++++++ .../daanse/sql/jdbc/api/schema/Function.java | 8 + .../daanse/sql/jdbc/api/schema/Procedure.java | 8 + .../sql/jdbc/metadata/H2MetadataProvider.java | 14 +- .../metadata/MariaDbMetadataProvider.java | 11 +- .../MicrosoftSqlServerMetadataProvider.java | 7 +- .../jdbc/metadata/MySqlMetadataProvider.java | 11 +- .../jdbc/metadata/OracleMetadataProvider.java | 9 +- .../metadata/PostgreSqlMetadataProvider.java | 11 +- .../jdbc/metadata/H2MetadataContractTest.java | 6 + .../metadata/MariaDbMetadataContractTest.java | 6 + .../metadata/MetadataProviderContract.java | 19 ++ .../metadata/MsSqlMetadataContractTest.java | 6 + .../metadata/MySqlMetadataContractTest.java | 6 + .../PostgreSqlMetadataContractTest.java | 6 + .../jdbc/record/schema/FunctionRecord.java | 10 +- .../jdbc/record/schema/ProcedureRecord.java | 10 +- 29 files changed, 954 insertions(+), 22 deletions(-) create mode 100644 dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoutineStatementsTest.java create mode 100644 dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/RoutineRoundTrip.java 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 cae27d3..c69d925 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 @@ -991,6 +991,124 @@ default Optional dropProcedure(String procedureName, String schemaName, return Optional.empty(); } + // -------------------- DDL — functions and procedures -------------------- + + /** How a parameter of a routine passes its value: into the routine, out of it, or both. */ + enum ParameterMode { + IN, OUT, INOUT + } + + /** + * A parameter of a routine: its name, how it passes its value ({@code IN} where none is given) + * and its type, written as given. + */ + record RoutineParameter(String name, ParameterMode mode, String type) { + + public RoutineParameter { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("parameter name must not be blank"); + } + if (type == null || type.isBlank()) { + throw new IllegalArgumentException("parameter type must not be blank"); + } + mode = mode == null ? ParameterMode.IN : mode; + } + + /** An {@code IN} parameter. */ + public static RoutineParameter in(String name, String type) { + return new RoutineParameter(name, ParameterMode.IN, type); + } + } + + /** + * A function or procedure to create: its schema ({@code null} for none), its name, its parameters + * in order, the type a function returns ({@code null} for a procedure, and for a function whose + * {@code OUT} parameters make its result where the database derives the result from them), the + * language of its body, and the body. The body is always the database's own and is written + * unchanged. + */ + record RoutineDefinition(String schemaName, String name, List parameters, String returnType, + String language, String body) { + + public RoutineDefinition { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("routine name must not be blank"); + } + if (body == null || body.isBlank()) { + throw new IllegalArgumentException("routine body must not be blank"); + } + parameters = parameters == null ? List.of() : List.copyOf(parameters); + } + } + + /** + * A routine to drop: its schema ({@code null} for none), its name and, to name one of several + * routines of that name (overloads), the types of its parameters in order; {@code null} names it + * by its name alone. + */ + record RoutineSignature(String schemaName, String name, List parameterTypes) { + + public RoutineSignature { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("routine name must not be blank"); + } + parameterTypes = parameterTypes == null ? null : List.copyOf(parameterTypes); + } + } + + /** + * The languages this dialect writes the body of a routine in, in lower case ({@code sql}, + * {@code plpgsql}, {@code plsql}, {@code tsql}); empty where it writes no routines. A routine whose + * body is in another language is not written. + */ + default java.util.Set routineLanguages() { + return java.util.Set.of(); + } + + /** + * {@code CREATE [OR REPLACE] FUNCTION schema.name (parameters) RETURNS type … body}: one + * statement, without a client's delimiter. With {@code orReplace} an existing function of that + * signature is replaced where the dialect can say so; elsewhere the statement fails on it. + * + * @return empty where the dialect writes no function in the definition's language + * ({@link #routineLanguages()}), or cannot write one of its parameters' modes + */ + default Optional createFunction(RoutineDefinition function, boolean orReplace) { + return Optional.empty(); + } + + /** + * {@code CREATE [OR REPLACE] PROCEDURE schema.name (parameters) … body}, as + * {@link #createFunction} writes a function; the definition's return type is not used. + * + * @return empty where the dialect writes no procedure in the definition's language + * ({@link #routineLanguages()}), or cannot write one of its parameters' modes + */ + default Optional createProcedure(RoutineDefinition procedure, boolean orReplace) { + return Optional.empty(); + } + + /** + * {@code DROP FUNCTION [IF EXISTS] schema.name [(types)]}: the types name one overload where the + * database has overloads. With {@code ifExists} a missing function is no error where the dialect + * can say so. + * + * @return empty where the dialect writes no routines + */ + default Optional dropFunction(RoutineSignature function, boolean ifExists) { + return Optional.empty(); + } + + /** + * {@code DROP PROCEDURE [IF EXISTS] schema.name [(types)]}, as {@link #dropFunction} drops a + * function. + * + * @return empty where the dialect writes no routines + */ + default Optional dropProcedure(RoutineSignature procedure, boolean ifExists) { + return Optional.empty(); + } + // -------------------- comments -------------------- /** diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoutineStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoutineStatementsTest.java new file mode 100644 index 0000000..f3ff792 --- /dev/null +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoutineStatementsTest.java @@ -0,0 +1,165 @@ +/* + * 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.Set; +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.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; +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.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * What each dialect writes to create and drop the function {@code s.f (a, b)} and the procedure + * {@code s.p (n, INOUT total)}, with a body in a language it takes. A dialect that writes no + * routines writes nothing and takes no language ({@link DdlGenerator#routineLanguages()}). + */ +class RoutineStatementsTest { + + /** What a dialect takes and writes; the statements are null where it writes no routines. */ + record Expected(Set languages, String language, String types, String body, String procedureBody, + String createFunction, String createOrReplaceFunction, String createProcedure, String dropFunction, + String dropProcedure) { + + static Expected none() { + return new Expected(Set.of(), "sql", "INT", "RETURN a + b", "SET total = total + n", null, null, null, + null, null); + } + } + + static Stream dialects() { + return Stream.of( + of("postgresql", new PostgreSqlDialect(), new Expected(Set.of("sql", "plpgsql"), "sql", "integer", + "SELECT a + b", "BEGIN total := total + n; END", + "CREATE FUNCTION \"s\".\"f\"(\"a\" integer, \"b\" integer) RETURNS integer LANGUAGE sql" + + " AS $$SELECT a + b$$", + "CREATE OR REPLACE FUNCTION \"s\".\"f\"(\"a\" integer, \"b\" integer) RETURNS integer" + + " LANGUAGE sql AS $$SELECT a + b$$", + "CREATE PROCEDURE \"s\".\"p\"(\"n\" integer, INOUT \"total\" integer) LANGUAGE sql" + + " AS $$BEGIN total := total + n; END$$", + "DROP FUNCTION IF EXISTS \"s\".\"f\"(integer, integer)", "DROP PROCEDURE \"s\".\"p\"")), + of("oracle, no version", new OracleDialect(), new Expected(Set.of("plsql"), "plsql", "NUMBER", + "BEGIN RETURN a + b; END;", "BEGIN total := total + n; END;", + "CREATE FUNCTION \"s\".\"f\"(\"a\" IN NUMBER, \"b\" IN NUMBER) RETURN NUMBER AS" + + " BEGIN RETURN a + b; END;", + "CREATE OR REPLACE FUNCTION \"s\".\"f\"(\"a\" IN NUMBER, \"b\" IN NUMBER) RETURN NUMBER AS" + + " BEGIN RETURN a + b; END;", + "CREATE PROCEDURE \"s\".\"p\"(\"n\" IN NUMBER, \"total\" IN OUT NUMBER) AS" + + " BEGIN total := total + n; END;", + "DROP FUNCTION \"s\".\"f\"", "DROP PROCEDURE \"s\".\"p\"")), + of("oracle 23", new OracleDialect(version(23, 0)), new Expected(Set.of("plsql"), "plsql", "NUMBER", + "BEGIN RETURN a + b; END;", "BEGIN total := total + n; END;", + "CREATE FUNCTION \"s\".\"f\"(\"a\" IN NUMBER, \"b\" IN NUMBER) RETURN NUMBER AS" + + " BEGIN RETURN a + b; END;", + "CREATE OR REPLACE FUNCTION \"s\".\"f\"(\"a\" IN NUMBER, \"b\" IN NUMBER) RETURN NUMBER AS" + + " BEGIN RETURN a + b; END;", + "CREATE PROCEDURE \"s\".\"p\"(\"n\" IN NUMBER, \"total\" IN OUT NUMBER) AS" + + " BEGIN total := total + n; END;", + "DROP FUNCTION IF EXISTS \"s\".\"f\"", "DROP PROCEDURE \"s\".\"p\"")), + of("mssql", new MicrosoftSqlServerDialect(), new Expected(Set.of("tsql"), "tsql", "INT", + "BEGIN RETURN @a + @b END", "BEGIN SET @total = @total + @n END", + "CREATE FUNCTION \"s\".\"f\"(@a INT, @b INT) RETURNS INT AS BEGIN RETURN @a + @b END", + "CREATE OR ALTER FUNCTION \"s\".\"f\"(@a INT, @b INT) RETURNS INT AS BEGIN RETURN @a + @b END", + "CREATE PROCEDURE \"s\".\"p\" @n INT, @total INT OUTPUT AS BEGIN SET @total = @total + @n END", + "DROP FUNCTION IF EXISTS \"s\".\"f\"", "DROP PROCEDURE \"s\".\"p\"")), + of("mysql", new MySqlDialect(), new Expected(Set.of("sql"), "sql", "INT", "DETERMINISTIC RETURN a + b", + "SET total = total + n", + "CREATE FUNCTION `s`.`f`(`a` INT, `b` INT) RETURNS INT DETERMINISTIC RETURN a + b", + "CREATE FUNCTION `s`.`f`(`a` INT, `b` INT) RETURNS INT DETERMINISTIC RETURN a + b", + "CREATE PROCEDURE `s`.`p`(IN `n` INT, INOUT `total` INT) SET total = total + n", + "DROP FUNCTION IF EXISTS `s`.`f`", "DROP PROCEDURE `s`.`p`")), + of("mariadb", new MariaDBDialect(), new Expected(Set.of("sql"), "sql", "INT", + "DETERMINISTIC RETURN a + b", "SET total = total + n", + "CREATE FUNCTION `s`.`f`(`a` INT, `b` INT) RETURNS INT DETERMINISTIC RETURN a + b", + "CREATE OR REPLACE FUNCTION `s`.`f`(`a` INT, `b` INT) RETURNS INT DETERMINISTIC RETURN a + b", + "CREATE PROCEDURE `s`.`p`(IN `n` INT, INOUT `total` INT) SET total = total + n", + "DROP FUNCTION IF EXISTS `s`.`f`", "DROP PROCEDURE `s`.`p`")), + of("h2", new H2Dialect(), Expected.none()), + of("duckdb", new DuckDbDialect(), Expected.none()), + of("sqlite", new SqliteDialect(), Expected.none()), + of("derby", new DerbyDialect(), Expected.none()), + of("clickhouse", new ClickHouseDialect(), Expected.none()), + of("hive", new HiveDialect(), Expected.none()), + of("impala", new ImpalaDialect(), Expected.none()), + of("ansi", new AnsiDialect(), Expected.none())); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("dialects") + void createAndDropAFunctionAndAProcedure(Dialect dialect, Expected expected) { + DdlGenerator ddl = dialect.ddlGenerator(); + RoutineDefinition function = new RoutineDefinition("s", "f", + List.of(RoutineParameter.in("a", expected.types()), RoutineParameter.in("b", expected.types())), + expected.types(), expected.language(), expected.body()); + RoutineDefinition procedure = new RoutineDefinition("s", "p", + List.of(RoutineParameter.in("n", expected.types()), + new RoutineParameter("total", ParameterMode.INOUT, expected.types())), + null, expected.language(), expected.procedureBody()); + + assertThat(ddl.routineLanguages()).isEqualTo(expected.languages()); + assertThat(ddl.createFunction(function, false)).isEqualTo(Optional.ofNullable(expected.createFunction())); + assertThat(ddl.createFunction(function, true)) + .isEqualTo(Optional.ofNullable(expected.createOrReplaceFunction())); + assertThat(ddl.createProcedure(procedure, false)).isEqualTo(Optional.ofNullable(expected.createProcedure())); + assertThat(ddl.dropFunction(new RoutineSignature("s", "f", List.of(expected.types(), expected.types())), true)) + .isEqualTo(Optional.ofNullable(expected.dropFunction())); + assertThat(ddl.dropProcedure(new RoutineSignature("s", "p", null), false)) + .isEqualTo(Optional.ofNullable(expected.dropProcedure())); + assertThat(ddl.createFunction(new RoutineDefinition("s", "f", List.of(), "INT", "cobol", "x"), false)) + .as("a body in a language the dialect does not take").isEmpty(); + } + + /** SQL Server's function has no OUT parameter, and MySQL's none but IN. */ + @Test + void aFunctionWithAnOutParameterWhereTheDatabaseHasNone() { + RoutineDefinition tsql = new RoutineDefinition("s", "f", + List.of(new RoutineParameter("r", ParameterMode.OUT, "INT")), "INT", "tsql", "BEGIN RETURN 1 END"); + RoutineDefinition sql = new RoutineDefinition("s", "f", + List.of(new RoutineParameter("r", ParameterMode.OUT, "INT")), "INT", "sql", "RETURN 1"); + + assertThat(new MicrosoftSqlServerDialect().ddlGenerator().createFunction(tsql, false)).isEmpty(); + assertThat(new MySqlDialect().ddlGenerator().createFunction(sql, false)).isEmpty(); + assertThat(new MariaDBDialect().ddlGenerator().createFunction(sql, false)).isEmpty(); + } + + private static Arguments of(String name, Dialect dialect, Expected 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/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 2f9cbd6..a93d586 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 @@ -190,4 +190,10 @@ public boolean supportsUsers() { public boolean supportsDescendingIndexColumns() { return dialectVersion.isUnknownOrAtLeast(10, 8); } + + /** MariaDB writes a routine {@code CREATE OR REPLACE}, from 10.1.3. */ + @Override + protected boolean createOrReplaceRoutine() { + return true; + } } 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 2d55e3c..bb17839 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 @@ -27,9 +27,13 @@ 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.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; 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.RoutineRoundTrip; 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; @@ -134,4 +138,24 @@ void descending_index_column_is_created_and_read_back() throws SQLException { IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new MariaDbMetadataProvider(), users, "ix_users_desc", "name", "id"); } + + /** + * A function and a procedure the dialect writes are created, the function is called, both are + * read back with their parameters, language and body, and dropped by their signature. A body + * starts with the routine's characteristics, as the database writes them. + */ + @Test + void routines_are_created_called_read_back_and_dropped() throws SQLException { + RoutineDefinition function = new RoutineDefinition("rt", "rt_add", + List.of(RoutineParameter.in("a", "INT"), RoutineParameter.in("b", "INT")), "INT", "sql", + "DETERMINISTIC RETURN a + b"); + RoutineDefinition procedure = new RoutineDefinition("rt", "rt_bump", + List.of(RoutineParameter.in("n", "INT"), new RoutineParameter("total", ParameterMode.INOUT, "INT")), + null, "sql", "SET total = total + n"); + // root may create a function while the binary log is on; the container's user may not + try (Connection root = DriverManager.getConnection(CONTAINER.getJdbcUrl(), "root", CONTAINER.getPassword())) { + RoutineRoundTrip.assertRoutineRoundTrip(root, dialect.ddlGenerator(), new MariaDbMetadataProvider(), function, procedure, + "SELECT `rt`.`rt_add`(2, 3)", 5, List.of("n IN", "total INOUT"), "a + b", "total = total + n"); + } + } } 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 745c9b9..01509f4 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 @@ -26,7 +26,13 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; +import java.util.Locale; import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; import org.eclipse.daanse.sql.model.schema.ColumnDefinition; import org.eclipse.daanse.sql.model.schema.ColumnMetaData; @@ -943,4 +949,68 @@ public boolean supportsFilteredIndexes() { public boolean supportsDescendingIndexColumns() { return true; } + + /** SQL Server writes a routine's body in T-SQL. */ + @Override + public Set routineLanguages() { + return Set.of("tsql"); + } + + /** + * {@code CREATE [OR ALTER] FUNCTION s.f (@a INT) RETURNS INT AS body}: a parameter is a variable, + * its name begins with {@code @}. A function has {@code IN} parameters only and needs its return + * type. {@code OR ALTER} from SQL Server 2016. + */ + @Override + public Optional createFunction(RoutineDefinition function, boolean orReplace) { + if (!routineLanguages().contains(function.language().toLowerCase(Locale.ROOT)) + || function.returnType() == null + || function.parameters().stream().anyMatch(p -> p.mode() != ParameterMode.IN)) { + return Optional.empty(); + } + return Optional.of("CREATE " + orAlter(orReplace) + "FUNCTION " + + qualifiedRoutine(function.schemaName(), function.name()) + "(" + + function.parameters().stream().map(p -> variable(p.name()) + " " + p.type()) + .collect(Collectors.joining(", ")) + + ") RETURNS " + function.returnType() + " AS " + function.body()); + } + + /** + * {@code CREATE [OR ALTER] PROCEDURE s.p @n INT, @total INT OUTPUT AS body}: an {@code OUT} or + * {@code INOUT} parameter is an {@code OUTPUT} one, which passes its value both ways. + */ + @Override + public Optional createProcedure(RoutineDefinition procedure, boolean orReplace) { + if (!routineLanguages().contains(procedure.language().toLowerCase(Locale.ROOT))) { + return Optional.empty(); + } + String parameters = procedure.parameters().stream() + .map(p -> variable(p.name()) + " " + p.type() + (p.mode() == ParameterMode.IN ? "" : " OUTPUT")) + .collect(Collectors.joining(", ")); + return Optional.of("CREATE " + orAlter(orReplace) + "PROCEDURE " + + qualifiedRoutine(procedure.schemaName(), procedure.name()) + + (parameters.isEmpty() ? "" : " " + parameters) + " AS " + procedure.body()); + } + + /** {@code DROP FUNCTION [IF EXISTS] s.f}; SQL Server has no overloads. {@code IF EXISTS} from 2016. */ + @Override + public Optional dropFunction(RoutineSignature function, boolean ifExists) { + return Optional.of("DROP FUNCTION " + (ifExists && dialectVersion.isUnknownOrAtLeast(13, 0) ? "IF EXISTS " : "") + + qualifiedRoutine(function.schemaName(), function.name())); + } + + /** {@code DROP PROCEDURE [IF EXISTS] s.p}, as {@link #dropFunction}. */ + @Override + public Optional dropProcedure(RoutineSignature procedure, boolean ifExists) { + return Optional.of("DROP PROCEDURE " + (ifExists && dialectVersion.isUnknownOrAtLeast(13, 0) ? "IF EXISTS " : "") + + qualifiedRoutine(procedure.schemaName(), procedure.name())); + } + + private String orAlter(boolean orReplace) { + return orReplace && dialectVersion.isUnknownOrAtLeast(13, 0) ? "OR ALTER " : ""; + } + + private static String variable(String name) { + return name.startsWith("@") ? name : "@" + name; + } } 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 0087861..df873b9 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 @@ -31,9 +31,13 @@ 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.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; 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.RoutineRoundTrip; 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; @@ -226,4 +230,21 @@ void view_comments_are_written_and_read_back() throws SQLException { s.execute(dialect.ddlGenerator().dropView(view, false)); } } + + /** + * A function and a procedure the dialect writes are created, the function is called, both are + * read back with their parameters, language and body, and dropped by their signature. + */ + @Test + void routines_are_created_called_read_back_and_dropped() throws SQLException { + RoutineDefinition function = new RoutineDefinition("dbo", "rt_add", + List.of(RoutineParameter.in("a", "INT"), RoutineParameter.in("b", "INT")), "INT", "tsql", + "BEGIN RETURN @a + @b END"); + RoutineDefinition procedure = new RoutineDefinition("dbo", "rt_bump", + List.of(RoutineParameter.in("n", "INT"), new RoutineParameter("total", ParameterMode.INOUT, "INT")), + null, "tsql", "BEGIN SET @total = @total + @n END"); + RoutineRoundTrip.assertRoutineRoundTrip(conn, dialect.ddlGenerator(), new MicrosoftSqlServerMetadataProvider(), + function, procedure, "SELECT [dbo].[rt_add](2, 3)", 5, List.of("n IN", "total OUT"), "@a + @b", + "@total = @total + @n"); + } } 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 0e2e730..a9c193e 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 @@ -25,11 +25,17 @@ import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import java.util.stream.Collectors; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; import org.eclipse.daanse.sql.model.schema.ColumnMetaData; import org.eclipse.daanse.sql.model.schema.TableReference; @@ -899,4 +905,64 @@ public boolean supportsDescendingIndexColumns() { public boolean supportsCommentOnView() { return false; } + + /** MySQL and MariaDB write a routine's body in their SQL. */ + @Override + public Set routineLanguages() { + return Set.of("sql"); + } + + /** + * {@code CREATE FUNCTION s.f (a INT) RETURNS INT body}. The body starts with the function's + * characteristics where it has them ({@code DETERMINISTIC}, {@code READS SQL DATA}), as the + * database writes them, and is written unchanged; with binary logging on, MySQL takes a function + * only with one of them. A function has {@code IN} parameters only and needs its return type. + * MySQL has no {@code OR REPLACE}; it is left out. + */ + @Override + public Optional createFunction(RoutineDefinition function, boolean orReplace) { + if (!routineLanguages().contains(function.language().toLowerCase(Locale.ROOT)) + || function.returnType() == null + || function.parameters().stream().anyMatch(p -> p.mode() != ParameterMode.IN)) { + return Optional.empty(); + } + return Optional.of("CREATE " + (orReplace && createOrReplaceRoutine() ? "OR REPLACE " : "") + "FUNCTION " + + qualifiedRoutine(function.schemaName(), function.name()) + "(" + + function.parameters().stream().map(p -> quoteIdentifier(p.name()) + " " + p.type()) + .collect(Collectors.joining(", ")) + + ") RETURNS " + function.returnType() + " " + function.body()); + } + + /** {@code CREATE PROCEDURE s.p (IN n INT, INOUT total INT) body}, the body as for a function. */ + @Override + public Optional createProcedure(RoutineDefinition procedure, boolean orReplace) { + if (!routineLanguages().contains(procedure.language().toLowerCase(Locale.ROOT))) { + return Optional.empty(); + } + return Optional.of("CREATE " + (orReplace && createOrReplaceRoutine() ? "OR REPLACE " : "") + "PROCEDURE " + + qualifiedRoutine(procedure.schemaName(), procedure.name()) + "(" + + procedure.parameters().stream() + .map(p -> p.mode().name() + " " + quoteIdentifier(p.name()) + " " + p.type()) + .collect(Collectors.joining(", ")) + + ") " + procedure.body()); + } + + /** {@code DROP FUNCTION [IF EXISTS] s.f}; a schema holds one routine of a name. */ + @Override + public Optional dropFunction(RoutineSignature function, boolean ifExists) { + return Optional.of("DROP FUNCTION " + (ifExists ? "IF EXISTS " : "") + + qualifiedRoutine(function.schemaName(), function.name())); + } + + /** {@code DROP PROCEDURE [IF EXISTS] s.p}. */ + @Override + public Optional dropProcedure(RoutineSignature procedure, boolean ifExists) { + return Optional.of("DROP PROCEDURE " + (ifExists ? "IF EXISTS " : "") + + qualifiedRoutine(procedure.schemaName(), procedure.name())); + } + + /** Whether a routine may be written {@code CREATE OR REPLACE}; MySQL has none. */ + protected boolean createOrReplaceRoutine() { + return false; + } } 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 13ebc82..9a52df3 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 @@ -25,9 +25,13 @@ 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.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; 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.RoutineRoundTrip; 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; @@ -141,4 +145,24 @@ void descending_index_column_is_created_and_read_back() throws SQLException { IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new MySqlMetadataProvider(), users, "ix_users_desc", "name", "id"); } + + /** + * A function and a procedure the dialect writes are created, the function is called, both are + * read back with their parameters, language and body, and dropped by their signature. A body + * starts with the routine's characteristics, as the database writes them. + */ + @Test + void routines_are_created_called_read_back_and_dropped() throws SQLException { + RoutineDefinition function = new RoutineDefinition("rt", "rt_add", + List.of(RoutineParameter.in("a", "INT"), RoutineParameter.in("b", "INT")), "INT", "sql", + "DETERMINISTIC RETURN a + b"); + RoutineDefinition procedure = new RoutineDefinition("rt", "rt_bump", + List.of(RoutineParameter.in("n", "INT"), new RoutineParameter("total", ParameterMode.INOUT, "INT")), + null, "sql", "SET total = total + n"); + // root may create a function while the binary log is on; the container's user may not + try (Connection root = java.sql.DriverManager.getConnection(CONTAINER.getJdbcUrl(), "root", CONTAINER.getPassword())) { + RoutineRoundTrip.assertRoutineRoundTrip(root, dialect.ddlGenerator(), new MySqlMetadataProvider(), function, procedure, + "SELECT `rt`.`rt_add`(2, 3)", 5, List.of("n IN", "total INOUT"), "a + b", "total = total + n"); + } + } } 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 3a73fcf..0d29c50 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 @@ -25,10 +25,16 @@ import java.sql.SQLException; import java.sql.Types; import java.util.List; +import java.util.Locale; import java.util.Optional; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import java.util.stream.Collectors; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; import org.eclipse.daanse.sql.model.schema.ColumnMetaData; import org.eclipse.daanse.sql.model.schema.TableReference; @@ -909,4 +915,64 @@ public boolean supportsDescendingIndexColumns() { public boolean supportsDeferrableForeignKeys() { return true; } + + /** Oracle writes a routine's body in PL/SQL. */ + @Override + public Set routineLanguages() { + return Set.of("plsql"); + } + + /** + * {@code CREATE [OR REPLACE] FUNCTION s.f ("A" IN NUMBER) RETURN NUMBER AS body}; the body ends + * with its own {@code END;}, and no client's {@code /} follows. A parameter's name is quoted as + * an identifier: a body names it as the database stores it. A function needs its return type. + */ + @Override + public Optional createFunction(RoutineDefinition function, boolean orReplace) { + if (!routineLanguages().contains(function.language().toLowerCase(Locale.ROOT)) + || function.returnType() == null) { + return Optional.empty(); + } + return Optional.of("CREATE " + (orReplace ? "OR REPLACE " : "") + "FUNCTION " + + qualifiedRoutine(function.schemaName(), function.name()) + parameters(function) + " RETURN " + + function.returnType() + " AS " + function.body()); + } + + /** {@code CREATE [OR REPLACE] PROCEDURE s.p ("N" IN NUMBER, "TOTAL" IN OUT NUMBER) AS body}. */ + @Override + public Optional createProcedure(RoutineDefinition procedure, boolean orReplace) { + if (!routineLanguages().contains(procedure.language().toLowerCase(Locale.ROOT))) { + return Optional.empty(); + } + return Optional.of("CREATE " + (orReplace ? "OR REPLACE " : "") + "PROCEDURE " + + qualifiedRoutine(procedure.schemaName(), procedure.name()) + parameters(procedure) + " AS " + + procedure.body()); + } + + /** + * {@code DROP FUNCTION s.f}: a schema holds one routine of a name, overloads live in packages + * only, so the types are not written. {@code IF EXISTS} from Oracle 23. + */ + @Override + public Optional dropFunction(RoutineSignature function, boolean ifExists) { + return Optional.of("DROP FUNCTION " + (ifExists && dialectVersion.atLeast(23, 0) ? "IF EXISTS " : "") + + qualifiedRoutine(function.schemaName(), function.name())); + } + + /** {@code DROP PROCEDURE s.p}, as {@link #dropFunction}. */ + @Override + public Optional dropProcedure(RoutineSignature procedure, boolean ifExists) { + return Optional.of("DROP PROCEDURE " + (ifExists && dialectVersion.atLeast(23, 0) ? "IF EXISTS " : "") + + qualifiedRoutine(procedure.schemaName(), procedure.name())); + } + + private String parameters(RoutineDefinition routine) { + if (routine.parameters().isEmpty()) { + return ""; + } + return routine.parameters().stream() + .map(p -> quoteIdentifier(p.name()) + " " + (p.mode() == ParameterMode.INOUT ? "IN OUT" : p.mode().name()) + + " " + p.type()) + .collect(Collectors.joining(", ", "(", ")")); + } } 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 65ee216..f170551 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 @@ -28,9 +28,13 @@ 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.Deferrability; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; 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.RoutineRoundTrip; import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip; import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal; import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey; @@ -242,4 +246,23 @@ void view_comments_are_written_and_read_back() throws SQLException { s.execute(dialect.ddlGenerator().dropView(view, false)); } } + + /** + * A function and a procedure the dialect writes are created, the function is called, both are + * read back with their parameters, language and body, and dropped by their signature. + */ + @Test + void routines_are_created_called_read_back_and_dropped() throws SQLException { + String schema = CONTAINER.getUsername().toUpperCase(); + RoutineDefinition function = new RoutineDefinition(schema, "RT_ADD", + List.of(RoutineParameter.in("A", "NUMBER"), RoutineParameter.in("B", "NUMBER")), "NUMBER", "plsql", + "BEGIN RETURN A + B; END;"); + RoutineDefinition procedure = new RoutineDefinition(schema, "RT_BUMP", + List.of(RoutineParameter.in("N", "NUMBER"), new RoutineParameter("TOTAL", ParameterMode.INOUT, + "NUMBER")), + null, "plsql", "BEGIN TOTAL := TOTAL + N; END;"); + RoutineRoundTrip.assertRoutineRoundTrip(conn, dialect.ddlGenerator(), new OracleMetadataProvider(), function, + procedure, "SELECT \"" + schema + "\".\"RT_ADD\"(2, 3) FROM DUAL", 5, + List.of("n IN", "total INOUT"), "RETURN A + B", "TOTAL := TOTAL + N"); + } } 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 a392789..f3ca9e9 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 @@ -27,10 +27,16 @@ import java.sql.SQLException; import java.sql.Types; import java.util.List; +import java.util.Locale; import java.util.Optional; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import java.util.stream.Collectors; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; import org.eclipse.daanse.sql.model.schema.TableReference; import org.eclipse.daanse.sql.model.schema.Trigger; @@ -580,4 +586,70 @@ public boolean supportsDescendingIndexColumns() { public boolean supportsDeferrableForeignKeys() { return true; } + + /** PostgreSQL writes a routine's body in SQL or PL/pgSQL. */ + @Override + public Set routineLanguages() { + return Set.of("sql", "plpgsql"); + } + + /** + * {@code CREATE [OR REPLACE] FUNCTION s.f (a integer, OUT r integer) [RETURNS t] LANGUAGE l AS $$body$$}: + * the body in a dollar quote that does not occur in it; without a return type the {@code OUT} + * parameters make the result. + */ + @Override + public Optional createFunction(RoutineDefinition function, boolean orReplace) { + if (!routineLanguages().contains(function.language().toLowerCase(Locale.ROOT))) { + return Optional.empty(); + } + return Optional.of("CREATE " + (orReplace ? "OR REPLACE " : "") + "FUNCTION " + + qualifiedRoutine(function.schemaName(), function.name()) + "(" + parameters(function) + ")" + + (function.returnType() == null ? "" : " RETURNS " + function.returnType()) + " LANGUAGE " + + function.language() + " AS " + dollarQuoted(function.body())); + } + + /** {@code CREATE [OR REPLACE] PROCEDURE s.p (n integer, INOUT total integer) LANGUAGE l AS $$body$$}. */ + @Override + public Optional createProcedure(RoutineDefinition procedure, boolean orReplace) { + if (!routineLanguages().contains(procedure.language().toLowerCase(Locale.ROOT))) { + return Optional.empty(); + } + return Optional.of("CREATE " + (orReplace ? "OR REPLACE " : "") + "PROCEDURE " + + qualifiedRoutine(procedure.schemaName(), procedure.name()) + "(" + parameters(procedure) + ")" + + " LANGUAGE " + procedure.language() + " AS " + dollarQuoted(procedure.body())); + } + + /** {@code DROP FUNCTION [IF EXISTS] s.f [(integer, text)]}: the types name one of several overloads. */ + @Override + public Optional dropFunction(RoutineSignature function, boolean ifExists) { + return Optional.of("DROP FUNCTION " + (ifExists ? "IF EXISTS " : "") + signature(function)); + } + + /** {@code DROP PROCEDURE [IF EXISTS] s.p [(integer, integer)]}. */ + @Override + public Optional dropProcedure(RoutineSignature procedure, boolean ifExists) { + return Optional.of("DROP PROCEDURE " + (ifExists ? "IF EXISTS " : "") + signature(procedure)); + } + + private String parameters(RoutineDefinition routine) { + return routine.parameters().stream() + .map(p -> (p.mode() == ParameterMode.IN ? "" : p.mode().name() + " ") + quoteIdentifier(p.name()) + + " " + p.type()) + .collect(Collectors.joining(", ")); + } + + private String signature(RoutineSignature routine) { + String name = qualifiedRoutine(routine.schemaName(), routine.name()); + return routine.parameterTypes() == null ? name : name + "(" + String.join(", ", routine.parameterTypes()) + ")"; + } + + /** {@code text} in the dollar quote {@code $$}, or {@code $body$}, … where that occurs in it. */ + private static String dollarQuoted(String text) { + String quote = "$$"; + for (int i = 0; text.contains(quote); i++) { + quote = i == 0 ? "$body$" : "$body" + i + "$"; + } + return quote + text + quote; + } } 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 aa9d368..df6019a 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 @@ -30,9 +30,15 @@ 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.Deferrability; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; 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.RoutineRoundTrip; 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; @@ -243,4 +249,44 @@ void view_comments_are_written_and_read_back() throws SQLException { s.execute(dialect.ddlGenerator().dropView(view, false)); } } + + /** + * A function and a procedure the dialect writes are created, the function is called, both are + * read back with their parameters, language and body, and dropped by their signature. + */ + @Test + void routines_are_created_called_read_back_and_dropped() throws SQLException { + RoutineDefinition function = new RoutineDefinition("public", "rt_add", + List.of(RoutineParameter.in("a", "integer"), RoutineParameter.in("b", "integer")), "integer", "sql", + "SELECT a + b"); + RoutineDefinition procedure = new RoutineDefinition("public", "rt_bump", + List.of(RoutineParameter.in("n", "integer"), new RoutineParameter("total", ParameterMode.INOUT, + "integer")), + null, "plpgsql", "BEGIN total := total + n; END"); + RoutineRoundTrip.assertRoutineRoundTrip(conn, dialect.ddlGenerator(), new PostgreSqlMetadataProvider(), + function, procedure, "SELECT \"public\".\"rt_add\"(2, 3)", 5, List.of("n IN", "total INOUT"), + "a + b", "total := total + n"); + } + + /** Of two functions of one name, the one the types of its parameters name is dropped. */ + @Test + void one_of_two_overloads_is_dropped_by_its_parameter_types() throws SQLException { + DdlGenerator ddl = dialect.ddlGenerator(); + RoutineDefinition two = new RoutineDefinition("public", "rt_twice", + List.of(RoutineParameter.in("a", "integer"), RoutineParameter.in("b", "integer")), "integer", "sql", + "SELECT a + b"); + RoutineDefinition one = new RoutineDefinition("public", "rt_twice", List.of(RoutineParameter.in("a", "integer")), + "integer", "sql", "SELECT a + a"); + try (Statement s = conn.createStatement()) { + s.execute(ddl.createFunction(two, false).orElseThrow()); + s.execute(ddl.createFunction(one, false).orElseThrow()); + s.execute(ddl.dropFunction(new RoutineSignature("public", "rt_twice", List.of("integer", "integer")), false) + .orElseThrow()); + assertFirstIntEquals(conn, "SELECT \"public\".\"rt_twice\"(4)", 8); + assertThat(new PostgreSqlMetadataProvider().getAllFunctions(conn, null, "public")) + .filteredOn(f -> f.reference().name().equals("rt_twice")).singleElement() + .satisfies(f -> assertThat(f.columns()).hasSize(1)); + s.execute(ddl.dropFunction(new RoutineSignature("public", "rt_twice", null), false).orElseThrow()); + } + } } diff --git a/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/RoutineRoundTrip.java b/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/RoutineRoundTrip.java new file mode 100644 index 0000000..88e09f6 --- /dev/null +++ b/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/RoutineRoundTrip.java @@ -0,0 +1,127 @@ +/* + * 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.ResultSet; +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.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; +import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.schema.Function; +import org.eclipse.daanse.sql.jdbc.api.schema.FunctionColumn; +import org.eclipse.daanse.sql.jdbc.api.schema.Procedure; +import org.eclipse.daanse.sql.jdbc.api.schema.ProcedureColumn; + +/** + * A function and a procedure on a database as a dialect writes them: created (and created again, + * where the dialect can replace one), the function called, both read back by the metadata provider + * with their parameters, language and body, and dropped by their signature. Names are compared + * without regard to case, as some databases fold them. + */ +public final class RoutineRoundTrip { + + private RoutineRoundTrip() { + // static helpers only + } + + /** + * @param call a query that calls the function and returns {@code expected} + * @param procedureModes the procedure's parameters as the provider reports them, + * {@code name MODE} in order: SQL Server reports an INOUT parameter as + * OUT, as its OUTPUT parameters are + * @param functionBodyPart a part of the function's body the provider reads back + * @param procedureBodyPart a part of the procedure's body the provider reads back + */ + public static void assertRoutineRoundTrip(Connection conn, DdlGenerator ddl, MetadataProvider provider, + RoutineDefinition function, RoutineDefinition procedure, String call, int expected, + List procedureModes, String functionBodyPart, String procedureBodyPart) throws SQLException { + String schema = function.schemaName(); + try (Statement s = conn.createStatement()) { + executeTwiceWhereReplaced(s, ddl.createFunction(function, false).orElseThrow(), + ddl.createFunction(function, true).orElseThrow()); + executeTwiceWhereReplaced(s, ddl.createProcedure(procedure, false).orElseThrow(), + ddl.createProcedure(procedure, true).orElseThrow()); + try (ResultSet rs = s.executeQuery(call)) { + assertThat(rs.next()).isTrue(); + assertThat(rs.getInt(1)).as("the function's result").isEqualTo(expected); + } + + assertThat(provider.getAllFunctions(conn, null, schema)) + .filteredOn(f -> f.reference().name().equalsIgnoreCase(function.name())).singleElement() + .satisfies(f -> { + assertThat(functionParameters(f)).containsExactlyElementsOf(names(function.parameters())); + assertThat(f.language()).hasValueSatisfying( + language -> assertThat(language).isEqualToIgnoringCase(function.language())); + assertThat(f.body().or(f::fullDefinition).orElseThrow()) + .containsIgnoringWhitespaces(functionBodyPart); + }); + assertThat(provider.getAllProcedures(conn, null, schema)) + .filteredOn(p -> p.reference().name().equalsIgnoreCase(procedure.name())).singleElement() + .satisfies(p -> { + assertThat(procedureParameters(p)).containsExactlyElementsOf(procedureModes); + assertThat(p.language()).hasValueSatisfying( + language -> assertThat(language).isEqualToIgnoringCase(procedure.language())); + assertThat(p.body().or(p::fullDefinition).orElseThrow()) + .containsIgnoringWhitespaces(procedureBodyPart); + }); + + RoutineSignature functionSignature = new RoutineSignature(schema, function.name(), + function.parameters().stream().map(RoutineParameter::type).toList()); + RoutineSignature procedureSignature = new RoutineSignature(schema, procedure.name(), + procedure.parameters().stream().map(RoutineParameter::type).toList()); + executeTwiceWhereReplaced(s, ddl.dropFunction(functionSignature, false).orElseThrow(), + ddl.dropFunction(functionSignature, true).orElseThrow()); + executeTwiceWhereReplaced(s, ddl.dropProcedure(procedureSignature, false).orElseThrow(), + ddl.dropProcedure(procedureSignature, true).orElseThrow()); + assertThat(provider.getAllFunctions(conn, null, schema)) + .noneMatch(f -> f.reference().name().equalsIgnoreCase(function.name())); + assertThat(provider.getAllProcedures(conn, null, schema)) + .noneMatch(p -> p.reference().name().equalsIgnoreCase(procedure.name())); + } + } + + /** {@code first}, and {@code second} too where it is another statement, as one that replaces. */ + private static void executeTwiceWhereReplaced(Statement s, String first, String second) throws SQLException { + s.execute(first); + if (!second.equals(first)) { + s.execute(second); + } + } + + /** The parameters, {@code name MODE}, without a function's return value. */ + private static List functionParameters(Function function) { + return function.columns().stream().filter(c -> !c.name().isBlank()) + .filter(c -> c.columnType() == FunctionColumn.ColumnType.IN + || c.columnType() == FunctionColumn.ColumnType.OUT + || c.columnType() == FunctionColumn.ColumnType.INOUT) + .sorted(Comparator.comparingInt(FunctionColumn::ordinalPosition)) + .map(c -> c.name().toLowerCase(Locale.ROOT) + " " + c.columnType()).toList(); + } + + private static List procedureParameters(Procedure procedure) { + return procedure.columns().stream().filter(c -> !c.name().isBlank()) + .sorted(Comparator.comparingInt(ProcedureColumn::ordinalPosition)) + .map(c -> c.name().toLowerCase(Locale.ROOT) + " " + c.columnType()).toList(); + } + + private static List names(List parameters) { + return parameters.stream().map(p -> p.name().toLowerCase(Locale.ROOT) + " " + p.mode()).toList(); + } +} diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Function.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Function.java index 16840b4..80559a0 100644 --- a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Function.java +++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Function.java @@ -44,6 +44,14 @@ default Optional lastModified() { return Optional.empty(); } + /** + * @return the language of the body, in lower case as the database names it ({@code sql}, + * {@code plpgsql}, {@code plsql}, {@code tsql}, {@code java}), or empty if not known + */ + default Optional language() { + return Optional.empty(); + } + enum FunctionType { UNKNOWN(DatabaseMetaData.functionResultUnknown), NO_TABLE(DatabaseMetaData.functionNoTable), RETURNS_TABLE(DatabaseMetaData.functionReturnsTable); diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Procedure.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Procedure.java index 2a88533..7b52c7d 100644 --- a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Procedure.java +++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/schema/Procedure.java @@ -44,6 +44,14 @@ default Optional lastModified() { return Optional.empty(); } + /** + * @return the language of the body, in lower case as the database names it ({@code sql}, + * {@code plpgsql}, {@code plsql}, {@code tsql}, {@code java}), or empty if not known + */ + default Optional language() { + return Optional.empty(); + } + enum ProcedureType { UNKNOWN(DatabaseMetaData.procedureResultUnknown), NO_RESULT(DatabaseMetaData.procedureNoResult), RETURNS_RESULT(DatabaseMetaData.procedureReturnsResult); 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 3ca0eb5..aee2804 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 @@ -540,7 +540,7 @@ public List getAllProcedures(Connection connection, String catalog, S Map> paramMap = loadProcedureColumns(connection, schemaName); String sql = """ - SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_TYPE, REMARKS, ROUTINE_DEFINITION + SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_TYPE, REMARKS, ROUTINE_DEFINITION, EXTERNAL_LANGUAGE FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE = 'PROCEDURE' ORDER BY ROUTINE_NAME @@ -560,7 +560,7 @@ public List getAllProcedures(Connection connection, String catalog, S procedures.add(new ProcedureRecord(new ProcedureReference(oSchema, routineName, specificName), Procedure.ProcedureType.NO_RESULT, Optional.ofNullable(remarks), cols, - Optional.ofNullable(body), Optional.empty(), Optional.empty())); + Optional.ofNullable(body), Optional.empty(), Optional.empty(), language(rs))); } } } @@ -575,7 +575,7 @@ public List getAllFunctions(Connection connection, String catalog, Str Map> paramMap = loadFunctionColumns(connection, schemaName); String sql = """ - SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_TYPE, REMARKS, ROUTINE_DEFINITION + SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_TYPE, REMARKS, ROUTINE_DEFINITION, EXTERNAL_LANGUAGE FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE = 'FUNCTION' ORDER BY ROUTINE_NAME @@ -595,7 +595,7 @@ public List getAllFunctions(Connection connection, String catalog, Str functions.add(new FunctionRecord(new FunctionReference(oSchema, routineName, specificName), Function.FunctionType.NO_TABLE, Optional.ofNullable(remarks), cols, - Optional.ofNullable(body), Optional.empty(), Optional.empty())); + Optional.ofNullable(body), Optional.empty(), Optional.empty(), language(rs))); } } } @@ -603,6 +603,12 @@ public List getAllFunctions(Connection connection, String catalog, Str } + /** The language of a routine's body: H2's routines are Java methods ({@code EXTERNAL_LANGUAGE}). */ + private static Optional language(ResultSet rs) throws SQLException { + return Optional.ofNullable(rs.getString("EXTERNAL_LANGUAGE")).map(l -> l.toLowerCase(java.util.Locale.ROOT)); + } + + private Map> loadProcedureColumns(Connection connection, String schemaName) throws SQLException { String sql = """ 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 b15d442..5e6bbb7 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 @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; @@ -576,7 +577,7 @@ public List getAllProcedures(Connection connection, String catalog, S Map> paramMap = loadProcedureColumns(connection, schemaName); String sql = """ - SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION + SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION, ROUTINE_BODY FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE = 'PROCEDURE' ORDER BY ROUTINE_NAME @@ -598,7 +599,8 @@ public List getAllProcedures(Connection connection, String catalog, S procedures.add(new ProcedureRecord(new ProcedureReference(oSchema, routineName, specificName), Procedure.ProcedureType.NO_RESULT, Optional.ofNullable(remarks), cols, - Optional.ofNullable(body), fullDef, Optional.empty())); + Optional.ofNullable(body), fullDef, Optional.empty(), + Optional.ofNullable(rs.getString("ROUTINE_BODY")).map(l -> l.toLowerCase(Locale.ROOT)))); } } } @@ -612,7 +614,7 @@ public List getAllFunctions(Connection connection, String catalog, Str Map> paramMap = loadFunctionColumns(connection, schemaName); String sql = """ - SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION + SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION, ROUTINE_BODY FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE = 'FUNCTION' ORDER BY ROUTINE_NAME @@ -634,7 +636,8 @@ public List getAllFunctions(Connection connection, String catalog, Str functions.add(new FunctionRecord(new FunctionReference(oSchema, routineName, specificName), Function.FunctionType.NO_TABLE, Optional.ofNullable(remarks), cols, - Optional.ofNullable(body), fullDef, Optional.empty())); + Optional.ofNullable(body), fullDef, Optional.empty(), + Optional.ofNullable(rs.getString("ROUTINE_BODY")).map(l -> l.toLowerCase(Locale.ROOT)))); } } } diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MicrosoftSqlServerMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MicrosoftSqlServerMetadataProvider.java index 1cbf95b..209d296 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MicrosoftSqlServerMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MicrosoftSqlServerMetadataProvider.java @@ -98,6 +98,9 @@ */ public class MicrosoftSqlServerMetadataProvider implements MetadataProvider { + /** The language of a routine whose module holds its text; a CLR routine has none. */ + private static final String TSQL = "tsql"; + /** The comments of the tables, views and their columns in the schemas a pattern matches. */ private static final String OBJECT_COMMENTS_SQL = """ SELECT s.name AS schema_name, o.name AS object_name, c.name AS column_name, @@ -662,7 +665,7 @@ WHERE OBJECT_SCHEMA_NAME(p.object_id) = ? : Optional.of(modifyDate.toInstant()); procedures.add(new ProcedureRecord(new ProcedureReference(oSchema, routineName), Procedure.ProcedureType.NO_RESULT, Optional.ofNullable(remarks), cols, bodyOpt, bodyOpt, - lastMod)); + lastMod, bodyOpt.map(b -> TSQL))); } } } @@ -708,7 +711,7 @@ WHERE o.type IN ('FN', 'IF', 'TF') AND OBJECT_SCHEMA_NAME(o.object_id) = ? Optional lastMod = modifyDate == null ? Optional.empty() : Optional.of(modifyDate.toInstant()); functions.add(new FunctionRecord(new FunctionReference(oSchema, routineName), funcType, - Optional.ofNullable(remarks), cols, bodyOpt, bodyOpt, lastMod)); + Optional.ofNullable(remarks), cols, bodyOpt, bodyOpt, lastMod, bodyOpt.map(b -> TSQL))); } } } 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 0f80fc3..16fe621 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 @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; @@ -523,7 +524,7 @@ public List getAllProcedures(Connection connection, String catalog, S Map> paramMap = loadProcedureColumns(connection, schemaName); String sql = """ - SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION + SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION, ROUTINE_BODY FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE = 'PROCEDURE' ORDER BY ROUTINE_NAME @@ -545,7 +546,8 @@ public List getAllProcedures(Connection connection, String catalog, S procedures.add(new ProcedureRecord(new ProcedureReference(oSchema, routineName, specificName), Procedure.ProcedureType.NO_RESULT, Optional.ofNullable(remarks), cols, - Optional.ofNullable(body), fullDef, Optional.empty())); + Optional.ofNullable(body), fullDef, Optional.empty(), + Optional.ofNullable(rs.getString("ROUTINE_BODY")).map(l -> l.toLowerCase(Locale.ROOT)))); } } } @@ -559,7 +561,7 @@ public List getAllFunctions(Connection connection, String catalog, Str Map> paramMap = loadFunctionColumns(connection, schemaName); String sql = """ - SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION + SELECT ROUTINE_NAME, SPECIFIC_NAME, ROUTINE_COMMENT, ROUTINE_DEFINITION, ROUTINE_BODY FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE = 'FUNCTION' ORDER BY ROUTINE_NAME @@ -581,7 +583,8 @@ public List getAllFunctions(Connection connection, String catalog, Str functions.add(new FunctionRecord(new FunctionReference(oSchema, routineName, specificName), Function.FunctionType.NO_TABLE, Optional.ofNullable(remarks), cols, - Optional.ofNullable(body), fullDef, Optional.empty())); + Optional.ofNullable(body), fullDef, Optional.empty(), + Optional.ofNullable(rs.getString("ROUTINE_BODY")).map(l -> l.toLowerCase(Locale.ROOT)))); } } } 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 cdbfdaa..f16a569 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 @@ -95,6 +95,9 @@ public class OracleMetadataProvider implements MetadataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(OracleMetadataProvider.class); + /** The language of a schema's own functions and procedures. */ + private static final Optional PLSQL = Optional.of("plsql"); + /** * The tables and views as the JDBC driver reports them, each with its comment from @@ -725,7 +728,8 @@ public List getAllProcedures(Connection connection, String catalog, S Optional lastMod = Optional.ofNullable(lastDdlMap.get(objectName)); procedures.add(new ProcedureRecord(new ProcedureReference(oSchema, objectName), - Procedure.ProcedureType.NO_RESULT, Optional.empty(), cols, body, fullDef, lastMod)); + Procedure.ProcedureType.NO_RESULT, Optional.empty(), cols, body, fullDef, lastMod, + PLSQL)); } } } @@ -760,7 +764,8 @@ public List getAllFunctions(Connection connection, String catalog, Str Optional lastMod = Optional.ofNullable(lastDdlMap.get(objectName)); functions.add(new FunctionRecord(new FunctionReference(oSchema, objectName), - Function.FunctionType.NO_TABLE, Optional.empty(), cols, body, fullDef, lastMod)); + Function.FunctionType.NO_TABLE, Optional.empty(), cols, body, fullDef, lastMod, + PLSQL)); } } } diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java index bef714b..50bbd0b 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataProvider.java @@ -615,10 +615,11 @@ SELECT c.relname, pg_get_viewdef(c.oid, true) AS view_body public List getAllProcedures(Connection connection, String catalog, String schema) throws SQLException { String sql = """ SELECT p.proname AS routine_name, p.proname || '_' || p.oid AS specific_name, - d.description AS remarks, p.prosrc AS body, + d.description AS remarks, p.prosrc AS body, l.lanname AS language, pg_get_functiondef(p.oid) AS full_def FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + JOIN pg_language l ON l.oid = p.prolang LEFT JOIN pg_description d ON d.objoid = p.oid AND d.classoid = 'pg_proc'::regclass WHERE n.nspname = ? AND p.prokind = 'p' ORDER BY p.proname @@ -642,7 +643,8 @@ public List getAllProcedures(Connection connection, String catalog, S procedures.add(new ProcedureRecord(new ProcedureReference(oSchema, routineName, specificName), Procedure.ProcedureType.NO_RESULT, Optional.ofNullable(remarks), columns, - Optional.ofNullable(body), Optional.ofNullable(fullDef), Optional.empty())); + Optional.ofNullable(body), Optional.ofNullable(fullDef), Optional.empty(), + Optional.ofNullable(rs.getString("language")))); } } } catch (SQLException e) { @@ -666,11 +668,12 @@ public List getAllProcedures(Connection connection, String catalog, S public List getAllFunctions(Connection connection, String catalog, String schema) throws SQLException { String sql = """ SELECT p.proname AS routine_name, p.proname || '_' || p.oid AS specific_name, - d.description AS remarks, p.prosrc AS body, + d.description AS remarks, p.prosrc AS body, l.lanname AS language, pg_get_functiondef(p.oid) AS full_def, CASE WHEN p.proretset THEN 'TABLE' ELSE 'SCALAR' END AS return_type FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + JOIN pg_language l ON l.oid = p.prolang LEFT JOIN pg_description d ON d.objoid = p.oid AND d.classoid = 'pg_proc'::regclass WHERE n.nspname = ? AND p.prokind = 'f' ORDER BY p.proname @@ -699,7 +702,7 @@ public List getAllFunctions(Connection connection, String catalog, Str functions.add(new FunctionRecord(new FunctionReference(oSchema, routineName, specificName), funcType, Optional.ofNullable(remarks), columns, Optional.ofNullable(body), - Optional.ofNullable(fullDef), Optional.empty())); + Optional.ofNullable(fullDef), Optional.empty(), Optional.ofNullable(rs.getString("language")))); } } } catch (SQLException e) { diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataContractTest.java index d16611c..42362b7 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataContractTest.java @@ -12,6 +12,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.util.List; +import java.util.Optional; import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; @@ -28,6 +29,11 @@ protected boolean makesForeignKeyIndexes() { return true; } + @Override + protected Optional functionLanguage() { + return Optional.of("java"); + } + @Override protected MetadataProvider provider() { return new H2MetadataProvider(); diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataContractTest.java index 1998634..c6f755c 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MariaDbMetadataContractTest.java @@ -13,6 +13,7 @@ import java.sql.DriverManager; import java.time.Duration; import java.util.List; +import java.util.Optional; import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; @@ -43,6 +44,11 @@ protected boolean makesForeignKeyIndexes() { return true; } + @Override + protected Optional functionLanguage() { + return Optional.of("sql"); + } + @Override protected MetadataProvider provider() { return new MariaDbMetadataProvider(); 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 fba6a1d..f4f23bf 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 @@ -254,6 +254,14 @@ protected List createCommentedFunction() { return List.of(); } + /** + * The language of the body of {@code f_answer} as the provider names it; empty where the + * provider names none. + */ + protected Optional functionLanguage() { + return Optional.empty(); + } + /** * The statements that create two overloads of the function {@code f_total} in the orders' schema * and grant {@code EXECUTE} on the first of them to {@code PUBLIC}: @@ -565,6 +573,17 @@ void aFunctionWithItsComment() throws SQLException { .satisfies(f -> assertThat(f.remarks()).contains(FUNCTION_COMMENT)); } + /** A function is reported with the language of its body, where the provider names it. */ + @Test + void aFunctionWithTheLanguageOfItsBody() throws SQLException { + assumeFalse(createCommentedFunction().isEmpty(), + "the database keeps no comment on a function, or the provider reads none"); + + assertThat(provider.getAllFunctions(connection, null, sales())) + .filteredOn(f -> f.reference().name().equalsIgnoreCase("f_answer")).singleElement() + .satisfies(f -> assertThat(f.language()).isEqualTo(functionLanguage())); + } + /** * Two functions of one name with different parameters are two routines, each with its own * parameters in order and a specific name that tells it from the other. A privilege on one of them diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java index e1cf592..8a5adf1 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java @@ -12,6 +12,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.util.List; +import java.util.Optional; import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; @@ -36,6 +37,11 @@ protected List createFilteredIndex() { return List.of("CREATE INDEX ix_orders_large ON sales.orders (qty) WHERE qty > 10"); } + @Override + protected Optional functionLanguage() { + return Optional.of("tsql"); + } + @Override protected MetadataProvider provider() { return new MicrosoftSqlServerMetadataProvider(); diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataContractTest.java index b44c1b3..6da3660 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataContractTest.java @@ -13,6 +13,7 @@ import java.sql.DriverManager; import java.time.Duration; import java.util.List; +import java.util.Optional; import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; @@ -43,6 +44,11 @@ protected boolean makesForeignKeyIndexes() { return true; } + @Override + protected Optional functionLanguage() { + return Optional.of("sql"); + } + @Override protected MetadataProvider provider() { return new MySqlMetadataProvider(); diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java index 9c7b1ec..3850d7a 100644 --- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java +++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/PostgreSqlMetadataContractTest.java @@ -12,6 +12,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.util.List; +import java.util.Optional; import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; @@ -47,6 +48,11 @@ protected List createDeferrableForeignKey() { + " REFERENCES sales.orders (id) DEFERRABLE INITIALLY DEFERRED)"); } + @Override + protected Optional functionLanguage() { + return Optional.of("sql"); + } + @Override protected MetadataProvider provider() { return new PostgreSqlMetadataProvider(); diff --git a/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/FunctionRecord.java b/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/FunctionRecord.java index b3ca418..2169375 100644 --- a/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/FunctionRecord.java +++ b/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/FunctionRecord.java @@ -28,5 +28,13 @@ public record FunctionRecord( List columns, Optional body, Optional fullDefinition, - Optional lastModified) implements Function { + Optional lastModified, + Optional language) implements Function { + + /** A function whose language is not known. */ + public FunctionRecord(FunctionReference reference, FunctionType functionType, Optional remarks, + List columns, Optional body, Optional fullDefinition, + Optional lastModified) { + this(reference, functionType, remarks, columns, body, fullDefinition, lastModified, Optional.empty()); + } } diff --git a/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/ProcedureRecord.java b/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/ProcedureRecord.java index 57d4e9d..bc9f572 100644 --- a/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/ProcedureRecord.java +++ b/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/schema/ProcedureRecord.java @@ -28,5 +28,13 @@ public record ProcedureRecord( List columns, Optional body, Optional fullDefinition, - Optional lastModified) implements Procedure { + Optional lastModified, + Optional language) implements Procedure { + + /** A procedure whose language is not known. */ + public ProcedureRecord(ProcedureReference reference, ProcedureType procedureType, Optional remarks, + List columns, Optional body, Optional fullDefinition, + Optional lastModified) { + this(reference, procedureType, remarks, columns, body, fullDefinition, lastModified, Optional.empty()); + } } From ff35a7a2a834888c874c0bd83cf4f9870ad6e9ad Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Thu, 12 Nov 2026 19:15:15 +0100 Subject: [PATCH 4/7] jdbc: a routine read through the driver has its own parameters DatabaseServiceImpl reads the procedures and functions of a plain JDBC connection with getProcedures and getFunctions and their parameters with getProcedureColumns and getFunctionColumns by name. Where a schema holds several routines of one name, the driver reports the parameters of all of them, and every routine got them all. A parameter row now belongs to the routine its SPECIFIC_NAME names, read last in the row as JDBC lists it. A row or a routine without a specific name, or a driver without the column, leaves the row to every routine of the name, as before. H2 makes an alias of Integer.toString two procedures, toString(int) and toString(int, int); read through the driver, each now has its own parameters. Signed-off-by: Stefan Bischof --- .../sql/jdbc/impl/DatabaseServiceImpl.java | 40 +++++++++++-- .../DatabaseServiceReadsOverloadsH2Test.java | 60 +++++++++++++++++++ 2 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsOverloadsH2Test.java diff --git a/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java b/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java index 707e4b0..0d088fc 100644 --- a/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java +++ b/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java @@ -1032,7 +1032,7 @@ private List getProcedures(DatabaseMetaData databaseMetaData, String // Get procedure columns List columns = getProcedureColumns(databaseMetaData, - oCatalogName.orElse(null), oSchemaName.orElse(null), procedureName); + oCatalogName.orElse(null), oSchemaName.orElse(null), procedureName, specificName); Procedure procedure = new ProcedureRecord(reference, Procedure.ProcedureType.of(procedureType), remarks, columns, Optional.empty(), Optional.empty(), Optional.empty()); @@ -1043,8 +1043,13 @@ private List getProcedures(DatabaseMetaData databaseMetaData, String return List.copyOf(procedures); } + /** + * The parameters of one procedure. The driver reports those of every procedure of the name; of + * several (overloads) a row belongs to the one its {@code SPECIFIC_NAME} names. A row or a + * procedure without a specific name belongs to every procedure of the name. + */ private List getProcedureColumns(DatabaseMetaData databaseMetaData, String catalog, - String schema, String procedureName) throws SQLException { + String schema, String procedureName, String specificName) throws SQLException { List columns = new ArrayList<>(); try (ResultSet rs = databaseMetaData.getProcedureColumns(catalog, schema, procedureName, null)) { @@ -1073,6 +1078,9 @@ private List getProcedureColumns(DatabaseMetaData databaseMetaD final Optional remarks = Optional.ofNullable(rs.getString("REMARKS")); final Optional columnDefault = Optional.ofNullable(rs.getString("COLUMN_DEF")); final int ordinalPosition = rs.getInt("ORDINAL_POSITION"); + if (!ofRoutine(rs, specificName)) { + continue; + } JDBCType jdbcType; try { @@ -1117,7 +1125,7 @@ private List getFunctions(DatabaseMetaData databaseMetaData, String ca // Get function columns List columns = getFunctionColumns(databaseMetaData, - oCatalogName.orElse(null), oSchemaName.orElse(null), functionName); + oCatalogName.orElse(null), oSchemaName.orElse(null), functionName, specificName); Function function = new FunctionRecord(reference, Function.FunctionType.of(functionType), remarks, columns, Optional.empty(), Optional.empty(), Optional.empty()); @@ -1128,8 +1136,12 @@ private List getFunctions(DatabaseMetaData databaseMetaData, String ca return List.copyOf(functions); } + /** + * The parameters of one function; of several of the name (overloads) a row belongs to the one its + * {@code SPECIFIC_NAME} names, as for {@link #getProcedureColumns}. + */ private List getFunctionColumns(DatabaseMetaData databaseMetaData, String catalog, - String schema, String functionName) throws SQLException { + String schema, String functionName, String specificName) throws SQLException { List columns = new ArrayList<>(); try (ResultSet rs = databaseMetaData.getFunctionColumns(catalog, schema, functionName, null)) { @@ -1163,6 +1175,9 @@ private List getFunctionColumns(DatabaseMetaData databaseMetaDat } final int ordinalPosition = rs.getInt("ORDINAL_POSITION"); + if (!ofRoutine(rs, specificName)) { + continue; + } JDBCType jdbcType; try { @@ -1183,6 +1198,23 @@ private List getFunctionColumns(DatabaseMetaData databaseMetaDat return List.copyOf(columns); } + /** + * Whether the parameter row {@code rs} is one of the routine {@code specificName} names: read + * last in the row, as JDBC lists {@code SPECIFIC_NAME} last. A driver without the column, or a + * routine or row without a specific name, leaves the row to every routine of the name. + */ + private static boolean ofRoutine(ResultSet rs, String specificName) { + if (specificName == null) { + return true; + } + try { + String rowSpecificName = rs.getString("SPECIFIC_NAME"); + return rowSpecificName == null || specificName.equals(rowSpecificName); + } catch (SQLException e) { + return true; + } + } + private List getExportedKeys(DatabaseMetaData databaseMetaData, TableReference table) throws SQLException { Optional oSchema = table.schema(); diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsOverloadsH2Test.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsOverloadsH2Test.java new file mode 100644 index 0000000..e1c490e --- /dev/null +++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsOverloadsH2Test.java @@ -0,0 +1,60 @@ +/* + * 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.jdbc.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; +import java.util.List; + +import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.schema.Procedure; +import org.eclipse.daanse.sql.jdbc.api.schema.ProcedureColumn; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * Read through the JDBC driver, each of two routines of one name has its own parameters, those the + * driver names with its specific name. H2 makes an alias of {@code Integer.toString} two + * procedures, {@code toString(int)} and {@code toString(int, int)}. + */ +class DatabaseServiceReadsOverloadsH2Test { + + private static Connection connection; + + @BeforeAll + static void setUp() throws Exception { + connection = DriverManager.getConnection("jdbc:h2:mem:readsOverloads;DB_CLOSE_DELAY=-1", "sa", ""); + try (Statement stmt = connection.createStatement()) { + stmt.execute("CREATE ALIAS TOSTR FOR 'java.lang.Integer.toString'"); + } + } + + @AfterAll + static void tearDown() throws Exception { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP ALL OBJECTS"); + } + connection.close(); + } + + @Test + void eachOverloadHasItsOwnParameters() throws Exception { + List overloads = new DatabaseServiceImpl().getProcedures(connection, MetadataProvider.EMPTY, null, + "PUBLIC", "TOSTR"); + + assertThat(overloads).hasSize(2); + assertThat(overloads).extracting(p -> p.columns().stream().map(ProcedureColumn::name).toList()) + .containsExactlyInAnyOrder(List.of("RESULT", "P1"), List.of("RESULT", "P1", "P2")); + } +} From 07c2765649ef99b5d63680544104645f23e446a7 Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Thu, 12 Nov 2026 20:09:43 +0100 Subject: [PATCH 5/7] dialect: CREATE and DROP ROLE with IF [NOT] EXISTS, and supportsRoles createRole and dropRole wrote CREATE ROLE and DROP ROLE for every dialect, also where the database has no roles, and could not say IF NOT EXISTS or IF EXISTS, so a script that drops its roles failed where one was missing. DdlGenerator gains createRole(name, ifNotExists) and dropRole(name, ifExists), which are empty where the database has no roles, and supportsRoles(), true by default; the methods without the flag stay as they were. With the flag, an existing or missing role is no error where the dialect can say so; elsewhere the clause is left out. - PostgreSQL has no CREATE ROLE IF NOT EXISTS: a DO block takes an existing role as done, the one the user statement uses; DROP ROLE IF EXISTS. - Oracle: IF [NOT] EXISTS from 23. - SQL Server: a guard on sys.database_principals, as for a user. - MySQL from 8.0, MariaDB, H2, ClickHouse and the ANSI dialect: CREATE ROLE IF NOT EXISTS and DROP ROLE IF EXISTS. - Derby, Hive and Impala have roles without IF [NOT] EXISTS. - DuckDB, SQLite and MySQL before 8.0 have no roles. The consistency tests check the statements of every dialect. On PostgreSQL, SQL Server, Oracle, MySQL and MariaDB a role is created, created again where the dialect can say IF NOT EXISTS, read back by the metadata provider as a role and dropped twice; on H2 the statements run. Signed-off-by: Stefan Bischof --- .../dialect/api/generator/DdlGenerator.java | 40 ++++++- .../consistencytest/RoleStatementsTest.java | 106 ++++++++++++++++++ .../sql/dialect/db/derby/DerbyDialect.java | 11 ++ .../sql/dialect/db/duckdb/DuckDbDialect.java | 6 + .../daanse/sql/dialect/db/h2/H2UserTest.java | 7 ++ .../sql/dialect/db/hive/HiveDialect.java | 11 ++ .../MariaDBGeneratorsRoundTripTest.java | 9 ++ .../MicrosoftSqlServerDialect.java | 14 +++ ...osoftSqlServerGeneratorsRoundTripTest.java | 7 ++ .../sql/dialect/db/mysql/MySqlDialect.java | 9 ++ .../mysql/MySqlGeneratorsRoundTripTest.java | 10 ++ .../sql/dialect/db/oracle/OracleDialect.java | 12 ++ .../oracle/OracleGeneratorsRoundTripTest.java | 10 ++ .../db/postgresql/PostgreSqlDialect.java | 21 +++- .../PostgreSqlGeneratorsRoundTripTest.java | 7 ++ .../sql/dialect/db/sqlite/SqliteDialect.java | 6 + .../dialect/db/testsupport/UserRoundTrip.java | 28 +++++ 17 files changed, 307 insertions(+), 7 deletions(-) create mode 100644 dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoleStatementsTest.java 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 c69d925..5c81028 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 @@ -1394,16 +1394,52 @@ private static String schemaKey(TableReference tbl) { // The grantor of a privilege is never rendered — it is implied by the // session executing the statement. - /** {@code CREATE ROLE "x"}; a user is created by {@link #createUser(String, boolean)}. */ + /** + * {@code CREATE ROLE "x"}, written whether or not the database has roles; a user is created by + * {@link #createUser(String, boolean)}. {@link #createRole(String, boolean)} says where the + * database has no roles. + */ default String createRole(String roleName) { return "CREATE ROLE " + quoteIdentifier(roleName); } - /** {@code DROP ROLE "x"}. */ + /** {@code DROP ROLE "x"}; {@link #dropRole(String, boolean)} says where the database has no roles. */ default String dropRole(String roleName) { return "DROP ROLE " + quoteIdentifier(roleName); } + /** + * {@code CREATE ROLE [IF NOT EXISTS] "x"}: a principal that holds privileges and is granted to + * users and other roles. With {@code ifNotExists} an existing role is no error where the dialect + * can say so; elsewhere the statement fails on it. + * + * @return empty where the database has no roles ({@link #supportsRoles()} is false) + */ + default Optional createRole(String roleName, boolean ifNotExists) { + if (!supportsRoles()) { + return Optional.empty(); + } + return Optional.of("CREATE ROLE " + (ifNotExists ? "IF NOT EXISTS " : "") + quoteIdentifier(roleName)); + } + + /** + * {@code DROP ROLE [IF EXISTS] "x"}. With {@code ifExists} a missing role is no error where the + * dialect can say so; elsewhere the statement fails on it. + * + * @return empty where the database has no roles ({@link #supportsRoles()} is false) + */ + default Optional dropRole(String roleName, boolean ifExists) { + if (!supportsRoles()) { + return Optional.empty(); + } + return Optional.of("DROP ROLE " + (ifExists ? "IF EXISTS " : "") + quoteIdentifier(roleName)); + } + + /** @return true if {@code createRole} / {@code dropRole} with a flag render statements */ + default boolean supportsRoles() { + return true; + } + /** * {@code CREATE USER [IF NOT EXISTS] "x"}: a principal that may log in and receives privileges * and roles as a role does. The user is created without credentials, as the API takes none: it diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoleStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoleStatementsTest.java new file mode 100644 index 0000000..28c7032 --- /dev/null +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/RoleStatementsTest.java @@ -0,0 +1,106 @@ +/* + * 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.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.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.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 to create and drop the role {@code r}, with and without + * {@code IF [NOT] EXISTS}. A dialect without roles writes nothing and says so by + * {@link DdlGenerator#supportsRoles()}. + */ +class RoleStatementsTest { + + /** The statements expected of a dialect; all null where it has no roles. */ + record Expected(String create, String createIfNotExists, String drop, String dropIfExists) { + + static Expected none() { + return new Expected(null, null, null, null); + } + + static Expected standard(String quoted) { + return new Expected("CREATE ROLE " + quoted, "CREATE ROLE IF NOT EXISTS " + quoted, "DROP ROLE " + quoted, + "DROP ROLE IF EXISTS " + quoted); + } + + static Expected withoutIf(String quoted) { + return new Expected("CREATE ROLE " + quoted, "CREATE ROLE " + quoted, "DROP ROLE " + quoted, + "DROP ROLE " + quoted); + } + } + + static Stream dialects() { + return Stream.of( + of("postgresql", new PostgreSqlDialect(), new Expected("CREATE ROLE \"r\"", + "DO $$ BEGIN CREATE ROLE \"r\"; EXCEPTION WHEN duplicate_object THEN NULL; END $$", + "DROP ROLE \"r\"", "DROP ROLE IF EXISTS \"r\"")), + of("oracle, no version", new OracleDialect(), Expected.withoutIf("\"r\"")), + of("oracle 23", new OracleDialect(version(23, 0)), Expected.standard("\"r\"")), + of("mssql", new MicrosoftSqlServerDialect(), new Expected("CREATE ROLE \"r\"", + "IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = N'r') CREATE ROLE \"r\"", + "DROP ROLE \"r\"", + "IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = N'r') DROP ROLE \"r\"")), + of("mysql", new MySqlDialect(), Expected.standard("`r`")), + of("mysql 5.7", new MySqlDialect(version(5, 7)), Expected.none()), + of("mariadb", new MariaDBDialect(), Expected.standard("`r`")), + of("h2", new H2Dialect(), Expected.standard("\"r\"")), + of("clickhouse", new ClickHouseDialect(), Expected.standard("\"r\"")), + of("derby", new DerbyDialect(), Expected.withoutIf("\"r\"")), + of("hive", new HiveDialect(), Expected.withoutIf("`r`")), + of("impala", new ImpalaDialect(), Expected.withoutIf("`r`")), + of("ansi", new AnsiDialect(), Expected.standard("\"r\"")), + of("duckdb", new DuckDbDialect(), Expected.none()), + of("sqlite", new SqliteDialect(), Expected.none())); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("dialects") + void createAndDropARole(Dialect dialect, Expected expected) { + DdlGenerator ddl = dialect.ddlGenerator(); + + assertThat(ddl.supportsRoles()).as("supportsRoles").isEqualTo(expected.create() != null); + assertThat(ddl.createRole("r", false)).isEqualTo(Optional.ofNullable(expected.create())); + assertThat(ddl.createRole("r", true)).isEqualTo(Optional.ofNullable(expected.createIfNotExists())); + assertThat(ddl.dropRole("r", false)).isEqualTo(Optional.ofNullable(expected.drop())); + assertThat(ddl.dropRole("r", true)).isEqualTo(Optional.ofNullable(expected.dropIfExists())); + } + + private static Arguments of(String name, Dialect dialect, Expected 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 aeec173..153057a 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 @@ -396,4 +396,15 @@ public boolean supportsDeferrableForeignKeys() { public boolean supportsCommentOnView() { return false; } + + /** Derby has no {@code IF [NOT] EXISTS} for a role; it is left out. */ + @Override + public java.util.Optional createRole(String roleName, boolean ifNotExists) { + return super.createRole(roleName, false); + } + + @Override + public java.util.Optional dropRole(String roleName, boolean ifExists) { + return super.dropRole(roleName, false); + } } diff --git a/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java b/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java index 9fe38f8..86b9fbd 100644 --- a/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java +++ b/dialect/db/duckdb/src/main/java/org/eclipse/daanse/sql/dialect/db/duckdb/DuckDbDialect.java @@ -516,4 +516,10 @@ yield new StringBuilder("make_date(").append(arguments.get(0)).append(", ").appe default -> super.generateKnownFunction(function, arguments); }; } + + /** DuckDB has no roles. */ + @Override + public boolean supportsRoles() { + return false; + } } diff --git a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2UserTest.java b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2UserTest.java index d38b845..f89c288 100644 --- a/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2UserTest.java +++ b/dialect/db/h2/src/test/java/org/eclipse/daanse/sql/dialect/db/h2/H2UserTest.java @@ -82,4 +82,11 @@ void user_exists_and_cannot_log_in() throws SQLException { s.execute(dialect.dropUser("rt_user", false).orElseThrow()); } } + + /** H2's provider reads no principals; the round trip checks the statements run. */ + @Test + void role_is_created_and_dropped() throws SQLException { + UserRoundTrip.assertRoleRoundTrip(conn, dialect.ddlGenerator(), MetadataProvider.EMPTY, + DatabasePrincipal.KIND_ROLE, "rt_only_role"); + } } diff --git a/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java b/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java index c165650..4fe6bc4 100644 --- a/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java +++ b/dialect/db/hive/src/main/java/org/eclipse/daanse/sql/dialect/db/hive/HiveDialect.java @@ -153,4 +153,15 @@ public boolean supportsNamedPrimaryKey() { public boolean supportsCommentOnView() { return false; } + + /** Hive, and Impala, which takes its spelling, has no {@code IF [NOT] EXISTS} for a role; it is left out. */ + @Override + public java.util.Optional createRole(String roleName, boolean ifNotExists) { + return super.createRole(roleName, false); + } + + @Override + public java.util.Optional dropRole(String roleName, boolean ifExists) { + return super.dropRole(roleName, false); + } } 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 bb17839..b995e4f 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 @@ -158,4 +158,13 @@ void routines_are_created_called_read_back_and_dropped() throws SQLException { "SELECT `rt`.`rt_add`(2, 3)", 5, List.of("n IN", "total INOUT"), "a + b", "total = total + n"); } } + + /** A role the dialect writes is created, again where it can say so, read back and dropped. */ + @Test + void role_is_created_read_back_and_dropped() throws SQLException { + try (Connection root = DriverManager.getConnection(CONTAINER.getJdbcUrl(), "root", CONTAINER.getPassword())) { + UserRoundTrip.assertRoleRoundTrip(root, dialect.ddlGenerator(), new MariaDbMetadataProvider(), + DatabasePrincipal.KIND_ROLE, "rt_only_role"); + } + } } 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 01509f4..23e9d3f 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 @@ -1013,4 +1013,18 @@ private String orAlter(boolean orReplace) { private static String variable(String name) { return name.startsWith("@") ? name : "@" + name; } + + /** With {@code ifNotExists}, guarded by the database's principals, as for a user. */ + @Override + public Optional createRole(String roleName, boolean ifNotExists) { + String create = "CREATE ROLE " + quoteIdentifier(roleName); + return Optional.of(ifNotExists ? "IF NOT EXISTS (" + principalNamed(roleName) + ") " + create : create); + } + + /** With {@code ifExists}, guarded by the database's principals, as for a user. */ + @Override + public Optional dropRole(String roleName, boolean ifExists) { + String drop = "DROP ROLE " + quoteIdentifier(roleName); + return Optional.of(ifExists ? "IF EXISTS (" + principalNamed(roleName) + ") " + drop : drop); + } } 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 df873b9..ef4c7da 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 @@ -247,4 +247,11 @@ void routines_are_created_called_read_back_and_dropped() throws SQLException { function, procedure, "SELECT [dbo].[rt_add](2, 3)", 5, List.of("n IN", "total OUT"), "@a + @b", "@total = @total + @n"); } + + /** A role the dialect writes is created, again where it can say so, read back and dropped. */ + @Test + void role_is_created_read_back_and_dropped() throws SQLException { + UserRoundTrip.assertRoleRoundTrip(conn, dialect.ddlGenerator(), new MicrosoftSqlServerMetadataProvider(), + DatabasePrincipal.KIND_ROLE, "rt_only_role"); + } } 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 a9c193e..05d535c 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 @@ -965,4 +965,13 @@ public Optional dropProcedure(RoutineSignature procedure, boolean ifExis protected boolean createOrReplaceRoutine() { return false; } + + /** + * MySQL has roles from 8.0, MariaDB from 10.0.5, both with {@code IF [NOT] EXISTS}; a dialect made + * without a connection takes such a version. + */ + @Override + public boolean supportsRoles() { + 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 9a52df3..25b43b3 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 @@ -165,4 +165,14 @@ void routines_are_created_called_read_back_and_dropped() throws SQLException { "SELECT `rt`.`rt_add`(2, 3)", 5, List.of("n IN", "total INOUT"), "a + b", "total = total + n"); } } + + /** A role the dialect writes is created, again where it can say so, read back and dropped. */ + @Test + void role_is_created_read_back_and_dropped() throws SQLException { + try (Connection root = java.sql.DriverManager.getConnection(CONTAINER.getJdbcUrl(), "root", + CONTAINER.getPassword())) { + UserRoundTrip.assertRoleRoundTrip(root, dialect.ddlGenerator(), new MySqlMetadataProvider(), + DatabasePrincipal.KIND_UNKNOWN, "rt_only_role"); + } + } } 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 0d29c50..8003162 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 @@ -975,4 +975,16 @@ private String parameters(RoutineDefinition routine) { + " " + p.type()) .collect(Collectors.joining(", ", "(", ")")); } + + /** {@code IF NOT EXISTS} for a role from Oracle 23; before, and for an unknown version, it is left out. */ + @Override + public Optional createRole(String roleName, boolean ifNotExists) { + return super.createRole(roleName, ifNotExists && dialectVersion.atLeast(23, 0)); + } + + /** {@code IF EXISTS} for a role from Oracle 23; before, and for an unknown version, it is left out. */ + @Override + public Optional dropRole(String roleName, boolean ifExists) { + return super.dropRole(roleName, ifExists && dialectVersion.atLeast(23, 0)); + } } 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 f170551..35aa069 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 @@ -265,4 +265,14 @@ void routines_are_created_called_read_back_and_dropped() throws SQLException { procedure, "SELECT \"" + schema + "\".\"RT_ADD\"(2, 3) FROM DUAL", 5, List.of("n IN", "total INOUT"), "RETURN A + B", "TOTAL := TOTAL + N"); } + + /** A role the dialect writes is created, again where it can say so, read back and dropped. */ + @Test + void role_is_created_read_back_and_dropped() throws SQLException { + try (Connection system = DriverManager.getConnection(CONTAINER.getJdbcUrl(), "system", + CONTAINER.getPassword())) { + UserRoundTrip.assertRoleRoundTrip(system, dialect.ddlGenerator(), new OracleMetadataProvider(), + DatabasePrincipal.KIND_ROLE, "rt_only_role"); + } + } } 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 f3ca9e9..f97e82d 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 @@ -552,15 +552,26 @@ public boolean supportsUsers() { @Override public Optional createUser(String userName, boolean ifNotExists) { String create = "CREATE USER " + quoteIdentifier(userName); - if (!ifNotExists) { - return Optional.of(create); - } + return Optional.of(ifNotExists ? unlessItExists(create) : create); + } + + /** + * PostgreSQL has no {@code CREATE ROLE IF NOT EXISTS}: with {@code ifNotExists} the statement is a + * {@code DO} block that takes an existing role of the name as done. + */ + @Override + public Optional createRole(String roleName, boolean ifNotExists) { + String create = "CREATE ROLE " + quoteIdentifier(roleName); + return Optional.of(ifNotExists ? unlessItExists(create) : create); + } + + /** {@code create} in a {@code DO} block that takes an existing object of the name as done. */ + private static String unlessItExists(String create) { String quote = "$$"; for (int i = 1; create.contains(quote); i++) { quote = "$u" + i + "$"; } - return Optional.of("DO " + quote + " BEGIN " + create + "; EXCEPTION WHEN duplicate_object THEN NULL; END " - + quote); + return "DO " + quote + " BEGIN " + create + "; EXCEPTION WHEN duplicate_object THEN NULL; END " + quote; } /** PostgreSQL keeps a materialized view's rows from its creation on, until it is refreshed. */ 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 df6019a..b50fd5f 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 @@ -289,4 +289,11 @@ void one_of_two_overloads_is_dropped_by_its_parameter_types() throws SQLExceptio s.execute(ddl.dropFunction(new RoutineSignature("public", "rt_twice", null), false).orElseThrow()); } } + + /** A role the dialect writes is created, again where it can say so, read back and dropped. */ + @Test + void role_is_created_read_back_and_dropped() throws SQLException { + UserRoundTrip.assertRoleRoundTrip(conn, dialect.ddlGenerator(), new PostgreSqlMetadataProvider(), + DatabasePrincipal.KIND_ROLE, "rt_only_role"); + } } 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 f571320..dafb37c 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 @@ -348,4 +348,10 @@ public boolean supportsDeferrableForeignKeys() { public boolean supportsCommentOnView() { return false; } + + /** SQLite has no roles. */ + @Override + public boolean supportsRoles() { + return false; + } } diff --git a/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/UserRoundTrip.java b/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/UserRoundTrip.java index b54defc..be26e42 100644 --- a/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/UserRoundTrip.java +++ b/dialect/db/test-support/src/main/java/org/eclipse/daanse/sql/dialect/db/testsupport/UserRoundTrip.java @@ -88,6 +88,34 @@ public static void assertUserRoundTrip(Connection conn, DdlGenerator ddl, Metada .noneMatch(p -> p.name().equalsIgnoreCase(user) || p.name().equalsIgnoreCase(role))); } + /** + * Creates the role {@code role}, and again where the dialect can say {@code IF NOT EXISTS}, reads + * it back as a principal of {@code roleKind} where the provider reads principals, drops it, and + * again where the dialect can say {@code IF EXISTS}. + */ + public static void assertRoleRoundTrip(Connection conn, DdlGenerator ddl, MetadataProvider provider, + String roleKind, String role) throws SQLException { + assertThat(ddl.supportsRoles()).as("supportsRoles").isTrue(); + String create = ddl.createRole(role, false).orElseThrow(); + String createIfNotExists = ddl.createRole(role, true).orElseThrow(); + String drop = ddl.dropRole(role, false).orElseThrow(); + String dropIfExists = ddl.dropRole(role, true).orElseThrow(); + + execute(conn, create); + if (!createIfNotExists.equals(create)) { + execute(conn, createIfNotExists); + } + provider.getAllPrincipals(conn).ifPresent(all -> assertThat(all) + .filteredOn(p -> p.name().equalsIgnoreCase(role)).as("the role").singleElement() + .satisfies(p -> assertThat(p.kind()).isEqualTo(roleKind))); + execute(conn, drop); + if (!dropIfExists.equals(drop)) { + execute(conn, dropIfExists); + } + provider.getAllPrincipals(conn).ifPresent(all -> assertThat(all).as("the principals after the drop") + .noneMatch(p -> p.name().equalsIgnoreCase(role))); + } + private static void execute(Connection conn, String sql) throws SQLException { try (Statement s = conn.createStatement()) { s.execute(sql); From 38c2ba95f95e113e615bb311e6a3e4ac5f735930 Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Thu, 12 Nov 2026 21:04:11 +0100 Subject: [PATCH 6/7] metadata(mysql, mariadb): a column's default as the database writes it JDBC asks for a column's default as the database writes it in SQL, a string as a quoted literal. MySQL keeps a literal default unquoted in information_schema.COLUMNS, and Connector/J reports it so: DEFAULT 'NEW' came back as NEW, which a reader cannot tell from an expression. MariaDB quotes a string itself, but reports the text NULL for a nullable column without a default. The MySQL provider now reads the columns itself: as the driver reports them, a schema being a catalog, with the defaults of the schema read from information_schema.COLUMNS in one query. An expression default, which EXTRA marks DEFAULT_GENERATED, is given as MySQL keeps it, with the quotes and backslashes it escapes there unescaped (lower(_utf8mb4'ABC')); a literal of a number or bit type as it is, and a hexadecimal one; any other literal, of a text, date, time or enumeration, quoted, a quote doubled and a backslash escaped. The MariaDB provider reads the columns the same way and gives the text NULL, which MariaDB reports for no default and for DEFAULT NULL alike, as no default. The metadata contract creates a table with a string, a number and an expression default and a column without one, and expects on every database a quoted literal, which the database may decorate ('NEW'::character varying on PostgreSQL, ('NEW') on SQL Server), a number, an expression that is no literal, and no default. PostgreSQL, Oracle, SQL Server, H2 and DuckDB gave that already. Signed-off-by: Stefan Bischof --- .../sql/jdbc/metadata/DriverMetadata.java | 28 +++++++- .../metadata/MariaDbMetadataProvider.java | 17 +++++ .../jdbc/metadata/MySqlMetadataProvider.java | 72 +++++++++++++++++++ .../metadata/MetadataProviderContract.java | 43 +++++++++-- .../metadata/MsSqlMetadataContractTest.java | 6 ++ .../jdbc/metadata/MySqlColumnDefaultTest.java | 55 ++++++++++++++ .../metadata/OracleMetadataContractTest.java | 2 +- 7 files changed, 216 insertions(+), 7 deletions(-) create mode 100644 jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlColumnDefaultTest.java diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DriverMetadata.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DriverMetadata.java index 88ad224..4d19fad 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DriverMetadata.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DriverMetadata.java @@ -49,6 +49,18 @@ interface Comments { String of(String schema, String table, String column); } + /** The default of a column as the provider reads it, from the one the driver reports. */ + @FunctionalInterface + interface Defaults { + + /** + * @param namespace the column's schema, or for a driver without schemas its catalog + * @param driverDefault the default the driver reports, or {@code null} + * @return the default as text, or {@code null} for none + */ + String of(String namespace, String table, String column, String driverDefault); + } + private DriverMetadata() { } @@ -82,6 +94,18 @@ static List tables(Connection connection, String catalog, Strin */ static List columns(Connection connection, String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern, Comments comments) throws SQLException { + return columns(connection, catalog, schemaPattern, tableNamePattern, columnNamePattern, comments, + (namespace, table, column, driverDefault) -> driverDefault); + } + + /** + * {@link java.sql.DatabaseMetaData#getColumns}, as + * {@link #columns(Connection, String, String, String, String, Comments)}, each column with the + * default {@code defaults} makes of the driver's. + */ + static List columns(Connection connection, String catalog, String schemaPattern, + String tableNamePattern, String columnNamePattern, Comments comments, Defaults defaults) + throws SQLException { List columns = new ArrayList<>(); try (ResultSet rs = connection.getMetaData().getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern)) { @@ -98,7 +122,9 @@ static List columns(Connection connection, String catalog, Str OptionalInt nullable = optionalInt(rs, "NULLABLE"); Optional remarks = Optional.ofNullable(rs.getString("REMARKS")) .or(() -> Optional.ofNullable(comments.of(schemaName, tableName, columnName))); - Optional columnDefault = Optional.ofNullable(rs.getString("COLUMN_DEF")); + String namespace = schemaName != null ? schemaName : catalogName; + Optional columnDefault = Optional.ofNullable( + defaults.of(namespace, tableName, columnName, rs.getString("COLUMN_DEF"))); OptionalInt charOctetLength = optionalInt(rs, "CHAR_OCTET_LENGTH"); ColumnMetaData.AutoIncrement autoIncrement = ColumnMetaData.AutoIncrement .ofString(rs.getString("IS_AUTOINCREMENT")); 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 5e6bbb7..e5a40be 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 @@ -65,6 +65,7 @@ import org.eclipse.daanse.sql.jdbc.record.schema.TriggerRecord; import org.eclipse.daanse.sql.jdbc.record.schema.UniqueConstraintRecord; import org.eclipse.daanse.sql.jdbc.record.schema.ViewDefinitionRecord; +import org.eclipse.daanse.sql.model.schema.ColumnDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,6 +80,22 @@ public class MariaDbMetadataProvider implements MetadataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(MariaDbMetadataProvider.class); + /** + * The columns of a schema as the JDBC driver reports them, a schema being a catalog. MariaDB + * writes a default in SQL itself, a string quoted; for a column without a default, and for + * {@code DEFAULT NULL}, which is the same, it reports the text {@code NULL}, which the provider + * gives as no default. + */ + @Override + public Optional> getAllColumnDefinitions(Connection connection, String catalog, + String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { + String schemaName = resolveSchema(schemaPattern, connection); + return Optional.of(DriverMetadata.columns(connection, schemaName, null, tableNamePattern, columnNamePattern, + (schema, table, column) -> null, + (namespace, table, column, driverDefault) -> "NULL".equals(driverDefault) ? null : driverDefault)); + } + + @Override public List getAllTriggers(Connection connection, String catalog, String schema) throws SQLException { String sql = """ 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 16fe621..60dedef 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 @@ -19,12 +19,14 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; +import java.util.Set; 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; @@ -62,6 +64,7 @@ import org.eclipse.daanse.sql.jdbc.record.schema.TriggerRecord; import org.eclipse.daanse.sql.jdbc.record.schema.UniqueConstraintRecord; import org.eclipse.daanse.sql.jdbc.record.schema.ViewDefinitionRecord; +import org.eclipse.daanse.sql.model.schema.ColumnDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,6 +79,75 @@ public class MySqlMetadataProvider implements MetadataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(MySqlMetadataProvider.class); + /** The types whose literal default is written as a number or a bit value, unquoted. */ + private static final Set UNQUOTED_DEFAULT_TYPES = Set.of("tinyint", "smallint", "mediumint", "int", + "integer", "bigint", "decimal", "numeric", "float", "double", "real", "bit", "year", "bool", "boolean"); + + /** + * The columns of a schema as the JDBC driver reports them, a schema being a catalog, each with its + * default as MySQL writes it in SQL. MySQL keeps a literal default unquoted in + * {@code information_schema.COLUMNS}, and Connector/J reports it so: {@code NEW} for + * {@code DEFAULT 'NEW'}, where JDBC asks for a quoted literal, and a reader cannot tell it from an + * expression. The provider reads the defaults of the schema in one query and gives them as + * {@link #columnDefault} writes them. + */ + @Override + public Optional> getAllColumnDefinitions(Connection connection, String catalog, + String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { + String schemaName = resolveSchema(schemaPattern, connection); + String sql = """ + SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, DATA_TYPE, EXTRA + FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? + """; + Map, String> defaults = new HashMap<>(); + try (PreparedStatement ps = connection.prepareStatement(sql)) { + ps.setString(1, schemaName); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + defaults.put(List.of(rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME")), + columnDefault(rs.getString("COLUMN_DEFAULT"), rs.getString("DATA_TYPE"), + rs.getString("EXTRA"))); + } + } + } + return Optional.of(DriverMetadata.columns(connection, schemaName, null, tableNamePattern, columnNamePattern, + (schema, table, column) -> null, (namespace, table, column, driverDefault) -> { + List key = List.of(table, column); + return defaults.containsKey(key) ? defaults.get(key) : driverDefault; + })); + } + + /** + * A column's default as MySQL writes it in SQL, from {@code information_schema.COLUMNS}: an + * expression, which {@code EXTRA} marks {@code DEFAULT_GENERATED} ({@code CURRENT_TIMESTAMP}, + * {@code (1 + 1)}), as MySQL gives it, with the quotes and backslashes it escapes in the text + * unescaped; a literal of a number or bit type as it is ({@code 5}, {@code b'1'}), and a hexadecimal + * literal ({@code 0x6162}); any other literal, of a text, date, time or enumeration, quoted, a quote + * doubled and a backslash escaped ({@code 'it''s'}). {@code null} for none. + */ + static String columnDefault(String columnDefault, String dataType, String extra) { + if (columnDefault == null) { + return null; + } + if (extra != null && extra.toUpperCase(Locale.ROOT).contains("DEFAULT_GENERATED")) { + StringBuilder unescaped = new StringBuilder(columnDefault.length()); + for (int i = 0; i < columnDefault.length(); i++) { + char c = columnDefault.charAt(i); + if (c == '\\' && i + 1 < columnDefault.length()) { + c = columnDefault.charAt(++i); + } + unescaped.append(c); + } + return unescaped.toString(); + } + String type = dataType == null ? "" : dataType.toLowerCase(Locale.ROOT); + if (UNQUOTED_DEFAULT_TYPES.contains(type) || columnDefault.startsWith("0x")) { + return columnDefault; + } + return "'" + columnDefault.replace("\\", "\\\\").replace("'", "''") + "'"; + } + + @Override public List getAllTriggers(Connection connection, String catalog, String schema) throws SQLException { String sql = """ 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 f4f23bf..8c266ec 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 @@ -55,6 +55,8 @@ * *
  * stock.product      PK (id), UNIQUE uq_product_code (code), code of 20 characters, price DECIMAL(10, 2)
+ * stock.defaults     PK (id), label DEFAULT 'NEW', amount DEFAULT 5, created DEFAULT CURRENT_TIMESTAMP,
+ *                    note without a default
  * sales.orders       PK (id), FK fk_orders_product (product_id) → stock.product,
  *                    CHECK ck_orders_id (id > 0), CHECK without a name (qty > 0), id and qty NOT NULL,
  *                    INDEX ix_orders_ordered_on (ordered_on),
@@ -135,6 +137,11 @@ protected String text(int length) {
         return "VARCHAR(" + length + ")";
     }
 
+    /** The type of a column that holds a date and a time of day. */
+    protected String timestampType() {
+        return "TIMESTAMP";
+    }
+
     /** The statement that creates a sequence, with the limits 1 to 999 or without limits. */
     protected String createSequence(String name, boolean limited) {
         return "CREATE SEQUENCE " + name + (limited ? " MINVALUE 1 MAXVALUE 999" : "");
@@ -306,6 +313,9 @@ private List fixture() {
         sql.add("CREATE TABLE " + stock + ".product (id INT NOT NULL, code " + text(20) + " NOT NULL,"
                 + " price DECIMAL(10, 2), CONSTRAINT pk_product PRIMARY KEY (id),"
                 + " CONSTRAINT uq_product_code UNIQUE (code))");
+        sql.add("CREATE TABLE " + stock + ".defaults (id INT NOT NULL, label " + text(10) + " DEFAULT 'NEW',"
+                + " amount INT DEFAULT 5, created " + timestampType() + " DEFAULT CURRENT_TIMESTAMP,"
+                + " note " + text(10) + ", CONSTRAINT pk_defaults PRIMARY KEY (id))");
         sql.addAll(afterStock());
         sql.addAll(createSchema(sales));
         sql.add("CREATE TABLE " + sales + ".orders (id INT NOT NULL, product_id INT, qty INT NOT NULL,"
@@ -363,6 +373,25 @@ void columnsWithTheirLengthPrecisionAndScale() throws SQLException {
         assertThat(columns.get("price").digits()).as("scale of price").hasValue(2);
     }
 
+    /**
+     * A column's default as text, as the database writes it in SQL: a string as a quoted literal,
+     * which the database may decorate ({@code 'NEW'::character varying}, {@code ('NEW')}), a number
+     * as a number, an expression as an expression, not a literal; a column without a default has
+     * none, not the text {@code NULL}.
+     */
+    @Test
+    void columnDefaultsAsText() throws SQLException {
+        Map columns = columns(stock(), "defaults");
+
+        assertThat(columns.get("label").columnDefault()).as("a string")
+                .hasValueSatisfying(d -> assertThat(d).contains("'NEW'"));
+        assertThat(columns.get("amount").columnDefault()).as("a number")
+                .hasValueSatisfying(d -> assertThat(d).contains("5").doesNotContain("'"));
+        assertThat(columns.get("created").columnDefault()).as("an expression")
+                .hasValueSatisfying(d -> assertThat(d).isNotBlank().doesNotContain("'"));
+        assertThat(columns.get("note").columnDefault()).as("no default").isEmpty();
+    }
+
     @Test
     void foreignKeyWithinASchema() throws SQLException {
         List keys = provider.getAllImportedKeys(connection, null, sales()).orElseThrow();
@@ -615,7 +644,8 @@ protected Connection connection() {
     }
 
     /** What the contract reads of a column. */
-    private record Column(OptionalInt size, OptionalInt digits, Optional remarks) {
+    private record Column(OptionalInt size, OptionalInt digits, Optional remarks,
+            Optional columnDefault) {
     }
 
     private Map columns(String schema, String table) throws SQLException {
@@ -626,8 +656,8 @@ private Map columns(String schema, String table) throws SQLExcep
             for (ColumnDefinition column : own.get()) {
                 if (column.column().table().filter(t -> is(t, schema, table)).isPresent()) {
                     ColumnMetaData meta = column.columnMetaData();
-                    columns.put(name(column.column()),
-                            new Column(meta.columnSize(), meta.decimalDigits(), meta.remarks()));
+                    columns.put(name(column.column()), new Column(meta.columnSize(), meta.decimalDigits(),
+                            meta.remarks(), meta.columnDefault()));
                 }
             }
             return columns;
@@ -644,8 +674,11 @@ private static Map jdbcColumns(ResultSet rs, String schema, Stri
             while (rs.next()) {
                 if (inSchema(rs, schema) && table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) {
                     String name = rs.getString("COLUMN_NAME").toLowerCase(Locale.ROOT);
-                    columns.put(name, new Column(optionalInt(rs, "COLUMN_SIZE"), optionalInt(rs, "DECIMAL_DIGITS"),
-                            Optional.ofNullable(rs.getString("REMARKS"))));
+                    OptionalInt size = optionalInt(rs, "COLUMN_SIZE");
+                    OptionalInt digits = optionalInt(rs, "DECIMAL_DIGITS");
+                    Optional remarks = Optional.ofNullable(rs.getString("REMARKS"));
+                    Optional columnDefault = Optional.ofNullable(rs.getString("COLUMN_DEF"));
+                    columns.put(name, new Column(size, digits, remarks, columnDefault));
                 }
             }
         }
diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java
index 8a5adf1..c909401 100644
--- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java
+++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MsSqlMetadataContractTest.java
@@ -74,6 +74,12 @@ private static String description(String comment, String schema, String type, St
                 + (column == null ? "" : ", @level2type = N'COLUMN', @level2name = N'" + column + "'");
     }
 
+    /** SQL Server's TIMESTAMP is a row version; a date and time is DATETIME2. */
+    @Override
+    protected String timestampType() {
+        return "DATETIME2";
+    }
+
     @Override
     protected String createSequence(String name, boolean limited) {
         return "CREATE SEQUENCE " + name + (limited ? " AS INT MINVALUE 1 MAXVALUE 999" : "");
diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlColumnDefaultTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlColumnDefaultTest.java
new file mode 100644
index 0000000..66ebf6d
--- /dev/null
+++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlColumnDefaultTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.jdbc.metadata;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * A column default as MySQL 8 keeps it in {@code information_schema.COLUMNS} ({@code COLUMN_DEFAULT},
+ * {@code DATA_TYPE}, {@code EXTRA}), written as MySQL writes it in SQL.
+ */
+class MySqlColumnDefaultTest {
+
+    @Test
+    void aTextOrDateLiteralIsQuoted() {
+        assertThat(MySqlMetadataProvider.columnDefault("NEW", "varchar", "")).isEqualTo("'NEW'");
+        assertThat(MySqlMetadataProvider.columnDefault("it's", "varchar", "")).isEqualTo("'it''s'");
+        assertThat(MySqlMetadataProvider.columnDefault("a\\b", "varchar", "")).isEqualTo("'a\\\\b'");
+        assertThat(MySqlMetadataProvider.columnDefault("", "varchar", "")).isEqualTo("''");
+        assertThat(MySqlMetadataProvider.columnDefault("2020-01-02", "date", "")).isEqualTo("'2020-01-02'");
+        assertThat(MySqlMetadataProvider.columnDefault("red", "enum", "")).isEqualTo("'red'");
+    }
+
+    @Test
+    void aNumberABitAndAHexadecimalLiteralStayAsTheyAre() {
+        assertThat(MySqlMetadataProvider.columnDefault("5", "int", "")).isEqualTo("5");
+        assertThat(MySqlMetadataProvider.columnDefault("1.50", "decimal", "")).isEqualTo("1.50");
+        assertThat(MySqlMetadataProvider.columnDefault("b'1'", "bit", "")).isEqualTo("b'1'");
+        assertThat(MySqlMetadataProvider.columnDefault("0x6162", "varbinary", "")).isEqualTo("0x6162");
+    }
+
+    @Test
+    void anExpressionIsGivenAsMySqlKeepsItWithItsEscapesUndone() {
+        assertThat(MySqlMetadataProvider.columnDefault("CURRENT_TIMESTAMP", "timestamp", "DEFAULT_GENERATED"))
+                .isEqualTo("CURRENT_TIMESTAMP");
+        assertThat(MySqlMetadataProvider.columnDefault("CURRENT_TIMESTAMP", "timestamp",
+                "DEFAULT_GENERATED on update CURRENT_TIMESTAMP")).isEqualTo("CURRENT_TIMESTAMP");
+        assertThat(MySqlMetadataProvider.columnDefault("(1 + 1)", "int", "DEFAULT_GENERATED")).isEqualTo("(1 + 1)");
+        assertThat(MySqlMetadataProvider.columnDefault("lower(_utf8mb4\\'ABC\\')", "varchar", "DEFAULT_GENERATED"))
+                .isEqualTo("lower(_utf8mb4'ABC')");
+    }
+
+    @Test
+    void noDefaultIsNone() {
+        assertThat(MySqlMetadataProvider.columnDefault(null, "varchar", "")).isNull();
+    }
+}
diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java
index c8c23f3..29e88f6 100644
--- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java
+++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java
@@ -117,7 +117,7 @@ protected List comments() {
 
     @Override
     protected List afterStock() {
-        return List.of("GRANT REFERENCES ON STOCK.product TO " + sales());
+        return List.of("GRANT REFERENCES ON STOCK.product TO " + sales(), "GRANT SELECT ON STOCK.defaults TO " + sales());
     }
 
     @Test

From 009b05a65e4132dfd564c783154430529adabd6b Mon Sep 17 00:00:00 2001
From: Stefan Bischof 
Date: Thu, 12 Nov 2026 21:58:39 +0100
Subject: [PATCH 7/7] jdbc: a snapshot holds the routines of a schema without
 tables

The snapshot read the bulk metadata of the schemas its tables lie in
and of the current one. A schema that holds functions, procedures,
sequences or user-defined types but no table came back without them.

Sequences, user-defined types, procedures and functions are now read
for every schema the database reports as well, and for a database
without schemas (MySQL, MariaDB) every catalog, as a catalog is taken
for the schema there. What lies in a table's schema only, keys,
indexes, constraints, triggers, partitions and privileges, is read for
the schemas of the tables as before.

On Oracle XE the database reports 30 users; 17 of them, Oracle's own
users without a table such as DIP or GGSYS, are read now, in about
0.6 s once warm, beside about 5.5 s for the routines, sequences and
types of the 13 schemas that hold tables, and they add 33 objects.
PostgreSQL reports no further system schema; a user schema without a
table costs a query or two.

A schema with one function and no table is now in the snapshot on H2,
PostgreSQL, Oracle, SQL Server, MySQL and MariaDB, with a sequence too
on H2.

Signed-off-by: Stefan Bischof 
---
 .../MariaDBGeneratorsRoundTripTest.java       | 28 +++++++++++++++++++
 ...osoftSqlServerGeneratorsRoundTripTest.java | 26 +++++++++++++++++
 .../mysql/MySqlGeneratorsRoundTripTest.java   | 28 +++++++++++++++++++
 .../oracle/OracleGeneratorsRoundTripTest.java | 27 ++++++++++++++++++
 .../PostgreSqlGeneratorsRoundTripTest.java    | 25 +++++++++++++++++
 .../sql/jdbc/impl/DatabaseServiceImpl.java    | 27 +++++++++++++++---
 ...DatabaseServiceReadsEverySchemaH2Test.java | 15 +++++++++-
 7 files changed, 171 insertions(+), 5 deletions(-)

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 b995e4f..d991df2 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
@@ -35,7 +35,9 @@
 import org.eclipse.daanse.sql.dialect.db.testsupport.IndexRoundTrip;
 import org.eclipse.daanse.sql.dialect.db.testsupport.RoutineRoundTrip;
 import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
 import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
+import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl;
 import org.eclipse.daanse.sql.jdbc.metadata.MariaDbMetadataProvider;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
@@ -167,4 +169,30 @@ void role_is_created_read_back_and_dropped() throws SQLException {
                     DatabasePrincipal.KIND_ROLE, "rt_only_role");
         }
     }
+
+    /**
+     * A schema that holds a function and no table: the snapshot holds its function. The time the
+     * snapshot takes is printed.
+     */
+    @Test
+    void routines_of_a_schema_without_tables_are_in_the_snapshot() throws SQLException {
+        Connection root = DriverManager.getConnection(CONTAINER.getJdbcUrl(), "root", CONTAINER.getPassword());
+        try (Statement s = root.createStatement()) {
+            s.execute("CREATE DATABASE only_routines");
+            s.execute("CREATE FUNCTION only_routines.f_alone() RETURNS INT DETERMINISTIC RETURN 1");
+        }
+        long start = System.nanoTime();
+        StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(root, new MariaDbMetadataProvider()).structureInfo();
+        System.out.printf("MariaDB snapshot with its provider: %d ms, %d schemas, %d functions%n",
+                (System.nanoTime() - start) / 1_000_000, structure.schemas().size(), structure.functions().size());
+        assertThat(structure.functions()).anySatisfy(f -> {
+            assertThat(f.reference().name()).isEqualToIgnoringCase("f_alone");
+            assertThat(f.reference().schema()).map(SchemaReference::name)
+                    .hasValueSatisfying(n -> assertThat(n).isEqualToIgnoringCase("only_routines"));
+        });
+        try (Statement s = root.createStatement()) {
+            s.execute("DROP DATABASE only_routines");
+        }
+        root.close();
+    }
 }
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 ef4c7da..968f88d 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
@@ -40,6 +40,7 @@
 import org.eclipse.daanse.sql.dialect.db.testsupport.RoutineRoundTrip;
 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.meta.StructureInfo;
 import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
 import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl;
 import org.junit.jupiter.api.AfterAll;
@@ -254,4 +255,29 @@ void role_is_created_read_back_and_dropped() throws SQLException {
         UserRoundTrip.assertRoleRoundTrip(conn, dialect.ddlGenerator(), new MicrosoftSqlServerMetadataProvider(),
                 DatabasePrincipal.KIND_ROLE, "rt_only_role");
     }
+
+    /**
+     * A schema that holds a function and no table: the snapshot holds its function. The time the
+     * snapshot takes is printed.
+     */
+    @Test
+    void routines_of_a_schema_without_tables_are_in_the_snapshot() throws SQLException {
+        try (Statement s = conn.createStatement()) {
+            s.execute("CREATE SCHEMA only_routines");
+            s.execute("CREATE FUNCTION only_routines.f_alone() RETURNS INT AS BEGIN RETURN 1 END");
+        }
+        long start = System.nanoTime();
+        StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(conn, new MicrosoftSqlServerMetadataProvider()).structureInfo();
+        System.out.printf("SQL Server snapshot with its provider: %d ms, %d schemas, %d functions%n",
+                (System.nanoTime() - start) / 1_000_000, structure.schemas().size(), structure.functions().size());
+        assertThat(structure.functions()).anySatisfy(f -> {
+            assertThat(f.reference().name()).isEqualToIgnoringCase("f_alone");
+            assertThat(f.reference().schema()).map(SchemaReference::name)
+                    .hasValueSatisfying(n -> assertThat(n).isEqualToIgnoringCase("only_routines"));
+        });
+        try (Statement s = conn.createStatement()) {
+            s.execute("DROP FUNCTION only_routines.f_alone");
+            s.execute("DROP SCHEMA only_routines");
+        }
+    }
 }
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 25b43b3..08ff256 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
@@ -33,7 +33,9 @@
 import org.eclipse.daanse.sql.dialect.db.testsupport.IndexRoundTrip;
 import org.eclipse.daanse.sql.dialect.db.testsupport.RoutineRoundTrip;
 import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
 import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
+import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl;
 import org.eclipse.daanse.sql.jdbc.metadata.MySqlMetadataProvider;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
@@ -175,4 +177,30 @@ void role_is_created_read_back_and_dropped() throws SQLException {
                     DatabasePrincipal.KIND_UNKNOWN, "rt_only_role");
         }
     }
+
+    /**
+     * A schema that holds a function and no table: the snapshot holds its function. The time the
+     * snapshot takes is printed.
+     */
+    @Test
+    void routines_of_a_schema_without_tables_are_in_the_snapshot() throws SQLException {
+        Connection root = java.sql.DriverManager.getConnection(CONTAINER.getJdbcUrl(), "root", CONTAINER.getPassword());
+        try (Statement s = root.createStatement()) {
+            s.execute("CREATE DATABASE only_routines");
+            s.execute("CREATE FUNCTION only_routines.f_alone() RETURNS INT DETERMINISTIC RETURN 1");
+        }
+        long start = System.nanoTime();
+        StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(root, new MySqlMetadataProvider()).structureInfo();
+        System.out.printf("MySQL snapshot with its provider: %d ms, %d schemas, %d functions%n",
+                (System.nanoTime() - start) / 1_000_000, structure.schemas().size(), structure.functions().size());
+        assertThat(structure.functions()).anySatisfy(f -> {
+            assertThat(f.reference().name()).isEqualToIgnoringCase("f_alone");
+            assertThat(f.reference().schema()).map(SchemaReference::name)
+                    .hasValueSatisfying(n -> assertThat(n).isEqualToIgnoringCase("only_routines"));
+        });
+        try (Statement s = root.createStatement()) {
+            s.execute("DROP DATABASE only_routines");
+        }
+        root.close();
+    }
 }
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 35aa069..ad616ec 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
@@ -36,6 +36,7 @@
 import org.eclipse.daanse.sql.dialect.db.testsupport.IndexRoundTrip;
 import org.eclipse.daanse.sql.dialect.db.testsupport.RoutineRoundTrip;
 import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
 import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
 import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey;
 import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl;
@@ -275,4 +276,30 @@ void role_is_created_read_back_and_dropped() throws SQLException {
                     DatabasePrincipal.KIND_ROLE, "rt_only_role");
         }
     }
+
+    /**
+     * A schema that holds a function and no table: the snapshot holds its function. The time the
+     * snapshot takes is printed.
+     */
+    @Test
+    void routines_of_a_schema_without_tables_are_in_the_snapshot() throws SQLException {
+        Connection system = DriverManager.getConnection(CONTAINER.getJdbcUrl(), "system", CONTAINER.getPassword());
+        try (Statement s = system.createStatement()) {
+            s.execute("CREATE USER ONLY_ROUTINES NO AUTHENTICATION");
+            s.execute("CREATE FUNCTION ONLY_ROUTINES.F_ALONE RETURN NUMBER AS BEGIN RETURN 1; END;");
+        }
+        long start = System.nanoTime();
+        StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(system, new OracleMetadataProvider()).structureInfo();
+        System.out.printf("Oracle snapshot with its provider: %d ms, %d schemas, %d functions%n",
+                (System.nanoTime() - start) / 1_000_000, structure.schemas().size(), structure.functions().size());
+        assertThat(structure.functions()).anySatisfy(f -> {
+            assertThat(f.reference().name()).isEqualToIgnoringCase("f_alone");
+            assertThat(f.reference().schema()).map(SchemaReference::name)
+                    .hasValueSatisfying(n -> assertThat(n).isEqualToIgnoringCase("only_routines"));
+        });
+        try (Statement s = system.createStatement()) {
+            s.execute("DROP USER ONLY_ROUTINES CASCADE");
+        }
+        system.close();
+    }
 }
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 b50fd5f..046a1fc 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
@@ -41,6 +41,7 @@
 import org.eclipse.daanse.sql.dialect.db.testsupport.RoutineRoundTrip;
 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.meta.StructureInfo;
 import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
 import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey;
 import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl;
@@ -296,4 +297,28 @@ void role_is_created_read_back_and_dropped() throws SQLException {
         UserRoundTrip.assertRoleRoundTrip(conn, dialect.ddlGenerator(), new PostgreSqlMetadataProvider(),
                 DatabasePrincipal.KIND_ROLE, "rt_only_role");
     }
+
+    /**
+     * A schema that holds a function and no table: the snapshot holds its function. The time the
+     * snapshot takes is printed.
+     */
+    @Test
+    void routines_of_a_schema_without_tables_are_in_the_snapshot() throws SQLException {
+        try (Statement s = conn.createStatement()) {
+            s.execute("CREATE SCHEMA only_routines");
+            s.execute("CREATE FUNCTION only_routines.f_alone() RETURNS INT LANGUAGE SQL AS 'SELECT 1'");
+        }
+        long start = System.nanoTime();
+        StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(conn, new PostgreSqlMetadataProvider()).structureInfo();
+        System.out.printf("PostgreSQL snapshot with its provider: %d ms, %d schemas, %d functions%n",
+                (System.nanoTime() - start) / 1_000_000, structure.schemas().size(), structure.functions().size());
+        assertThat(structure.functions()).anySatisfy(f -> {
+            assertThat(f.reference().name()).isEqualToIgnoringCase("f_alone");
+            assertThat(f.reference().schema()).map(SchemaReference::name)
+                    .hasValueSatisfying(n -> assertThat(n).isEqualToIgnoringCase("only_routines"));
+        });
+        try (Statement s = conn.createStatement()) {
+            s.execute("DROP SCHEMA only_routines CASCADE");
+        }
+    }
 }
diff --git a/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java b/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java
index 0d088fc..f12e119 100644
--- a/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java
+++ b/jdbc/impl/src/main/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceImpl.java
@@ -235,8 +235,11 @@ protected MetaInfo readMetaInfoWithProvider(Connection connection, DatabaseMetaD
         }
 
         // NEW metadata — only via dialect, no JDBC fallback needed
+        // Sequences, user-defined types and routines may lie in a schema that holds no table: they are
+        // read for every schema the database reports as well.
+        List everySchema = everySchema(tableSchemas, schemas, catalogs);
         List triggers = eachSchema(tableSchemas, s -> provider.getAllTriggers(connection, null, s));
-        List sequences = eachSchema(tableSchemas, s -> provider.getAllSequences(connection, null, s));
+        List sequences = eachSchema(everySchema, s -> provider.getAllSequences(connection, null, s));
         List synonyms =
                 eachSchema(tableSchemas, s -> provider.getAllSynonyms(connection, null, s));
         List checkConstraints =
@@ -244,11 +247,11 @@ protected MetaInfo readMetaInfoWithProvider(Connection connection, DatabaseMetaD
         List uniqueConstraints =
                 eachSchema(tableSchemas, s -> provider.getAllUniqueConstraints(connection, null, s));
         List userDefinedTypes =
-                eachSchema(tableSchemas, s -> provider.getAllUserDefinedTypes(connection, null, s));
+                eachSchema(everySchema, s -> provider.getAllUserDefinedTypes(connection, null, s));
         List viewDefinitions =
                 eachSchema(tableSchemas, s -> provider.getAllViewDefinitions(connection, null, s));
-        List procedures = eachSchema(tableSchemas, s -> provider.getAllProcedures(connection, null, s));
-        List functions = eachSchema(tableSchemas, s -> provider.getAllFunctions(connection, null, s));
+        List procedures = eachSchema(everySchema, s -> provider.getAllProcedures(connection, null, s));
+        List functions = eachSchema(everySchema, s -> provider.getAllFunctions(connection, null, s));
         List materializedViews =
                 eachSchema(tableSchemas, s -> provider.getAllMaterializedViews(connection, null, s));
         List partitions =
@@ -306,6 +309,22 @@ protected MetaInfo readMetaInfoWithProvider(Connection connection, DatabaseMetaD
         return new MetaInfoRecord(databaseInfo, structureInfo, identifierInfo, typeInfos, indexInfos);
     }
 
+    /**
+     * The schemas the tables lie in, and every other schema the database reports, named as the
+     * providers name a schema: for a database without schemas (MySQL, MariaDB), its catalogs, which
+     * {@link #namespaceOf} takes as the schemas.
+     */
+    private static List everySchema(List tableSchemas, List schemas,
+            List catalogs) {
+        Set names = new LinkedHashSet<>(tableSchemas);
+        if (!schemas.isEmpty()) {
+            schemas.forEach(schema -> names.add(schema.name()));
+        } else {
+            catalogs.forEach(catalog -> names.add(catalog.name()));
+        }
+        return List.copyOf(names);
+    }
+
     /** Reads the bulk metadata of one schema. */
     @FunctionalInterface
     private interface SchemaRead {
diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsEverySchemaH2Test.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsEverySchemaH2Test.java
index 599213e..4dad942 100644
--- a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsEverySchemaH2Test.java
+++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsEverySchemaH2Test.java
@@ -27,7 +27,7 @@
 /**
  * The snapshot holds the tables of every schema, so it holds their keys and constraints too — not only
  * those of the connection's current schema, which a provider reads when it is given no schema. The
- * current schema is read as well, though it holds no table.
+ * routines and sequences of every schema are read as well, also of a schema that holds no table.
  */
 class DatabaseServiceReadsEverySchemaH2Test {
 
@@ -60,6 +60,10 @@ CONSTRAINT CK_ORDERS_QTY CHECK (QTY > 0)
                     """);
             // the current schema stays PUBLIC: no table, a sequence
             stmt.execute("CREATE SEQUENCE PUBLIC.SEQ_ORDER_NO");
+            // a schema without a table: a function and a sequence
+            stmt.execute("CREATE SCHEMA ROUTINES");
+            stmt.execute("CREATE ALIAS ROUTINES.F_ALONE FOR 'java.lang.System.currentTimeMillis'");
+            stmt.execute("CREATE SEQUENCE ROUTINES.SEQ_ALONE");
         }
         MetaInfo metaInfo = new DatabaseServiceImpl().createMetaInfo(connection, new H2MetadataProvider());
         structure = metaInfo.structureInfo();
@@ -101,6 +105,15 @@ void theCurrentSchemaIsReadThoughItHoldsNoTable() {
         assertThat(structure.sequences()).extracting(s -> s.name()).contains("SEQ_ORDER_NO");
     }
 
+    @Test
+    void routinesAndSequencesOfASchemaWithoutATableAreRead() {
+        assertThat(structure.functions()).anySatisfy(f -> {
+            assertThat(f.reference().name()).isEqualTo("F_ALONE");
+            assertThat(f.reference().schema()).map(SchemaReference::name).contains("ROUTINES");
+        });
+        assertThat(structure.sequences()).extracting(s -> s.name()).contains("SEQ_ALONE");
+    }
+
     private static String name(TableReference table) {
         return table.schema().map(SchemaReference::name).orElse("?") + "." + table.name();
     }