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 63772a1b..5c810280 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); @@ -933,16 +991,136 @@ 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 -------------------- /** - * {@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)); } /** @@ -960,6 +1138,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("'", "''") + "'"; @@ -1207,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/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 c774f786..753d4e14 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/DeferrableForeignKeyStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/DeferrableForeignKeyStatementsTest.java new file mode 100644 index 00000000..94d81c0c --- /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/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 00000000..28c70322 --- /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/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 00000000..f3ff7926 --- /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/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 00000000..0927fc4d --- /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 9f7e1e13..153057a9 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,30 @@ 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); + } + + /** Derby keeps no comments. */ + @Override + 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 9fe38f87..86b9fbd5 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 d38b845d..f89c2884 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/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 00000000..dcdd0d4f --- /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 6b3924be..4fe6bc4f 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,21 @@ 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; + } + + /** 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/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 2f9cbd6c..a93d586a 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 2d55e3cb..d991df2d 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,11 +27,17 @@ 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.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; @@ -134,4 +140,59 @@ 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"); + } + } + + /** 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"); + } + } + + /** + * 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/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 745c9b9e..23e9d3fc 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,82 @@ 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; + } + + /** 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 5eab6702..968f88dc 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,12 +31,18 @@ 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.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; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -198,4 +204,80 @@ 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)); + } + } + + /** + * 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"); + } + + /** 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"); + } + + /** + * 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/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 3aa7f2f9..05d535c7 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; @@ -707,6 +713,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 +727,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 +899,79 @@ 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; + } + + /** 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; + } + + /** + * 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 13ebc827..08ff256c 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,11 +25,17 @@ 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.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; @@ -141,4 +147,60 @@ 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"); + } + } + + /** 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"); + } + } + + /** + * 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/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 deb77f5c..80031629 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; @@ -903,4 +909,82 @@ 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; + } + + /** 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(", ", "(", ")")); + } + + /** {@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 fb9c3a67..ad616ecf 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,19 @@ 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.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.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; import org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -179,4 +187,119 @@ 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\""); + } + } + + /** + * 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)); + } + } + + /** + * 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"); + } + + /** 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"); + } + } + + /** + * 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/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 c3302551..f97e82d3 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; @@ -546,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. */ @@ -574,4 +591,76 @@ 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; + } + + /** 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 28809db1..046a1fc4 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,22 @@ 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.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.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; import org.eclipse.daanse.sql.jdbc.metadata.PostgreSqlMetadataProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -182,4 +192,133 @@ 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\""); + } + } + + /** + * 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)); + } + } + + /** + * 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()); + } + } + + /** 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"); + } + + /** + * 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/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 5492a1f7..dafb37c4 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,22 @@ 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; + } + + /** SQLite keeps no comments. */ + @Override + public boolean supportsCommentOnView() { + return false; + } + + /** SQLite has no roles. */ + @Override + public boolean supportsRoles() { + return false; + } } 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 9ee0e8f9..5b6e9a69 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/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 00000000..88e09f62 --- /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/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 b54defc4..be26e429 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); 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 16840b4d..80559a0a 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 2a88533a..7b52c7d1 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/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 707e4b0d..f12e119c 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 { @@ -1032,7 +1051,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 +1062,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 +1097,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 +1144,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 +1155,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 +1194,9 @@ private List getFunctionColumns(DatabaseMetaData databaseMetaDat } final int ordinalPosition = rs.getInt("ORDINAL_POSITION"); + if (!ofRoutine(rs, specificName)) { + continue; + } JDBCType jdbcType; try { @@ -1183,6 +1217,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/DatabaseServiceReadsEverySchemaH2Test.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsEverySchemaH2Test.java index 599213eb..4dad9426 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(); } 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 00000000..e1c490ef --- /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")); + } +} 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 88ad2248..4d19fadd 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/H2MetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataProvider.java index 3ca0eb51..aee28048 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 b15d442c..e5a40be3 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; @@ -64,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; @@ -78,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 = """ @@ -576,7 +594,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 +616,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 +631,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 +653,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 1cbf95b0..209d2963 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 0f80fc38..60dedefe 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,11 +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; @@ -61,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; @@ -75,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 = """ @@ -523,7 +596,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 +618,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 +633,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 +655,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 62ffa88d..f16a5691 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 @@ -457,7 +460,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 +492,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 @@ -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)); } } } @@ -1040,7 +1045,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 04fdb5eb..50bbd0bc 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 @@ -613,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 @@ -640,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) { @@ -664,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 @@ -697,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) { @@ -962,7 +967,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/H2MetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/H2MetadataContractTest.java index d16611c3..42362b74 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 1998634e..c6f755cd 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 06236047..8c266ec3 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),
@@ -62,6 +64,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)
@@ -89,6 +93,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";
 
@@ -130,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" : "");
@@ -185,6 +197,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;
@@ -215,13 +237,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. */
@@ -238,6 +261,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}:
@@ -282,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,"
@@ -302,6 +336,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));
@@ -338,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();
@@ -367,6 +421,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());
@@ -504,16 +576,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);
         }
     }
 
@@ -527,6 +602,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
@@ -558,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 {
@@ -569,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;
@@ -587,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 be169d73..c9094014 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();
@@ -51,7 +57,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
@@ -67,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 00000000..66ebf6dd
--- /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/MySqlMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlMetadataContractTest.java
index b44c1b30..6da3660c 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/OracleMetadataContractTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleMetadataContractTest.java
index b99bc268..29e88f62 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();
@@ -104,12 +111,13 @@ 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
     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
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 6effca66..3850d7ab 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;
@@ -40,6 +41,18 @@ 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 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 b3ca4186..21693759 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 57d4e9d5..bc9f5727 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());
+    }
 }