diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/ReturningGenerator.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/ReturningGenerator.java index dabf7ee..f97d83c 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/ReturningGenerator.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/ReturningGenerator.java @@ -10,14 +10,48 @@ import java.util.List; import java.util.Optional; +/** + * The clause that brings back what an {@code INSERT}, an {@code UPDATE} or a {@code DELETE} wrote, in one of two forms: + * + * A dialect has either, both or none; each is asked for on its own. + */ public interface ReturningGenerator { + /** + * The clause that makes the statement return the given columns as rows, read with {@code executeQuery}. + * + * @return empty where the dialect has no such clause ({@link #supportsReturning()} is false), and for no columns + */ default Optional returning(List columns) { return Optional.empty(); } - /** Whether this dialect supports any form of RETURNING/OUTPUT clause. */ + /** Whether {@link #returning(List)} writes a clause: the statement returns its rows. */ default boolean supportsReturning() { return false; } + + /** + * {@code RETURNING c1, c2 INTO ?, ?}: the clause that puts the given columns of the rows the statement wrote into + * out parameters, one {@code ?} per column, in the order of the columns, after the statement's own parameters. The + * statement is executed with {@code executeUpdate}, and the values are read as the driver serves out parameters of + * a DML statement (Oracle: {@code OraclePreparedStatement.registerReturnParameter} and + * {@code getReturnResultSet}, a row per row written). + * + * @return empty where the dialect has no such clause ({@link #supportsReturningInto()} is false), for no columns, + * and for {@code *}, which names no column a parameter can be bound to + */ + default Optional returningInto(List columns) { + return Optional.empty(); + } + + /** Whether {@link #returningInto(List)} writes a clause: the statement returns into out parameters. */ + default boolean supportsReturningInto() { + return false; + } } 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 8003162..9fd0e96 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 @@ -43,6 +43,7 @@ import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming; import org.eclipse.daanse.sql.model.sql.BitOperation; import org.eclipse.daanse.sql.dialect.api.generator.KnownFunction; +import org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator; import org.eclipse.daanse.sql.dialect.api.generator.StatementHint; import org.eclipse.daanse.sql.model.sql.OrderedColumn; import org.eclipse.daanse.sql.model.type.BestFitColumnType; @@ -126,7 +127,7 @@ public String binaryTypeName(java.util.OptionalInt size) { } private volatile org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator cachedMergeGenerator; - private volatile org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator cachedReturningGenerator; + private volatile ReturningGenerator cachedReturningGenerator; /** JDBC-free constructor for SQL generation. */ public OracleDialect() { @@ -210,39 +211,31 @@ public java.util.Optional upsert(UpsertSpec spec, java.util.List return local; } + /** + * Oracle writes {@code RETURNING} only with {@code INTO}, its values bound to out parameters, in every version, 23 + * too: {@link ReturningGenerator#returningInto(List) RETURNING c1, c2 INTO ?, ?}. A {@code RETURNING} clause alone, + * which a query reads back as rows, fails with ORA-00925, so {@link ReturningGenerator#returning(List)} writes + * none. {@code *} names no column a parameter can be bound to, and is not written either. + */ @Override - public org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator returningGenerator() { + public ReturningGenerator returningGenerator() { var local = cachedReturningGenerator; if (local != null) return local; - if (!dialectVersion.isUnknownOrAtLeast(23, 0)) { - local = super.returningGenerator(); - cachedReturningGenerator = local; - return local; - } - local = new org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator() { + local = new ReturningGenerator() { @Override - public boolean supportsReturning() { + public boolean supportsReturningInto() { return true; } @Override - public java.util.Optional returning(java.util.List columns) { - if (columns == null || columns.isEmpty()) - return java.util.Optional.empty(); - if (columns.size() == 1 && "*".equals(columns.get(0))) { - // Oracle 23c does NOT support RETURNING * — only explicit columns. - return java.util.Optional.empty(); + public Optional returningInto(List columns) { + if (columns == null || columns.isEmpty() || columns.contains("*")) { + return Optional.empty(); } - StringBuilder sb = new StringBuilder(" RETURNING "); - boolean first = true; - for (String c : columns) { - if (!first) - sb.append(", "); - sb.append(quoteIdentifier(c)); - first = false; - } - return java.util.Optional.of(sb.toString()); + return Optional.of(" RETURNING " + columns.stream().map(c -> quoteIdentifier(c)) + .collect(Collectors.joining(", ")) + " INTO " + + columns.stream().map(c -> "?").collect(Collectors.joining(", "))); } }; cachedReturningGenerator = local; @@ -254,27 +247,34 @@ public boolean supportsDropTableCascade() { return false; } - /** Oracle: no {@code IF NOT EXISTS} on any DDL. */ + /** + * {@code CREATE TABLE IF NOT EXISTS} from Oracle 23 (23ai); before, the server refuses it with ORA-00922. A dialect + * made without a connection knows no version and says no. + */ @Override public boolean supportsCreateTableIfNotExists() { - return false; + return dialectVersion.atLeast(23, 0); } + /** {@code CREATE INDEX IF NOT EXISTS} from Oracle 23, as {@link #supportsCreateTableIfNotExists()}. */ @Override public boolean supportsCreateIndexIfNotExists() { - return false; + return dialectVersion.atLeast(23, 0); } + /** {@code DROP INDEX IF EXISTS} from Oracle 23, as {@link #supportsCreateTableIfNotExists()}. */ @Override public boolean supportsDropIndexIfExists() { - return false; + return dialectVersion.atLeast(23, 0); } + /** {@code DROP VIEW IF EXISTS} from Oracle 23, as {@link #supportsCreateTableIfNotExists()}. */ @Override public boolean supportsDropViewIfExists() { - return false; + return dialectVersion.atLeast(23, 0); } + /** No version of Oracle, 23 neither, drops a constraint if it exists: ORA-01735. */ @Override public boolean supportsDropConstraintIfExists() { return false; diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java index ad616ec..aaf013b 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 @@ -126,9 +126,8 @@ void merge_into_using_dual_inserts_then_updates() throws SQLException { } @Test - void returning_unsupported_on_pre_23c_oracle() { - // Oracle XE 21 reports major < 23 → generator falls through to empty default. - // (PG-style RETURNING was introduced in 23c, Aug 2023.) + void returning_unsupported() { + // Oracle writes RETURNING only with INTO, in every version: the generator writes no clause. assertThat(dialect.returningGenerator().returning(List.of("id"))).isEmpty(); } diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleContainers.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleContainers.java new file mode 100644 index 0000000..be79f7f --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleContainers.java @@ -0,0 +1,38 @@ +/* + * 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.oracle.container; + +import java.time.Duration; + +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * A container of an Oracle image: Oracle XE (11, 18, 21) and Oracle Free (23) are served by two Testcontainers modules. + * The password of the container's user is that of SYS and SYSTEM too. Oracle 11g has no pluggable database: it is + * reached by its SID, XE. + */ +final class OracleContainers { + + private OracleContainers() { + } + + @SuppressWarnings("resource") + static JdbcDatabaseContainer of(String image) { + if (image.contains("oracle-free")) { + return new org.testcontainers.oracle.OracleContainer(image).withStartupTimeout(Duration.ofMinutes(5)); + } + org.testcontainers.containers.OracleContainer xe = new org.testcontainers.containers.OracleContainer(image) + .withUsername("rt").withPassword("rt"); + if (image.contains("oracle-xe:11")) { + xe = xe.usingSid(); + } + return xe.withStartupTimeout(Duration.ofMinutes(5)); + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropFunctionIfExistsTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropFunctionIfExistsTest.java new file mode 100644 index 0000000..aae0a5a --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropFunctionIfExistsTest.java @@ -0,0 +1,104 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +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.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle drops a function only if it exists, {@code DROP FUNCTION IF EXISTS}, from 23 (23ai) on. The dialect is built + * from a live connection: on every version the function it creates is called and named by its name alone, for a schema + * holds one routine of a name; from 23 on it writes IF EXISTS, the function it drops is gone and the drop of a missing + * one passes; before, on 18 and 21, it writes a plain DROP FUNCTION, for the server refuses IF EXISTS, and the drop of + * a missing function fails with ORA-04043. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleDropFunctionIfExistsTest { + + @ParameterizedTest(name = "{0} -> DROP FUNCTION IF EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void dropFunctionIfExists(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + String schema = ora.getUsername().toUpperCase(); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + st.execute(dialect.createFunction(new RoutineDefinition(schema, "TWICE", + List.of(RoutineParameter.in("X", "NUMBER")), "NUMBER", "plsql", + "BEGIN RETURN \"X\" * 2; END;"), false).orElseThrow()); + assertThat(exists(st)).as("created").isTrue(); + assertThat(call(st)).as("called").isEqualTo(42); + + // the types of its parameters are not written: a schema holds one function of a name + RoutineSignature twice = new RoutineSignature(schema, "TWICE", List.of("NUMBER")); + String drop = dialect.dropFunction(twice, true).orElseThrow(); + + if (!expected) { + assertThat(drop).as("a plain drop before 23") + .isEqualTo("DROP FUNCTION \"" + schema + "\".\"TWICE\""); + assertThatThrownBy(() -> st.execute("DROP FUNCTION IF EXISTS TWICE")) + .as("IF EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThat(exists(st)).as("the refused drop leaves the function").isTrue(); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-04043"); + return; + } + + assertThat(drop).as("IF EXISTS from 23") + .isEqualTo("DROP FUNCTION IF EXISTS \"" + schema + "\".\"TWICE\""); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + assertThatThrownBy(() -> call(st)).as("no longer called").isInstanceOf(SQLException.class); + st.execute(drop); + assertThatThrownBy(() -> st.execute(dialect.dropFunction(twice, false).orElseThrow())) + .as("a missing one without IF EXISTS").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-04043"); + } + } + } + + private static int call(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery("SELECT TWICE(21) FROM DUAL")) { + rs.next(); + return rs.getInt(1); + } + } + + private static boolean exists(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery( + "SELECT COUNT(*) FROM USER_OBJECTS WHERE OBJECT_TYPE = 'FUNCTION' AND OBJECT_NAME = 'TWICE'")) { + rs.next(); + return rs.getInt(1) > 0; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropMaterializedViewIfExistsTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropMaterializedViewIfExistsTest.java new file mode 100644 index 0000000..433ab66 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropMaterializedViewIfExistsTest.java @@ -0,0 +1,93 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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.dialect.db.oracle.OracleDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle drops a materialized view only if it exists, {@code DROP MATERIALIZED VIEW IF EXISTS}, from 23 (23ai) on. The + * dialect is built from a live connection: from 23 on it writes IF EXISTS, the view it drops is gone and the drop of a + * missing one passes; before, on 18 and 21, it writes a plain DROP MATERIALIZED VIEW, for the server refuses IF EXISTS, + * and the drop of a missing view fails with ORA-12003. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleDropMaterializedViewIfExistsTest { + + private static final String SELECT = "SELECT REGION, SUM(AMOUNT) AS TOTAL FROM SALES GROUP BY REGION"; + + @ParameterizedTest(name = "{0} -> DROP MATERIALIZED VIEW IF EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void dropMaterializedViewIfExists(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + String schema = ora.getUsername().toUpperCase(); + TableReference totals = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), + "REGION_TOTALS", TableReference.TYPE_VIEW); + st.execute("CREATE TABLE SALES (REGION VARCHAR2(10), AMOUNT NUMBER)"); + st.execute("INSERT INTO SALES VALUES ('EU', 10)"); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + st.execute(dialect.createMaterializedView(totals, SELECT, false).orElseThrow()); + assertThat(exists(st)).as("created").isTrue(); + String drop = dialect.dropMaterializedView(totals, true).orElseThrow(); + + if (!expected) { + assertThat(drop).as("a plain drop before 23") + .isEqualTo("DROP MATERIALIZED VIEW \"" + schema + "\".\"REGION_TOTALS\""); + assertThatThrownBy(() -> st.execute("DROP MATERIALIZED VIEW IF EXISTS REGION_TOTALS")) + .as("IF EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThat(exists(st)).as("the refused drop leaves the view").isTrue(); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-12003"); + return; + } + + assertThat(drop).as("IF EXISTS from 23") + .isEqualTo("DROP MATERIALIZED VIEW IF EXISTS \"" + schema + "\".\"REGION_TOTALS\""); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + st.execute(drop); + assertThatThrownBy(() -> st.execute(dialect.dropMaterializedView(totals, false).orElseThrow())) + .as("a missing one without IF EXISTS").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-12003"); + } + } + } + + private static boolean exists(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM USER_MVIEWS WHERE MVIEW_NAME = 'REGION_TOTALS'")) { + rs.next(); + return rs.getInt(1) > 0; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropProcedureIfExistsTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropProcedureIfExistsTest.java new file mode 100644 index 0000000..2e76bdc --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropProcedureIfExistsTest.java @@ -0,0 +1,111 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.List; + +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.DdlGenerator.RoutineSignature; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle drops a procedure only if it exists, {@code DROP PROCEDURE IF EXISTS}, from 23 (23ai) on. The dialect is + * built from a live connection: on every version the procedure it creates is called, its IN OUT parameter carrying the + * result back, and is named by its name alone, for a schema holds one routine of a name; from 23 on it writes IF + * EXISTS, the procedure it drops is gone and the drop of a missing one passes; before, on 18 and 21, it writes a plain + * DROP PROCEDURE, for the server refuses IF EXISTS, and the drop of a missing procedure fails with ORA-04043. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleDropProcedureIfExistsTest { + + @ParameterizedTest(name = "{0} -> DROP PROCEDURE IF EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void dropProcedureIfExists(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + String schema = ora.getUsername().toUpperCase(); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + st.execute(dialect.createProcedure(new RoutineDefinition(schema, "ADD_TO", + List.of(RoutineParameter.in("N", "NUMBER"), + new RoutineParameter("TOTAL", ParameterMode.INOUT, "NUMBER")), + null, "plsql", "BEGIN \"TOTAL\" := \"TOTAL\" + \"N\"; END;"), false).orElseThrow()); + assertThat(exists(st)).as("created").isTrue(); + assertThat(call(c)).as("called").isEqualTo(42); + + // the types of its parameters are not written: a schema holds one procedure of a name + RoutineSignature addTo = new RoutineSignature(schema, "ADD_TO", List.of("NUMBER", "NUMBER")); + String drop = dialect.dropProcedure(addTo, true).orElseThrow(); + + if (!expected) { + assertThat(drop).as("a plain drop before 23") + .isEqualTo("DROP PROCEDURE \"" + schema + "\".\"ADD_TO\""); + assertThatThrownBy(() -> st.execute("DROP PROCEDURE IF EXISTS ADD_TO")) + .as("IF EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThat(exists(st)).as("the refused drop leaves the procedure").isTrue(); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-04043"); + return; + } + + assertThat(drop).as("IF EXISTS from 23") + .isEqualTo("DROP PROCEDURE IF EXISTS \"" + schema + "\".\"ADD_TO\""); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + assertThatThrownBy(() -> call(c)).as("no longer called").isInstanceOf(SQLException.class); + st.execute(drop); + assertThatThrownBy(() -> st.execute(dialect.dropProcedure(addTo, false).orElseThrow())) + .as("a missing one without IF EXISTS").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-04043"); + } + } + } + + private static int call(Connection c) throws SQLException { + try (CallableStatement cs = c.prepareCall("{call ADD_TO(?, ?)}")) { + cs.setInt(1, 2); + cs.setInt(2, 40); + cs.registerOutParameter(2, Types.NUMERIC); + cs.execute(); + return cs.getInt(2); + } + } + + private static boolean exists(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery( + "SELECT COUNT(*) FROM USER_OBJECTS WHERE OBJECT_TYPE = 'PROCEDURE' AND OBJECT_NAME = 'ADD_TO'")) { + rs.next(); + return rs.getInt(1) > 0; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropTableIfExistsContainerTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropTableIfExistsContainerTest.java new file mode 100644 index 0000000..924cb1f --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropTableIfExistsContainerTest.java @@ -0,0 +1,84 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle drops a table only if it exists, {@code DROP TABLE IF EXISTS}, from 23 (23ai) on. The dialect is built from a + * live connection: from 23 on it writes IF EXISTS, the drop of a missing table passes and the table it drops is gone; + * before, on 18 and 21, it writes a plain DROP TABLE, for the server refuses IF EXISTS with ORA-00933, and the drop of + * a missing table fails with ORA-00942. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleDropTableIfExistsContainerTest { + + @ParameterizedTest(name = "{0} -> DROP TABLE IF EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void dropTableIfExists(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + String schema = ora.getUsername().toUpperCase(); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsDropTableIfExists()).as("supportsDropTableIfExists").isEqualTo(expected); + + st.execute("CREATE TABLE ITEMS (ID NUMBER)"); + String drop = dialect.dropTable(schema, "ITEMS", true); + + if (!expected) { + assertThat(drop).as("a plain drop before 23").isEqualTo("DROP TABLE \"" + schema + "\".\"ITEMS\""); + assertThatThrownBy(() -> st.execute("DROP TABLE IF EXISTS ITEMS")) + .as("IF EXISTS is refused before 23").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-00933"); + st.execute(drop); + assertThat(exists(st, "ITEMS")).as("dropped").isFalse(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-00942"); + return; + } + + assertThat(drop).as("IF EXISTS from 23") + .isEqualTo("DROP TABLE IF EXISTS \"" + schema + "\".\"ITEMS\""); + st.execute(drop); + assertThat(exists(st, "ITEMS")).as("dropped").isFalse(); + st.execute(drop); + assertThatThrownBy(() -> st.execute(dialect.dropTable(schema, "ITEMS", false))) + .as("a missing one without IF EXISTS").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-00942"); + } + } + } + + private static boolean exists(Statement st, String table) throws SQLException { + try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME = '" + table + "'")) { + rs.next(); + return rs.getInt(1) > 0; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropUserIfExistsTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropUserIfExistsTest.java new file mode 100644 index 0000000..573f611 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleDropUserIfExistsTest.java @@ -0,0 +1,84 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle drops a user only if it exists, {@code DROP USER IF EXISTS x}, from 23 (23ai) on. The dialect is built from a + * live connection of SYSTEM: from 23 on it writes IF EXISTS, the user it drops is gone and the drop of a missing one + * passes; before, on 18 and 21, it writes a plain DROP USER, for the server refuses IF EXISTS, and the drop of a + * missing user fails with ORA-01918. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleDropUserIfExistsTest { + + private static final String USER = "RT_USER"; + + @ParameterizedTest(name = "{0} -> DROP USER IF EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void dropUserIfExists(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + // SYSTEM may create and drop users and read DBA_USERS; the container's user may not + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), "system", ora.getPassword()); + Statement st = c.createStatement()) { + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + String drop = dialect.dropUser(USER, true).orElseThrow(); + + st.execute(dialect.createUser(USER, false).orElseThrow()); + assertThat(exists(st)).as("created").isTrue(); + + if (!expected) { + assertThat(drop).as("a plain drop before 23").isEqualTo("DROP USER \"RT_USER\""); + assertThatThrownBy(() -> st.execute("DROP USER IF EXISTS " + USER)) + .as("IF EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThat(exists(st)).as("the refused drop leaves the user").isTrue(); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01918"); + return; + } + + assertThat(drop).as("IF EXISTS from 23").isEqualTo("DROP USER IF EXISTS \"RT_USER\""); + st.execute(drop); + assertThat(exists(st)).as("dropped").isFalse(); + st.execute(drop); + assertThatThrownBy(() -> st.execute(dialect.dropUser(USER, false).orElseThrow())) + .as("a missing one without IF EXISTS").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-01918"); + } + } + } + + private static boolean exists(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME = '" + USER + "'")) { + rs.next(); + return rs.getInt(1) > 0; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleIfExistsTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleIfExistsTest.java new file mode 100644 index 0000000..fb3fd70 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleIfExistsTest.java @@ -0,0 +1,162 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.JDBCType; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnDefinitionRecord; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnMetaDataRecord; +import org.eclipse.daanse.sql.jdbc.record.schema.PrimaryKeyRecord; +import org.eclipse.daanse.sql.model.schema.ColumnDefinition; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData; +import org.eclipse.daanse.sql.model.schema.ColumnReference; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle writes {@code IF [NOT] EXISTS} for the DDL of a table, an index and a view from 23 (23ai) on: + * {@code CREATE TABLE IF NOT EXISTS}, {@code CREATE INDEX IF NOT EXISTS}, {@code DROP INDEX IF EXISTS}, + * {@code DROP VIEW IF EXISTS}; and for a constraint in no version, {@code ALTER TABLE … DROP CONSTRAINT IF EXISTS} + * failing with ORA-01735 on 23 too. The dialect is built from a live connection: from 23 on it writes the clause and + * a second create or drop passes, leaving what is there; before, on 18 and 21, it leaves it out, for the server refuses + * it, and a second create or drop fails. {@code DROP TABLE IF EXISTS} is {@link OracleDropTableIfExistsContainerTest}'s. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleIfExistsTest { + + @ParameterizedTest(name = "{0} -> IF [NOT] EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void ifExists(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + String schema = ora.getUsername().toUpperCase(); + TableReference items = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), + "ITEMS", TableReference.TYPE_TABLE); + TableReference names = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), + "ITEM_NAMES", TableReference.TYPE_VIEW); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + DdlGenerator ddl = dialect.ddlGenerator(); + + assertThat(dialect.supportsCreateTableIfNotExists()).as("CREATE TABLE IF NOT EXISTS") + .isEqualTo(expected); + assertThat(dialect.supportsCreateIndexIfNotExists()).as("CREATE INDEX IF NOT EXISTS") + .isEqualTo(expected); + assertThat(dialect.supportsDropIndexIfExists()).as("DROP INDEX IF EXISTS").isEqualTo(expected); + assertThat(dialect.supportsDropViewIfExists()).as("DROP VIEW IF EXISTS").isEqualTo(expected); + assertThat(dialect.supportsDropConstraintIfExists()).as("DROP CONSTRAINT IF EXISTS, in no version") + .isFalse(); + + // CREATE TABLE + List columns = List.of(column(items, "ID"), column(items, "NAME")); + String createTable = ddl.createTable(items, columns, + new PrimaryKeyRecord(items, List.of(columns.get(0).column()), Optional.of("PK_ITEMS")), true); + assertThat(createTable.startsWith("CREATE TABLE IF NOT EXISTS ")).as(createTable).isEqualTo(expected); + st.execute(createTable); + st.execute("INSERT INTO ITEMS VALUES (1, 'apple')"); + assertThat(count(st, "SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME = 'ITEMS'")).isEqualTo(1); + createdAgain(st, createTable, expected, "ORA-00955"); + assertThat(count(st, "SELECT COUNT(*) FROM ITEMS")).as("the table and its row left").isEqualTo(1); + + // CREATE INDEX + String createIndex = ddl.createIndex("IX_ITEMS_NAME", items, List.of("NAME"), false, true); + assertThat(createIndex.startsWith("CREATE INDEX IF NOT EXISTS ")).as(createIndex).isEqualTo(expected); + st.execute(createIndex); + assertThat(index(st)).as("the index").isTrue(); + createdAgain(st, createIndex, expected, "ORA-00955"); + + // DROP INDEX + String dropIndex = ddl.dropIndex("IX_ITEMS_NAME", items, true); + assertThat(dropIndex).isEqualTo( + "DROP INDEX " + (expected ? "IF EXISTS " : "") + "\"" + schema + "\".\"IX_ITEMS_NAME\""); + st.execute(dropIndex); + assertThat(index(st)).as("the index dropped").isFalse(); + createdAgain(st, dropIndex, expected, "ORA-01418"); + + // DROP VIEW + st.execute(ddl.createView(names, "SELECT NAME FROM ITEMS", false)); + String dropView = ddl.dropView(names, true); + assertThat(dropView).isEqualTo( + "DROP VIEW " + (expected ? "IF EXISTS " : "") + "\"" + schema + "\".\"ITEM_NAMES\""); + st.execute(dropView); + assertThat(count(st, "SELECT COUNT(*) FROM USER_VIEWS WHERE VIEW_NAME = 'ITEM_NAMES'")) + .as("the view dropped").isZero(); + createdAgain(st, dropView, expected, "ORA-00942"); + + // DROP CONSTRAINT: no IF EXISTS in any version + String dropConstraint = ddl.dropConstraint(items, "PK_ITEMS", true); + assertThat(dropConstraint).isEqualTo( + "ALTER TABLE \"" + schema + "\".\"ITEMS\" DROP CONSTRAINT \"PK_ITEMS\""); + assertThatThrownBy(() -> st.execute("ALTER TABLE ITEMS DROP CONSTRAINT IF EXISTS PK_ITEMS")) + .as("IF EXISTS is refused for a constraint").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-01735"); + st.execute(dropConstraint); + assertThatThrownBy(() -> st.execute(dropConstraint)).as("a missing one") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-02443"); + } + } + } + + /** + * The statement a second time: with IF [NOT] EXISTS it passes, without it fails with the error of an existing or a + * missing object. + */ + private static void createdAgain(Statement st, String sql, boolean ifExists, String error) throws SQLException { + if (ifExists) { + st.execute(sql); + } else { + assertThatThrownBy(() -> st.execute(sql)).as("a second time: " + sql).isInstanceOf(SQLException.class) + .hasMessageContaining(error); + } + } + + private static ColumnDefinition column(TableReference table, String name) { + boolean id = "ID".equals(name); + JDBCType type = id ? JDBCType.INTEGER : JDBCType.VARCHAR; + return new ColumnDefinitionRecord(new ColumnReference(Optional.of(table), name), + new ColumnMetaDataRecord(type, type.getName(), id ? OptionalInt.empty() : OptionalInt.of(20), + OptionalInt.empty(), OptionalInt.empty(), + id ? ColumnMetaData.Nullability.NO_NULLS : ColumnMetaData.Nullability.NULLABLE, + OptionalInt.empty(), Optional.empty(), Optional.empty(), ColumnMetaData.AutoIncrement.UNKNOWN, + ColumnMetaData.GeneratedColumn.UNKNOWN)); + } + + private static boolean index(Statement st) throws SQLException { + return count(st, "SELECT COUNT(*) FROM USER_INDEXES WHERE INDEX_NAME = 'IX_ITEMS_NAME'") > 0; + } + + private static int count(Statement st, String sql) throws SQLException { + try (ResultSet rs = st.executeQuery(sql)) { + rs.next(); + return rs.getInt(1); + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleMaterializedViewTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleMaterializedViewTest.java new file mode 100644 index 0000000..5ffff31 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleMaterializedViewTest.java @@ -0,0 +1,112 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle has materialized views of old, and {@code CREATE MATERIALIZED VIEW IF NOT EXISTS} from 23 (23ai) on. The + * dialect is built from a live connection: on every version the view it creates keeps the rows of its creation until + * it is refreshed and is dropped again; from 23 on it writes IF NOT EXISTS, which leaves an existing view as it is; + * before, on 18 and 21, it leaves it out, for the server refuses it, and the statement fails on an existing view with + * ORA-12006, as the contract says. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleMaterializedViewTest { + + private static final String SELECT = "SELECT REGION, SUM(AMOUNT) AS TOTAL FROM SALES GROUP BY REGION"; + private static final String READ = "SELECT REGION, TOTAL FROM REGION_TOTALS ORDER BY REGION"; + + @ParameterizedTest(name = "{0} -> IF NOT EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void materializedView(String image, boolean ifNotExists) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + String schema = ora.getUsername().toUpperCase(); + TableReference totals = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)), + "REGION_TOTALS", TableReference.TYPE_VIEW); + st.execute("CREATE TABLE SALES (REGION VARCHAR2(10), AMOUNT NUMBER)"); + st.execute("INSERT INTO SALES VALUES ('EU', 10)"); + st.execute("INSERT INTO SALES VALUES ('EU', 20)"); + st.execute("INSERT INTO SALES VALUES ('US', 30)"); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsMaterializedViews()).isTrue(); + + String create = dialect.createMaterializedView(totals, SELECT, false).orElseThrow(); + assertThat(create).isEqualTo( + "CREATE MATERIALIZED VIEW \"" + schema + "\".\"REGION_TOTALS\" AS " + SELECT); + st.execute(create); + assertThat(rows(st, READ)).as("the rows of its creation").containsExactly("EU=30", "US=30"); + + st.execute("INSERT INTO SALES VALUES ('US', 5)"); + assertThat(rows(st, READ)).as("kept until it is refreshed").containsExactly("EU=30", "US=30"); + st.execute("BEGIN DBMS_MVIEW.REFRESH('REGION_TOTALS'); END;"); + assertThat(rows(st, READ)).as("refreshed").containsExactly("EU=30", "US=35"); + + assertThatThrownBy(() -> st.execute(create)).as("a second one of the name") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-12006"); + + String again = dialect.createMaterializedView(totals, SELECT, true).orElseThrow(); + if (ifNotExists) { + assertThat(again).as("IF NOT EXISTS from 23").isEqualTo( + "CREATE MATERIALIZED VIEW IF NOT EXISTS \"" + schema + "\".\"REGION_TOTALS\" AS " + SELECT); + st.execute(again); + assertThat(rows(st, READ)).as("IF NOT EXISTS left it").containsExactly("EU=30", "US=35"); + } else { + assertThat(again).as("no IF NOT EXISTS before 23").isEqualTo(create); + assertThatThrownBy( + () -> st.execute("CREATE MATERIALIZED VIEW IF NOT EXISTS REGION_TOTALS AS " + SELECT)) + .as("IF NOT EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> st.execute(again)).as("without IF NOT EXISTS it fails on it") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-12006"); + assertThat(rows(st, READ)).as("the failed create left it").containsExactly("EU=30", "US=35"); + } + + st.execute(dialect.dropMaterializedView(totals, false).orElseThrow()); + assertThatThrownBy(() -> rows(st, READ)).as("dropped").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-00942"); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getInt(2)); + } + } + return out; + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleReturningTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleReturningTest.java new file mode 100644 index 0000000..aba6613 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleReturningTest.java @@ -0,0 +1,146 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +import oracle.jdbc.OraclePreparedStatement; + +/** + * Oracle brings back what an {@code INSERT}, an {@code UPDATE} and a {@code DELETE} wrote with + * {@code RETURNING … INTO}, into out parameters, in every version: on 18, 21 and 23 the clause the dialect writes + * brings back a key the database made, a default, a quoted column of mixed case, the new values of every row an update + * wrote, the rows a delete removed and none where it removed none, after the statement's own parameter too. A + * {@code RETURNING} clause alone, which a query would read back as rows, fails with ORA-00925 for every statement, 23 + * too, so the dialect writes none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleReturningTest { + + /** A key the database makes, and a column of mixed case, which only a quoted name reaches, with a default. */ + private static final String SETUP = "CREATE TABLE ITEMS (ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY," + + " NAME VARCHAR2(20), \"Note\" VARCHAR2(20) DEFAULT 'n/a')"; + + @ParameterizedTest(name = "{0} -> RETURNING INTO") + @ValueSource(strings = { "gvenzl/oracle-xe:18-slim-faststart", "gvenzl/oracle-xe:21-slim-faststart", + "gvenzl/oracle-free:23.9-slim-faststart", + "gvenzl/oracle-free:23.26.4-slim-faststart" }) + void returningInto(String image) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), ora.getUsername(), ora.getPassword()); + Statement st = c.createStatement()) { + st.execute(SETUP); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + ReturningGenerator ret = dialect.returningGenerator(); + + assertThat(ret.supportsReturningInto()).as("supportsReturningInto").isTrue(); + assertThat(ret.returningInto(List.of("ID", "NAME"))).as("the clause") + .contains(" RETURNING \"ID\", \"NAME\" INTO ?, ?"); + assertThat(ret.returningInto(List.of("*"))).as("every column names no parameter").isEmpty(); + assertThat(ret.returningInto(List.of())).as("no columns, no clause").isEmpty(); + assertThat(ret.returningInto(null)).as("no columns, no clause").isEmpty(); + + assertThat(returned(c, "INSERT INTO ITEMS(NAME) VALUES ('apple')" + into(ret, "ID"), types(N))) + .as("the key the database made").containsExactly("1"); + assertThat(returned(c, "INSERT INTO ITEMS(NAME) VALUES ('fig')" + into(ret, "Note"), types(S))) + .as("a quoted column of mixed case, its default").containsExactly("n/a"); + assertThat(returned(c, "INSERT INTO ITEMS(NAME) VALUES (?)" + into(ret, "ID", "NAME"), types(N, S), + "pear")).as("after the statement's own parameter").containsExactly("3|pear"); + returned(c, "INSERT INTO ITEMS(NAME) VALUES ('plum')" + into(ret, "ID"), types(N)); + + assertThat(returned(c, "UPDATE ITEMS SET \"Note\" = 'sold' WHERE ID IN (1, 2)" + + into(ret, "ID", "Note"), types(N, S))).as("UPDATE, the new values of every row it wrote") + .containsExactlyInAnyOrder("1|sold", "2|sold"); + assertThat(returned(c, "DELETE FROM ITEMS WHERE NAME LIKE 'p%'" + into(ret, "NAME"), types(S))) + .as("DELETE, the rows it removed").containsExactlyInAnyOrder("pear", "plum"); + assertThat(returned(c, "DELETE FROM ITEMS WHERE ID = 99" + into(ret, "ID"), types(N))) + .as("nothing deleted, no row").isEmpty(); + + // the form that returns rows: Oracle has none, in no version + assertThat(ret.supportsReturning()).as("supportsReturning").isFalse(); + assertThat(ret.returning(List.of("ID"))).as("no RETURNING without INTO").isEmpty(); + for (String dml : List.of("INSERT INTO ITEMS(NAME) VALUES ('kiwi')", + "UPDATE ITEMS SET NAME = 'lime' WHERE ID = 1", "DELETE FROM ITEMS WHERE ID = 1")) { + assertThatThrownBy(() -> { + try (ResultSet rs = st.executeQuery(dml + " RETURNING \"ID\"")) { + rs.next(); + } + }).as("RETURNING without INTO: " + dml).isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-00925"); + } + } + } + } + + private static final int N = Types.NUMERIC; + private static final int S = Types.VARCHAR; + + private static int[] types(int... types) { + return types; + } + + private static String into(ReturningGenerator ret, String... columns) { + return ret.returningInto(List.of(columns)).orElseThrow(); + } + + /** + * Executes the statement with its own parameters, then binds an out parameter of each type after them, and reads + * what the statement returned into them, a row per row written. + */ + private static List returned(Connection c, String sql, int[] types, String... params) throws SQLException { + try (PreparedStatement ps = c.prepareStatement(sql)) { + OraclePreparedStatement ops = ps.unwrap(OraclePreparedStatement.class); + for (int i = 0; i < params.length; i++) { + ps.setString(i + 1, params[i]); + } + for (int i = 0; i < types.length; i++) { + if (types[i] == S) { + ops.registerReturnParameter(params.length + i + 1, S, 20); + } else { + ops.registerReturnParameter(params.length + i + 1, types[i]); + } + } + ps.executeUpdate(); + List out = new ArrayList<>(); + try (ResultSet rs = ops.getReturnResultSet()) { + while (rs.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= types.length; i++) { + if (i > 1) + row.append('|'); + row.append(rs.getString(i)); + } + out.add(row.toString()); + } + } + return out; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleRolesTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleRolesTest.java new file mode 100644 index 0000000..8c287b0 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleRolesTest.java @@ -0,0 +1,137 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle has roles of old, and {@code CREATE ROLE IF NOT EXISTS} and {@code DROP ROLE IF EXISTS} from 23 (23ai) on. + * The dialect is built from a live connection of SYSTEM: on every version the role it creates is there, holds a + * privilege, is granted to a user, with the admin option too, and revoked, and is dropped with its grants; from 23 on + * IF [NOT] EXISTS spares an error; before, on 18 and 21, it is left out, for the server refuses it, and a second create + * fails with ORA-01921, a second drop with ORA-01919. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleRolesTest { + + private static final String ROLE = "RT_ROLE"; + private static final String USER = "RT_USER"; + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "SYSTEM")), "ITEMS", TableReference.TYPE_TABLE); + + @ParameterizedTest(name = "{0} -> IF [NOT] EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void roles(String image, boolean ifExists) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + // SYSTEM may create roles and users and read DBA_ROLES; the container's user may not + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), "system", ora.getPassword()); + Statement st = c.createStatement()) { + st.execute("CREATE TABLE ITEMS (ID NUMBER)"); + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsRoles()).as("supportsRoles").isTrue(); + + String create = dialect.createRole(ROLE, false).orElseThrow(); + assertThat(create).as("a plain create").isEqualTo("CREATE ROLE \"RT_ROLE\""); + st.execute(create); + assertThat(rows(st, "SELECT ROLE FROM DBA_ROLES WHERE ROLE = '" + ROLE + "'")).as("the role") + .containsExactly(ROLE); + assertThatThrownBy(() -> st.execute(create)).as("a second one of the name") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01921"); + + String createIfNotExists = dialect.createRole(ROLE, true).orElseThrow(); + if (ifExists) { + assertThat(createIfNotExists).as("IF NOT EXISTS from 23") + .isEqualTo("CREATE ROLE IF NOT EXISTS \"RT_ROLE\""); + st.execute(createIfNotExists); + } else { + assertThat(createIfNotExists).as("no IF NOT EXISTS before 23").isEqualTo(create); + assertThatThrownBy(() -> st.execute("CREATE ROLE IF NOT EXISTS " + ROLE)) + .as("IF NOT EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> st.execute(createIfNotExists)).as("a second one, plainly") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01921"); + } + + st.execute(dialect.grantTablePrivilege("SELECT", ITEMS, ROLE, false)); + assertThat(rows(st, "SELECT PRIVILEGE || ' ' || OWNER || '.' || TABLE_NAME FROM DBA_TAB_PRIVS" + + " WHERE GRANTEE = '" + ROLE + "'")).as("the role's privilege") + .containsExactly("SELECT SYSTEM.ITEMS"); + + st.execute(dialect.createUser(USER, false).orElseThrow()); + st.execute(dialect.grantRole(ROLE, USER, false)); + assertThat(grants(st)).as("the role granted to the user").containsExactly(ROLE + ":NO"); + st.execute(dialect.revokeRole(ROLE, USER)); + assertThat(grants(st)).as("revoked").isEmpty(); + st.execute(dialect.grantRole(ROLE, USER, true)); + assertThat(grants(st)).as("with the admin option").containsExactly(ROLE + ":YES"); + + String drop = dialect.dropRole(ROLE, false).orElseThrow(); + assertThat(drop).as("a plain drop").isEqualTo("DROP ROLE \"RT_ROLE\""); + st.execute(drop); + assertThat(rows(st, "SELECT ROLE FROM DBA_ROLES WHERE ROLE = '" + ROLE + "'")).as("dropped") + .isEmpty(); + assertThat(grants(st)).as("the grant gone with the role").isEmpty(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-01919"); + + String dropIfExists = dialect.dropRole(ROLE, true).orElseThrow(); + if (ifExists) { + assertThat(dropIfExists).as("IF EXISTS from 23").isEqualTo("DROP ROLE IF EXISTS \"RT_ROLE\""); + st.execute(dropIfExists); + } else { + assertThat(dropIfExists).as("no IF EXISTS before 23").isEqualTo(drop); + assertThatThrownBy(() -> st.execute("DROP ROLE IF EXISTS " + ROLE)) + .as("IF EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> st.execute(dropIfExists)).as("a missing one, plainly") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01919"); + } + st.execute(dialect.dropUser(USER, false).orElseThrow()); + } + } + } + + /** The roles granted to the user, each with whether it may grant it on. */ + private static List grants(Statement st) throws SQLException { + return rows(st, "SELECT GRANTED_ROLE || ':' || ADMIN_OPTION FROM DBA_ROLE_PRIVS WHERE GRANTEE = '" + USER + + "'"); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleSupportsUsersTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleSupportsUsersTest.java new file mode 100644 index 0000000..b078ed1 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleSupportsUsersTest.java @@ -0,0 +1,97 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle creates a user without credentials, {@code CREATE USER x NO AUTHENTICATION}, a schema-only account, from 18 + * on. The dialect is built from a live connection of SYSTEM: from 18 on the user it creates is there, authenticated by + * nothing, and cannot log in until it is given a password and the right to log in, when it does; on 11g it writes no + * user, for the server refuses NO AUTHENTICATION. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleSupportsUsersTest { + + private static final String USER = "RT_USER"; + + @ParameterizedTest(name = "{0} -> users {1}") + @CsvSource({ "gvenzl/oracle-xe:11-slim, false", "gvenzl/oracle-xe:18-slim-faststart, true", + "gvenzl/oracle-xe:21-slim-faststart, true", "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void supportsUsers(String image, boolean expected) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + // SYSTEM may create users and read DBA_USERS; the container's user may not + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), "system", ora.getPassword()); + Statement st = c.createStatement()) { + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsUsers()).as("supportsUsers").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.createUser(USER, false)).as("no user before 18").isEmpty(); + assertThat(dialect.createUser(USER, true)).as("no user before 18").isEmpty(); + assertThat(dialect.dropUser(USER, true)).as("no user before 18").isEmpty(); + assertThatThrownBy(() -> st.execute("CREATE USER " + USER + " NO AUTHENTICATION")) + .as("NO AUTHENTICATION is refused before 18").isInstanceOf(SQLException.class); + assertThat(exists(st)).as("the refused create wrote no user").isFalse(); + return; + } + + st.execute(dialect.createUser(USER, false).orElseThrow()); + assertThat(authentication(st)).as("the user, authenticated by nothing").isEqualTo("NONE"); + assertThatThrownBy(() -> DriverManager.getConnection(ora.getJdbcUrl(), USER, "rt").close()) + .as("a user without credentials does not log in").isInstanceOf(SQLException.class); + + st.execute("ALTER USER " + USER + " IDENTIFIED BY rt"); + st.execute("GRANT CREATE SESSION TO " + USER); + assertThat(authentication(st)).as("given a password").isEqualTo("PASSWORD"); + try (Connection u = DriverManager.getConnection(ora.getJdbcUrl(), USER, "rt"); + Statement us = u.createStatement(); ResultSet rs = us.executeQuery("SELECT USER FROM DUAL")) { + rs.next(); + assertThat(rs.getString(1)).as("it logs in then").isEqualTo(USER); + } + + st.execute(dialect.dropUser(USER, false).orElseThrow()); + assertThat(exists(st)).as("dropped").isFalse(); + } + } + } + + private static String authentication(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery( + "SELECT AUTHENTICATION_TYPE FROM DBA_USERS WHERE USERNAME = '" + USER + "'")) { + rs.next(); + return rs.getString(1); + } + } + + private static boolean exists(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME = '" + USER + "'")) { + rs.next(); + return rs.getInt(1) > 0; + } + } +} diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleUsersTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleUsersTest.java new file mode 100644 index 0000000..fbb5117 --- /dev/null +++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/container/OracleUsersTest.java @@ -0,0 +1,110 @@ +/* + * 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.oracle.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.JdbcDatabaseContainer; + +/** + * Oracle creates a user without credentials with {@code CREATE USER x NO AUTHENTICATION}, from 18 on, and writes + * {@code IF NOT EXISTS} for it, and {@code IF EXISTS} for its drop, from 23 on. The dialect is built from a live + * connection of SYSTEM: on every version the user it creates is there, authenticated by nothing, cannot log in and is + * dropped; from 23 on IF [NOT] EXISTS spares an error; on 18 and 21 it is left out, for the server refuses it, and a + * second create fails with ORA-01920, a second drop with ORA-01918. Oracle 11g, which has no users without + * credentials, is {@link OracleSupportsUsersTest}'s. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class OracleUsersTest { + + private static final String USER = "RT_USER"; + + @ParameterizedTest(name = "{0} -> IF [NOT] EXISTS {1}") + @CsvSource({ "gvenzl/oracle-xe:18-slim-faststart, false", "gvenzl/oracle-xe:21-slim-faststart, false", + "gvenzl/oracle-free:23.9-slim-faststart, true", + "gvenzl/oracle-free:23.26.4-slim-faststart, true" }) + void users(String image, boolean ifExists) throws Exception { + try (JdbcDatabaseContainer ora = OracleContainers.of(image)) { + ora.start(); + // SYSTEM may create users and read DBA_USERS; the container's user may not + try (Connection c = DriverManager.getConnection(ora.getJdbcUrl(), "system", ora.getPassword()); + Statement st = c.createStatement()) { + OracleDialect dialect = new OracleDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsUsers()).as("supportsUsers from 18").isTrue(); + + String create = dialect.createUser(USER, false).orElseThrow(); + assertThat(create).as("a plain create").isEqualTo("CREATE USER \"RT_USER\" NO AUTHENTICATION"); + st.execute(create); + assertThat(rows(st, "SELECT AUTHENTICATION_TYPE FROM DBA_USERS WHERE USERNAME = '" + USER + "'")) + .as("the user, authenticated by nothing").containsExactly("NONE"); + + assertThatThrownBy(() -> DriverManager.getConnection(ora.getJdbcUrl(), USER, "rt").close()) + .as("a user without credentials does not log in").isInstanceOf(SQLException.class); + + assertThatThrownBy(() -> st.execute(create)).as("a second one of the name") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01920"); + + String createIfNotExists = dialect.createUser(USER, true).orElseThrow(); + String dropIfExists = dialect.dropUser(USER, true).orElseThrow(); + if (ifExists) { + assertThat(createIfNotExists).as("IF NOT EXISTS from 23") + .isEqualTo("CREATE USER IF NOT EXISTS \"RT_USER\" NO AUTHENTICATION"); + assertThat(dropIfExists).as("IF EXISTS from 23").isEqualTo("DROP USER IF EXISTS \"RT_USER\""); + st.execute(createIfNotExists); + } else { + assertThat(createIfNotExists).as("no IF NOT EXISTS before 23").isEqualTo(create); + assertThat(dropIfExists).as("no IF EXISTS before 23").isEqualTo("DROP USER \"RT_USER\""); + assertThatThrownBy(() -> st.execute("CREATE USER IF NOT EXISTS " + USER + " NO AUTHENTICATION")) + .as("IF NOT EXISTS is refused before 23").isInstanceOf(SQLException.class); + assertThatThrownBy(() -> st.execute(createIfNotExists)).as("a second one, plainly") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01920"); + } + + String drop = dialect.dropUser(USER, false).orElseThrow(); + st.execute(drop); + assertThat(rows(st, "SELECT USERNAME FROM DBA_USERS WHERE USERNAME = '" + USER + "'")) + .as("dropped").isEmpty(); + assertThatThrownBy(() -> st.execute(drop)).as("a missing one").isInstanceOf(SQLException.class) + .hasMessageContaining("ORA-01918"); + if (ifExists) { + st.execute(dropIfExists); + } else { + assertThatThrownBy(() -> st.execute(dropIfExists)).as("a missing one, plainly") + .isInstanceOf(SQLException.class).hasMessageContaining("ORA-01918"); + } + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +}