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 aaf013b2..11d8721d 100644
--- a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java
+++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleGeneratorsRoundTripTest.java
@@ -36,6 +36,7 @@
import org.eclipse.daanse.sql.dialect.db.testsupport.IndexRoundTrip;
import org.eclipse.daanse.sql.dialect.db.testsupport.RoutineRoundTrip;
import org.eclipse.daanse.sql.dialect.db.testsupport.UserRoundTrip;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
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;
@@ -51,6 +52,11 @@
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
+/**
+ * The statements of the Oracle dialect, run in a container and read back. The container's user
+ * {@code rt} writes and reads its own schema with plain rights, so its provider reads in
+ * {@link MetadataScope#USER}; SYSTEM reads the whole database.
+ */
@Testcontainers
@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
@TestInstance(Lifecycle.PER_CLASS)
@@ -156,7 +162,7 @@ void materialized_view_is_created_read_back_and_dropped() throws SQLException {
TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)),
"MV_USERS", TableReference.TYPE_VIEW);
String query = "SELECT id, name FROM \"" + schema + "\".\"USERS\" WHERE id <= 5";
- OracleMetadataProvider provider = new OracleMetadataProvider();
+ OracleMetadataProvider provider = new OracleMetadataProvider(MetadataScope.USER);
String create = dialect.ddlGenerator().createMaterializedView(view, query, false).orElseThrow();
String createIfNotExists = dialect.ddlGenerator().createMaterializedView(view, query, true).orElseThrow();
String drop = dialect.ddlGenerator().dropMaterializedView(view, false).orElseThrow();
@@ -183,8 +189,8 @@ void materialized_view_is_created_read_back_and_dropped() throws SQLException {
/** An index the dialect writes with a descending column is read back with the order of each column. */
@Test
void descending_index_column_is_created_and_read_back() throws SQLException {
- IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(), new OracleMetadataProvider(), users,
- "IX_USERS_DESC", "NAME", "ID");
+ IndexRoundTrip.assertDescendingIndexRoundTrip(conn, dialect.ddlGenerator(),
+ new OracleMetadataProvider(MetadataScope.USER), users, "IX_USERS_DESC", "NAME", "ID");
}
/**
@@ -210,7 +216,7 @@ void deferrable_foreign_key_is_checked_at_commit_and_read_back() throws SQLExcep
} finally {
conn.setAutoCommit(true);
}
- assertThat(new OracleMetadataProvider().getAllImportedKeys(conn, null, schema).orElseThrow())
+ assertThat(new OracleMetadataProvider(MetadataScope.USER).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()) {
@@ -229,7 +235,7 @@ void view_comments_are_written_and_read_back() throws SQLException {
TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)),
"V_NOTED", TableReference.TYPE_VIEW);
DatabaseServiceImpl service = new DatabaseServiceImpl();
- OracleMetadataProvider provider = new OracleMetadataProvider();
+ OracleMetadataProvider provider = new OracleMetadataProvider(MetadataScope.USER);
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());
@@ -261,9 +267,10 @@ void routines_are_created_called_read_back_and_dropped() throws SQLException {
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");
+ RoutineRoundTrip.assertRoutineRoundTrip(conn, dialect.ddlGenerator(),
+ new OracleMetadataProvider(MetadataScope.USER), 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. */
diff --git a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleInitMetaInfoLatencyTest.java b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleInitMetaInfoLatencyTest.java
index 11b7b4b7..f1b08558 100644
--- a/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleInitMetaInfoLatencyTest.java
+++ b/dialect/db/oracle/src/test/java/org/eclipse/daanse/sql/dialect/db/oracle/OracleInitMetaInfoLatencyTest.java
@@ -67,7 +67,8 @@ void measure() throws SQLException {
private void runMetaInfo(DataSource ds) throws SQLException {
try (Connection c = ds.getConnection()) {
- service.createMetaInfo(c, new org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider());
+ service.createMetaInfo(c, new org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider(
+ org.eclipse.daanse.sql.jdbc.api.MetadataScope.USER));
}
}
diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProvider.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProvider.java
index 97fe13f4..7a3dffe6 100644
--- a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProvider.java
+++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProvider.java
@@ -47,6 +47,18 @@
import org.eclipse.daanse.sql.jdbc.api.schema.VersionColumn;
import org.eclipse.daanse.sql.jdbc.api.schema.ViewDefinition;
+/**
+ * Reads the metadata of one database engine from its system catalog, where JDBC's
+ * {@link java.sql.DatabaseMetaData} reads too little or too slowly. A method that returns
+ * {@link Optional#empty()} leaves the reading to JDBC.
+ *
+ * A provider reads in one {@link MetadataScope}: the whole database ({@link MetadataScope#DATABASE},
+ * the default) or what the connected user may see ({@link MetadataScope#USER}). The scope is a
+ * property of the provider, not of a method: {@link #withScope(MetadataScope)} gives the provider for
+ * another scope, and every method of it reads in that scope. In {@link MetadataScope#DATABASE} a
+ * method may need rights the connection lacks; {@link #effectiveScope(Connection)} says beforehand
+ * whether it has them.
+ */
public interface MetadataProvider {
/**
@@ -57,6 +69,51 @@ public interface MetadataProvider {
MetadataProvider EMPTY = new MetadataProvider() {
};
+ /**
+ * This provider reading in {@code scope}. A provider that reads one way only, or is in
+ * {@code scope} already, returns itself.
+ *
+ * @param scope the scope to read in
+ * @return the provider for {@code scope}
+ */
+ default MetadataProvider withScope(MetadataScope scope) {
+ return this;
+ }
+
+ /**
+ * The scope this provider was asked to read in.
+ *
+ * @return the scope {@link #withScope(MetadataScope)} gave it; {@link MetadataScope#DATABASE} by
+ * default and for a provider that reads one way only
+ */
+ default MetadataScope scope() {
+ return MetadataScope.DATABASE;
+ }
+
+ /**
+ * The scope this provider reads in on {@code connection}: the one it was asked for, or
+ * {@link MetadataScope#USER} where {@link MetadataScope#DATABASE} was asked for and the
+ * connection may not read what that needs ({@link #scopeRequirement()}). Asked once before a
+ * snapshot, which is then read in the scope given, as a whole.
+ *
+ * @param connection the connection to read through
+ * @return the scope the connection may read in
+ * @throws SQLException on database access error
+ */
+ default MetadataScope effectiveScope(Connection connection) throws SQLException {
+ return scope();
+ }
+
+ /**
+ * The right a connection needs to read in {@link MetadataScope#DATABASE}, in words, as a message
+ * names it: {@code "none"} where every connection may.
+ *
+ * @return the right, such as {@code "SELECT_CATALOG_ROLE or SELECT ANY DICTIONARY"}
+ */
+ default String scopeRequirement() {
+ return "none";
+ }
+
/**
* @param catalog the catalog name, or null
* @return the index info list, or Optional.empty() to fall back to standard
@@ -258,7 +315,11 @@ default Optional> getAllCatalogs(Connection connection) t
/**
* Bulk alternative to
- * {@link java.sql.DatabaseMetaData#getSchemas(String, String)}.
+ * {@link java.sql.DatabaseMetaData#getSchemas(String, String)}: the schemas of the provider's
+ * scope, in a database that keeps its schemas as catalogs (MySQL, MariaDB) these catalogs. A
+ * snapshot reads the tables, routines and grants of these schemas; empty leaves the list to JDBC.
+ *
+ * @param catalog the catalog name, or {@code null} for the database of the connection
*/
default Optional> getAllSchemas(Connection connection, String catalog) throws SQLException {
return Optional.empty();
diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProviderFactory.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProviderFactory.java
index a9178f4c..19571bb2 100644
--- a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProviderFactory.java
+++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataProviderFactory.java
@@ -29,5 +29,16 @@ public interface MetadataProviderFactory {
*/
boolean supports(String databaseProductName);
+ /** @return the provider, reading in {@link MetadataScope#DATABASE} */
MetadataProvider createProvider();
+
+ /**
+ * The provider for {@code scope}, as {@link MetadataProvider#withScope(MetadataScope)} gives it.
+ *
+ * @param scope the scope to read in
+ * @return the provider for {@code scope}
+ */
+ default MetadataProvider createProvider(MetadataScope scope) {
+ return createProvider().withScope(scope);
+ }
}
diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataScope.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataScope.java
new file mode 100644
index 00000000..e78c7a8f
--- /dev/null
+++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataScope.java
@@ -0,0 +1,37 @@
+/*
+* 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
+*
+* Contributors:
+* SmartCity Jena - initial
+* Stefan Bischof (bipolis.org) - initial
+*/
+package org.eclipse.daanse.sql.jdbc.api;
+
+/**
+ * From whose point of view a database is read. A {@link MetadataProvider} reads in one scope; a
+ * snapshot is taken in one scope as a whole, never part in one and part in the other.
+ */
+public enum MetadataScope {
+
+ /**
+ * The whole database of the connection, as its administrator sees it: every schema with every
+ * table, view, key, constraint, index, trigger and routine, every user and role, every
+ * membership and every grant. The connection needs the right to read the whole catalog
+ * ({@link MetadataProvider#scopeRequirement()}); where it lacks it, the provider reads in
+ * {@link #USER} instead.
+ */
+ DATABASE,
+
+ /**
+ * What the connected user may see: the schemas and objects it has a right on, also in schemas
+ * of others, the roles it holds, its memberships and the grants that concern it. What it may
+ * not see is left out, without an error.
+ */
+ USER
+}
diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataScopeException.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataScopeException.java
new file mode 100644
index 00000000..2b50e792
--- /dev/null
+++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/MetadataScopeException.java
@@ -0,0 +1,74 @@
+/*
+* 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
+*
+* Contributors:
+* SmartCity Jena - initial
+* Stefan Bischof (bipolis.org) - initial
+*/
+package org.eclipse.daanse.sql.jdbc.api;
+
+import java.io.Serial;
+import java.sql.SQLException;
+
+/**
+ * A snapshot was asked for in a scope the connection may not read, and the caller wanted no
+ * fallback: thrown before anything is read. Names the database product, the scope asked for, the
+ * scope the connection may read and the right it lacks.
+ */
+public class MetadataScopeException extends SQLException {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ private final String product;
+ private final MetadataScope requested;
+ private final MetadataScope available;
+ private final String requirement;
+
+ /**
+ * @param product the database product, as the driver names it
+ * @param requested the scope asked for
+ * @param available the scope the connection may read
+ * @param requirement the right the connection lacks for {@code requested}, in words
+ */
+ public MetadataScopeException(String product, MetadataScope requested, MetadataScope available,
+ String requirement) {
+ super(message(product, requested, available, requirement));
+ this.product = product;
+ this.requested = requested;
+ this.available = available;
+ this.requirement = requirement;
+ }
+
+ private static String message(String product, MetadataScope requested, MetadataScope available,
+ String requirement) {
+ return "The connection to " + product + " may not read the metadata in scope " + requested
+ + ", only in scope " + available + "; scope " + requested + " needs " + requirement;
+ }
+
+ /** @return the database product, as the driver names it */
+ public String product() {
+ return product;
+ }
+
+ /** @return the scope asked for */
+ public MetadataScope requested() {
+ return requested;
+ }
+
+ /** @return the scope the connection may read */
+ public MetadataScope available() {
+ return available;
+ }
+
+ /** @return the right the connection lacks for the scope asked for, in words */
+ public String requirement() {
+ return requirement;
+ }
+}
diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/SnapshotBuilder.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/SnapshotBuilder.java
index 0e53cf19..4c3ff898 100644
--- a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/SnapshotBuilder.java
+++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/SnapshotBuilder.java
@@ -60,4 +60,51 @@ default MetaInfo createMetaInfo(DataSource dataSource, MetadataProvider metadata
default MetaInfo createMetaInfo(Connection connection, MetadataProvider metadataProvider) throws SQLException {
return createMetaInfo(connection);
}
+
+ /**
+ * A snapshot in the scope of {@code metadataProvider} ({@link MetadataProvider#scope()}). Where
+ * the connection may not read in that scope ({@link MetadataProvider#effectiveScope(Connection)}),
+ * the snapshot is read as a whole in the scope the connection may read, and
+ * {@link org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo#requestedScope()} and
+ * {@link org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo#scope()} tell the two apart; with
+ * {@code strict}, a {@link MetadataScopeException} is thrown instead, before anything is read.
+ * The default implementation checks the scope and delegates to
+ * {@link #createMetaInfo(Connection, MetadataProvider)}.
+ *
+ * @param connection caller-managed connection (not closed by this method)
+ * @param metadataProvider dialect-specific provider, in the scope to read in
+ * @param strict whether to fail instead of reading in another scope
+ * @return MetaInfo snapshot
+ * @throws MetadataScopeException where {@code strict} and the connection may not read in the
+ * scope of {@code metadataProvider}
+ * @throws SQLException on database access error
+ */
+ default MetaInfo createMetaInfo(Connection connection, MetadataProvider metadataProvider, boolean strict)
+ throws SQLException {
+ if (strict) {
+ MetadataScope effective = metadataProvider.effectiveScope(connection);
+ if (effective != metadataProvider.scope()) {
+ throw new MetadataScopeException(connection.getMetaData().getDatabaseProductName(),
+ metadataProvider.scope(), effective, metadataProvider.scopeRequirement());
+ }
+ }
+ return createMetaInfo(connection, metadataProvider);
+ }
+
+ /**
+ * As {@link #createMetaInfo(Connection, MetadataProvider, boolean)}, on a connection borrowed
+ * from {@code dataSource} and released at once.
+ *
+ * @param dataSource pooled or unpooled source
+ * @param metadataProvider dialect-specific provider, in the scope to read in
+ * @param strict whether to fail instead of reading in another scope
+ * @return MetaInfo snapshot
+ * @throws SQLException on database access error
+ */
+ default MetaInfo createMetaInfo(DataSource dataSource, MetadataProvider metadataProvider, boolean strict)
+ throws SQLException {
+ try (Connection connection = dataSource.getConnection()) {
+ return createMetaInfo(connection, metadataProvider, strict);
+ }
+ }
}
diff --git a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/meta/StructureInfo.java b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/meta/StructureInfo.java
index 446aa402..ba78d60f 100644
--- a/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/meta/StructureInfo.java
+++ b/jdbc/api/src/main/java/org/eclipse/daanse/sql/jdbc/api/meta/StructureInfo.java
@@ -15,6 +15,7 @@
import java.util.List;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
import org.eclipse.daanse.sql.model.schema.CatalogReference;
import org.eclipse.daanse.sql.jdbc.api.schema.CheckConstraint;
import org.eclipse.daanse.sql.model.schema.ColumnDefinition;
@@ -126,4 +127,25 @@ default List principal
return List.of();
}
+ /**
+ * The scope the snapshot was asked for.
+ *
+ * @return the scope asked for; {@link MetadataScope#DATABASE} where none was, as for a snapshot
+ * read through JDBC alone, whose driver decides what it shows
+ */
+ default MetadataScope requestedScope() {
+ return MetadataScope.DATABASE;
+ }
+
+ /**
+ * The scope the snapshot was read in: the one asked for, or {@link MetadataScope#USER} where
+ * {@link MetadataScope#DATABASE} was asked for and the connection may not read the whole
+ * database.
+ *
+ * @return the scope read in; {@link MetadataScope#DATABASE} where none was asked for
+ */
+ default MetadataScope scope() {
+ return MetadataScope.DATABASE;
+ }
+
}
diff --git a/jdbc/impl/pom.xml b/jdbc/impl/pom.xml
index 0bcd44cf..14f028d6 100644
--- a/jdbc/impl/pom.xml
+++ b/jdbc/impl/pom.xml
@@ -76,6 +76,31 @@
${project.version}
test
+
+
+ org.testcontainers
+ oracle-free
+ 1.21.4
+ test
+
+
+ org.testcontainers
+ postgresql
+ 1.21.4
+ test
+
+
+ com.oracle.database.jdbc
+ ojdbc11
+ 23.3.0.23.09
+ test
+
+
+ org.postgresql
+ postgresql
+ 42.7.12
+ test
+
org.junit.jupiter
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 f12e119c..ca528d3e 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
@@ -45,6 +45,8 @@
import org.eclipse.daanse.sql.jdbc.api.schema.VersionColumn;
import org.eclipse.daanse.sql.jdbc.api.schema.ViewDefinition;
import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException;
import org.eclipse.daanse.sql.jdbc.api.meta.DatabaseInfo;
import org.eclipse.daanse.sql.jdbc.api.meta.IdentifierInfo;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo;
@@ -156,33 +158,78 @@ public MetaInfo createMetaInfo(DataSource dataSource, MetadataProvider metadataP
*/
@Override
public MetaInfo createMetaInfo(Connection connection, MetadataProvider metadataProvider) throws SQLException {
+ return createMetaInfo(connection, metadataProvider, false);
+ }
+
+ @Override
+ public MetaInfo createMetaInfo(Connection connection, MetadataProvider metadataProvider, boolean strict)
+ throws SQLException {
DatabaseMetaData databaseMetaData = connection.getMetaData();
- return readMetaInfoWithProvider(connection, databaseMetaData, metadataProvider);
+ MetadataScope requested = metadataProvider.scope();
+ MetadataScope effective = metadataProvider.effectiveScope(connection);
+ MetadataProvider provider = metadataProvider;
+ if (effective != requested) {
+ String product = databaseMetaData.getDatabaseProductName();
+ if (strict) {
+ throw new MetadataScopeException(product, requested, effective, metadataProvider.scopeRequirement());
+ }
+ LOGGER.warn("The connection to {} may not read the metadata in scope {}, which needs {}: read in scope {}",
+ product, requested, metadataProvider.scopeRequirement(), effective);
+ provider = metadataProvider.withScope(effective);
+ }
+ return readMetaInfoWithProvider(connection, databaseMetaData, provider, requested);
}
protected MetaInfo readMetaInfoWithProvider(Connection connection, DatabaseMetaData databaseMetaData,
MetadataProvider provider) throws SQLException {
+ return readMetaInfoWithProvider(connection, databaseMetaData, provider, provider.scope());
+ }
+
+ /**
+ * A snapshot in the scope of {@code provider}, asked for in {@code requested}; the scope is not
+ * checked.
+ */
+ protected MetaInfo readMetaInfoWithProvider(Connection connection, DatabaseMetaData databaseMetaData,
+ MetadataProvider provider, MetadataScope requested) throws SQLException {
// Standard metadata (always via JDBC)
DatabaseInfo databaseInfo = readDatabaseInfo(databaseMetaData);
IdentifierInfo identifierInfo = readIdentifierInfo(databaseMetaData);
List typeInfos = getTypeInfo(databaseMetaData);
- // Tables, columns, catalogs, schemas (always via JDBC as the base)
+ // Catalogs via JDBC; the schemas of the provider's scope where it lists them, else as JDBC
+ // lists them.
List catalogs = getCatalogs(databaseMetaData);
- List schemas = getSchemas(databaseMetaData);
- List tables = getTableDefinitions(databaseMetaData);
- // The tables come from every schema, but a provider's bulk method reads one schema — called
- // without one, the connection's current schema only. So each bulk method is called for every
- // schema the tables lie in, and for the current schema, and the snapshot holds the keys,
- // constraints, indexes, … of all its tables, as the per-table JDBC fallbacks do.
- List tableSchemas = schemaNames(tables, connection);
- // BULK: Tables — a provider that reads the tables itself gives them, schema by schema, as it
- // gives the columns: SQL Server's driver reports no comments, Oracle's only on request.
- Optional> providerTables = eachSchemaIfSupported(tableSchemas,
- s -> provider.getAllTableDefinitions(connection, null, s, null, null));
- if (providerTables.isPresent()) {
- tables = providerTables.get();
+ Optional> providerSchemas = provider.getAllSchemas(connection, null);
+ List schemas = providerSchemas.isPresent() ? providerSchemas.get()
+ : getSchemas(databaseMetaData);
+ List tables;
+ // A provider's bulk method reads one schema — called without one, the connection's current
+ // schema only. So each bulk method is called for every schema of the snapshot, and the
+ // snapshot holds the keys, constraints, indexes, … of all its tables, as the per-table JDBC
+ // fallbacks do.
+ List tableSchemas;
+ if (providerSchemas.isPresent()) {
+ // The schemas of the scope decide, not the driver, which reads as the user does: a
+ // provider that reads the tables itself gives them schema by schema.
+ List scopeSchemas = providerSchemas.get().stream().map(SchemaReference::name).distinct()
+ .toList();
+ Optional> providerTables = eachSchemaIfSupported(scopeSchemas,
+ s -> provider.getAllTableDefinitions(connection, null, s, null, null));
+ tables = providerTables.isPresent() ? providerTables.get() : getTableDefinitions(databaseMetaData);
+ tableSchemas = union(scopeSchemas, schemaNamesOf(tables));
+ } else {
+ tables = getTableDefinitions(databaseMetaData);
+ // The tables come from every schema, and the current schema may hold sequences or
+ // routines without holding a table.
+ tableSchemas = schemaNames(tables, connection);
+ // BULK: Tables — a provider that reads the tables itself gives them, schema by schema, as
+ // it gives the columns: SQL Server's driver reports no comments, Oracle's only on request.
+ Optional> providerTables = eachSchemaIfSupported(tableSchemas,
+ s -> provider.getAllTableDefinitions(connection, null, s, null, null));
+ if (providerTables.isPresent()) {
+ tables = providerTables.get();
+ }
}
// BULK: Columns — dialect-optimized when supported (Oracle's ALL_TAB_COLS
// avoids the COLUMN_DEF LONG quirk that breaks DatabaseMetaData.getColumns).
@@ -305,10 +352,26 @@ protected MetaInfo readMetaInfoWithProvider(Connection connection, DatabaseMetaD
importedKeys, primaryKeys, triggers, sequences, checkConstraints, uniqueConstraints,
userDefinedTypes, viewDefinitions, procedures, functions, materializedViews, partitions,
tablePrivileges, List.copyOf(columnPrivileges), objectPrivileges, roleMemberships, principals,
- synonyms);
+ synonyms, requested, provider.scope());
return new MetaInfoRecord(databaseInfo, structureInfo, identifierInfo, typeInfos, indexInfos);
}
+ /** The names of the schemas the tables lie in, as {@link #schemaNames} names them. */
+ private static List schemaNamesOf(List tables) {
+ Set names = new LinkedHashSet<>();
+ for (TableDefinition td : tables) {
+ td.table().schema().map(SchemaReference::name).ifPresent(names::add);
+ }
+ return List.copyOf(names);
+ }
+
+ /** {@code first}, then what {@code second} adds, each once. */
+ private static List union(List first, List second) {
+ Set names = new LinkedHashSet<>(first);
+ names.addAll(second);
+ return List.copyOf(names);
+ }
+
/**
* 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
@@ -339,10 +402,7 @@ private interface SchemaRead {
*/
private static List schemaNames(List tables, Connection connection)
throws SQLException {
- Set names = new LinkedHashSet<>();
- for (TableDefinition td : tables) {
- td.table().schema().map(SchemaReference::name).ifPresent(names::add);
- }
+ Set names = new LinkedHashSet<>(schemaNamesOf(tables));
String current = connection.getSchema() != null ? connection.getSchema() : connection.getCatalog();
if (current != null) {
names.add(current);
diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java
new file mode 100644
index 00000000..a6b26553
--- /dev/null
+++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java
@@ -0,0 +1,193 @@
+/*
+* 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 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.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
+import org.eclipse.daanse.sql.jdbc.api.schema.TableDefinition;
+import org.eclipse.daanse.sql.jdbc.record.schema.TableDefinitionRecord;
+import org.eclipse.daanse.sql.jdbc.record.schema.TableMetaDataRecord;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.eclipse.daanse.sql.model.schema.TableReference;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * A snapshot is read in one scope, as a whole. Where the connection may not read in the scope asked
+ * for, the snapshot is read with the provider for the scope it may read in, and names both; asked
+ * to be strict, it fails before reading. The schemas of the provider's scope replace those JDBC
+ * lists, and the tables are read in these schemas.
+ *
+ * The provider here sees two schemas, {@code VISIBLE} and {@code HIDDEN}; in {@code USER} only
+ * {@code VISIBLE}. Its {@code DATABASE} scope is out of reach for the connection, as a database that
+ * needs a right the connection lacks.
+ */
+class DatabaseServiceReadsInOneScopeH2Test {
+
+ private static Connection connection;
+
+ @BeforeAll
+ static void setUp() throws Exception {
+ connection = DriverManager.getConnection("jdbc:h2:mem:readsInOneScope;DB_CLOSE_DELAY=-1", "sa", "");
+ try (Statement stmt = connection.createStatement()) {
+ stmt.execute("CREATE SCHEMA VISIBLE");
+ stmt.execute("CREATE TABLE VISIBLE.ORDERS (ID INT NOT NULL PRIMARY KEY)");
+ stmt.execute("CREATE SCHEMA HIDDEN");
+ stmt.execute("CREATE TABLE HIDDEN.SECRET (ID INT NOT NULL PRIMARY KEY)");
+ }
+ }
+
+ @AfterAll
+ static void tearDown() throws Exception {
+ try (Statement stmt = connection.createStatement()) {
+ stmt.execute("DROP ALL OBJECTS");
+ }
+ connection.close();
+ }
+
+ @Test
+ void aConnectionThatMayNotReadTheWholeDatabaseIsReadInUserScope() throws SQLException {
+ ScopedProvider database = new ScopedProvider(MetadataScope.DATABASE, false);
+
+ StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(connection, database).structureInfo();
+
+ assertThat(structure.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(structure.scope()).isEqualTo(MetadataScope.USER);
+ assertThat(database.reads).as("nothing read in the scope asked for").isZero();
+ assertThat(structure.schemas()).extracting(SchemaReference::name).containsExactly("VISIBLE");
+ assertThat(structure.tables()).extracting(t -> t.table().name()).containsExactly("ORDERS");
+ assertThat(structure.primaryKeys()).extracting(k -> k.table().name()).containsExactly("ORDERS");
+ }
+
+ @Test
+ void aStrictSnapshotFailsBeforeReading() throws SQLException {
+ ScopedProvider database = new ScopedProvider(MetadataScope.DATABASE, false);
+
+ assertThatThrownBy(() -> new DatabaseServiceImpl().createMetaInfo(connection, database, true))
+ .isInstanceOfSatisfying(MetadataScopeException.class, e -> {
+ assertThat(e.product()).isEqualTo("H2");
+ assertThat(e.requested()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(e.available()).isEqualTo(MetadataScope.USER);
+ assertThat(e.requirement()).isEqualTo(ScopedProvider.REQUIREMENT);
+ assertThat(e.getMessage()).contains(ScopedProvider.REQUIREMENT);
+ });
+ assertThat(database.reads).as("nothing read").isZero();
+ }
+
+ @Test
+ void aConnectionThatMayReadTheWholeDatabaseIsReadInDatabaseScope() throws SQLException {
+ ScopedProvider database = new ScopedProvider(MetadataScope.DATABASE, true);
+
+ StructureInfo structure = new DatabaseServiceImpl().createMetaInfo(connection, database, true)
+ .structureInfo();
+
+ assertThat(structure.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(structure.scope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(structure.schemas()).extracting(SchemaReference::name).containsExactly("VISIBLE", "HIDDEN");
+ assertThat(structure.tables()).extracting(t -> t.table().name()).containsExactlyInAnyOrder("ORDERS",
+ "SECRET");
+ }
+
+ /** The schemas of the provider's scope replace those JDBC lists, PUBLIC and INFORMATION_SCHEMA. */
+ @Test
+ void theUserScopeAskedForIsReadInIt() throws SQLException {
+ StructureInfo structure = new DatabaseServiceImpl()
+ .createMetaInfo(connection, new ScopedProvider(MetadataScope.USER, false), true).structureInfo();
+
+ assertThat(structure.requestedScope()).isEqualTo(MetadataScope.USER);
+ assertThat(structure.scope()).isEqualTo(MetadataScope.USER);
+ assertThat(structure.schemas()).extracting(SchemaReference::name).containsExactly("VISIBLE");
+ assertThat(structure.tables()).extracting(t -> t.table().name()).containsExactly("ORDERS");
+ }
+
+ /**
+ * Reads {@code VISIBLE} and {@code HIDDEN} in {@code DATABASE}, {@code VISIBLE} in {@code USER};
+ * counts what it reads.
+ */
+ private static final class ScopedProvider implements MetadataProvider {
+
+ static final String REQUIREMENT = "the right to read the whole catalog";
+
+ private final MetadataScope scope;
+ private final boolean mayReadDatabase;
+ int reads;
+
+ ScopedProvider(MetadataScope scope, boolean mayReadDatabase) {
+ this.scope = scope;
+ this.mayReadDatabase = mayReadDatabase;
+ }
+
+ @Override
+ public MetadataProvider withScope(MetadataScope other) {
+ return other == scope ? this : new ScopedProvider(other, mayReadDatabase);
+ }
+
+ @Override
+ public MetadataScope scope() {
+ return scope;
+ }
+
+ @Override
+ public MetadataScope effectiveScope(Connection c) {
+ return scope == MetadataScope.DATABASE && !mayReadDatabase ? MetadataScope.USER : scope;
+ }
+
+ @Override
+ public String scopeRequirement() {
+ return REQUIREMENT;
+ }
+
+ private List schemas() {
+ return scope == MetadataScope.DATABASE ? List.of("VISIBLE", "HIDDEN") : List.of("VISIBLE");
+ }
+
+ @Override
+ public Optional> getAllSchemas(Connection c, String catalog) {
+ reads++;
+ return Optional.of(schemas().stream().map(name -> new SchemaReference(Optional.empty(), name)).toList());
+ }
+
+ @Override
+ public Optional> getAllTableDefinitions(Connection c, String catalog,
+ String schemaPattern, String tableNamePattern, String[] types) throws SQLException {
+ reads++;
+ List tables = new ArrayList<>();
+ if (!schemas().contains(schemaPattern)) {
+ return Optional.of(tables);
+ }
+ try (ResultSet rs = c.getMetaData().getTables(null, schemaPattern, tableNamePattern, types)) {
+ while (rs.next()) {
+ TableReference table = new TableReference(
+ Optional.of(new SchemaReference(Optional.empty(), rs.getString("TABLE_SCHEM"))),
+ rs.getString("TABLE_NAME"), rs.getString("TABLE_TYPE"));
+ tables.add(new TableDefinitionRecord(table, new TableMetaDataRecord(Optional.empty(),
+ Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(),
+ Optional.empty())));
+ }
+ }
+ return Optional.of(tables);
+ }
+ }
+}
diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java
new file mode 100644
index 00000000..9e8d3eab
--- /dev/null
+++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java
@@ -0,0 +1,396 @@
+/*
+* 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.scope;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
+import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl;
+import org.eclipse.daanse.sql.model.schema.CatalogReference;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.eclipse.daanse.sql.model.schema.TableReference;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestInstance.Lifecycle;
+
+/**
+ * A database read in both scopes, the same way on every database. Each database gets the same
+ * objects, created by its administrator:
+ *
+ *
+ * shop.orders (id, qty) stock.product stock.secret hidden.t function stock.f
+ * role r_reader SELECT on shop.orders and stock.product
+ * role r_other SELECT on stock.secret
+ * user clerk member of r_reader, UPDATE (qty) on shop.orders, EXECUTE on stock.f
+ * user other member of r_other
+ *
+ *
+ * The administrator reads everything in {@link MetadataScope#DATABASE}; {@code clerk} reads in
+ * {@link MetadataScope#USER} what it may see: the orders and the products, the function, the role
+ * it holds, its membership and the grants that concern it; not the secret, not the hidden schema,
+ * not {@code r_other} and its member. Asked for {@link MetadataScope#DATABASE}, {@code clerk} gets
+ * the whole snapshot in {@link MetadataScope#USER}, where the database keeps the catalog from it.
+ *
+ * A subclass starts the database and says how it differs: the statements of the objects, the
+ * connections and what the database lacks. Names are compared without regard to case, as databases
+ * fold them.
+ */
+@TestInstance(Lifecycle.PER_CLASS)
+abstract class MetadataScopeContract {
+
+ /** The schemas of the objects. */
+ private static final Set SCHEMAS = Set.of("shop", "stock", "hidden");
+
+ private StructureInfo database;
+ private StructureInfo user;
+ private StructureInfo fallback;
+ private List userStatements;
+
+ protected abstract void start() throws Exception;
+
+ protected void stop() throws Exception {
+ }
+
+ /** A new connection of the administrator, who creates the objects and reads everything. */
+ protected abstract Connection admin() throws SQLException;
+
+ protected abstract Connection clerk() throws SQLException;
+
+ /** The statements that create the objects, run by the administrator. */
+ protected abstract List fixture();
+
+ /** The statements that grant {@code clerk} reading {@code hidden.t}, run by the administrator. */
+ protected abstract List grantTheHiddenTable();
+
+ protected abstract List revokeTheHiddenTable();
+
+ protected abstract MetadataProvider provider(MetadataScope scope);
+
+ /** Whether every user may read the whole catalog, so that no reader falls back. */
+ protected boolean everyReaderMayReadTheDatabase() {
+ return false;
+ }
+
+ /** Whether every user is a schema, so that {@code clerk} sees the name of the hidden schema. */
+ protected boolean everyUserIsASchema() {
+ return false;
+ }
+
+ /**
+ * What a statement read in {@link MetadataScope#USER} must not name: the views or tables only an
+ * administrator may read. Empty where both scopes read the same catalog views.
+ */
+ protected List catalogOfTheAdministrator() {
+ return List.of();
+ }
+
+ @BeforeAll
+ void setUp() throws Exception {
+ start();
+ run(fixture());
+ try (Connection admin = admin()) {
+ database = snapshot(admin, MetadataScope.DATABASE);
+ }
+ try (Connection clerk = clerk()) {
+ Recorder recorder = new Recorder(clerk);
+ user = snapshot(recorder.connection(), MetadataScope.USER);
+ userStatements = recorder.statements;
+ }
+ try (Connection clerk = clerk()) {
+ fallback = snapshot(clerk, MetadataScope.DATABASE);
+ }
+ }
+
+ @AfterAll
+ void tearDown() throws Exception {
+ stop();
+ }
+
+ @Test
+ void databaseScopeHoldsEverything() {
+ assertThat(database.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(database.scope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(tables(database)).containsExactlyInAnyOrder("shop.orders", "stock.product", "stock.secret",
+ "hidden.t");
+ assertThat(schemas(database)).contains("shop", "stock", "hidden");
+ assertThat(routines(database)).contains("stock.f");
+ assertThat(principals(database)).contains("r_reader", "r_other", "clerk", "other");
+ assertThat(memberships(database)).contains("clerk > r_reader", "other > r_other");
+ assertThat(tableGrants(database)).contains("r_reader select shop.orders", "r_reader select stock.product",
+ "r_other select stock.secret");
+ assertThat(columnGrants(database)).contains("clerk update shop.orders.qty");
+ assertThat(routineGrants(database)).contains("clerk execute stock.f");
+ }
+
+ @Test
+ void userScopeHoldsWhatTheUserMaySee() {
+ assertThat(user.requestedScope()).isEqualTo(MetadataScope.USER);
+ assertThat(user.scope()).isEqualTo(MetadataScope.USER);
+ assertThat(tables(user)).containsExactlyInAnyOrder("shop.orders", "stock.product");
+ assertThat(schemas(user)).contains("shop", "stock");
+ if (!everyUserIsASchema()) {
+ assertThat(schemas(user)).doesNotContain("hidden");
+ }
+ assertThat(routines(user)).contains("stock.f");
+ assertThat(principals(user)).contains("r_reader").doesNotContain("r_other");
+ assertThat(memberships(user)).contains("clerk > r_reader")
+ .noneMatch(m -> m.startsWith("other ") || m.endsWith(" r_other"));
+ assertThat(tableGrants(user)).contains("r_reader select shop.orders", "r_reader select stock.product")
+ .noneMatch(g -> g.endsWith("stock.secret") || g.contains("r_other"));
+ assertThat(columnGrants(user)).contains("clerk update shop.orders.qty");
+ assertThat(routineGrants(user)).contains("clerk execute stock.f");
+ }
+
+ /**
+ * A user without the right to read the whole catalog, asked for {@link MetadataScope#DATABASE},
+ * gets the snapshot of {@link MetadataScope#USER}, whole, and is told so. Where every user may
+ * read the catalog, it gets {@link MetadataScope#DATABASE}, the secret and the hidden table too.
+ */
+ @Test
+ void databaseScopeFallsBackForAPlainUser() {
+ assertThat(fallback.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ if (everyReaderMayReadTheDatabase()) {
+ assertThat(fallback.scope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(tables(fallback)).contains("stock.secret", "hidden.t");
+ return;
+ }
+ assertThat(fallback.scope()).isEqualTo(MetadataScope.USER);
+ assertThat(fallback.schemas()).containsExactlyInAnyOrderElementsOf(user.schemas());
+ assertThat(fallback.tables()).containsExactlyInAnyOrderElementsOf(user.tables());
+ assertThat(fallback.functions()).containsExactlyInAnyOrderElementsOf(user.functions());
+ assertThat(fallback.procedures()).containsExactlyInAnyOrderElementsOf(user.procedures());
+ assertThat(fallback.tablePrivileges()).containsExactlyInAnyOrderElementsOf(user.tablePrivileges());
+ assertThat(fallback.columnPrivileges()).containsExactlyInAnyOrderElementsOf(user.columnPrivileges());
+ assertThat(fallback.objectPrivileges()).containsExactlyInAnyOrderElementsOf(user.objectPrivileges());
+ assertThat(fallback.roleMemberships()).containsExactlyInAnyOrderElementsOf(user.roleMemberships());
+ assertThat(fallback.principals()).containsExactlyInAnyOrderElementsOf(user.principals());
+ }
+
+ @Test
+ void aStrictSnapshotOfAPlainUserFailsAndNamesTheRight() throws SQLException {
+ MetadataProvider provider = provider(MetadataScope.DATABASE);
+ try (Connection clerk = clerk()) {
+ if (everyReaderMayReadTheDatabase()) {
+ assertThat(new DatabaseServiceImpl().createMetaInfo(clerk, provider, true).structureInfo().scope())
+ .isEqualTo(MetadataScope.DATABASE);
+ return;
+ }
+ assertThatThrownBy(() -> new DatabaseServiceImpl().createMetaInfo(clerk, provider, true))
+ .isInstanceOfSatisfying(MetadataScopeException.class, e -> {
+ assertThat(e.requested()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(e.available()).isEqualTo(MetadataScope.USER);
+ assertThat(e.requirement()).isEqualTo(provider.scopeRequirement()).isNotEqualTo("none");
+ assertThat(e.getMessage()).contains(provider.scopeRequirement());
+ });
+ }
+ }
+
+ @Test
+ void aSchemaGrantedToTheUserComesWithItsTables() throws Exception {
+ run(grantTheHiddenTable());
+ try (Connection clerk = clerk()) {
+ StructureInfo granted = snapshot(clerk, MetadataScope.USER);
+
+ assertThat(schemas(granted)).contains("hidden");
+ assertThat(tables(granted)).contains("hidden.t");
+ } finally {
+ run(revokeTheHiddenTable());
+ }
+ }
+
+ @Test
+ void userScopeReadsNoCatalogOfTheAdministrator() {
+ assumeFalse(catalogOfTheAdministrator().isEmpty(), "both scopes read the same catalog");
+
+ assertThat(userStatements).isNotEmpty();
+ for (String forbidden : catalogOfTheAdministrator()) {
+ assertThat(userStatements).noneMatch(sql -> sql.toUpperCase(Locale.ROOT).contains(forbidden));
+ }
+ }
+
+ protected StructureInfo snapshot(Connection connection, MetadataScope scope) throws SQLException {
+ return new DatabaseServiceImpl().createMetaInfo(connection, provider(scope)).structureInfo();
+ }
+
+ /** Runs {@code statements} as the administrator. */
+ protected void run(List statements) throws SQLException {
+ try (Connection admin = admin(); Statement statement = admin.createStatement()) {
+ for (String sql : statements) {
+ statement.execute(sql);
+ }
+ }
+ }
+
+ /** The tables of the snapshot in the schemas of the objects, as {@code schema.table}. */
+ protected static Set tables(StructureInfo structure) {
+ Set names = new TreeSet<>();
+ for (var definition : structure.tables()) {
+ TableReference table = definition.table();
+ String type = table.type();
+ if (inSchemas(table.schema()) && (type == null || "TABLE".equalsIgnoreCase(type)
+ || "BASE TABLE".equalsIgnoreCase(type))) {
+ names.add(qualified(table.schema(), table.name()));
+ }
+ }
+ return names;
+ }
+
+ /**
+ * The schemas of the snapshot; for a database that keeps none, its catalogs, which it names as
+ * the schemas.
+ */
+ protected static Set schemas(StructureInfo structure) {
+ Set names = new TreeSet<>();
+ structure.schemas().forEach(schema -> names.add(lower(schema.name())));
+ if (names.isEmpty()) {
+ structure.catalogs().stream().map(CatalogReference::name).forEach(name -> names.add(lower(name)));
+ }
+ return names;
+ }
+
+ /** The functions and procedures of the snapshot in the schemas of the objects. */
+ protected static Set routines(StructureInfo structure) {
+ Set names = new TreeSet<>();
+ structure.functions().stream().filter(f -> inSchemas(f.reference().schema()))
+ .forEach(f -> names.add(qualified(f.reference().schema(), f.reference().name())));
+ structure.procedures().stream().filter(p -> inSchemas(p.reference().schema()))
+ .forEach(p -> names.add(qualified(p.reference().schema(), p.reference().name())));
+ return names;
+ }
+
+ /** The names of the users and roles. */
+ protected static Set principals(StructureInfo structure) {
+ Set names = new TreeSet<>();
+ structure.principals().forEach(principal -> names.add(lower(principal.name())));
+ return names;
+ }
+
+ /** The memberships, as {@code grantee > role}. */
+ protected static Set memberships(StructureInfo structure) {
+ Set names = new TreeSet<>();
+ structure.roleMemberships().forEach(m -> names.add(lower(m.grantee()) + " > " + lower(m.role())));
+ return names;
+ }
+
+ /** The grants on tables in the schemas of the objects, as {@code grantee privilege schema.table}. */
+ protected static Set tableGrants(StructureInfo structure) {
+ Set grants = new TreeSet<>();
+ structure.tablePrivileges().stream().filter(p -> inSchemas(p.table().schema()))
+ .forEach(p -> grants.add(lower(p.grantee()) + " " + lower(p.privilege()) + " "
+ + qualified(p.table().schema(), p.table().name())));
+ return grants;
+ }
+
+ /**
+ * The grants on columns in the schemas of the objects, as
+ * {@code grantee privilege schema.table.column}.
+ */
+ protected static Set columnGrants(StructureInfo structure) {
+ Set grants = new TreeSet<>();
+ for (var p : structure.columnPrivileges()) {
+ Optional table = p.column().table();
+ if (table.isPresent() && inSchemas(table.get().schema())) {
+ grants.add(lower(p.grantee()) + " " + lower(p.privilege()) + " "
+ + qualified(table.get().schema(), table.get().name()) + "." + lower(p.column().name()));
+ }
+ }
+ return grants;
+ }
+
+ /**
+ * The grants on other objects in the schemas of the objects, routines among them, as
+ * {@code grantee privilege schema.object}.
+ */
+ protected static Set routineGrants(StructureInfo structure) {
+ Set grants = new TreeSet<>();
+ structure.objectPrivileges().stream()
+ .filter(p -> p.schemaName().map(s -> SCHEMAS.contains(lower(s))).orElse(false))
+ .forEach(p -> grants.add(lower(p.grantee()) + " " + lower(p.privilege()) + " "
+ + lower(p.schemaName().orElseThrow()) + "." + lower(p.objectName())));
+ return grants;
+ }
+
+ private static boolean inSchemas(Optional schema) {
+ return schema.map(s -> SCHEMAS.contains(lower(s.name()))).orElse(false);
+ }
+
+ private static String qualified(Optional schema, String name) {
+ return schema.map(s -> lower(s.name()) + ".").orElse("") + lower(name);
+ }
+
+ private static String lower(String name) {
+ return name == null ? "" : name.toLowerCase(Locale.ROOT);
+ }
+
+ /** A connection that writes down every statement it is given. */
+ private static final class Recorder implements InvocationHandler {
+
+ private final Connection target;
+ private final List statements = Collections.synchronizedList(new ArrayList<>());
+
+ Recorder(Connection target) {
+ this.target = target;
+ }
+
+ Connection connection() {
+ return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
+ new Class>[] { Connection.class }, this);
+ }
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ if (args != null && args.length > 0 && args[0] instanceof String sql
+ && (method.getName().startsWith("prepare") || method.getName().equals("nativeSQL"))) {
+ statements.add(sql);
+ }
+ Object result = call(target, method, args);
+ if (result instanceof Statement statement && method.getName().equals("createStatement")) {
+ return Proxy.newProxyInstance(Statement.class.getClassLoader(), new Class>[] { Statement.class },
+ (p, m, a) -> {
+ if (a != null && a.length > 0 && a[0] instanceof String sql) {
+ statements.add(sql);
+ }
+ return call(statement, m, a);
+ });
+ }
+ return result;
+ }
+
+ private static Object call(Object target, Method method, Object[] args) throws Throwable {
+ try {
+ return method.invoke(target, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ }
+ }
+}
diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/OracleMetadataScopeTest.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/OracleMetadataScopeTest.java
new file mode 100644
index 00000000..17d1566a
--- /dev/null
+++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/OracleMetadataScopeTest.java
@@ -0,0 +1,135 @@
+/*
+* 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.scope;
+
+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.time.Duration;
+import java.util.List;
+
+import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
+import org.eclipse.daanse.sql.jdbc.metadata.OracleMetadataProvider;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.testcontainers.oracle.OracleContainer;
+
+/**
+ * The scopes on Oracle, in a container. A schema is a user: {@code shop}, {@code stock} and
+ * {@code hidden} are users that cannot log in. SYSTEM creates the objects and reads in
+ * {@link MetadataScope#DATABASE}; {@code auditor}, which may log in and read the dictionary
+ * ({@code SELECT_CATALOG_ROLE}) and nothing else, reads the whole database too.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class OracleMetadataScopeTest extends MetadataScopeContract {
+
+ @SuppressWarnings("resource")
+ private final OracleContainer container = new OracleContainer("gvenzl/oracle-free:23-slim-faststart")
+ .withStartupTimeout(Duration.ofMinutes(5));
+
+ @Override
+ protected void start() {
+ container.start();
+ }
+
+ @Override
+ protected void stop() {
+ container.stop();
+ }
+
+ @Override
+ protected Connection admin() throws SQLException {
+ return DriverManager.getConnection(container.getJdbcUrl(), "system", container.getPassword());
+ }
+
+ @Override
+ protected Connection clerk() throws SQLException {
+ return DriverManager.getConnection(container.getJdbcUrl(), "clerk", "clerk");
+ }
+
+ private Connection auditor() throws SQLException {
+ return DriverManager.getConnection(container.getJdbcUrl(), "auditor", "auditor");
+ }
+
+ @Override
+ protected List fixture() {
+ return List.of("CREATE USER shop NO AUTHENTICATION QUOTA UNLIMITED ON USERS",
+ "CREATE USER stock NO AUTHENTICATION QUOTA UNLIMITED ON USERS",
+ "CREATE USER hidden NO AUTHENTICATION QUOTA UNLIMITED ON USERS",
+ "CREATE TABLE shop.orders (id INT PRIMARY KEY, qty INT)",
+ "CREATE TABLE stock.product (id INT PRIMARY KEY)",
+ "CREATE TABLE stock.secret (id INT PRIMARY KEY)",
+ "CREATE TABLE hidden.t (id INT PRIMARY KEY)",
+ "CREATE FUNCTION stock.f RETURN NUMBER AS BEGIN RETURN 1; END;",
+ "CREATE ROLE r_reader", "CREATE ROLE r_other",
+ "GRANT SELECT ON shop.orders TO r_reader", "GRANT SELECT ON stock.product TO r_reader",
+ "GRANT SELECT ON stock.secret TO r_other",
+ "CREATE USER clerk IDENTIFIED BY clerk", "GRANT CREATE SESSION TO clerk",
+ "GRANT r_reader TO clerk", "GRANT UPDATE (qty) ON shop.orders TO clerk",
+ "GRANT EXECUTE ON stock.f TO clerk",
+ "CREATE USER other IDENTIFIED BY other", "GRANT CREATE SESSION TO other", "GRANT r_other TO other",
+ "CREATE USER auditor IDENTIFIED BY auditor", "GRANT CREATE SESSION, SELECT_CATALOG_ROLE TO auditor");
+ }
+
+ @Override
+ protected List grantTheHiddenTable() {
+ return List.of("GRANT SELECT ON hidden.t TO clerk");
+ }
+
+ @Override
+ protected List revokeTheHiddenTable() {
+ return List.of("REVOKE SELECT ON hidden.t FROM clerk");
+ }
+
+ @Override
+ protected MetadataProvider provider(MetadataScope scope) {
+ return new OracleMetadataProvider(scope);
+ }
+
+ @Override
+ protected boolean everyUserIsASchema() {
+ return true;
+ }
+
+ @Override
+ protected List catalogOfTheAdministrator() {
+ return List.of("DBA_");
+ }
+
+ /**
+ * A reader of the dictionary, who has no right on any table, reads the whole database: the
+ * {@code ALL_} views show it nothing of the three schemas, the {@code DBA_} views everything.
+ */
+ @Test
+ void databaseScopeForAReaderOfTheDictionary() throws SQLException {
+ try (Connection auditor = auditor()) {
+ try (Statement statement = auditor.createStatement();
+ ResultSet rs = statement.executeQuery(
+ "SELECT COUNT(*) FROM ALL_TABLES WHERE OWNER IN ('SHOP', 'STOCK', 'HIDDEN')")) {
+ rs.next();
+ assertThat(rs.getInt(1)).as("the tables ALL_TABLES shows the auditor").isZero();
+ }
+ StructureInfo structure = snapshot(auditor, MetadataScope.DATABASE);
+
+ assertThat(structure.scope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(tables(structure)).containsExactlyInAnyOrder("shop.orders", "stock.product", "stock.secret",
+ "hidden.t");
+ assertThat(memberships(structure)).contains("clerk > r_reader", "other > r_other");
+ assertThat(tableGrants(structure)).contains("r_other select stock.secret");
+ assertThat(columnGrants(structure)).contains("clerk update shop.orders.qty");
+ }
+ }
+}
diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/PostgreSqlMetadataScopeTest.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/PostgreSqlMetadataScopeTest.java
new file mode 100644
index 00000000..0c74fb26
--- /dev/null
+++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/PostgreSqlMetadataScopeTest.java
@@ -0,0 +1,175 @@
+/*
+* 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.scope;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
+import org.eclipse.daanse.sql.jdbc.metadata.PostgreSqlMetadataProvider;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.testcontainers.containers.PostgreSQLContainer;
+
+/**
+ * The scopes on PostgreSQL, in a container. The container's user, a superuser, creates the objects
+ * and reads in {@link MetadataScope#DATABASE}. The system catalog shows every object and every grant
+ * to every user, so {@code clerk} reads the whole database too where it asks for it; in
+ * {@link MetadataScope#USER} it reads what {@code information_schema} would show it.
+ */
+@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
+class PostgreSqlMetadataScopeTest extends MetadataScopeContract {
+
+ @SuppressWarnings("resource")
+ private final PostgreSQLContainer> container = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ @Override
+ protected void start() {
+ container.start();
+ }
+
+ @Override
+ protected void stop() {
+ container.stop();
+ }
+
+ @Override
+ protected Connection admin() throws SQLException {
+ return DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword());
+ }
+
+ @Override
+ protected Connection clerk() throws SQLException {
+ return DriverManager.getConnection(container.getJdbcUrl(), "clerk", "clerk");
+ }
+
+ @Override
+ protected List fixture() {
+ return List.of("CREATE SCHEMA shop", "CREATE SCHEMA stock", "CREATE SCHEMA hidden",
+ "CREATE TABLE shop.orders (id INT PRIMARY KEY, qty INT)",
+ "CREATE TABLE stock.product (id INT PRIMARY KEY)",
+ "CREATE TABLE stock.secret (id INT PRIMARY KEY)",
+ "CREATE TABLE hidden.t (id INT PRIMARY KEY)",
+ "CREATE FUNCTION stock.f() RETURNS INT LANGUAGE SQL AS 'SELECT 1'",
+ "REVOKE EXECUTE ON FUNCTION stock.f() FROM PUBLIC",
+ "CREATE ROLE r_reader", "CREATE ROLE r_other",
+ "GRANT USAGE ON SCHEMA shop, stock TO r_reader",
+ "GRANT SELECT ON shop.orders, stock.product TO r_reader",
+ "GRANT USAGE ON SCHEMA stock TO r_other", "GRANT SELECT ON stock.secret TO r_other",
+ "CREATE ROLE clerk LOGIN PASSWORD 'clerk'", "GRANT r_reader TO clerk",
+ "GRANT UPDATE (qty) ON shop.orders TO clerk", "GRANT EXECUTE ON FUNCTION stock.f() TO clerk",
+ "CREATE ROLE other LOGIN PASSWORD 'other'", "GRANT r_other TO other");
+ }
+
+ @Override
+ protected List grantTheHiddenTable() {
+ return List.of("GRANT USAGE ON SCHEMA hidden TO clerk", "GRANT SELECT ON hidden.t TO clerk");
+ }
+
+ @Override
+ protected List revokeTheHiddenTable() {
+ return List.of("REVOKE SELECT ON hidden.t FROM clerk", "REVOKE USAGE ON SCHEMA hidden FROM clerk");
+ }
+
+ @Override
+ protected MetadataProvider provider(MetadataScope scope) {
+ return new PostgreSqlMetadataProvider(scope);
+ }
+
+ @Override
+ protected boolean everyReaderMayReadTheDatabase() {
+ return true;
+ }
+
+ @Test
+ void everyReaderMayReadDatabaseScope() throws SQLException {
+ MetadataProvider database = provider(MetadataScope.DATABASE);
+ try (Connection clerk = clerk()) {
+ assertThat(database.effectiveScope(clerk)).isEqualTo(MetadataScope.DATABASE);
+ }
+ assertThat(database.scopeRequirement()).isEqualTo("none");
+ }
+
+ /**
+ * A grant on a column is one row, of the column; the grant on its table is not repeated for each
+ * column, as {@code information_schema.column_privileges} repeats it.
+ */
+ @Test
+ void columnGrantIsOneRowNotExpanded() throws SQLException {
+ try (Connection admin = admin()) {
+ StructureInfo structure = snapshot(admin, MetadataScope.DATABASE);
+
+ assertThat(columnGrants(structure)).containsExactly("clerk update shop.orders.qty");
+ }
+ }
+
+ /** A foreign key into a table the user may not see is not read; one into a visible table is. */
+ @Test
+ void aForeignKeyIntoAnInvisibleTableIsNotRead() throws SQLException {
+ run(List.of("CREATE TABLE shop.lines (id INT PRIMARY KEY, orders_id INT REFERENCES shop.orders (id),"
+ + " secret_id INT REFERENCES stock.secret (id))", "GRANT SELECT ON shop.lines TO r_reader"));
+ try (Connection clerk = clerk()) {
+ StructureInfo structure = snapshot(clerk, MetadataScope.USER);
+
+ assertThat(structure.importedKeys())
+ .filteredOn(key -> key.foreignKeyColumn().table().map(t -> t.name().equals("lines")).orElse(false))
+ .extracting(key -> key.primaryKeyColumn().table().orElseThrow().name()).containsExactly("orders");
+ } finally {
+ run(List.of("DROP TABLE shop.lines"));
+ }
+ }
+
+ /**
+ * {@code PUBLIC} may execute a routine unless revoked, so the user sees every such routine of a
+ * schema it may use, and none of a schema it may not.
+ */
+ @Test
+ void aRoutineOfAUsableSchemaIsVisibleThroughPublic() throws SQLException {
+ run(List.of("CREATE FUNCTION shop.g() RETURNS INT LANGUAGE SQL AS 'SELECT 2'",
+ "CREATE FUNCTION hidden.h() RETURNS INT LANGUAGE SQL AS 'SELECT 3'"));
+ try (Connection clerk = clerk()) {
+ StructureInfo structure = snapshot(clerk, MetadataScope.USER);
+
+ assertThat(routines(structure)).contains("shop.g", "stock.f").doesNotContain("hidden.h");
+ } finally {
+ run(List.of("DROP FUNCTION shop.g()", "DROP FUNCTION hidden.h()"));
+ }
+ }
+
+ @Test
+ void ownerSeesItsOwnTablesWithoutGrants() throws SQLException {
+ run(List.of("CREATE ROLE keeper LOGIN PASSWORD 'keeper'", "CREATE SCHEMA own AUTHORIZATION keeper",
+ "CREATE TABLE own.mine (id INT PRIMARY KEY)", "ALTER TABLE own.mine OWNER TO keeper"));
+ try (Connection keeper = DriverManager.getConnection(container.getJdbcUrl(), "keeper", "keeper")) {
+ StructureInfo structure = snapshot(keeper, MetadataScope.USER);
+
+ assertThat(structure.schemas()).extracting(SchemaReference::name).contains("own")
+ .doesNotContain("shop", "stock", "hidden");
+ Set tables = new TreeSet<>();
+ structure.tables().stream().filter(t -> "TABLE".equals(t.table().type()))
+ .filter(t -> t.table().schema().map(s -> s.name().equals("own")).orElse(false))
+ .forEach(t -> tables.add(t.table().name().toLowerCase(Locale.ROOT)));
+ assertThat(tables).containsExactly("mine");
+ assertThat(structure.tablePrivileges()).noneMatch(p -> p.table().name().equals("mine"));
+ } finally {
+ run(List.of("DROP SCHEMA own CASCADE", "DROP ROLE keeper"));
+ }
+ }
+}
diff --git a/jdbc/impl/tests.bnd b/jdbc/impl/tests.bnd
new file mode 100644
index 00000000..a7f64973
--- /dev/null
+++ b/jdbc/impl/tests.bnd
@@ -0,0 +1,22 @@
+#*******************************************************************************
+# 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
+#
+# Contributors:
+# SmartCity Jena - initial
+# Stefan Bischof (bipolis.org) - initial
+#*******************************************************************************
+
+# The instructions of the test fragment, as the parent declares them, and one more: the tests that
+# read databases in containers use Testcontainers, which is no bundle. They run outside OSGi; its
+# packages are imported optionally, so that the fragment resolves without them.
+Test-Cases: ${classes;HIERARCHY_INDIRECTLY_ANNOTATED;org.junit.platform.commons.annotation.Testable;CONCRETE;NAMED;*.integration.*}
+-fixupmessages: *for this fragment/require bundle cannot be found on the classpath
+-noextraheaders: true
+-noimportjava: true
+Import-Package: org.testcontainers.*;resolution:=optional, *
diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviders.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviders.java
index 555facfb..6ab5899e 100644
--- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviders.java
+++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataProviders.java
@@ -16,10 +16,12 @@
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
import org.eclipse.daanse.sql.jdbc.api.MetadataProviderFactory;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
/**
* Static resolver over the engine {@link MetadataProviderFactory} implementations for
@@ -41,15 +43,50 @@ public final class MetadataProviders {
private MetadataProviders() {
}
+ /**
+ * The provider for a database product, reading in {@link MetadataScope#DATABASE}.
+ *
+ * @param databaseProductName as {@code DatabaseMetaData.getDatabaseProductName()} reports it
+ * @return the provider, or empty where no provider serves the product
+ */
public static Optional forProductName(String databaseProductName) {
+ return forProductName(databaseProductName, MetadataScope.DATABASE);
+ }
+
+ /**
+ * The provider for a database product, for {@code scope}, as
+ * {@link MetadataProviderFactory#createProvider(MetadataScope)} creates it.
+ *
+ * @param databaseProductName as {@code DatabaseMetaData.getDatabaseProductName()} reports it
+ * @param scope the scope to read in
+ * @return the provider, or empty where no provider serves the product
+ */
+ public static Optional forProductName(String databaseProductName, MetadataScope scope) {
+ Objects.requireNonNull(scope, "scope");
return FACTORIES.stream()
.filter(f -> f.supports(databaseProductName))
.findFirst()
- .map(MetadataProviderFactory::createProvider);
+ .map(factory -> factory.createProvider(scope));
}
- /** Resolves via {@code connection.getMetaData().getDatabaseProductName()}. */
+ /**
+ * Resolves via {@code connection.getMetaData().getDatabaseProductName()}, reading in
+ * {@link MetadataScope#DATABASE}.
+ */
public static Optional forConnection(Connection connection) throws SQLException {
- return forProductName(connection.getMetaData().getDatabaseProductName());
+ return forConnection(connection, MetadataScope.DATABASE);
+ }
+
+ /**
+ * Resolves via {@code connection.getMetaData().getDatabaseProductName()}, for {@code scope}.
+ *
+ * @param connection the connection whose database is read
+ * @param scope the scope to read in
+ * @return the provider, or empty where no provider serves the database
+ * @throws SQLException on database access error
+ */
+ public static Optional forConnection(Connection connection, MetadataScope scope)
+ throws SQLException {
+ return forProductName(connection.getMetaData().getDatabaseProductName(), scope);
}
}
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 940d7d9a..e9559124 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
@@ -19,16 +19,23 @@
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Statement;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfoItem;
import org.eclipse.daanse.sql.jdbc.api.schema.CheckConstraint;
@@ -77,6 +84,8 @@
import org.eclipse.daanse.sql.jdbc.record.schema.PseudoColumnRecord;
import org.eclipse.daanse.sql.jdbc.record.schema.SequenceRecord;
import org.eclipse.daanse.sql.jdbc.record.schema.SynonymRecord;
+import org.eclipse.daanse.sql.jdbc.record.schema.TableDefinitionRecord;
+import org.eclipse.daanse.sql.jdbc.record.schema.TableMetaDataRecord;
import org.eclipse.daanse.sql.jdbc.record.schema.TablePrivilegeRecord;
import org.eclipse.daanse.sql.jdbc.record.schema.TriggerRecord;
import org.eclipse.daanse.sql.jdbc.record.schema.UniqueConstraintRecord;
@@ -86,58 +95,194 @@
import org.slf4j.LoggerFactory;
/**
- * The Oracle system-catalog/{@code information_schema} reader — the
- * {@link MetadataProvider} overrides extracted 1:1 from the SQL dialect (reading only,
- * no spelling).
+ * The Oracle data dictionary reader — the {@link MetadataProvider} overrides extracted 1:1 from
+ * the SQL dialect (reading only, no spelling).
+ *
+ * In {@link MetadataScope#DATABASE} it reads the {@code DBA_} views, which show every object, user,
+ * role, membership and grant of the database to a reader that may read them
+ * ({@code SELECT_CATALOG_ROLE} or {@code SELECT ANY DICTIONARY}); every structure too, not only the
+ * grants, as the {@code ALL_} views show a reader with these rights nothing of the schemas of
+ * others. In {@link MetadataScope#USER} it reads the {@code ALL_} views and the roles of the user
+ * from {@code USER_ROLE_PRIVS} and {@code ROLE_ROLE_PRIVS}, which every user may read and which
+ * show what the user has a right on.
*/
public class OracleMetadataProvider implements MetadataProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(OracleMetadataProvider.class);
+ /**
+ * The views the provider reads, without their prefix: {@code DBA_} in
+ * {@link MetadataScope#DATABASE}, {@code ALL_} in {@link MetadataScope#USER}.
+ */
+ private static final List VIEWS = List.of("ARGUMENTS", "COL_COMMENTS", "COL_PRIVS", "CONS_COLUMNS",
+ "CONSTRAINTS", "IND_COLUMNS", "IND_EXPRESSIONS", "INDEXES", "MVIEWS", "OBJECTS", "PART_KEY_COLUMNS",
+ "PART_TABLES", "PROCEDURES", "SEQUENCES", "SOURCE", "SUBPART_KEY_COLUMNS", "SYNONYMS", "TAB_COLS",
+ "TAB_COMMENTS", "TAB_PARTITIONS", "TAB_PRIVS", "TAB_SUBPARTITIONS", "TRIGGERS", "TYPES", "USERS",
+ "VIEWS");
+
+ /** The views {@link MetadataScope#DATABASE} reads beyond {@link #VIEWS}, which have no {@code ALL_} form. */
+ private static final List DATABASE_ONLY_VIEWS = List.of("ROLE_PRIVS", "ROLES");
+
+ private static final List DATABASE_VIEWS = Stream.concat(VIEWS.stream(), DATABASE_ONLY_VIEWS.stream())
+ .toList();
+
+ private static final Pattern TOKEN = Pattern.compile("\\{([A-Z_]+)\\}");
+
+ private final MetadataScope scope;
+
+ public OracleMetadataProvider() {
+ this(MetadataScope.DATABASE);
+ }
+
+ public OracleMetadataProvider(MetadataScope scope) {
+ this.scope = Objects.requireNonNull(scope, "scope");
+ }
+
+ @Override
+ public MetadataProvider withScope(MetadataScope other) {
+ return other == scope ? this : new OracleMetadataProvider(other);
+ }
+
+ @Override
+ public MetadataScope scope() {
+ return scope;
+ }
+
+ @Override
+ public MetadataScope effectiveScope(Connection connection) throws SQLException {
+ if (scope != MetadataScope.DATABASE) {
+ return scope;
+ }
+ // A DBA_ view may be granted on its own, so every view DATABASE reads is tried, not one.
+ try (Statement statement = connection.createStatement()) {
+ for (String view : DATABASE_VIEWS) {
+ try (ResultSet rs = statement.executeQuery("SELECT 1 FROM DBA_" + view + " WHERE 1 = 0")) {
+ rs.next();
+ } catch (SQLException e) {
+ LOGGER.debug("DBA_{} is not readable: {}", view, e.getMessage());
+ return MetadataScope.USER;
+ }
+ }
+ }
+ return MetadataScope.DATABASE;
+ }
+
+ @Override
+ public String scopeRequirement() {
+ return "SELECT_CATALOG_ROLE or SELECT ANY DICTIONARY";
+ }
+
+ @Override
+ public Optional> getAllSchemas(Connection connection, String catalog)
+ throws SQLException {
+ return Optional.of(userNames(connection).stream()
+ .map(user -> new SchemaReference(Optional.empty(), user)).toList());
+ }
+
+ /**
+ * Every user: Oracle keeps a schema for each, and {@code ALL_USERS} names every user to every
+ * user.
+ */
+ private List userNames(Connection connection) throws SQLException {
+ List users = new ArrayList<>();
+ try (PreparedStatement ps = connection.prepareStatement(
+ dictionary("SELECT USERNAME FROM {USERS} ORDER BY USERNAME"));
+ ResultSet rs = ps.executeQuery()) {
+ while (rs.next()) {
+ users.add(rs.getString("USERNAME"));
+ }
+ }
+ return users;
+ }
+
+ private String view(String name) {
+ return (scope == MetadataScope.DATABASE ? "DBA_" : "ALL_") + name;
+ }
+
+ /**
+ * The column of {@code TAB_PRIVS} and {@code COL_PRIVS} that names the owner of the object:
+ * {@code DBA_TAB_PRIVS} and {@code DBA_COL_PRIVS} call it {@code OWNER}, the {@code ALL_} views
+ * {@code TABLE_SCHEMA}.
+ */
+ private String privilegesOwner() {
+ return scope == MetadataScope.DATABASE ? "OWNER" : "TABLE_SCHEMA";
+ }
+
+ /**
+ * {@code sql} with each view named for the scope: {@code {OBJECTS}} is {@link #view(String)
+ * view("OBJECTS")}, {@code {PRIVS_OWNER}} the owner column of the privilege views.
+ */
+ private String dictionary(String sql) {
+ return TOKEN.matcher(sql).replaceAll(token -> "PRIVS_OWNER".equals(token.group(1)) ? privilegesOwner()
+ : view(token.group(1)));
+ }
+
/** 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
- * {@code ALL_TAB_COMMENTS}, read for the schemas in one query: the driver reports a table's
- * comment only where the connection asks for it ({@code remarksReporting}).
+ * The tables, views and synonyms as the JDBC driver reports them, but from the views of the
+ * scope: the driver reads {@code ALL_OBJECTS}, which shows a reader of the {@code DBA_} views
+ * nothing of the schemas of others. A materialized view is a table there, as its container
+ * table is. Each with its comment from {@code TAB_COMMENTS}, which the driver reports only where
+ * the connection asks for it ({@code remarksReporting}).
*/
@Override
public Optional> getAllTableDefinitions(
Connection connection, String catalog, String schemaPattern, String tableNamePattern, String[] types)
throws SQLException {
- String sql = """
- SELECT OWNER, TABLE_NAME, COMMENTS FROM ALL_TAB_COMMENTS
- WHERE COMMENTS IS NOT NULL AND (? IS NULL OR OWNER LIKE ? ESCAPE '/')
- """;
- Map comments = new java.util.HashMap<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
- ps.setString(1, schemaPattern);
- ps.setString(2, schemaPattern);
+ List objectTypes = types == null ? List.of("TABLE", "VIEW", "SYNONYM") : List.of(types);
+ StringBuilder sql = new StringBuilder(dictionary("""
+ SELECT o.OWNER, o.OBJECT_NAME, o.OBJECT_TYPE, c.COMMENTS
+ FROM {OBJECTS} o
+ LEFT JOIN {TAB_COMMENTS} c ON c.OWNER = o.OWNER AND c.TABLE_NAME = o.OBJECT_NAME
+ WHERE o.OBJECT_TYPE IN (""")).append(String.join(", ", Collections.nCopies(
+ Math.max(objectTypes.size(), 1), "?"))).append(")\n");
+ if (schemaPattern != null) {
+ sql.append("AND o.OWNER LIKE ? ESCAPE '/'\n");
+ }
+ if (tableNamePattern != null) {
+ sql.append("AND o.OBJECT_NAME LIKE ? ESCAPE '/'\n");
+ }
+ sql.append("ORDER BY o.OBJECT_TYPE, o.OWNER, o.OBJECT_NAME");
+ List tables = new ArrayList<>();
+ try (PreparedStatement ps = connection.prepareStatement(sql.toString())) {
+ int index = 1;
+ if (objectTypes.isEmpty()) {
+ ps.setString(index++, "");
+ }
+ for (String type : objectTypes) {
+ ps.setString(index++, type);
+ }
+ if (schemaPattern != null) {
+ ps.setString(index++, schemaPattern);
+ }
+ if (tableNamePattern != null) {
+ ps.setString(index++, tableNamePattern);
+ }
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
- comments.put(new TableKey(rs.getString("OWNER"), rs.getString("TABLE_NAME")),
- rs.getString("COMMENTS"));
+ TableReference table = new TableReference(
+ Optional.of(new SchemaReference(Optional.empty(), rs.getString("OWNER"))),
+ rs.getString("OBJECT_NAME"), rs.getString("OBJECT_TYPE"));
+ tables.add(new TableDefinitionRecord(table, new TableMetaDataRecord(
+ Optional.ofNullable(rs.getString("COMMENTS")), Optional.empty(), Optional.empty(),
+ Optional.empty(), Optional.empty(), Optional.empty())));
}
}
}
- return Optional.of(DriverMetadata.tables(connection, catalog, schemaPattern, tableNamePattern, types,
- (schema, table, column) -> comments.get(new TableKey(schema, table))));
- }
-
- /** A table or view by its owner, the schema, and its name. */
- private record TableKey(String owner, String table) {
+ return Optional.of(List.copyOf(tables));
}
@Override
public List getAllTriggers(Connection connection, String catalog, String schema) throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT TRIGGER_NAME, TABLE_NAME, TRIGGER_TYPE, TRIGGERING_EVENT, WHEN_CLAUSE, TRIGGER_BODY
- FROM ALL_TRIGGERS WHERE OWNER = ? ORDER BY TABLE_NAME, TRIGGER_NAME
- """;
+ FROM {TRIGGERS} WHERE OWNER = ? ORDER BY TABLE_NAME, TRIGGER_NAME
+ """);
String schemaName = resolveSchema(schema, connection);
List triggers = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -155,11 +300,11 @@ public List getAllTriggers(Connection connection, String catalog, Strin
@Override
public List getTriggers(Connection connection, String catalog, String schema, String tableName)
throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT TRIGGER_NAME, TABLE_NAME, TRIGGER_TYPE, TRIGGERING_EVENT, WHEN_CLAUSE, TRIGGER_BODY
- FROM ALL_TRIGGERS WHERE OWNER = ? AND TABLE_NAME = ?
+ FROM {TRIGGERS} WHERE OWNER = ? AND TABLE_NAME = ?
ORDER BY TRIGGER_NAME
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
List triggers = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -177,10 +322,10 @@ public List getTriggers(Connection connection, String catalog, String s
@Override
public List getAllSequences(Connection connection, String catalog, String schema) throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT SEQUENCE_NAME, MIN_VALUE, MAX_VALUE, INCREMENT_BY, CYCLE_FLAG, CACHE_SIZE, LAST_NUMBER
- FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER = ? ORDER BY SEQUENCE_NAME
- """;
+ FROM {SEQUENCES} WHERE SEQUENCE_OWNER = ? ORDER BY SEQUENCE_NAME
+ """);
String schemaName = resolveSchema(schema, connection);
List sequences = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -211,14 +356,14 @@ public List getAllSequences(Connection connection, String catalog, Str
public List getAllSynonyms(Connection connection, String catalog, String schema) throws SQLException {
// Private synonyms of the schema, plus PUBLIC synonyms pointing into it — all
// PUBLIC synonyms would pull in thousands of SYS/dictionary aliases.
- // The target type comes from ALL_OBJECTS; synonyms over a DB link point to a
+ // The target type comes from OBJECTS; synonyms over a DB link point to a
// remote object, so they are not joined. Object types outside the synonym
// namespace (INDEX, PACKAGE BODY, partitions, ...) can share the target's name
// and are excluded.
- String sql = """
+ String sql = dictionary("""
SELECT s.OWNER, s.SYNONYM_NAME, s.TABLE_OWNER, s.TABLE_NAME, s.DB_LINK, o.OBJECT_TYPE
- FROM ALL_SYNONYMS s
- LEFT JOIN ALL_OBJECTS o
+ FROM {SYNONYMS} s
+ LEFT JOIN {OBJECTS} o
ON s.DB_LINK IS NULL
AND o.OWNER = s.TABLE_OWNER
AND o.OBJECT_NAME = s.TABLE_NAME
@@ -226,7 +371,7 @@ AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW', 'SEQUENCE', 'SYNONYM
'PROCEDURE', 'FUNCTION', 'PACKAGE', 'TYPE', 'JAVA CLASS')
WHERE s.OWNER = ? OR (s.OWNER = 'PUBLIC' AND s.TABLE_OWNER = ?)
ORDER BY s.OWNER, s.SYNONYM_NAME
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
Map synonyms = new LinkedHashMap<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -239,7 +384,7 @@ AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW', 'SEQUENCE', 'SYNONYM
String targetOwner = rs.getString("TABLE_OWNER");
String objectType = rs.getString("OBJECT_TYPE");
String key = owner + "\u0001" + name;
- // A materialized view is listed in ALL_OBJECTS twice — as MATERIALIZED VIEW
+ // A materialized view is listed in OBJECTS twice — as MATERIALIZED VIEW
// and as its container TABLE; keep the more specific one.
SynonymRecord existing = synonyms.get(key);
if (existing != null && !"MATERIALIZED VIEW".equals(objectType)) {
@@ -254,7 +399,7 @@ AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW', 'SEQUENCE', 'SYNONYM
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read synonyms from ALL_SYNONYMS: {}", e.getMessage());
+ LOGGER.debug("Could not read synonyms from {}: {}", view("SYNONYMS"), e.getMessage());
return List.of();
}
return List.copyOf(synonyms.values());
@@ -263,42 +408,39 @@ AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW', 'SEQUENCE', 'SYNONYM
@Override
public List getAllPartitions(Connection connection, String catalog, String schema) throws SQLException {
- // Oracle exposes partitioning via ALL_TAB_PARTITIONS / ALL_TAB_SUBPARTITIONS
- // plus
- // ALL_PART_TABLES (carrying the partitioning_type, sub-partitioning_type,
- // partition_count)
- // and ALL_PART_KEY_COLUMNS (the partition key columns).
- // We emit one Partition per ALL_TAB_PARTITIONS row plus one per
- // ALL_TAB_SUBPARTITIONS row.
- String partitionSql = """
+ // Oracle exposes partitioning via TAB_PARTITIONS / TAB_SUBPARTITIONS plus PART_TABLES
+ // (carrying the partitioning_type, sub-partitioning_type, partition_count) and
+ // PART_KEY_COLUMNS (the partition key columns). We emit one Partition per TAB_PARTITIONS
+ // row plus one per TAB_SUBPARTITIONS row.
+ String partitionSql = dictionary("""
SELECT atp.TABLE_NAME, atp.PARTITION_NAME, atp.PARTITION_POSITION,
atp.HIGH_VALUE, atp.NUM_ROWS,
apt.PARTITIONING_TYPE, apt.SUBPARTITIONING_TYPE,
(SELECT LISTAGG(akc.COLUMN_NAME, ',') WITHIN GROUP (ORDER BY akc.COLUMN_POSITION)
- FROM ALL_PART_KEY_COLUMNS akc
+ FROM {PART_KEY_COLUMNS} akc
WHERE akc.OWNER = atp.TABLE_OWNER AND akc.NAME = atp.TABLE_NAME) AS PART_KEY,
(SELECT LISTAGG(askc.COLUMN_NAME, ',') WITHIN GROUP (ORDER BY askc.COLUMN_POSITION)
- FROM ALL_SUBPART_KEY_COLUMNS askc
+ FROM {SUBPART_KEY_COLUMNS} askc
WHERE askc.OWNER = atp.TABLE_OWNER AND askc.NAME = atp.TABLE_NAME) AS SUBPART_KEY
- FROM ALL_TAB_PARTITIONS atp
- JOIN ALL_PART_TABLES apt
+ FROM {TAB_PARTITIONS} atp
+ JOIN {PART_TABLES} apt
ON apt.OWNER = atp.TABLE_OWNER AND apt.TABLE_NAME = atp.TABLE_NAME
WHERE atp.TABLE_OWNER = ?
ORDER BY atp.TABLE_NAME, atp.PARTITION_POSITION
- """;
- String subPartitionSql = """
+ """);
+ String subPartitionSql = dictionary("""
SELECT atsp.TABLE_NAME, atsp.PARTITION_NAME, atsp.SUBPARTITION_NAME,
atsp.SUBPARTITION_POSITION, atsp.HIGH_VALUE, atsp.NUM_ROWS,
apt.SUBPARTITIONING_TYPE,
(SELECT LISTAGG(askc.COLUMN_NAME, ',') WITHIN GROUP (ORDER BY askc.COLUMN_POSITION)
- FROM ALL_SUBPART_KEY_COLUMNS askc
+ FROM {SUBPART_KEY_COLUMNS} askc
WHERE askc.OWNER = atsp.TABLE_OWNER AND askc.NAME = atsp.TABLE_NAME) AS SUBPART_KEY
- FROM ALL_TAB_SUBPARTITIONS atsp
- JOIN ALL_PART_TABLES apt
+ FROM {TAB_SUBPARTITIONS} atsp
+ JOIN {PART_TABLES} apt
ON apt.OWNER = atsp.TABLE_OWNER AND apt.TABLE_NAME = atsp.TABLE_NAME
WHERE atsp.TABLE_OWNER = ?
ORDER BY atsp.TABLE_NAME, atsp.PARTITION_NAME, atsp.SUBPARTITION_POSITION
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
List partitions = new ArrayList<>();
Optional oSchema = Optional.of(new SchemaReference(Optional.empty(), schemaName));
@@ -394,13 +536,13 @@ public List getCheckConstraints(Connection connection, String c
@Override
public List getAllUniqueConstraints(Connection connection, String catalog, String schema)
throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, cc.COLUMN_NAME, cc.POSITION
- FROM ALL_CONSTRAINTS c
- JOIN ALL_CONS_COLUMNS cc ON c.OWNER = cc.OWNER AND c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
+ FROM {CONSTRAINTS} c
+ JOIN {CONS_COLUMNS} cc ON c.OWNER = cc.OWNER AND c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'U'
ORDER BY c.TABLE_NAME, c.CONSTRAINT_NAME, cc.POSITION
- """;
+ """);
return readUniqueConstraints(connection, sql, schema, null);
}
@@ -408,13 +550,13 @@ public List getAllUniqueConstraints(Connection connection, Str
@Override
public List getUniqueConstraints(Connection connection, String catalog, String schema,
String tableName) throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, cc.COLUMN_NAME, cc.POSITION
- FROM ALL_CONSTRAINTS c
- JOIN ALL_CONS_COLUMNS cc ON c.OWNER = cc.OWNER AND c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
+ FROM {CONSTRAINTS} c
+ JOIN {CONS_COLUMNS} cc ON c.OWNER = cc.OWNER AND c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'U' AND c.TABLE_NAME = ?
ORDER BY c.CONSTRAINT_NAME, cc.POSITION
- """;
+ """);
return readUniqueConstraints(connection, sql, schema, tableName);
}
@@ -422,13 +564,13 @@ public List getUniqueConstraints(Connection connection, String
@Override
public Optional> getAllPrimaryKeys(Connection connection, String catalog, String schema)
throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, cc.COLUMN_NAME, cc.POSITION
- FROM ALL_CONSTRAINTS c
- JOIN ALL_CONS_COLUMNS cc ON c.OWNER = cc.OWNER AND c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
+ FROM {CONSTRAINTS} c
+ JOIN {CONS_COLUMNS} cc ON c.OWNER = cc.OWNER AND c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'P'
ORDER BY c.TABLE_NAME, cc.POSITION
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
Map pkMap = new LinkedHashMap<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -456,19 +598,19 @@ public Optional> getAllPrimaryKeys(Connection connection, Strin
@Override
public Optional> getAllImportedKeys(Connection connection, String catalog, String schema)
throws SQLException {
- String sql = """
+ String sql = dictionary("""
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, 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
- JOIN ALL_CONS_COLUMNS pk_col ON pk.OWNER = pk_col.OWNER AND pk.CONSTRAINT_NAME = pk_col.CONSTRAINT_NAME
+ FROM {CONSTRAINTS} fk
+ JOIN {CONS_COLUMNS} fk_col ON fk.OWNER = fk_col.OWNER AND fk.CONSTRAINT_NAME = fk_col.CONSTRAINT_NAME
+ JOIN {CONSTRAINTS} pk ON fk.R_OWNER = pk.OWNER AND fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
+ JOIN {CONS_COLUMNS} pk_col ON pk.OWNER = pk_col.OWNER AND pk.CONSTRAINT_NAME = pk_col.CONSTRAINT_NAME
AND fk_col.POSITION = pk_col.POSITION
WHERE fk.OWNER = ? AND fk.CONSTRAINT_TYPE = 'R'
ORDER BY fk.TABLE_NAME, fk.CONSTRAINT_NAME, fk_col.POSITION
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
List importedKeys = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -488,19 +630,19 @@ public Optional> getAllExportedKeys(Connection connection, Str
throws SQLException {
// Symmetric to getAllImportedKeys: FK entries whose referenced (R_OWNER) side
// is the given schema.
- String sql = """
+ String sql = dictionary("""
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, 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
- JOIN ALL_CONS_COLUMNS pk_col ON pk.OWNER = pk_col.OWNER AND pk.CONSTRAINT_NAME = pk_col.CONSTRAINT_NAME
+ FROM {CONSTRAINTS} fk
+ JOIN {CONS_COLUMNS} fk_col ON fk.OWNER = fk_col.OWNER AND fk.CONSTRAINT_NAME = fk_col.CONSTRAINT_NAME
+ JOIN {CONSTRAINTS} pk ON fk.R_OWNER = pk.OWNER AND fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
+ JOIN {CONS_COLUMNS} pk_col ON pk.OWNER = pk_col.OWNER AND pk.CONSTRAINT_NAME = pk_col.CONSTRAINT_NAME
AND fk_col.POSITION = pk_col.POSITION
WHERE fk.R_OWNER = ? AND fk.CONSTRAINT_TYPE = 'R'
ORDER BY pk.TABLE_NAME, fk.CONSTRAINT_NAME, fk_col.POSITION
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
List exportedKeys = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -519,15 +661,15 @@ public Optional> getAllExportedKeys(Connection connection, Str
public Optional> getAllIndexInfo(Connection connection, String catalog, String schema)
throws SQLException {
// COLUMN_EXPRESSION is a LONG: it comes last and is read last
- String sql = """
+ String sql = dictionary("""
SELECT i.INDEX_NAME, i.INDEX_TYPE, i.TABLE_NAME, i.UNIQUENESS,
ic.COLUMN_NAME, ic.COLUMN_POSITION, ic.DESCEND, ie.COLUMN_EXPRESSION
- FROM ALL_INDEXES i
- JOIN ALL_IND_COLUMNS ic ON i.OWNER = ic.INDEX_OWNER AND i.INDEX_NAME = ic.INDEX_NAME
- LEFT JOIN ALL_IND_EXPRESSIONS ie ON ie.INDEX_OWNER = ic.INDEX_OWNER
+ FROM {INDEXES} i
+ JOIN {IND_COLUMNS} ic ON i.OWNER = ic.INDEX_OWNER AND i.INDEX_NAME = ic.INDEX_NAME
+ LEFT JOIN {IND_EXPRESSIONS} ie ON ie.INDEX_OWNER = ic.INDEX_OWNER
AND ie.INDEX_NAME = ic.INDEX_NAME AND ie.COLUMN_POSITION = ic.COLUMN_POSITION
WHERE i.TABLE_OWNER = ? ORDER BY i.TABLE_NAME, i.INDEX_NAME, ic.COLUMN_POSITION
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
Map> tableIndexes = new LinkedHashMap<>();
Map tableRefs = new LinkedHashMap<>();
@@ -600,9 +742,9 @@ public List getAllViewDefinitions(Connection connection, String
// Try TEXT_VC first (available in Oracle 12.2+)
try {
- String sql = """
- SELECT VIEW_NAME, TEXT_VC FROM ALL_VIEWS WHERE OWNER = ? ORDER BY VIEW_NAME
- """;
+ String sql = dictionary("""
+ SELECT VIEW_NAME, TEXT_VC FROM {VIEWS} WHERE OWNER = ? ORDER BY VIEW_NAME
+ """);
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
@@ -625,9 +767,9 @@ public List getAllViewDefinitions(Connection connection, String
// Fall back to TEXT column (LONG type, may have issues)
try {
- String sqlFallback = """
- SELECT VIEW_NAME, TEXT FROM ALL_VIEWS WHERE OWNER = ? ORDER BY VIEW_NAME
- """;
+ String sqlFallback = dictionary("""
+ SELECT VIEW_NAME, TEXT FROM {VIEWS} WHERE OWNER = ? ORDER BY VIEW_NAME
+ """);
try (PreparedStatement ps = connection.prepareStatement(sqlFallback)) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
@@ -650,7 +792,7 @@ public List getAllViewDefinitions(Connection connection, String
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read view definitions from ALL_VIEWS", e);
+ LOGGER.debug("Could not read view definitions from {}", view("VIEWS"), e);
}
return List.copyOf(views);
}
@@ -659,17 +801,17 @@ public List getAllViewDefinitions(Connection connection, String
@Override
public List getAllMaterializedViews(Connection connection, String catalog, String schema)
throws SQLException {
- // ALL_MVIEWS drives the list. Oracle also exposes REFRESH_MODE
+ // MVIEWS drives the list. Oracle also exposes REFRESH_MODE
// ('DEMAND','COMMIT','NEVER')
// and REFRESH_METHOD ('COMPLETE','FAST','FORCE','NEVER'); we report
// REFRESH_METHOD since
// that is what users normally think of when saying "refresh mode".
- String sql = """
+ String sql = dictionary("""
SELECT MVIEW_NAME, QUERY, REFRESH_METHOD, LAST_REFRESH_DATE
- FROM ALL_MVIEWS
+ FROM {MVIEWS}
WHERE OWNER = ?
ORDER BY MVIEW_NAME
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
List result = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -694,7 +836,7 @@ public List getAllMaterializedViews(Connection connection, Str
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read materialized views from ALL_MVIEWS: {}", e.getMessage());
+ LOGGER.debug("Could not read materialized views from {}: {}", view("MVIEWS"), e.getMessage());
return List.of();
}
return List.copyOf(result);
@@ -708,12 +850,12 @@ public List getAllProcedures(Connection connection, String catalog, S
Map sourceMap = loadOracleSources(connection, schemaName, "PROCEDURE");
Map lastDdlMap = loadOracleLastDdlTimes(connection, schemaName, "PROCEDURE");
- String sql = """
+ String sql = dictionary("""
SELECT OBJECT_NAME, PROCEDURE_NAME
- FROM ALL_PROCEDURES
+ FROM {PROCEDURES}
WHERE OWNER = ? AND OBJECT_TYPE = 'PROCEDURE'
ORDER BY OBJECT_NAME
- """;
+ """);
List procedures = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -744,12 +886,12 @@ public List getAllFunctions(Connection connection, String catalog, Str
Map sourceMap = loadOracleSources(connection, schemaName, "FUNCTION");
Map lastDdlMap = loadOracleLastDdlTimes(connection, schemaName, "FUNCTION");
- String sql = """
+ String sql = dictionary("""
SELECT OBJECT_NAME
- FROM ALL_PROCEDURES
+ FROM {PROCEDURES}
WHERE OWNER = ? AND OBJECT_TYPE = 'FUNCTION'
ORDER BY OBJECT_NAME
- """;
+ """);
List functions = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -774,14 +916,14 @@ public List getAllFunctions(Connection connection, String catalog, Str
private Map loadOracleLastDdlTimes(Connection connection, String schemaName, String objectType) {
- // ALL_OBJECTS.LAST_DDL_TIME is the canonical source for "when was this PL/SQL
+ // OBJECTS.LAST_DDL_TIME is the canonical source for "when was this PL/SQL
// object
// last changed"; a single bulk query covers the whole schema.
- String sql = """
+ String sql = dictionary("""
SELECT OBJECT_NAME, LAST_DDL_TIME
- FROM ALL_OBJECTS
+ FROM {OBJECTS}
WHERE OWNER = ? AND OBJECT_TYPE = ?
- """;
+ """);
Map result = new LinkedHashMap<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -796,7 +938,8 @@ private Map loadOracleLastDdlTimes(Connection connection, Strin
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read LAST_DDL_TIME for {} from ALL_OBJECTS: {}", objectType, e.getMessage());
+ LOGGER.debug("Could not read LAST_DDL_TIME for {} from {}: {}", objectType, view("OBJECTS"),
+ e.getMessage());
return Map.of();
}
return result;
@@ -804,13 +947,13 @@ private Map loadOracleLastDdlTimes(Connection connection, Strin
private Map loadOracleSources(Connection connection, String schemaName, String type) {
- // Aggregate source lines per object from ALL_SOURCE.
- String sql = """
+ // Aggregate source lines per object from SOURCE.
+ String sql = dictionary("""
SELECT NAME, TEXT
- FROM ALL_SOURCE
+ FROM {SOURCE}
WHERE OWNER = ? AND TYPE = ?
ORDER BY NAME, LINE
- """;
+ """);
Map byName = new LinkedHashMap<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -823,7 +966,7 @@ private Map loadOracleSources(Connection connection, String sche
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read ALL_SOURCE for type {}: {}", type, e.getMessage());
+ LOGGER.debug("Could not read {} for type {}: {}", view("SOURCE"), type, e.getMessage());
return Map.of();
}
Map result = new LinkedHashMap<>();
@@ -855,14 +998,14 @@ private Optional getMetadataDdl(Connection connection, String objectType
private Map> loadOracleProcedureColumns(Connection connection, String schemaName)
throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT a.OBJECT_NAME, a.ARGUMENT_NAME, a.IN_OUT, a.DATA_TYPE,
a.POSITION, a.DATA_PRECISION, a.DATA_SCALE
- FROM ALL_ARGUMENTS a
- JOIN ALL_PROCEDURES p ON a.OBJECT_ID = p.OBJECT_ID AND a.SUBPROGRAM_ID = p.SUBPROGRAM_ID
+ FROM {ARGUMENTS} a
+ JOIN {PROCEDURES} p ON a.OBJECT_ID = p.OBJECT_ID AND a.SUBPROGRAM_ID = p.SUBPROGRAM_ID
WHERE a.OWNER = ? AND p.OBJECT_TYPE = 'PROCEDURE' AND a.POSITION > 0
ORDER BY a.OBJECT_NAME, a.POSITION
- """;
+ """);
Map> result = new LinkedHashMap<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -897,14 +1040,14 @@ private Map> loadOracleProcedureColumns(Connection
private Map> loadOracleFunctionColumns(Connection connection, String schemaName)
throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT a.OBJECT_NAME, a.ARGUMENT_NAME, a.IN_OUT, a.DATA_TYPE,
a.POSITION, a.DATA_PRECISION, a.DATA_SCALE
- FROM ALL_ARGUMENTS a
- JOIN ALL_PROCEDURES p ON a.OBJECT_ID = p.OBJECT_ID AND a.SUBPROGRAM_ID = p.SUBPROGRAM_ID
+ FROM {ARGUMENTS} a
+ JOIN {PROCEDURES} p ON a.OBJECT_ID = p.OBJECT_ID AND a.SUBPROGRAM_ID = p.SUBPROGRAM_ID
WHERE a.OWNER = ? AND p.OBJECT_TYPE = 'FUNCTION'
ORDER BY a.OBJECT_NAME, a.POSITION
- """;
+ """);
Map> result = new LinkedHashMap<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -1050,7 +1193,7 @@ private ImportedKey readImportedKey(ResultSet rs) throws SQLException {
}
/**
- * When a key is checked, from {@code ALL_CONSTRAINTS.DEFERRABLE} ({@code DEFERRABLE} or
+ * When a key is checked, from {@code CONSTRAINTS.DEFERRABLE} ({@code DEFERRABLE} or
* {@code NOT DEFERRABLE}) and {@code DEFERRED} ({@code DEFERRED} or {@code IMMEDIATE}).
*/
static ImportedKey.Deferrability deferrability(String deferrable, String deferred) {
@@ -1087,19 +1230,19 @@ private List readCheckConstraintsWithVc(Connection connection,
throws SQLException {
String sql;
if (tableName != null) {
- sql = """
+ sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, c.SEARCH_CONDITION_VC
- FROM ALL_CONSTRAINTS c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
+ FROM {CONSTRAINTS} c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
AND NOT REGEXP_LIKE(c.SEARCH_CONDITION_VC, '%s') AND c.TABLE_NAME = ?
ORDER BY c.CONSTRAINT_NAME
- """.formatted(NOT_NULL_CONDITION);
+ """).formatted(NOT_NULL_CONDITION);
} else {
- sql = """
+ sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, c.SEARCH_CONDITION_VC
- FROM ALL_CONSTRAINTS c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
+ FROM {CONSTRAINTS} c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
AND NOT REGEXP_LIKE(c.SEARCH_CONDITION_VC, '%s')
ORDER BY c.TABLE_NAME, c.CONSTRAINT_NAME
- """.formatted(NOT_NULL_CONDITION);
+ """).formatted(NOT_NULL_CONDITION);
}
List constraints = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -1129,18 +1272,18 @@ private List readCheckConstraintsWithLong(Connection connection
String tableName) throws SQLException {
String sql;
if (tableName != null) {
- sql = """
+ sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, c.SEARCH_CONDITION
- FROM ALL_CONSTRAINTS c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
+ FROM {CONSTRAINTS} c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
AND c.TABLE_NAME = ?
ORDER BY c.CONSTRAINT_NAME
- """;
+ """);
} else {
- sql = """
+ sql = dictionary("""
SELECT c.CONSTRAINT_NAME, c.TABLE_NAME, c.SEARCH_CONDITION
- FROM ALL_CONSTRAINTS c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
+ FROM {CONSTRAINTS} c WHERE c.OWNER = ? AND c.CONSTRAINT_TYPE = 'C'
ORDER BY c.TABLE_NAME, c.CONSTRAINT_NAME
- """;
+ """);
}
List constraints = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -1308,12 +1451,12 @@ private static IndexInfoItem.IndexType mapOracleIndexType(String indexType) {
public List getAllUserDefinedTypes(Connection connection, String catalog, String schema)
throws SQLException {
String schemaName = resolveSchema(schema, connection);
- String sql = """
+ String sql = dictionary("""
SELECT TYPE_NAME, TYPECODE, SUPERTYPE_NAME
- FROM ALL_TYPES
+ FROM {TYPES}
WHERE OWNER = ?
ORDER BY TYPE_NAME
- """;
+ """);
List types = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, schemaName);
@@ -1350,26 +1493,24 @@ private static JDBCType mapOracleUdtBaseType(String typeCode) {
@Override
public Optional> getAllTablePrivileges(Connection connection, String catalog,
String schemaPattern, String tableNamePattern) throws SQLException {
- // ALL_TAB_PRIVS sees grants regardless of the current user — PUBLIC, role
- // grants,
- // and grants made by others are all returned. JDBC's getTablePrivileges only
- // returns direct grants to the connected user.
- // ALL_TAB_PRIVS covers every object type — scope to table-like objects;
- // everything else is reported via getAllObjectPrivileges.
- StringBuilder sql = new StringBuilder("""
- SELECT TABLE_SCHEMA, TABLE_NAME, GRANTOR, GRANTEE, PRIVILEGE, GRANTABLE
- FROM ALL_TAB_PRIVS t
- WHERE TABLE_SCHEMA = ?
- AND EXISTS (SELECT 1 FROM ALL_OBJECTS o WHERE o.OWNER = t.TABLE_SCHEMA
+ // DBA_TAB_PRIVS holds every grant of the database; ALL_TAB_PRIVS those the user may see: on
+ // its own objects, by it or to it, to PUBLIC or to a role it holds. JDBC's getTablePrivileges
+ // only returns direct grants to the connected user. The view covers every object type —
+ // scope to table-like objects; everything else is reported via getAllObjectPrivileges.
+ StringBuilder sql = new StringBuilder(dictionary("""
+ SELECT t.TABLE_NAME, t.GRANTOR, t.GRANTEE, t.PRIVILEGE, t.GRANTABLE
+ FROM {TAB_PRIVS} t
+ WHERE t.{PRIVS_OWNER} = ?
+ AND EXISTS (SELECT 1 FROM {OBJECTS} o WHERE o.OWNER = t.{PRIVS_OWNER}
AND o.OBJECT_NAME = t.TABLE_NAME
AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW'))
- """);
+ """));
boolean hasTableFilter = tableNamePattern != null && !tableNamePattern.isBlank()
&& !"%".equals(tableNamePattern);
if (hasTableFilter) {
- sql.append(" AND TABLE_NAME LIKE ?\n");
+ sql.append(" AND t.TABLE_NAME LIKE ?\n");
}
- sql.append("ORDER BY TABLE_NAME, PRIVILEGE, GRANTEE");
+ sql.append("ORDER BY t.TABLE_NAME, t.PRIVILEGE, t.GRANTEE");
String schemaName = resolveSchema(schemaPattern, connection);
List result = new ArrayList<>();
@@ -1394,7 +1535,7 @@ AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW'))
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read table privileges from ALL_TAB_PRIVS: {}", e.getMessage());
+ LOGGER.debug("Could not read table privileges from {}: {}", view("TAB_PRIVS"), e.getMessage());
return Optional.empty();
}
return Optional.of(List.copyOf(result));
@@ -1404,18 +1545,18 @@ AND o.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW'))
@Override
public Optional> getAllObjectPrivileges(
Connection connection, String catalog, String schema) throws SQLException {
- // Non-table objects from ALL_TAB_PRIVS: procedures, functions, packages,
- // sequences, types, directories, ... (bodies excluded).
- String sql = """
+ // Non-table objects from TAB_PRIVS: procedures, functions, packages, sequences, types,
+ // directories, ... (bodies excluded).
+ String sql = dictionary("""
SELECT DISTINCT t.TABLE_NAME AS OBJECT_NAME, o.OBJECT_TYPE, t.GRANTOR, t.GRANTEE,
t.PRIVILEGE, t.GRANTABLE
- FROM ALL_TAB_PRIVS t
- JOIN ALL_OBJECTS o ON o.OWNER = t.TABLE_SCHEMA AND o.OBJECT_NAME = t.TABLE_NAME
- WHERE t.TABLE_SCHEMA = ?
+ FROM {TAB_PRIVS} t
+ JOIN {OBJECTS} o ON o.OWNER = t.{PRIVS_OWNER} AND o.OBJECT_NAME = t.TABLE_NAME
+ WHERE t.{PRIVS_OWNER} = ?
AND o.OBJECT_TYPE NOT IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
AND o.OBJECT_TYPE NOT LIKE '%BODY'
ORDER BY o.OBJECT_TYPE, OBJECT_NAME, t.PRIVILEGE, t.GRANTEE
- """;
+ """);
String schemaName = resolveSchema(schema, connection);
List result = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -1437,12 +1578,12 @@ AND o.OBJECT_TYPE NOT IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
@Override
public Optional> getColumnPrivileges(Connection connection, String catalog, String schema,
String tableName, String columnNamePattern) throws SQLException {
- // ALL_COL_PRIVS is the column-level equivalent of ALL_TAB_PRIVS.
- StringBuilder sql = new StringBuilder("""
- SELECT OWNER, TABLE_NAME, COLUMN_NAME, GRANTOR, GRANTEE, PRIVILEGE, GRANTABLE
- FROM ALL_COL_PRIVS
- WHERE OWNER = ? AND TABLE_NAME = ?
- """);
+ // COL_PRIVS is the column-level equivalent of TAB_PRIVS.
+ StringBuilder sql = new StringBuilder(dictionary("""
+ SELECT TABLE_NAME, COLUMN_NAME, GRANTOR, GRANTEE, PRIVILEGE, GRANTABLE
+ FROM {COL_PRIVS}
+ WHERE {PRIVS_OWNER} = ? AND TABLE_NAME = ?
+ """));
boolean hasColumnFilter = columnNamePattern != null && !columnNamePattern.isBlank()
&& !"%".equals(columnNamePattern);
if (hasColumnFilter) {
@@ -1475,7 +1616,7 @@ public Optional> getColumnPrivileges(Connection connection
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read column privileges from ALL_COL_PRIVS: {}", e.getMessage());
+ LOGGER.debug("Could not read column privileges from {}: {}", view("COL_PRIVS"), e.getMessage());
return Optional.empty();
}
return Optional.of(List.copyOf(result));
@@ -1486,15 +1627,15 @@ public Optional> getColumnPrivileges(Connection connection
public Optional> getAllPseudoColumns(Connection connection, String catalog, String schemaPattern,
String tableNamePattern, String columnNamePattern) throws SQLException {
// Oracle's JDBC driver returns an empty pseudo-column set for most objects.
- // ALL_TAB_COLS with HIDDEN_COLUMN='YES' surfaces Oracle-specific pseudo columns
+ // TAB_COLS with HIDDEN_COLUMN='YES' surfaces Oracle-specific pseudo columns
// (ROWID of index-organized tables, virtual columns, system-generated identity
// tracking columns, etc.) that never show up via getPseudoColumns.
- StringBuilder sql = new StringBuilder("""
+ StringBuilder sql = new StringBuilder(dictionary("""
SELECT c.OWNER, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.DATA_LENGTH,
c.DATA_PRECISION, c.DATA_SCALE, c.NULLABLE
- FROM ALL_TAB_COLS c
+ FROM {TAB_COLS} c
WHERE c.HIDDEN_COLUMN = 'YES' AND c.OWNER = ?
- """);
+ """));
boolean hasTableFilter = tableNamePattern != null && !tableNamePattern.isBlank()
&& !"%".equals(tableNamePattern);
if (hasTableFilter) {
@@ -1547,7 +1688,7 @@ public Optional> getAllPseudoColumns(Connection connection, S
}
}
} catch (SQLException e) {
- LOGGER.debug("Could not read pseudo columns from ALL_TAB_COLS: {}", e.getMessage());
+ LOGGER.debug("Could not read pseudo columns from {}: {}", view("TAB_COLS"), e.getMessage());
return Optional.empty();
}
return Optional.of(List.copyOf(result));
@@ -1612,7 +1753,7 @@ UniqueConstraint build() {
private static final Set TEXT_TYPES = Set.of("CHAR", "NCHAR", "VARCHAR", "VARCHAR2", "NVARCHAR2");
/**
- * The columns of a schema from {@code ALL_TAB_COLS}. A text column has its length in characters, as
+ * The columns of a schema from {@code TAB_COLS}. A text column has its length in characters, as
* Oracle's JDBC driver reports it: {@code DATA_LENGTH} counts bytes, four for each character of a
* {@code VARCHAR2 (n CHAR)} in AL32UTF8.
*/
@@ -1620,15 +1761,15 @@ UniqueConstraint build() {
public Optional> getAllColumnDefinitions(
Connection connection, String catalog, String schemaPattern, String tableNamePattern,
String columnNamePattern) throws SQLException {
- String sql = """
+ String sql = dictionary("""
SELECT t.OWNER, t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.DATA_LENGTH, t.CHAR_LENGTH,
t.DATA_PRECISION, t.DATA_SCALE, t.NULLABLE, t.DATA_DEFAULT, t.COLUMN_ID, c.COMMENTS
- FROM ALL_TAB_COLS t
- LEFT JOIN ALL_COL_COMMENTS c
+ FROM {TAB_COLS} t
+ LEFT JOIN {COL_COMMENTS} c
ON c.OWNER = t.OWNER AND c.TABLE_NAME = t.TABLE_NAME AND c.COLUMN_NAME = t.COLUMN_NAME
WHERE t.OWNER = ? AND t.HIDDEN_COLUMN = 'NO'
ORDER BY t.OWNER, t.TABLE_NAME, t.COLUMN_ID
- """;
+ """);
String schemaName = resolveSchema(schemaPattern, connection);
List out = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
@@ -1717,15 +1858,18 @@ private static boolean isNumericJdbc(java.sql.JDBCType t) {
@Override
public Optional> getAllRoleMemberships(Connection connection)
throws SQLException {
- // With plain read rights: the user's own memberships (USER_ROLE_PRIVS, those of PUBLIC among
- // them) and those of the roles it holds, directly or through other roles (ROLE_ROLE_PRIVS).
+ // USER: the user's own memberships (USER_ROLE_PRIVS, those of PUBLIC among them) and those of
+ // the roles it holds, directly or through other roles (ROLE_ROLE_PRIVS); who else holds a
+ // role, the user does not see, even of a role it created.
+ String sql = scope == MetadataScope.DATABASE
+ ? "SELECT GRANTEE, GRANTED_ROLE, ADMIN_OPTION FROM DBA_ROLE_PRIVS ORDER BY 1, 2"
+ : """
+ SELECT USERNAME AS GRANTEE, GRANTED_ROLE, ADMIN_OPTION FROM USER_ROLE_PRIVS
+ UNION
+ SELECT ROLE AS GRANTEE, GRANTED_ROLE, ADMIN_OPTION FROM ROLE_ROLE_PRIVS
+ ORDER BY 1, 2""";
List result = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement("""
- SELECT USERNAME AS GRANTEE, GRANTED_ROLE, ADMIN_OPTION FROM USER_ROLE_PRIVS
- UNION
- SELECT ROLE AS GRANTEE, GRANTED_ROLE, ADMIN_OPTION FROM ROLE_ROLE_PRIVS
- ORDER BY 1, 2""");
- ResultSet rs = ps.executeQuery()) {
+ try (PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(new org.eclipse.daanse.sql.jdbc.record.schema.RoleMembershipRecord(
rs.getString("GRANTEE"), rs.getString("GRANTED_ROLE"),
@@ -1738,14 +1882,11 @@ public Optional> get
@Override
public Optional> getAllPrincipals(Connection connection)
throws SQLException {
- // With plain read rights: ALL_USERS names every user to every user; the roles are those the
- // user holds, directly or through other roles.
List result = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(
- "SELECT USERNAME FROM ALL_USERS ORDER BY USERNAME");
- ResultSet rs = ps.executeQuery()) {
- while (rs.next()) {
- result.add(new org.eclipse.daanse.sql.jdbc.record.schema.DatabasePrincipalRecord(rs.getString("USERNAME"), org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal.KIND_USER));
+ try {
+ for (String user : userNames(connection)) {
+ result.add(new org.eclipse.daanse.sql.jdbc.record.schema.DatabasePrincipalRecord(user,
+ org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal.KIND_USER));
}
} catch (SQLException e) {
return Optional.empty();
@@ -1758,19 +1899,20 @@ public Optional>
}
/**
- * The roles the current user holds: granted to it or to PUBLIC (USER_ROLE_PRIVS), and those
- * granted to these roles in turn (ROLE_ROLE_PRIVS, which shows the roles the user has access to).
+ * In {@link MetadataScope#USER} the roles the current user holds: granted to it or to PUBLIC
+ * ({@code USER_ROLE_PRIVS}), and those granted to these roles in turn ({@code ROLE_ROLE_PRIVS},
+ * which shows the roles the user has access to).
*/
- private static List roleNames(Connection connection) throws SQLException {
- List roles = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement("""
+ private List roleNames(Connection connection) throws SQLException {
+ String sql = scope == MetadataScope.DATABASE ? "SELECT ROLE FROM DBA_ROLES ORDER BY 1" : """
SELECT GRANTED_ROLE AS ROLE FROM USER_ROLE_PRIVS
UNION
SELECT ROLE FROM ROLE_ROLE_PRIVS
UNION
SELECT GRANTED_ROLE AS ROLE FROM ROLE_ROLE_PRIVS
- ORDER BY 1""");
- ResultSet rs = ps.executeQuery()) {
+ ORDER BY 1""";
+ List roles = new ArrayList<>();
+ try (PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
roles.add(rs.getString("ROLE"));
}
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 50bbd0bc..02e53be7 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
@@ -19,16 +19,25 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo;
import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfoItem;
import org.eclipse.daanse.sql.jdbc.api.schema.CheckConstraint;
import org.eclipse.daanse.sql.jdbc.api.schema.ColumnPrivilege;
+import org.eclipse.daanse.sql.model.schema.CatalogReference;
+import org.eclipse.daanse.sql.model.schema.ColumnDefinition;
import org.eclipse.daanse.sql.model.schema.ColumnReference;
import org.eclipse.daanse.sql.jdbc.api.schema.Function;
import org.eclipse.daanse.sql.jdbc.api.schema.FunctionColumn;
@@ -44,6 +53,7 @@
import org.eclipse.daanse.sql.model.schema.SchemaReference;
import org.eclipse.daanse.sql.jdbc.api.schema.Sequence;
import org.eclipse.daanse.sql.jdbc.api.schema.SequenceReference;
+import org.eclipse.daanse.sql.jdbc.api.schema.TableDefinition;
import org.eclipse.daanse.sql.jdbc.api.schema.TablePrivilege;
import org.eclipse.daanse.sql.model.schema.TableReference;
import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent;
@@ -74,12 +84,194 @@
import org.eclipse.daanse.sql.jdbc.record.schema.ViewDefinitionRecord;
/**
- * The PostgreSql system-catalog/{@code information_schema} reader — the
- * {@link MetadataProvider} overrides extracted 1:1 from the SQL dialect (reading only,
- * no spelling).
+ * The PostgreSql system-catalog reader — the {@link MetadataProvider} overrides extracted 1:1
+ * from the SQL dialect (reading only, no spelling).
+ *
+ * The system catalog shows every schema, relation, routine, role and access control list to every
+ * user, so every connection may read in {@link MetadataScope#DATABASE}: the whole database, the
+ * grants from the access control lists ({@code relacl}, {@code attacl}, {@code proacl}), the
+ * memberships from {@code pg_auth_members}. {@link MetadataScope#USER} reads the same catalog with
+ * the conditions {@code information_schema} applies: a schema the user may use ({@code USAGE}); in
+ * it a relation the user owns, through a role or itself, or holds a right on, a routine it owns or
+ * may execute, a sequence it owns or holds a right on, a type it may use; keys, constraints,
+ * indexes, triggers and partitions of these relations only, a foreign key only where both its
+ * tables are visible. The grants that concern the user, granted to or by a role it has or to
+ * {@code PUBLIC}; the memberships of the user and of the roles it has; these roles and the user.
+ * Routines may be executed by {@code PUBLIC} unless revoked, so every routine of a schema the user
+ * may use is visible.
+ *
+ * Where a relation has no access control list, it has the default one: only its owner holds a right
+ * on it, and no grant is read.
*/
public class PostgreSqlMetadataProvider implements MetadataProvider {
+ /**
+ * A condition of the scope in a query: {@code {VISIBLE_RELATION c n}} names the aliases of
+ * {@code pg_class} and {@code pg_namespace}.
+ */
+ private static final Pattern CONDITION = Pattern.compile("\\{([A-Z_]+)((?: [a-z_.]+)+)\\}");
+
+ /** The rights on a relation that make it visible, as {@code information_schema.tables} has them. */
+ private static final String RELATION_RIGHTS = "SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER";
+
+ /** The rights on a column that make its relation visible. */
+ private static final String COLUMN_RIGHTS = "SELECT, INSERT, UPDATE, REFERENCES";
+
+ private final MetadataScope scope;
+
+ public PostgreSqlMetadataProvider() {
+ this(MetadataScope.DATABASE);
+ }
+
+ public PostgreSqlMetadataProvider(MetadataScope scope) {
+ this.scope = Objects.requireNonNull(scope, "scope");
+ }
+
+ @Override
+ public MetadataProvider withScope(MetadataScope other) {
+ return other == scope ? this : new PostgreSqlMetadataProvider(other);
+ }
+
+ @Override
+ public MetadataScope scope() {
+ return scope;
+ }
+
+ /**
+ * {@code sql} with each condition of the scope written out: in {@link MetadataScope#DATABASE}
+ * {@code TRUE}, in {@link MetadataScope#USER} what makes the object visible to the user.
+ */
+ private String scoped(String sql) {
+ return CONDITION.matcher(sql).replaceAll(token -> Matcher
+ .quoteReplacement(condition(token.group(1), token.group(2).trim().split(" "))));
+ }
+
+ private String condition(String name, String[] alias) {
+ if (scope == MetadataScope.DATABASE) {
+ return "TRUE";
+ }
+ return switch (name) {
+ case "VISIBLE_SCHEMA" -> usable(alias[0]);
+ case "VISIBLE_RELATION" -> "(" + usable(alias[1]) + " AND " + relationGranted(alias[0]) + ")";
+ case "VISIBLE_ROUTINE" -> "(" + usable(alias[1]) + " AND (pg_has_role(" + alias[0]
+ + ".proowner, 'USAGE') OR has_function_privilege(" + alias[0] + ".oid, 'EXECUTE')))";
+ case "VISIBLE_SEQUENCE" -> "(" + usable(alias[1]) + " AND " + sequenceGranted(alias[0]) + ")";
+ case "VISIBLE_TYPE" -> "(" + usable(alias[1]) + " AND has_type_privilege(" + alias[0]
+ + ".oid, 'USAGE'))";
+ // A grant concerns the user where it is granted to PUBLIC, or to or by a role the user has.
+ case "CONCERNS_USER" -> "(CASE WHEN " + alias[0] + ".grantee = 0 THEN TRUE ELSE pg_has_role(" + alias[0]
+ + ".grantee, 'USAGE') END OR pg_has_role(" + alias[0] + ".grantor, 'USAGE'))";
+ case "HELD_ROLE" -> "pg_has_role(" + alias[0] + ", 'USAGE')";
+ default -> throw new IllegalArgumentException(name);
+ };
+ }
+
+ private static String usable(String namespace) {
+ return "has_schema_privilege(" + namespace + ".oid, 'USAGE')";
+ }
+
+ private static String relationGranted(String relation) {
+ return "(pg_has_role(" + relation + ".relowner, 'USAGE') OR has_table_privilege(" + relation + ".oid, '"
+ + RELATION_RIGHTS + "') OR has_any_column_privilege(" + relation + ".oid, '" + COLUMN_RIGHTS
+ + "'))";
+ }
+
+ /**
+ * A sequence the user owns or holds a right on. {@code has_sequence_privilege} fails on any other
+ * relation, and the planner may test the condition before a join narrows the rows to sequences.
+ */
+ private static String sequenceGranted(String sequence) {
+ return "(pg_has_role(" + sequence + ".relowner, 'USAGE') OR CASE WHEN " + sequence
+ + ".relkind = 'S' THEN has_sequence_privilege(" + sequence
+ + ".oid, 'SELECT, UPDATE, USAGE') ELSE FALSE END)";
+ }
+
+ @Override
+ public Optional> getAllSchemas(Connection connection, String catalog)
+ throws SQLException {
+ // As the JDBC driver lists them: without the schemas of the temporary objects of other sessions.
+ String sql = scoped("""
+ SELECT n.nspname, current_database() AS catalog_name
+ FROM pg_namespace n
+ WHERE n.nspname <> 'pg_toast'
+ AND (n.nspname !~ '^pg_temp_' OR n.nspname = (pg_catalog.current_schemas(true))[1])
+ AND (n.nspname !~ '^pg_toast_temp_'
+ OR n.nspname = replace((pg_catalog.current_schemas(true))[1], 'pg_temp_', 'pg_toast_temp_'))
+ AND {VISIBLE_SCHEMA n}
+ ORDER BY n.nspname
+ """);
+ List schemas = new ArrayList<>();
+ try (PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery()) {
+ while (rs.next()) {
+ schemas.add(new SchemaReference(Optional.of(new CatalogReference(rs.getString("catalog_name"))),
+ rs.getString("nspname")));
+ }
+ }
+ return Optional.of(List.copyOf(schemas));
+ }
+
+ @Override
+ public Optional> getAllTableDefinitions(Connection connection, String catalog,
+ String schemaPattern, String tableNamePattern, String[] types) throws SQLException {
+ // The driver reads the system catalog, which shows every relation: USER keeps those the user
+ // may see.
+ if (scope == MetadataScope.DATABASE) {
+ return Optional.empty();
+ }
+ Set visible = visibleRelations(connection, schemaPattern);
+ return Optional.of(DriverMetadata
+ .tables(connection, catalog, schemaPattern, tableNamePattern, types, (s, t, c) -> null).stream()
+ .filter(table -> visible.contains(key(table.table()))).toList());
+ }
+
+ @Override
+ public Optional> getAllColumnDefinitions(Connection connection, String catalog,
+ String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException {
+ if (scope == MetadataScope.DATABASE) {
+ return Optional.empty();
+ }
+ Set visible = visibleRelations(connection, schemaPattern);
+ return Optional.of(DriverMetadata
+ .columns(connection, catalog, schemaPattern, tableNamePattern, columnNamePattern, (s, t, c) -> null)
+ .stream().filter(column -> column.column().table().map(t -> visible.contains(key(t))).orElse(false))
+ .toList());
+ }
+
+ /**
+ * The relations the user may see: a table, view, materialized view or foreign table it owns or
+ * holds a right on, an index of such a table, a sequence it owns or holds a right on, a composite
+ * type it may use.
+ */
+ private static Set visibleRelations(Connection connection, String schemaPattern) throws SQLException {
+ String sql = """
+ SELECT n.nspname, c.relname
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ LEFT JOIN pg_index ix ON ix.indexrelid = c.oid
+ LEFT JOIN pg_class t ON t.oid = ix.indrelid
+ WHERE n.nspname LIKE ? AND %s AND CASE
+ WHEN c.relkind IN ('i', 'I') THEN %s
+ WHEN c.relkind = 'S' THEN %s
+ WHEN c.relkind = 'c' THEN has_type_privilege(c.reltype, 'USAGE')
+ ELSE %s
+ END
+ """.formatted(usable("n"), relationGranted("t"), sequenceGranted("c"), relationGranted("c"));
+ Set visible = new HashSet<>();
+ try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ ps.setString(1, schemaPattern == null ? "%" : schemaPattern);
+ try (ResultSet rs = ps.executeQuery()) {
+ while (rs.next()) {
+ visible.add(rs.getString("nspname") + "\u0001" + rs.getString("relname"));
+ }
+ }
+ }
+ return visible;
+ }
+
+ private static String key(TableReference table) {
+ return table.schema().map(SchemaReference::name).orElse("") + "\u0001" + table.name();
+ }
+
@Override
public List getAllTriggers(Connection connection, String catalog, String schema) throws SQLException {
@@ -92,12 +284,12 @@ public List getAllTriggers(Connection connection, String catalog, Strin
JOIN pg_class c ON c.oid = t.tgrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_proc p ON p.oid = t.tgfoid
- WHERE NOT t.tgisinternal AND n.nspname = ?
+ WHERE NOT t.tgisinternal AND n.nspname = ? AND {VISIBLE_RELATION c n}
ORDER BY c.relname, t.tgname
""";
String schemaName = resolveSchema(schema, connection);
List triggers = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -121,12 +313,12 @@ public List getTriggers(Connection connection, String catalog, String s
JOIN pg_class c ON c.oid = t.tgrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_proc p ON p.oid = t.tgfoid
- WHERE NOT t.tgisinternal AND n.nspname = ? AND c.relname = ?
+ WHERE NOT t.tgisinternal AND n.nspname = ? AND c.relname = ? AND {VISIBLE_RELATION c n}
ORDER BY t.tgname
""";
String schemaName = resolveSchema(schema, connection);
List triggers = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
ps.setString(2, tableName);
try (ResultSet rs = ps.executeQuery()) {
@@ -141,16 +333,22 @@ public List getTriggers(Connection connection, String catalog, String s
@Override
public List getAllSequences(Connection connection, String catalog, String schema) throws SQLException {
+ // pg_sequence, not information_schema.sequences, which shows only the sequences the reader
+ // owns or holds a right on.
String sql = """
- SELECT sequence_name, start_value, increment, minimum_value, maximum_value,
- cycle_option, data_type
- FROM information_schema.sequences
- WHERE sequence_schema = ?
- ORDER BY sequence_name
+ SELECT c.relname AS sequence_name, s.seqstart AS start_value, s.seqincrement AS increment,
+ s.seqmin AS minimum_value, s.seqmax AS maximum_value,
+ CASE WHEN s.seqcycle THEN 'YES' ELSE 'NO' END AS cycle_option,
+ format_type(s.seqtypid, NULL) AS data_type
+ FROM pg_sequence s
+ JOIN pg_class c ON c.oid = s.seqrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = ? AND {VISIBLE_SEQUENCE c n}
+ ORDER BY c.relname
""";
String schemaName = resolveSchema(schema, connection);
List sequences = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -198,13 +396,13 @@ public List getAllPartitions(Connection connection, String catalog, S
JOIN pg_class p ON p.oid = i.inhparent
JOIN pg_partitioned_table pt ON pt.partrelid = p.oid
JOIN pg_namespace np ON np.oid = p.relnamespace
- WHERE np.nspname = ?
+ WHERE np.nspname = ? AND {VISIBLE_RELATION p np}
ORDER BY p.relname, c.relname
""";
String schemaName = resolveSchema(schema, connection);
List partitions = new ArrayList<>();
Optional oSchema = Optional.of(new SchemaReference(Optional.empty(), schemaName));
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -271,12 +469,12 @@ SELECT con.conname, c.relname, pg_get_constraintdef(con.oid) AS check_clause
FROM pg_constraint con
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE con.contype = 'c' AND n.nspname = ?
+ WHERE con.contype = 'c' AND n.nspname = ? AND {VISIBLE_RELATION c n}
ORDER BY c.relname, con.conname
""";
String schemaName = resolveSchema(schema, connection);
List constraints = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -303,12 +501,12 @@ SELECT con.conname, c.relname, pg_get_constraintdef(con.oid) AS check_clause
FROM pg_constraint con
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE con.contype = 'c' AND n.nspname = ? AND c.relname = ?
+ WHERE con.contype = 'c' AND n.nspname = ? AND c.relname = ? AND {VISIBLE_RELATION c n}
ORDER BY con.conname
""";
String schemaName = resolveSchema(schema, connection);
List constraints = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
ps.setString(2, tableName);
try (ResultSet rs = ps.executeQuery()) {
@@ -336,7 +534,7 @@ SELECT con.conname, c.relname, a.attname, array_position(con.conkey, a.attnum) A
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = ANY(con.conkey)
- WHERE con.contype = 'u' AND n.nspname = ?
+ WHERE con.contype = 'u' AND n.nspname = ? AND {VISIBLE_RELATION c n}
ORDER BY c.relname, con.conname, ordinal
""";
return readUniqueConstraints(connection, sql, schema, null);
@@ -352,7 +550,7 @@ SELECT con.conname, c.relname, a.attname, array_position(con.conkey, a.attnum) A
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = ANY(con.conkey)
- WHERE con.contype = 'u' AND n.nspname = ? AND c.relname = ?
+ WHERE con.contype = 'u' AND n.nspname = ? AND c.relname = ? AND {VISIBLE_RELATION c n}
ORDER BY con.conname, ordinal
""";
return readUniqueConstraints(connection, sql, schema, tableName);
@@ -368,12 +566,12 @@ SELECT con.conname, c.relname, a.attname, array_position(con.conkey, a.attnum) A
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = ANY(con.conkey)
- WHERE con.contype = 'p' AND n.nspname = ?
+ WHERE con.contype = 'p' AND n.nspname = ? AND {VISIBLE_RELATION c n}
ORDER BY c.relname, ordinal
""";
String schemaName = resolveSchema(schema, connection);
Map pkMap = new LinkedHashMap<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -413,11 +611,12 @@ JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(fk_attnum,
JOIN pg_attribute fk_att ON fk_att.attrelid = con.conrelid AND fk_att.attnum = cols.fk_attnum
JOIN pg_attribute pk_att ON pk_att.attrelid = con.confrelid AND pk_att.attnum = cols.pk_attnum
WHERE con.contype = 'f' AND fk_n.nspname = ?
+ AND {VISIBLE_RELATION fk_class fk_n} AND {VISIBLE_RELATION pk_class pk_n}
ORDER BY fk_class.relname, con.conname, cols.ord
""";
String schemaName = resolveSchema(schema, connection);
List importedKeys = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -449,11 +648,12 @@ JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(fk_attnum,
JOIN pg_attribute fk_att ON fk_att.attrelid = con.conrelid AND fk_att.attnum = cols.fk_attnum
JOIN pg_attribute pk_att ON pk_att.attrelid = con.confrelid AND pk_att.attnum = cols.pk_attnum
WHERE con.contype = 'f' AND pk_n.nspname = ?
+ AND {VISIBLE_RELATION fk_class fk_n} AND {VISIBLE_RELATION pk_class pk_n}
ORDER BY pk_class.relname, con.conname, cols.ord
""";
String schemaName = resolveSchema(schema, connection);
List exportedKeys = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -481,13 +681,13 @@ a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ordinal,
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_am am ON am.oid = i_class.relam
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(ix.indkey)
- WHERE n.nspname = ? AND NOT ix.indisprimary
+ WHERE n.nspname = ? AND NOT ix.indisprimary AND {VISIBLE_RELATION c n}
ORDER BY c.relname, i_class.relname, ordinal
""";
String schemaName = resolveSchema(schema, connection);
Map> tableIndexes = new LinkedHashMap<>();
Map tableRefs = new LinkedHashMap<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -548,12 +748,12 @@ public List getAllViewDefinitions(Connection connection, String
SELECT c.relname, pg_get_viewdef(c.oid, true) AS view_body
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE c.relkind = 'v' AND n.nspname = ?
+ WHERE c.relkind = 'v' AND n.nspname = ? AND {VISIBLE_RELATION c n}
ORDER BY c.relname
""";
String schemaName = resolveSchema(schema, connection);
List views = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -582,12 +782,12 @@ public List getAllMaterializedViews(Connection connection, Str
SELECT c.relname, pg_get_viewdef(c.oid, true) AS view_body
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE c.relkind = 'm' AND n.nspname = ?
+ WHERE c.relkind = 'm' AND n.nspname = ? AND {VISIBLE_RELATION c n}
ORDER BY c.relname
""";
String schemaName = resolveSchema(schema, connection);
List mviews = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -621,12 +821,12 @@ public List getAllProcedures(Connection connection, String catalog, S
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'
+ WHERE n.nspname = ? AND p.prokind = 'p' AND {VISIBLE_ROUTINE p n}
ORDER BY p.proname
""";
String schemaName = resolveSchema(schema, connection);
List procedures = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
Map> parameters = loadParameters(connection, schemaName, "p");
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
@@ -675,12 +875,12 @@ public List getAllFunctions(Connection connection, String catalog, Str
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'
+ WHERE n.nspname = ? AND p.prokind = 'f' AND {VISIBLE_ROUTINE p n}
ORDER BY p.proname
""";
String schemaName = resolveSchema(schema, connection);
List functions = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
Map> parameters = loadParameters(connection, schemaName, "f");
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
@@ -723,7 +923,7 @@ public List getAllFunctions(Connection connection, String catalog, Str
* {@code RETURNS TABLE}, or of {@code proargtypes} where all are {@code IN}. A parameter
* without a name has the empty one.
*/
- private static Map> loadParameters(Connection connection, String schemaName,
+ private Map> loadParameters(Connection connection, String schemaName,
String kind) throws SQLException {
String sql = """
SELECT p.proname || '_' || p.oid AS specific_name, a.ord,
@@ -734,11 +934,11 @@ private static Map> loadParameters(Connection connecti
CROSS JOIN LATERAL unnest(COALESCE(p.proallargtypes, p.proargtypes::oid[]))
WITH ORDINALITY AS a(type_oid, ord)
JOIN pg_type t ON t.oid = a.type_oid
- WHERE n.nspname = ? AND p.prokind = ?
+ WHERE n.nspname = ? AND p.prokind = ? AND {VISIBLE_ROUTINE p n}
ORDER BY p.oid, a.ord
""";
Map> result = new LinkedHashMap<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
ps.setString(2, kind);
try (ResultSet rs = ps.executeQuery()) {
@@ -835,14 +1035,14 @@ public List getAllUserDefinedTypes(Connection connection, Strin
obj_description(t.oid, 'pg_type') AS remarks
FROM pg_type t
JOIN pg_namespace n ON n.oid = t.typnamespace
- WHERE n.nspname = ?
+ WHERE n.nspname = ? AND {VISIBLE_TYPE t n}
AND t.typtype IN ('c', 'e', 'd')
AND NOT EXISTS (SELECT 1 FROM pg_class c WHERE c.reltype = t.oid AND c.relkind IN ('r', 'v', 'm'))
ORDER BY t.typname
""";
String schemaName = resolveSchema(schema, connection);
List types = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@@ -984,7 +1184,7 @@ private List readUniqueConstraints(Connection connection, Stri
String tableName) throws SQLException {
String schemaName = resolveSchema(schema, connection);
Map ucMap = new LinkedHashMap<>();
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
ps.setString(1, schemaName);
if (tableName != null) {
ps.setString(2, tableName);
@@ -1079,24 +1279,28 @@ private static ImportedKey.ReferentialAction mapPgReferentialAction(String actio
@Override
public Optional> getAllTablePrivileges(Connection connection, String catalog,
String schemaPattern, String tableNamePattern) throws SQLException {
- // information_schema.table_privileges already expands role memberships and
- // PUBLIC grants through the pg_catalog views, so it reports more than
- // JDBC's getTablePrivileges alone.
+ // The access control list of each table, view, materialized view and foreign table, not
+ // information_schema.table_privileges, which shows only the grants to or by a role of the
+ // reader.
StringBuilder sql = new StringBuilder("""
- SELECT table_schema, table_name, grantor, grantee, privilege_type, is_grantable
- FROM information_schema.table_privileges
- WHERE table_schema = ?
+ SELECT c.relname AS table_name, pg_get_userbyid(a.grantor) AS grantor,
+ CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
+ a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END AS is_grantable
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace, aclexplode(c.relacl) a
+ WHERE n.nspname = ? AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
+ AND {VISIBLE_RELATION c n} AND {CONCERNS_USER a}
""");
boolean hasTableFilter = tableNamePattern != null && !tableNamePattern.isBlank()
&& !"%".equals(tableNamePattern);
if (hasTableFilter) {
- sql.append(" AND table_name LIKE ?\n");
+ sql.append(" AND c.relname LIKE ?\n");
}
sql.append("ORDER BY table_name, privilege_type, grantee");
String schemaName = resolveSchema(schemaPattern, connection);
List result = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql.toString())) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql.toString()))) {
ps.setString(1, schemaName);
if (hasTableFilter) {
ps.setString(2, tableNamePattern);
@@ -1125,8 +1329,7 @@ public Optional> getAllTablePrivileges(Connection connectio
public Optional> getAllObjectPrivileges(
Connection connection, String catalog, String schema) throws SQLException {
// ACL-based privileges on non-table objects. aclexplode() skips NULL ACLs
- // (implicit owner-only default) — matching information_schema behaviour is
- // not required here; explicit grants are what matters.
+ // (implicit owner-only default): explicit grants are what matters.
String schemaName = resolveSchema(schema, connection);
List result = new ArrayList<>();
@@ -1138,7 +1341,7 @@ public Optional> ge
CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
a.privilege_type, a.is_grantable
FROM pg_database d, aclexplode(d.datacl) a
- WHERE d.datname = current_database()
+ WHERE d.datname = current_database() AND {CONCERNS_USER a}
""";
readObjectPrivileges(connection, databaseSql, null, null, result);
@@ -1150,7 +1353,7 @@ FROM pg_database d, aclexplode(d.datacl) a
a.privilege_type, a.is_grantable
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace, aclexplode(p.proacl) a
- WHERE n.nspname = ?
+ WHERE n.nspname = ? AND {VISIBLE_ROUTINE p n} AND {CONCERNS_USER a}
""";
readObjectPrivileges(connection, routineSql, schemaName, schemaName, result);
@@ -1161,7 +1364,7 @@ FROM pg_database d, aclexplode(d.datacl) a
a.privilege_type, a.is_grantable
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace, aclexplode(c.relacl) a
- WHERE c.relkind = 'S' AND n.nspname = ?
+ WHERE c.relkind = 'S' AND n.nspname = ? AND {VISIBLE_SEQUENCE c n} AND {CONCERNS_USER a}
""";
readObjectPrivileges(connection, sequenceSql, schemaName, schemaName, result);
@@ -1169,10 +1372,10 @@ FROM pg_database d, aclexplode(d.datacl) a
}
- private static void readObjectPrivileges(Connection connection, String sql, String parameter,
+ private void readObjectPrivileges(Connection connection, String sql, String parameter,
String schemaName, List result)
throws SQLException {
- try (PreparedStatement ps = connection.prepareStatement(sql)) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql))) {
if (parameter != null) {
ps.setString(1, parameter);
}
@@ -1193,21 +1396,28 @@ private static void readObjectPrivileges(Connection connection, String sql, Stri
@Override
public Optional> getColumnPrivileges(Connection connection, String catalog, String schema,
String tableName, String columnNamePattern) throws SQLException {
+ // The access control list of each column: the grants on the column itself, not those on
+ // its table, which information_schema.column_privileges repeats for every column.
StringBuilder sql = new StringBuilder("""
- SELECT column_name, grantor, grantee, privilege_type, is_grantable
- FROM information_schema.column_privileges
- WHERE table_schema = ? AND table_name = ?
+ SELECT att.attname AS column_name, pg_get_userbyid(a.grantor) AS grantor,
+ CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
+ a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END AS is_grantable
+ FROM pg_attribute att
+ JOIN pg_class c ON c.oid = att.attrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace, aclexplode(att.attacl) a
+ WHERE n.nspname = ? AND c.relname = ? AND att.attnum > 0 AND NOT att.attisdropped
+ AND {VISIBLE_RELATION c n} AND {CONCERNS_USER a}
""");
boolean hasColumnFilter = columnNamePattern != null && !columnNamePattern.isBlank()
&& !"%".equals(columnNamePattern);
if (hasColumnFilter) {
- sql.append(" AND column_name LIKE ?\n");
+ sql.append(" AND att.attname LIKE ?\n");
}
sql.append("ORDER BY column_name, privilege_type, grantee");
String schemaName = resolveSchema(schema, connection);
List result = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql.toString())) {
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql.toString()))) {
ps.setString(1, schemaName);
ps.setString(2, tableName);
if (hasColumnFilter) {
@@ -1290,7 +1500,8 @@ UniqueConstraint build() {
@Override
public Optional> getAllRoleMemberships(Connection connection)
throws SQLException {
- // pg_auth_members: every membership edge incl. grantor and ADMIN OPTION.
+ // pg_auth_members: every membership edge incl. grantor and ADMIN OPTION; in USER those of
+ // the user and of the roles it has, as information_schema.applicable_roles has them.
String sql = """
SELECT m.rolname AS grantee, r.rolname AS role_name,
g.rolname AS grantor, am.admin_option
@@ -1298,10 +1509,11 @@ public Optional> get
JOIN pg_roles r ON r.oid = am.roleid
JOIN pg_roles m ON m.oid = am.member
LEFT JOIN pg_roles g ON g.oid = am.grantor
+ WHERE {HELD_ROLE am.member}
ORDER BY grantee, role_name
""";
List result = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql);
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql));
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(new org.eclipse.daanse.sql.jdbc.record.schema.RoleMembershipRecord(
@@ -1316,10 +1528,11 @@ public Optional> get
@Override
public Optional> getAllPrincipals(Connection connection)
throws SQLException {
- // pg_roles is world-readable; rolcanlogin separates users from roles.
- String sql = "SELECT rolname, rolcanlogin FROM pg_roles ORDER BY rolname";
+ // pg_roles is world-readable; rolcanlogin separates users from roles. In USER the user and
+ // the roles it has.
+ String sql = "SELECT rolname, rolcanlogin FROM pg_roles r WHERE {HELD_ROLE r.oid} ORDER BY rolname";
List result = new ArrayList<>();
- try (PreparedStatement ps = connection.prepareStatement(sql);
+ try (PreparedStatement ps = connection.prepareStatement(scoped(sql));
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(new org.eclipse.daanse.sql.jdbc.record.schema.DatabasePrincipalRecord(rs.getString("rolname"),
diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataScopeDefaultsTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataScopeDefaultsTest.java
new file mode 100644
index 00000000..5aee3906
--- /dev/null
+++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MetadataScopeDefaultsTest.java
@@ -0,0 +1,191 @@
+/*
+* 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 static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.List;
+
+import javax.sql.DataSource;
+
+import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException;
+import org.eclipse.daanse.sql.jdbc.api.SnapshotBuilder;
+import org.eclipse.daanse.sql.jdbc.api.meta.MetaInfo;
+import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
+import org.eclipse.daanse.sql.jdbc.api.schema.ImportedKey;
+import org.eclipse.daanse.sql.jdbc.api.schema.TableDefinition;
+import org.eclipse.daanse.sql.jdbc.record.meta.StructureInfoRecord;
+import org.eclipse.daanse.sql.model.schema.CatalogReference;
+import org.eclipse.daanse.sql.model.schema.ColumnDefinition;
+import org.eclipse.daanse.sql.model.schema.PrimaryKey;
+import org.eclipse.daanse.sql.model.schema.SchemaReference;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+/**
+ * Who asks for no scope reads the whole database: a provider, a snapshot and the resolver by product
+ * name say {@link MetadataScope#DATABASE} unless another scope was asked for.
+ */
+class MetadataScopeDefaultsTest {
+
+ @Test
+ void aProviderReadsInDatabaseScopeAndNeedsNoRightOfItsOwn() throws SQLException {
+ MetadataProvider provider = MetadataProvider.EMPTY;
+
+ assertThat(provider.scope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(provider.effectiveScope(null)).isEqualTo(MetadataScope.DATABASE);
+ assertThat(provider.scopeRequirement()).isEqualTo("none");
+ assertThat(provider.getAllSchemas(null, null)).isEmpty();
+ }
+
+ @Test
+ void aProviderThatReadsOneWayOnlyIsItselfInEveryScope() {
+ assertThat(MetadataProvider.EMPTY.withScope(MetadataScope.USER)).isSameAs(MetadataProvider.EMPTY);
+ }
+
+ @Test
+ void aStructureInfoWithoutScopesWasAskedForAndReadInDatabaseScope() {
+ StructureInfo plain = new StructureInfo() {
+ @Override
+ public List catalogs() {
+ return List.of();
+ }
+
+ @Override
+ public List schemas() {
+ return List.of();
+ }
+
+ @Override
+ public List tables() {
+ return List.of();
+ }
+
+ @Override
+ public List columns() {
+ return List.of();
+ }
+
+ @Override
+ public List importedKeys() {
+ return List.of();
+ }
+
+ @Override
+ public List primaryKeys() {
+ return List.of();
+ }
+ };
+
+ assertThat(plain.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(plain.scope()).isEqualTo(MetadataScope.DATABASE);
+ }
+
+ @Test
+ void theRecordBuiltWithoutScopesWasAskedForAndReadInDatabaseScope() {
+ StructureInfoRecord withSynonyms = new StructureInfoRecord(List.of(), List.of(), List.of(), List.of(),
+ List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(),
+ List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of());
+ StructureInfoRecord plainJdbc = new StructureInfoRecord(List.of(), List.of(), List.of(), List.of(),
+ List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(),
+ List.of(), List.of(), List.of());
+
+ for (StructureInfoRecord record : List.of(withSynonyms, plainJdbc)) {
+ assertThat(record.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(record.scope()).isEqualTo(MetadataScope.DATABASE);
+ }
+ }
+
+ @Test
+ void theRecordKeepsBothScopes() {
+ StructureInfoRecord record = new StructureInfoRecord(List.of(), List.of(), List.of(), List.of(), List.of(),
+ List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(),
+ List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(),
+ MetadataScope.DATABASE, MetadataScope.USER);
+
+ assertThat(record.requestedScope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(record.scope()).isEqualTo(MetadataScope.USER);
+ }
+
+ @Test
+ void theProviderOfAProductReadsInDatabaseScopeUnlessAskedOtherwise() {
+ assertThat(MetadataProviders.forProductName("PostgreSQL").orElseThrow().scope())
+ .isEqualTo(MetadataScope.DATABASE);
+ assertThat(MetadataProviders.forProductName("no such database", MetadataScope.USER)).isEmpty();
+ }
+
+ @ParameterizedTest
+ @CsvSource({ "Oracle, OracleMetadataProvider", "PostgreSQL, PostgreSqlMetadataProvider" })
+ void theProviderOfEachProductReadsInTheScopeAskedFor(String product, String providerClass) {
+ MetadataProvider user = MetadataProviders.forProductName(product, MetadataScope.USER).orElseThrow();
+
+ assertThat(user.getClass().getSimpleName()).isEqualTo(providerClass);
+ assertThat(user.scope()).isEqualTo(MetadataScope.USER);
+ assertThat(user.withScope(MetadataScope.USER)).isSameAs(user);
+ MetadataProvider database = user.withScope(MetadataScope.DATABASE);
+ assertThat(database.getClass()).isEqualTo(user.getClass());
+ assertThat(database.scope()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(MetadataProviders.forProductName(product).orElseThrow().scope()).isEqualTo(MetadataScope.DATABASE);
+ }
+
+ /**
+ * A snapshot builder of its own checks the scope before it reads, where asked to be strict: the
+ * exception names the product, both scopes and the right that is missing. Without strict, it
+ * reads.
+ */
+ @Test
+ void aStrictSnapshotFailsBeforeReadingWhereTheConnectionMayNotReadTheScope() throws SQLException {
+ MetadataProvider restricted = new MetadataProvider() {
+ @Override
+ public MetadataScope effectiveScope(Connection connection) {
+ return MetadataScope.USER;
+ }
+
+ @Override
+ public String scopeRequirement() {
+ return "the right to read the catalog";
+ }
+ };
+ int[] reads = { 0 };
+ SnapshotBuilder builder = new SnapshotBuilder() {
+ @Override
+ public MetaInfo createMetaInfo(DataSource dataSource) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MetaInfo createMetaInfo(Connection connection) {
+ reads[0]++;
+ return null;
+ }
+ };
+ try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:scope")) {
+ assertThatThrownBy(() -> builder.createMetaInfo(connection, restricted, true))
+ .isInstanceOfSatisfying(MetadataScopeException.class, e -> {
+ assertThat(e.product()).isEqualTo("H2");
+ assertThat(e.requested()).isEqualTo(MetadataScope.DATABASE);
+ assertThat(e.available()).isEqualTo(MetadataScope.USER);
+ assertThat(e.requirement()).isEqualTo("the right to read the catalog");
+ assertThat(e.getMessage()).contains("H2", "DATABASE", "the right to read the catalog");
+ });
+ assertThat(reads[0]).as("nothing read").isZero();
+
+ builder.createMetaInfo(connection, restricted, false);
+ assertThat(reads[0]).as("read without strict").isOne();
+ }
+ }
+}
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 b040da3c..76f76ba7 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
@@ -20,8 +20,11 @@
import java.util.Locale;
import org.eclipse.daanse.sql.jdbc.api.MetadataProvider;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
+import org.eclipse.daanse.sql.jdbc.api.schema.ColumnPrivilege;
import org.eclipse.daanse.sql.jdbc.api.schema.DatabasePrincipal;
import org.eclipse.daanse.sql.jdbc.api.schema.RoleMembership;
+import org.eclipse.daanse.sql.jdbc.api.schema.TablePrivilege;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.testcontainers.oracle.OracleContainer;
@@ -29,7 +32,8 @@
/**
* The metadata contract on Oracle, in a container. A schema is a user: the orders lie in the
* container's user, the products in the user STOCK. SYSTEM creates the objects, as only it may create
- * them in both; the container's user reads them.
+ * them in both; the container's user reads them, in {@link MetadataScope#DATABASE} with the right to
+ * read the dictionary ({@code SELECT_CATALOG_ROLE}).
*/
@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
class OracleMetadataContractTest extends MetadataProviderContract {
@@ -46,6 +50,7 @@ protected Connection open() throws Exception {
system = DriverManager.getConnection(container.getJdbcUrl(), "system", container.getPassword());
try (var s = system.createStatement()) {
s.execute("CREATE USER STOCK IDENTIFIED BY stock QUOTA UNLIMITED ON USERS");
+ s.execute("GRANT SELECT_CATALOG_ROLE TO " + container.getUsername());
}
return DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword());
}
@@ -129,9 +134,10 @@ void theSequencesOfOracleItselfAreRead() throws SQLException {
}
/**
- * The container's user reads with plain rights, from views every user may read: every user, the
- * roles it holds, also one it holds through another role, and the memberships among them; a role it does not hold
- * stays unseen. It reads in a session of its own, which has the roles granted before it began.
+ * The container's user reads in {@link MetadataScope#USER}, from views every user may read: every
+ * user, the roles it holds, also one it holds through another role, and the memberships among
+ * them; a role it does not hold stays unseen. It reads in a session of its own, which has the
+ * roles granted before it began.
*/
@Test
void usersRolesAndMembershipsAreReadWithPlainReadRights() throws SQLException {
@@ -144,7 +150,8 @@ void usersRolesAndMembershipsAreReadWithPlainReadRights() throws SQLException {
}
try (Connection reader = DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(),
container.getPassword())) {
- List principals = provider().getAllPrincipals(reader).orElseThrow();
+ MetadataProvider user = provider().withScope(MetadataScope.USER);
+ List principals = user.getAllPrincipals(reader).orElseThrow();
assertThat(principals).as("the users and roles")
.extracting(DatabasePrincipal::name, DatabasePrincipal::kind)
.contains(tuple(sales(), DatabasePrincipal.KIND_USER), tuple("STOCK", DatabasePrincipal.KIND_USER),
@@ -152,10 +159,74 @@ void usersRolesAndMembershipsAreReadWithPlainReadRights() throws SQLException {
tuple("R_PARENT", DatabasePrincipal.KIND_ROLE))
.doesNotContain(tuple("R_OTHER", DatabasePrincipal.KIND_ROLE));
- List memberships = provider().getAllRoleMemberships(reader).orElseThrow();
+ List memberships = user.getAllRoleMemberships(reader).orElseThrow();
assertThat(memberships).as("the memberships")
.extracting(RoleMembership::grantee, RoleMembership::role, m -> m.adminOption().orElse(null))
.contains(tuple(sales(), "R_CHILD", "NO"), tuple("R_CHILD", "R_PARENT", "YES"));
}
}
+
+ /**
+ * A grant on some columns of a table is read for its owner, in {@link MetadataScope#USER} from
+ * {@code ALL_COL_PRIVS}, which names the owner {@code TABLE_SCHEMA}, in
+ * {@link MetadataScope#DATABASE} from {@code DBA_COL_PRIVS}, which names it {@code OWNER}.
+ */
+ @Test
+ void columnPrivilegesAreReadByTheOwner() throws SQLException {
+ try (var s = system.createStatement()) {
+ s.execute("GRANT UPDATE (qty) ON " + sales() + ".orders TO STOCK");
+ }
+ for (MetadataScope scope : MetadataScope.values()) {
+ List privileges = provider().withScope(scope)
+ .getColumnPrivileges(connection(), null, sales(), "ORDERS", null).orElseThrow();
+
+ assertThat(privileges).as("in scope %s", scope)
+ .extracting(p -> p.column().name(), ColumnPrivilege::grantee, ColumnPrivilege::privilege)
+ .contains(tuple("QTY", "STOCK", "UPDATE"));
+ }
+ }
+
+ /**
+ * A reader that may read the DBA_ views ({@code SELECT_CATALOG_ROLE}) and nothing else reads in
+ * {@link MetadataScope#DATABASE} every role, every membership and every grant, also those that
+ * concern neither it nor an object of its own: a role it does not hold, the membership of another
+ * user in it, the grants on the tables of another schema, on the whole table and on a column. In
+ * {@link MetadataScope#USER}, the container's user sees none of these.
+ */
+ @Test
+ void aReaderOfTheDictionarySeesEveryRoleMembershipAndGrant() throws SQLException {
+ try (var s = system.createStatement()) {
+ s.execute("CREATE USER AUDITOR IDENTIFIED BY auditor");
+ s.execute("GRANT CREATE SESSION, SELECT_CATALOG_ROLE TO AUDITOR");
+ s.execute("CREATE ROLE R_AUDITED");
+ s.execute("GRANT R_AUDITED TO STOCK");
+ s.execute("GRANT SELECT ON " + sales() + ".orders TO R_AUDITED");
+ s.execute("GRANT UPDATE (qty) ON " + sales() + ".orders TO R_AUDITED");
+ }
+ MetadataProvider database = provider();
+ try (Connection auditor = DriverManager.getConnection(container.getJdbcUrl(), "AUDITOR", "auditor")) {
+ assertThat(database.effectiveScope(auditor)).isEqualTo(MetadataScope.DATABASE);
+ assertThat(database.getAllPrincipals(auditor).orElseThrow()).as("a role the auditor does not hold")
+ .extracting(DatabasePrincipal::name, DatabasePrincipal::kind)
+ .contains(tuple("R_AUDITED", DatabasePrincipal.KIND_ROLE));
+ assertThat(database.getAllRoleMemberships(auditor).orElseThrow()).as("the membership of another user")
+ .extracting(RoleMembership::grantee, RoleMembership::role).contains(tuple("STOCK", "R_AUDITED"));
+ assertThat(database.getAllTablePrivileges(auditor, null, sales(), null).orElseThrow())
+ .as("a grant on a table of another schema")
+ .extracting(p -> p.table().name(), TablePrivilege::grantee, TablePrivilege::privilege)
+ .contains(tuple("ORDERS", "R_AUDITED", "SELECT"));
+ assertThat(database.getColumnPrivileges(auditor, null, sales(), "ORDERS", null).orElseThrow())
+ .as("a grant on a column of a table of another schema")
+ .extracting(p -> p.column().name(), ColumnPrivilege::grantee, ColumnPrivilege::privilege)
+ .contains(tuple("QTY", "R_AUDITED", "UPDATE"));
+ }
+ MetadataProvider user = provider().withScope(MetadataScope.USER);
+ try (Connection reader = DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(),
+ container.getPassword())) {
+ assertThat(user.getAllPrincipals(reader).orElseThrow()).as("plain read rights")
+ .extracting(DatabasePrincipal::name).doesNotContain("R_AUDITED");
+ assertThat(user.getAllRoleMemberships(reader).orElseThrow()).as("plain read rights")
+ .extracting(RoleMembership::role).doesNotContain("R_AUDITED");
+ }
+ }
}
diff --git a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleSynonymsTest.java b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleSynonymsTest.java
index bfcca604..beb70016 100644
--- a/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleSynonymsTest.java
+++ b/jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/OracleSynonymsTest.java
@@ -31,6 +31,10 @@
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.oracle.OracleContainer;
+/**
+ * The synonyms of a schema on Oracle, in a container: read in {@code MetadataScope.DATABASE} by the
+ * container's user, which may read the dictionary ({@code SELECT_CATALOG_ROLE}).
+ */
@Testcontainers
@EnabledIfSystemProperty(named = "integration.docker", matches = "true")
@TestInstance(Lifecycle.PER_CLASS)
@@ -51,6 +55,7 @@ void setUp() throws Exception {
try (Connection system = DriverManager.getConnection(CONTAINER.getJdbcUrl(), "system",
CONTAINER.getPassword()); Statement stmt = system.createStatement()) {
stmt.execute("GRANT CREATE SYNONYM, CREATE PUBLIC SYNONYM, DROP PUBLIC SYNONYM, CREATE MATERIALIZED VIEW TO " + SCHEMA);
+ stmt.execute("GRANT SELECT_CATALOG_ROLE TO " + SCHEMA);
}
connection = DriverManager.getConnection(CONTAINER.getJdbcUrl(), CONTAINER.getUsername(),
CONTAINER.getPassword());
diff --git a/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/meta/StructureInfoRecord.java b/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/meta/StructureInfoRecord.java
index 0ce2362e..3eace0bc 100644
--- a/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/meta/StructureInfoRecord.java
+++ b/jdbc/record/src/main/java/org/eclipse/daanse/sql/jdbc/record/meta/StructureInfoRecord.java
@@ -15,6 +15,7 @@
import java.util.List;
+import org.eclipse.daanse.sql.jdbc.api.MetadataScope;
import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo;
import org.eclipse.daanse.sql.model.schema.CatalogReference;
import org.eclipse.daanse.sql.jdbc.api.schema.CheckConstraint;
@@ -61,7 +62,25 @@ public record StructureInfoRecord(
List objectPrivileges,
List roleMemberships,
List principals,
- List synonyms) implements StructureInfo {
+ List synonyms,
+ MetadataScope requestedScope,
+ MetadataScope scope) implements StructureInfo {
+
+ /** Compatibility constructor without the scopes: asked for and read in {@link MetadataScope#DATABASE}. */
+ public StructureInfoRecord(List catalogs, List