25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(schema): add schema-level index management for Oracle-family
efeire29722c2f28b0
diff --git a/.github/pr-assets/schema-index-create-confirm.jpg b/.github/pr-assets/schema-index-create-confirm.jpgnew file mode 100644index 0000000000..b3a772ce86Binary files /dev/null and b/.github/pr-assets/schema-index-create-confirm.jpg differdiff --git a/.github/pr-assets/schema-index-empty.jpg b/.github/pr-assets/schema-index-empty.jpgnew file mode 100644index 0000000000..bb6f9ae564Binary files /dev/null and b/.github/pr-assets/schema-index-empty.jpg differdiff --git a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.javaindex 19a9541959..2f9ac6d2eb 100644--- a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java+++ b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java@@ -144,6 +144,7 @@ public final class AgentProtocol {public static final String CAPABILITY_MULTI_SESSION = "multi_session";public static final String CAPABILITY_STRUCTURED_ERROR_V1 = "structured_error_v1";public static final String CAPABILITY_BLOB_BIND_STATEMENTS_V1 = "blob_bind_statements_v1";+ public static final String CAPABILITY_EXACT_METADATA_IDENTITY_V1 = "exact_metadata_identity_v1";public static final List<String> CAPABILITIES = Collections.unmodifiableList(Arrays.asList(CAPABILITY_CONNECT,@@ -181,7 +182,8 @@ public final class AgentProtocol {CAPABILITY_MONGO_REPLACE_DOCUMENT,CAPABILITY_MONGO_BULK_WRITE,CAPABILITY_MONGO_RENAME_COLLECTION,- CAPABILITY_MONGO_FIND_CURSOR+ CAPABILITY_MONGO_FIND_CURSOR,+ CAPABILITY_EXACT_METADATA_IDENTITY_V1));public static final List<String> MULTI_SESSION_CAPABILITIES;@@ -357,6 +359,13 @@ public final class AgentProtocol {return new HandshakeResult(PROTOCOL_VERSION, PROTOCOL_VERSION, CAPABILITIES);}+ public static HandshakeResult withExactMetadataIdentity(HandshakeResult result, boolean supported) {+ if (!supported) return result;+ java.util.ArrayList<String> capabilities = new java.util.ArrayList<>(result.capabilities);+ capabilities.add(CAPABILITY_EXACT_METADATA_IDENTITY_V1);+ return new HandshakeResult(result.protocolVersion, result.agentProtocolVersion, capabilities);+ }+public static HandshakeResult multiSessionHandshakeResult() {return new HandshakeResult(MULTI_SESSION_PROTOCOL_VERSION,diff --git a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.javaindex 181b68e204..a8681117e1 100644--- a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java+++ b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java@@ -16,6 +16,9 @@ public interface DatabaseAgent {default boolean supportsBlobBindStatements() { return false; }+ /** Opt in only when dictionary-derived owner/name values are preserved without fallback. */+ default boolean supportsExactMetadataIdentity() { return false; }+default QueryResult executeBlobBoundStatements(List<String> previews, List<BlobBoundStatement> statements,String schema, int timeoutSecs, boolean transaction) {throw new UnsupportedOperationException("BLOB statement binding is not supported by this agent");@@ -126,6 +129,10 @@ public interface DatabaseAgent {return DdlBuilder.buildTableDdl(schema, table, getColumns(schema, table), indexes, foreignKeys, Collections.emptyList(), false, false, tableComment);}+ default String getTableDdl(String schema, String table, boolean exactIdentity) {+ return getTableDdl(schema, table);+ }+/*** Returns the comment/description for a table, or null if not available.* Default implementation looks up the comment from listTables results.diff --git a/agents/common/src/main/java/com/dbx/agent/IndexInfo.java b/agents/common/src/main/java/com/dbx/agent/IndexInfo.javaindex 4ca3109c99..b9d9db988d 100644--- a/agents/common/src/main/java/com/dbx/agent/IndexInfo.java+++ b/agents/common/src/main/java/com/dbx/agent/IndexInfo.java@@ -5,6 +5,7 @@ import java.util.List;import java.util.Objects;public final class IndexInfo {+ private String owner;private String name;private List<String> columns;private boolean is_unique;@@ -76,6 +77,10 @@ public final class IndexInfo {return name;}+ public String getOwner() { return owner; }++ public void setOwner(String owner) { this.owner = owner; }+public List<String> getColumns() {return columns;}@@ -193,6 +198,7 @@ public final class IndexInfo {&& is_primary == that.is_primary&& constraint_backed == that.constraint_backed&& Objects.equals(name, that.name)+ && Objects.equals(owner, that.owner)&& Objects.equals(columns, that.columns)&& Objects.equals(filter, that.filter)&& Objects.equals(index_type, that.index_type)@@ -208,6 +214,7 @@ public final class IndexInfo {@Overridepublic int hashCode() {return Objects.hash(+ owner,name,columns,is_unique,diff --git a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.javaindex 9e07e2d907..f49ede4a18 100644--- a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java@@ -186,14 +186,17 @@ public final class JsonRpcServer {observingAgent.beforeAgentMethod(method, stringOrNull(params, "sessionId"));}if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {- return AgentProtocol.handshakeResult();+ return AgentProtocol.withExactMetadataIdentity(AgentProtocol.handshakeResult(), agent.supportsExactMetadataIdentity());}if (AgentProtocol.METHOD_CONNECT.equals(method)) {ConnectParams connectParams = gson.fromJson(params, ConnectParams.class);agent.connect(connectParams);lastConnectParams = connectParams;lastConnectionValidationTimeMillis = 0L;- return Collections.singletonMap("ok", true);+ Map<String, Object> result = new LinkedHashMap<>();+ result.put("ok", true);+ result.put("exactMetadataIdentity", agent.supportsExactMetadataIdentity());+ return result;}if (AgentProtocol.METHOD_TEST_CONNECTION.equals(method)) {Map<String, Object> result = agent.testConnectionWithInfo(gson.fromJson(params, ConnectParams.class));@@ -219,6 +222,14 @@ public final class JsonRpcServer {}return Collections.singletonMap("ok", true);}+ boolean exactIdentity = booleanOrDefault(params, "exact_identity", false);+ if (exactIdentity) {+ if (!agent.supportsExactMetadataIdentity()) {+ throw new UnsupportedOperationException("Agent does not support exact_metadata_identity_v1");+ }+ String schema = stringOrNull(params, "schema");+ if (schema == null || schema.isBlank()) throw new IllegalArgumentException("schema is required for exact metadata identity");+ }ensureLiveConnection(method);if (AgentProtocol.METHOD_CONNECTION_INFO.equals(method)) {Map<String, Object> result = new LinkedHashMap<>();@@ -262,13 +273,15 @@ public final class JsonRpcServer {}if (AgentProtocol.METHOD_GET_TABLE_DDL.equals(method)) {switchCatalog(params);- return agent.getTableDdl(params.get("schema").getAsString(), params.get("table").getAsString());+ return agent.getTableDdl(params.get("schema").getAsString(), params.get("table").getAsString(), exactIdentity);}if (AgentProtocol.METHOD_GET_COLUMNS.equals(method)) {switchCatalog(params);String currentSchema = params.has("current_schema") && !params.get("current_schema").isJsonNull()? params.get("current_schema").getAsString() : null;- return agent.getColumnsInContext(params.get("schema").getAsString(), params.get("table").getAsString(), currentSchema);+ return exactIdentity+ ? agent.getColumns(params.get("schema").getAsString(), params.get("table").getAsString())+ : agent.getColumnsInContext(params.get("schema").getAsString(), params.get("table").getAsString(), currentSchema);}if (AgentProtocol.METHOD_LIST_INDEXES.equals(method)) {switchCatalog(params);@@ -641,7 +654,8 @@ public final class JsonRpcServer {stringOrNull(params, "filter"),intOrNull(params, "limit"),intOrNull(params, "offset"),- stringListOrNull(params, "object_types")+ stringListOrNull(params, "object_types"),+ booleanOrDefault(params, "exact_identity", false));}diff --git a/agents/common/src/main/java/com/dbx/agent/MetadataListConstraints.java b/agents/common/src/main/java/com/dbx/agent/MetadataListConstraints.javaindex 0fcf8155e5..6ca425f154 100644--- a/agents/common/src/main/java/com/dbx/agent/MetadataListConstraints.java+++ b/agents/common/src/main/java/com/dbx/agent/MetadataListConstraints.java@@ -12,12 +12,22 @@ public final class MetadataListConstraints {private final Integer limit;private final Integer offset;private final List<String> objectTypes;+ private final boolean exactIdentity;public MetadataListConstraints(String filter, Integer limit, Integer offset, List<String> objectTypes) {+ this(filter, limit, offset, objectTypes, false);+ }++ public MetadataListConstraints(String filter, Integer limit, Integer offset, List<String> objectTypes, boolean exactIdentity) {this.filter = normalizeFilter(filter);this.limit = limit == null || limit <= 0 ? null : limit;this.offset = offset == null || offset <= 0 ? null : offset;this.objectTypes = normalizeObjectTypes(objectTypes);+ this.exactIdentity = exactIdentity;+ }++ public boolean isExactIdentity() {+ return exactIdentity;}public static MetadataListConstraints orNone(MetadataListConstraints constraints) {@@ -57,7 +67,7 @@ public final class MetadataListConstraints {}public MetadataListConstraints withoutPaging() {- return new MetadataListConstraints(filter, null, null, objectTypes);+ return new MetadataListConstraints(filter, null, null, objectTypes, exactIdentity);}public String fuzzyLikePattern() {diff --git a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.javaindex f67b8dbdcd..38e6c142c0 100644--- a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java@@ -46,6 +46,7 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {private final AtomicBoolean closed = new AtomicBoolean();private ScheduledExecutorService maintenance;private boolean blobBindStatements;+ private boolean exactMetadataIdentity;public MultiSessionJsonRpcServer(Supplier<? extends DatabaseAgent> agentFactory) {this(agentFactory, new JdbcConnectionPoolRegistry(), RuntimeLimits.defaults());@@ -98,6 +99,11 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {return server;}+ public MultiSessionJsonRpcServer withExactMetadataIdentity() {+ exactMetadataIdentity = true;+ return this;+ }+public void run() {synchronized (outputLock) {protocolOutput.println("{\"ready\":true}");@@ -146,7 +152,7 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {Object result;if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {result = sessionHandlerFactory == null- ? AgentProtocol.multiSessionJdbcHandshakeResult(blobBindStatements)+ ? AgentProtocol.withExactMetadataIdentity(AgentProtocol.multiSessionJdbcHandshakeResult(blobBindStatements), exactMetadataIdentity): customHandshake();} else if (AgentProtocol.METHOD_OPEN_SESSION.equals(method)) {result = openSession(requiredSessionId(params), params);diff --git a/agents/common/src/main/java/com/dbx/agent/ObjectInfo.java b/agents/common/src/main/java/com/dbx/agent/ObjectInfo.javaindex 0dc0f557ff..ef21b9ea72 100644--- a/agents/common/src/main/java/com/dbx/agent/ObjectInfo.java+++ b/agents/common/src/main/java/com/dbx/agent/ObjectInfo.java@@ -9,6 +9,7 @@ public final class ObjectInfo {private String comment;private Boolean valid;private String parent_name;+ private String parent_schema;public ObjectInfo() {this("", "", null, null, null);@@ -78,6 +79,14 @@ public final class ObjectInfo {this.parent_name = parentName;}+ public String getParent_schema() {+ return parent_schema;+ }++ public void setParent_schema(String parentSchema) {+ this.parent_schema = parentSchema;+ }+@Overridepublic boolean equals(Object other) {if (this == other) return true;@@ -88,12 +97,13 @@ public final class ObjectInfo {&& Objects.equals(schema, that.schema)&& Objects.equals(comment, that.comment)&& Objects.equals(parent_name, that.parent_name)+ && Objects.equals(parent_schema, that.parent_schema)&& Objects.equals(valid, that.valid);}@Overridepublic int hashCode() {- return Objects.hash(name, object_type, schema, comment, valid, parent_name);+ return Objects.hash(name, object_type, schema, comment, valid, parent_name, parent_schema);}@Overridediff --git a/agents/common/src/main/resources/agent-protocol-v1.json b/agents/common/src/main/resources/agent-protocol-v1.jsonindex af91085bbf..c7713e1aa7 100644--- a/agents/common/src/main/resources/agent-protocol-v1.json+++ b/agents/common/src/main/resources/agent-protocol-v1.json@@ -2,7 +2,7 @@"protocolVersion": 1,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl"],"commonMethods": [diff --git a/agents/common/src/main/resources/agent-protocol-v2.json b/agents/common/src/main/resources/agent-protocol-v2.jsonindex 76d831bce7..3b472f8a5b 100644--- a/agents/common/src/main/resources/agent-protocol-v2.json+++ b/agents/common/src/main/resources/agent-protocol-v2.json@@ -2,7 +2,7 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],"commonMethods": [diff --git a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.javaindex 03f41bd371..955927bd76 100644--- a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java+++ b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java@@ -32,6 +32,7 @@ import java.util.concurrent.atomic.AtomicBoolean;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;@@ -54,6 +55,23 @@ class CommonJavaCompatibilityTest {assertTrue(AgentProtocol.CAPABILITIES.contains(AgentProtocol.CAPABILITY_CONNECT));assertTrue(AgentProtocol.CAPABILITIES.contains(AgentProtocol.CAPABILITY_QUERY));assertTrue(AgentProtocol.CAPABILITIES.contains(AgentProtocol.CAPABILITY_METADATA));+ assertFalse(AgentProtocol.CAPABILITIES.contains(AgentProtocol.CAPABILITY_EXACT_METADATA_IDENTITY_V1));+ }++ @Test+ void objectInfoRetainsIndependentOwnersWithoutChangingLegacyConstructors() {+ Gson gson = new Gson();+ ObjectInfo legacy = gson.fromJson("{\"name\":\"T\",\"object_type\":\"TABLE\"}", ObjectInfo.class);+ assertNull(legacy.getParent_schema());+ ObjectInfo index = new ObjectInfo(" Ix(a) ", "INDEX", "Index Owner", null);+ index.setParent_schema(" Table Owner ");+ index.setParent_name(" T(a) ");+ ObjectInfo restored = gson.fromJson(gson.toJson(index), ObjectInfo.class);+ assertEquals(index, restored);+ assertEquals(index.hashCode(), restored.hashCode());+ assertEquals(" Table Owner ", restored.getParent_schema());+ restored.setParent_schema("Other Owner");+ assertFalse(index.equals(restored));}@Test@@ -120,6 +138,47 @@ class CommonJavaCompatibilityTest {assertTrue(containsCapability(result.getAsJsonArray("capabilities"), "metadata"));}+ @Test+ void exactMetadataRequiresExplicitAgentSupportBeforeReading() {+ JsonRpcServer server = new JsonRpcServer(new MinimalAgent());+ JsonObject old = JsonParser.parseString(server.handleRequest("{\"id\":1,\"method\":\"get_columns\",\"params\":{\"schema\":\"APP\",\"table\":\"T\"}}")).getAsJsonObject();+ assertTrue(old.has("result"));+ JsonObject exact = JsonParser.parseString(server.handleRequest("{\"id\":2,\"method\":\"get_columns\",\"params\":{\"schema\":\"APP\",\"table\":\"T\",\"exact_identity\":true}}")).getAsJsonObject();+ assertTrue(exact.has("error"), exact.toString());+ assertTrue(exact.getAsJsonObject("error").get("message").getAsString().contains("exact_metadata_identity_v1"));+ }++ @Test+ void explicitExactIdentityAgentAdvertisesTheCapability() {+ MinimalAgent agent = new MinimalAgent() {+ public boolean supportsExactMetadataIdentity() { return true; }+ };+ JsonObject handshake = JsonParser.parseString(new JsonRpcServer(agent).handleRequest("{\"id\":1,\"method\":\"handshake\",\"params\":{}}")).getAsJsonObject();+ assertTrue(containsCapability(handshake.getAsJsonObject("result").getAsJsonArray("capabilities"), "exact_metadata_identity_v1"));+ }++ @Test+ void connectedSessionReportsItsOwnExactIdentitySupport() {+ try (MultiSessionJsonRpcServer server = new MultiSessionJsonRpcServer(() -> new MinimalAgent() {+ private boolean exactIdentity = true;+ @Override+ public void connect(ConnectParams params) { exactIdentity = !"legacy".equals(params.getDatabase()); }+ @Override+ public boolean supportsExactMetadataIdentity() { return exactIdentity; }+ }).withExactMetadataIdentity()) {+ JsonObject legacy = JsonParser.parseString(server.handleRequest("{\"id\":1,\"method\":\"open_session\",\"params\":{\"agentSessionId\":\"legacy\",\"database\":\"legacy\"}} ")).getAsJsonObject();+ JsonObject current = JsonParser.parseString(server.handleRequest("{\"id\":2,\"method\":\"open_session\",\"params\":{\"agentSessionId\":\"current\",\"database\":\"current\"}} ")).getAsJsonObject();+ assertTrue(legacy.getAsJsonObject("result").get("ok").getAsBoolean());+ assertTrue(legacy.getAsJsonObject("result").has("exactMetadataIdentity"));+ assertFalse(legacy.getAsJsonObject("result").get("exactMetadataIdentity").getAsBoolean());+ assertTrue(current.getAsJsonObject("result").get("exactMetadataIdentity").getAsBoolean());+ JsonObject ordinary = JsonParser.parseString(server.handleRequest("{\"id\":3,\"method\":\"get_columns\",\"params\":{\"agentSessionId\":\"legacy\",\"schema\":\"APP\",\"table\":\"T\"}} ")).getAsJsonObject();+ assertTrue(ordinary.has("result"), ordinary.toString());+ JsonObject exact = JsonParser.parseString(server.handleRequest("{\"id\":4,\"method\":\"get_columns\",\"params\":{\"agentSessionId\":\"legacy\",\"schema\":\"APP\",\"table\":\"T\",\"exact_identity\":true}} ")).getAsJsonObject();+ assertTrue(exact.has("error"), exact.toString());+ }+ }+@Testvoid constraintMetadataUnsupportedIsNotAnEmptySuccess() {JsonRpcServer server = new JsonRpcServer(new MinimalAgent());diff --git a/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.java b/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.javaindex 31d21bb863..991e361d45 100644--- a/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.java+++ b/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.java@@ -574,6 +574,9 @@ public final class DamengAgent extends AbstractJdbcAgent {return queryConstrainedTables(schema, MetadataListConstraints.NONE);}+ @Override+ public boolean supportsExactMetadataIdentity() { return !legacyJdbcMetadata; }+@Overridepublic List<TableInfo> listTables(String schema, List<String> objectTypes) {return queryConstrainedTables(schema, new MetadataListConstraints(null, null, null, objectTypes));@@ -586,6 +589,10 @@ public final class DamengAgent extends AbstractJdbcAgent {private List<TableInfo> queryConstrainedTables(String rawSchema, MetadataListConstraints constraints) {final String schema = normalizeSchema(rawSchema);+ if (constraints.isExactIdentity()) {+ if (legacyJdbcMetadata) throw new UnsupportedOperationException("Legacy DM metadata does not support exact_metadata_identity_v1");+ return withViewValidity(executeConstrainedTables(buildAccessibleConstrainedTablesQuery(schema, constraints), constraints), schema);+ }if (legacyJdbcMetadata) {return withViewValidity(executeJdbcMetadataTables(schema, constraints), schema);}@@ -1176,12 +1183,53 @@ public final class DamengAgent extends AbstractJdbcAgent {private List<ObjectInfo> queryConstrainedObjects(String rawSchema, MetadataListConstraints constraints) {final String schema = normalizeSchema(rawSchema);- List<ObjectInfo> objects = queryConstrainedObjectsWithoutValidity(schema, constraints);+ List<ObjectInfo> objects;+ if (constraints.objectTypeAllowed("INDEX") && (constraints.hasObjectTypes() || constraints.isExactIdentity())) {+ // Merge before paging: separate dictionary sources must not each consume the offset.+ objects = new ArrayList<>();+ List<String> otherTypes = damengObjectTypes(constraints);+ if (!otherTypes.isEmpty()) {+ objects.addAll(queryConstrainedObjectsWithoutValidity(schema,+ new MetadataListConstraints(constraints.getFilter(), null, null, otherTypes, constraints.isExactIdentity())));+ }+ objects.addAll(querySchemaIndexes(schema, constraints.withoutPaging()));+ objects.sort(java.util.Comparator.comparing(ObjectInfo::getName).thenComparing(ObjectInfo::getObject_type));+ objects = constraints.filterObjects(objects);+ } else {+ objects = queryConstrainedObjectsWithoutValidity(schema, constraints);+ }applyViewValidity(objects, schema);return objects;}+ private List<ObjectInfo> querySchemaIndexes(String schema, MetadataListConstraints constraints) {+ return unchecked(() -> {+ List<Object> args = new ArrayList<>();+ args.add(schema);+ StringBuilder sql = new StringBuilder("SELECT OWNER, INDEX_NAME, TABLE_OWNER, TABLE_NAME FROM ALL_INDEXES i WHERE i.OWNER = ?");+ appendNameFilter(sql, args, "i.INDEX_NAME", constraints);+ sql.append(" ORDER BY i.INDEX_NAME");+ List<ObjectInfo> objects = new ArrayList<>();+ try (PreparedStatement statement = requireConnected().prepareStatement(sql.toString())) {+ bind(statement, args);+ try (ResultSet rows = statement.executeQuery()) {+ while (rows.next()) {+ ObjectInfo index = new ObjectInfo(rows.getString(2), "INDEX", rows.getString(1), null);+ index.setParent_schema(rows.getString(3));+ index.setParent_name(rows.getString(4));+ objects.add(index);+ }+ }+ }+ return constraints.filterObjects(objects);+ });+ }+private List<ObjectInfo> queryConstrainedObjectsWithoutValidity(String schema, MetadataListConstraints constraints) {+ if (constraints.isExactIdentity()) {+ if (legacyJdbcMetadata) throw new UnsupportedOperationException("Legacy DM metadata does not support exact_metadata_identity_v1");+ return executeConstrainedObjects(schema, buildAccessibleConstrainedObjectsQuery(schema, constraints), constraints);+ }if (legacyJdbcMetadata) {return executeJdbcMetadataObjects(schema, constraints);}@@ -1875,8 +1923,14 @@ public final class DamengAgent extends AbstractJdbcAgent {@Overridepublic String getTableDdl(String rawSchema, String table) {+ return getTableDdl(rawSchema, table, false);+ }++ @Override+ public String getTableDdl(String rawSchema, String table, boolean exactIdentity) {final String schema = normalizeSchema(rawSchema);if (legacyJdbcMetadata) {+ if (exactIdentity) throw new UnsupportedOperationException("Legacy DM metadata does not support exact_metadata_identity_v1");return super.getTableDdl(schema, table);}try {@@ -1900,6 +1954,7 @@ public final class DamengAgent extends AbstractJdbcAgent {throw new IllegalArgumentException("Table not found: " + schema + "." + table);});} catch (RuntimeException error) {+ if (exactIdentity) throw error;if (!isDamengMetadataUnavailableError(error)) {throw error;}@@ -2331,12 +2386,14 @@ public final class DamengAgent extends AbstractJdbcAgent {MAX(CASE WHEN constraint_metadata.TYPE$ = 'P' THEN 1 ELSE 0 END) AS IS_PK,index_metadata.TYPE$,MAX(CASE WHEN constraint_metadata.TYPE$ IN ('P', 'U') THEN 1 ELSE 0 END) AS CONSTRAINT_BACKED,- index_metadata.FLAG+ index_metadata.FLAG, index_schema_object.NAME AS INDEX_OWNERFROM SYS.SYSOBJECTS schema_objectJOIN SYS.SYSOBJECTS table_object ON table_object.SCHID = schema_object.IDAND table_object.TYPE$ = 'SCHOBJ' AND table_object.SUBTYPE$ = 'UTAB'JOIN SYS.SYSOBJECTS index_object ON index_object.PID = table_object.IDAND index_object.SUBTYPE$ = 'INDEX'+ JOIN SYS.SYSOBJECTS index_schema_object ON index_schema_object.ID = index_object.SCHID+ AND index_schema_object.TYPE$ = 'SCH'JOIN SYS.SYSINDEXES index_metadata ON index_metadata.ID = index_object.IDJOIN SYS.SYSCOLUMNS column_object ON column_object.ID = table_object.IDAND SF_COL_IS_IDX_KEY(@@ -2348,8 +2405,8 @@ public final class DamengAgent extends AbstractJdbcAgent {AND constraint_metadata.INDEXID = index_metadata.IDAND constraint_metadata.TYPE$ IN ('P', 'U')WHERE schema_object.TYPE$ = 'SCH' AND schema_object.NAME = ? AND table_object.NAME = ?- GROUP BY index_object.NAME, index_metadata.ISUNIQUE, index_metadata.TYPE$, index_metadata.FLAG- ORDER BY index_object.NAME+ GROUP BY index_schema_object.NAME, index_object.NAME, index_metadata.ISUNIQUE, index_metadata.TYPE$, index_metadata.FLAG+ ORDER BY index_schema_object.NAME, index_object.NAME""".stripIndent().trim();try (PreparedStatement stmt = requireConnected().prepareStatement(sql)) {stmt.setString(1, schema);@@ -2369,6 +2426,7 @@ public final class DamengAgent extends AbstractJdbcAgent {null);index.setConstraint_backed(constraintBacked);+ index.setOwner(rs.getString(8));result.add(index);}}@@ -2386,14 +2444,14 @@ public final class DamengAgent extends AbstractJdbcAgent {i.UNIQUENESS,CASE WHEN c.CONSTRAINT_TYPE = 'P' THEN 1 ELSE 0 END AS IS_PK,i.INDEX_TYPE,- CASE WHEN c.CONSTRAINT_TYPE IN ('P', 'U') THEN 1 ELSE 0 END AS CONSTRAINT_BACKED+ CASE WHEN c.CONSTRAINT_TYPE IN ('P', 'U') THEN 1 ELSE 0 END AS CONSTRAINT_BACKED, i.OWNER AS INDEX_OWNERFROM ALL_INDEXES iJOIN ALL_IND_COLUMNS ic ON i.INDEX_NAME = ic.INDEX_NAME AND i.OWNER = ic.INDEX_OWNER AND i.TABLE_OWNER = ic.TABLE_OWNERLEFT JOIN ALL_CONSTRAINTS c ON i.INDEX_NAME = c.INDEX_NAME AND i.TABLE_OWNER = c.OWNERAND c.CONSTRAINT_TYPE IN ('P', 'U')WHERE i.TABLE_OWNER = ? AND i.TABLE_NAME = ?- GROUP BY i.INDEX_NAME, i.UNIQUENESS, c.CONSTRAINT_TYPE, i.INDEX_TYPE- ORDER BY i.INDEX_NAME+ GROUP BY i.OWNER, i.INDEX_NAME, i.UNIQUENESS, c.CONSTRAINT_TYPE, i.INDEX_TYPE+ ORDER BY i.OWNER, i.INDEX_NAME""".stripIndent().trim();try (PreparedStatement stmt = requireConnected().prepareStatement(sql)) {stmt.setString(1, schema);@@ -2411,6 +2469,7 @@ public final class DamengAgent extends AbstractJdbcAgent {null);index.setConstraint_backed("1".equals(rs.getString(6)));+ index.setOwner(rs.getString(7));result.add(index);}}@@ -3441,6 +3500,6 @@ public final class DamengAgent extends AbstractJdbcAgent {}public static void main(String[] args) {- new MultiSessionJsonRpcServer(DamengAgent::new).run();+ new MultiSessionJsonRpcServer(DamengAgent::new).withExactMetadataIdentity().run();}}diff --git a/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.java b/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.javaindex 6b95e7f11f..7a81251f1a 100644--- a/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.java+++ b/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.java@@ -235,14 +235,15 @@ class DamengAgentMetadataTest {DamengAgent agent = new DamengAgent();TestSupport.setPrivateConnection(agent, indexMetadataConnection(List.of(// UNIQUE constraint (虚索引) / standalone CREATE UNIQUE INDEX (实索引) / plain index.- Arrays.asList("UX_USERS_EMAIL", "EMAIL", "Y", "0", "BT", "1", 0),- Arrays.asList("UX_USERS_CODE", "CODE", "Y", "0", "BT", "0", 0),- Arrays.asList("IDX_USERS_NAME", "NAME", "N", "0", "BT", "0", 0),- Arrays.asList("PK_USERS", "ID", "Y", "1", "BT", "1", 4)+ Arrays.asList("UX_USERS_EMAIL", "EMAIL", "Y", "0", "BT", "1", 0, " Index Owner "),+ Arrays.asList("UX_USERS_CODE", "CODE", "Y", "0", "BT", "0", 0, " Index Owner "),+ Arrays.asList("IDX_USERS_NAME", "NAME", "N", "0", "BT", "0", 0, " Index Owner "),+ Arrays.asList("PK_USERS", "ID", "Y", "1", "BT", "1", 4, " Index Owner "))));List<IndexInfo> indexes = agent.listIndexes("APP", "USERS");+ Assertions.assertTrue(indexes.stream().allMatch(index -> " Index Owner ".equals(index.getOwner())));Assertions.assertEquals(List.of("UX_USERS_EMAIL", "UX_USERS_CODE", "IDX_USERS_NAME", "PK_USERS"),indexes.stream().map(IndexInfo::getName).toList()@@ -275,12 +276,13 @@ class DamengAgentMetadataTest {List.of(),new SQLException("no SYS index catalog privilege"),"FROM ALL_INDEXES i",- List.of(Arrays.asList("IDX_USERS_NAME", "NAME", "NONUNIQUE", "0", "NORMAL", "0"))+ List.of(Arrays.asList("IDX_USERS_NAME", "NAME", "NONUNIQUE", "0", "NORMAL", "0", " Index Owner "))));List<IndexInfo> indexes = agent.listIndexes("APP", "USERS");Assertions.assertEquals(List.of("IDX_USERS_NAME"), indexes.stream().map(IndexInfo::getName).toList());+ Assertions.assertEquals(" Index Owner ", indexes.get(0).getOwner());Assertions.assertTrue(indexOfSql(sqls, "SYS.SYSINDEXES") >= 0, String.join("\n", sqls));Assertions.assertTrue(indexOfSql(sqls, "ALL_INDEXES") > indexOfSql(sqls, "SYS.SYSINDEXES"),@@ -2464,7 +2466,7 @@ class DamengAgentMetadataTest {indexRow("IDX_USERS_NAME", "NAME", "N", "BT", 0),indexRow("UX_USERS_EMAIL", "EMAIL", "Y", "BT", 0),indexRow("IDX_USERS_GEO", "GEO", "N", "ST", 0),- Arrays.asList("PK_USERS", "ID", "Y", "1", "BT", "1", 4)+ Arrays.asList("PK_USERS", "ID", "Y", "1", "BT", "1", 4, "APP")),sqls);@@ -2766,7 +2768,7 @@ class DamengAgentMetadataTest {}private static List<Object> indexRow(String name, String columns, String uniqueness, String indexType, int flags) {- return List.of(name, columns, uniqueness, "0", indexType, "0", flags);+ return List.of(name, columns, uniqueness, "0", indexType, "0", flags, "APP");}private static List<List<Object>> dictionaryIndexRows(List<List<Object>> systemRows) {@@ -2776,7 +2778,7 @@ class DamengAgentMetadataTest {"Y".equals(row.get(2)) ? "UNIQUE" : "NONUNIQUE",row.get(3),"ST".equals(row.get(4)) ? "SPATIAL" : "NORMAL",- row.get(5)+ row.get(5), row.get(7))).toList();}diff --git a/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengSchemaIndexTest.java b/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengSchemaIndexTest.javanew file mode 100644index 0000000000..d3f5b90b26--- /dev/null+++ b/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengSchemaIndexTest.java@@ -0,0 +1,76 @@+package com.dbx.agent.dameng;++import com.dbx.agent.MetadataListConstraints;+import com.dbx.agent.ObjectInfo;+import com.dbx.agent.test.TestSupport;+import org.junit.jupiter.api.Test;++import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.util.ArrayList;+import java.util.List;++import static org.junit.jupiter.api.Assertions.*;++class DamengSchemaIndexTest {+ @Test+ void indexListingPreservesRawParentIdentity() {+ DamengAgent agent = new DamengAgent();+ List<String> owners = new ArrayList<>();+ TestSupport.setPrivateConnection(agent, connection(owners, false));++ List<ObjectInfo> objects = agent.listObjects(" Index Owner ",+ new MetadataListConstraints(null, 2, 0, List.of("INDEX")));++ assertEquals(1, objects.size());+ ObjectInfo index = objects.get(0);+ assertEquals(" Ix (a) ", index.getName());+ assertEquals(" Index Owner ", index.getSchema());+ assertEquals("INDEX", index.getObject_type());+ assertEquals("Table Owner", index.getParent_schema());+ assertEquals(" T(a) ", index.getParent_name());+ assertEquals(List.of(" Index Owner "), owners);+ }++ @Test+ void indexDictionaryPermissionFailureDoesNotUseTableOnlyFallback() {+ DamengAgent agent = new DamengAgent();+ TestSupport.setPrivateConnection(agent, connection(new ArrayList<>(), true));++ RuntimeException error = assertThrows(RuntimeException.class,+ () -> agent.listObjects("APP", new MetadataListConstraints(null, 2, 0, List.of("INDEX"))));++ assertEquals(-5669, ((SQLException) error.getCause()).getErrorCode());+ }++ private static Connection connection(List<String> owners, boolean denied) {+ return proxy(Connection.class, (target, method, args) -> {+ if (method.getName().equals("prepareStatement")) {+ assertTrue(((String) args[0]).contains("ALL_INDEXES"), (String) args[0]);+ return proxy(PreparedStatement.class, (statement, operation, values) -> {+ if (operation.getName().equals("setString") && values[0].equals(1)) owners.add((String) values[1]);+ if (operation.getName().equals("executeQuery")) {+ if (denied) throw new SQLException("权限不足", "42000", -5669);+ int[] row = {0};+ String[] data = {" Index Owner ", " Ix (a) ", "Table Owner", " T(a) "};+ return proxy(ResultSet.class, (result, read, arguments) -> switch (read.getName()) {+ case "next" -> row[0]++ == 0;+ case "getString" -> data[(Integer) arguments[0] - 1];+ default -> null;+ });+ }+ return null;+ });+ }+ if (method.getName().equals("isClosed")) return false;+ return null;+ });+ }++ private static <T> T proxy(Class<T> type, java.lang.reflect.InvocationHandler handler) {+ return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, handler));+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.javaindex 5dd092897d..6a4b182148 100644--- a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java@@ -670,6 +670,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {return queryObjects(schema, MetadataListConstraints.NONE);}+ @Override+ public boolean supportsExactMetadataIdentity() { return true; }+@Overridepublic List<ObjectInfo> listObjects(String schema, MetadataListConstraints constraints) {return queryObjects(schema, MetadataListConstraints.orNone(constraints));@@ -683,15 +686,18 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {return List.of();}String baseSql = """- SELECT o.OBJECT_NAME, o.OBJECT_TYPE, c.COMMENTS+ SELECT o.OBJECT_NAME, o.OBJECT_TYPE, c.COMMENTS,+ i.TABLE_OWNER AS PARENT_SCHEMA, i.TABLE_NAME AS PARENT_NAMEFROM ALL_OBJECTS oLEFT JOIN ALL_TAB_COMMENTS c ON c.OWNER = o.OWNER AND c.TABLE_NAME = o.OBJECT_NAMEAND o.OBJECT_TYPE IN ('TABLE', 'VIEW')+ LEFT JOIN ALL_INDEXES i ON o.OBJECT_TYPE = 'INDEX'+ AND i.OWNER = o.OWNER AND i.INDEX_NAME = o.OBJECT_NAMEWHERE o.OWNER = ? AND o.OBJECT_TYPE IN (%s)""".stripIndent().trim();MetadataSql query = oceanBaseMetadataSql(String.format(baseSql, placeholders(objectTypes.size())),- "OBJECT_NAME, OBJECT_TYPE, COMMENTS",+ "OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAME","OBJECT_NAME","""ORDER BY CASE OBJECT_TYPE@@ -716,8 +722,13 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {try (ResultSet rs = stmt.executeQuery()) {while (rs.next()) {String objectType = rs.getString(2);- result.add(new ObjectInfo(rs.getString(1),- objectType.replace(' ', '_'), owner, rs.getString(3)));+ ObjectInfo object = new ObjectInfo(rs.getString(1),+ objectType.replace(' ', '_'), owner, rs.getString(3));+ if ("INDEX".equals(objectType)) {+ object.setParent_schema(rs.getString(4));+ object.setParent_name(rs.getString(5));+ }+ result.add(object);}}}@@ -1292,7 +1303,7 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}private static List<String> oceanBaseObjectTypes(MetadataListConstraints constraints) {- List<String> supported = List.of("TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY", "SEQUENCE", "SYNONYM", "TYPE", "TYPE BODY");+ List<String> supported = List.of("TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY", "SEQUENCE", "SYNONYM", "TYPE", "TYPE BODY", "INDEX");if (!constraints.hasObjectTypes()) {return supported;}@@ -1942,7 +1953,7 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {String tableName = normalizeObjectName(table);String sql = """SELECT i.INDEX_NAME, ic.COLUMN_NAME, ic.COLUMN_POSITION, i.UNIQUENESS,- c.CONSTRAINT_TYPE, i.INDEX_TYPE, i.PARTITIONED, i.VISIBILITY, ic.DESCEND, ie.COLUMN_EXPRESSION+ c.CONSTRAINT_TYPE, i.INDEX_TYPE, i.PARTITIONED, i.VISIBILITY, ic.DESCEND, ie.COLUMN_EXPRESSION, i.OWNER AS INDEX_OWNERFROM ALL_INDEXES iJOIN ALL_IND_COLUMNS icON i.INDEX_NAME = ic.INDEX_NAME@@ -1959,29 +1970,33 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {ON i.INDEX_NAME = c.INDEX_NAMEAND i.TABLE_OWNER = c.OWNERAND i.TABLE_NAME = c.TABLE_NAME+ AND i.OWNER = c.INDEX_OWNERAND c.CONSTRAINT_TYPE = 'P'WHERE i.TABLE_OWNER = ? AND i.TABLE_NAME = ?- ORDER BY i.INDEX_NAME, ic.COLUMN_POSITION+ ORDER BY i.OWNER, i.INDEX_NAME, ic.COLUMN_POSITION""".stripIndent().trim();- Map<String, IndexInfo> indexesByName = new LinkedHashMap<>();+ Map<List<String>, IndexInfo> indexesByName = new LinkedHashMap<>();try (var stmt = requireConnection().prepareStatement(sql)) {stmt.setString(1, owner);stmt.setString(2, tableName);try (ResultSet rs = stmt.executeQuery()) {while (rs.next()) {String indexName = rs.getString("INDEX_NAME");- IndexInfo index = indexesByName.get(indexName);+ String indexOwner = rs.getString("INDEX_OWNER");+ var identity = java.util.Arrays.asList(indexOwner, indexName);+ IndexInfo index = indexesByName.get(identity);if (index == null) {IndexInfo item = new IndexInfo(indexName, new ArrayList<>(),"UNIQUE".equalsIgnoreCase(rs.getString("UNIQUENESS")),"P".equalsIgnoreCase(rs.getString("CONSTRAINT_TYPE")),null, rs.getString("INDEX_TYPE"), null, null);item.setKey_is_expression(new ArrayList<>());+ item.setOwner(indexOwner);item.setKey_directions(new ArrayList<>());item.setKey_metadata_complete(true);item.setVisibility(rs.getString("VISIBILITY"));- indexesByName.put(indexName, item);+ indexesByName.put(identity, item);index = item;}String column = rs.getString("COLUMN_NAME");@@ -2433,6 +2448,6 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}public static void main(String[] args) {- MultiSessionJsonRpcServer.withBlobBindings(OceanBaseOracleAgent::new).run();+ MultiSessionJsonRpcServer.withBlobBindings(OceanBaseOracleAgent::new).withExactMetadataIdentity().run();}}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.javaindex bac7910fff..570ab9e112 100644--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.java+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.java@@ -32,6 +32,7 @@ class OceanBaseOracleIndexRpcTest {var indexes = response.getAsJsonArray("result");assertEquals(1, indexes.size());JsonObject index = indexes.get(0).getAsJsonObject();+ assertEquals(" Index Owner ", index.get("owner").getAsString());assertEquals(List.of("LOWER(\"EVENT_NAME\")", "EVENT_TS"), index.getAsJsonArray("columns").asList().stream().map(value -> value.getAsString()).toList());assertEquals(List.of(true, false), index.getAsJsonArray("key_is_expression").asList()@@ -67,6 +68,7 @@ class OceanBaseOracleIndexRpcTest {String descend, String visibility) {Map<String, String> row = new HashMap<>();row.put("INDEX_NAME", name);+ row.put("INDEX_OWNER", " Index Owner ");row.put("COLUMN_NAME", column);row.put("COLUMN_POSITION", position);row.put("UNIQUENESS", uniqueness);@@ -79,6 +81,21 @@ class OceanBaseOracleIndexRpcTest {return row;}+ @Test+ void keepsSameNameIndexesFromDifferentDictionaryOwnersSeparate() {+ var first = row(" Ix(a) ", "ID", "1", "NONUNIQUE", "I", "NORMAL", "NO", null, "ASC", "VISIBLE");+ var other = row(" Ix(a) ", "CODE", "1", "NONUNIQUE", "I", "NORMAL", "NO", null, "ASC", "VISIBLE");+ other.put("INDEX_OWNER", "Other");+ var response = new Fixture(List.of(first, other)).request(" Parent ", " T(a) ");+ assertFalse(response.has("error"), response.toString());+ var indexes = response.getAsJsonArray("result");+ assertEquals(2, indexes.size());+ assertEquals(" Index Owner ", indexes.get(0).getAsJsonObject().get("owner").getAsString());+ assertEquals("Other", indexes.get(1).getAsJsonObject().get("owner").getAsString());+ assertEquals(1, indexes.get(0).getAsJsonObject().getAsJsonArray("columns").size());+ assertEquals(1, indexes.get(1).getAsJsonObject().getAsJsonArray("columns").size());+ }+private static final class Fixture {final List<String> sql = new ArrayList<>();final List<String> parameters = new ArrayList<>();diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.javaindex ba9f724858..b4c0463dac 100644--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.java+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.java@@ -23,6 +23,38 @@ import java.util.List;import static org.junit.jupiter.api.Assertions.*;class OceanBaseOracleObjectListTest {+ @Test+ void schemaIndexPagesPreserveBothOwnersAndRawNames() {+ JdbcFixture jdbc = new JdbcFixture();+ JdbcCall call = jdbc.rows(row(" Ix (a) ", "INDEX", null, "Table Owner", " T(a) "));+ List<ObjectInfo> objects = jdbc.agent.listObjects("Index Owner", constraints("Ix", 2, 2, "INDEX"));++ assertEquals(1, objects.size());+ String json = new com.google.gson.Gson().toJson(objects.get(0));+ com.google.gson.JsonObject object = com.google.gson.JsonParser.parseString(json).getAsJsonObject();+ assertEquals(" Ix (a) ", object.get("name").getAsString());+ assertEquals("Index Owner", object.get("schema").getAsString());+ assertEquals("INDEX", object.get("object_type").getAsString());+ assertEquals("Table Owner", object.get("parent_schema").getAsString());+ assertEquals(" T(a) ", object.get("parent_name").getAsString());+ assertEquals(List.of("Index Owner", "INDEX", "%I%X%", "%I%X%", 4L, 2), call.args);+ call.assertClosed();+ }++ @Test+ void schemaIndexDictionaryFailureDoesNotBecomeAnEmptyPage() {+ JdbcFixture jdbc = new JdbcFixture();+ JdbcCall call = jdbc.rows();+ SQLException denied = new SQLException("ORA-01031: insufficient privileges", "42000", 1031);+ call.executeFailure = denied;++ RuntimeException error = assertThrows(RuntimeException.class,+ () -> jdbc.agent.listObjects("APP", constraints(null, 2, 0, "INDEX")));++ assertSame(denied, error.getCause());+ assertTrue(call.statementClosed);+ }+@Testvoid tableAndViewCommentsSurviveObjectListing() {JdbcFixture jdbc = new JdbcFixture();@@ -78,13 +110,13 @@ class OceanBaseOracleObjectListTest {};assertEquals(List.of("APP", "TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE",- "PACKAGE BODY", "SEQUENCE", "SYNONYM", "TYPE", "TYPE BODY"), call.args);+ "PACKAGE BODY", "SEQUENCE", "SYNONYM", "TYPE", "TYPE BODY", "INDEX"), call.args);assertEquals(List.of("TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE","PACKAGE_BODY", "SEQUENCE", "SYNONYM"), objects.stream().map(ObjectInfo::getObject_type).toList());assertEquals(8, objects.size());assertTrue(objects.stream().allMatch(object -> "APP".equals(object.getSchema())));assertTrue(objects.stream().allMatch(object -> object.getValid() == null));- assertTrue(call.sql.contains("OBJECT_TYPE IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"), call.sql);+ assertTrue(call.sql.contains("OBJECT_TYPE IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"), call.sql);assertFalse(call.sql.contains("ROWNUM"), call.sql);assertObjectOrder(call.sql);call.assertClosed();diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.goindex d5cf6579de..1992f611db 100644--- a/agents/drivers/oracle-go/main.go+++ b/agents/drivers/oracle-go/main.go@@ -155,11 +155,13 @@ FROM USER_MVIEWS mvconst oracleListTablesOrderSQL = `ORDER BY OBJECT_NAME`const oracleListTablesSQL = oracleListTablesBaseSQL + "\n" + oracleListTablesOrderSQLconst oracleListObjectsBaseSQL = `-SELECT OBJECT_NAME, OBJECT_TYPE, COMMENTS+SELECT OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAMEFROM (SELECT t.TABLE_NAME AS OBJECT_NAME,'TABLE' AS OBJECT_TYPE,- CAST(NULL AS VARCHAR2(4000)) AS COMMENTS+ CAST(NULL AS VARCHAR2(4000)) AS COMMENTS,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_SCHEMA,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_NAMEFROM ALL_TABLES tWHERE t.OWNER = :1AND t.NESTED = 'NO'@@ -177,23 +179,31 @@ SELECT o.OBJECT_NAME,WHEN 'MATERIALIZED VIEW' THEN 'MATERIALIZED_VIEW'ELSE o.OBJECT_TYPEEND AS OBJECT_TYPE,- CAST(NULL AS VARCHAR2(4000)) AS COMMENTS+ CAST(NULL AS VARCHAR2(4000)) AS COMMENTS,+ i.TABLE_OWNER AS PARENT_SCHEMA,+ i.TABLE_NAME AS PARENT_NAMEFROM ALL_OBJECTS o+LEFT JOIN ALL_INDEXES i+ ON o.OBJECT_TYPE = 'INDEX' AND i.OWNER = o.OWNER AND i.INDEX_NAME = o.OBJECT_NAMEWHERE o.OWNER = :2- AND o.OBJECT_TYPE IN ('VIEW', 'MATERIALIZED VIEW', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'PACKAGE', 'PACKAGE BODY')+ AND o.OBJECT_TYPE IN ('VIEW', 'MATERIALIZED VIEW', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'PACKAGE', 'PACKAGE BODY', 'INDEX')UNION ALLSELECT s.SYNONYM_NAME AS OBJECT_NAME,'SYNONYM' AS OBJECT_TYPE,- CAST(NULL AS VARCHAR2(4000)) AS COMMENTS+ CAST(NULL AS VARCHAR2(4000)) AS COMMENTS,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_SCHEMA,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_NAMEFROM ALL_SYNONYMS sWHERE s.OWNER = :3)`const oracleListObjectsSessionUserBaseSQL = `-SELECT OBJECT_NAME, OBJECT_TYPE, COMMENTS+SELECT OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAMEFROM (SELECT t.TABLE_NAME AS OBJECT_NAME,'TABLE' AS OBJECT_TYPE,- CAST(NULL AS VARCHAR2(4000)) AS COMMENTS+ CAST(NULL AS VARCHAR2(4000)) AS COMMENTS,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_SCHEMA,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_NAMEFROM USER_TABLES tWHERE t.NESTED = 'NO'AND NOT EXISTS (@@ -209,13 +219,18 @@ SELECT o.OBJECT_NAME,WHEN 'MATERIALIZED VIEW' THEN 'MATERIALIZED_VIEW'ELSE o.OBJECT_TYPEEND AS OBJECT_TYPE,- CAST(NULL AS VARCHAR2(4000)) AS COMMENTS+ CAST(NULL AS VARCHAR2(4000)) AS COMMENTS,+ i.TABLE_OWNER AS PARENT_SCHEMA,+ i.TABLE_NAME AS PARENT_NAMEFROM USER_OBJECTS o-WHERE o.OBJECT_TYPE IN ('VIEW', 'MATERIALIZED VIEW', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'PACKAGE', 'PACKAGE BODY')+LEFT JOIN USER_INDEXES i ON o.OBJECT_TYPE = 'INDEX' AND i.INDEX_NAME = o.OBJECT_NAME+WHERE o.OBJECT_TYPE IN ('VIEW', 'MATERIALIZED VIEW', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'PACKAGE', 'PACKAGE BODY', 'INDEX')UNION ALLSELECT s.SYNONYM_NAME AS OBJECT_NAME,'SYNONYM' AS OBJECT_TYPE,- CAST(NULL AS VARCHAR2(4000)) AS COMMENTS+ CAST(NULL AS VARCHAR2(4000)) AS COMMENTS,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_SCHEMA,+ CAST(NULL AS VARCHAR2(128)) AS PARENT_NAMEFROM USER_SYNONYMS s)`const oracleListObjectsOrderSQL = `ORDER BY CASE OBJECT_TYPE@@ -462,17 +477,20 @@ type tableInfo struct {}type metadataListConstraints struct {- Filter string- Limit int- Offset int- ObjectTypes []string+ Filter string+ Limit int+ Offset int+ ObjectTypes []string+ ExactIdentity bool}type objectInfo struct {- Name string `json:"name"`- ObjectType string `json:"object_type"`- Schema string `json:"schema"`- Comment *string `json:"comment"`+ Name string `json:"name"`+ ObjectType string `json:"object_type"`+ Schema string `json:"schema"`+ Comment *string `json:"comment"`+ ParentSchema *string `json:"parent_schema,omitempty"`+ ParentName *string `json:"parent_name,omitempty"`}type columnInfo struct {@@ -491,6 +509,7 @@ type columnInfo struct {}type indexInfo struct {+ Owner *string `json:"owner,omitempty"`Name string `json:"name"`Columns []string `json:"columns"`IsUnique bool `json:"is_unique"`@@ -725,7 +744,7 @@ func (r *runtimeServer) dispatch(method string, params map[string]json.RawMessagreturn map[string]any{"protocolVersion": multiSessionProtocolVersion,"agentProtocolVersion": multiSessionProtocolVersion,- "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "multi_session"},+ "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "multi_session", "exact_metadata_identity_v1"},}, false, nilcase "open_session":agentSessionID := stringParam(params, "agentSessionId")@@ -911,7 +930,7 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyreturn map[string]any{"protocolVersion": protocolVersion,"agentProtocolVersion": protocolVersion,- "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl"},+ "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "exact_metadata_identity_v1"},}, false, nilcase "connect":var cp connectParams@@ -959,12 +978,12 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anycase "get_columns":schema := stringParam(params, "schema")table := stringParam(params, "table")- result, err := s.getColumns(schema, table)+ result, err := s.getColumnsWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "get_table_comment":schema := stringParam(params, "schema")table := stringParam(params, "table")- result, err := s.getTableComment(schema, table)+ result, err := s.getTableCommentWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "get_object_source":schema := stringParam(params, "schema")@@ -976,7 +995,7 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyschema := stringParam(params, "schema")table := stringParam(params, "table")objectType := stringParam(params, "object_type")- ddl, err := s.getTableDDLWithOptions(schema, table, objectType, boolParam(params, "portable"))+ ddl, err := s.getTableDDLWithIdentity(schema, table, objectType, boolParam(params, "portable"), boolParam(params, "exact_identity"))return ddl, false, errcase "execute_query":var opts queryOptions@@ -1012,22 +1031,22 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anycase "list_indexes":schema := stringParam(params, "schema")table := stringParam(params, "table")- result, err := s.listIndexes(schema, table)+ result, err := s.listIndexesWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "list_foreign_keys":schema := stringParam(params, "schema")table := stringParam(params, "table")- result, err := s.listForeignKeys(schema, table)+ result, err := s.listForeignKeysWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "list_constraints":schema := stringParam(params, "schema")table := stringParam(params, "table")- result, err := s.listConstraints(schema, table)+ result, err := s.listConstraintsWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "list_triggers":schema := stringParam(params, "schema")table := stringParam(params, "table")- result, err := s.listTriggers(schema, table)+ result, err := s.listTriggersWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "get_explain_info":sqlText := stringParam(params, "sql")@@ -1772,6 +1791,16 @@ func (s *server) normalizeSchema(schema string) (string, error) {return resolveOracleSchema(schema, s.currentSchema, s.sessionUser)}+func (s *server) metadataSchema(schema string, exactIdentity bool) (string, error) {+ if !exactIdentity {+ return s.normalizeSchema(schema)+ }+ if schema == "" {+ return "", errors.New("schema is required for exact metadata identity")+ }+ return schema, nil+}+func resolveOracleSchema(schema string, currentSchema, sessionUser func() (string, error)) (string, error) {if schema = strings.TrimSpace(schema); schema != "" {return strings.ToUpper(schema), nil@@ -1783,6 +1812,11 @@ func resolveOracleSchema(schema string, currentSchema, sessionUser func() (strin}func (s *server) sessionUser() (string, error) {+ username, err := s.rawSessionUser()+ return strings.ToUpper(username), err+}++func (s *server) rawSessionUser() (string, error) {db, err := s.requireDB()if err != nil {return "", err@@ -1791,7 +1825,7 @@ func (s *server) sessionUser() (string, error) {if err := db.QueryRow("SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') FROM DUAL").Scan(&username); err != nil {return "", err}- return strings.ToUpper(username), nil+ return username, nil}func (s *server) schemaIsSessionUser(schema string) bool {@@ -1799,6 +1833,14 @@ func (s *server) schemaIsSessionUser(schema string) bool {return err == nil && strings.EqualFold(schema, username)}+func (s *server) metadataSchemaIsSessionUser(schema string, exactIdentity bool) bool {+ if !exactIdentity {+ return s.schemaIsSessionUser(schema)+ }+ username, err := s.rawSessionUser()+ return err == nil && schema == username+}+type oracleMetadataListQuery struct {SQL stringArgs []any@@ -1818,10 +1860,11 @@ func metadataListConstraintsFromParams(params map[string]json.RawMessage) metadaoffset = 0}return metadataListConstraints{- Filter: stringParam(params, "filter"),- Limit: limit,- Offset: offset,- ObjectTypes: objectTypes,+ Filter: stringParam(params, "filter"),+ Limit: limit,+ Offset: offset,+ ObjectTypes: objectTypes,+ ExactIdentity: boolParam(params, "exact_identity"),}}@@ -1850,7 +1893,7 @@ func oracleListSessionUserTablesQuery(constraints metadataListConstraints) oraclfunc oracleListObjectsQuery(schema string, constraints metadataListConstraints) oracleMetadataListQuery {return oracleConstrainedMetadataListQuery(oracleListObjectsBaseSQL,- "OBJECT_NAME, OBJECT_TYPE, COMMENTS",+ "OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAME","OBJECT_TYPE",oracleListObjectsOrderSQL,[]any{schema, schema, schema},@@ -1861,7 +1904,7 @@ func oracleListObjectsQuery(schema string, constraints metadataListConstraints)func oracleListSessionUserObjectsQuery(constraints metadataListConstraints) oracleMetadataListQuery {return oracleConstrainedMetadataListQuery(oracleListObjectsSessionUserBaseSQL,- "OBJECT_NAME, OBJECT_TYPE, COMMENTS",+ "OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAME","OBJECT_TYPE",oracleListObjectsOrderSQL,nil,@@ -1954,17 +1997,17 @@ func oracleFuzzyLikePattern(value string) string {}func (s *server) listTables(schema string, constraints metadataListConstraints) ([]tableInfo, error) {- schema, err := s.normalizeSchema(schema)+ schema, err := s.metadataSchema(schema, constraints.ExactIdentity)if err != nil {return nil, err}query := oracleListTablesQuery(schema, constraints)- if s.schemaIsSessionUser(schema) {+ if s.metadataSchemaIsSessionUser(schema, constraints.ExactIdentity) {query = oracleListSessionUserTablesQuery(constraints)}rows, err := s.queryRows(query.SQL, query.Args)if err != nil {- if isOraclePGALimitError(err) {+ if isOraclePGALimitError(err) && !constraints.ExactIdentity {return []tableInfo{}, nil}return nil, err@@ -1982,17 +2025,17 @@ func (s *server) listTables(schema string, constraints metadataListConstraints)}func (s *server) listObjects(schema string, constraints metadataListConstraints) ([]objectInfo, error) {- schema, err := s.normalizeSchema(schema)+ schema, err := s.metadataSchema(schema, constraints.ExactIdentity)if err != nil {return nil, err}query := oracleListObjectsQuery(schema, constraints)- if s.schemaIsSessionUser(schema) {+ if s.metadataSchemaIsSessionUser(schema, constraints.ExactIdentity) {query = oracleListSessionUserObjectsQuery(constraints)}rows, err := s.queryRows(query.SQL, query.Args)if err != nil {- if isOraclePGALimitError(err) {+ if isOraclePGALimitError(err) && !constraints.ExactIdentity && !metadataIncludesIndexes(constraints.ObjectTypes) {return []objectInfo{}, nil}return nil, err@@ -2002,7 +2045,7 @@ func (s *server) listObjects(schema string, constraints metadataListConstraints)for rows.Next() {var item objectInfoitem.Schema = schema- if err := rows.Scan(&item.Name, &item.ObjectType, &item.Comment); err != nil {+ if err := rows.Scan(&item.Name, &item.ObjectType, &item.Comment, &item.ParentSchema, &item.ParentName); err != nil {return nil, err}result = append(result, item)@@ -2010,6 +2053,15 @@ func (s *server) listObjects(schema string, constraints metadataListConstraints)return emptyIfNil(result), rows.Err()}+func metadataIncludesIndexes(objectTypes []string) bool {+ for _, objectType := range normalizedMetadataObjectTypes(objectTypes) {+ if objectType == "INDEX" {+ return true+ }+ }+ return false+}+func (s *server) completionAssistantSearch(request completionAssistantRequest) (completionAssistantResponse, error) {limit := request.MaxResultsif limit <= 0 {@@ -2658,10 +2710,17 @@ func oracleObjectNameCandidates(name string) (string, string, bool) {}func (s *server) getColumns(schema, table string) ([]columnInfo, error) {- schema, err := s.normalizeSchema(schema)+ return s.getColumnsWithIdentity(schema, table, false)+}++func (s *server) getColumnsWithIdentity(schema, table string, exactIdentity bool) ([]columnInfo, error) {+ schema, err := s.metadataSchema(schema, exactIdentity)if err != nil {return nil, err}+ if exactIdentity {+ return s.getColumnsByName(schema, table)+ }exact, uppercase, hasUppercaseFallback := oracleObjectNameCandidates(table)result, err := s.getColumnsByName(schema, exact)if err != nil || len(result) > 0 || !hasUppercaseFallback {@@ -2726,10 +2785,18 @@ ORDER BY c.COLUMN_ID`, []any{schema, table})}func (s *server) getTableComment(schema, table string) (*string, error) {- schema, err := s.normalizeSchema(schema)+ return s.getTableCommentWithIdentity(schema, table, false)+}++func (s *server) getTableCommentWithIdentity(schema, table string, exactIdentity bool) (*string, error) {+ schema, err := s.metadataSchema(schema, exactIdentity)if err != nil {return nil, err}+ if exactIdentity {+ comment, _, err := s.getTableCommentByName(schema, table)+ return comment, err+ }exact, uppercase, hasUppercaseFallback := oracleObjectNameCandidates(table)comment, found, err := s.getTableCommentByName(schema, exact)if err != nil || found || !hasUppercaseFallback {@@ -2801,11 +2868,17 @@ ORDER BY COLUMN_ID`, []any{schema, table})}func (s *server) listIndexes(schema, table string) ([]indexInfo, error) {- schema, err := s.normalizeSchema(schema)+ return s.listIndexesWithIdentity(schema, table, false)+}++func (s *server) listIndexesWithIdentity(schema, table string, exactIdentity bool) ([]indexInfo, error) {+ schema, err := s.metadataSchema(schema, exactIdentity)if err != nil {return nil, err}- table = strings.TrimSpace(table)+ if !exactIdentity {+ table = strings.TrimSpace(table)+ }rows, err := s.queryRows(`SELECT i.INDEX_NAME,ic.COLUMN_NAME,@@ -2816,7 +2889,7 @@ SELECT i.INDEX_NAME,i.VISIBILITY,ic.DESCEND,ie.COLUMN_EXPRESSION,- ic.COLUMN_POSITION+ ic.COLUMN_POSITION, i.OWNERFROM ALL_INDEXES iJOIN ALL_IND_COLUMNS ic ON ic.INDEX_OWNER = i.OWNER AND ic.INDEX_NAME = i.INDEX_NAMEAND ic.TABLE_OWNER = i.TABLE_OWNER AND ic.TABLE_NAME = i.TABLE_NAME@@ -2826,27 +2899,30 @@ LEFT JOIN ALL_CONSTRAINTS pk ON pk.OWNER = i.TABLE_OWNERAND pk.TABLE_NAME = i.TABLE_NAMEAND pk.CONSTRAINT_TYPE = 'P'AND pk.INDEX_NAME = i.INDEX_NAME+ AND pk.INDEX_OWNER = i.OWNERWHERE i.TABLE_OWNER = :1 AND i.TABLE_NAME = :2-ORDER BY i.INDEX_NAME, ic.COLUMN_POSITION`, []any{schema, table})+ORDER BY i.OWNER, i.INDEX_NAME, ic.COLUMN_POSITION`, []any{schema, table})if err != nil {return nil, err}defer s.closeRows(rows)- byName := map[string]*indexInfo{}- order := []string{}+ byName := map[[2]string]*indexInfo{}+ order := [][2]string{}for rows.Next() {- var name, column, uniqueness, indexType, partitioned, visibility, direction string+ var name, column, uniqueness, indexType, partitioned, visibility, direction, owner stringvar expression sql.NullStringvar primary intvar position int- if err := rows.Scan(&name, &column, &uniqueness, &primary, &indexType, &partitioned, &visibility, &direction, &expression, &position); err != nil {+ if err := rows.Scan(&name, &column, &uniqueness, &primary, &indexType, &partitioned, &visibility, &direction, &expression, &position, &owner); err != nil {return nil, err}- item := byName[name]+ identity := [2]string{owner, name}+ item := byName[identity]if item == nil {visible := visibilityitem = &indexInfo{+ Owner: &owner,Name: name,Columns: []string{},IsUnique: uniqueness == "UNIQUE",@@ -2858,8 +2934,8 @@ ORDER BY i.INDEX_NAME, ic.COLUMN_POSITION`, []any{schema, table})Visibility: &visible,KeyMetadataComplete: true,}- byName[name] = item- order = append(order, name)+ byName[identity] = item+ order = append(order, identity)}if position != len(item.Columns)+1 || (direction != "ASC" && direction != "DESC") || (visibility != "VISIBLE" && visibility != "INVISIBLE") || item.Visibility == nil || *item.Visibility != visibility || partitioned != "NO" || (indexType != "NORMAL" && indexType != "FUNCTION-BASED NORMAL") {item.KeyMetadataComplete = false@@ -2886,11 +2962,17 @@ ORDER BY i.INDEX_NAME, ic.COLUMN_POSITION`, []any{schema, table})}func (s *server) listForeignKeys(schema, table string) ([]foreignKeyInfo, error) {- schema, err := s.normalizeSchema(schema)+ return s.listForeignKeysWithIdentity(schema, table, false)+}++func (s *server) listForeignKeysWithIdentity(schema, table string, exactIdentity bool) ([]foreignKeyInfo, error) {+ schema, err := s.metadataSchema(schema, exactIdentity)if err != nil {return nil, err}- table = strings.TrimSpace(table)+ if !exactIdentity {+ table = strings.TrimSpace(table)+ }rows, err := s.queryRows(`SELECT ac.CONSTRAINT_NAME,acc.COLUMN_NAME,@@ -2954,11 +3036,22 @@ func oracleSystemNotNullConstraint(kind string, generated sql.NullString, defini// only contains constraints a user would recognize as such, matching how// tools like DBeaver/Navicat present Oracle constraints.func (s *server) listConstraints(schema, table string) ([]constraintInfo, error) {- schema, err := s.normalizeSchemaForIdentity(schema)+ return s.listConstraintsWithIdentity(schema, table, false)+}++func (s *server) listConstraintsWithIdentity(schema, table string, exactIdentity bool) ([]constraintInfo, error) {+ var err error+ if exactIdentity {+ schema, err = s.metadataSchema(schema, true)+ } else {+ schema, err = s.normalizeSchemaForIdentity(schema)+ }if err != nil {return nil, err}- table = strings.TrimSpace(table)+ if !exactIdentity {+ table = strings.TrimSpace(table)+ }// SEARCH_CONDITION is a LONG column: Oracle rejects LONG values in WHERE// clauses, functions, or ORDER BY (ORA-00932), so it can only appear in// the SELECT list here. The NOT-NULL-check exclusion below is therefore@@ -3148,11 +3241,17 @@ WHERE OWNER = :1 AND TABLE_NAME = :2 AND INDEX_OWNER = :3 AND INDEX_NAME = :4}func (s *server) listTriggers(schema, table string) ([]triggerInfo, error) {- schema, err := s.normalizeSchema(schema)+ return s.listTriggersWithIdentity(schema, table, false)+}++func (s *server) listTriggersWithIdentity(schema, table string, exactIdentity bool) ([]triggerInfo, error) {+ schema, err := s.metadataSchema(schema, exactIdentity)if err != nil {return nil, err}- table = strings.TrimSpace(table)+ if !exactIdentity {+ table = strings.TrimSpace(table)+ }rows, err := s.queryRows(oracleListTriggersSQL, []any{schema, table})if err != nil {return nil, err@@ -3399,8 +3498,12 @@ func (s *server) getTableDDL(schema, table, objectType string) (string, error) {}func (s *server) getTableDDLWithOptions(schema, table, objectType string, portable bool) (string, error) {+ return s.getTableDDLWithIdentity(schema, table, objectType, portable, false)+}++func (s *server) getTableDDLWithIdentity(schema, table, objectType string, portable, exactIdentity bool) (string, error) {var err error- schema, err = s.normalizeSchema(schema)+ schema, err = s.metadataSchema(schema, exactIdentity)if err != nil {return "", err}@@ -3408,7 +3511,7 @@ func (s *server) getTableDDLWithOptions(schema, table, objectType string, portabif err != nil {return "", err}- objectType, table, err = s.resolveDDLObject(schema, table, objectType)+ objectType, table, err = s.resolveDDLObjectWithIdentity(schema, table, objectType, exactIdentity)if err != nil {return "", err}@@ -3447,6 +3550,12 @@ func (s *server) getTableDDLWithOptions(schema, table, objectType string, portabreturn ddl, nil}if objectType == "TABLE" {+ if exactIdentity {+ if err != nil {+ return "", err+ }+ return "", errors.New("exact table DDL is unavailable")+ }fallback, fallbackErr := s.buildTableDDL(schema, table)if fallbackErr != nil {return "", fallbackErr@@ -3654,7 +3763,14 @@ func oracleStringLiteral(value string) string {}func (s *server) resolveDDLObject(schema, name, requested string) (string, string, error) {+ return s.resolveDDLObjectWithIdentity(schema, name, requested, false)+}++func (s *server) resolveDDLObjectWithIdentity(schema, name, requested string, exactIdentity bool) (string, string, error) {exact, uppercase, hasUppercaseFallback := oracleObjectNameCandidates(name)+ if exactIdentity {+ exact, hasUppercaseFallback = name, false+ }objectType := normalizeDDLObjectType(requested)if objectType != "" {return objectType, exact, nildiff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.goindex 7bf537ae8d..d2b7742462 100644--- a/agents/drivers/oracle-go/main_test.go+++ b/agents/drivers/oracle-go/main_test.go@@ -57,6 +57,9 @@ func TestHandshakeResponse(t *testing.T) {if !contains(result.Capabilities, "query") || !contains(result.Capabilities, "metadata") {t.Fatalf("expected query and metadata capabilities, got %v", result.Capabilities)}+ if !contains(result.Capabilities, "exact_metadata_identity_v1") {+ t.Fatal("updated Oracle metadata must explicitly advertise exact identity")+ }}func TestRuntimeHandshakeAdvertisesMultiSessionProtocol(t *testing.T) {@@ -876,14 +879,14 @@ func TestListIndexesSeparatesQuotedCloneTableNamesByCase(t *testing.T) {{queryContains: "FROM ALL_INDEXES",args: []driver.Value{schema, "ORDERS_COPY"},- columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},- rows: [][]driver.Value{{"ORDERS_COPY_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1)}},+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION", "OWNER"},+ rows: [][]driver.Value{{"ORDERS_COPY_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1), "HR"}},},{queryContains: "FROM ALL_INDEXES",args: []driver.Value{schema, "ORDERS_copy"},- columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},- rows: [][]driver.Value{{"ORDERS_copy_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1)}},+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION", "OWNER"},+ rows: [][]driver.Value{{"ORDERS_copy_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1), "HR"}},},})s := newServer()@@ -914,10 +917,10 @@ func TestListIndexesExposesExpressionDirectionAndVisibilityMetadata(t *testing.Tdb, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: "FROM ALL_INDEXES",args: []driver.Value{schema, table},- columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION", "OWNER"},rows: [][]driver.Value{- {"IX_EVENT_EXPR", "SYS_NC00001$", "NONUNIQUE", int64(0), "FUNCTION-BASED NORMAL", "NO", "INVISIBLE", "DESC", `LOWER("EVENT_NAME")`, int64(1)},- {"IX_EVENT_EXPR", "EVENT_TS", "NONUNIQUE", int64(0), "FUNCTION-BASED NORMAL", "NO", "INVISIBLE", "ASC", nil, int64(2)},+ {"IX_EVENT_EXPR", "SYS_NC00001$", "NONUNIQUE", int64(0), "FUNCTION-BASED NORMAL", "NO", "INVISIBLE", "DESC", `LOWER("EVENT_NAME")`, int64(1), " Index Owner "},+ {"IX_EVENT_EXPR", "EVENT_TS", "NONUNIQUE", int64(0), "FUNCTION-BASED NORMAL", "NO", "INVISIBLE", "ASC", nil, int64(2), " Index Owner "},},}})s := newServer()@@ -943,6 +946,7 @@ func TestListIndexesExposesExpressionDirectionAndVisibilityMetadata(t *testing.Tt.Fatal(err)}for key, want := range map[string]any{+ "owner": " Index Owner ","columns": []any{`LOWER("EVENT_NAME")`, "EVENT_TS"},"key_is_expression": []any{true, false},"key_directions": []any{"DESC", "ASC"},@@ -968,8 +972,8 @@ func TestListIndexesMarksUnsupportedShapesIncompleteThroughRPC(t *testing.T) {db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: "FROM ALL_INDEXES",args: []driver.Value{"APP", "EVENTS"},- columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},- rows: [][]driver.Value{{"IX_EVENT", "EVENT_TS", "NONUNIQUE", int64(0), test.indexType, test.partitioned, "VISIBLE", "ASC", nil, int64(1)}},+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION", "OWNER"},+ rows: [][]driver.Value{{"IX_EVENT", "EVENT_TS", "NONUNIQUE", int64(0), test.indexType, test.partitioned, "VISIBLE", "ASC", nil, int64(1), "APP"}},}})s := newServer()s.db = db@@ -986,6 +990,28 @@ func TestListIndexesMarksUnsupportedShapesIncompleteThroughRPC(t *testing.T) {}}+func TestExactIndexesKeepSameNameDifferentOwnersSeparate(t *testing.T) {+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{+ queryContains: "FROM ALL_INDEXES",+ args: []driver.Value{" Parent ", " T(a) "},+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION", "OWNER"},+ rows: [][]driver.Value{+ {" Ix(a) ", "ID", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1), " Owner "},+ {" Ix(a) ", "CODE", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1), "Other"},+ },+ }})+ s := newServer()+ s.db = db+ response, _ := s.handleLine(`{"jsonrpc":"2.0","id":1,"method":"list_indexes","params":{"schema":" Parent ","table":" T(a) ","exact_identity":true}}`)+ if response.Error != nil {+ t.Fatal(response.Error)+ }+ indexes := response.Result.([]indexInfo)+ if len(indexes) != 2 || indexes[0].Owner == nil || *indexes[0].Owner != " Owner " || indexes[1].Owner == nil || *indexes[1].Owner != "Other" || len(indexes[0].Columns) != 1 || len(indexes[1].Columns) != 1 {+ t.Fatalf("owner identity was lost or merged: %#v", indexes)+ }+}+func TestGetTableCommentPreservesQuotedObjectName(t *testing.T) {const schema = "HR"const table = "OrderDetails"@@ -2343,6 +2369,92 @@ func TestListObjectsSQLUsesSplitDictionaryQuery(t *testing.T) {}}+func TestSchemaIndexObjectsPreserveBothOwnersThroughRPC(t *testing.T) {+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "SYS_CONTEXT('USERENV', 'SESSION_USER')", args: []driver.Value{}, rows: [][]driver.Value{{"APP"}}},+ {queryContains: "USER_INDEXES", args: []driver.Value{"INDEX", int64(2), int64(0)}, columns: []string{"OBJECT_NAME", "OBJECT_TYPE", "COMMENTS", "PARENT_SCHEMA", "PARENT_NAME"}, rows: [][]driver.Value{{" Ix (a) ", "INDEX", nil, "Table Owner", " T(a) "}}},+ })+ s := newServer()+ s.db = db+ resp, _ := s.handleLine(`{"id":1,"method":"list_objects","params":{"schema":"APP","object_types":["INDEX"],"limit":2}}`)+ if resp.Error != nil {+ t.Fatalf("list_objects failed: %v", resp.Error)+ }+ data, err := json.Marshal(resp.Result)+ if err != nil {+ t.Fatal(err)+ }+ var objects []map[string]any+ if err := json.Unmarshal(data, &objects); err != nil {+ t.Fatal(err)+ }+ if len(objects) != 1 || objects[0]["schema"] != "APP" || objects[0]["name"] != " Ix (a) " || objects[0]["object_type"] != "INDEX" || objects[0]["parent_schema"] != "Table Owner" || objects[0]["parent_name"] != " T(a) " {+ t.Fatalf("index identities were not preserved: %s", data)+ }+ if scripted.next != len(scripted.steps) {+ t.Fatalf("queries consumed = %d, want %d", scripted.next, len(scripted.steps))+ }+}++func TestSchemaIndexObjectsDoNotReportPGAFailureAsEmpty(t *testing.T) {+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "SYS_CONTEXT('USERENV', 'SESSION_USER')", args: []driver.Value{}, rows: [][]driver.Value{{"APP"}}},+ {queryContains: "FROM USER_TABLES", args: []driver.Value{"INDEX"}, err: errors.New("ORA-04036: PGA memory used by the instance exceeds PGA_AGGREGATE_LIMIT")},+ })+ s := newServer()+ s.db = db+ resp, _ := s.handleLine(`{"id":1,"method":"list_objects","params":{"schema":"APP","object_types":["INDEX"]}}`)+ if resp.Error == nil || !strings.Contains(resp.Error.Message, "ORA-04036") {+ t.Fatalf("dictionary failure must remain an error, got %+v", resp)+ }+}++func TestExactSchemaIndexAllDictionaryPagePreservesMissingParent(t *testing.T) {+ owner := " Index Owner "+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "SYS_CONTEXT('USERENV', 'SESSION_USER')", args: []driver.Value{}, rows: [][]driver.Value{{"Other Owner"}}},+ {queryContains: "ALL_INDEXES", args: []driver.Value{owner, owner, owner, "INDEX", int64(3), int64(1)}, columns: []string{"OBJECT_NAME", "OBJECT_TYPE", "COMMENTS", "PARENT_SCHEMA", "PARENT_NAME"}, rows: [][]driver.Value{{" Ix (a) ", "INDEX", nil, nil, nil}}},+ })+ s := newServer()+ s.db = db+ resp, _ := s.handleLine(`{"id":1,"method":"list_objects","params":{"schema":" Index Owner ","object_types":["INDEX"],"limit":2,"offset":1,"exact_identity":true}}`)+ if resp.Error != nil {+ t.Fatalf("exact ALL dictionary page failed: %v", resp.Error)+ }+ objects := resp.Result.([]objectInfo)+ if len(objects) != 1 || objects[0].Schema != owner || objects[0].Name != " Ix (a) " || objects[0].ParentName != nil || objects[0].ParentSchema != nil || scripted.next != 2 {+ t.Fatalf("page must preserve raw/unknown identities without applying offset twice: %+v", objects)+ }+}++func TestExactMetadataRPCNeverNormalizesOrRetriesANearbyName(t *testing.T) {+ for _, method := range []string{"get_columns", "list_indexes", "get_table_comment", "list_foreign_keys", "list_constraints", "list_triggers"} {+ t.Run(method, func(t *testing.T) {+ query := map[string]string{"get_columns": "FROM ALL_TAB_COLUMNS", "list_indexes": "FROM ALL_INDEXES", "get_table_comment": "FROM ALL_TAB_COMMENTS", "list_foreign_keys": "FROM ALL_CONSTRAINTS", "list_constraints": "FROM ALL_CONSTRAINTS", "list_triggers": "FROM ALL_TRIGGERS"}[method]+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: query, args: []driver.Value{" Mixed Owner ", " T(a) "}}})+ s := newServer()+ s.db = db+ resp, _ := s.handleLine(fmt.Sprintf(`{"id":1,"method":%q,"params":{"schema":" Mixed Owner ","table":" T(a) ","exact_identity":true}}`, method))+ if resp.Error != nil {+ t.Fatalf("exact read failed: %v", resp.Error)+ }+ if scripted.next != 1 {+ t.Fatalf("exact missing target must not retry a nearby name; queries=%d", scripted.next)+ }+ })+ }+}++func TestExactTableDDLDoesNotBuildAnotherTargetAfterMetadataFailure(t *testing.T) {+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: "DBMS_METADATA.GET_DDL", args: []driver.Value{"TABLE", " T(a) ", " Mixed Owner "}, err: errors.New("ORA-01031: insufficient privileges")}})+ s := newServer()+ s.db = db+ resp, _ := s.handleLine(`{"id":1,"method":"get_table_ddl","params":{"schema":" Mixed Owner ","table":" T(a) ","object_type":"TABLE","exact_identity":true}}`)+ if resp.Error == nil || !strings.Contains(resp.Error.Message, "ORA-01031") || scripted.next != 1 {+ t.Fatalf("must preserve exact identity failure without fallback, got %+v after %d queries", resp, scripted.next)+ }+}+func TestListSessionUserObjectsSQLIncludesSequences(t *testing.T) {sqlText := strings.ToUpper(oracleListObjectsSessionUserBaseSQL)if !strings.Contains(sqlText, "FROM USER_OBJECTS") || !strings.Contains(sqlText, "'SEQUENCE'") {diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex fbf3d13a9b..f2d24e150a 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -5592,6 +5592,7 @@ onUnmounted(() => {schema: tab.schema,catalog: tab.catalog,tableName: tab.structureTableName || '',+ exactIdentity: tab.structureExactIdentity,},commentChanged,!!createdTableName,diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vueindex 10ef4d358f..dbb10c0cb0 100644--- a/apps/desktop/src/components/connection/ConnectionDialog.vue+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue@@ -4893,6 +4893,7 @@ function connectionConfigForSshTunnelTest(id: string): ConnectionConfig {function connectionConfigForSubmit(id: string, generatedName = "", validatePluginRequired = true): ConnectionConfig {let config: LegacyConnectionConfig;+ let preserveExistingShowDatabaseLinks = false;if (isPluginConnection.value) {const entry = selectedPluginProvider.value;if (!entry) throw new Error(pluginLoadError.value || t("connection.pluginProviderUnavailable"));@@ -5466,8 +5467,18 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugiconfig.connection_string = config.connection_string?.trim() || JDBCX_DEFAULT_URL;config.jdbc_driver_class = config.jdbc_driver_class?.trim() || JDBCX_JDBC_DRIVER_CLASS;} else {- config.host = "";- config.port = 0;+ const keepsExistingTarget = editingId.value === id && props.editConfig?.id === id && config.db_type === props.editConfig.db_type && config.driver_profile === props.editConfig.driver_profile && config.connection_string === props.editConfig.connection_string;+ if (!keepsExistingTarget) {+ config.host = "";+ config.port = 0;+ } else if (props.editConfig.production_badge_scope == null && config.production_badge_scope === sidebarProductionBadgeScope(props.editConfig)) {+ config.production_badge_scope = undefined;+ }+ preserveExistingShowDatabaseLinks = keepsExistingTarget && !supportsOracleDatabaseLinks(config.db_type);+ if (preserveExistingShowDatabaseLinks) {+ // Generic JDBC has no DB-link toggle; retain the saved target setting.+ config.show_database_links = props.editConfig?.show_database_links;+ }config.connection_string = config.connection_string?.trim() || "";}} else if (config.db_type === "prestosql") {@@ -5541,7 +5552,7 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugiconfig.visible_databases = Array.isArray(config.visible_databases) && config.visible_databases.length > 0 ? config.visible_databases : undefined;}if (!config.show_system_schemas) config.show_system_schemas = undefined;- if (config.show_database_links !== false) config.show_database_links = undefined;+ if (config.show_database_links !== false && !preserveExistingShowDatabaseLinks) config.show_database_links = undefined;if (!config.sidebar_auto_load_all_tables) config.sidebar_auto_load_all_tables = undefined;if (config.visible_schemas && Object.keys(config.visible_schemas).length === 0) config.visible_schemas = undefined;if (config.agent_java_options && config.agent_java_options.length === 0) config.agent_java_options = undefined;diff --git a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.tsindex a86cd982e3..fc1559e4be 100644--- a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts+++ b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts@@ -209,6 +209,47 @@ afterEach(() => {});describe("ConnectionDialog deep-link edit confirmation", () => {+ it("preserves a protected generic JDBC target when only its name changes", async () => {+ const saved = savedConnection({+ db_type: "jdbc",+ driver_profile: "jdbc",+ driver_label: "JDBC",+ host: "db.example.test",+ port: 2881,+ username: "saved-user",+ password: "__DBX_SAVED_CREDENTIAL__:synthetic-password",+ connection_string: "__DBX_SAVED_CREDENTIAL__:synthetic-url",+ jdbc_driver_class: "example.Driver",+ jdbc_driver_paths: ["driver.jar"],+ jdbc_dialect: "oceanbase-oracle",+ production_badge_scope: undefined,+ });+ await mountDialog(saved, "");+ const name = [...document.querySelectorAll<HTMLInputElement>("input")].find((input) => input.value === saved.name);+ expect(name).toBeTruthy();+ name!.value = "Renamed JDBC";+ name!.dispatchEvent(new Event("input", { bubbles: true }));+ await settle();+ const save = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Save");+ save!.click();+ await settle();+ expect(store.updateConnection).toHaveBeenCalledTimes(1);+ const submitted = store.updateConnection.mock.calls[0][0];+ expect(submitted.name).toBe("Renamed JDBC");+ expect(submitted.production_badge_scope).toBeUndefined();+ expect(submitted).toMatchObject({+ db_type: saved.db_type,+ driver_profile: saved.driver_profile,+ host: saved.host,+ port: saved.port,+ username: saved.username,+ password: saved.password,+ connection_string: saved.connection_string,+ jdbc_driver_class: saved.jdbc_driver_class,+ jdbc_driver_paths: saved.jdbc_driver_paths,+ });+ });+it("shows the global Redis preview limit in advanced settings and persists it", async () => {visibleTab.value = "advanced";settings.editorSettings.redisValuePreviewLimitKiB = 64;diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex bcd0359c51..89f758d76c 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -3676,6 +3676,20 @@ defineExpose({:initial-event-open-request-id="activeTab.objectBrowser?.eventOpenRequestId":initial-event-create-request-id="activeTab.objectBrowser?.eventCreateRequestId":initial-object-filter="activeTab.objectBrowser?.initialObjectFilter"+ :initial-index-create-request-id="activeTab.objectBrowser?.indexCreateRequestId"+ :initial-view-target="activeTab.objectBrowser?.initialViewTarget"+ :initial-view-request-id="activeTab.objectBrowser?.initialViewRequestId"+ @index-request-consumed="+ (kind) => {+ if (activeTab.objectBrowser) {+ if (kind === 'create') activeTab.objectBrowser.indexCreateRequestId = undefined;+ else {+ activeTab.objectBrowser.initialViewTarget = undefined;+ activeTab.objectBrowser.initialViewRequestId = undefined;+ }+ }+ }+ ":selected-object-filter="activeTab.objectBrowser?.filter":initial-search-query="activeTab.objectBrowser?.searchQuery":viewport="activeTab.objectBrowser?.viewport"@@ -3702,6 +3716,7 @@ defineExpose({:schema="activeTab.schema":table-name="activeTab.structureTableName || ''":table-type="activeTab.structureTableType"+ :exact-identity="activeTab.structureExactIdentity":initial-tab="activeTab.structureInitialTab":initial-tab-request-id="activeTab.structureInitialTabRequestId":initial-target="activeTab.structureInitialTarget"diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 4df93b100b..bc947806ea 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -81,7 +81,7 @@ import CustomTypeInfoPanel from "@/components/objects/CustomTypeInfoPanel.vue";import TablePartitionsPanel from "@/components/structure/TablePartitionsPanel.vue";import XlsxHeaderDialog from "@/components/export/XlsxHeaderDialog.vue";import * as api from "@/lib/backend/api";-import type { ColumnInfo, ConnectionConfig, ConstraintInfo, ForeignKeyInfo, IndexInfo, ObjectBrowserViewMode, ObjectBrowserViewport, ObjectInfo, ObjectSourceKind, ObjectStatistics, PgTablePartitioning, TableInfoTab, TreeNode, TriggerInfo } from "@/types/database";+import type { ColumnInfo, ConnectionConfig, ConstraintInfo, ForeignKeyInfo, IndexInfo, ObjectBrowserViewMode, ObjectBrowserViewport, ObjectInfo, ObjectSourceKind, ObjectStatistics, PgTablePartitioning, SchemaIndexIdentity, TableInfoTab, TreeNode, TriggerInfo } from "@/types/database";import { sortTablesByFkDependency, type TableWithFk } from "@/lib/table/tableDependencySort";import { isSchemaAware, supportsTableVacuum, supportsTransfer } from "@/lib/database/databaseCapabilities";import { supportsAiAssistantContext, supportsDataDictionary, supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/database/databaseFeatureSupport";@@ -186,7 +186,9 @@ import {} from "@/lib/table/objectBrowserRows";import { isSourceOnlyObjectBrowserRow, resolveRowClickAction, shouldDeferSingleClick, singleClickRowAction, type ObjectBrowserRowAction } from "@/lib/table/objectBrowserRowAction";import { objectBrowserTableSelectionAnchor, objectBrowserTableSelectionRange } from "@/lib/table/objectBrowserSelection";-import { customTypeCapabilities, supportsTypeObjectSource, type SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";+import { customTypeCapabilities, sidebarObjectKindsForDatabase, supportsSchemaIndexManagement, supportsTypeObjectSource, type SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";+import { schemaIndexIdentity, schemaIndexIsSameOwner } from "@/lib/table/schemaIndexNavigation";+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";import { filterObjectBrowserTableColumns } from "@/lib/table/objectBrowserTableInfo";import { visibleMongoCollections } from "@/lib/sidebar/mongoCollectionMutation";import { createSidePanelRequestGuard } from "@/lib/table/sidePanelRequestGuard";@@ -220,7 +222,10 @@ const props = defineProps<{initialEventOpenRequestId?: number;/** 显式"新建事件"请求号:每次菜单点击递增,用于打开/重新进入 CREATE 编辑器 */initialEventCreateRequestId?: number;- initialObjectFilter?: "tables" | "events";+ initialObjectFilter?: "tables" | "events" | "indexes";+ initialIndexCreateRequestId?: number;+ initialViewTarget?: SchemaIndexIdentity;+ initialViewRequestId?: number;selectedObjectFilter?: ObjectFilter;initialSearchQuery?: string;viewport?: ObjectBrowserViewport;@@ -233,6 +238,7 @@ const emit = defineEmits<{viewportChange: [viewport: ObjectBrowserViewport];searchChange: [query: string];filterChange: [filter: ObjectFilter];+ indexRequestConsumed: [kind: "create" | "view"];addToAi: [tables: Array<{ name: string; schema?: string }>];}>();@@ -260,7 +266,7 @@ let objectBrowserUnmounted = false;const rows = ref<ObjectBrowserRow[]>([]);const rootRef = ref<HTMLElement>();const search = ref(props.initialSearchQuery ?? "");-const objectFilter = ref<ObjectFilter>(props.connection.db_type === "oceanbase-oracle" ? (props.selectedObjectFilter ?? props.initialObjectFilter ?? "tables") : "all");+const objectFilter = ref<ObjectFilter>(props.selectedObjectFilter === "indexes" || props.initialObjectFilter === "indexes" ? "indexes" : props.connection.db_type === "oceanbase-oracle" ? (props.selectedObjectFilter ?? props.initialObjectFilter ?? "tables") : "all");const userHasSelectedFilter = ref(false);const sortKey = ref<ObjectBrowserSortKey>("name");const sortDirection = ref<ObjectBrowserSortDirection>("asc");@@ -269,6 +275,7 @@ const loadingObjects = ref(false);const loadingMoreObjects = ref(false);const hasMoreObjects = ref(false);let objectPageOffset = 0;+let indexNextPageAnchor: string | undefined;let objectSearchTimer: ReturnType<typeof setTimeout> | undefined;const refreshingObjects = ref(false);const scaffoldRefreshError = ref("");@@ -288,6 +295,7 @@ const openedInitialEvent = ref("");const isEventEditor = computed(() => sidePanelMode.value === "event-editor");const isSidePanelOpen = computed(() => !!sidePanelRow.value || isEventEditor.value);const sidePanelMode = ref<"table-info" | "source" | "type-info" | "event-editor">("source");+const isSchemaIndexInfo = computed(() => sidePanelMode.value === "table-info" && sidePanelRow.value?.type === "INDEX");const eventEditorKey = computed(() =>eventEditorInstanceKey({createRequestId: props.initialEventCreateRequestId,@@ -311,6 +319,7 @@ const tableDdlLoaded = ref(false);const tableIndexes = ref<IndexInfo[]>([]);const tableIndexesLoading = ref(false);const tableIndexesLoaded = ref(false);+const tableIndexesError = ref("");const tableForeignKeys = ref<ForeignKeyInfo[]>([]);const tableForeignKeysLoading = ref(false);const tableForeignKeysLoaded = ref(false);@@ -355,10 +364,12 @@ let sidePanelResizeStartWidth = 0;const isResizingSidePanel = ref(false);const sidePanelGuard = createSidePanelRequestGuard();const sidePanelRef = ref<InstanceType<typeof CustomTypeInfoPanel> | null>(null);-const tableMetadataCapabilities = computed<TableMetadataCapabilities>(() => getTableMetadataCapabilities(effectiveDatabaseType.value));+const tableMetadataCapabilities = computed<TableMetadataCapabilities>(() => getTableMetadataCapabilities(effectiveDatabaseType.value, { connectionType: props.connection.db_type, exactIdentity: sidePanelRow.value?.type === "INDEX" }));const effectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type);const oracleInvalidObjectsSupported = computed(() => effectiveDatabaseType.value === "oracle" || effectiveDatabaseType.value === "oceanbase-oracle");-const usesServerObjectPaging = computed(() => props.connection.db_type === "oceanbase-oracle");+const supportsSchemaIndexes = computed(() => supportsSchemaIndexManagement(effectiveDatabaseType.value));+const exactIndexList = computed(() => supportsSchemaIndexes.value && objectFilter.value === "indexes");+const usesServerObjectPaging = computed(() => props.connection.db_type === "oceanbase-oracle" || exactIndexList.value);const objectPageSize = computed(() => Math.max(1, Math.min(10_000, Math.floor(settingsStore.desktopSettings?.sidebar_table_page_size || 500))));const isGaussdbM = computed(() => effectiveDatabaseType.value === "gaussdb" && props.connection.driver_profile?.toLowerCase() === "gaussdb-m");@@ -526,6 +537,7 @@ const objectCounts = computed(() => countObjectBrowserRowsByFilter(rows.value));// Count direct search matches once; partition parents rendered only for context must not inflate badges.const objectSearchSummary = computed(() => summarizeObjectBrowserSearch(rows.value, search.value));const canOpenStructureEditor = computed(() => supportsTableStructureEditing(tableStructureDatabaseType.value));+const canCreateSchemaIndex = computed(() => supportsSchemaIndexes.value && !connectionIsEffectivelyReadOnly(props.connection));const canOpenDiagram = computed(() => !!props.database && supportsSchemaDiagram(effectiveDatabaseType.value));const canOpenDataDictionary = computed(() => !!props.database && supportsDataDictionary(effectiveDatabaseType.value));const canOpenTableImport = computed(() => !!props.database && supportsTableImport(effectiveDatabaseType.value));@@ -536,7 +548,7 @@ const sourceDialect = computed(() => codeMirrorSqlDialect(effectiveDatabaseType.const sourceFormatDialect = computed<SqlFormatDialect>(() => sqlFormatDialectForDbType(effectiveDatabaseType.value));const objectFilters = computed<ObjectFilter[]>(() =>usesServerObjectPaging.value- ? ["all", "tables", "views", "procedures", "functions", "sequences", "packages", "types"]+ ? ["all", "tables", "views", "procedures", "functions", "sequences", ...(supportsSchemaIndexes.value ? ["indexes" as const] : []), "packages", "types"]: ([["all", objectCounts.value.all],@@ -548,20 +560,21 @@ const objectFilters = computed<ObjectFilter[]>(() =>["triggers", objectCounts.value.triggers],["events", objectCounts.value.events],["sequences", objectCounts.value.sequences],+ ["indexes", objectCounts.value.indexes],["packages", objectCounts.value.packages],["types", objectCounts.value.types],] as Array<[ObjectFilter, number]>)- .filter(([filter, count]) => filter === "all" || count > 0)+ .filter(([filter, count]) => filter === "all" || count > 0 || (filter === "indexes" && supportsSchemaIndexes.value)).map(([filter]) => filter),);-const showObjectFilter = computed(() => objectFilters.value.length > 2);+const showObjectFilter = computed(() => objectFilters.value.length > 2 || (supportsSchemaIndexes.value && objectFilters.value.includes("indexes")));// A scope that holds a single object kind makes "全部 14" and "表 14" the same number, so the// strip is dropped as redundant — which used to drop the only object count the toolbar could// show at all (t8y2/dbx#11624, the common MySQL "tables only" database). Keep that one kind's// count visible on its own instead; it stays a value, not a filter control, because with a// single kind there is no 全部 chip left for the user to reset the selection back to.-const singleKindFilter = computed<ObjectFilter | null>(() => (objectFilters.value.length === 2 ? (objectFilters.value.find((filter) => filter !== "all") ?? null) : null));+const singleKindFilter = computed<ObjectFilter | null>(() => (!showObjectFilter.value && objectFilters.value.length === 2 ? (objectFilters.value.find((filter) => filter !== "all") ?? null) : null));// Measured condensation for the header row: tier 1 moves the sort/view/checkbox// controls into the overflow menu, tier 2 additionally moves the object type// filter there and drops the database chip. See useToolbarOverflow for the@@ -896,6 +909,7 @@ const selectedTableRows = computed(() => {return selectableRows.value.filter((row) => ids.has(row.id));});const selectedTableCount = computed(() => selectedTableRows.value.length);+const hasSelectedSchemaIndexes = computed(() => selectedTableRows.value.some((row) => row.type === "INDEX"));const hasSelectedTablesOnly = computed(() => selectedTableRows.value.length > 0 && selectedTableRows.value.every((row) => row.type === "TABLE"));const batchDropConfirmTitle = computed(() => (hasSelectedTablesOnly.value ? t("objects.confirmBatchDropTitle") : t("contextMenu.confirmBatchDropTitle")));const batchDropConfirmMessage = computed(() => (hasSelectedTablesOnly.value ? t("objects.confirmBatchDropMessage", { count: selectedTableCount.value }) : t("contextMenu.confirmBatchDropMessage", { count: selectedTableCount.value })));@@ -913,6 +927,7 @@ const allVisibleTablesSelected = computed(() => visibleSelectableRows.value.lengconst batchDropProgressPercent = computed(() => (batchDropProgress.value.total > 0 ? Math.round((batchDropProgress.value.completed / batchDropProgress.value.total) * 100) : 0));function iconFor(row: ObjectBrowserRow) {+ if (row.type === "INDEX") return KeyRound;if (row.type === "VIEW" || row.type === "MATERIALIZED_VIEW") return Eye;if (row.type === "PROCEDURE") return ScrollText;if (row.type === "FUNCTION") return Braces;@@ -925,6 +940,7 @@ function iconFor(row: ObjectBrowserRow) {}function typeLabel(row: ObjectBrowserRow) {+ if (row.type === "INDEX") return t("grid.tableInfoIndexes");if (isMongodb.value) {if (row.collectionKind === "view" || row.type === "VIEW") return t("objects.view");if (row.collectionKind === "timeseries") return t("objects.timeseries");@@ -1044,6 +1060,7 @@ function rowMatchesFilter(row: ObjectBrowserRow, filter: ObjectFilter) {if (filter === "triggers") return row.type === "TRIGGER";if (filter === "events") return row.type === "EVENT";if (filter === "sequences") return row.type === "SEQUENCE";+ if (filter === "indexes") return row.type === "INDEX";if (filter === "packages") return row.type === "PACKAGE" || row.type === "PACKAGE_BODY";if (filter === "types") return row.type === "TYPE" || row.type === "TYPE_BODY";return true;@@ -1151,6 +1168,7 @@ function togglePartitionParent(row: ObjectBrowserRow) {}function canRename(row: ObjectBrowserRow) {+ if (row.type === "INDEX") return false;return (supportsObjectRename(effectiveDatabaseType.value, row.type) ||((effectiveDatabaseType.value === "oracle" || effectiveDatabaseType.value === "oceanbase-oracle") && (row.type === "PROCEDURE" || row.type === "FUNCTION")) ||@@ -1168,6 +1186,12 @@ let singleClickTimer: ReturnType<typeof setTimeout> | null = null;function executeRowAction(row: ObjectBrowserRow, action: ObjectBrowserRowAction) {switch (action) {+ case "index-info":+ void openTableInfo(row, "indexes");+ break;+ case "index-editor":+ openSchemaIndexEditor(row);+ break;case "table-info":void openTableInfo(row);break;@@ -1269,7 +1293,7 @@ const tableInfoTabs = computed<TableInfoTabItem[]>(() => {if (tableMetadataCapabilities.value.partitions && tableIsPartitioned.value) {tabs.push({ id: "partitions", label: t("structureEditor.partitions"), icon: Network, count: tablePartitions.value?.partitions.length });}- return tabs;+ return sidePanelRow.value?.type === "INDEX" ? tabs.filter((tab) => ["info", "ddl", "columns", "indexes"].includes(tab.id)) : tabs;});const tableInfoTabListStyle = computed(() => ({@@ -1337,9 +1361,12 @@ function onTableInfoColumnsKeydown(event: KeyboardEvent) {}const tableOverviewRows = computed(() => {const stats = tableOverviewStats.value;+ const source = sidePanelRow.value;+ const index = source?.type === "INDEX" ? schemaIndexIdentity(source) : null;const rows = [- { label: t("common.table"), value: sidePanelRow.value?.name ?? "" },- { label: t("common.schema"), value: sidePanelRow.value?.schema || selectedSchema.value || props.database },+ ...(index ? [{ label: t("grid.tableInfoIndexes"), value: `${index.schema}.${index.name}` }] : []),+ { label: t("common.table"), value: index ? `${index.parentSchema}.${index.parentName}` : (source?.name ?? "") },+ { label: t("common.schema"), value: index?.parentSchema ?? (source?.schema || selectedSchema.value || props.database) },{ label: t("common.database"), value: props.database },...(sidePanelRow.value?.valid != null ? [{ label: t("objects.validity"), value: t(sidePanelRow.value.valid ? "objects.validStatus" : "objects.invalidStatus") }] : []),{ label: t("structureEditor.comment"), value: tableOverviewComment.value ?? "" },@@ -1368,6 +1395,16 @@ const filteredTableIndexes = computed(() => {return tableIndexes.value.filter((i) => i.name.toLowerCase().includes(q) || i.columns.some((c) => c.toLowerCase().includes(q)));});+function schemaIndexOwner(index: IndexInfo): string | undefined {+ return typeof index.owner === "string" ? index.owner : undefined;+}++function isInitialSchemaIndex(index: IndexInfo): boolean {+ const source = sidePanelRow.value;+ if (source?.type !== "INDEX" || !source.schema || schemaIndexOwner(index) !== source.schema || index.name !== source.name) return false;+ return tableIndexes.value.filter((item) => schemaIndexOwner(item) === source.schema && item.name === source.name).length === 1;+}+const filteredTableForeignKeys = computed(() => {if (!tableInfoSearchQuery.value) return tableForeignKeys.value;const q = tableInfoSearchQuery.value.toLowerCase();@@ -1399,6 +1436,10 @@ const filteredTableDdlContent = computed(() => {});async function openTableInfo(row: ObjectBrowserRow, initialTab?: TableInfoTab) {+ if (row.type === "INDEX" && (!supportsSchemaIndexes.value || !schemaIndexIdentity(row))) {+ toast(t("schemaIndex.parentUnavailable"), 4000);+ return;+ }selectedTableInfoColumns.value = [];selectedRowId.value = row.id;// Toggle off if clicking the same table@@ -1420,6 +1461,7 @@ async function openTableInfo(row: ObjectBrowserRow, initialTab?: TableInfoTab) {tableOverviewLoaded.value = false;rawTableDdlContent.value = "";tableIndexes.value = [];+ tableIndexesError.value = "";tableForeignKeys.value = [];tableTriggers.value = [];tableConstraints.value = [];@@ -1470,16 +1512,20 @@ async function fetchTableOverview(force = false) {const row = sidePanelRow.value;if (!row || (!force && tableOverviewLoaded.value)) return;const epoch = sidePanelGuard.capture();- const schema = row.schema || selectedSchema.value || props.database;+ const request = tableMetadataRequest(row);+ const schema = request.schema;tableOverviewLoading.value = true;try {const [statistics, comment] = await sidePanelGuard.wait(epoch,- Promise.all([api.listObjectStatistics(props.connection.id, props.database, schema).catch(() => [] as ObjectStatistics[]), api.getTableComment(props.connection.id, props.database, schema, row.name, props.catalog).catch(() => null)]),+ Promise.all([+ request.exactIdentity ? Promise.resolve([] as ObjectStatistics[]) : api.listObjectStatistics(props.connection.id, props.database, schema).catch(() => [] as ObjectStatistics[]),+ api.getTableComment(props.connection.id, props.database, schema, request.tableName, props.catalog, ...(request.exactIdentity ? ([true] as const) : [])).catch(() => null),+ ]),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;- tableOverviewStats.value = findTableStatistics(statistics, row.name, schema) ?? null;+ tableOverviewStats.value = findTableStatistics(statistics, request.tableName, schema) ?? null;tableOverviewComment.value = comment;tableOverviewLoaded.value = true;} catch (error) {@@ -1490,14 +1536,17 @@ async function fetchTableOverview(force = false) {}function tableMetadataRequest(row: ObjectBrowserRow): ObjectDdlRequest {+ const index = row.type === "INDEX" ? schemaIndexIdentity(row) : null;+ if (row.type === "INDEX" && !index) throw new Error("Index parent identity is unavailable");return {connectionId: props.connection.id,queryTimeoutSecs: props.connection.query_timeout_secs,database: props.database || "",- schema: row.schema || selectedSchema.value || props.database,- tableName: row.name,- objectType: tableDdlObjectType(row.type),+ schema: index ? index.parentSchema : row.schema || selectedSchema.value || props.database,+ tableName: index ? index.parentName : row.name,+ objectType: index ? undefined : tableDdlObjectType(row.type),catalog: props.catalog,+ ...(index ? { exactIdentity: true } : {}),};}@@ -1535,7 +1584,13 @@ async function fetchTableColumns(force = false) {const request = tableMetadataRequest(row);const { value: columns } = await sidePanelGuard.wait(epoch,- loadObjectMetadataFacet(request, "columns", () => api.getColumns(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog), { force }),+ loadObjectMetadataFacet(+ request,+ "columns",+ () =>+ request.exactIdentity ? api.getColumns(request.connectionId, request.database, request.schema, request.tableName, request.catalog, undefined, undefined, true) : api.getColumns(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog),+ { force },+ ),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;@@ -1558,12 +1613,13 @@ async function fetchTableIndexes(force = false) {if (!row || (tableIndexesLoaded.value && !force)) return;const epoch = sidePanelGuard.capture();tableIndexesLoading.value = true;+ tableIndexesError.value = "";let loadedSuccessfully = false;try {const request = tableMetadataRequest(row);const { value: indexes } = await sidePanelGuard.wait(epoch,- loadObjectMetadataFacet(request, "indexes", () => api.listIndexes(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog), { force }),+ loadObjectMetadataFacet(request, "indexes", () => api.listIndexes(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, ...(request.exactIdentity ? ([true] as const) : [])), { force }),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;@@ -1572,7 +1628,7 @@ async function fetchTableIndexes(force = false) {} catch (error) {if (sidePanelGuard.isStale(epoch)) return;tableIndexes.value = [];- toast(translateBackendError(t, error), 5000);+ tableIndexesError.value = translateBackendError(t, error);} finally {if (sidePanelGuard.isFresh(epoch)) {tableIndexesLoaded.value = loadedSuccessfully;@@ -1591,7 +1647,7 @@ async function fetchTableForeignKeys(force = false) {const request = tableMetadataRequest(row);const { value: fks } = await sidePanelGuard.wait(epoch,- loadObjectMetadataFacet(request, "foreign-keys", () => api.listForeignKeys(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog), { force }),+ loadObjectMetadataFacet(request, "foreign-keys", () => api.listForeignKeys(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, ...(request.exactIdentity ? ([true] as const) : [])), { force }),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;@@ -1619,7 +1675,7 @@ async function fetchTableTriggers(force = false) {const request = tableMetadataRequest(row);const { value: triggers } = await sidePanelGuard.wait(epoch,- loadObjectMetadataFacet(request, "triggers", () => api.listTriggers(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog), { force }),+ loadObjectMetadataFacet(request, "triggers", () => api.listTriggers(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, ...(request.exactIdentity ? ([true] as const) : [])), { force }),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;@@ -1639,7 +1695,7 @@ async function fetchTableTriggers(force = false) {async function probeTablePartitionStatus() {const row = sidePanelRow.value;- if (!row || !tableMetadataCapabilities.value.partitions) {+ if (!row || row.type === "INDEX" || !tableMetadataCapabilities.value.partitions) {tableIsPartitioned.value = false;tablePartitionStatusResolved.value = true;return;@@ -1695,7 +1751,7 @@ async function fetchTableConstraints(force = false) {const request = tableMetadataRequest(row);const { value: constraints } = await sidePanelGuard.wait(epoch,- loadObjectMetadataFacet(request, "constraints", () => api.listConstraints(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog), { force }),+ loadObjectMetadataFacet(request, "constraints", () => api.listConstraints(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, ...(request.exactIdentity ? ([true] as const) : [])), { force }),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;@@ -2116,6 +2172,14 @@ async function executeProcedureSql(sql: string) {}function requestDrop(row: ObjectBrowserRow) {+ if (selectedTableCount.value > 1 && selectedTableIds.value.has(row.id) && selectedTableRows.value.some((item) => item.type === "INDEX")) {+ toast(t("schemaIndex.editIndividually"), 4000);+ return;+ }+ if (row.type === "INDEX") {+ openSchemaIndexEditor(row, "delete");+ return;+ }dropTarget.value = row;dropPreviewSql.value = "";dropTableCascade.value = false;@@ -2312,7 +2376,7 @@ async function refreshRenamePreviewSql() {const requestId = ++renamePreviewRequestId;const row = renameTarget.value;const newName = renameInput.value.trim();- if (!showRenameDialog.value || !row || !newName || newName === row.name) {+ if (!showRenameDialog.value || !row || row.type === "INDEX" || !newName || newName === row.name) {renamePreviewSqlText.value = "";viewRenamePlan.value = undefined;routineRenamePlan.value = undefined;@@ -2479,7 +2543,7 @@ watch([showRenameDialog, renameTarget, renameInput, selectedSchema, () => props.async function confirmRename() {const row = renameTarget.value;let newName = renameInput.value.trim();- if (!row || !newName || newName === row.name) return;+ if (!row || row.type === "INDEX" || !newName || newName === row.name) return;renameError.value = "";const oldPinnedNode = pinnedTreeNodeForObjectBrowserRow(row);const oldLegacyPinnedNodes = legacyPinnedTreeNodesForObjectBrowserRow(row);@@ -2619,6 +2683,7 @@ async function confirmRename() {async function confirmDrop() {if (!dropTarget.value) return;const row = dropTarget.value;+ if (row.type === "INDEX") return;let executedSql = "";const start = Date.now();let successRecorded = false;@@ -2667,6 +2732,7 @@ async function confirmDrop() {}async function buildDropSqlForRow(row: ObjectBrowserRow, options?: { cascade?: boolean }): Promise<string> {+ if (row.type === "INDEX") throw new Error(t("schemaIndex.editIndividually"));if (row.type === "TABLE") {return buildDropTableSql(tableAdminSqlOptions(row, { cascade: options?.cascade && supportsDropTableCascade(effectiveDatabaseType.value) }));}@@ -2760,6 +2826,108 @@ function openStructureEditor(row: ObjectBrowserRow) {queryStore.openTableStructure(props.connection.id, props.database, row.schema || selectedSchema.value, row.name, undefined, undefined, props.catalog);}+function openSchemaIndexEditor(row: ObjectBrowserRow, action?: "delete") {+ if (row.type !== "INDEX" || !supportsSchemaIndexes.value) return;+ const target = schemaIndexIdentity(row);+ if (!target) return;+ if (!schemaIndexIsSameOwner(target) || connectionIsEffectivelyReadOnly(props.connection)) {+ if (!action) void openTableInfo(row, "indexes");+ return;+ }+ queryStore.openTableStructure(props.connection.id, props.database, target.parentSchema, target.parentName, "indexes", { kind: "index", name: target.name, owner: target.schema, ...(action ? { action } : {}) }, props.catalog, "table", true);+}++const showIndexParentPicker = ref(false);+const indexParentTables = ref<string[]>([]);+const indexParentTable = ref("");+const indexParentLoading = ref(false);+const indexParentError = ref("");+const indexParentGuard = createSidePanelRequestGuard();+let loadedIndexParentScope = "";+function indexParentSchema() {+ return selectedSchema.value ?? props.schema ?? objectListSchemaForConnection(props.connection, selectedSchema.value) ?? props.database;+}+function indexParentScope() {+ return JSON.stringify([props.connection.id, props.database, props.catalog, indexParentSchema(), connectionConfigFingerprint(props.connection)]);+}+async function loadIndexParentTables() {+ if (!showIndexParentPicker.value || !canCreateSchemaIndex.value) return;+ const epoch = indexParentGuard.start();+ const scope = indexParentScope();+ const schema = indexParentSchema();+ loadedIndexParentScope = "";+ indexParentLoading.value = true;+ indexParentError.value = "";+ indexParentTables.value = [];+ indexParentTable.value = "";+ try {+ const tables = await indexParentGuard.wait(epoch, api.listTables(props.connection.id, props.database, schema, undefined, undefined, undefined, ["TABLE"], props.catalog, undefined, true), metadataLoadBudgetMs(props.connection.query_timeout_secs));+ if (indexParentGuard.isStale(epoch) || indexParentScope() !== scope) return;+ indexParentTables.value = tables.filter((table) => table.table_type.toUpperCase() === "TABLE").map((table) => table.name);+ loadedIndexParentScope = scope;+ } catch (error) {+ if (indexParentGuard.isFresh(epoch) && indexParentScope() === scope) indexParentError.value = translateBackendError(t, error);+ } finally {+ if (indexParentGuard.isFresh(epoch)) indexParentLoading.value = false;+ }+}+function createSchemaIndex() {+ if (!canCreateSchemaIndex.value) return;+ showIndexParentPicker.value = true;+ void loadIndexParentTables();+}+function confirmIndexParent() {+ if (!showIndexParentPicker.value || !canCreateSchemaIndex.value || indexParentLoading.value || loadedIndexParentScope !== indexParentScope() || !indexParentTables.value.includes(indexParentTable.value)) return;+ queryStore.openTableStructure(props.connection.id, props.database, indexParentSchema(), indexParentTable.value, "indexes", { kind: "index", name: "", action: "create" }, props.catalog, "table", true);+ showIndexParentPicker.value = false;+}+watch(showIndexParentPicker, (open) => {+ if (open) return;+ indexParentGuard.bump();+ indexParentLoading.value = false;+ loadedIndexParentScope = "";+});+watch(+ () => [props.connection.id, props.database, selectedSchema.value, props.catalog, connectionConfigFingerprint(props.connection)],+ () => {+ showIndexParentPicker.value = false;+ indexParentGuard.bump();+ },+);+let consumedIndexCreateRequest = "";+watch(+ () => props.initialIndexCreateRequestId,+ () => {+ if (props.initialIndexCreateRequestId === undefined) return;+ const key = JSON.stringify([props.connection.id, props.database, props.schema, props.initialIndexCreateRequestId]);+ if (consumedIndexCreateRequest === key) return;+ consumedIndexCreateRequest = key;+ const scope = indexParentScope();+ emit("indexRequestConsumed", "create");+ void nextTick(() => {+ if (indexParentScope() === scope) createSchemaIndex();+ });+ },+ { immediate: true },+);+let consumedIndexViewRequest = "";+watch(+ () => [props.initialViewRequestId, props.initialViewTarget],+ () => {+ const target = props.initialViewTarget && schemaIndexIdentity(props.initialViewTarget);+ if (!target || props.initialViewRequestId === undefined || !supportsSchemaIndexes.value) return;+ const key = JSON.stringify([props.connection.id, props.database, target, props.initialViewRequestId]);+ if (consumedIndexViewRequest === key) return;+ consumedIndexViewRequest = key;+ const scope = indexParentScope();+ emit("indexRequestConsumed", "view");+ void nextTick(() => {+ if (indexParentScope() === scope) void openTableInfo({ ...target, id: `index:${JSON.stringify(target)}`, type: "INDEX", displayName: target.name }, "indexes");+ });+ },+ { immediate: true, flush: "post" },+);+function droppedTableObjectTypeForRow(row: ObjectBrowserRow): "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | null {if (row.type === "TABLE") return "TABLE";if (row.type === "VIEW") return "VIEW";@@ -2854,6 +3022,7 @@ function clearTableSelection() {}function openBatchDatabaseExport() {+ if (hasSelectedSchemaIndexes.value) return;const selectedTables = selectedTableRows.value.map((row) => row.name);if (selectedTables.length === 0) return;connectionStore.databaseExportSource = {@@ -2894,6 +3063,10 @@ async function refreshBatchDropPreviewSql() {function requestBatchDropTables() {if (selectedTableCount.value === 0) return;+ if (selectedTableRows.value.some((row) => row.type === "INDEX")) {+ toast(t("schemaIndex.editIndividually"), 4000);+ return;+ }batchDropCascade.value = false;batchDropProgress.value = { completed: 0, total: 0 };batchDropPreviewSql.value = "";@@ -2903,6 +3076,7 @@ function requestBatchDropTables() {async function confirmBatchDropTables() {if (batchDropExecuting.value) return;+ if (selectedTableRows.value.some((row) => row.type === "INDEX")) return;batchDropExecuting.value = true;let batchSql = "";let batchDropRecorded = false;@@ -3472,6 +3646,7 @@ function objectBrowserTableNamesCopyText(rows: readonly ObjectBrowserRow[]): str}async function copySelectedTablesToClipboard() {+ if (hasSelectedSchemaIndexes.value) return;const selectedRows = selectedTableRows.value;if (selectedRows.length === 0) return;connectionStore.treeClipboard = {@@ -3587,6 +3762,20 @@ function openPasteTableDialog() {function onObjectBrowserKeydown(event: KeyboardEvent) {if (event.defaultPrevented) return;+ const selectedIndex = rows.value.find((row) => row.id === selectedRowId.value && row.type === "INDEX");+ const target = event.target;+ if (event.key === "Delete" && target instanceof Element && !target.closest("input, textarea, select, [contenteditable='true']") && selectedTableCount.value > 1 && selectedTableRows.value.some((row) => row.type === "INDEX")) {+ event.preventDefault();+ event.stopPropagation();+ toast(t("schemaIndex.editIndividually"), 4000);+ return;+ }+ if (selectedIndex && target instanceof Element && !target.closest("input, textarea, select, [contenteditable='true']") && (event.key === "Delete" || event.key === "F2")) {+ event.preventDefault();+ event.stopPropagation();+ openSchemaIndexEditor(selectedIndex, event.key === "Delete" ? "delete" : undefined);+ return;+ }if (!supportsBatchTableActions.value) return;if (eventTargetAllowsAppClipboardShortcut(event, "c")) {if (selectedTableCount.value === 0) return;@@ -4099,13 +4288,14 @@ function objectBrowserRowsCacheScope(schema: string): ObjectBrowserRowsCacheScopdatabase: props.database,schema,catalog: props.catalog,+ ...(supportsSchemaIndexes.value ? { exactIdentity: true } : {}),};}function applyObjectBrowserRows(nextRows: ObjectBrowserRow[]) {rows.value = nextRows;- const availableTableIds = new Set(rows.value.filter((row) => row.type === "TABLE").map((row) => row.id));- setSelectedTableIds(new Set([...selectedTableIds.value].filter((id) => availableTableIds.has(id))));+ const availableIds = new Set(selectableRows.value.map((row) => row.id));+ setSelectedTableIds(new Set([...selectedTableIds.value].filter((id) => availableIds.has(id))));expandedPartitionParentIds.value = new Set([...expandedPartitionParentIds.value].filter((id) => rows.value.some((row) => row.id === id && row.partitionCount)));}@@ -4161,7 +4351,7 @@ watch([() => props.initialEventName, () => props.initialEventOpenRequestId, () =// 达梦;oracle/oceanbase-oracle 维持空 schema 由后端解析当前 schema。async function loadObjects(options?: { allowCached?: boolean; preserveExistingRows?: boolean }) {clearTimeout(objectSearchTimer);- if (usesServerObjectPaging.value) return loadObjectPage(false);+ if (usesServerObjectPaging.value) return loadObjectPage(false, options);error.value = "";// A new load supersedes any in-flight one, so reset the transient refresh flags// on entry. A superseded request's finally() can no longer run (the guard's@@ -4239,14 +4429,22 @@ async function loadObjects(options?: { allowCached?: boolean; preserveExistingRo}}-async function loadObjectPage(append: boolean) {- if (append && (loadingObjects.value || loadingMoreObjects.value || !hasMoreObjects.value)) return;- const schema = needsSchema.value ? objectListSchemaForConnection(props.connection, selectedSchema.value) : props.database;+function exactIndexPageAnchor(object: ObjectInfo | undefined): string | undefined {+ return object ? JSON.stringify([object.schema, object.name, object.parent_schema, object.parent_name]) : undefined;+}++async function loadObjectPage(append: boolean, options?: { preserveExistingRows?: boolean }) {+ if (append && (loadingObjects.value || refreshingObjects.value || loadingMoreObjects.value || !hasMoreObjects.value)) return;+ const schema = exactIndexList.value ? indexParentSchema() : needsSchema.value ? objectListSchemaForConnection(props.connection, selectedSchema.value) : props.database;const request = objectBrowserRowsLoadGuard.start(objectBrowserRowsCacheScope(schema));const offset = append ? objectPageOffset : 0;const pageSize = objectPageSize.value;const filter = search.value.trim();const typeFilter = objectFilter.value;+ const exactIdentity = exactIndexList.value;+ const keepExisting = exactIdentity && !append && options?.preserveExistingRows === true && rows.value.length > 0;+ const expectedAnchor = append ? indexNextPageAnchor : undefined;+ const queryTypes = supportsSchemaIndexes.value && typeFilter === "all" ? sidebarObjectKindsForDatabase(effectiveDatabaseType.value).filter((type) => type !== "INDEX") : undefined;const objectTypes: Partial<Record<ObjectFilter, (SidebarObjectKind | "EVENT")[]>> = {tables: ["TABLE"],views: ["VIEW"],@@ -4256,52 +4454,79 @@ async function loadObjectPage(append: boolean) {triggers: ["TRIGGER"],events: ["EVENT"],sequences: ["SEQUENCE"],+ indexes: ["INDEX"],packages: ["PACKAGE", "PACKAGE_BODY"],types: ["TYPE", "TYPE_BODY"],};const isCurrent = () => objectBrowserRowsLoadGuard.isCurrent(request) && search.value.trim() === filter && objectFilter.value === typeFilter;error.value = "";scaffoldRefreshError.value = "";- loadingObjects.value = !append;+ loadingObjects.value = !append && !keepExisting;+ refreshingObjects.value = keepExisting;loadingMoreObjects.value = append;- if (!append) {+ if (!append && !keepExisting) {rows.value = [];hasMoreObjects.value = false;objectPageOffset = 0;+ indexNextPageAnchor = undefined;}try {if (parseSlashDelimitedRegexQuery(filter)) {error.value = t("objects.pagedRegexUnsupported");return;}- const objects = await objectBrowserRowsLoadGuard.wait(- request.epoch,- api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, objectTypes[typeFilter], filter || undefined, pageSize + 1, offset, request.scope.catalog),- metadataLoadBudgetMs(props.connection.query_timeout_secs),- );+ const fetchPage = (pageOffset: number, size: number) =>+ objectBrowserRowsLoadGuard.wait(+ request.epoch,+ exactIdentity+ ? api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, objectTypes[typeFilter], filter || undefined, size + 1, pageOffset, request.scope.catalog, undefined, undefined, true)+ : api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, queryTypes ?? objectTypes[typeFilter], filter || undefined, size + 1, pageOffset, request.scope.catalog),+ metadataLoadBudgetMs(props.connection.query_timeout_secs),+ );+ let objects = await fetchPage(offset, pageSize);if (!isCurrent()) return;- const page = objects.slice(0, pageSize);- const pageRows = buildObjectBrowserRows({ objects: page, database: request.scope.database, fallbackSchema: request.scope.schema, rowSchema: connectionObjectTreeNodeSchema(props.connection, props.database, selectedSchema.value) });- applyObjectBrowserRows(append ? [...rows.value, ...pageRows] : pageRows);- objectPageOffset = offset + page.length;- hasMoreObjects.value = objects.length > pageSize;+ let pageOffset = offset;+ let size = pageSize;+ // Match the sidebar's peek-row contract: a moved offset replaces the whole+ // displayed window instead of appending an overlapping or incomplete page.+ if (exactIdentity && append && expectedAnchor && exactIndexPageAnchor(objects[0]) !== expectedAnchor) {+ pageOffset = 0;+ size = offset + pageSize;+ objects = await fetchPage(pageOffset, size);+ if (!isCurrent()) return;+ }+ const page = objects.slice(0, size);+ const pageRows = buildObjectBrowserRows({+ objects: page.filter((object) => !supportsSchemaIndexes.value || typeFilter !== "all" || object.object_type !== "INDEX"),+ database: request.scope.database,+ fallbackSchema: request.scope.schema,+ rowSchema: connectionObjectTreeNodeSchema(props.connection, props.database, selectedSchema.value),+ });+ applyObjectBrowserRows(append && pageOffset > 0 ? [...rows.value, ...pageRows] : pageRows);+ objectPageOffset = pageOffset + page.length;+ hasMoreObjects.value = objects.length > size;+ indexNextPageAnchor = exactIdentity && hasMoreObjects.value ? exactIndexPageAnchor(objects[size]) : undefined;} catch (e: unknown) {if (!isCurrent()) return;- if (append) scaffoldRefreshError.value = translateBackendError(t, e);+ if (append || keepExisting) scaffoldRefreshError.value = translateBackendError(t, e);else error.value = translateBackendError(t, e);} finally {if (isCurrent()) {loadingObjects.value = false;loadingMoreObjects.value = false;+ refreshingObjects.value = false;if (!append) finishObjectBrowserRowsLoad();}}}async function loadSqlObjectBrowserRows(request: ObjectBrowserRowsLoadHandle) {- const objects: ObjectInfo[] = await api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, undefined, undefined, undefined, undefined, request.scope.catalog);+ // Schema indexes use their dedicated exact, server-paged filter. Mixing an+ // unbounded exact subset into the legacy all view defeats both contracts.+ const types = supportsSchemaIndexes.value ? sidebarObjectKindsForDatabase(effectiveDatabaseType.value).filter((type) => type !== "INDEX") : undefined;+ const objects = await api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, types, undefined, undefined, undefined, request.scope.catalog);return buildObjectBrowserRows({- objects: objects.filter((object) => object.object_type !== "INDEX"),+ objects: objects.filter((object) => !supportsSchemaIndexes.value || object.object_type !== "INDEX"),database: request.scope.database,fallbackSchema: request.scope.schema,rowSchema: connectionObjectTreeNodeSchema(props.connection, props.database, selectedSchema.value),@@ -4407,6 +4632,7 @@ function filterCount(filter: ObjectFilter) {}function filterLabel(filter: ObjectFilter) {+ if (filter === "indexes") return usesServerObjectPaging.value ? t("tree.indexes") : `${t("tree.indexes")} ${filterCount(filter)}`;const key =filter === "tables"? isMongodb.value@@ -4436,12 +4662,20 @@ function filterLabel(filter: ObjectFilter) {function selectObjectFilter(filter: ObjectFilter) {if (filter === objectFilter.value) return;+ const wasPaged = usesServerObjectPaging.value;userHasSelectedFilter.value = true;objectFilter.value = filter;emit("filterChange", filter);- if (usesServerObjectPaging.value) void loadObjects();+ if (wasPaged || usesServerObjectPaging.value) void loadObjects();}+watch(+ () => props.selectedObjectFilter ?? props.initialObjectFilter,+ (filter) => {+ if (filter && (filter === "indexes" || objectFilter.value === "indexes")) selectObjectFilter(filter);+ },+);+function getSearchInput(): HTMLInputElement | null {return rootRef.value?.querySelector<HTMLInputElement>("[data-object-search-input]") ?? null;}@@ -4481,6 +4715,7 @@ function matchesRefreshScope(scope: { schema?: string; catalog?: string }): booldefineExpose({ focusSearch, refresh, matchesRefreshScope });onBeforeUnmount(() => {+ indexParentGuard.bump();objectBrowserUnmounted = true;invalidObjectsDialogGeneration++;invalidObjectSourceRequestGeneration++;@@ -4792,6 +5027,28 @@ function getTypeMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {}function getObjectBrowserActionMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {+ if (item.type === "INDEX") {+ const target = schemaIndexIdentity(item);+ const writable = supportsSchemaIndexes.value && schemaIndexIsSameOwner(target) && !connectionIsEffectivelyReadOnly(props.connection);+ const multiple = selectedTableCount.value > 1 && selectedTableIds.value.has(item.id);+ return [+ ...(target ? [{ label: t("contextMenu.viewDetails"), action: () => void openTableInfo(item, "indexes"), icon: Info }] : [{ label: t("schemaIndex.parentUnavailable"), disabled: true }]),+ ...(writable+ ? [+ { label: t("contextMenu.editStructure"), action: () => openSchemaIndexEditor(item), icon: PencilRuler },+ { label: t(multiple ? "schemaIndex.editIndividually" : "contextMenu.dropIndex"), action: () => (multiple ? toast(t("schemaIndex.editIndividually"), 4000) : openSchemaIndexEditor(item, "delete")), icon: Trash2, variant: "destructive" as const },+ ]+ : []),+ { label: t("contextMenu.copyName"), action: () => copyName(item), icon: Copy },+ {+ label: t("grid.refresh"),+ action: () => {+ refresh();+ },+ icon: RefreshCw,+ },+ ];+ }if (isMongodb.value) {return [{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },@@ -4851,6 +5108,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {<SidebarMenuPreferencesDialog v-if="sidebarMenuPreferences" v-model:open="sidebarMenuPreferencesOpen" :scope="sidebarMenuPreferences.scope" :items="sidebarMenuPreferences.items" /><div v-if="!isEventEditor" ref="toolbarRef" class="flex h-10 shrink-0 items-center gap-2 overflow-hidden border-b px-3"><Button v-if="effectiveDatabaseType === 'firebird'" variant="outline" size="sm" @click="firebirdManagerOpen = true">{{ t("tree.firebirdObjectManager") }}</Button>+ <Button v-if="canCreateSchemaIndex" data-create-schema-index variant="outline" size="sm" class="h-7 shrink-0 gap-1 px-2 text-xs" @click="createSchemaIndex"> <CopyPlus class="h-3.5 w-3.5" />{{ t("structureEditor.addIndex") }} </Button><Button v-if="oracleInvalidObjectsSupported" variant="ghost" size="sm" class="h-7 gap-1.5 px-2 text-xs" @click="setOracleInvalidObjectsOpen(true)">{{ t("processList.oracleInvalidObjects.title") }}</Button><div class="flex min-w-12 items-center gap-2"><span class="inline-flex max-w-[14rem] min-w-0 items-center rounded border border-border bg-muted/50 px-2 py-0.5 text-xs font-medium truncate" :title="selectedSchema || props.database">@@ -5011,11 +5269,11 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {<div class="min-w-0 flex-1 truncate text-muted-foreground">{{ t("objects.selectedTables", { count: selectedTableCount }) }}</div>- <Button v-if="supportsBatchTableActions" variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="openBatchDatabaseExport">+ <Button v-if="supportsBatchTableActions && !hasSelectedSchemaIndexes" variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="openBatchDatabaseExport"><Upload class="mr-1.5 h-3.5 w-3.5" />{{ t("objects.exportSelected") }}</Button>- <Button v-if="supportsBatchTableActions" variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="copySelectedTablesToClipboard">+ <Button v-if="supportsBatchTableActions && !hasSelectedSchemaIndexes" variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="copySelectedTablesToClipboard"><Clipboard class="mr-1.5 h-3.5 w-3.5" />{{ t("objects.copyTableSelected") }}</Button>@@ -5041,14 +5299,14 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {<RefreshCw class="h-3 w-3 shrink-0" /><span class="min-w-0 truncate">{{ scaffoldRefreshError }}</span></div>- <div v-if="loadingObjects" class="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">+ <div v-if="loadingObjects && !isSchemaIndexInfo" class="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("objects.loading") }}</div>- <div v-else-if="error" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-destructive">+ <div v-else-if="error && !isSchemaIndexInfo" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-destructive">{{ error }}</div>- <div v-else-if="filteredRows.length === 0 && !isEventEditor" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">+ <div v-else-if="filteredRows.length === 0 && !isEventEditor && !isSchemaIndexInfo" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">{{ t("objects.empty") }}</div><div v-else class="flex min-h-0 min-w-0 flex-1" :class="{ 'event-editor-layout': isEventEditor }">@@ -5451,9 +5709,11 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {</table></div><div v-else-if="tableInfoTab === 'indexes'" class="flex-1 min-h-0 overflow-auto">+ <p v-if="sidePanelRow?.type === 'INDEX' && tableIndexesLoaded && !tableIndexesError && !tableIndexes.some(isInitialSchemaIndex)" class="border-b px-3 py-2 text-xs text-muted-foreground" data-schema-index-focus-unavailable>{{ t("schemaIndex.focusUnavailable") }}</p><div v-if="tableIndexesLoading" class="h-full flex items-center justify-center"><Loader2 class="w-4 h-4 animate-spin text-muted-foreground" /></div>+ <div v-else-if="tableIndexesError" class="p-3 text-xs text-destructive">{{ tableIndexesError }}</div><div v-else-if="tableInfoSearchQuery && filteredTableIndexes.length === 0" class="p-6 text-center text-xs text-muted-foreground">{{ t("grid.tableInfoNoResults") }}</div>@@ -5461,7 +5721,13 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {{{ t("grid.tableInfoEmpty") }}</div><div v-else class="divide-y">- <div v-for="index in filteredTableIndexes" :key="index.name" class="p-3 text-xs">+ <div+ v-for="(index, ordinal) in filteredTableIndexes"+ :key="JSON.stringify([schemaIndexOwner(index), index.name, ordinal])"+ class="p-3 text-xs"+ :class="{ 'bg-primary/10 ring-1 ring-inset ring-primary/40': isInitialSchemaIndex(index) }"+ :data-schema-index-match="isInitialSchemaIndex(index) || undefined"+ ><div class="flex items-start gap-2"><div class="min-w-0 flex-1"><div class="font-medium truncate">{{ index.name }}</div>@@ -5711,6 +5977,34 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {@reload="validatePackageSaveAsDrafts"@confirm="confirmPackageSaveAs"/>+ <Dialog v-model:open="showIndexParentPicker">+ <DialogContent data-schema-index-parent-picker class="sm:max-w-[420px]">+ <DialogHeader+ ><DialogTitle>{{ t("structureEditor.addIndex") }}</DialogTitle></DialogHeader+ >+ <label class="grid gap-2 text-sm">+ {{ t("structureEditor.tableName") }}+ <SearchableSelect+ data-index-parent-table+ v-model="indexParentTable"+ :options="indexParentTables"+ :loading="indexParentLoading"+ :disabled="indexParentLoading"+ :placeholder="t('dataCompare.selectTable')"+ :search-placeholder="t('dataCompare.searchTable')"+ :empty-text="t('grid.noSearchResults')"+ />+ </label>+ <div v-if="indexParentError" role="alert" class="flex items-center gap-2 text-sm text-destructive">+ <span class="min-w-0 flex-1 break-words">{{ indexParentError }}</span>+ <Button variant="outline" size="sm" @click="loadIndexParentTables">{{ t("common.retry") }}</Button>+ </div>+ <DialogFooter>+ <Button variant="outline" @click="showIndexParentPicker = false">{{ t("common.cancel") }}</Button>+ <Button data-confirm-index-parent :disabled="indexParentLoading || !indexParentTables.includes(indexParentTable) || !!indexParentError" @click="confirmIndexParent">{{ t("common.confirm") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog><Dialog v-model:open="showRenameDialog"><DialogContent:class="(effectiveDatabaseType === 'oracle' || effectiveDatabaseType === 'oceanbase-oracle') && (renameTarget?.type === 'VIEW' || renameTarget?.type === 'PROCEDURE' || renameTarget?.type === 'FUNCTION' || renameTarget?.type === 'TABLE') ? 'sm:max-w-[min(90vw,900px)]' : 'sm:max-w-[420px]'"diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.component.spec.tsindex a51b406a9e..b429e199bc 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.component.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.component.spec.ts@@ -96,7 +96,7 @@ afterEach(() => {invalidateObjectBrowserRowsCache({});});-async function mountBrowser(overrides: Partial<InstanceType<typeof ObjectBrowser>["$props"]> = {}) {+async function mountBrowser(overrides: Partial<InstanceType<typeof ObjectBrowser>["$props"]> = {}, expectedObjectRequests = 1) {const props = reactive({ connection, database: "app", initialEventCreateRequestId: 1 as number | undefined, ...overrides });const browser = ref<InstanceType<typeof ObjectBrowser> | null>(null);const host = document.createElement("div");@@ -104,7 +104,7 @@ async function mountBrowser(overrides: Partial<InstanceType<typeof ObjectBrowserconst app = createApp({ setup: () => () => h(ObjectBrowser, { ...props, ref: browser }) });mountedApps.push({ app, host });app.mount(host);- await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(expectedObjectRequests));await nextTick();return { browser, host, props };}@@ -183,7 +183,7 @@ describe("ObjectBrowser event editor rendering", () => {mocks.listObjects.mockRejectedValue(new Error("objects unavailable"));const { host } = await mountBrowser();- expect(host.textContent).toContain("objects unavailable");+ await vi.waitFor(() => expect(host.textContent).toContain("objects unavailable"));expect(host.querySelector("[data-event-editor]")).toBeNull();});});diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.tsindex 6617067018..bd1e30a369 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.ts@@ -6,9 +6,9 @@ import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import type { ConnectionConfig, ObjectBrowserFilter, ObjectInfo } from "@/types/database";-const mocks = vi.hoisted(() => ({ listObjects: vi.fn(), listSchemas: vi.fn() }));+const mocks = vi.hoisted(() => ({ listObjects: vi.fn(), listSchemas: vi.fn(), listSchemaIndexes: vi.fn().mockResolvedValue([]) }));vi.mock("@/lib/backend/api", () => ({- listObjects: (...args: unknown[]) => mocks.listObjects(...args),+ listObjects: (...args: unknown[]) => (args[10] === true ? mocks.listSchemaIndexes(...args) : mocks.listObjects(...args)),listSchemas: (...args: unknown[]) => mocks.listSchemas(...args),listObjectStatistics: vi.fn().mockResolvedValue([]),}));@@ -132,7 +132,7 @@ describe("OceanBase Oracle object pagination (#11418)", () => {mocks.listObjects.mockResolvedValueOnce([object("O11418_10"), object("O11418_2"), object("O11418_3")]).mockResolvedValueOnce([object("O11418_3")]);const { host } = await mountBrowser();await vi.waitFor(() => expect(host.querySelector('[title="O11418_10"]')).not.toBeNull());- expect(mocks.listObjects).toHaveBeenNthCalledWith(1, connection.id, "APP", "APP", undefined, undefined, 3, 0, undefined);+ expect(mocks.listObjects).toHaveBeenNthCalledWith(1, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), undefined, 3, 0, undefined);expect(host.querySelector('[title="O11418_3"]')).toBeNull();expect(Array.from(host.querySelectorAll('[title^="O11418_"]')).map((el) => el.getAttribute("title"))).toEqual(["O11418_10", "O11418_2"]);@@ -140,7 +140,7 @@ describe("OceanBase Oracle object pagination (#11418)", () => {expect(more).not.toBeNull();more!.click();await vi.waitFor(() => expect(host.querySelector('[title="O11418_3"]')).not.toBeNull());- expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", undefined, undefined, 3, 2, undefined);+ expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), undefined, 3, 2, undefined);expect(host.querySelector("[data-object-load-more]")).toBeNull();});@@ -153,7 +153,7 @@ describe("OceanBase Oracle object pagination (#11418)", () => {await searchObjects(host, "needle");await vi.waitFor(() => expect(host.querySelector('[title="O11418_LATE_VIEW"]')).not.toBeNull());expect(host.querySelector('[title="O11418_1"]')).toBeNull();- expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", undefined, "needle", 3, 0, undefined);+ expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), "needle", 3, 0, undefined);const views = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.trim() === "objects.views");expect(views).toBeDefined();diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.tsnew file mode 100644index 0000000000..da99f605e1--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.ts@@ -0,0 +1,405 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";+import { clearObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";+import { clearMetadataRuntimeCache } from "@/lib/metadata/metadataRuntimeCache";+import type { ConnectionConfig, IndexInfo, ObjectInfo } from "@/types/database";++const mocks = vi.hoisted(() => ({ listObjects: vi.fn(), listTables: vi.fn(), listIndexes: vi.fn(), getColumns: vi.fn(), getTableDdl: vi.fn(), openTableStructure: vi.fn(), executeQuery: vi.fn(), executeBatch: vi.fn(), toolbarTier: 0 }));+vi.mock("@/lib/backend/api", () => ({ ...mocks, listSchemas: vi.fn().mockResolvedValue([" Mixed "]), listObjectStatistics: vi.fn().mockResolvedValue([]), loadSchemaCache: vi.fn().mockResolvedValue(null), saveSchemaCache: vi.fn(), deleteSchemaCachePrefix: vi.fn() }));+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ getConfig: () => connection, ensureConnected: vi.fn().mockResolvedValue(undefined), orderByPinnedTreeNodes: (rows: unknown[]) => rows }) }));+vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({ openTableStructure: mocks.openTableStructure }) }));+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ desktopSettings: { sidebar_table_page_size: 2 }, editorSettings: { shortcuts: { refreshData: "F5" }, objectBrowserViewMode: "list", objectBrowserShowCheckbox: true, sidebarActivation: "double" } }) }));+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key, locale: ref("en-US") }) }));+vi.mock("@/i18n", () => ({ default: { install: () => undefined } }));+vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (sql: string) => sql }) }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));+vi.mock("@/composables/useToolbarOverflow", () => ({ useToolbarOverflow: () => ({ tier: ref(mocks.toolbarTier) }) }));+vi.mock("vue-virtual-scroller", () => ({+ RecycleScroller: defineComponent({+ props: { items: { type: Array, default: () => [] } },+ setup:+ (props, { slots }) =>+ () =>+ h(+ "div",+ props.items.map((item) => slots.default?.({ item })),+ ),+ }),+}));+vi.mock("@/components/ui/searchable-select", () => ({+ SearchableSelect: defineComponent({+ props: ["modelValue", "options"],+ emits: ["update:modelValue"],+ setup:+ (props, { emit, attrs }) =>+ () =>+ h(+ "select",+ { ...attrs, value: props.modelValue, onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value) },+ (props.options ?? []).map((option: string) => h("option", { value: option }, option)),+ ),+ }),+}));+vi.mock("@/components/ui/dialog", () => ({+ Dialog: defineComponent({+ props: ["open"],+ setup:+ (props, { slots }) =>+ () =>+ props.open ? h("div", slots.default?.()) : null,+ }),+ DialogContent: {+ render() {+ return h("div", this.$slots.default?.());+ },+ },+ DialogHeader: {+ render() {+ return h("div", this.$slots.default?.());+ },+ },+ DialogTitle: {+ render() {+ return h("h2", this.$slots.default?.());+ },+ },+ DialogFooter: {+ render() {+ return h("div", this.$slots.default?.());+ },+ },+}));+vi.mock("@/components/editor/QueryEditor.vue", () => ({ default: { render: () => null } }));+vi.mock("@/components/editor/DangerConfirmDialog.vue", () => ({+ default: defineComponent({+ props: ["open"],+ emits: ["confirm"],+ setup:+ (props, { emit }) =>+ () =>+ props.open ? h("button", { "data-danger-confirm": "", onClick: () => emit("confirm") }, "Confirm") : null,+ }),+}));+vi.mock("@/components/objects/ProcedureExecutionDialog.vue", () => ({ default: { render: () => null } }));+vi.mock("@/components/objects/CustomTypeInfoPanel.vue", () => ({ default: { render: () => null } }));+vi.mock("@/components/export/XlsxHeaderDialog.vue", () => ({ default: { render: () => null } }));++const connection = { id: "schema-indexes", db_type: "oceanbase-oracle", name: "fixture", database: "service", transport_layers: [] } as unknown as ConnectionConfig;+const mounted: { app: App; host: HTMLElement }[] = [];+const index = (name: string, parentSchema = " Mixed "): ObjectInfo => ({ name, schema: " Mixed ", object_type: "INDEX", parent_schema: parentSchema, parent_name: ' T(a)" ' });+beforeEach(() => {+ vi.clearAllMocks();+ mocks.listObjects.mockReset().mockResolvedValue([]);+ mocks.listTables.mockReset().mockResolvedValue([{ name: ' T(a)" ', table_type: "TABLE" }]);+ mocks.listIndexes.mockReset().mockResolvedValue([{ name: " Ix(a) ", owner: " Mixed ", columns: ["Id"], is_unique: false, is_primary: false }]);+ mocks.getColumns.mockReset().mockResolvedValue([]);+ mocks.getTableDdl.mockReset().mockResolvedValue("CREATE TABLE parent (id NUMBER)");+ connection.db_type = "oceanbase-oracle";+ mocks.toolbarTier = 0;+ clearObjectBrowserRowsCache();+ clearMetadataRuntimeCache();+});+afterEach(() => {+ for (const { app, host } of mounted.splice(0)) {+ app.unmount();+ host.remove();+ }+});++async function mountBrowser(extra: Record<string, unknown> = {}) {+ const schema = ref(" Mixed ");+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({ setup: () => () => h(ObjectBrowser, { connection, database: "service", schema: schema.value, selectedObjectFilter: "indexes", ...extra }) });+ mounted.push({ app, host });+ app.mount(host);+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalled());+ return { host, schema };+}++describe("schema index browsing and draft navigation", () => {+ it("keeps INDEX selectable in the real overflow menu when the all view is empty", async () => {+ mocks.toolbarTier = 2;+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => (args[10] === true ? [index("EXACT")] : []));+ const { host } = await mountBrowser({ selectedObjectFilter: "all" });+ expect(host.querySelector("[data-object-filter-chips]")).toBeNull();+ const trigger = host.querySelector<HTMLButtonElement>('[aria-label="toolbar.moreActions"]')!;+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ const filter = await vi.waitFor(() => {+ const item = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemcheckbox"]')).find((item) => item.textContent?.trim() === "tree.indexes");+ expect(item).toBeDefined();+ return item!;+ });+ filter.click();+ await vi.waitFor(() => expect(host.querySelector('[title="EXACT"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls.at(-1)?.slice(3, 7)).toEqual([["INDEX"], undefined, 3, 0]);+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ });+ it.each(["empty", "only-indexes"])("keeps the exact INDEX filter clickable from a legacy %s all view", async (kind) => {+ connection.db_type = "oracle";+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => (args[10] === true ? [index("EXACT")] : kind === "empty" ? [] : [index("LEGACY")]));+ const { host } = await mountBrowser({ selectedObjectFilter: "all" });+ const button = await vi.waitFor(() => {+ const filter = Array.from(host.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim().startsWith("tree.indexes"));+ expect(filter).toBeDefined();+ return filter!;+ });+ button.click();+ await vi.waitFor(() => expect(host.querySelector('[title="EXACT"]')).not.toBeNull());+ expect(host.querySelector('[title="LEGACY"]')).toBeNull();+ expect(mocks.listObjects.mock.calls.at(-1)?.slice(3, 7)).toEqual([["INDEX"], undefined, 3, 0]);+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ });+ it.each(["same", "mixed"])("blocks %s batch deletion containing INDEX rows at the browser entry", async (kind) => {+ mocks.listObjects.mockResolvedValue([index("INDEX_A"), kind === "same" ? index("INDEX_B") : { name: "ORDINARY", object_type: "TABLE", schema: " Mixed " }]);+ const { host } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title="INDEX_A"]')).not.toBeNull());+ for (const name of ["INDEX_A", kind === "same" ? "INDEX_B" : "ORDINARY"]) {+ host.querySelector(`[title="${name}"]`)!.parentElement!.parentElement!.querySelector<HTMLButtonElement>("button")!.click();+ }+ await nextTick();+ expect(host.textContent).not.toContain("objects.exportSelected");+ expect(host.textContent).not.toContain("objects.copyTableSelected");+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((button) => button.textContent?.includes("objects.dropSelected"))!+ .click();+ await nextTick();+ expect(host.querySelector("[data-danger-confirm]")).toBeNull();+ expect(mocks.openTableStructure).not.toHaveBeenCalled();+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(mocks.executeBatch).not.toHaveBeenCalled();+ });++ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("keeps %s schema indexes out of the legacy mixed all view", async (type) => {+ connection.db_type = type;+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => (args[10] === true ? [index(" Ix(a) ")] : [{ name: "ORDINARY", schema: " Mixed ", object_type: "TABLE" }, index("LEGACY_WRONG")]));+ const { host } = await mountBrowser({ selectedObjectFilter: "all" });+ await vi.waitFor(() => expect(host.querySelector('[title="ORDINARY"]')).not.toBeNull());+ expect(host.querySelector('[title="ORDINARY"]')).not.toBeNull();+ expect(host.querySelector('[title="LEGACY_WRONG"]')).toBeNull();+ expect(host.querySelector('[title=" Ix(a) "]')).toBeNull();+ expect(mocks.listObjects.mock.calls.every((call) => !call[10] && !call[3]?.includes("INDEX"))).toBe(true);+ });++ it("loads indexes only after choosing the dedicated bounded exact filter", async () => {+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => {+ if (args[10] !== true) return [{ name: "ORDINARY", object_type: "TABLE", schema: " Mixed " }];+ const all = [index("I1"), index("I2"), index("I3"), index("I4")];+ return all.slice(Number(args[6] ?? 0), Number(args[6] ?? 0) + Number(args[5] ?? all.length));+ });+ const { host } = await mountBrowser({ selectedObjectFilter: "all" });+ await vi.waitFor(() => expect(host.querySelector('[title="ORDINARY"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls.some((call) => call[10] === true)).toBe(false);+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((button) => button.textContent === "tree.indexes")!+ .click();+ await vi.waitFor(() => expect(host.querySelector('[title="I2"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls.find((call) => call[10] === true)?.slice(5, 7)).toEqual([3, 0]);+ expect(host.querySelector('[title="I3"]')).toBeNull();+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="I4"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls.filter((call) => call[10] === true)[1]?.slice(5, 7)).toEqual([3, 2]);+ expect(host.querySelectorAll('[title="I1"]')).toHaveLength(1);+ expect(host.querySelector('[title="ORDINARY"]')).toBeNull();+ expect(host.querySelector("[data-object-load-more]")).toBeNull();+ });++ it("keeps ordinary mixed objects available without requesting exact INDEX metadata", async () => {+ connection.db_type = "oracle";+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => {+ if (args[10] === true) throw new Error("exact_metadata_identity_v1 unavailable");+ return [{ name: "ORDINARY", schema: " Mixed ", object_type: "TABLE" }];+ });+ const { host } = await mountBrowser({ selectedObjectFilter: "all" });+ await vi.waitFor(() => expect(host.querySelector('[title="ORDINARY"]')).not.toBeNull());+ expect(host.textContent).not.toContain("exact_metadata_identity_v1 unavailable");+ expect(mocks.listObjects).toHaveBeenCalledTimes(1);+ });++ it("retains selected indexes across append and refresh, but removes disappeared selections", async () => {+ let indexes = [index("I1"), index("I2"), index("I3"), index("I4")];+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => indexes.slice(Number(args[6] ?? 0), Number(args[6] ?? 0) + Number(args[5] ?? indexes.length)));+ const { host } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title="I2"]')).not.toBeNull());+ host.querySelector('[title="I1"]')!.parentElement!.parentElement!.querySelector<HTMLButtonElement>("button")!.click();+ await nextTick();+ expect(host.textContent).toContain("objects.dropSelected");+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="I4"]')).not.toBeNull());+ expect(host.textContent).toContain("objects.dropSelected");+ host.querySelector<HTMLButtonElement>('[title^="grid.refresh"]')!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(3));+ await nextTick();+ expect(host.textContent).toContain("objects.dropSelected");+ indexes = indexes.filter((object) => object.name !== "I1");+ host.querySelector<HTMLButtonElement>('[title^="grid.refresh"]')!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="I1"]')).toBeNull());+ expect(host.textContent).not.toContain("objects.dropSelected");+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ });++ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("%s requests exact typed pages before rendering INDEX rows", async (type) => {+ connection.db_type = type;+ mocks.listObjects.mockResolvedValue([index(" Ix(a) "), index("IX_A_2"), index("third")]);+ const { host } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title=" Ix(a) "]')).not.toBeNull());+ expect(mocks.listObjects).toHaveBeenCalledExactlyOnceWith(connection.id, "service", " Mixed ", ["INDEX"], undefined, 3, 0, undefined, undefined, undefined, true);+ expect(host.querySelector('[title="third"]')).toBeNull();+ expect(host.querySelector("[data-object-load-more]")).not.toBeNull();+ });++ it.each(["insert", "delete"] as const)("refreshes the displayed exact index range after a concurrent %s moves its page anchor", async (change) => {+ const first = [index("I1"), index("I2"), index("I3")];+ const shifted = change === "insert" ? [index("I2"), index("I3"), index("I4")] : [index("I4")];+ const refreshed = change === "insert" ? [index("I0"), ...first, index("I4")] : [index("I2"), index("I3"), index("I4")];+ mocks.listObjects.mockResolvedValueOnce(first).mockResolvedValueOnce(shifted).mockResolvedValueOnce(refreshed);+ const { host } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title="I2"]')).not.toBeNull());+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(3));+ expect(mocks.listObjects.mock.calls[2]?.slice(5, 7)).toEqual([5, 0]);+ const visible = refreshed.slice(0, 4).map((object) => object.name);+ await vi.waitFor(() => expect(Array.from(host.querySelectorAll('[title^="I"]')).map((element) => element.getAttribute("title"))).toEqual(visible));+ expect(host.querySelector("[data-object-load-more]") !== null).toBe(change === "insert");+ });++ it("retains the applicable index list after a failed manual refresh and permits retry", async () => {+ mocks.listObjects+ .mockResolvedValueOnce([index("KEPT")])+ .mockRejectedValueOnce(new Error("index dictionary denied"))+ .mockResolvedValueOnce([index("FRESH")]);+ const { host } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title="KEPT"]')).not.toBeNull());+ host.querySelector<HTMLButtonElement>('[title^="grid.refresh"]')!.click();+ await vi.waitFor(() => expect(host.querySelector('[role="status"]')?.textContent).toContain("index dictionary denied"));+ expect(host.querySelector('[title="KEPT"]')).not.toBeNull();+ host.querySelector<HTMLButtonElement>('[title^="grid.refresh"]')!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="FRESH"]')).not.toBeNull());+ expect(host.querySelector('[title="KEPT"]')).toBeNull();+ expect(host.textContent).not.toContain("index dictionary denied");+ });++ it("creates from an empty index list by choosing an exact visible TABLE, with no DDL", async () => {+ const { host } = await mountBrowser();+ const create = await vi.waitFor(() => {+ const button = host.querySelector<HTMLButtonElement>("[data-create-schema-index]");+ expect(button).not.toBeNull();+ return button!;+ });+ create.click();+ await vi.waitFor(() => expect(mocks.listTables).toHaveBeenCalledExactlyOnceWith(connection.id, "service", " Mixed ", undefined, undefined, undefined, ["TABLE"], undefined, undefined, true));+ const select = host.querySelector<HTMLSelectElement>("[data-index-parent-table]")!;+ await vi.waitFor(() => expect([...select.options].some((option) => option.value === ' T(a)" ')).toBe(true));+ select.value = ' T(a)" ';+ select.dispatchEvent(new Event("change", { bubbles: true }));+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-confirm-index-parent]")!.click();+ expect(mocks.openTableStructure).toHaveBeenCalledExactlyOnceWith(connection.id, "service", " Mixed ", ' T(a)" ', "indexes", { kind: "index", name: "", action: "create" }, undefined, "table", true);+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(mocks.executeBatch).not.toHaveBeenCalled();+ });++ it.each(["empty", "loading", "failed"])("a direct cross-owner view request reads the parent with a %s list and never edits", async (state) => {+ if (state === "loading") mocks.listObjects.mockReturnValue(new Promise(() => {}));+ if (state === "failed") mocks.listObjects.mockRejectedValue(new Error("central list unavailable"));+ const target = { schema: " Mixed ", name: " Ix(a) ", parentSchema: " Other Owner ", parentName: ' T(a)" ' };+ const { host } = await mountBrowser({ initialViewTarget: target, initialViewRequestId: 1 });+ await vi.waitFor(() => expect(mocks.listIndexes).toHaveBeenCalledExactlyOnceWith(connection.id, "service", " Other Owner ", ' T(a)" ', undefined, true));+ expect(host.querySelector("[data-object-table-info-panel]")).not.toBeNull();+ expect(host.querySelector("[data-object-table-structure]")).toBeNull();+ expect(mocks.openTableStructure).not.toHaveBeenCalled();+ });++ it("changing schema retires a pending table picker, without opening a stale draft", async () => {+ let resolve!: (value: unknown[]) => void;+ mocks.listTables.mockReturnValueOnce(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const { host, schema } = await mountBrowser();+ const create = await vi.waitFor(() => {+ const button = host.querySelector<HTMLButtonElement>("[data-create-schema-index]");+ expect(button).not.toBeNull();+ return button!;+ });+ create.click();+ await vi.waitFor(() => expect(mocks.listTables).toHaveBeenCalledOnce());+ schema.value = "OTHER";+ await nextTick();+ resolve([{ name: "STALE", table_type: "TABLE" }]);+ await nextTick();+ expect(host.querySelector("[data-confirm-index-parent]")).toBeNull();+ expect(mocks.openTableStructure).not.toHaveBeenCalled();+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ });++ it("retries a failed parent read and permits cancelling without creating a draft", async () => {+ mocks.listTables.mockRejectedValueOnce(new Error("exact metadata unavailable"));+ const { host } = await mountBrowser();+ host.querySelector<HTMLButtonElement>("[data-create-schema-index]")!.click();+ await vi.waitFor(() => expect(host.querySelector('[role="alert"]')?.textContent).toContain("exact metadata unavailable"));+ expect(host.querySelector<HTMLButtonElement>("[data-confirm-index-parent]")!.disabled).toBe(true);+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((button) => button.textContent === "common.retry")!+ .click();+ await vi.waitFor(() => expect(mocks.listTables).toHaveBeenCalledTimes(2));+ await vi.waitFor(() => expect(host.querySelector('[role="alert"]')).toBeNull());+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((button) => button.textContent === "common.cancel")!+ .click();+ await nextTick();+ expect(host.querySelector("[data-confirm-index-parent]")).toBeNull();+ expect(mocks.openTableStructure).not.toHaveBeenCalled();+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(mocks.executeBatch).not.toHaveBeenCalled();+ });++ it.each([false, true])("ignores a late exact INDEX page after changing Schema (failed: %s)", async (failed) => {+ let release!: (value: ObjectInfo[]) => void;+ let reject!: (error: Error) => void;+ mocks.listObjects.mockResolvedValueOnce([index("FIRST"), index("SECOND"), index("LOOKAHEAD")]);+ mocks.listObjects.mockImplementationOnce(+ () =>+ new Promise<ObjectInfo[]>((resolve, fail) => {+ release = resolve;+ reject = fail;+ }),+ );+ mocks.listObjects.mockResolvedValue([{ ...index("CURRENT", "OTHER"), schema: "OTHER" }]);+ const { host, schema } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title="SECOND"]')).not.toBeNull());+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(2));+ expect(mocks.listObjects.mock.calls[1]?.slice(5, 7)).toEqual([3, 2]);+ schema.value = "OTHER";+ await vi.waitFor(() => expect(host.querySelector('[title="CURRENT"]')).not.toBeNull());+ if (failed) reject(new Error("retired page failure"));+ else release([index("STALE")]);+ await new Promise((resolve) => setTimeout(resolve, 0));+ await nextTick();+ expect(host.querySelector('[title="CURRENT"]')).not.toBeNull();+ expect(host.querySelector('[title="STALE"]')).toBeNull();+ expect(host.textContent).not.toContain("retired page failure");+ });++ it("shows parent indexes without a false match when index owner is absent", async () => {+ mocks.listIndexes.mockResolvedValue([{ name: " Ix(a) ", columns: ["Id"], is_unique: false, is_primary: false }]);+ const { host } = await mountBrowser({ initialViewTarget: { schema: " Mixed ", name: " Ix(a) ", parentSchema: " Other Owner ", parentName: ' T(a)" ' }, initialViewRequestId: 1 });+ await vi.waitFor(() => expect(host.querySelector("[data-schema-index-focus-unavailable]")).not.toBeNull());+ expect(host.querySelector("[data-schema-index-match]")).toBeNull();+ expect(host.querySelector("[data-object-table-structure]")).toBeNull();+ expect(mocks.openTableStructure).not.toHaveBeenCalled();+ });++ it("focuses only the exact dictionary owner among same-name parent indexes", async () => {+ const indexes: IndexInfo[] = [" Mixed ", "Other"].map((owner) => ({ name: " Ix(a) ", owner, columns: ["Id"], is_unique: false, is_primary: false }));+ mocks.listIndexes.mockResolvedValue(indexes);+ const { host } = await mountBrowser({ initialViewTarget: { schema: " Mixed ", name: " Ix(a) ", parentSchema: " Other Owner ", parentName: ' T(a)" ' }, initialViewRequestId: 1 });+ await vi.waitFor(() => expect(host.querySelectorAll("[data-schema-index-match]")).toHaveLength(1));+ expect(host.querySelector("[data-schema-index-focus-unavailable]")).toBeNull();+ expect(mocks.openTableStructure).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.tsindex 1f706443da..96fb3dac6d 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.ts@@ -1,6 +1,6 @@// @vitest-environment happy-dom-import { createApp, defineComponent, h, ref, type App } from "vue";+import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";@@ -81,7 +81,7 @@ const mountedApps: Array<{ app: App; host: HTMLElement }> = [];beforeEach(() => {vi.clearAllMocks();- mocks.listObjects.mockResolvedValue([{ name: "TEST2026", object_type: "TABLE" }]);+ mocks.listObjects.mockImplementation(async (...args: unknown[]) => (args[10] === true ? [] : [{ name: "TEST2026", object_type: "TABLE" }]));mocks.ensureConnected.mockResolvedValue(undefined);invalidateObjectBrowserRowsCache({});});@@ -111,7 +111,9 @@ describe("ObjectBrowser with a slow schema list", () => {const host = await mountBrowser();await vi.waitFor(() => expect(host.textContent).toContain("TEST2026"));- expect(mocks.listObjects).toHaveBeenCalledWith("dameng-slow-schemas", "TEST", "TEST", undefined, undefined, undefined, undefined, undefined);+ // Schema index metadata is read only in the dedicated paged filter.+ expect(mocks.listObjects).toHaveBeenCalledWith("dameng-slow-schemas", "TEST", "TEST", expect.arrayContaining(["TABLE", "VIEW"]), undefined, undefined, undefined, undefined);+ expect(mocks.listObjects).toHaveBeenCalledTimes(1);expect(mocks.listSchemas).toHaveBeenCalledWith("dameng-slow-schemas", "TEST");expect(host.textContent).not.toContain("objects.empty");});@@ -124,6 +126,8 @@ describe("ObjectBrowser with a slow schema list", () => {await vi.waitFor(() => expect(host.textContent).toContain("TEST2026"));resolveSchemas(["TEST", "OTHER"]);- await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(1));+ await Promise.resolve();+ await nextTick();+ expect(mocks.listObjects).toHaveBeenCalledTimes(1);});});diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.tsindex fe908be3a9..4ec823a2a2 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts@@ -341,8 +341,9 @@ describe("ObjectBrowser view source save", () => {if (prefix === ddlPrefix) await new Promise<void>((resolve) => (release = resolve));});const { host } = await mountOracleBrowserWithSchema();- const scope = { connectionId: oracleConnection.id, database: "ORCL", schema: "APP_A" };+ const scope = { connectionId: oracleConnection.id, database: "ORCL", schema: "APP_A", exactIdentity: true };expect(getCachedObjectBrowserRows(scope)).toBeDefined();+ expect(getCachedObjectBrowserRows({ ...scope, exactIdentity: false })).toBeUndefined();const listCalls = mocks.listObjects.mock.calls.length;[...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();await nextTick();diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 86536c86af..c6bf9b966a 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -163,7 +163,8 @@ import {treeNodeRowDoubleClickAction,} from "@/lib/sidebar/treeNodeClick";import { qualifiedNameForSidebarNode } from "@/lib/sidebar/sidebarTableNameCopy";-import { customTypeCapabilities, supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";+import { customTypeCapabilities, supportsTypeObjectSource, supportsSchemaIndexManagement } from "@/lib/database/databaseObjectCapabilities";+import { schemaIndexIsSameOwner, schemaIndexNodeIdentity } from "@/lib/table/schemaIndexNavigation";import { mongoCollectionTableTypeFromNode, mongoCreateDatabasePreview, mongoDropIndexFailureCount } from "@/lib/sidebar/mongoCollectionMutation";import { dataTabOpenModeFromTreeClick, type DataTabOpenMode } from "@/lib/sidebar/dataTabOpenPolicy";import { isCopySidebarSelectionShortcut, isDisconnectSidebarConnectionShortcut, isEditSidebarConnectionShortcut, isEditSidebarTableStructureShortcut, isModRShortcut, isPasteSidebarSelectionShortcut, isRefreshDataShortcut } from "@/lib/editor/keyboardShortcuts";@@ -824,6 +825,7 @@ function hasNodeDatabaseContext(node: TreeNode): node is TreeNode & { connectionconst groupTypes: Set<TreeNodeType> = new Set(["group-columns","group-indexes",+ "group-database-indexes","group-fkeys","group-triggers","group-events",@@ -1987,6 +1989,47 @@ async function openObjectBrowser(eventReadOnly = false, openEventEditor: boolean}}+function isSchemaIndexNode(node: TreeNode): boolean {+ return node.type === "index" && node.objectScope === "schema";+}++function canEditSchemaIndex(node: TreeNode): boolean {+ return !!node.connectionId && !!node.database && supportsSchemaIndexManagement(databaseTypeForNode(node)) && schemaIndexIsSameOwner(schemaIndexNodeIdentity(node)) && !connectionIsEffectivelyReadOnly(connectionStore.getConfig(node.connectionId));+}++function openSchemaIndexInfo(node: TreeNode) {+ const target = schemaIndexNodeIdentity(node);+ if (!target || !node.connectionId || !node.database || !supportsSchemaIndexManagement(databaseTypeForNode(node))) return;+ queryStore.openObjectBrowser(node.connectionId, node.database, target.schema, node.catalog, undefined, false, "indexes", undefined, { view: target });+}++async function openSchemaIndexCreate() {+ const node = activeNode.value;+ if (node.type !== "group-database-indexes" || !node.connectionId || !node.database || !supportsSchemaIndexManagement(databaseTypeForNode(node)) || connectionIsEffectivelyReadOnly(connectionStore.getConfig(node.connectionId))) return;+ try {+ await connectionStore.ensureConnected(node.connectionId);+ queryStore.openObjectBrowser(node.connectionId, node.database, node.schema, node.catalog, undefined, false, "indexes", undefined, { create: true });+ } catch (error) {+ toast(translateBackendError(t, error), 5000);+ }+}++function requestSchemaIndexDelete(node: TreeNode): boolean {+ const target = schemaIndexNodeIdentity(node);+ if (!canEditSchemaIndex(node) || !target || !node.connectionId || !node.database) return false;+ queryStore.openTableStructure(node.connectionId, node.database, target.parentSchema, target.parentName, "indexes", { kind: "index", name: target.name, owner: target.schema, action: "delete" }, node.catalog, "table", true);+ return true;+}++function hasSchemaIndexBatchSelection(): boolean {+ const selected = selectedTreeNodesInVisibleOrder();+ return selected.length > 1 && selected.some((node) => node.id === activeNode.value.id) && selected.some(isSchemaIndexNode);+}++function explainIndividualIndexEditing() {+ toast(t("schemaIndex.editIndividually"), 4000);+}+// 每次"新建事件"菜单点击都会分配一个单调递增的请求号,保证同一个// ObjectBrowser tab 被复用时也能重新进入 MySQL Event 的 CREATE 编辑器。let mysqlEventCreateRequestSeq = 0;@@ -2916,6 +2959,8 @@ function dropTableChildObjectSqlOptions(): DropTableChildObjectSqlOptions | null}function dropTableChildObjectSqlOptionsForNode(node: TreeNode): DropTableChildObjectSqlOptions | null {+ // Schema indexes must use the structure editor's preflight and readback.+ if (isSchemaIndexNode(node)) return null;const objectType = tableChildDropObjectType(node.type);if (!objectType || !node.tableName) return null;const name = tableChildDropObjectName(node).trim();@@ -3232,6 +3277,10 @@ function requestDropObject() {}function requestDropTableChildObject() {+ if (isSchemaIndexNode(activeNode.value)) {+ requestSchemaIndexDelete(activeNode.value);+ return;+ }if (!canDropTableChildObject.value) return;void refreshDropTableChildObjectPreviewSql();showDropTableChildObjectConfirm.value = true;@@ -3455,6 +3504,10 @@ async function refreshBatchEmptyPreviewSql(targets: TreeNode[]) {}function requestBatchDrop() {+ if (hasSchemaIndexBatchSelection()) {+ explainIndividualIndexEditing();+ return;+ }const targets = selectedBatchDropTargets();if (!targets.length) return;batchDropTargets.value = targets.slice();@@ -3571,6 +3624,10 @@ async function confirmBatchMysqlAutoIncrement() {}function requestDropSelectedNodes(): boolean {+ if (hasSchemaIndexBatchSelection()) {+ explainIndividualIndexEditing();+ return true;+ }const selected = selectedTreeNodesInVisibleOrder();if (selected.length > 1 && selected.some((node) => node.id === activeNode.value.id)) {if (!selectedBatchDropTargets().length) return false;@@ -3581,6 +3638,7 @@ function requestDropSelectedNodes(): boolean {}function requestDropSelectedNode(): boolean {+ if (isSchemaIndexNode(activeNode.value)) return requestSchemaIndexDelete(activeNode.value);if (["neo4j", "nebula"].includes(currentDatabaseType() || "")) return false;if (activeNode.value.type === "table") {dropTable();@@ -4312,6 +4370,11 @@ async function confirmDropTableChildObject() {async function confirmBatchDrop() {const targets = batchDropTargets.value.slice();if (!targets.length) return;+ if (targets.some(isSchemaIndexNode)) {+ showBatchDropConfirm.value = false;+ explainIndividualIndexEditing();+ return;+ }try {const mongoIndexTargets = targets.filter(canDropMongoIndexNode);if (mongoIndexTargets.length) {@@ -5839,6 +5902,7 @@ const canOpenTableImport = computed(() => {});const canOpenStructureEditor = computed(() => {+ if (isSchemaIndexNode(activeNode.value)) return supportsSchemaIndexManagement(currentDatabaseType()) && !!schemaIndexNodeIdentity(activeNode.value);return sidebarNodeSupportsStructureEdit(activeNode.value, currentTableStructureDatabaseType());});@@ -7671,6 +7735,20 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {return true;}+ if (isSchemaIndexNode(node)) {+ items.push({ label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });+ if (!schemaIndexNodeIdentity(node)) items.push({ label: t("schemaIndex.parentUnavailable"), disabled: true });+ if (schemaIndexNodeIdentity(node) && supportsSchemaIndexManagement(currentDatabaseType())) {+ items.push({ label: t("contextMenu.viewObject"), action: () => openSchemaIndexInfo(node), icon: Eye });+ }+ if (canEditSchemaIndex(node)) {+ items.push({ label: t("contextMenu.editIndex"), action: openStructureEditor, icon: PencilRuler });+ items.push({ label: deleteMenuLabel(t("contextMenu.dropIndex")), action: deleteMenuAction(() => requestSchemaIndexDelete(node)), icon: Trash2, shortcut: shortcutDelete, variant: "destructive" as const });+ }+ items.push({ label: t("contextMenu.refreshChildren"), action: refresh, icon: RefreshCw, shortcut: shortcutRefresh.value });+ return true;+ }+if (node.type === "index" || node.type === "fkey" || (node.type === "trigger" && !!node.tableName)) {items.push(node.type === "trigger" || node.type === "index" ? copyNameMenuItem() : { label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });if (node.type === "trigger") {@@ -7881,7 +7959,8 @@ function buildObjectGroupSidebarMenu(context: SidebarMenuFactoryContext): booleaconst hasMongoDropAllIndexesAction = node.type === "group-indexes" && canDropAllMongoIndexes.value;const canCreateGroupView = node.type === "group-views" && !!node.connectionId && !!node.database && !["neo4j", "nebula"].includes(currentDatabaseType() || "");const canCreateTableGroup = isTableVGroupContainerNode(node);- const hasGroupAction = (node.type === "group-tables" && canCreateTable.value) || canCreateTableGroup || canCreateGroupView || !!objectTemplate || hasMongoCreateIndexAction || hasMongoDropAllIndexesAction;+ const canCreateSchemaIndex = node.type === "group-database-indexes" && supportsSchemaIndexManagement(currentDatabaseType()) && !connectionIsEffectivelyReadOnly(connectionStore.getConfig(node.connectionId || ""));+ const hasGroupAction = (node.type === "group-tables" && canCreateTable.value) || canCreateTableGroup || canCreateGroupView || !!objectTemplate || hasMongoCreateIndexAction || hasMongoDropAllIndexesAction || canCreateSchemaIndex;const canLoadAllObjectGroup = node.type === "group-tables" || node.type === "group-dolt-system-tables" || node.type === "group-views" || node.type === "group-materialized-views";if (node.type === "group-tables" && canCreateTable.value) {items.push({ label: t("contextMenu.createTable"), action: createTable, icon: Plus });@@ -7889,6 +7968,9 @@ function buildObjectGroupSidebarMenu(context: SidebarMenuFactoryContext): booleaif (canCreateGroupView) {items.push({ label: t("contextMenu.createView"), action: createView, icon: Plus });}+ if (canCreateSchemaIndex) {+ items.push({ label: t("structureEditor.addIndex"), action: openSchemaIndexCreate, icon: Plus });+ }if (node.type === "group-events" && node.connectionId && node.database) {items.push({ label: t("contextMenu.createEvent"), action: openMysqlEventCreateEditor, icon: Plus });}@@ -8049,8 +8131,9 @@ function treeItemMenuItems(): ContextMenuItem[] {const batchEmptyCount = selectedBatchEmptyTargets().length;const batchTruncateCount = selectedBatchTruncateTargets().length;const batchAutoIncrementCount = selectedBatchMysqlAutoIncrementTargets().length;- const deleteMenuLabel = (singleLabel: string) => (batchDropCount > 1 ? batchDropMenuLabel() : singleLabel);- const deleteMenuAction = (singleAction: () => void) => (batchDropCount > 1 ? requestBatchDrop : singleAction);+ const individualIndexes = hasSchemaIndexBatchSelection();+ const deleteMenuLabel = (singleLabel: string) => (individualIndexes ? t("schemaIndex.editIndividually") : batchDropCount > 1 ? batchDropMenuLabel() : singleLabel);+ const deleteMenuAction = (singleAction: () => void) => (individualIndexes ? explainIndividualIndexEditing : batchDropCount > 1 ? requestBatchDrop : singleAction);const truncateMenuLabel = (singleLabel: string) => (batchTruncateCount > 1 ? batchTruncateMenuLabel() : singleLabel);const truncateMenuAction = (singleAction: () => void) => (batchTruncateCount > 1 ? requestBatchTruncate : singleAction);const emptyMenuLabel = (singleLabel: string) => (batchEmptyCount > 1 ? batchEmptyMenuLabel() : singleLabel);diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vueindex 193fe5f75d..3bcd000baa 100644--- a/apps/desktop/src/components/sidebar/TreeItem.vue+++ b/apps/desktop/src/components/sidebar/TreeItem.vue@@ -1722,6 +1722,7 @@ function onKeydown(event: KeyboardEvent) {node.type === 'group-udf-functions' ||node.type === 'group-columns' ||node.type === 'group-indexes' ||+ node.type === 'group-database-indexes' ||node.type === 'group-fkeys' ||node.type === 'group-triggers' ||node.type === 'group-events' ||diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.schemaIndexes.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.schemaIndexes.spec.tsnew file mode 100644index 0000000000..a0a5e50c98--- /dev/null+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.schemaIndexes.spec.ts@@ -0,0 +1,166 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, ref, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";+import type { ConnectionConfig, DatabaseType, TreeNode } from "@/types/database";++const api = vi.hoisted(() => ({ executeQuery: vi.fn(), executeBatch: vi.fn(), buildDropTableChildObjectSql: vi.fn().mockResolvedValue("DROP INDEX unsafe") }));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<object>()), ...api, listPlugins: vi.fn().mockResolvedValue([]), saveSidebarLayout: vi.fn().mockResolvedValue(undefined) }));+import SidebarTreeRuntimeHost from "../SidebarTreeRuntimeHost.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import { useQueryStore } from "@/stores/queryStore";+import { showDropTableChildObjectConfirm, showBatchDropConfirm, batchDropTargets } from "../sidebarTreeDialogState";++const mounted: { app: App; container: HTMLElement }[] = [];+const tr = (key: string) => i18n.global.t(key);+const indexNode = (extra: Partial<TreeNode> = {}): TreeNode => ({+ id: "index-1",+ type: "index",+ objectScope: "schema",+ label: " Ix (a) (display only)",+ objectName: " Ix (a) ",+ connectionId: "c",+ database: "service",+ schema: " Owner ",+ parentSchema: " Owner ",+ parentName: " T (1) ",+ tableName: " T (1) ",+ ...extra,+});+beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ showDropTableChildObjectConfirm.value = false;+ showBatchDropConfirm.value = false;+ batchDropTargets.value = [];+});+afterEach(() => {+ for (const { app, container } of mounted.splice(0)) {+ app.unmount();+ container.remove();+ }+});++async function mountHost(node: TreeNode, dbType: DatabaseType = "oracle", readOnly = false) {+ const pinia = createPinia();+ setActivePinia(pinia);+ const store = useConnectionStore();+ store.connections = [{ id: "c", name: "Index test", db_type: dbType, database: "service", username: "OWNER", read_only: readOnly } as ConnectionConfig];+ store.connectedIds.add("c");+ store.treeNodes = [node];+ store.selectedTreeNodeId = node.id;+ store.selectedTreeNodeIds = [node.id];+ vi.spyOn(store, "ensureConnected").mockResolvedValue(undefined);+ const queries = useQueryStore();+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);+ const danger: { confirm: () => Promise<unknown> }[] = [];+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp({+ setup: () => () =>+ h(SidebarTreeRuntimeHost, {+ ref: host,+ node,+ depth: 0,+ onOpenDangerDialog: (request: any) => {+ danger.push(request);+ },+ }),+ })+ .use(pinia)+ .use(i18n);+ app.mount(container);+ mounted.push({ app, container });+ await nextTick();+ return { host: host.value!, store, queries, danger };+}++it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("opens an empty %s Schema index group for creation without DDL", async (dbType) => {+ const node = indexNode({ id: "group", type: "group-database-indexes", objectScope: undefined, tableName: undefined, parentName: undefined, parentSchema: undefined });+ const { host, queries } = await mountHost(node, dbType);+ const item = host.buildContextMenu(node).find((entry: ContextMenuItem) => entry.label === tr("structureEditor.addIndex"));+ expect(item).toBeDefined();+ await item?.action?.();+ expect(queries.tabs.at(-1)).toMatchObject({ mode: "objects", database: "service", objectBrowser: { schema: " Owner ", initialObjectFilter: "indexes", indexCreateRequestId: expect.any(Number) } });+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeBatch).not.toHaveBeenCalled();+});++it("routes menu, double click and Delete to one exact parent draft, never the generic DROP consumer", async () => {+ const node = indexNode();+ const { host, queries, danger } = await mountHost(node);+ host.handleRowDoubleClick(node, new MouseEvent("dblclick"));+ await nextTick();+ expect(queries.tabs.at(-1)).toMatchObject({ mode: "structure", schema: " Owner ", structureTableName: " T (1) ", structureExactIdentity: true, structureInitialTarget: { kind: "index", name: " Ix (a) ", owner: " Owner " } });+ host+ .buildContextMenu(node)+ .find((entry: ContextMenuItem) => entry.label === tr("contextMenu.dropIndex"))+ ?.action?.();+ await nextTick();+ expect(queries.tabs).toHaveLength(1);+ expect(queries.tabs[0]?.structureInitialTarget).toMatchObject({ name: " Ix (a) ", owner: " Owner ", action: "delete" });+ expect(showDropTableChildObjectConfirm.value).toBe(false);+ host.handleRowKeydown(node, new KeyboardEvent("keydown", { key: "Delete" }));+ await nextTick();+ expect(queries.tabs[0]?.structureInitialTarget).toMatchObject({ action: "delete" });+ expect(danger).toHaveLength(0);+ showDropTableChildObjectConfirm.value = true;+ await nextTick();+ await danger.at(-1)?.confirm();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeBatch).not.toHaveBeenCalled();+});++it.each([{ parentSchema: "Other Owner" }, { parentSchema: undefined }, { parentName: undefined }])("blocks destructive paths for a cross-owner or unknown-parent index %j", async (extra) => {+ const node = indexNode(extra);+ const { host, queries, danger } = await mountHost(node);+ const menu = host.buildContextMenu(node);+ expect(menu.some((entry: ContextMenuItem) => entry.label === tr("contextMenu.dropIndex") || entry.label === tr("contextMenu.editIndex"))).toBe(false);+ host.handleRowKeydown(node, new KeyboardEvent("keydown", { key: "Delete" }));+ await nextTick();+ expect(showDropTableChildObjectConfirm.value).toBe(false);+ expect(queries.tabs).toHaveLength(0);+ expect(danger).toHaveLength(0);+ if (extra.parentSchema) {+ host.handleRowDoubleClick(node, new MouseEvent("dblclick"));+ await nextTick();+ expect(queries.tabs.at(-1)).toMatchObject({ mode: "objects", objectBrowser: { initialViewTarget: { name: " Ix (a) ", parentSchema: "Other Owner", parentName: " T (1) " } } });+ }+ expect(api.executeQuery).not.toHaveBeenCalled();+});++it.each(["same", "mixed"])("does not batch DROP a %s selection containing a Schema index, including stale confirmation", async (kind) => {+ const first = indexNode();+ const second = kind === "same" ? indexNode({ id: "index-2", objectName: "OTHER" }) : indexNode({ id: "table", type: "table", objectScope: undefined, label: "OTHER" });+ const { host, store, danger } = await mountHost(first);+ store.treeNodes = [first, second];+ store.selectedTreeNodeIds = [first.id, second.id];+ const menu = host.buildContextMenu(first);+ menu.find((entry: ContextMenuItem) => entry.variant === "destructive")?.action?.();+ await nextTick();+ expect(showBatchDropConfirm.value).toBe(false);+ expect(showDropTableChildObjectConfirm.value).toBe(false);+ host.handleRowKeydown(first, new KeyboardEvent("keydown", { key: "Delete" }));+ await nextTick();+ expect(showBatchDropConfirm.value).toBe(false);+ expect(danger).toHaveLength(0);+ batchDropTargets.value = [first, second];+ showBatchDropConfirm.value = true;+ await nextTick();+ await danger.at(-1)?.confirm();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeBatch).not.toHaveBeenCalled();+});++it("keeps the existing table-child index deletion contract", async () => {+ const node = indexNode({ objectScope: undefined, schema: "OWNER", label: "IX_OLD", objectName: "IX_OLD", tableName: "T" });+ const { host, danger } = await mountHost(node, "firebird");+ host+ .buildContextMenu(node)+ .find((entry: ContextMenuItem) => entry.label === tr("contextMenu.dropIndex"))+ ?.action?.();+ await nextTick();+ expect(danger).toHaveLength(1);+});diff --git a/apps/desktop/src/components/sidebar/__tests__/TreeItem.tableMetadataCounts.spec.ts b/apps/desktop/src/components/sidebar/__tests__/TreeItem.tableMetadataCounts.spec.tsindex 44b92c3ac4..82ca69a3f0 100644--- a/apps/desktop/src/components/sidebar/__tests__/TreeItem.tableMetadataCounts.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/TreeItem.tableMetadataCounts.spec.ts@@ -78,6 +78,13 @@ afterEach(() => {});describe("TreeItem table metadata counts", () => {+ it("translates the Schema index group and renders its index icon and count", async () => {+ const container = await mountTreeItem({ id: "ob:APP:__indexes", type: "group-database-indexes", label: "tree.indexes", connectionId: "connection-1", database: "APP", schema: "APP", objectCount: 5, children: [] });+ expect(container.textContent).toContain(i18n.global.t("tree.indexes"));+ expect(container.textContent).not.toContain("tree.indexes");+ expect(container.textContent).toContain("5");+ expect(container.querySelector(".text-amber-400")).not.toBeNull();+ });it("renders counts for loaded table metadata groups, including empty groups", async () => {const groups = [["group-columns", "tree.columns", 2],diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex 6f5e55dac6..ff0db65d1c 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -98,8 +98,9 @@ import { queryTimeoutSecsForConcurrentIndex, queryTimeoutSecsForConnection } froimport { isMacOS } from "@/lib/backend/platform";import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";-import { invalidateObjectDdl, loadObjectDdl } from "@/lib/metadata/objectDdlCache";+import { invalidateObjectDdl, invalidateObjectDdlCache, loadObjectDdl } from "@/lib/metadata/objectDdlCache";import { invalidateObjectMetadataCache, loadObjectMetadataFacet, type ObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";+import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import { invalidateTableMetadataCache } from "@/lib/metadata/tableMetadataCache";import {type BuildTableStructureChangeSqlOptions,@@ -260,6 +261,7 @@ const props = defineProps<{initialTab?: TableInfoTab;initialTabRequestId?: number;initialTarget?: TableStructureEditorTarget;+ exactIdentity?: boolean;draft?: TableStructureEditorDraft;}>();@@ -304,6 +306,7 @@ const rawDdlContent = ref("");const ddlStorageExcluded = ref(settingsStore.editorSettings.excludeDdlStorage);const ddlContent = computed(() => applyDdlStoragePreference(rawDdlContent.value, databaseType.value, ddlStorageExcluded.value));const ddlLoading = ref(false);+let ddlLoadRequestId = 0;const ddlEditorContainer = ref<HTMLDivElement>();const ddlSearchPanelRef = ref<InstanceType<typeof EditorSearchPanel>>();const ddlSearchOpen = ref(false);@@ -520,6 +523,7 @@ type StructureDdlRequest = {tableName: string;catalog?: string;objectType?: "VIEW";+ exactIdentity?: boolean;};function ddlRequest(): StructureDdlRequest {@@ -531,22 +535,35 @@ function ddlRequest(): StructureDdlRequest {tableName: props.tableName,catalog: props.catalog,objectType: props.tableType === "view" ? "VIEW" : undefined,+ ...(props.exactIdentity ? { exactIdentity: true } : {}),};}+function getStructureColumns(request: StructureDdlRequest) {+ return request.exactIdentity ? api.getColumns(request.connectionId, request.database, request.schema, request.tableName, request.catalog, undefined, undefined, true) : api.getColumns(request.connectionId, request.database, request.schema, request.tableName, request.catalog);+}+async function fetchDdl(force = false) {if (!props.connectionId || !props.database || !props.tableName || (!force && ddlFetched.value) || !tableMetadataCapabilities.value.ddl) return;if (force) destroyDdlEditor();+ const request = ddlRequest();+ const requestId = ++ddlLoadRequestId;+ const revision = store.connectionStateRevision(request.connectionId);+ const fingerprint = connection.value ? connectionConfigFingerprint(connection.value) : "";+ const current = () => !primaryKeyUnmounted && requestId === ddlLoadRequestId && JSON.stringify(request) === JSON.stringify(ddlRequest()) && store.connectionStateRevision(request.connectionId) === revision && (connection.value ? connectionConfigFingerprint(connection.value) : "") === fingerprint;ddlLoading.value = true;try {- const { ddl } = await loadObjectDdl(ddlRequest(), { force });- rawDdlContent.value = await formatStructureDdl(ddl);+ const { ddl } = await loadObjectDdl(request, { force });+ const formatted = await formatStructureDdl(ddl);+ if (!current()) return;+ rawDdlContent.value = formatted;ddlFetched.value = true;} catch (e: any) {+ if (!current()) return;rawDdlContent.value = `-- Error: ${e?.message || e}`;ddlFetched.value = true;} finally {- ddlLoading.value = false;+ if (current()) ddlLoading.value = false;}}const errorMessage = ref("");@@ -1521,7 +1538,7 @@ const usesNativeMysqlIndexNames = computed(() => {const supportsCharacterLengthUnits = computed(() => databaseType.value === "dameng" || databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");const usesMysql8SafeDefaults = computed(() => databaseType.value === "mysql" && connection.value?.db_type === "mysql" && connection.value.driver_profile === "mysql");const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value, connection.value?.db_type, connection.value?.database_info?.productVersion, starrocksAlterContext.value?.model));-const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value));+const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value, { connectionType: connection.value?.db_type, exactIdentity: props.exactIdentity }));const structureDialect = computed(() => structureCapabilities.value.dialect);const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment || (!isCreateMode.value && databaseType.value === "starrocks" && !getStarRocksCapabilities(connection.value?.database_info?.productVersion).tableComment));const dynamicDataTypeOptions = ref<string[]>([]);@@ -2085,8 +2102,8 @@ const indexSearchMatchCount = computed(() => (indexSearchText.value.trim() ? filconst foreignKeyActionOptions = computed(() => (structureDialect.value === "sqlserver" ? ["", "CASCADE", "SET NULL", "NO ACTION"] : ["", "CASCADE", "SET NULL", "RESTRICT", "NO ACTION"]));const triggerTimingOptions = computed(() => (databaseType.value === "sqlserver" ? ["AFTER", "INSTEAD OF"] : ["BEFORE", "AFTER"]));const triggerEventOptions = ["INSERT", "UPDATE", "DELETE"];-const metadataSchema = computed(() => connectionObjectTreeQuerySchema(connection.value, props.database, props.schema));-const refreshVersion = computed(() => (props.connectionId && props.tableName ? queryStore.tableStructureRefreshVersion(props.connectionId, props.database, props.schema, props.tableName) : 0));+const metadataSchema = computed(() => (props.exactIdentity ? (props.schema ?? "") : connectionObjectTreeQuerySchema(connection.value, props.database, props.schema)));+const refreshVersion = computed(() => (props.connectionId && props.tableName ? queryStore.tableStructureRefreshVersion(props.connectionId, props.database, props.schema, props.tableName, props.exactIdentity === true, props.catalog) : 0));const isCreateMode = computed(() => !props.tableName);// Hidden for an existing table that is not partitioned: the tab could only ever// render an empty state. Create mode keeps it so partitioning can be declared.@@ -2163,6 +2180,7 @@ const oracleIndexBusy = ref(false);const oracleIndexEpoch = ref(0);const oracleIndexReady = shallowRef<OracleIndexLoadBaseline>();const oracleIndexRefreshGuard = ref<{ target: string; afterRequestId: number; completedCreates: OracleIndexDefinition[] }>();+const oracleIndexRefreshError = ref("");const oracleIndexConfirmationScope = `structure-oracle-index:${uuid()}`;const oracleConstraintConfirmationScope = `structure-oracle-constraint:${uuid()}`;const oracleConstraintChanged = computed(() => !!oracleConstraintDraft.value && JSON.stringify(oracleConstraintDraft.value.original) !== JSON.stringify(oracleConstraintDraft.value.target));@@ -2184,8 +2202,12 @@ onBeforeUnmount(() => {if (saving.value) productionSafetyStore.cancelScope(oracleIndexConfirmationScope);});watch(- () => [props.connectionId, props.database, props.schema, props.tableName, props.catalog],+ () => [props.connectionId, props.database, props.schema, props.tableName, props.catalog, props.exactIdentity],() => {+ ddlLoadRequestId += 1;+ ddlLoading.value = false;+ tableCommentLoadRequestId += 1;+ tableCommentLoadPromise = null;invalidateOracleIndexReady();if (primaryKeyBusy.value) productionSafetyStore.cancelScope(primaryKeyConfirmationScope);if (saving.value) productionSafetyStore.cancelScope(oracleForeignKeyConfirmationScope);@@ -2202,6 +2224,8 @@ watch(oracleConstraintPlan.value = undefined;oracleConstraintSession.value = undefined;oracleIndexPlan.value = undefined;+ oracleIndexRefreshGuard.value = undefined;+ oracleIndexRefreshError.value = "";if (primaryKeyBusy.value) saving.value = false;},);@@ -2224,11 +2248,11 @@ function primaryKeyTarget(): PrimaryKeyTarget {}function oracleConstraintTarget(): OracleConstraintTarget {- return { ...primaryKeyTarget(), schema: metadataSchema.value, databaseType: databaseType.value === "oracle" ? "oracle" : "oceanbase-oracle" };+ return { ...primaryKeyTarget(), schema: metadataSchema.value, databaseType: databaseType.value === "oracle" ? "oracle" : "oceanbase-oracle", ...(props.exactIdentity ? { exactIdentity: true } : {}) };}function oracleIndexTargetIdentity(target: OracleConstraintTarget): string {- return JSON.stringify({ connectionId: target.connectionId, database: target.database, schema: target.schema, tableName: target.tableName, catalog: target.catalog });+ return JSON.stringify({ connectionId: target.connectionId, database: target.database, schema: target.schema, tableName: target.tableName, catalog: target.catalog, ...(target.exactIdentity ? { exactIdentity: true } : {}) });}function invalidateOracleIndexReady() {@@ -2331,7 +2355,7 @@ function addOracleUniqueColumn(name: string) {}function canOpenPairedOracleConstraint(index: EditableStructureIndex): boolean {- return isOracleConstraintEditor.value && index.isUnique && !!index.original;+ return isOracleConstraintEditor.value && tableMetadataCapabilities.value.constraints && index.isUnique && !!index.original;}async function editOracleUniqueConstraintForIndex(index: EditableStructureIndex) {@@ -2339,7 +2363,7 @@ async function editOracleUniqueConstraintForIndex(index: EditableStructureIndex)const target = oracleConstraintTarget();const identity = JSON.stringify(target);try {- const fresh = await api.listConstraints(target.connectionId, target.database, target.schema, target.tableName, target.catalog);+ const fresh = await api.listConstraints(target.connectionId, target.database, target.schema, target.tableName, target.catalog, ...(target.exactIdentity ? ([true] as const) : []));if (primaryKeyUnmounted || identity !== JSON.stringify(oracleConstraintTarget())) return;const constraint = fresh.find((item) => item.constraint_type === "UNIQUE" && item.oracle_metadata?.metadataComplete && item.oracle_metadata.owner === target.schema && item.oracle_metadata.indexOwner === target.schema && item.oracle_metadata.indexName === index.original?.name);if (!constraint) throw new Error("This unique index has no uniquely paired constraint metadata.");@@ -2535,6 +2559,8 @@ let structureHorizontalScrollbarDragState: {// and row scrolling are tracked separately for each request.let appliedInitialTargetSearchKey = "";let appliedInitialTargetScrollKey = "";+let lastAppliedInitialTargetRequestId: number | undefined;+let initialIndexTargetError: { key: string; message: string } | undefined;function cloneDraftValue<T>(value: T): T {return JSON.parse(JSON.stringify(value)) as T;@@ -2797,6 +2823,8 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {loadedMetadataFacets: [...loadedMetadataFacets],scrollPositions: cloneDraftValue(structureScrollPositions),appliedInitialTabRequestId: lastAppliedInitialTabRequestId,+ appliedInitialTargetRequestId: lastAppliedInitialTargetRequestId,+ oracleIndexRecovery: oracleIndexRefreshGuard.value ? { target: oracleIndexRefreshGuard.value.target, completedCreates: cloneDraftValue(oracleIndexRefreshGuard.value.completedCreates), refreshError: oracleIndexRefreshError.value || undefined } : undefined,initialized,};}@@ -2839,6 +2867,11 @@ function restoreDraft(draft: TableStructureEditorDraft) {restoringDraft = true;draftHydrated = false;lastAppliedInitialTabRequestId = draft.appliedInitialTabRequestId;+ lastAppliedInitialTargetRequestId = draft.appliedInitialTargetRequestId;+ if (draft.oracleIndexRecovery?.target === oracleIndexTargetIdentity(oracleConstraintTarget())) {+ oracleIndexRefreshGuard.value = { ...cloneDraftValue(draft.oracleIndexRecovery), afterRequestId: -1 };+ oracleIndexRefreshError.value = draft.oracleIndexRecovery.refreshError ?? "";+ }activeTab.value = draft.activeTab || "columns";// Restore the DDL baseline alongside the edit, otherwise the restored script// would read as dirty (or clean) against the wrong reference text.@@ -2941,7 +2974,8 @@ async function hydrateRestoredDraftFromDatabase() {let shouldRefreshPreview = false;try {await store.ensureConnected(connectionId);- let { value: nextColumns } = await loadObjectMetadataFacet({ connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs }, "columns", () => api.getColumns(connectionId, database, schema, tableName, catalog));+ const request = ddlRequest();+ let { value: nextColumns } = await loadObjectMetadataFacet(request, "columns", () => getStructureColumns(request));if (databaseType.value === "manticoresearch" && tableMetadataCapabilities.value.ddl) {try {const { ddl } = await loadObjectDdl({ connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs });@@ -3215,6 +3249,14 @@ async function refreshSqlPreview() {existingOracleForeignKeySession.value = undefined;newOracleForeignKeyPlan.value = undefined;newOracleForeignKeySession.value = undefined;+ const indexWriteWarning = schemaIndexWriteWarning();+ if (indexWriteWarning) {+ pendingStatements.value = [];+ warnings.value = [indexWriteWarning];+ sqlPreviewLoading.value = false;+ sqlPreviewPending.value = false;+ return;+ }if (concurrentAvailabilityInvalidated.value) {// Availability gap in effect: never regenerate SQL here — doing so would// turn a lost Concurrent request into a silent blocking CREATE INDEX. Keep@@ -3496,6 +3538,7 @@ const canApply = computed(!oracleConstraintBusy.value &&(databaseType.value !== "starrocks" || !starrocksStatusBusy.value) &&!postSaveRefreshing.value &&+ !oracleIndexRefreshError.value &&!secondaryMetadataLoading.value &&!mysqlTableEngineLoading.value &&!sqlPreviewLoading.value &&@@ -3528,6 +3571,9 @@ function resetState() {partitionsLoading.value = false;partitionsError.value = "";errorMessage.value = "";+ oracleIndexRefreshError.value = "";+ oracleIndexRefreshGuard.value = undefined;+ lastAppliedInitialTargetRequestId = undefined;secondaryMetadataErrors.value = {};isPartitionedParent.value = false;isTablePartition.value = false;@@ -3605,11 +3651,13 @@ function resetState() {highlightedIndexId.value = null;appliedInitialTargetSearchKey = "";appliedInitialTargetScrollKey = "";+ initialIndexTargetError = undefined;localColumnOrderNoticeShown.value = false;}async function reloadStructureFromDatabase() {if (isCreateMode.value) return;+ if (oracleIndexRefreshError.value) return retryOracleIndexRefresh();draftHydrated = false;if (activeTab.value !== "triggers") {triggers.value = [];@@ -3670,7 +3718,7 @@ async function fetchTableCommentValue(connectionId: string, database: string, sctry {const tables = await api.listTables(connectionId, database, schema, undefined, undefined, undefined, undefined, catalog);const table = tables.find((t) => t.name.toLowerCase() === tableName.toLowerCase() && t.table_type !== "VIEW");- return table?.comment || "";+ return table ? table.comment || "" : undefined;} catch {return undefined;}@@ -3678,7 +3726,12 @@ async function fetchTableCommentValue(connectionId: string, database: string, sc}function loadCachedTableComment(request: StructureDdlRequest, force = false): Promise<{ value: string | undefined; cacheStatus: "memory" | "disk" | "remote" }> {- return loadObjectMetadataFacet(request, "comment", () => fetchTableCommentValue(request.connectionId, request.database, request.schema, request.tableName, request.catalog), { force });+ return loadObjectMetadataFacet(+ request,+ "comment",+ () => (request.exactIdentity ? api.getTableComment(request.connectionId, request.database, request.schema, request.tableName, request.catalog, true).then((value) => value ?? "") : fetchTableCommentValue(request.connectionId, request.database, request.schema, request.tableName, request.catalog)),+ { force },+ );}async function loadVisibleTableComment(force = false, preserveDraft = false) {@@ -3687,6 +3740,7 @@ async function loadVisibleTableComment(force = false, preserveDraft = false) {const schema = metadataSchema.value;const tableName = props.tableName;const catalog = props.catalog;+ const exactIdentity = props.exactIdentity === true;if (!structureCapabilities.value.comment || !connectionId || !database || !tableName) return;if (!force && loadedMetadataFacets.has("comment")) return;if (!force && tableCommentLoadPromise) return tableCommentLoadPromise;@@ -3695,8 +3749,11 @@ async function loadVisibleTableComment(force = false, preserveDraft = false) {const loadPromise = (async () => {try {await store.ensureConnected(connectionId);- const { value } = await loadCachedTableComment({ connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs }, force);+ const revision = store.connectionStateRevision(connectionId);+ const fingerprint = store.getConfig(connectionId) ? connectionConfigFingerprint(store.getConfig(connectionId)!) : "";+ const { value } = await loadCachedTableComment({ connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs, ...(exactIdentity ? { exactIdentity: true } : {}) }, force);if (requestId !== tableCommentLoadRequestId) return;+ if (exactIdentity !== (props.exactIdentity === true) || revision !== store.connectionStateRevision(connectionId) || fingerprint !== (store.getConfig(connectionId) ? connectionConfigFingerprint(store.getConfig(connectionId)!) : "")) return;if (connectionId !== props.connectionId || database !== props.database || schema !== metadataSchema.value || tableName !== props.tableName || (catalog || "") !== (props.catalog || "")) return;if (value === undefined) return;const hasCommentDraft = tableComment.value !== originalTableComment.value;@@ -3848,7 +3905,7 @@ async function loadStructure(if (!connectionId || !database || !tableName) return;const oracleIndexContext = !isCreateMode.value && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");const needsOracleIndexBaseline = oracleIndexContext && scope.indexes;- const effectiveScope = withRequiredPostgresPrimaryKeyMetadata(needsOracleIndexBaseline ? { ...scope, columns: true, indexes: true } : scope);+ const effectiveScope = withRequiredPostgresPrimaryKeyMetadata(needsOracleIndexBaseline || (props.exactIdentity && scope.indexes) ? { ...scope, columns: true, indexes: true } : scope);if (oracleIndexContext && (scope.columns || scope.indexes)) invalidateOracleIndexReady();let loadEpoch = oracleIndexEpoch.value;const requestId = ++structureLoadRequestId;@@ -3887,7 +3944,7 @@ async function loadStructure(.then((status) => ({ known: true, status })).catch(() => ({ known: false, status: { isPartitionedParent: false, isPartition: false, isForeign: false } })): Promise.resolve({ known: true, status: { isPartitionedParent: false, isPartition: false, isForeign: false } });- const columnsLoad = effectiveScope.columns ? loadObjectMetadataFacet(metadataRequest, "columns", () => api.getColumns(connectionId, database, schema, tableName, catalog), { force: forceMetadata }) : undefined;+ const columnsLoad = effectiveScope.columns ? loadObjectMetadataFacet(metadataRequest, "columns", () => getStructureColumns(metadataRequest), { force: forceMetadata }) : undefined;const columnsPromise = columnsLoad? columnsLoad.then((result) => {columnsServedFromCache = result.cacheStatus !== "remote";@@ -3896,22 +3953,22 @@ async function loadStructure(: Promise.resolve(undefined);const indexesPromise = effectiveScope.indexes? tableMetadataCapabilities.value.indexes- ? loadObjectMetadataFacet(metadataRequest, "indexes", () => api.listIndexes(connectionId, database, schema, tableName, catalog), { force: forceMetadata }).then((result) => result.value)+ ? loadObjectMetadataFacet(metadataRequest, "indexes", () => api.listIndexes(connectionId, database, schema, tableName, catalog, ...(metadataRequest.exactIdentity ? ([true] as const) : [])), { force: forceMetadata }).then((result) => result.value): Promise.resolve([]): Promise.resolve(undefined);const foreignKeysPromise = effectiveScope.foreignKeys? tableMetadataCapabilities.value.foreignKeys- ? loadObjectMetadataFacet(metadataRequest, "foreign-keys", () => api.listForeignKeys(connectionId, database, schema, tableName, catalog), { force: forceMetadata }).then((result) => result.value)+ ? loadObjectMetadataFacet(metadataRequest, "foreign-keys", () => api.listForeignKeys(connectionId, database, schema, tableName, catalog, ...(metadataRequest.exactIdentity ? ([true] as const) : [])), { force: forceMetadata }).then((result) => result.value): Promise.resolve([]): Promise.resolve(undefined);const constraintsPromise = effectiveScope.constraints? tableMetadataCapabilities.value.constraints- ? loadObjectMetadataFacet(metadataRequest, "constraints", () => api.listConstraints(connectionId, database, schema, tableName, catalog), { force: forceMetadata }).then((result) => result.value)+ ? loadObjectMetadataFacet(metadataRequest, "constraints", () => api.listConstraints(connectionId, database, schema, tableName, catalog, ...(metadataRequest.exactIdentity ? ([true] as const) : [])), { force: forceMetadata }).then((result) => result.value): Promise.resolve([]): Promise.resolve(undefined);const triggersPromise = effectiveScope.triggers? tableMetadataCapabilities.value.triggers- ? loadObjectMetadataFacet(metadataRequest, "triggers", () => api.listTriggers(connectionId, database, schema, tableName, catalog), { force: forceMetadata }).then((result) => result.value)+ ? loadObjectMetadataFacet(metadataRequest, "triggers", () => api.listTriggers(connectionId, database, schema, tableName, catalog, ...(metadataRequest.exactIdentity ? ([true] as const) : [])), { force: forceMetadata }).then((result) => result.value): Promise.resolve([]): Promise.resolve(undefined);// Partition metadata is a live catalog read (not persisted), so it is@@ -3946,7 +4003,7 @@ async function loadStructure(// editor shows the correct options for the server version.void loadCharsetMetadata();void loadMysqlTableDefaultCollation();- const retainOracleColumns = oracleIndexContext && options.preserveDraft === true && !scope.columns;+ const retainOracleColumns = (oracleIndexContext || props.exactIdentity) && options.preserveDraft === true && !scope.columns;if (!retainOracleColumns) {const nextColumnDrafts = createColumnDrafts(nextColumns, databaseType.value);const hydratedColumnDrafts = supportsCharacterLengthUnits.value && options.characterLengthUnitsAfterSave ? restoreCharacterLengthUnitsAfterSave(databaseType.value, nextColumnDrafts, options.characterLengthUnitsAfterSave) : nextColumnDrafts;@@ -3962,8 +4019,9 @@ async function loadStructure(const nextTableComment = await tableCommentPromise;if (nextTableComment !== undefined) {+ const retainCommentDraft = options.preserveDraft && tableComment.value !== originalTableComment.value;originalTableComment.value = nextTableComment;- tableComment.value = nextTableComment;+ if (!retainCommentDraft) tableComment.value = nextTableComment;loadedMetadataFacets.add("comment");}const partitionStatus = await partitionStatusPromise;@@ -4011,14 +4069,11 @@ async function loadStructure(if (nextIndexes) {// An empty lazy load changes no draft data and should not trigger another save.const indexRefreshGuard = oracleIndexRefreshGuard.value;- if (options.preserveDraft && indexRefreshGuard?.target === JSON.stringify({ connectionId, database, schema, tableName, catalog })) {- indexes.value = mergeOracleIndexDraftsAfterRefresh(indexes.value, nextIndexes, indexRefreshGuard.completedCreates);+ if (options.preserveDraft && (props.exactIdentity || indexRefreshGuard?.target === loadTargetIdentity)) {+ indexes.value = mergeOracleIndexDraftsAfterRefresh(indexes.value, nextIndexes, indexRefreshGuard?.target === loadTargetIdentity ? indexRefreshGuard.completedCreates : []);} else if (nextIndexes.length || indexes.value.length) {indexes.value = createIndexDrafts(nextIndexes);}- if (oracleIndexRefreshGuard.value?.target === JSON.stringify({ connectionId, database, schema, tableName, catalog }) && requestId > oracleIndexRefreshGuard.value.afterRequestId) {- oracleIndexRefreshGuard.value = undefined;- }loadedMetadataFacets.add("indexes");}if (nextForeignKeys) {@@ -4084,7 +4139,7 @@ async function loadStructure(const target = oracleConstraintTarget();const snapshot = await readOracleIndexSnapshot(target);if (oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint) && oracleIndexEpoch.value === loadEpoch) {- const loadedColumns = columns.value.flatMap((column) => (column.original ? [column.original] : []));+ const loadedColumns = nextColumns ?? columns.value.flatMap((column) => (column.original ? [column.original] : []));if (oracleIndexSnapshotMatchesLoaded(snapshot, target, indexes.value) && oracleIndexSnapshotMatchesLoadedColumns(snapshot, loadedColumns)) {oracleIndexReady.value = {snapshot,@@ -4096,6 +4151,7 @@ async function loadStructure(columnsFingerprint: JSON.stringify(columns.value),indexesFingerprint: JSON.stringify(snapshot.indexes),};+ if (oracleIndexRefreshGuard.value?.target === loadTargetIdentity && requestId > oracleIndexRefreshGuard.value.afterRequestId) oracleIndexRefreshGuard.value = undefined;}}} catch (error) {@@ -4146,7 +4202,8 @@ async function revalidateCachedStructureMetadata(loadRequestId: number, scope: {if (!connectionId || !database || !tableName) return;if (scope.columns && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle")) invalidateOracleIndexReady();const revalidationId = ++structureMetadataRevalidationId;- const metadataRequest = { connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs };+ const exactIdentity = props.exactIdentity === true;+ const metadataRequest = { connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs, ...(exactIdentity ? { exactIdentity: true } : {}) };let revalidationConnectionRevision: number | undefined;let revalidationConfigFingerprint = "";const isCurrent = () =>@@ -4155,6 +4212,7 @@ async function revalidateCachedStructureMetadata(loadRequestId: number, scope: {connectionId === props.connectionId &&database === props.database &&schema === metadataSchema.value &&+ exactIdentity === (props.exactIdentity === true) &&tableName === props.tableName &&(catalog || "") === (props.catalog || "") &&(revalidationConnectionRevision === undefined ||@@ -4172,7 +4230,7 @@ async function revalidateCachedStructureMetadata(loadRequestId: number, scope: {// first, the same thing an explicit "Refresh Structure" does.await invalidateObjectMetadataCache({ connectionId, database, schema, tableName });if (!isCurrent()) return;- const columnsPromise = scope.columns ? loadObjectMetadataFacet(metadataRequest, "columns", () => api.getColumns(connectionId, database, schema, tableName, catalog), { force: true }) : Promise.resolve(undefined);+ const columnsPromise = scope.columns ? loadObjectMetadataFacet(metadataRequest, "columns", () => getStructureColumns(metadataRequest), { force: true }) : Promise.resolve(undefined);const commentPromise = scope.tableComment ? loadCachedTableComment(metadataRequest, true) : Promise.resolve(undefined);// allSettled so a failing comment re-fetch cannot swallow a valid columns// fix (and vice versa); each failure is logged on its own.@@ -5566,6 +5624,7 @@ function addIndex() {input?.focus();input?.select();});+ return draft;}function structureIndexTableName(): string {@@ -5705,6 +5764,7 @@ function toggleDropIndex(index: EditableStructureIndex) {function canEditIndexDraft(index: EditableStructureIndex): boolean {if (indexesLoading.value) return false;+ if (schemaIndexDraftIsReadOnly(index)) return false;if (index.markedForDrop || index.isPrimary) return false;if (!index.original) return structureCapabilities.value.createIndex;return structureCapabilities.value.rebuildIndex && structureCapabilities.value.createIndex && structureCapabilities.value.dropIndex;@@ -5803,9 +5863,20 @@ function canEditIndexComment(index: EditableStructureIndex): boolean {function canDropIndex(index: EditableStructureIndex): boolean {if (indexesLoading.value) return false;+ if (schemaIndexDraftIsReadOnly(index)) return false;return !!index.original && !index.isPrimary && structureCapabilities.value.dropIndex;}+function schemaIndexDraftIsReadOnly(index: EditableStructureIndex): boolean {+ return props.exactIdentity === true && !!index.original && (index.original.owner == null || index.original.owner !== metadataSchema.value);+}++function schemaIndexWriteWarning(): string | undefined {+ const blocked = indexes.value.find((index) => schemaIndexDraftIsReadOnly(index) && indexChanged(index));+ if (!blocked) return undefined;+ return blocked.original?.owner == null ? t("schemaIndex.targetMissing", { name: blocked.original?.name }) : t("schemaIndex.crossOwnerReadOnly", { owner: blocked.original.owner, name: blocked.original.name });+}+const isOracleForeignKeyEditor = computed(() => databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");const canEditForeignKeys = computed(() => (isOracleForeignKeyEditor.value ? true : structureCapabilities.value.foreignKey));const canEditTriggers = computed(() => structureDialect.value === "mysql" || structureDialect.value === "oracle" || structureDialect.value === "sqlserver");@@ -6010,20 +6081,20 @@ function primarySqlOperation(sql: string): string {return statement?.match(/^([a-z]+)/i)?.[1]?.toUpperCase() || "SQL";}-async function recordStructureHistory(sql: string, start: number, success: boolean, result?: { affected_rows?: number }, error?: string) {- const connection = store.getConfig(props.connectionId);+async function recordStructureHistory(sql: string, start: number, success: boolean, result?: { affected_rows?: number }, error?: string, target?: StructureDdlRequest) {+ const connection = store.getConfig(target?.connectionId ?? props.connectionId);try {await historyStore.add({- connection_id: props.connectionId,+ connection_id: target?.connectionId ?? props.connectionId,connection_name: connection?.name || "",- database: props.database,+ database: target?.database ?? props.database,sql,execution_time_ms: Date.now() - start,success,error,activity_kind: "schema_change",- operation: hasSqliteTypeChange.value ? "ALTER TABLE" : primarySqlOperation(sql),- target: isCreateMode.value ? newTableName.value.trim() : props.tableName,+ operation: !target && hasSqliteTypeChange.value ? "ALTER TABLE" : primarySqlOperation(sql),+ target: target?.tableName ?? (isCreateMode.value ? newTableName.value.trim() : props.tableName),affected_rows: success ? result?.affected_rows : undefined,});} catch (e) {@@ -6498,76 +6569,55 @@ async function applyOracleIndexPlan(): Promise<boolean> {console.warn("[DBX][structure-history:save-failed]", error);}}- if (result.steps.some((step) => step.state !== "notExecuted")) {+ const complete = result.steps.length > 0 && result.steps.every((step) => step.state === "committed") && !result.readbackError;+ let refreshError = "";+ const contextStillCurrent = () =>+ !primaryKeyUnmounted &&+ JSON.stringify(target) === JSON.stringify(oracleConstraintTarget()) &&+ store.connectionStateRevision(target.connectionId) === revision &&+ (store.getConfig(target.connectionId) ? connectionConfigFingerprint(store.getConfig(target.connectionId)!) : "") === configFingerprint;+ if (attemptedSteps) {const completedCreates = plan.mutations.flatMap((mutation, index) => {if (mutation.operation !== "CREATE" || result.steps[index]?.state !== "committed") return [];const created = mutation.expectedAfter.find((item) => item.name === mutation.name);return created ? [created] : [];});- oracleIndexRefreshGuard.value = { target: oracleIndexTargetIdentity(target), afterRequestId: structureLoadRequestId, completedCreates };- invalidateTableMetadataCache(target);- await invalidateObjectMetadataCache(target);- await invalidateObjectDdl(target);- loadedMetadataFacets.clear();- }- const complete = result.steps.length > 0 && result.steps.every((step) => step.state === "committed") && !result.readbackError;- if (saveSessionCurrent()) {- // Never leave a DROP in the Apply queue after partial or unknown execution.- pendingStatements.value = [];- oracleIndexPlan.value = undefined;- if (complete) {- const columnsBeforeReadback = cloneDraftValue(columns.value);- const indexesBeforeReadback = cloneDraftValue(indexes.value);- const expectedReadbackRequestId = structureLoadRequestId + 1;- const refresh = await loadStructure(true, { columns: false, indexes: true, constraints: false, foreignKeys: false, triggers: false, partitions: false, tableComment: true }, true, { forceMetadata: true, blockSecondaryMetadata: true });- if (!refresh?.error && !oracleIndexReady.value && secondaryMetadataLoading.value) {- await new Promise<void>((resolve) => {- const stop = watch(secondaryMetadataLoading, (loading) => {- if (!loading) {- stop();- resolve();- }- });- if (!secondaryMetadataLoading.value) {- stop();- resolve();- }- });- }- const readback = oracleIndexReady.value;- const currentConfig = store.getConfig(target.connectionId);- const contextStillCurrent = !primaryKeyUnmounted && JSON.stringify(target) === JSON.stringify(oracleConstraintTarget()) && store.connectionStateRevision(target.connectionId) === revision && (currentConfig ? connectionConfigFingerprint(currentConfig) : "") === configFingerprint;- const readbackReady =- !!readback &&- contextStillCurrent &&- !refresh?.error &&- !secondaryMetadataErrors.value.indexes &&- !errorMessage.value &&- readback.requestId === structureLoadRequestId &&- readback.requestId >= expectedReadbackRequestId &&- readback.epoch === oracleIndexEpoch.value &&- readback.targetIdentity === oracleIndexTargetIdentity(target) &&- readback.connectionRevision === store.connectionStateRevision(target.connectionId) &&- readback.configFingerprint === (currentConfig ? connectionConfigFingerprint(currentConfig) : "");- if (readbackReady) {- emit("saved", false);- } else {- if (structureLoadRequestId === expectedReadbackRequestId && contextStillCurrent) {- columns.value = columnsBeforeReadback;- indexes.value = indexesBeforeReadback;- }- result.readbackError = refresh?.error || secondaryMetadataErrors.value.indexes || errorMessage.value || "Index refresh did not publish a current complete baseline after DDL.";+ const recovery = { target: oracleIndexTargetIdentity(target), afterRequestId: structureLoadRequestId, completedCreates };+ if (contextStillCurrent()) {+ oracleIndexRefreshGuard.value = recovery;+ // Already attempted SQL is never left queued for another Apply.+ pendingStatements.value = [];+ oracleIndexPlan.value = undefined;+ }+ if (complete && contextStillCurrent()) {+ refreshError = await refreshOracleIndexMetadata(target, recovery);+ } else {+ refreshError = await refreshSchemaIndexLists(target);+ invalidateTableMetadataCache(target);+ try {+ await invalidateObjectDdlCache(target);+ } catch (error) {+ refreshError = [refreshError, error instanceof Error ? error.message : String(error)].filter(Boolean).join("\n");}}+ if (complete && contextStillCurrent()) {+ skipNextRefreshVersion = true;+ emit("saved", false);+ void nextTick(() => {+ skipNextRefreshVersion = false;+ });+ }+ if (contextStillCurrent()) syncDraftToParent();}- if ((!complete || result.readbackError) && !primaryKeyUnmounted) {+ if ((!complete || refreshError) && !primaryKeyUnmounted) {primaryKeyResultTitle.value = "oracleStructureResult.resultTitle";- primaryKeyResultMessage.value = `${target.schema}.${target.tableName}: ${t("oracleStructureResult.executionFailed")}`;+ primaryKeyResultMessage.value = `${target.schema}.${target.tableName}: ${t(complete ? "oracleStructureResult.appliedRefreshPending" : "oracleStructureResult.executionFailed")}`;primaryKeyResultDetails.value = result.steps.map((step, index) => `${index + 1}. ${step.state}\n${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n\n");if (result.readbackError) primaryKeyResultDetails.value += `\n\n${t("oracleStructureResult.readbackFailed")}: ${result.readbackError}`;+ if (refreshError) primaryKeyResultDetails.value += `\n\n${t("oracleStructureResult.refreshPending")}: ${refreshError}`;if (!primaryKeyUnmounted) primaryKeyResultOpen.value = true;}- return complete && !result.readbackError;+ return complete;} catch (error) {if (saveSessionCurrent()) {pendingStatements.value = [];@@ -6581,6 +6631,73 @@ async function applyOracleIndexPlan(): Promise<boolean> {}}+async function refreshSchemaIndexLists(target: Pick<StructureDdlRequest, "connectionId" | "database" | "schema" | "catalog">): Promise<string> {+ const scope = { connectionId: target.connectionId, database: target.database, schema: target.schema, catalog: target.catalog };+ invalidateObjectBrowserRowsCache({ connectionId: target.connectionId, database: target.database, schema: target.schema });+ let error = "";+ try {+ await store.refreshObjectListTreeNode(target.connectionId, target.database, target.schema, target.catalog, true);+ } catch (caught) {+ error = caught instanceof Error ? caught.message : String(caught);+ }+ window.dispatchEvent(new CustomEvent("dbx-refresh-object-browser", { detail: scope }));+ return error;+}++async function refreshOracleIndexMetadata(target: OracleConstraintTarget, recovery: NonNullable<typeof oracleIndexRefreshGuard.value>): Promise<string> {+ const revision = store.connectionStateRevision(target.connectionId);+ const config = store.getConfig(target.connectionId);+ const fingerprint = config ? connectionConfigFingerprint(config) : "";+ const current = () =>+ !primaryKeyUnmounted && recovery.target === oracleIndexTargetIdentity(oracleConstraintTarget()) && store.connectionStateRevision(target.connectionId) === revision && (store.getConfig(target.connectionId) ? connectionConfigFingerprint(store.getConfig(target.connectionId)!) : "") === fingerprint;+ const errors: string[] = [];+ try {+ invalidateTableMetadataCache(target);+ await invalidateObjectDdlCache(target, { strict: true });+ } catch (error) {+ errors.push(error instanceof Error ? error.message : String(error));+ }+ const listError = await refreshSchemaIndexLists(target);+ if (listError) errors.push(listError);+ if (!current()) return errors.join("\n");+ const expectedRequestId = structureLoadRequestId + 1;+ loadedMetadataFacets.clear();+ const refresh = await loadStructure(true, { columns: false, indexes: true, constraints: false, foreignKeys: false, triggers: false, partitions: false, tableComment: true }, true, { forceMetadata: true, blockSecondaryMetadata: true, preserveDraft: true });+ if (!current()) return errors.join("\n");+ const baseline = oracleIndexReady.value;+ if (+ !baseline ||+ baseline.requestId !== structureLoadRequestId ||+ baseline.requestId < expectedRequestId ||+ baseline.epoch !== oracleIndexEpoch.value ||+ baseline.targetIdentity !== recovery.target ||+ baseline.connectionRevision !== revision ||+ baseline.configFingerprint !== fingerprint ||+ secondaryMetadataErrors.value.indexes ||+ errorMessage.value ||+ (structureCapabilities.value.comment && !loadedMetadataFacets.has("comment"))+ ) {+ errors.push(refresh?.error || secondaryMetadataErrors.value.indexes || errorMessage.value || "Index refresh did not publish a current complete baseline after DDL.");+ }+ oracleIndexRefreshError.value = errors.join("\n");+ oracleIndexRefreshGuard.value = errors.length ? recovery : undefined;+ if (errors.length) errorMessage.value = "";+ markDraftHydratedAndSync();+ await refreshSqlPreview();+ return oracleIndexRefreshError.value;+}++async function retryOracleIndexRefresh() {+ const recovery = oracleIndexRefreshGuard.value;+ if (!recovery || recovery.target !== oracleIndexTargetIdentity(oracleConstraintTarget()) || saving.value || postSaveRefreshing.value) return;+ postSaveRefreshing.value = true;+ try {+ await refreshOracleIndexMetadata(oracleConstraintTarget(), recovery);+ } finally {+ postSaveRefreshing.value = false;+ }+}+async function applyOracleForeignKeyCreatePlan(): Promise<boolean> {if (oracleForeignKeyBusy.value || !newOracleForeignKeyPlan.value || !newOracleForeignKeySession.value) return false;const plan = cloneDraftValue(newOracleForeignKeyPlan.value);@@ -6774,6 +6891,11 @@ async function applyOracleForeignKeyCreatePlan(): Promise<boolean> {}async function applyChanges() {+ const indexWriteWarning = schemaIndexWriteWarning();+ if (indexWriteWarning) {+ errorMessage.value = indexWriteWarning;+ return false;+ }if (!canApply.value || !props.connectionId || !props.database) return false;if (oracleIndexRefreshGuard.value?.target === oracleIndexTargetIdentity(oracleConstraintTarget())) {errorMessage.value = "Index execution may have changed the database. Refresh index metadata before applying again.";@@ -6800,6 +6922,18 @@ async function applyChanges() {const sql = previewSqlText.value;const submittedStarRocksTarget = starrocksStatusTarget.value;const connection = store.getConfig(props.connectionId);+ const exactTarget = props.exactIdentity ? ddlRequest() : undefined;+ const exactRevision = store.connectionStateRevision(props.connectionId);+ const exactConfig = connection ? connectionConfigFingerprint(connection) : "";+ const exactDraft = JSON.stringify(structureChangeOptions());+ const submittedStatements = [...pendingStatements.value];+ const exactContextCurrent = () =>+ !exactTarget ||+ (!primaryKeyUnmounted &&+ JSON.stringify(ddlRequest()) === JSON.stringify(exactTarget) &&+ store.connectionStateRevision(exactTarget.connectionId) === exactRevision &&+ (store.getConfig(exactTarget.connectionId) ? connectionConfigFingerprint(store.getConfig(exactTarget.connectionId)!) : "") === exactConfig);+ const exactDraftCurrent = () => exactContextCurrent() && (!exactTarget || (sql === previewSqlText.value && exactDraft === JSON.stringify(structureChangeOptions())));const productionContext = productionContextForDatabase(connection, props.database);if (productionContext.active) {const confirmed = await productionSafetyStore.requestConfirmation({@@ -6811,6 +6945,7 @@ async function applyChanges() {});if (!confirmed) return false;}+ if (!exactDraftCurrent()) return false;saving.value = true;if (databaseType.value === "starrocks") starrocksSubmittedSql.value = undefined;errorMessage.value = "";@@ -6862,15 +6997,19 @@ async function applyChanges() {// non-concurrent batches keep the configured timeout unchanged.const configuredTimeoutSecs = queryTimeoutSecsForConnection(connection, settingsStore.editorSettings.globalQueryTimeoutSecs);const executionTimeoutSecs = queryTimeoutSecsForConcurrentIndex(configuredTimeoutSecs, hasConcurrentIndexBuild);+ let exactIndexSubmitted = false;try {// An edited DDL script is always executed as the batch it previews as; the// SQLite rebuild path would rebuild from the structure draft instead.+ if (!exactDraftCurrent()) return false;+ exactIndexSubmitted = !!exactTarget && refreshScope.indexes;const result =hasSqliteTypeChange.value && !ddlDirty.value? await api.applySqliteTableStructureChange(props.connectionId, props.database, structureChangeOptions(), sqliteSchemaRevision.value!)- : await api.executeBatch(props.connectionId, props.database, pendingStatements.value, props.schema, executionTimeoutSecs, useTransaction);+ : await api.executeBatch(exactTarget?.connectionId ?? props.connectionId, exactTarget?.database ?? props.database, exactTarget ? submittedStatements : pendingStatements.value, exactTarget?.schema ?? props.schema, executionTimeoutSecs, useTransaction);if (databaseType.value === "starrocks") starrocksSubmittedSql.value = { target: submittedStarRocksTarget, sql };- await recordStructureHistory(sql, startedAt, true, result);+ await recordStructureHistory(sql, startedAt, true, result, undefined, exactTarget);+ if (!exactContextCurrent()) return true;if (!isCreateMode.value && props.tableName) {const metadataMatch = { connectionId: props.connectionId, database: props.database, schema: metadataSchema.value, tableName: props.tableName };invalidateTableMetadataCache(metadataMatch);@@ -6919,15 +7058,23 @@ async function applyChanges() {return true;} catch (e: any) {const rawMessage = e?.message || String(e);+ if (!exactContextCurrent()) {+ await recordStructureHistory(sql, startedAt, false, undefined, rawMessage, exactTarget);+ return false;+ }// A cancelled/errored concurrent build leaves a same-name INVALID index// behind; surface that so retries are not silently doomed.const invalidIndexHint = hasConcurrentIndexBuild && /already exists/i.test(rawMessage) ? `\n\n${t("structureEditor.invalidIndexRetryHint")}` : "";const starrocksSchemaChangeBusy = databaseType.value === "starrocks" && /a schema change operation is in progress on the table\b/i.test(rawMessage);errorMessage.value = starrocksSchemaChangeBusy ? t("starrocksLayout.schemaChangeBusy", { table: props.tableName }) : `${rawMessage}${invalidIndexHint}`;- await recordStructureHistory(sql, startedAt, false, undefined, starrocksSchemaChangeBusy ? rawMessage : errorMessage.value);+ await recordStructureHistory(sql, startedAt, false, undefined, starrocksSchemaChangeBusy ? rawMessage : errorMessage.value, exactTarget);return false;} finally {saving.value = false;+ if (exactIndexSubmitted && exactTarget) {+ const error = await refreshSchemaIndexLists(exactTarget);+ if (error && exactContextCurrent()) toast(error, 5000);+ }if (databaseType.value === "starrocks") starrocksStatusRevision.value++;}}@@ -7127,6 +7274,11 @@ onMounted(() => {void hydrateRestoredDraftFromDatabase().then(async () => {applyInitialStructureTarget();void loadMysqlAutoIncrementCounter(true);+ if (oracleIndexRefreshError.value) {+ await retryOracleIndexRefresh();+ } else if ((props.exactIdentity || oracleIndexRefreshGuard.value) && !isCreateMode.value) {+ await loadStructure(true, { columns: false, indexes: true, constraints: false, foreignKeys: false, triggers: false, partitions: false, tableComment: false }, true, { blockSecondaryMetadata: true, preserveDraft: true, forceMetadata: true });+ }await loadActiveTableStructureMetadataIfNeeded();if (revalidateRestoredColumns) {// The existing revalidation checks again for edits made while loading.@@ -7234,11 +7386,50 @@ function applyPendingInitialStructureTab() {}function initialTargetKey(target: TableStructureEditorTarget): string {- return `${props.initialTabRequestId ?? 0}:${target.kind}:${target.name}`;+ return JSON.stringify([props.initialTabRequestId ?? 0, props.exactIdentity === true, target.kind, target.owner, target.name, target.action]);}function applyInitialStructureTarget() {const target = props.initialTarget;+ if (props.exactIdentity && target?.kind === "index") {+ const key = initialTargetKey(target);+ if (initialIndexTargetError && initialIndexTargetError.key !== key) {+ if (errorMessage.value === initialIndexTargetError.message) errorMessage.value = "";+ initialIndexTargetError = undefined;+ }+ if (appliedInitialTargetScrollKey === key || (target.action && props.initialTabRequestId !== undefined && props.initialTabRequestId === lastAppliedInitialTargetRequestId)) return;+ activeTab.value = resolveStructureMetadataTab("indexes");+ if (loading.value || indexesLoading.value || !loadedMetadataFacets.has("columns") || !loadedMetadataFacets.has("indexes") || errorMessage.value || secondaryMetadataErrors.value.indexes) return;+ if (target.action === "create") {+ if (!structureCapabilities.value.createIndex) return;+ if (isOracleConstraintEditor.value && !oracleIndexReady.value) return;+ appliedInitialTargetScrollKey = key;+ lastAppliedInitialTargetRequestId = props.initialTabRequestId;+ addIndex();+ syncDraftToParent();+ return;+ }+ const matches = typeof target.owner === "string" ? indexes.value.filter((index) => index.original?.owner === target.owner && index.original?.name === target.name) : [];+ if (matches.length !== 1) {+ initialIndexTargetError = { key, message: t("schemaIndex.targetMissing", { name: target.name }) };+ errorMessage.value = initialIndexTargetError.message;+ return;+ }+ initialIndexTargetError = undefined;+ const index = matches[0]!;+ appliedInitialTargetScrollKey = key;+ lastAppliedInitialTargetRequestId = props.initialTabRequestId;+ indexSearchText.value = "";+ highlightedIndexId.value = index.id;+ if (target.action === "delete" && canDropIndex(index)) index.markedForDrop = true;+ syncDraftToParent();+ void nextTick(() => {+ if (!props.initialTarget || initialTargetKey(props.initialTarget) !== key) return;+ const row = Array.from(rootRef.value?.querySelectorAll<HTMLElement>("[data-index-row-id]") ?? []).find((candidate) => candidate.dataset.indexRowId === index.id);+ row?.scrollIntoView({ block: "nearest" });+ });+ return;+ }const targetName = target?.name.trim();if (!target || !targetName) return;@@ -7294,7 +7485,7 @@ watch([() => props.initialTab, () => props.initialTabRequestId, () => props.initapplyInitialStructureTarget();});-watch([columns, indexes], () => {+watch([columns, indexes, indexesLoading, loading, oracleIndexReady], () => {applyInitialStructureTarget();});@@ -7424,7 +7615,7 @@ watch(refreshVersion, (version, previous) => {partitioning.value = null;loadedMetadataFacets.delete("partitions");}- void loadStructure(true, visibleTableStructureRefreshScope(activeTab.value));+ void loadStructure(true, visibleTableStructureRefreshScope(activeTab.value), true, { preserveDraft: props.exactIdentity === true });});async function loadActiveTableStructureMetadataIfNeeded() {@@ -9209,6 +9400,13 @@ watch(</div></div>+ <div v-if="oracleIndexRefreshError" data-oracle-index-refresh-warning role="status" class="flex shrink-0 items-center gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">+ <div class="min-w-0 flex-1">+ <p>{{ t("oracleStructureResult.appliedRefreshPending") }}</p>+ <p class="break-words text-muted-foreground">{{ oracleIndexRefreshError }}</p>+ </div>+ <Button data-retry-oracle-index-refresh variant="outline" size="sm" :disabled="saving || postSaveRefreshing" @click="retryOracleIndexRefresh">{{ t("common.retry") }}</Button>+ </div><div v-if="errorMessage" class="shrink-0 rounded-md border border-destructive/30 bg-destructive/10 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)] text-destructive">{{ errorMessage }}</div>diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.tsindex 56d59dc036..c1317c096c 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.ts@@ -1,5 +1,5 @@// @vitest-environment happy-dom-import { createApp, h, nextTick, type App } from "vue";+import { createApp, h, nextTick, reactive, type App } from "vue";import { createPinia, setActivePinia } from "pinia";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import TableStructureEditor from "../TableStructureEditor.vue";@@ -10,9 +10,10 @@ import { useConnectionStore } from "@/stores/connectionStore";import { useQueryStore } from "@/stores/queryStore";import { useProductionSafetyStore } from "@/stores/productionSafetyStore";import type { ConnectionConfig, ConstraintInfo, IndexInfo } from "@/types/database";-import type { TableStructureEditorDraft } from "@/types/database";+import type { TableStructureEditorDraft, TableStructureEditorTarget } from "@/types/database";import * as api from "@/lib/backend/api";import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";+import { cacheObjectBrowserRows, createObjectBrowserRowsCacheWriteToken, getCachedObjectBrowserRows } from "@/lib/table/objectBrowserRowsCache";vi.mock("@/lib/backend/api", async (importOriginal) => ({...(await importOriginal<typeof import("@/lib/backend/api")>()),@@ -25,6 +26,7 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({getColumns: vi.fn(),listConstraints: vi.fn(),listIndexes: vi.fn(),+ listTables: vi.fn().mockResolvedValue([]),listForeignKeys: vi.fn().mockResolvedValue([]),listTriggers: vi.fn().mockResolvedValue([]),getTableComment: vi.fn().mockResolvedValue(""),@@ -35,6 +37,7 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({saveOpenTabsState: vi.fn().mockResolvedValue(undefined),disconnectDb: vi.fn().mockResolvedValue(undefined),executeQuery: vi.fn().mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 }),+ executeBatch: vi.fn().mockResolvedValue({ affected_rows: 0 }),}));const connection = { id: "ob-constraint-edit", name: "OB constraint fixture", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", host: "fixture", port: 2881, username: "APP", database: "APP" } as ConnectionConfig;@@ -46,6 +49,7 @@ beforeEach(() => {connection.db_type = "oceanbase-oracle";connection.driver_profile = "oceanbase-oracle";connection.is_production = false;+ delete connection.connection_string;i18n.global.locale.value = "en";});@@ -65,6 +69,7 @@ async function mountConstraintEditor(loadedColumns?: Array<{ name: string; data_type: string; is_nullable: boolean; is_primary_key: boolean; column_default: string | null; character_maximum_length?: number }>,beforeMount: (() => void) | undefined = undefined,events: { drafts?: unknown[]; saved?: unknown[] } = {},+ editorProps: { exactIdentity?: boolean; initialTarget?: TableStructureEditorTarget; initialTabRequestId?: number } = {},) {const pinia = createPinia();setActivePinia(pinia);@@ -144,7 +149,10 @@ async function mountConstraintEditor(h(TooltipProvider,{},- { default: () => h(TableStructureEditor, { connectionId: connection.id, database: "APP", schema: "APP", tableName: "CONTACTS", initialTab, ref: expose, draft, "onUpdate:draft": (value: unknown) => events.drafts?.push(value), onSaved: (...args: unknown[]) => events.saved?.push(args) }) },+ {+ default: () =>+ h(TableStructureEditor, { connectionId: connection.id, database: "APP", schema: "APP", tableName: "CONTACTS", initialTab, ref: expose, draft, ...editorProps, "onUpdate:draft": (value: unknown) => events.drafts?.push(value), onSaved: (...args: unknown[]) => events.saved?.push(args) }),+ },),});app.use(pinia);@@ -177,6 +185,7 @@ function configureOracleIndexCatalog((index) =>({name: index.name,+ owner: "APP",columns: [...index.columns],is_primary: false,is_unique: index.unique,@@ -413,14 +422,27 @@ describe("Oracle CHECK and UNIQUE entry points", () => {await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="UQ_EMAIL"]')).toBeTruthy());});- it("opens the same UNIQUE draft from its paired index entry", async () => {- const container = await mountConstraintEditor("indexes");+ it.each([false, true])("opens the paired UNIQUE draft with the selected identity mode (exact: %s)", async (exactIdentity) => {+ const container = await mountConstraintEditor("indexes", undefined, undefined, undefined, false, undefined, undefined, {}, { exactIdentity });await vi.waitFor(() => expect(container.querySelector("[data-index-name-input]")).toBeTruthy());const editConstraint = container.querySelector<HTMLButtonElement>('[data-paired-unique-constraint="UQ_EMAIL"]');expect(editConstraint).toBeTruthy();editConstraint!.click();await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="UQ_EMAIL"]')).toBeTruthy());+ expect(vi.mocked(api.listConstraints).mock.calls.some((call) => call[2] === "APP" && call[3] === "CONTACTS" && call[5] === (exactIdentity ? true : undefined))).toBe(true);+ });++ it.each([false, true])("limits only exact JDBC metadata tabs to implemented facets (exact: %s)", async (exactIdentity) => {+ connection.db_type = "jdbc";+ connection.driver_profile = "jdbc";+ connection.connection_string = "jdbc:oracle:thin:@fixture";+ const container = await mountConstraintEditor("indexes", undefined, undefined, undefined, false, undefined, undefined, {}, { exactIdentity });+ const values = Array.from(container.querySelectorAll('[role="tab"]')).map((tab) => tab.getAttribute("data-value") ?? tab.getAttribute("id") ?? tab.textContent);+ const labels = Array.from(container.querySelectorAll('[role="tab"]')).map((tab) => tab.textContent);+ expect(labels).toContain("Indexes");+ for (const label of ["Foreign Keys", "Constraints", "Triggers"]) expect(labels.includes(label), JSON.stringify(values)).toBe(!exactIdentity);+ expect(container.querySelector('[data-paired-unique-constraint="UQ_EMAIL"]') !== null).toBe(!exactIdentity);});it("passes loaded Oracle key metadata through the index rebuild preview", async () => {@@ -460,7 +482,102 @@ describe("Oracle CHECK and UNIQUE entry points", () => {});describe("Oracle independent index execution", () => {+ it.each([false, true])("DM exact index saves retain the batch path and bind confirmation to the connection (changed: %s)", async (changeTarget) => {+ connection.db_type = "dameng";+ connection.driver_profile = "dameng";+ connection.is_production = changeTarget;+ let editor: { applyChanges: () => Promise<boolean> } | undefined;+ const container = await mountConstraintEditor(+ "indexes",+ [loadedIndex],+ (instance) => {+ editor = instance;+ },+ undefined,+ false,+ undefined,+ configureIndexRenamePreview,+ {},+ { exactIdentity: true },+ );+ const input = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;+ input.value = "IX_EMAIL_RENAMED";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].indexes?.[0]?.name).toBe("IX_EMAIL_RENAMED"));+ const refresh = vi.spyOn(useConnectionStore(), "refreshObjectListTreeNode");+ const oldHost = connection.host;+ try {+ const applying = editor!.applyChanges();+ if (changeTarget) {+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toBeDefined());+ useConnectionStore().connections[0].host = "different-target";+ safety.confirm();+ }+ expect(await applying).toBe(!changeTarget);+ if (changeTarget) {+ expect(api.executeBatch).not.toHaveBeenCalled();+ expect(refresh).not.toHaveBeenCalled();+ expect(input.value).toBe("IX_EMAIL_RENAMED");+ } else {+ expect(api.executeBatch).toHaveBeenCalledOnce();+ expect(refresh).toHaveBeenCalledWith(connection.id, "APP", "APP", undefined, true);+ }+ } finally {+ connection.host = oldHost;+ }+ });++ it.each([true, false])("explicit Oracle-mode JDBC satisfies the real editor index guards only with complete metadata (%s)", async (complete) => {+ connection.db_type = "jdbc";+ connection.driver_profile = "jdbc";+ connection.connection_string = "jdbc:oceanbase:oracle://fixture:2881/service";+ const fixture = configureOracleIndexCatalog();+ vi.mocked(api.listIndexes).mockResolvedValue([{ ...loadedIndex, key_metadata_complete: complete }]);+ let editor: { applyChanges: () => Promise<boolean> } | undefined;+ const container = await mountConstraintEditor(+ "indexes",+ [loadedIndex],+ (instance) => {+ editor = instance;+ },+ undefined,+ true,+ undefined,+ configureIndexRenamePreview,+ {},+ { exactIdentity: true },+ );+ const input = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;+ input.value = "IX_EMAIL_RENAMED";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].indexes?.[0]?.name).toBe("IX_EMAIL_RENAMED"));+ expect(await editor!.applyChanges()).toBe(complete);+ expect(fixture.ddl).toHaveLength(complete ? 2 : 0);+ });++ it("consumes a Schema create-index request once after exact columns and indexes load", async () => {+ const fixture = configureOracleIndexCatalog(false, []);+ const requests = reactive({ exactIdentity: true, initialTarget: { kind: "index", name: "", action: "create" } as TableStructureEditorTarget, initialTabRequestId: 1 });+ const drafts: unknown[] = [];+ const container = await mountConstraintEditor("indexes", [], undefined, undefined, true, undefined, undefined, { drafts }, requests);+ await vi.waitFor(() => expect(container.querySelectorAll("[data-index-name-input]")).toHaveLength(1));+ expect(api.getColumns).toHaveBeenCalledWith(connection.id, "APP", "APP", "CONTACTS", undefined, undefined, undefined, true);+ expect(api.listIndexes).toHaveBeenCalledWith(connection.id, "APP", "APP", "CONTACTS", undefined, true);+ requests.initialTabRequestId = 2;+ await vi.waitFor(() => expect(container.querySelectorAll("[data-index-name-input]")).toHaveLength(2));+ const saved = drafts.at(-1) as TableStructureEditorDraft;+ expect(saved.appliedInitialTargetRequestId).toBe(2);+ expect(fixture.ddl).toEqual([]);+ app!.unmount();+ app = undefined;+ container.remove();+ const restored = await mountConstraintEditor("indexes", [], undefined, saved, true, undefined, undefined, {}, requests);+ await vi.waitFor(() => expect(restored.querySelectorAll("[data-index-name-input]")).toHaveLength(2));+ expect(fixture.ddl).toEqual([]);+ });const loadedIndex = {+ owner: "APP",name: "IX_EMAIL",columns: ["EMAIL"],is_primary: false,@@ -473,6 +590,114 @@ describe("Oracle independent index execution", () => {constraint_backed: false,} as IndexInfo;+ it.each(["IX_EMAIL", "IX_EMAIL_2", "ix_email", " IX_EMAIL "])("targets only the exact original index %s when opening a delete draft", async (name) => {+ const names = ["IX_EMAIL", "IX_EMAIL_2", "ix_email", " IX_EMAIL "];+ const fixture = configureOracleIndexCatalog(+ false,+ names.map((item) => ({ name: item, columns: ["EMAIL"], unique: false, indexType: "NORMAL", partitioned: "NO", visibility: "VISIBLE", directions: ["ASC"], expressions: [null] })),+ );+ const drafts: unknown[] = [];+ await mountConstraintEditor(+ "indexes",+ names.map((item) => ({ ...loadedIndex, name: item })),+ undefined,+ undefined,+ true,+ undefined,+ undefined,+ { drafts },+ { exactIdentity: true, initialTarget: { kind: "index", name, owner: "APP", action: "delete" }, initialTabRequestId: 1 },+ );+ await vi.waitFor(() => expect((drafts.at(-1) as TableStructureEditorDraft)?.indexes.filter((item) => item.markedForDrop).map((item) => item.original?.name)).toEqual([name]));+ expect(fixture.ddl).toEqual([]);+ });++ it("accepts a new exact target after an earlier requested index is missing", async () => {+ const fixture = configureOracleIndexCatalog();+ const requests = reactive({ exactIdentity: true, initialTarget: { kind: "index", name: "MISSING", owner: "APP", action: "delete" } as TableStructureEditorTarget, initialTabRequestId: 1 });+ const drafts: unknown[] = [];+ const container = await mountConstraintEditor("indexes", [loadedIndex], undefined, undefined, true, undefined, undefined, { drafts }, requests);+ await vi.waitFor(() => expect(container.textContent).toContain("MISSING"));+ requests.initialTarget = { kind: "index", name: "IX_EMAIL", owner: "APP", action: "delete" };+ requests.initialTabRequestId = 2;+ await vi.waitFor(() => expect((drafts.at(-1) as TableStructureEditorDraft)?.indexes.filter((item) => item.markedForDrop).map((item) => item.original?.name)).toEqual(["IX_EMAIL"]));+ expect(fixture.ddl).toEqual([]);+ });++ it("uses owner/name to focus and draft a deletion without touching a same-name foreign index", async () => {+ connection.db_type = "dameng";+ connection.driver_profile = "dameng";+ const drafts: unknown[] = [];+ const container = await mountConstraintEditor(+ "indexes",+ [loadedIndex, { ...loadedIndex, owner: "Other" }],+ undefined,+ undefined,+ false,+ undefined,+ undefined,+ { drafts },+ { exactIdentity: true, initialTarget: { kind: "index", name: "IX_EMAIL", owner: "APP", action: "delete" }, initialTabRequestId: 1 },+ );+ await vi.waitFor(() => {+ const indexes = (drafts.at(-1) as TableStructureEditorDraft)?.indexes ?? [];+ expect(indexes.filter((index) => index.markedForDrop).map((index) => index.original?.owner)).toEqual(["APP"]);+ expect(new Set(indexes.map((index) => index.id)).size).toBe(2);+ });+ expect(container.querySelectorAll("[data-index-name-input]")).toHaveLength(2);+ expect(vi.mocked(api.executeBatch)).not.toHaveBeenCalled();+ });++ it.each([undefined, "Other"])("does not auto-delete an exact target without a matching owner (%s)", async (owner) => {+ connection.db_type = "dameng";+ connection.driver_profile = "dameng";+ const drafts: unknown[] = [];+ const container = await mountConstraintEditor("indexes", [loadedIndex], undefined, undefined, false, undefined, undefined, { drafts }, { exactIdentity: true, initialTarget: { kind: "index", name: "IX_EMAIL", owner, action: "delete" }, initialTabRequestId: 1 });+ await vi.waitFor(() => expect(container.textContent).toContain("Cannot locate index"));+ expect((drafts.at(-1) as TableStructureEditorDraft).indexes.some((index) => index.markedForDrop)).toBe(false);+ expect(vi.mocked(api.executeBatch)).not.toHaveBeenCalled();+ });++ it.each([false, true])("keeps foreign-owner index inputs read-only only in the new exact source (%s)", async (exactIdentity) => {+ connection.db_type = "dameng";+ connection.driver_profile = "dameng";+ const container = await mountConstraintEditor("indexes", [{ ...loadedIndex, owner: "Other" }], undefined, undefined, false, undefined, undefined, {}, { exactIdentity });+ expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")!.disabled).toBe(exactIdentity);+ });++ it("blocks restored foreign-owner deletion before SQL preview or DM execution", async () => {+ connection.db_type = "dameng";+ connection.driver_profile = "dameng";+ const drafts: unknown[] = [];+ const first = await mountConstraintEditor("indexes", [{ ...loadedIndex, owner: "Other" }], undefined, undefined, false, undefined, undefined, { drafts }, { exactIdentity: true });+ const saved = structuredClone(drafts.at(-1)) as TableStructureEditorDraft;+ saved.dirty = true;+ saved.indexes[0]!.markedForDrop = true;+ app!.unmount();+ app = undefined;+ first.remove();+ vi.mocked(api.buildTableStructureChangeSql).mockClear();+ let editor!: { applyChanges: () => Promise<boolean> };+ const restored = await mountConstraintEditor(+ "indexes",+ [{ ...loadedIndex, owner: "Other" }],+ (instance) => {+ editor = instance;+ },+ saved,+ false,+ undefined,+ undefined,+ {},+ { exactIdentity: true },+ );+ expect(await editor.applyChanges()).toBe(false);+ expect(restored.textContent).toContain("Other.IX_EMAIL");+ expect(restored.textContent).toContain("read-only");+ expect(vi.mocked(api.buildTableStructureChangeSql)).not.toHaveBeenCalled();+ expect(vi.mocked(api.executeBatch)).not.toHaveBeenCalled();+ });+async function prepareRename(failCreate = false,index: IndexInfo = loadedIndex,@@ -980,7 +1205,7 @@ describe("Oracle independent index execution", () => {expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED");});- it("returns false and preserves the index draft when post-DDL column readback mismatches", async () => {+ it("keeps an authoritative committed result when only the later column refresh mismatches, then retries reads only", async () => {let editor: { applyChanges: () => Promise<boolean> } | undefined;const { container, fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {editor = instance;@@ -990,10 +1215,86 @@ describe("Oracle independent index execution", () => {{ name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },]);- expect(await editor!.applyChanges()).toBe(false);+ expect(await editor!.applyChanges()).toBe(true);expect(fixture.ddl).toHaveLength(2);expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED");expect(document.body.textContent).toContain("committed");- expect(document.body.textContent).toContain("Readback failed or did not match the intended result");+ expect(container.querySelector("[data-oracle-index-refresh-warning]")).not.toBeNull();+ expect(document.body.textContent).not.toContain("Operation did not complete");+ expect(await editor!.applyChanges()).toBe(false);+ expect(fixture.ddl).toHaveLength(2);+ container.querySelector<HTMLButtonElement>("[data-retry-oracle-index-refresh]")!.click();+ await vi.waitFor(() => expect(container.querySelector("[data-oracle-index-refresh-warning]")).toBeNull());+ expect(fixture.ddl).toHaveLength(2);+ });++ it.each(["columns", "indexes", "comment", "cache"] as const)("keeps committed DDL separate from an auxiliary %s failure", async (facet) => {+ let editor: { applyChanges: () => Promise<boolean> } | undefined;+ const { container, fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {+ editor = instance;+ });+ let armed = true;+ const originalExecute = vi.mocked(api.executeQuery).getMockImplementation()!;+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {+ const result = await originalExecute(...args);+ if (armed && args[2].startsWith("CREATE INDEX")) {+ armed = false;+ if (facet === "columns") vi.mocked(api.getColumns).mockRejectedValueOnce(new Error("later columns unavailable"));+ if (facet === "indexes") vi.mocked(api.listIndexes).mockRejectedValueOnce(new Error("later indexes unavailable"));+ if (facet === "comment") vi.mocked(api.getTableComment).mockRejectedValueOnce(new Error("later comment unavailable"));+ if (facet === "cache") vi.mocked(api.deleteSchemaCachePrefix).mockRejectedValueOnce(new Error("later cache unavailable"));+ }+ return result;+ });+ expect(await editor!.applyChanges()).toBe(true);+ expect(fixture.ddl).toHaveLength(2);+ expect(container.querySelector("[data-oracle-index-refresh-warning]")).not.toBeNull();+ expect(document.body.textContent).toContain("committed");+ expect(document.body.textContent).not.toContain("Operation did not complete");+ expect(await editor!.applyChanges()).toBe(false);+ expect(fixture.ddl).toHaveLength(2);+ });++ it("still reports unknown and stops when immediate executor dictionary readback fails", async () => {+ let editor: { applyChanges: () => Promise<boolean> } | undefined;+ const { fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {+ editor = instance;+ });+ const originalExecute = vi.mocked(api.executeQuery).getMockImplementation()!;+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {+ if (fixture.ddl.length && args[2].includes("SYS.ALL_IND_COLUMNS")) throw new Error("immediate dictionary unavailable");+ return originalExecute(...args);+ });+ expect(await editor!.applyChanges()).toBe(false);+ expect(fixture.ddl).toHaveLength(1);+ expect(document.body.textContent).toContain("unknown");+ expect(document.body.textContent).toContain("immediate catalog readback failed");+ expect(await editor!.applyChanges()).toBe(false);+ expect(fixture.ddl).toHaveLength(1);+ });++ it.each([false, true])("invalidates only the owner list after an index attempt (CREATE rejected: %s)", async (rejectCreate) => {+ let editor: { applyChanges: () => Promise<boolean> } | undefined;+ const { fixture } = await prepareRename(rejectCreate, loadedIndex, undefined, (instance) => {+ editor = instance;+ });+ const store = useConnectionStore();+ const refresh = vi.spyOn(store, "refreshObjectListTreeNode");+ const target = { connectionId: connection.id, database: "APP", schema: "APP" };+ const other = { ...target, schema: "OTHER" };+ cacheObjectBrowserRows(createObjectBrowserRowsCacheWriteToken(target), []);+ cacheObjectBrowserRows(createObjectBrowserRowsCacheWriteToken(other), []);+ const event = vi.fn();+ window.addEventListener("dbx-refresh-object-browser", event);+ try {+ expect(await editor!.applyChanges()).toBe(!rejectCreate);+ expect(fixture.ddl).toHaveLength(2);+ expect(refresh).toHaveBeenCalledWith(connection.id, "APP", "APP", undefined, true);+ expect(getCachedObjectBrowserRows(target)).toBeUndefined();+ expect(getCachedObjectBrowserRows(other)).toEqual([]);+ expect(event).toHaveBeenCalledWith(expect.objectContaining({ detail: expect.objectContaining(target) }));+ } finally {+ window.removeEventListener("dbx-refresh-object-browser", event);+ }});});diff --git a/apps/desktop/src/composables/useNavigationTargets.ts b/apps/desktop/src/composables/useNavigationTargets.tsindex 75241daccb..ab15876b61 100644--- a/apps/desktop/src/composables/useNavigationTargets.ts+++ b/apps/desktop/src/composables/useNavigationTargets.ts@@ -411,7 +411,13 @@ export function useNavigationTargets(dialogs: { showFieldLineageDialog: { value:await openTableTarget(target);}- async function onStructureEditorSaved(reloadData: () => Promise<void>, toast: (msg: string, duration?: number) => void, context: { connectionId: string; database: string; schema?: string; catalog?: string; tableName: string }, commentChanged?: boolean, createdTable = false) {+ async function onStructureEditorSaved(+ reloadData: () => Promise<void>,+ toast: (msg: string, duration?: number) => void,+ context: { connectionId: string; database: string; schema?: string; catalog?: string; tableName: string; exactIdentity?: boolean },+ commentChanged?: boolean,+ createdTable = false,+ ) {if (!context.tableName) {try {await connectionStore.refreshObjectListTreeNode(context.connectionId, context.database, context.schema || undefined);@@ -424,11 +430,12 @@ export function useNavigationTargets(dialogs: { showFieldLineageDialog: { value:} catch {}}connectionStore.invalidateCompletionTableCache(context.connectionId, context.database, context.tableName, context.schema, context.catalog);- queryStore.invalidateTableStructure(context.connectionId, context.database, context.schema, context.tableName);+ if (context.exactIdentity) queryStore.invalidateTableStructure(context.connectionId, context.database, context.schema, context.tableName, true, context.catalog);+ else queryStore.invalidateTableStructure(context.connectionId, context.database, context.schema, context.tableName);// 结构已变更:无论是否有打开的 data tab 都必须作废共享元数据缓存,否则// 其它 loadTableMetadata 消费者最长 30 秒拿到旧列。不带 schema/catalog// 维度(宁可多废,schema 形态在各消费点可能不同)- invalidateTableMetadataCache({ connectionId: context.connectionId, database: context.database, tableName: context.tableName });+ invalidateTableMetadataCache({ connectionId: context.connectionId, database: context.database, tableName: context.tableName, ...(context.exactIdentity ? { schema: context.schema } : {}) });const matchingDataTabs = queryStore.tabs.filter((tab) => tab.mode === "data" && tab.connectionId === context.connectionId && tab.database === context.database && tab.tableMeta?.tableName === context.tableName && (tab.schema || tab.tableMeta.schema || "") === (context.schema || ""));// 同一 catalog 只强制加载一次,结果分发给全部匹配 tabconst loadedByCatalog = new Map<string, { columns: ColumnInfo[]; primaryKeys: string[] }>();diff --git a/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts b/apps/desktop/src/composables/useSidebarTreeToolRuntime.tsindex 1a58af2cbf..852c2929fa 100644--- a/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts+++ b/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts@@ -5,6 +5,10 @@ import type { useSettingsStore } from "@/stores/settingsStore";import type { TreeNode } from "@/types/database";import { allDatabasesExportSourceForNode, databaseExportSourceForNode, sidebarSameSchemaStructureTargets } from "@/lib/sidebar/sidebarExportRuntime";import { schemaDiffRoutineKey } from "@/lib/schema/schemaDiffRoutine";+import { schemaIndexIsSameOwner, schemaIndexNodeIdentity } from "@/lib/table/schemaIndexNavigation";+import { supportsSchemaIndexManagement } from "@/lib/database/databaseObjectCapabilities";+import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";+import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";interface SidebarTreeToolRuntimeOptions {activeNode: ShallowRef<TreeNode>;@@ -186,6 +190,17 @@ export function useSidebarTreeToolRuntime(options: SidebarTreeToolRuntimeOptionsfunction openStructureEditor() {const node = activeNode.value;if (!node.connectionId || !node.database) return;+ if (node.type === "index" && node.objectScope === "schema") {+ const target = schemaIndexNodeIdentity(node);+ const config = connectionStore.getConfig(node.connectionId);+ if (!target || !config || !supportsSchemaIndexManagement(effectiveDatabaseTypeForConnection(config))) return;+ if (schemaIndexIsSameOwner(target) && !connectionIsEffectivelyReadOnly(config)) {+ queryStore.openTableStructure(node.connectionId, node.database, target.parentSchema, target.parentName, "indexes", { kind: "index", name: target.name, owner: target.schema }, node.catalog, "table", true);+ } else {+ queryStore.openObjectBrowser(node.connectionId, node.database, target.schema, node.catalog, undefined, false, "indexes", undefined, { view: target });+ }+ return;+ }if (node.type === "table") {queryStore.openTableStructure(node.connectionId, node.database, node.schema, node.label, undefined, undefined, node.catalog);return;diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 413484e855..fb00eb5420 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -196,7 +196,16 @@ export default {},sidebarMenu,oracleIndex: { mixedDraft: "Apply Oracle-family index changes separately from other table structure changes." },+ schemaIndex: {+ crossOwnerReadOnly: "Index “{owner}.{name}” is read-only in this editor.",+ editIndividually: "Manage indexes individually",+ parentUnavailable: "Parent table information is unavailable. Copy the name or refresh the list.",+ focusUnavailable: "The selected index cannot be located exactly. The readable indexes of its parent table are shown below.",+ targetMissing: "Cannot locate index “{name}” exactly. Refresh and try again.",+ },oracleStructureResult: {+ appliedRefreshPending: "Applied; refresh incomplete",+ refreshPending: "Metadata refresh is incomplete. Retrying refresh will not execute DDL again.",resultTitle: "Operation result",executionFailed: "The operation did not complete cleanly. Check each statement and the database state.",readbackFailed: "Readback failed or did not match the intended result",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 94f55012cc..07be9458ff 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -198,7 +198,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "Aplica los cambios de índices Oracle por separado de los demás cambios de estructura de tabla." },+ schemaIndex: {+ crossOwnerReadOnly: "El índice «{owner}.{name}» es de solo lectura en este editor.",+ editIndividually: "Gestionar los índices por separado",+ parentUnavailable: "No hay información de la tabla principal. Copie el nombre o actualice la lista.",+ focusUnavailable: "No se puede localizar exactamente el índice seleccionado. Se muestran los índices accesibles de su tabla principal.",+ targetMissing: "No se puede localizar exactamente el índice «{name}». Actualice e inténtelo de nuevo.",+ },oracleStructureResult: {+ appliedRefreshPending: "Aplicado; actualización incompleta",+ refreshPending: "La actualización de metadatos está incompleta. Reintentar la actualización no vuelve a ejecutar DDL.",resultTitle: "Resultado de la operación",executionFailed: "La operación no se completó por completo. Revisa cada sentencia y el estado de la base de datos.",readbackFailed: "La lectura de vuelta falló o no coincide con el resultado previsto",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex f72a7c2f79..ccd78f58ae 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -196,7 +196,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "Applica le modifiche agli indici Oracle separatamente dalle altre modifiche alla struttura della tabella." },+ schemaIndex: {+ crossOwnerReadOnly: "L'indice «{owner}.{name}» è di sola lettura in questo editor.",+ editIndividually: "Gestire gli indici singolarmente",+ parentUnavailable: "Le informazioni sulla tabella padre non sono disponibili. Copiare il nome o aggiornare l'elenco.",+ focusUnavailable: "Non è possibile individuare esattamente l'indice selezionato. Sono mostrati gli indici leggibili della tabella padre.",+ targetMissing: "Impossibile individuare esattamente l'indice «{name}». Aggiornare e riprovare.",+ },oracleStructureResult: {+ appliedRefreshPending: "Applicato; aggiornamento incompleto",+ refreshPending: "L'aggiornamento dei metadati è incompleto. Ripeterlo non esegue nuovamente il DDL.",resultTitle: "Risultato dell'operazione",executionFailed: "L'operazione non è stata completata completamente. Controlla ogni istruzione e lo stato del database.",readbackFailed: "La rilettura non è riuscita o non corrisponde al risultato previsto",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 8f9a74eda8..8110a27d7b 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -197,7 +197,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "Oracle 系インデックスの変更は、他のテーブル構造の変更と分けて適用してください。" },+ schemaIndex: {+ crossOwnerReadOnly: "インデックス「{owner}.{name}」はこのエディターでは読み取り専用です。",+ editIndividually: "インデックスは個別に管理してください",+ parentUnavailable: "親テーブルの情報がありません。名前をコピーするか一覧を更新してください。",+ focusUnavailable: "選択したインデックスを正確に特定できません。親テーブルの読み取り可能なインデックスを表示しています。",+ targetMissing: "インデックス「{name}」を正確に特定できません。更新して再試行してください。",+ },oracleStructureResult: {+ appliedRefreshPending: "適用済み・更新未完了",+ refreshPending: "メタデータの更新が完了していません。更新の再試行で DDL は再実行されません。",resultTitle: "操作結果",executionFailed: "操作が完全には完了しませんでした。各ステートメントとデータベースの状態を確認してください。",readbackFailed: "読み戻しに失敗したか、想定した結果と一致しません",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 5a88c815f8..aadd213aa4 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -195,7 +195,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "Oracle 계열 인덱스 변경은 다른 테이블 구조 변경과 분리해 적용하세요." },+ schemaIndex: {+ crossOwnerReadOnly: "이 편집기에서 인덱스 ‘{owner}.{name}’은 읽기 전용입니다.",+ editIndividually: "인덱스를 개별적으로 관리하세요",+ parentUnavailable: "상위 테이블 정보가 없습니다. 이름을 복사하거나 목록을 새로 고치세요.",+ focusUnavailable: "선택한 인덱스를 정확히 식별할 수 없습니다. 상위 테이블에서 읽을 수 있는 인덱스를 표시합니다.",+ targetMissing: "인덱스 ‘{name}’을 정확히 찾을 수 없습니다. 새로 고친 후 다시 시도하세요.",+ },oracleStructureResult: {+ appliedRefreshPending: "적용됨; 새로 고침 미완료",+ refreshPending: "메타데이터 새로 고침이 완료되지 않았습니다. 새로 고침을 다시 시도해도 DDL은 재실행되지 않습니다.",resultTitle: "작업 결과",executionFailed: "작업이 완전히 완료되지 않았습니다. 각 문과 데이터베이스 상태를 확인하세요.",readbackFailed: "다시 읽기에 실패했거나 예상한 결과와 일치하지 않습니다",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 54105c2ea9..993f6b1b79 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -197,7 +197,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "Aplique as alterações de índices Oracle separadamente das demais alterações na estrutura da tabela." },+ schemaIndex: {+ crossOwnerReadOnly: "O índice “{owner}.{name}” é somente leitura neste editor.",+ editIndividually: "Gerencie os índices individualmente",+ parentUnavailable: "As informações da tabela pai não estão disponíveis. Copie o nome ou atualize a lista.",+ focusUnavailable: "Não é possível localizar exatamente o índice selecionado. Os índices legíveis da tabela pai são exibidos abaixo.",+ targetMissing: "Não foi possível localizar exatamente o índice “{name}”. Atualize e tente novamente.",+ },oracleStructureResult: {+ appliedRefreshPending: "Aplicado; atualização incompleta",+ refreshPending: "A atualização dos metadados está incompleta. Tentar atualizar novamente não executa o DDL outra vez.",resultTitle: "Resultado da operação",executionFailed: "A operação não foi concluída por completo. Verifique cada instrução e o estado do banco de dados.",readbackFailed: "A releitura falhou ou não correspondeu ao resultado esperado",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 6ff8b4775d..fdd1c6d4d0 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -139,7 +139,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "Применяйте изменения индексов Oracle отдельно от других изменений структуры таблицы." },+ schemaIndex: {+ crossOwnerReadOnly: "Индекс «{owner}.{name}» в этом редакторе доступен только для чтения.",+ editIndividually: "Управляйте индексами по отдельности",+ parentUnavailable: "Сведения о родительской таблице недоступны. Скопируйте имя или обновите список.",+ focusUnavailable: "Невозможно точно определить выбранный индекс. Показаны доступные для чтения индексы родительской таблицы.",+ targetMissing: "Не удалось точно найти индекс «{name}». Обновите список и повторите попытку.",+ },oracleStructureResult: {+ appliedRefreshPending: "Применено; обновление не завершено",+ refreshPending: "Обновление метаданных не завершено. Повторное обновление не выполняет DDL заново.",resultTitle: "Результат операции",executionFailed: "Операция завершилась не полностью. Проверьте каждый оператор и состояние базы данных.",readbackFailed: "Обратное чтение не удалось или не совпало с ожидаемым результатом",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 36eb641c26..363aeae8c4 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -166,7 +166,16 @@ export default withEnglishFallback({},},oracleIndex: { mixedDraft: "กรุณาแยกการแก้ไข Index ของตระกูล Oracle ออกจากการแก้ไขโครงสร้างตารางอื่น" },+ schemaIndex: {+ crossOwnerReadOnly: "ดัชนี “{owner}.{name}” เป็นแบบอ่านอย่างเดียวในตัวแก้ไขนี้",+ editIndividually: "จัดการดัชนีทีละรายการ",+ parentUnavailable: "ไม่มีข้อมูลตารางแม่ คัดลอกชื่อหรือรีเฟรชรายการ",+ focusUnavailable: "ไม่สามารถระบุดัชนีที่เลือกได้อย่างแน่ชัด ด้านล่างคือดัชนีของตารางแม่ที่อ่านได้",+ targetMissing: "ไม่สามารถระบุดัชนี “{name}” ได้อย่างแน่ชัด โปรดรีเฟรชแล้วลองอีกครั้ง",+ },oracleStructureResult: {+ appliedRefreshPending: "นำไปใช้แล้ว แต่รีเฟรชยังไม่เสร็จ",+ refreshPending: "การรีเฟรชเมทาดาทายังไม่เสร็จ การลองรีเฟรชอีกครั้งจะไม่เรียกใช้ DDL ซ้ำ",resultTitle: "ผลลัพธ์การดำเนินการ",executionFailed: "การดำเนินการไม่เสร็จสมบูรณ์ กรุณาตรวจสอบผลลัพธ์แต่ละรายการและสถานะฐานข้อมูล",readbackFailed: "การอ่านกลับล้มเหลวหรือไม่ตรงกับผลลัพธ์ที่ต้องการ",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex f072ad178e..0648200dcb 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -141,7 +141,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "请将 Oracle 系索引修改与其他表结构修改分开应用。" },+ schemaIndex: {+ crossOwnerReadOnly: "索引「{owner}.{name}」在此编辑器中为只读。",+ editIndividually: "索引需逐项管理",+ parentUnavailable: "缺少父表信息,可复制名称或刷新列表。",+ focusUnavailable: "无法精确定位所选索引;以下为父表可读取的索引。",+ targetMissing: "无法精确定位索引「{name}」。请刷新后重试。",+ },oracleStructureResult: {+ appliedRefreshPending: "已应用,刷新未完成",+ refreshPending: "元数据刷新未完成。重试刷新不会重新执行 DDL。",resultTitle: "操作结果",executionFailed: "操作未完整完成,请核对逐条结果和数据库状态。",readbackFailed: "读回失败或与预期结果不一致",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex e2b6481601..8439b12ab5 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -197,7 +197,16 @@ export default withEnglishFallback({},sidebarMenu,oracleIndex: { mixedDraft: "請將 Oracle 系索引修改與其他資料表結構修改分開套用。" },+ schemaIndex: {+ crossOwnerReadOnly: "索引「{owner}.{name}」在此編輯器中為唯讀。",+ editIndividually: "索引需逐項管理",+ parentUnavailable: "缺少父資料表資訊,可複製名稱或重新整理清單。",+ focusUnavailable: "無法精確定位所選索引;以下為父資料表可讀取的索引。",+ targetMissing: "無法精確定位索引「{name}」。請重新整理後重試。",+ },oracleStructureResult: {+ appliedRefreshPending: "已套用,重新整理未完成",+ refreshPending: "中繼資料重新整理未完成。重試重新整理不會再次執行 DDL。",resultTitle: "操作結果",executionFailed: "操作未完整完成,請核對逐條結果和資料庫狀態。",readbackFailed: "讀回失敗或與預期結果不一致",diff --git a/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.tsindex 22b2f7afbe..b7f3df8636 100644--- a/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts@@ -13,6 +13,21 @@ import {import { buildObjectGroupPlaceholderNodes } from "@/lib/table/tableTree";describe("databaseObjectCapabilities", () => {+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("exposes the schema index group for %s without advertising index source", (dbType) => {+ const capabilities = databaseObjectCapabilities(dbType);+ expect(capabilities.sidebarObjects).toContain("INDEX");+ expect(capabilities.sourceReadable).not.toContain("INDEX");+ expect(+ buildObjectGroupPlaceholderNodes({+ nodeId: "connection:database:APP",+ connectionId: "connection",+ database: "database",+ schema: "APP",+ objectTypes: capabilities.sidebarObjects,+ }).map((node) => node.type),+ ).toContain("group-database-indexes");+ });+it("exposes supported programmable objects for Dameng", () => {expect(sidebarObjectKindsForDatabase("dameng")).toEqual(expect.arrayContaining(["MATERIALIZED_VIEW", "SEQUENCE", "PACKAGE", "PACKAGE_BODY"]));});@@ -27,7 +42,7 @@ describe("databaseObjectCapabilities", () => {it("exposes OceanBase Oracle sequences and synonyms through the grouped object path", () => {const oceanBaseObjects = sidebarObjectKindsForDatabase("oceanbase-oracle");- expect(oceanBaseObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY"]);+ expect(oceanBaseObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY"]);expect(databaseObjectCapabilities("oceanbase-oracle").sourceReadable).toEqual(["VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY"]);expect(buildObjectGroupPlaceholderNodes({@@ -37,13 +52,13 @@ describe("databaseObjectCapabilities", () => {schema: "APP",objectTypes: oceanBaseObjects,}).map((node) => node.type),- ).toEqual(["group-tables", "group-views", "group-materialized-views", "group-procedures", "group-functions", "group-sequences", "group-synonyms", "group-packages"]);+ ).toEqual(["group-tables", "group-views", "group-materialized-views", "group-procedures", "group-functions", "group-sequences", "group-database-indexes", "group-synonyms", "group-packages"]);});it("exposes Oracle sequences through the existing grouped object path", () => {const oracleObjects = sidebarObjectKindsForDatabase("oracle");- expect(oracleObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY"]);+ expect(oracleObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY"]);expect(databaseObjectCapabilities("oracle").sourceReadable).toContain("SEQUENCE");expect(buildObjectGroupPlaceholderNodes({diff --git a/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts b/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.tsindex a5f095f032..99beccefe3 100644--- a/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts@@ -66,6 +66,33 @@ describe("Kingbase compatibility mode routing", () => {});describe("jdbc dialect inference", () => {+ it("uses the explicit OceanBase Oracle URL before MySQL driver metadata", () => {+ const connection = {+ db_type: "jdbc" as const,+ connection_string: "jdbc:oceanbase:oracle://example.test:2881/APP",+ driver_label: "OceanBase MySQL",+ jdbc_driver_class: "com.oceanbase.jdbc.Driver",+ };+ expect(inferJdbcDialect(connection)).toBe("oceanbase-oracle");+ expect(effectiveDatabaseTypeForConnection(connection)).toBe("oceanbase-oracle");+ expect(connectionUsesConnectionRootSchemaMode(connection)).toBe(true);+ });++ it("does not infer Oracle mode for an ordinary OceanBase JDBC URL", () => {+ const connection = { db_type: "jdbc" as const, connection_string: "jdbc:oceanbase://example.test:2881/APP", driver_label: "OceanBase MySQL" };+ expect(inferJdbcDialect(connection)).toBe("mysql");+ expect(connectionUsesConnectionRootSchemaMode(connection)).toBe(false);+ });++ it("uses an approved dialect hint only for protected saved JDBC URLs", () => {+ const protectedConnection = { db_type: "jdbc" as const, connection_string: "__DBX_SAVED_CREDENTIAL__:opaque", jdbc_dialect: "oceanbase-oracle" as const };+ expect(effectiveDatabaseTypeForConnection(protectedConnection)).toBe("oceanbase-oracle");+ expect(effectiveDatabaseTypeForConnection({ ...protectedConnection, connection_string: "jdbc:mysql://host/db" })).toBe("mysql");+ expect(effectiveDatabaseTypeForConnection({ ...protectedConnection, connection_string: "" })).toBe("jdbc");+ expect(effectiveDatabaseTypeForConnection({ ...protectedConnection, db_type: "oracle" })).toBe("oracle");+ expect(effectiveDatabaseTypeForConnection({ ...protectedConnection, jdbc_dialect: "oracle" as never })).toBe("jdbc");+ });+it("detects InterSystems IRIS and Caché JDBC connections", () => {expect(inferJdbcDialect({diff --git a/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeLabel.schemaIndexes.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeLabel.schemaIndexes.spec.tsnew file mode 100644index 0000000000..d22a5839fc--- /dev/null+++ b/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeLabel.schemaIndexes.spec.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from "vitest";+import { sidebarTreeDisplayLabel } from "@/lib/sidebar/sidebarTreeLabel";+import type { TreeNode } from "@/types/database";++describe("sidebar tree labels", () => {+ it("retains the schema index load-more label for rendering and width measurement", () => {+ const node: TreeNode = { id: "indexes-more", type: "load-more", label: "tree.loadMore", loadMore: { parentId: "schema", objectType: "INDEX", offset: 100, pageSize: 100 } };+ expect(sidebarTreeDisplayLabel(node, (key) => key)).toBe("tree.indexes · tree.loadMore");+ expect(sidebarTreeDisplayLabel({ ...node, loadMore: undefined }, (key) => key)).toBe("tree.loadMore");+ });+});diff --git a/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.tsindex 5142c05be6..decba9aa98 100644--- a/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts+++ b/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import {+ copyNameForTreeNode,isDirectNavigationTreeNode,isRepeatableNavigationTreeNode,objectSourceKindForTreeNode,@@ -13,6 +14,9 @@ import {} from "@/lib/sidebar/treeNodeClick";describe("treeNodeClick", () => {+ it("copies the raw Schema index name rather than its decorated tree label", () => {+ expect(copyNameForTreeNode({ id: "index", type: "index", objectScope: "schema", objectName: ' Ix (a)" ', label: ' Ix (a)" (TABLE)', connectionId: "ob", database: "service" })).toBe(' Ix (a)" ');+ });it("opens DynamoDB tables in the document browser on single or double activation", () => {expect(treeNodeRowAction("dynamodb-table", false, "single", "dynamodb")).toBe("toggle");expect(treeNodeRowDoubleClickAction("dynamodb-table", false, "double", false, "dynamodb")).toBe("toggle");diff --git a/apps/desktop/src/lib/__tests__/table/objectBrowserRows.spec.ts b/apps/desktop/src/lib/__tests__/table/objectBrowserRows.spec.tsindex c095c46706..9b7e48aea2 100644--- a/apps/desktop/src/lib/__tests__/table/objectBrowserRows.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/objectBrowserRows.spec.ts@@ -4,6 +4,19 @@ import { buildMongoObjectBrowserRows, buildObjectBrowserRows, canonicalizeObjectimport type { TreeNode } from "@/types/database";describe("buildObjectBrowserRows", () => {+ it("keeps a schema index distinct from a table and preserves its exact parent identity", () => {+ const rows = buildObjectBrowserRows({+ objects: [{ name: " Ix (a) ", object_type: "INDEX", schema: "Index Owner", parent_schema: "Table Owner", parent_name: " T(a) " }],+ database: "database",+ fallbackSchema: "Index Owner",+ });++ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ name: " Ix (a) ", displayName: " Ix (a) ", type: "INDEX", schema: "Index Owner", parentSchema: "Table Owner", parentName: " T(a) " });+ expect(rows[0]?.partitionParentSchema).toBeUndefined();+ expect(rows[0]?.partitionParentName).toBeUndefined();+ });+it("preserves a resolved SQLite attached-database alias on every row", () => {const rows = buildObjectBrowserRows({objects: [{ name: "events", object_type: "TABLE" }],diff --git a/apps/desktop/src/lib/__tests__/table/tableTree.spec.ts b/apps/desktop/src/lib/__tests__/table/tableTree.spec.tsindex 43c51a9587..c778056e1d 100644--- a/apps/desktop/src/lib/__tests__/table/tableTree.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/tableTree.spec.ts@@ -23,6 +23,16 @@ const context = {};describe("case-sensitive database objects", () => {+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("preserves schema index identities in both %s layouts", (databaseType) => {+ const objects: ObjectInfo[] = [{ name: " Ix (a) ", object_type: "INDEX", schema: " Index Owner ", parent_schema: "Table Owner", parent_name: " T(a) " }];+ const simple = buildSimpleObjectTreeNodes({ ...context, databaseType, objects });+ const grouped = buildGroupedObjectTreeNodes({ ...context, databaseType, objects }).find((group) => group.type === "group-database-indexes")?.children;+ for (const nodes of [simple, grouped]) {+ expect(nodes).toHaveLength(1);+ expect(nodes?.[0]).toMatchObject({ type: "index", objectScope: "schema", objectName: " Ix (a) ", schema: " Index Owner ", parentSchema: "Table Owner", parentName: " T(a) " });+ }+ });+it("publishes each changed partition group once per page while retaining exact identities", () => {const current = buildTableTreeNodes({...context,diff --git a/apps/desktop/src/lib/app/openTabsPersistence.ts b/apps/desktop/src/lib/app/openTabsPersistence.tsindex bc49e723e9..8001117d0c 100644--- a/apps/desktop/src/lib/app/openTabsPersistence.ts+++ b/apps/desktop/src/lib/app/openTabsPersistence.ts@@ -68,6 +68,7 @@ export interface SavedOpenTab {nacosNamespace?: string;nacosNamespaceName?: string;structureTableName?: string;+ structureExactIdentity?: boolean;structureDraft?: QueryTab["structureDraft"];databaseSearchState?: QueryTab["databaseSearchState"];objectBrowser?: QueryTab["objectBrowser"];@@ -219,6 +220,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {...(tab.nacosNamespace !== undefined ? { nacosNamespace: tab.nacosNamespace } : {}),...(tab.nacosNamespaceName !== undefined ? { nacosNamespaceName: tab.nacosNamespaceName } : {}),...(tab.structureTableName !== undefined ? { structureTableName: tab.structureTableName } : {}),+ ...(tab.structureExactIdentity ? { structureExactIdentity: true } : {}),...(tab.structureDraft ? { structureDraft: JSON.parse(JSON.stringify(tab.structureDraft)) } : {}),...(tab.databaseSearchState ? { databaseSearchState: tab.databaseSearchState } : {}),objectBrowser: tab.objectBrowser,diff --git a/apps/desktop/src/lib/backend/__tests__/exactMetadataTransport.spec.ts b/apps/desktop/src/lib/backend/__tests__/exactMetadataTransport.spec.tsnew file mode 100644index 0000000000..fa47229949--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/exactMetadataTransport.spec.ts@@ -0,0 +1,61 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++const invoke = vi.hoisted(() => vi.fn().mockResolvedValue([]));+vi.mock("@tauri-apps/api/core", () => ({ invoke, Channel: class {} }));+import * as tauri from "@/lib/backend/tauri";+import * as http from "@/lib/backend/http";++const owner = " Mixed Owner ";+const table = ' T(a)" ';++describe("exact metadata transports", () => {+ beforeEach(() => {+ invoke.mockClear();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(() => Promise.resolve(new Response("[]", { status: 200 }))),+ );+ });+ afterEach(() => vi.unstubAllGlobals());++ const calls = [+ ["tables", (api: typeof tauri | typeof http, exact?: boolean) => api.listTables("conn", "db", owner, "Ix", 2, 1, ["TABLE"], undefined, undefined, exact)],+ ["objects", (api: typeof tauri | typeof http, exact?: boolean) => api.listObjects("conn", "db", owner, ["INDEX"], "Ix", 2, 1, undefined, undefined, "request", exact)],+ ["columns", (api: typeof tauri | typeof http, exact?: boolean) => api.getColumns("conn", "db", owner, table, undefined, undefined, undefined, exact)],+ ["indexes", (api: typeof tauri | typeof http, exact?: boolean) => api.listIndexes("conn", "db", owner, table, undefined, exact)],+ ["foreign-keys", (api: typeof tauri | typeof http, exact?: boolean) => api.listForeignKeys("conn", "db", owner, table, undefined, exact)],+ ["constraints", (api: typeof tauri | typeof http, exact?: boolean) => api.listConstraints("conn", "db", owner, table, undefined, exact)],+ ["triggers", (api: typeof tauri | typeof http, exact?: boolean) => api.listTriggers("conn", "db", owner, table, undefined, exact)],+ ["ddl", (api: typeof tauri | typeof http, exact?: boolean) => api.getTableDdl("conn", "db", owner, table, undefined, undefined, false, exact)],+ ] as const;++ test.each(calls)("Tauri %s opts in without changing raw identity or legacy payloads", async (_name, call) => {+ await call(tauri, true);+ expect(invoke.mock.calls[0][1]).toMatchObject({ schema: owner, exactIdentity: true });+ if (invoke.mock.calls[0][1].table !== undefined) expect(invoke.mock.calls[0][1].table).toBe(table);+ await call(tauri);+ expect(invoke.mock.calls[1][1]).not.toHaveProperty("exactIdentity");+ });++ test.each(calls)("HTTP %s opts in without changing raw identity or legacy requests", async (_name, call) => {+ await call(http, true);+ const exact = new URL(String(vi.mocked(fetch).mock.calls[0][0]), "http://localhost");+ expect(exact.searchParams.get("schema")).toBe(owner);+ expect(exact.searchParams.get("exact_identity")).toBe("true");+ if (exact.searchParams.has("table")) expect(exact.searchParams.get("table")).toBe(table);+ await call(http);+ const legacy = new URL(String(vi.mocked(fetch).mock.calls[1][0]), "http://localhost");+ expect(legacy.searchParams.has("exact_identity")).toBe(false);+ });++ test("both comment requests preserve the exact parent", async () => {+ await tauri.getTableComment("conn", "db", owner, table, undefined, true);+ expect(invoke.mock.calls[0]).toEqual(["get_table_comment", expect.objectContaining({ schema: owner, table, exactIdentity: true })]);+ await http.getTableComment("conn", "db", owner, table, undefined, true);+ const url = new URL(String(vi.mocked(fetch).mock.calls[0][0]), "http://localhost");+ expect(url.pathname).toBe("/api/schema/table-comment");+ expect(url.searchParams.get("schema")).toBe(owner);+ expect(url.searchParams.get("table")).toBe(table);+ expect(url.searchParams.get("exact_identity")).toBe("true");+ });+});diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex a0b13a9c0e..e8a722de30 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -1231,19 +1231,31 @@ export async function listSchemaInfos(connectionId: string, database: string): Preturn schemas.map((name) => ({ name, comment: null }));}-export async function listTables(connectionId: string, database: string, schema: string, filter?: string, limit?: number, offset?: number, objectTypes?: SidebarObjectKind[], catalog?: string, tableNameFilter?: TableNameFilter): Promise<TableInfo[]> {- return get(`/api/schema/tables?${qs({ connection_id: connectionId, database, schema, filter, limit, offset, object_types: objectTypes?.join(","), catalog, table_name_filter: tableNameFilter ? JSON.stringify(tableNameFilter) : undefined })}`);+export async function listTables(connectionId: string, database: string, schema: string, filter?: string, limit?: number, offset?: number, objectTypes?: SidebarObjectKind[], catalog?: string, tableNameFilter?: TableNameFilter, exactIdentity?: boolean): Promise<TableInfo[]> {+ return get(`/api/schema/tables?${qs({ connection_id: connectionId, database, schema, filter, limit, offset, object_types: objectTypes?.join(","), catalog, table_name_filter: tableNameFilter ? JSON.stringify(tableNameFilter) : undefined, exact_identity: exactIdentity || undefined })}`);}-export async function getTableComment(_connectionId: string, _database: string, _schema: string, _table: string, _catalog?: string): Promise<string | null> {- throw new Error("Table comment lookup is not available in the web backend");+export async function getTableComment(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<string | null> {+ return get(`/api/schema/table-comment?${qs({ connection_id: connectionId, database, schema, table, catalog, exact_identity: exactIdentity || undefined })}`);}export async function getMysqlTableAutoIncrement(connectionId: string, database: string, table: string): Promise<string | null> {return get(`/api/schema/mysql/auto-increment?${qs({ connection_id: connectionId, database, table })}`);}-export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: TableNameFilter, executionId?: string): Promise<ObjectInfo[]> {+export async function listObjects(+ connectionId: string,+ database: string,+ schema: string,+ objectTypes?: (SidebarObjectKind | "EVENT")[],+ filter?: string,+ limit?: number,+ offset?: number,+ catalog?: string,+ tableNameFilter?: TableNameFilter,+ executionId?: string,+ exactIdentity?: boolean,+): Promise<ObjectInfo[]> {return get(`/api/schema/objects?${qs({connection_id: connectionId,@@ -1256,6 +1268,7 @@ export async function listObjects(connectionId: string, database: string, schemacatalog,table_name_filter: tableNameFilter ? JSON.stringify(tableNameFilter) : undefined,execution_id: executionId,+ exact_identity: exactIdentity || undefined,})}`,);}@@ -1284,8 +1297,8 @@ export async function getCustomTypeDetails(connectionId: string, database: strinreturn get(`/api/schema/custom-type-details?${qs({ connection_id: connectionId, database, schema, table: name })}`);}-export async function getColumns(connectionId: string, database: string, schema: string, table: string, catalog?: string, clientSessionId?: string, currentSchema?: string): Promise<ColumnInfo[]> {- return get(`/api/schema/columns?${qs({ connection_id: connectionId, database, schema, table, catalog, client_session_id: clientSessionId, current_schema: currentSchema })}`);+export async function getColumns(connectionId: string, database: string, schema: string, table: string, catalog?: string, clientSessionId?: string, currentSchema?: string, exactIdentity?: boolean): Promise<ColumnInfo[]> {+ return get(`/api/schema/columns?${qs({ connection_id: connectionId, database, schema, table, catalog, client_session_id: clientSessionId, current_schema: currentSchema, exact_identity: exactIdentity || undefined })}`);}export async function getPluginTableMetadata(request: PluginTableMetadataRequest): Promise<PluginTableMetadata> {@@ -1310,8 +1323,8 @@ export async function listDataTypes(connectionId: string, database: string): Proreturn get(`/api/schema/data-types?${qs({ connection_id: connectionId, database })}`);}-export async function listIndexes(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<IndexInfo[]> {- return get(`/api/schema/indexes?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);+export async function listIndexes(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<IndexInfo[]> {+ return get(`/api/schema/indexes?${qs({ connection_id: connectionId, database, schema, table, catalog, exact_identity: exactIdentity || undefined })}`);}export async function listReferenceKeyColumns(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<string[]> {@@ -1322,20 +1335,20 @@ export async function listReferenceKeys(connectionId: string, database: string,return get(`/api/schema/reference-keys?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);}-export async function listForeignKeys(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<ForeignKeyInfo[]> {- return get(`/api/schema/foreign-keys?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);+export async function listForeignKeys(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<ForeignKeyInfo[]> {+ return get(`/api/schema/foreign-keys?${qs({ connection_id: connectionId, database, schema, table, catalog, exact_identity: exactIdentity || undefined })}`);}export async function listForeignKeysForDatabase(connectionId: string, database: string, schema: string, catalog?: string, executionId?: string): Promise<Record<string, ForeignKeyInfo[]>> {return get(`/api/schema/foreign-keys-for-database?${qs({ connection_id: connectionId, database, schema, catalog, execution_id: executionId })}`);}-export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<TriggerInfo[]> {- return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);+export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<TriggerInfo[]> {+ return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table, catalog, exact_identity: exactIdentity || undefined })}`);}-export async function listConstraints(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<ConstraintInfo[]> {- return get(`/api/schema/constraints?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);+export async function listConstraints(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<ConstraintInfo[]> {+ return get(`/api/schema/constraints?${qs({ connection_id: connectionId, database, schema, table, catalog, exact_identity: exactIdentity || undefined })}`);}export async function listPartitions(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<PartitionInfo[]> {@@ -1364,8 +1377,8 @@ export async function listSubpartitions(connectionId: string, database: string,return get(`/api/schema/subpartitions?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);}-export async function getTableDdl(connectionId: string, database: string, schema: string, table: string, objectType?: ObjectSourceKind, catalog?: string, portable = false): Promise<string> {- return get(`/api/schema/ddl?${qs({ connection_id: connectionId, database, schema, table, object_type: objectType, catalog, portable })}`);+export async function getTableDdl(connectionId: string, database: string, schema: string, table: string, objectType?: ObjectSourceKind, catalog?: string, portable = false, exactIdentity?: boolean): Promise<string> {+ return get(`/api/schema/ddl?${qs({ connection_id: connectionId, database, schema, table, object_type: objectType, catalog, portable, exact_identity: exactIdentity || undefined })}`);}export async function getTableDisplayDdl(connectionId: string, database: string, schema: string, table: string, objectType?: ObjectSourceKind, catalog?: string): Promise<string> {diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 6d3b72f1ff..a64264fa4c 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -1803,7 +1803,18 @@ export async function deleteSchemaCachePrefix(prefix: string): Promise<void> {return invoke("delete_schema_cache_prefix", { prefix });}-export async function listTables(connectionId: string, database: string, schema: string, filter?: string, limit?: number, offset?: number, objectTypes?: SidebarObjectKind[], catalog?: string, tableNameFilter?: import("@/types/database").TableNameFilter): Promise<TableInfo[]> {+export async function listTables(+ connectionId: string,+ database: string,+ schema: string,+ filter?: string,+ limit?: number,+ offset?: number,+ objectTypes?: SidebarObjectKind[],+ catalog?: string,+ tableNameFilter?: import("@/types/database").TableNameFilter,+ exactIdentity?: boolean,+): Promise<TableInfo[]> {return invoke("list_tables", {connectionId,database,@@ -1814,16 +1825,18 @@ export async function listTables(connectionId: string, database: string, schema:objectTypes,catalog,tableNameFilter,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}-export async function getTableComment(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<string | null> {+export async function getTableComment(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<string | null> {return invoke("get_table_comment", {connectionId,database,schema,table,catalog,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}@@ -1842,6 +1855,7 @@ export async function listObjects(catalog?: string,tableNameFilter?: import("@/types/database").TableNameFilter,executionId?: string,+ exactIdentity?: boolean,): Promise<ObjectInfo[]> {return invoke("list_objects", {connectionId,@@ -1854,6 +1868,7 @@ export async function listObjects(catalog,tableNameFilter,executionId,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}@@ -1896,7 +1911,7 @@ export async function listSchemaInfos(connectionId: string, database: string): Pexport async function getCustomTypeDetails(connectionId: string, database: string, schema: string, name: string): Promise<CustomTypeDetails> {return invoke("get_custom_type_details", { connectionId, database, schema, name });}-export async function getColumns(connectionId: string, database: string, schema: string, table: string, catalog?: string, clientSessionId?: string, currentSchema?: string): Promise<ColumnInfo[]> {+export async function getColumns(connectionId: string, database: string, schema: string, table: string, catalog?: string, clientSessionId?: string, currentSchema?: string, exactIdentity?: boolean): Promise<ColumnInfo[]> {return invoke("get_columns", {connectionId,database,@@ -1905,6 +1920,7 @@ export async function getColumns(connectionId: string, database: string, schema:catalog,clientSessionId,currentSchema,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}@@ -2646,13 +2662,14 @@ export async function buildDataCompareSyncPlan(options: DataCompareSyncPlanOptioreturn invoke("build_data_compare_sync_plan", { options });}-export async function listIndexes(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<IndexInfo[]> {+export async function listIndexes(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<IndexInfo[]> {return invoke("list_indexes", {connectionId,database,schema,table,catalog,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}@@ -2676,13 +2693,14 @@ export async function listReferenceKeys(connectionId: string, database: string,});}-export async function listForeignKeys(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<ForeignKeyInfo[]> {+export async function listForeignKeys(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<ForeignKeyInfo[]> {return invoke("list_foreign_keys", {connectionId,database,schema,table,catalog,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}@@ -2690,23 +2708,25 @@ export async function listForeignKeysForDatabase(connectionId: string, database:return invoke("list_foreign_keys_for_database", { connectionId, database, schema, catalog, executionId });}-export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<TriggerInfo[]> {+export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<TriggerInfo[]> {return invoke("list_triggers", {connectionId,database,schema,table,catalog,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}-export async function listConstraints(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<ConstraintInfo[]> {+export async function listConstraints(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<ConstraintInfo[]> {return invoke("list_constraints", {connectionId,database,schema,table,catalog,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}@@ -2763,7 +2783,7 @@ export async function listSubpartitions(connectionId: string, database: string,});}-export async function getTableDdl(connectionId: string, database: string, schema: string, table: string, objectType?: ObjectSourceKind, catalog?: string, portable = false): Promise<string> {+export async function getTableDdl(connectionId: string, database: string, schema: string, table: string, objectType?: ObjectSourceKind, catalog?: string, portable = false, exactIdentity?: boolean): Promise<string> {return invoke("get_table_ddl", {connectionId,database,@@ -2772,6 +2792,7 @@ export async function getTableDdl(connectionId: string, database: string, schemaobjectType,catalog,portable,+ ...(exactIdentity ? { exactIdentity: true } : {}),});}diff --git a/apps/desktop/src/lib/connection/__tests__/connectionDatabaseInfo.spec.ts b/apps/desktop/src/lib/connection/__tests__/connectionDatabaseInfo.spec.tsindex 1fa8271f20..09b4d64c8a 100644--- a/apps/desktop/src/lib/connection/__tests__/connectionDatabaseInfo.spec.ts+++ b/apps/desktop/src/lib/connection/__tests__/connectionDatabaseInfo.spec.ts@@ -87,6 +87,7 @@ describe("connectionDatabaseInfo", () => {expect(connectionConfigFingerprint({ ...original, default_schema: "archive" })).toBe(connectionConfigFingerprint(original));expect(connectionConfigFingerprint({ ...original, sidebar_auto_load_all_tables: true })).toBe(connectionConfigFingerprint(original));expect(connectionConfigFingerprint({ ...original, show_database_links: false })).toBe(connectionConfigFingerprint(original));+ expect(connectionConfigFingerprint({ ...original, jdbc_dialect: "oceanbase-oracle" })).toBe(connectionConfigFingerprint(original));});it("formats only database metadata for rows and copied text", () => {diff --git a/apps/desktop/src/lib/connection/connectionDatabaseInfo.ts b/apps/desktop/src/lib/connection/connectionDatabaseInfo.tsindex 7e09b0afac..6f84a90c4e 100644--- a/apps/desktop/src/lib/connection/connectionDatabaseInfo.ts+++ b/apps/desktop/src/lib/connection/connectionDatabaseInfo.ts@@ -95,7 +95,7 @@ function fnv1a(value: string, seed: number): number {}export function connectionConfigFingerprint(config: ConnectionConfig, sourceName = config.name): string {- const { database_info: _databaseInfo, default_schema: _defaultSchema, note: _note, show_database_links: _showDatabaseLinks, sidebar_auto_load_all_tables: _sidebarAutoLoadAllTables, redis_key_filter: _redisKeyFilter, ...submittedConfig } = config;+ const { database_info: _databaseInfo, default_schema: _defaultSchema, note: _note, show_database_links: _showDatabaseLinks, sidebar_auto_load_all_tables: _sidebarAutoLoadAllTables, redis_key_filter: _redisKeyFilter, jdbc_dialect: _jdbcDialect, ...submittedConfig } = config;const serialized = JSON.stringify(stableValue({ config: submittedConfig, sourceName }));const first = fnv1a(serialized, 0x811c9dc5).toString(16).padStart(8, "0");const second = fnv1a(serialized, 0x9e3779b9).toString(16).padStart(8, "0");diff --git a/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.tsindex f57c42a3d5..5cd37f4b6d 100644--- a/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.ts+++ b/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import * as api from "@/lib/backend/api";-import { executeOracleIndexPlan, mergeOracleIndexDraftsAfterRefresh, oracleIndexSnapshotMatchesLoadedColumns, prepareOracleIndexPlan } from "../oracleIndexes";+import { executeOracleIndexPlan, mergeOracleIndexDraftsAfterRefresh, oracleIndexSnapshotMatchesLoaded, oracleIndexSnapshotMatchesLoadedColumns, prepareOracleIndexPlan } from "../oracleIndexes";+import { createIndexDrafts } from "@/lib/table/tableStructureEditorState";import { readOracleConstraintSnapshot, readOracleIndexSnapshot } from "../oracleConstraints";vi.mock("@/lib/backend/api", () => ({ executeQuery: vi.fn(), listConstraints: vi.fn() }));@@ -112,6 +113,71 @@ describe("Oracle index plans", () => {expect(snapshot.indexes.map((index) => index.name)).toEqual(["IX_OLD"]);});+ it("does not accept a different dictionary owner as the same loaded index", async () => {+ const snapshot = await readOracleIndexSnapshot(target);+ const loaded = { ...drafts[0]!.original!, owner: "Other" };+ expect(oracleIndexSnapshotMatchesLoaded(snapshot, target, createIndexDrafts([loaded]))).toBe(false);+ expect(oracleIndexSnapshotMatchesLoaded(snapshot, target, createIndexDrafts([{ ...loaded, owner: "APP" }]))).toBe(true);+ });++ it("keeps draft IDs and refresh matching independent for equal index names under different owners", () => {+ const actual = ["APP", "Other"].map((owner) => ({ ...drafts[0]!.original!, owner }));+ const current = createIndexDrafts(actual);+ expect(new Set(current.map((draft) => draft.id)).size).toBe(2);+ const merged = mergeOracleIndexDraftsAfterRefresh(current, actual, []);+ expect(merged.map((draft) => draft.original?.owner)).toEqual(["APP", "Other"]);+ expect(merged.every((draft) => !draft.oracleOriginalMissing)).toBe(true);+ expect(createIndexDrafts([drafts[0]!.original!])[0]!.id).toBe("existing:IX_OLD");+ });++ it("refreshes an ownerless legacy draft from a unique dictionary row without changing its ID", () => {+ const [legacy] = createIndexDrafts([drafts[0]!.original!]);+ const actual = { ...drafts[0]!.original!, owner: "APP" };+ const merged = mergeOracleIndexDraftsAfterRefresh([legacy!], [actual], []);++ expect(merged).toHaveLength(1);+ expect(merged[0]).toMatchObject({ id: "existing:IX_OLD", original: actual, oracleOriginalMissing: false });+ });++ it("does not resolve an ambiguous legacy owner after another draft consumes one same-name row", () => {+ const actual = ["APP", "Other"].map((owner) => ({ ...drafts[0]!.original!, owner }));+ const [known] = createIndexDrafts([actual[0]!]);+ const [legacy] = createIndexDrafts([drafts[0]!.original!]);+ const merged = mergeOracleIndexDraftsAfterRefresh([known!, { ...legacy!, markedForDrop: true }], actual, []);++ expect(merged).toHaveLength(3);+ expect(merged[0]).toMatchObject({ id: known!.id, original: { owner: "APP" }, oracleOriginalMissing: false });+ expect(merged[1]).toMatchObject({ id: legacy!.id, markedForDrop: true, oracleOriginalMissing: true });+ expect(merged[1]!.original!.owner).toBeUndefined();+ expect(merged[2]!.original!.owner).toBe("Other");+ });++ it("keeps a deletion draft unverifiable when dictionary identity is duplicated", () => {+ const actual = { ...drafts[0]!.original!, owner: "APP" };+ const [draft] = createIndexDrafts([actual]);+ const merged = mergeOracleIndexDraftsAfterRefresh([{ ...draft!, markedForDrop: true }], [actual, { ...actual }], []);++ expect(merged[0]).toMatchObject({ id: draft!.id, markedForDrop: true, oracleOriginalMissing: true });+ });++ it.each(["APP", "Other", undefined])("reconciles a completed CREATE only with its authoritative or uniquely ownerless readback (%s)", async (owner) => {+ const expected = (await readOracleIndexSnapshot(target)).indexes[0]!;+ const draft = { ...drafts[1]!, name: expected.name };+ const actual = { ...drafts[0]!.original!, owner };+ const merged = mergeOracleIndexDraftsAfterRefresh([draft], [actual], [expected]);++ expect(merged[0]!.id).toBe(draft.id);+ if (owner === "Other") {+ expect(merged).toHaveLength(2);+ expect(merged[0]!.original).toBeUndefined();+ expect(merged[1]!.original!.owner).toBe("Other");+ } else {+ expect(merged).toHaveLength(1);+ expect(merged[0]!.original!.owner).toBe(owner);+ expect(merged[0]!.oracleOriginalMissing).toBe(false);+ }+ });+it("reads a target snapshot when unrelated owner index names exceed the row limit", async () => {otherOwnerIndexNames = Array.from({ length: 10_000 }, (_, i) => `IX_OTHER_${i}`);diff --git a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts b/apps/desktop/src/lib/database/databaseObjectCapabilities.tsindex 3be3347f13..4f76bc11c3 100644--- a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts+++ b/apps/desktop/src/lib/database/databaseObjectCapabilities.ts@@ -33,9 +33,13 @@ const KINGBASE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIconst VASTBASE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "TYPE"];const POSTGRES_LIKE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION"];-const ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY"];-const OCEANBASE_ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY"];-const DAMENG_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "PACKAGE", "PACKAGE_BODY"];+const ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY"];+const OCEANBASE_ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY"];+const DAMENG_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "PACKAGE", "PACKAGE_BODY"];++export function supportsSchemaIndexManagement(dbType?: DatabaseType): boolean {+ return dbType === "oracle" || dbType === "oceanbase-oracle" || dbType === "dameng";+}const XUGU_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];const FIREBIRD_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION_INTERNAL", "FUNCTION_UDF", "TRIGGER", "SEQUENCE", "INDEX", "PACKAGE"];const PACKAGE_MEMBER_EXPANSION_DATABASES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "xugu"]);diff --git a/apps/desktop/src/lib/database/jdbcDialect.ts b/apps/desktop/src/lib/database/jdbcDialect.tsindex 478a2a3f74..484176948f 100644--- a/apps/desktop/src/lib/database/jdbcDialect.ts+++ b/apps/desktop/src/lib/database/jdbcDialect.ts@@ -1,8 +1,9 @@import type { ConnectionConfig, DatabaseType } from "@/types/database";import { isSchemaAware, spannerObjectTreeSchema, usesDatabaseObjectTreeMode, usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";import type { CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";+import { isSavedCredential } from "@/lib/security/passwordViewer";-export type JdbcDialectConnection = Partial<Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "connection_string" | "url_params" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info" | "external_config" | "username">>;+export type JdbcDialectConnection = Partial<Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "connection_string" | "jdbc_dialect" | "url_params" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info" | "external_config" | "username">>;export type GaussdbIdentifierQuoteStyle = "auto" | "double" | "backtick";export type GaussdbConnectionMode = "native" | "m-jdbc" | "dws";@@ -59,6 +60,9 @@ const JDBC_ASE_PROFILE_PATTERNS = [/(?:^|[\s_-])ase(?:$|[\s_-])/i, /\bsap[\s_-]+export function inferJdbcDialect(connection?: JdbcDialectConnection): DatabaseType | undefined {if (!connection || connection.db_type !== "jdbc") return undefined;if (isGbase8sProfile(connection.driver_profile)) return undefined;+ const connectionString = connection.connection_string?.trim() ?? "";+ if (isSavedCredential(connectionString) && connection.jdbc_dialect === "oceanbase-oracle") return "oceanbase-oracle";+ if (/^jdbc:oceanbase:oracle:\/\//i.test(connectionString)) return "oceanbase-oracle";const haystack = [connection.driver_profile, connection.driver_label, connection.connection_string, connection.jdbc_driver_class, ...(connection.jdbc_driver_paths ?? []), connection.database_info?.productName, connection.database_info?.serverComment, connection.database_info?.driverName].filter(Boolean).join("\n");diff --git a/apps/desktop/src/lib/database/oracleConstraints.ts b/apps/desktop/src/lib/database/oracleConstraints.tsindex 8de7aa7a83..2d95c75ecf 100644--- a/apps/desktop/src/lib/database/oracleConstraints.ts+++ b/apps/desktop/src/lib/database/oracleConstraints.ts@@ -10,6 +10,7 @@ export interface OracleConstraintTarget {tableName: string;catalog?: string;databaseType: "oracle" | "oceanbase-oracle";+ exactIdentity?: boolean;}export interface OracleConstraintSnapshot {diff --git a/apps/desktop/src/lib/database/oracleIndexes.ts b/apps/desktop/src/lib/database/oracleIndexes.tsindex ae21e9202b..98156528ff 100644--- a/apps/desktop/src/lib/database/oracleIndexes.ts+++ b/apps/desktop/src/lib/database/oracleIndexes.ts@@ -67,6 +67,7 @@ function sameTargetIdentity(left: OracleIndexSnapshot, right: OracleIndexSnapshofunction actualIndexMatchesLoaded(index: OracleIndexDefinition, original: IndexInfo, target: OracleConstraintTarget): boolean {return (index.owner === target.schema &&+ (original.owner == null || original.owner === index.owner) &&index.tableOwner === target.schema &&index.tableName === target.tableName &&index.name === original.name &&@@ -245,6 +246,7 @@ function expectedCreatedIndex(draft: EditableStructureIndex, target: OracleConstfunction completedCreateMatchesLoaded(index: IndexInfo, expected: OracleIndexDefinition): boolean {return (+ (index.owner == null || index.owner === expected.owner) &&index.name === expected.name &&index.is_unique === (expected.uniqueness === "UNIQUE") &&!index.is_primary &&@@ -259,28 +261,43 @@ function completedCreateMatchesLoaded(index: IndexInfo, expected: OracleIndexDef}export function mergeOracleIndexDraftsAfterRefresh(drafts: EditableStructureIndex[], actualIndexes: IndexInfo[], completedCreates: OracleIndexDefinition[]): EditableStructureIndex[] {- const loadedByName = new Map(actualIndexes.map((index) => [index.name, index]));+ // Resolve uniqueness against the complete readback, never against a map that+ // earlier drafts have already consumed. Unknown legacy owners may match one+ // unique name; known owners cannot claim a different owner's row.+ const byName = new Map<string, IndexInfo[]>();+ for (const index of actualIndexes) byName.set(index.name, [...(byName.get(index.name) ?? []), index]);+ const remaining = new Set(actualIndexes);+ const findActual = (name: string, owner?: string | null, completed = false) => {+ const named = byName.get(name) ?? [];+ const candidates = owner == null ? named : named.filter((index) => index.owner === owner || (completed && index.owner == null && named.length === 1));+ return candidates.length === 1 && remaining.has(candidates[0]!) ? candidates[0] : undefined;+ };const refreshedDrafts: EditableStructureIndex[] = [];for (const draft of drafts) {- const current = loadedByName.get(draft.original?.name || draft.name);+ const completed = completedCreates.filter((created) => created.name === draft.name);+ const expected = completed.length === 1 ? completed[0] : undefined;+ if (!draft.original && !expected) {+ refreshedDrafts.push(draft);+ continue;+ }+ const current = draft.original ? findActual(draft.original.name, draft.original.owner) : expected && findActual(expected.name, expected.owner, true);if (current) {- loadedByName.delete(current.name);+ remaining.delete(current);refreshedDrafts.push({ ...draft, original: current, indexType: current.index_type ?? draft.indexType, oracleOriginalMissing: false, isPrimary: current.is_primary });continue;}if (draft.original) {- const expected = completedCreates.find((index) => index.name === draft.name);- const actual = loadedByName.get(draft.name);+ const actual = expected && findActual(expected.name, expected.owner, true);if (expected && actual && completedCreateMatchesLoaded(actual, expected)) {- loadedByName.delete(actual.name);+ remaining.delete(actual);const committedDraft = { ...draft, original: actual, indexType: actual.index_type ?? draft.indexType, oracleOriginalMissing: false, isPrimary: actual.is_primary };refreshedDrafts.push(draftMatchesCompletedCreate(committedDraft, expected) ? createIndexDrafts([actual])[0]! : committedDraft);continue;}}- if (!draft.markedForDrop) refreshedDrafts.push({ ...draft, oracleOriginalMissing: !!draft.original, isPrimary: false });+ if (!draft.markedForDrop || (draft.original && byName.has(draft.original.name))) refreshedDrafts.push({ ...draft, oracleOriginalMissing: !!draft.original, isPrimary: false });}- return [...refreshedDrafts, ...createIndexDrafts([...loadedByName.values()])];+ return [...refreshedDrafts, ...createIndexDrafts([...remaining])];}function draftMatchesCompletedCreate(draft: EditableStructureIndex, expected: OracleIndexDefinition): boolean {diff --git a/apps/desktop/src/lib/metadata/__tests__/objectDdlCache.spec.ts b/apps/desktop/src/lib/metadata/__tests__/objectDdlCache.spec.tsindex 9c43d6765b..636af11927 100644--- a/apps/desktop/src/lib/metadata/__tests__/objectDdlCache.spec.ts+++ b/apps/desktop/src/lib/metadata/__tests__/objectDdlCache.spec.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({+ getTableDdl: vi.fn(),getTableDisplayDdl: vi.fn(),saveSchemaCache: vi.fn(),loadSchemaCache: vi.fn(),@@ -39,6 +40,7 @@ describe("objectDdlCache", () => {clearMetadataRuntimeCache();vi.clearAllMocks();mocks.getTableDisplayDdl.mockReset();+ mocks.getTableDdl.mockReset();mocks.persisted.clear();mocks.loadSchemaCache.mockImplementation(async (cacheKey: string) => mocks.persisted.get(cacheKey) ?? null);mocks.saveSchemaCache.mockImplementation(async (cacheKey: string, payload: unknown) => {@@ -58,6 +60,21 @@ describe("objectDdlCache", () => {expect(mocks.getTableDisplayDdl).not.toHaveBeenCalled();});+ it("keeps exact DDL separate and never trusts or persists an unverified process snapshot", async () => {+ mocks.loadSchemaCache.mockResolvedValue({ version: 1, cachedAt: new Date().toISOString(), ddl: "legacy" });+ await loadObjectDdl(request);+ const exact = { ...request, schema: " Mixed ", tableName: " T(a) ", exactIdentity: true };+ mocks.getTableDdl.mockResolvedValue("exact");+ expect(objectDdlCacheKey(exact)).not.toBe(objectDdlCacheKey({ ...exact, exactIdentity: false }));+ await expect(loadObjectDdl(exact)).resolves.toEqual({ ddl: "exact", cacheStatus: "remote" });+ expect(mocks.getTableDdl).toHaveBeenCalledExactlyOnceWith("c1", "app", " Mixed ", " T(a) ", undefined, "analytics", false, true);+ expect(mocks.loadSchemaCache).toHaveBeenCalledOnce();+ expect(mocks.saveSchemaCache).not.toHaveBeenCalled();+ cancelObjectDdlLoadsForConnection("c1");+ mocks.getTableDdl.mockRejectedValueOnce(new Error("exact capability unavailable"));+ await expect(loadObjectDdl(exact)).rejects.toThrow("exact capability unavailable");+ });+it("backfills memory after a disk hit", async () => {mocks.loadSchemaCache.mockResolvedValue({ version: 1, cachedAt: new Date().toISOString(), ddl: "CREATE TABLE users (id int)" });diff --git a/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.ts b/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.tsindex b12a93e505..8ebb442a84 100644--- a/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.ts+++ b/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.ts@@ -81,6 +81,19 @@ describe("objectMetadataCache", () => {expect(loader).not.toHaveBeenCalled();});+ it("does not grant an exact baseline from legacy memory or any persisted facet", async () => {+ mocks.loadSchemaCache.mockResolvedValue({ version: 1, cachedAt: new Date().toISOString(), value: ["legacy"] });+ const loader = vi.fn().mockResolvedValue(["exact"]);+ await loadObjectMetadataFacet(request, "indexes", loader);+ await expect(loadObjectMetadataFacet({ ...request, exactIdentity: true }, "indexes", loader)).resolves.toEqual({ value: ["exact"], cacheStatus: "remote" });+ expect(loader).toHaveBeenCalledOnce();+ expect(mocks.loadSchemaCache).toHaveBeenCalledOnce();+ expect(mocks.saveSchemaCache).not.toHaveBeenCalled();+ cancelObjectMetadataLoadsForConnection("c1");+ loader.mockRejectedValueOnce(new Error("exact capability unavailable"));+ await expect(loadObjectMetadataFacet({ ...request, exactIdentity: true }, "indexes", loader)).rejects.toThrow("exact capability unavailable");+ });+it("backfills memory after a disk hit", async () => {mocks.loadSchemaCache.mockResolvedValue({ version: 1, cachedAt: new Date().toISOString(), value: [] });const loader = vi.fn();diff --git a/apps/desktop/src/lib/metadata/__tests__/tableMetadataCache.columns.spec.ts b/apps/desktop/src/lib/metadata/__tests__/tableMetadataCache.columns.spec.tsindex 32ec3092e0..f94bc1d82b 100644--- a/apps/desktop/src/lib/metadata/__tests__/tableMetadataCache.columns.spec.ts+++ b/apps/desktop/src/lib/metadata/__tests__/tableMetadataCache.columns.spec.ts@@ -69,6 +69,18 @@ describe("tableMetadataCache columns facet request counts", () => {expect(mocks.getColumns).toHaveBeenCalledOnce();});+ it("separates exact dictionary identities from legacy snapshots and sends the mode to both facets", async () => {+ const request = { ...usersRequest, schema: " Mixed ", tableName: " T(a) ", databaseType: "oceanbase-oracle", tableType: "TABLE" };+ await loadTableMetadata(request);+ const exact = { ...request, exactIdentity: true };+ const result = await loadTableMetadata(exact);+ expect(result.cacheStatus).toBe("miss");+ expect(mocks.getColumns).toHaveBeenNthCalledWith(2, "c1", "db", " Mixed ", " T(a) ", undefined, undefined, undefined, true);+ expect(mocks.listIndexes).toHaveBeenNthCalledWith(2, "c1", "db", " Mixed ", " T(a) ", undefined, true);+ expect((await loadTableMetadata(request)).cacheStatus).toBe("hit");+ expect((await loadTableMetadata(exact)).cacheStatus).toBe("hit");+ });+it("uses a synonym's exact resolved target for indexes while retaining its source name", async () => {mocks.getColumns.mockResolvedValue([{ ...column("ItemId"), is_primary_key: false, resolved_schema: "MixedOwner", resolved_table: "ActualItems", resolved_object_type: "TABLE" }]);mocks.listIndexes.mockResolvedValue([{ name: "ITEMS_PK", columns: ["ItemId"], is_primary: true, is_unique: true }]);diff --git a/apps/desktop/src/lib/metadata/objectDdlCache.ts b/apps/desktop/src/lib/metadata/objectDdlCache.tsindex 9ed528dc3e..bdee0ab854 100644--- a/apps/desktop/src/lib/metadata/objectDdlCache.ts+++ b/apps/desktop/src/lib/metadata/objectDdlCache.ts@@ -31,6 +31,7 @@ export interface ObjectDdlRequest {tableName: string;objectType?: ObjectSourceKind;catalog?: string;+ exactIdentity?: boolean;}export interface ObjectDdlLoadResult {@@ -65,7 +66,7 @@ function cacheSegment(value: string | undefined): string {}export function objectDdlCacheKey(request: ObjectDdlRequest): string {- return `${[OBJECT_DDL_CACHE_PREFIX, cacheSegment(request.connectionId), cacheSegment(request.database), cacheSegment(request.schema), cacheSegment(request.tableName), cacheSegment(request.catalog), cacheSegment(request.objectType ?? "TABLE")].join(":")}:`;+ return `${[OBJECT_DDL_CACHE_PREFIX, cacheSegment(request.connectionId), cacheSegment(request.database), cacheSegment(request.schema), cacheSegment(request.tableName), cacheSegment(request.catalog), cacheSegment(request.objectType ?? "TABLE"), ...(request.exactIdentity ? ["exact-v1"] : [])].join(":")}:`;}function invalidationPrefix(match: MetadataCacheInvalidation): string {@@ -154,11 +155,14 @@ async function loadRemoteDdl(request: ObjectDdlRequest, cacheKey: string, force:};signal.addEventListener("abort", cancel, { once: true });recordMetadataCacheRemoteMiss(cacheKey);+ const remote = request.exactIdentity+ ? api.getTableDdl(request.connectionId, request.database, request.schema, request.tableName, request.objectType, request.catalog, false, true)+ : api.getTableDisplayDdl(request.connectionId, request.database, request.schema, request.tableName, request.objectType, request.catalog);entry.promise = waitForMetadata(- api.getTableDisplayDdl(request.connectionId, request.database, request.schema, request.tableName, request.objectType, request.catalog).then((rawDdl) => {+ remote.then((rawDdl) => {const ddl = sanitizeDdl(rawDdl);const current = !entry.invalidated;- if (current && ddl.length <= MAX_PERSISTED_DDL_CHARS) {+ if (current && !request.exactIdentity && ddl.length <= MAX_PERSISTED_DDL_CHARS) {const envelope: ObjectDdlCacheEnvelope = { version: 1, cachedAt: new Date().toISOString(), ddl };setMetadataRuntimeCache(cacheKey, ddl, request.connectionId);persistSchemaCache(cacheKey, envelope, () => entry.invalidated);@@ -209,6 +213,7 @@ async function loadObjectDdlInternal(request: ObjectDdlRequest, signal: AbortSigif (!options?.force) {const runtime = getMetadataRuntimeCache<string>(cacheKey);if (runtime) return { ddl: runtime.value, cacheStatus: "memory" };+ if (request.exactIdentity) return { ddl: await loadRemoteDdl(request, cacheKey, false, signal), cacheStatus: "remote" };const readToken = activeCacheReads.begin(cacheKey);let cached: string | null;try {diff --git a/apps/desktop/src/lib/metadata/objectMetadataCache.ts b/apps/desktop/src/lib/metadata/objectMetadataCache.tsindex 9a4982c235..9ca85af15d 100644--- a/apps/desktop/src/lib/metadata/objectMetadataCache.ts+++ b/apps/desktop/src/lib/metadata/objectMetadataCache.ts@@ -51,7 +51,7 @@ function cacheSegment(value: string | undefined): string {}function facetKey(request: ObjectDdlRequest, facet: ObjectMetadataFacet): string {- return `${[OBJECT_METADATA_CACHE_PREFIX, cacheSegment(request.connectionId), cacheSegment(request.database), cacheSegment(request.schema), cacheSegment(request.tableName), cacheSegment(request.catalog), cacheSegment(request.objectType ?? "TABLE"), facet].join(":")}:`;+ return `${[OBJECT_METADATA_CACHE_PREFIX, cacheSegment(request.connectionId), cacheSegment(request.database), cacheSegment(request.schema), cacheSegment(request.tableName), cacheSegment(request.catalog), cacheSegment(request.objectType ?? "TABLE"), ...(request.exactIdentity ? ["exact-v1"] : []), facet].join(":")}:`;}function invalidationPrefix(match: MetadataCacheInvalidation): string {@@ -155,22 +155,25 @@ async function loadObjectMetadataFacetInternal<T>(request: ObjectDdlRequest, facif (!options?.force) {const runtime = getMetadataRuntimeCache<T>(cacheKey);if (runtime) return { value: runtime.value, cacheStatus: "memory" };- const readToken = activeCacheReads.begin(cacheKey);- let cached: ReturnType<typeof decodeEnvelope<T>>;- try {- cached = decodeEnvelope<T>(await waitForMetadata(loadSchemaCacheSafe<unknown>(cacheKey), metadataLoadBudgetMs(request.queryTimeoutSecs), signal));- } finally {- activeCacheReads.finish(readToken);- }- signal.throwIfAborted();- if (readToken.invalidated) {- const value = await loadObjectMetadataFacetInternal(request, facet, loader, signal, { force: false });- return { value: value.value, cacheStatus: "remote" };- }- if (cached?.hit) {- recordMetadataCacheL2Hit(cacheKey, cached.value);- setMetadataRuntimeCache(cacheKey, cached.value, request.connectionId);- return { value: cached.value, cacheStatus: "disk" };+ // A persisted snapshot cannot prove which Agent/plugin is running now.+ if (!request.exactIdentity) {+ const readToken = activeCacheReads.begin(cacheKey);+ let cached: ReturnType<typeof decodeEnvelope<T>>;+ try {+ cached = decodeEnvelope<T>(await waitForMetadata(loadSchemaCacheSafe<unknown>(cacheKey), metadataLoadBudgetMs(request.queryTimeoutSecs), signal));+ } finally {+ activeCacheReads.finish(readToken);+ }+ signal.throwIfAborted();+ if (readToken.invalidated) {+ const value = await loadObjectMetadataFacetInternal(request, facet, loader, signal, { force: false });+ return { value: value.value, cacheStatus: "remote" };+ }+ if (cached?.hit) {+ recordMetadataCacheL2Hit(cacheKey, cached.value);+ setMetadataRuntimeCache(cacheKey, cached.value, request.connectionId);+ return { value: cached.value, cacheStatus: "disk" };+ }}}@@ -195,7 +198,7 @@ async function loadObjectMetadataFacetInternal<T>(request: ObjectDdlRequest, facconst serialized = JSON.stringify(value);const current = !entry.invalidated;if (current) setMetadataRuntimeCache(cacheKey, value, request.connectionId);- if (current && serialized !== undefined && serialized.length <= MAX_PERSISTED_METADATA_CHARS) {+ if (current && !request.exactIdentity && serialized !== undefined && serialized.length <= MAX_PERSISTED_METADATA_CHARS) {const envelope: ObjectMetadataCacheEnvelope<T> = { version: 1, cachedAt: new Date().toISOString(), value };persistSchemaCache(cacheKey, envelope, () => entry.invalidated);}diff --git a/apps/desktop/src/lib/metadata/tableMetadataCache.ts b/apps/desktop/src/lib/metadata/tableMetadataCache.tsindex 797d1ac18a..3743dccb81 100644--- a/apps/desktop/src/lib/metadata/tableMetadataCache.ts+++ b/apps/desktop/src/lib/metadata/tableMetadataCache.ts@@ -34,6 +34,7 @@ export interface TableMetadataRequest {driverProfile?: string;catalog?: string;force?: boolean;+ exactIdentity?: boolean;traceLogger?: MetadataLoadTraceLogger;}@@ -158,7 +159,7 @@ function bumpTableMetadataInvalidationStamp(scopeKey: string): void {tableMetadataInvalidationStamps.set(scopeKey, (tableMetadataInvalidationStamps.get(scopeKey) ?? 0) + 1);}-export function tableMetadataScope(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema">): MetadataScopeInput {+export function tableMetadataScope(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema" | "exactIdentity">): MetadataScopeInput {return {kind: "table-metadata",connectionId: request.connectionId,@@ -167,7 +168,7 @@ export function tableMetadataScope(request: Pick<TableMetadataRequest, "connectitableName: request.tableName,tableType: request.tableType,driverProfile: request.driverProfile || request.databaseType,- extra: request.catalog || request.currentSchema ? { catalog: request.catalog, currentSchema: request.currentSchema } : undefined,+ extra: request.catalog || request.currentSchema || request.exactIdentity ? { catalog: request.catalog, currentSchema: request.currentSchema, ...(request.exactIdentity ? { exactIdentity: true } : {}) } : undefined,};}@@ -178,13 +179,13 @@ function withVirtualRowIdentifier(metadata: TableMetadata, request: Pick<TableMereturn { ...metadata, primaryKeys: virtualPrimaryKeys, virtualPrimaryKeys, rowIdentityResolved: true };}-export function getCachedTableMetadata(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema">): TableMetadataLoadResult | undefined {+export function getCachedTableMetadata(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema" | "exactIdentity">): TableMetadataLoadResult | undefined {const hit = tableMetadataCache.get(tableMetadataScope(request));if (!hit) return undefined;return { metadata: withVirtualRowIdentifier(hit.value, request), cacheStatus: hit.stale ? "stale" : "hit", ageMs: hit.ageMs };}-export function updateCachedTableMetadataType(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema">, tableType: string): boolean {+export function updateCachedTableMetadataType(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema" | "exactIdentity">, tableType: string): boolean {const scope = tableMetadataScope(request);const hit = tableMetadataCache.get(scope);if (!hit) return false;@@ -192,7 +193,7 @@ export function updateCachedTableMetadataType(request: Pick<TableMetadataRequestreturn true;}-export function getCachedTableColumns(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema">): TableColumnsLoadResult | undefined {+export function getCachedTableColumns(request: Pick<TableMetadataRequest, "connectionId" | "database" | "schema" | "tableName" | "tableType" | "driverProfile" | "databaseType" | "catalog" | "currentSchema" | "exactIdentity">): TableColumnsLoadResult | undefined {const hit = tableColumnsCache.get(tableMetadataScope(request));if (!hit) return undefined;return { columns: hit.value.columns, tableType: hit.value.tableType, cacheStatus: hit.stale ? "stale" : "hit", ageMs: hit.ageMs, cachedAt: hit.cachedAt };@@ -249,9 +250,11 @@ export async function loadTableColumns(request: TableMetadataRequest): Promise<Tscope,async () => {// Display-only loader: columns only, never index discovery.- const columns = request.currentSchema- ? await api.getColumns(request.connectionId, request.database, request.schema ?? "", request.tableName, request.catalog, undefined, request.currentSchema)- : await api.getColumns(request.connectionId, request.database, request.schema ?? "", request.tableName, request.catalog);+ const columns = request.exactIdentity+ ? await api.getColumns(request.connectionId, request.database, request.schema ?? "", request.tableName, request.catalog, undefined, undefined, true)+ : request.currentSchema+ ? await api.getColumns(request.connectionId, request.database, request.schema ?? "", request.tableName, request.catalog, undefined, request.currentSchema)+ : await api.getColumns(request.connectionId, request.database, request.schema ?? "", request.tableName, request.catalog);const resolvedTarget = columns.find((column) => column.resolved_table);const resolvedSchema = (request.databaseType === "vastbase" || request.databaseType === "kingbase") && !request.schema ? columns.find((column) => column.resolved_schema)?.resolved_schema : request.schema;return {@@ -306,7 +309,9 @@ export async function loadTableIndexes(request: TableMetadataRequest): Promise<Iif (!oldestKey) break;tableIndexesLoads.delete(oldestKey);}- const promise = api.listIndexes(request.connectionId, request.database, request.schema || request.currentSchema || "", request.tableName, request.catalog);+ const promise = request.exactIdentity+ ? api.listIndexes(request.connectionId, request.database, request.schema ?? "", request.tableName, request.catalog, true)+ : api.listIndexes(request.connectionId, request.database, request.schema || request.currentSchema || "", request.tableName, request.catalog);const entry = { parts: metadataScopeParts(scope), promise, expiresAt: Date.now() + TABLE_METADATA_CACHE_TTL_MS };tableIndexesLoads.set(scopeKey, entry);void promise.catch(() => {diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeLabel.ts b/apps/desktop/src/lib/sidebar/sidebarTreeLabel.tsindex 94a502f986..b7aa1765e9 100644--- a/apps/desktop/src/lib/sidebar/sidebarTreeLabel.ts+++ b/apps/desktop/src/lib/sidebar/sidebarTreeLabel.ts@@ -11,7 +11,7 @@ export function sidebarTreeDisplayLabel(node: TreeNode, t: SidebarTreeTranslate,if (node.type === "schema" && node.connectionId) {if (databaseType === "xugu") return xuguSchemaDisplayName(node.schema ?? node.label);}- if (node.type === "load-more") return t(node.label);+ if (node.type === "load-more") return node.loadMore?.objectType === "INDEX" ? `${t("tree.indexes")} · ${t(node.label)}` : t(node.label);if (node.type === "object-browser") return t(node.label, { count: node.objectCount ?? 0 });// Use the canonical key for persisted trees created before this label was// internationalized; those nodes may still contain the old Chinese text.diff --git a/apps/desktop/src/lib/sidebar/treeNodeClick.ts b/apps/desktop/src/lib/sidebar/treeNodeClick.tsindex c1bff81417..6a5f22badf 100644--- a/apps/desktop/src/lib/sidebar/treeNodeClick.ts+++ b/apps/desktop/src/lib/sidebar/treeNodeClick.ts@@ -96,6 +96,7 @@ const databaseChildGroupNodeTypes = new Set<TreeNodeType>(["group-triggers","group-events","group-sequences",+ "group-database-indexes","group-synonyms","group-jobs","group-packages",@@ -221,6 +222,7 @@ export function sidebarSelectionCopyAction(event: ShortcutLikeEvent, platform?:}export function copyNameForTreeNode(node: TreeNode): string {+ if (node.type === "index" && node.objectScope === "schema" && node.objectName) return node.objectName;if (tableChildGroupNodeTypes.has(node.type) && node.tableName) return node.tableName;if (databaseChildGroupNodeTypes.has(node.type)) return node.schema || node.database || node.label;if (node.type === "column") {diff --git a/apps/desktop/src/lib/sidebar/treeNodeGroup.ts b/apps/desktop/src/lib/sidebar/treeNodeGroup.tsindex e218f027d7..464f63c8da 100644--- a/apps/desktop/src/lib/sidebar/treeNodeGroup.ts+++ b/apps/desktop/src/lib/sidebar/treeNodeGroup.ts@@ -4,6 +4,7 @@ const treeGroupNodeTypes = new Set<TreeNodeType>(["oracle-db-links","group-columns","group-indexes",+ "group-database-indexes","group-fkeys","group-triggers","group-events",diff --git a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts b/apps/desktop/src/lib/sidebar/treeNodeIcon.tsindex 1f16541a89..42fa150adb 100644--- a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts+++ b/apps/desktop/src/lib/sidebar/treeNodeIcon.ts@@ -62,6 +62,7 @@ export function getTreeNodeIconInfo(node: TreeNode): TreeNodeIconInfo | null {case "group-columns":return { icon: ListTree, colorClass: "text-green-400" };case "group-indexes":+ case "group-database-indexes":case "index":return { icon: Key, colorClass: "text-amber-500" };case "group-fkeys":diff --git a/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts b/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.tsindex a2a080c850..163b25d516 100644--- a/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts+++ b/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts@@ -2,6 +2,12 @@ import { describe, expect, it } from "vitest";import { getTableMetadataCapabilities, isStructureMetadataTabSupported } from "@/lib/table/tableMetadataCapabilities";describe("tableMetadataCapabilities", () => {+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("keeps legacy %s JDBC facets while hiding unsupported exact facets", (type) => {+ const legacy = getTableMetadataCapabilities(type);+ expect(getTableMetadataCapabilities(type, { connectionType: "jdbc" })).toEqual(legacy);+ expect(getTableMetadataCapabilities(type, { connectionType: type, exactIdentity: true })).toEqual(legacy);+ expect(getTableMetadataCapabilities(type, { connectionType: "jdbc", exactIdentity: true })).toEqual({ ...legacy, foreignKeys: false, constraints: false, triggers: false, partitions: false });+ });it("exposes only collection indexes for MongoDB table information", () => {expect(getTableMetadataCapabilities("mongodb")).toEqual({columns: false,diff --git a/apps/desktop/src/lib/table/objectBrowserRowAction.ts b/apps/desktop/src/lib/table/objectBrowserRowAction.tsindex 4a2561dada..a9fecbaad4 100644--- a/apps/desktop/src/lib/table/objectBrowserRowAction.ts+++ b/apps/desktop/src/lib/table/objectBrowserRowAction.ts@@ -1,8 +1,9 @@import type { DatabaseType } from "@/types/database";-import { customTypeCapabilities, supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";+import { customTypeCapabilities, supportsSchemaIndexManagement, supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";+import { schemaIndexIdentity, schemaIndexIsSameOwner } from "@/lib/table/schemaIndexNavigation";import type { ObjectBrowserRow } from "@/lib/table/objectBrowserRows";-export type ObjectBrowserRowAction = "table-info" | "type-info" | "open-table" | "open-source" | "open-source-tab" | "none";+export type ObjectBrowserRowAction = "table-info" | "index-info" | "index-editor" | "type-info" | "open-table" | "open-source" | "open-source-tab" | "none";/*** Determine the action for a single click on an object browser row.@@ -17,6 +18,7 @@ export type ObjectBrowserRowAction = "table-info" | "type-info" | "open-table" |export function singleClickRowAction(row: ObjectBrowserRow | null | undefined, dbType?: DatabaseType): ObjectBrowserRowAction {if (!row) return "none";if (dbType === "mongodb") return mongoObjectBrowserRowAction(row);+ if (row.type === "INDEX") return supportsSchemaIndexManagement(dbType) && schemaIndexIdentity(row) ? "index-info" : "none";if (row.type === "TABLE") return "table-info";if (row.type === "EVENT") return "none";if (row.type === "TYPE" && customTypeCapabilities(dbType).details) return "type-info";@@ -35,6 +37,11 @@ export function singleClickRowAction(row: ObjectBrowserRow | null | undefined, dexport function doubleClickRowAction(row: ObjectBrowserRow | null | undefined, dbType?: DatabaseType): ObjectBrowserRowAction {if (!row) return "none";if (dbType === "mongodb") return mongoObjectBrowserRowAction(row);+ if (row.type === "INDEX") {+ if (!supportsSchemaIndexManagement(dbType)) return "none";+ const target = schemaIndexIdentity(row);+ return schemaIndexIsSameOwner(target) ? "index-editor" : target ? "index-info" : "none";+ }if (row.type === "TABLE" || row.type === "VIEW" || row.type === "MATERIALIZED_VIEW") return "open-table";if (row.type === "EVENT") return "open-source";if (row.type === "TYPE" && customTypeCapabilities(dbType).details) return "type-info";diff --git a/apps/desktop/src/lib/table/objectBrowserRows.ts b/apps/desktop/src/lib/table/objectBrowserRows.tsindex d420de278a..cdb39ea6d2 100644--- a/apps/desktop/src/lib/table/objectBrowserRows.ts+++ b/apps/desktop/src/lib/table/objectBrowserRows.ts@@ -10,7 +10,9 @@ export type ObjectBrowserRow = {name: string;displayName: string;schema?: string;- type: "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT" | "SEQUENCE" | "PACKAGE" | "PACKAGE_BODY" | "TYPE" | "TYPE_BODY";+ type: "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT" | "SEQUENCE" | "INDEX" | "PACKAGE" | "PACKAGE_BODY" | "TYPE" | "TYPE_BODY";+ parentSchema?: string;+ parentName?: string;collectionKind?: MongoCollectionKind;valid?: boolean | null;signature?: string | null;@@ -46,6 +48,7 @@ export function objectBrowserRowTreeNodeType(type: ObjectBrowserRow["type"]): Trif (type === "TRIGGER") return "trigger";if (type === "EVENT") return "event";if (type === "SEQUENCE") return "sequence";+ if (type === "INDEX") return "index";if (type === "PACKAGE_BODY") return "package-body";if (type === "PACKAGE") return "package";if (type === "TYPE_BODY") return "type-body";@@ -91,8 +94,8 @@ function objectBrowserRowObjectInfo(row: ObjectBrowserRow, schema?: string): Objschema,valid: row.valid,signature: row.signature || undefined,- parent_schema: row.partitionParentSchema,- parent_name: row.partitionParentName,+ parent_schema: row.type === "INDEX" ? row.parentSchema : row.partitionParentSchema,+ parent_name: row.type === "INDEX" ? row.parentName : row.partitionParentName,};}@@ -143,6 +146,7 @@ export function objectBrowserRowLegacyPinnedTreeNodeIds(row: ObjectBrowserRow, cexport function normalizeObjectBrowserType(type: string): ObjectBrowserRow["type"] {const value = type.toUpperCase();const normalized = value.replace(/[\s-]+/g, "_");+ if (normalized === "INDEX") return "INDEX";if (normalized.includes("PACKAGE_BODY")) return "PACKAGE_BODY";if (normalized.includes("TYPE_BODY")) return "TYPE_BODY";if (normalized.includes("PACKAGE")) return "PACKAGE";@@ -160,11 +164,11 @@ export function normalizeObjectBrowserType(type: string): ObjectBrowserRow["typeexport function buildObjectBrowserRows(options: { objects: ObjectInfo[]; database: string; fallbackSchema: string; rowSchema?: string }): ObjectBrowserRow[] {const seen = new Map<string, number>();const rows = options.objects.flatMap((object) => {- const name = normalizeDatabaseObjectName(object.name);+ const type = normalizeObjectBrowserType(object.object_type);+ const name = type === "INDEX" ? object.name : normalizeDatabaseObjectName(object.name);if (!name) return [];- const objectSchema = object.schema ? normalizeDatabaseObjectName(object.schema) : undefined;+ const objectSchema = type === "INDEX" ? object.schema : object.schema ? normalizeDatabaseObjectName(object.schema) : undefined;const schema = objectSchema || options.rowSchema;- const type = normalizeObjectBrowserType(object.object_type);const signature = routineSignatureForDisplay(type, object.signature);const displayName = signature === undefined ? name : `${name}(${signature})`;const signatureIdPart = signature === undefined ? "" : `:${signature}`;@@ -183,8 +187,10 @@ export function buildObjectBrowserRows(options: { objects: ObjectInfo[]; databascomment: object.comment,created_at: object.created_at,updated_at: object.updated_at,- partitionParentSchema: object.parent_schema ? normalizeDatabaseObjectName(object.parent_schema) : undefined,- partitionParentName: object.parent_name ? normalizeDatabaseObjectName(object.parent_name) : undefined,+ parentSchema: type === "INDEX" ? (object.parent_schema ?? undefined) : undefined,+ parentName: type === "INDEX" ? (object.parent_name ?? undefined) : undefined,+ partitionParentSchema: type !== "INDEX" && object.parent_schema ? normalizeDatabaseObjectName(object.parent_schema) : undefined,+ partitionParentName: type !== "INDEX" && object.parent_name ? normalizeDatabaseObjectName(object.parent_name) : undefined,},];});@@ -359,6 +365,7 @@ export function countObjectBrowserRowsByFilter(rows: ObjectBrowserRow[]): Objecttriggers: 0,events: 0,sequences: 0,+ indexes: 0,packages: 0,types: 0,};@@ -372,6 +379,7 @@ export function countObjectBrowserRowsByFilter(rows: ObjectBrowserRow[]): Objectelse if (row.type === "TRIGGER") counts.triggers++;else if (row.type === "EVENT") counts.events++;else if (row.type === "SEQUENCE") counts.sequences++;+ else if (row.type === "INDEX") counts.indexes++;else if (row.type === "PACKAGE" || row.type === "PACKAGE_BODY") counts.packages++;else if (row.type === "TYPE" || row.type === "TYPE_BODY") counts.types++;}diff --git a/apps/desktop/src/lib/table/objectBrowserRowsCache.ts b/apps/desktop/src/lib/table/objectBrowserRowsCache.tsindex 2018598151..9fad5d4ffe 100644--- a/apps/desktop/src/lib/table/objectBrowserRowsCache.ts+++ b/apps/desktop/src/lib/table/objectBrowserRowsCache.ts@@ -11,6 +11,7 @@ export interface ObjectBrowserRowsCacheScope {database: string;schema: string;catalog?: string;+ exactIdentity?: boolean;}export interface ObjectBrowserRowsCacheWriteToken {@@ -37,7 +38,7 @@ function objectBrowserRowsScope(scope: ObjectBrowserRowsCacheScope): MetadataScoconnectionId: scope.connectionId,database: scope.database,schema: scope.schema,- extra: scope.catalog ? { catalog: scope.catalog } : undefined,+ extra: scope.catalog || scope.exactIdentity ? { catalog: scope.catalog, ...(scope.exactIdentity ? { exactIdentity: true } : {}) } : undefined,};}diff --git a/apps/desktop/src/lib/table/schemaIndexNavigation.ts b/apps/desktop/src/lib/table/schemaIndexNavigation.tsnew file mode 100644index 0000000000..24fd9ee1c4--- /dev/null+++ b/apps/desktop/src/lib/table/schemaIndexNavigation.ts@@ -0,0 +1,16 @@+import type { SchemaIndexIdentity, TreeNode } from "@/types/database";++/** Only dictionary fields identify an index and its table; never parse a label. */+export function schemaIndexIdentity(source: { schema?: string; name?: string; parentSchema?: string; parentName?: string }): SchemaIndexIdentity | null {+ const { schema, name, parentSchema, parentName } = source;+ if (!schema || !name || !parentSchema || !parentName) return null;+ return { schema, name, parentSchema, parentName };+}++export function schemaIndexNodeIdentity(node: TreeNode): SchemaIndexIdentity | null {+ return node.type === "index" && node.objectScope === "schema" ? schemaIndexIdentity({ ...node, name: node.objectName }) : null;+}++export function schemaIndexIsSameOwner(target: SchemaIndexIdentity | null): target is SchemaIndexIdentity {+ return target !== null && target.schema === target.parentSchema;+}diff --git a/apps/desktop/src/lib/table/tableMetadataCapabilities.ts b/apps/desktop/src/lib/table/tableMetadataCapabilities.tsindex 8a8c906e78..b625cdd083 100644--- a/apps/desktop/src/lib/table/tableMetadataCapabilities.ts+++ b/apps/desktop/src/lib/table/tableMetadataCapabilities.ts@@ -163,8 +163,14 @@ const capabilityByType: Partial<Record<DatabaseType, Partial<TableMetadataCapabi},};-export function getTableMetadataCapabilities(dbType?: DatabaseType): TableMetadataCapabilities {- return { ...defaultCapabilities, ...(dbType ? capabilityByType[dbType] : undefined) };+export function getTableMetadataCapabilities(dbType?: DatabaseType, context?: { connectionType?: DatabaseType; exactIdentity?: boolean }): TableMetadataCapabilities {+ const capabilities = { ...defaultCapabilities, ...(dbType ? capabilityByType[dbType] : undefined) };+ // Exact JDBC currently implements columns, indexes and DDL only. Do not offer+ // metadata tabs whose requests cannot preserve the selected raw identity.+ if (context?.exactIdentity && context.connectionType === "jdbc") {+ return { ...capabilities, foreignKeys: false, constraints: false, triggers: false, partitions: false };+ }+ return capabilities;}export function firstStructureMetadataTab(capabilities: TableMetadataCapabilities, isCreateMode: boolean): TableInfoTab {diff --git a/apps/desktop/src/lib/table/tableStructureEditorState.ts b/apps/desktop/src/lib/table/tableStructureEditorState.tsindex fc5cd17bea..073f54d2dd 100644--- a/apps/desktop/src/lib/table/tableStructureEditorState.ts+++ b/apps/desktop/src/lib/table/tableStructureEditorState.ts@@ -1297,7 +1297,7 @@ export function sortStructureIndexColumnOptions<T extends { name: string }>(optiexport function createIndexDrafts(indexes: IndexInfo[]): EditableStructureIndex[] {return indexes.map((index) => ({- id: `existing:${index.name}`,+ id: index.owner == null ? `existing:${index.name}` : `existing-owned-index:${JSON.stringify([index.owner, index.name])}`,name: index.name,columns: [...index.columns],nameEdited: true,diff --git a/apps/desktop/src/lib/table/tableTree.ts b/apps/desktop/src/lib/table/tableTree.tsindex 65b622c725..1342b1b1f0 100644--- a/apps/desktop/src/lib/table/tableTree.ts+++ b/apps/desktop/src/lib/table/tableTree.ts@@ -1,5 +1,5 @@import type { DatabaseType, ObjectInfo, TableInfo, TreeNode, TreeNodeType } from "@/types/database";-import { normalizeSidebarObjectKind, type SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";+import { normalizeSidebarObjectKind, supportsSchemaIndexManagement, type SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";const databaseObjectNameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });@@ -433,7 +433,7 @@ export function appendTableTreeLoadMoreNode(children: TreeNode[], loadMoreNode:export function withoutTableTreeLoadMoreNodes(nodes: TreeNode[] | undefined): TreeNode[] {return (nodes ?? [])- .filter((node) => node.type !== "load-more")+ .filter((node) => node.type !== "load-more" || node.loadMore?.objectType === "INDEX").map((node) => {if (node.children) node.children = withoutTableTreeLoadMoreNodes(node.children);if (node.hiddenChildren) node.hiddenChildren = withoutTableTreeLoadMoreNodes(node.hiddenChildren);@@ -686,17 +686,18 @@ export function buildSimpleObjectTreeNodes({ nodeId, connectionId, database, schfor (const obj of coalesceXuguPackageObjects(objects, databaseType)) {const objectType = normalizeObjectType(obj.object_type);- if (!["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"].includes(objectType)) {+ const schemaIndex = objectType === "INDEX" && supportsSchemaIndexManagement(databaseType);+ if (!schemaIndex && !["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"].includes(objectType)) {continue;}- const name = normalizeDatabaseObjectName(obj.name);+ const name = schemaIndex ? obj.name : normalizeDatabaseObjectName(obj.name);if (!name) continue;- const childSchema = obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema;+ const childSchema = schemaIndex ? (obj.schema ?? schema) : obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema;const signature = obj.signature?.trim() || "";- const triggerParentName = objectType === "TRIGGER" && obj.parent_name ? normalizeDatabaseObjectName(obj.parent_name) : undefined;- const triggerParentSchema = objectType === "TRIGGER" && obj.parent_schema ? normalizeDatabaseObjectName(obj.parent_schema) : undefined;+ const triggerParentName = schemaIndex ? (obj.parent_name ?? undefined) : objectType === "TRIGGER" && obj.parent_name ? normalizeDatabaseObjectName(obj.parent_name) : undefined;+ const triggerParentSchema = schemaIndex ? (obj.parent_schema ?? undefined) : objectType === "TRIGGER" && obj.parent_schema ? normalizeDatabaseObjectName(obj.parent_schema) : undefined;const dedupeKey = `${exactObjectIdentityKey(objectType, childSchema, name, signature)}\0${triggerParentName || ""}`;if (seen.has(dedupeKey)) continue;seen.add(dedupeKey);@@ -719,10 +720,15 @@ export function buildSimpleObjectTreeNodes({ nodeId, connectionId, database, sch} else {const simpleNodeType = simpleObjectNodeType(objectType);objectNodes.push({- id: objectType === "VIEW" || objectType === "MATERIALIZED_VIEW" ? entry.node.id : `${nodeId}:${childSchema ? `${childSchema}:` : ""}${name}:${signature}:${triggerParentName || ""}:${objectType}`,+ id: schemaIndex+ ? `${nodeId}:index:${JSON.stringify([childSchema, name, triggerParentSchema, triggerParentName])}`+ : objectType === "VIEW" || objectType === "MATERIALIZED_VIEW"+ ? entry.node.id+ : `${nodeId}:${childSchema ? `${childSchema}:` : ""}${name}:${signature}:${triggerParentName || ""}:${objectType}`,label: signature && (objectType === "FUNCTION" || objectType === "PROCEDURE") ? `${name}(${signature})` : triggerParentName ? `${name} (${triggerParentName})` : name,type: simpleNodeType,objectName: name,+ objectScope: schemaIndex ? "schema" : undefined,signature: objectType === "FUNCTION" || objectType === "PROCEDURE" ? (obj.signature == null ? undefined : signature) : signature || undefined,customTypeKind: obj.custom_type_kind ?? undefined,hasMembers: obj.has_members ?? undefined,@@ -942,17 +948,18 @@ export function buildGroupedObjectTreeNodes({ nodeId, connectionId, database, scconst buckets = new Map<string, ObjectInfo[]>();const seen = new Set<string>();for (const obj of coalesceXuguPackageObjects(objects, databaseType)) {- const name = normalizeDatabaseObjectName(obj.name);- if (!name) continue;const t = normalizeObjectType(obj.object_type);- const objectSchema = obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema || "";+ const schemaIndex = t === "INDEX" && supportsSchemaIndexManagement(databaseType);+ const name = schemaIndex ? obj.name : normalizeDatabaseObjectName(obj.name);+ if (!name) continue;+ const objectSchema = schemaIndex ? (obj.schema ?? schema ?? "") : obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema || "";const signature = (obj.signature ?? "").trim();const triggerParentName = t === "TRIGGER" && obj.parent_name ? normalizeDatabaseObjectName(obj.parent_name) : "";const key = `${exactObjectIdentityKey(t, objectSchema, name, signature)}\0${triggerParentName}`;if (seen.has(key)) continue;seen.add(key);const arr = buckets.get(t) ?? [];- arr.push({ ...obj, name, schema: obj.schema ? normalizeDatabaseObjectName(obj.schema) : obj.schema });+ arr.push({ ...obj, name, schema: schemaIndex ? obj.schema : obj.schema ? normalizeDatabaseObjectName(obj.schema) : obj.schema });buckets.set(t, arr);}@@ -972,19 +979,21 @@ export function buildGroupedObjectTreeNodes({ nodeId, connectionId, database, scobjectType: def.objectTypes[0] as "TABLE" | "VIEW" | "MATERIALIZED_VIEW",}): sortDatabaseObjectsByName(items, (obj) => obj.name).map((obj) => {- const childSchema = obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema;const objectType = normalizeObjectType(obj.object_type);+ const schemaIndex = objectType === "INDEX" && supportsSchemaIndexManagement(databaseType);+ const childSchema = schemaIndex ? (obj.schema ?? schema) : obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema;const childType = typeof def.childType === "function" ? def.childType(objectType) : def.childType;const objectTypeSuffix = objectType === "PACKAGE" || objectType === "PACKAGE_BODY" || objectType === "TYPE" || objectType === "TYPE_BODY" ? `:${objectType}` : "";const signature = obj.signature?.trim() || "";const signatureIdPart = signature && (objectType === "FUNCTION" || objectType === "PROCEDURE") ? `:${signature}` : "";- const triggerParentName = (objectType === "TRIGGER" || objectType === "INDEX") && obj.parent_name ? normalizeDatabaseObjectName(obj.parent_name) : undefined;- const triggerParentSchema = objectType === "TRIGGER" && obj.parent_schema ? normalizeDatabaseObjectName(obj.parent_schema) : undefined;+ const triggerParentName = schemaIndex ? (obj.parent_name ?? undefined) : (objectType === "TRIGGER" || objectType === "INDEX") && obj.parent_name ? normalizeDatabaseObjectName(obj.parent_name) : undefined;+ const triggerParentSchema = schemaIndex ? (obj.parent_schema ?? undefined) : objectType === "TRIGGER" && obj.parent_schema ? normalizeDatabaseObjectName(obj.parent_schema) : undefined;return {- id: `${nodeId}:${def.key}:${childSchema ? `${childSchema}:` : ""}${obj.name}${signatureIdPart}${triggerParentName ? `:${triggerParentName}` : ""}${objectTypeSuffix}`,+ id: schemaIndex ? `${nodeId}:${def.key}:${JSON.stringify([childSchema, obj.name, triggerParentSchema, triggerParentName])}` : `${nodeId}:${def.key}:${childSchema ? `${childSchema}:` : ""}${obj.name}${signatureIdPart}${triggerParentName ? `:${triggerParentName}` : ""}${objectTypeSuffix}`,label: signature && (objectType === "FUNCTION" || objectType === "PROCEDURE") ? `${obj.name}(${signature})` : triggerParentName ? `${obj.name} (${triggerParentName})` : obj.name,type: childType,objectName: obj.name,+ objectScope: schemaIndex ? ("schema" as const) : undefined,signature: objectType === "FUNCTION" || objectType === "PROCEDURE" ? (obj.signature == null ? undefined : signature) : signature || undefined,customTypeKind: obj.custom_type_kind ?? undefined,hasMembers: obj.has_members ?? undefined,diff --git a/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.tsindex 19c28fb5fa..2b7f719ea1 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.ts@@ -18,6 +18,7 @@ async function setup(listObjects: ReturnType<typeof vi.fn>, listTables?: ReturnTvi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));vi.doMock("@/lib/backend/api", () => ({checkConnectionHealth: vi.fn().mockResolvedValue(undefined),+ disconnectDb: vi.fn().mockResolvedValue(undefined),deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),listObjects,listTables: listTables ?? vi.fn().mockResolvedValue([]),@@ -76,28 +77,263 @@ function findMore(nodes: TreeNode[]): TreeNode | undefined {}describe("OceanBase Oracle sidebar paging (#11418)", () => {+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("adds exact %s indexes to the flat tree without changing the legacy table request", async (dbType) => {+ const listObjects = vi.fn().mockImplementation(async (...args: unknown[]) => (args[10] === true ? [{ name: " Ix(a) ", object_type: "INDEX", schema: " Mixed ", parent_schema: " Other ", parent_name: " T(a) " }] : []));+ const { store } = await setup(listObjects);+ store.connections = [{ ...connection, db_type: dbType }];+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.id = `${connection.id}:APP: Mixed `;+ schema.schema = " Mixed ";+ schema.children = [];+ await store.loadTables(connection.id, "APP", " Mixed ", { force: true });+ await vi.waitFor(() => expect(schema.children?.find((node) => node.type === "index")).toMatchObject({ objectName: " Ix(a) ", schema: " Mixed ", parentSchema: " Other ", parentName: " T(a) ", objectScope: "schema" }));+ expect(listObjects).toHaveBeenCalledWith(connection.id, "APP", " Mixed ", ["INDEX"], undefined, 3, 0, undefined, undefined, undefined, true);+ const api = await import("@/lib/backend/api");+ expect(vi.mocked(api.saveSchemaCache).mock.calls.every((call) => !JSON.stringify(call[1]).includes('"objectScope":"schema"'))).toBe(true);+ });++ it.each(["table-first", "index-first"])("pages flat indexes and tables independently (%s)", async (order) => {+ const indexes: ObjectInfo[] = ["I1", "I2", "I3", "I4"].map((name) => ({ name, object_type: "INDEX", schema: "APP", parent_schema: "OTHER", parent_name: "T" }));+ const tables = ["T1", "T2", "T3", "T4"].map((name) => ({ name, table_type: "TABLE" }));+ const listObjects = vi.fn(async (...args: unknown[]) => (args[10] === true ? indexes.slice(Number(args[6] ?? 0), Number(args[6] ?? 0) + Number(args[5] ?? indexes.length)) : []));+ const listTables = vi.fn(async (...args: unknown[]) => tables.slice(Number(args[5] ?? 0), Number(args[5] ?? 0) + Number(args[4] ?? tables.length)));+ const { store } = await setup(listObjects, listTables);+ store.connections = [{ ...connection, db_type: "oracle" }];+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(schema.children?.filter((node) => node.type === "load-more")).toHaveLength(2));+ const markers = schema.children!.filter((node) => node.type === "load-more");+ expect(new Set(markers.map((node) => node.id)).size).toBe(2);+ const indexMore = markers.find((node) => node.loadMore?.objectType === "INDEX")!;+ const tableMore = markers.find((node) => node.loadMore?.objectType !== "INDEX")!;+ await store.loadMoreObjectGroupChildren(order === "table-first" ? tableMore : indexMore);+ expect(schema.children?.filter((node) => node.type === "load-more").map((node) => node.id)).toEqual([order === "table-first" ? indexMore.id : tableMore.id]);+ await store.loadMoreObjectGroupChildren(order === "table-first" ? indexMore : tableMore);+ expect(schema.children?.some((node) => node.type === "load-more")).toBe(false);+ expect(schema.children?.filter((node) => node.type === "index").map((node) => node.objectName)).toEqual(indexes.map((object) => object.name));+ expect(schema.children?.filter((node) => node.type === "table").map((node) => node.label)).toEqual(tables.map((table) => table.name));+ expect(listObjects.mock.calls.filter((args) => args[10] === true).map((args) => args.slice(5, 7))).toEqual([+ [3, 0],+ [3, 2],+ ]);+ const api = await import("@/lib/backend/api");+ expect(vi.mocked(api.saveSchemaCache).mock.calls.every((call) => !JSON.stringify(call[1]).includes('"objectType":"INDEX"'))).toBe(true);+ });++ it("keeps the captured flat index search on later pages and clears it on refresh", async () => {+ const indexes: ObjectInfo[] = ["needle1", "needle2", "needle3", "other"].map((name) => ({ name, object_type: "INDEX", schema: "APP", parent_schema: "APP", parent_name: "T" }));+ const listObjects = vi.fn(async (...args: unknown[]) => {+ if (args[10] !== true) return [];+ const filtered = indexes.filter((object) => !args[4] || object.name.includes(String(args[4])));+ return filtered.slice(Number(args[6] ?? 0), Number(args[6] ?? 0) + Number(args[5]));+ });+ const { store } = await setup(listObjects);+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ store.sidebarSearchQuery = "needle";+ await store.loadTables(connection.id, "APP", "APP", { force: true, searchFilter: "needle", expectedSidebarSearchQuery: "needle" });+ await vi.waitFor(() => expect(schema.children?.find((node) => node.loadMore?.objectType === "INDEX")).toBeDefined());+ await store.loadMoreObjectGroupChildren(schema.children!.find((node) => node.loadMore?.objectType === "INDEX")!);+ expect(listObjects.mock.calls.filter((args) => args[10] === true).map((args) => args.slice(4, 7))).toEqual([+ ["needle", 3, 0],+ ["needle", 3, 2],+ ]);+ expect(schema.children?.filter((node) => node.type === "index").map((node) => node.objectName)).toEqual(["needle1", "needle2", "needle3"]);+ store.sidebarSearchQuery = "";+ await store.loadTables(connection.id, "APP", "APP", { force: true, searchFilter: "", expectedSidebarSearchQuery: "" });+ await vi.waitFor(() => expect(schema.children?.find((node) => node.loadMore?.objectType === "INDEX")).toBeDefined());+ expect(+ listObjects.mock.calls+ .filter((args) => args[10] === true)+ .at(-1)+ ?.slice(4, 7),+ ).toEqual([undefined, 3, 0]);+ });++ it("rejects a late supplemental index page after the parent is refreshed", async () => {+ let release!: (objects: ObjectInfo[]) => void;+ let exactCalls = 0;+ const listObjects = vi.fn((...args: unknown[]) => {+ if (args[10] !== true) return Promise.resolve([]);+ if (++exactCalls === 1)+ return new Promise<ObjectInfo[]>((resolve) => {+ release = resolve;+ });+ return Promise.resolve([{ name: "CURRENT", object_type: "INDEX", schema: "APP", parent_schema: "APP", parent_name: "T" }]);+ });+ const { store } = await setup(listObjects);+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(exactCalls).toBe(1));+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(schema.children?.some((node) => node.objectName === "CURRENT")).toBe(true));+ release([{ name: "STALE", object_type: "INDEX", schema: "APP", parent_schema: "APP", parent_name: "T" }]);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(schema.children?.some((node) => node.objectName === "STALE")).toBe(false);+ expect(schema.children?.some((node) => node.objectName === "CURRENT")).toBe(true);+ });++ it("does not start an exact page from a retired ordinary supplement", async () => {+ let release!: (objects: ObjectInfo[]) => void;+ let ordinaryCalls = 0;+ let exactCalls = 0;+ const listObjects = vi.fn((...args: unknown[]) => {+ if (args[10] === true) {+ exactCalls++;+ return Promise.resolve([{ name: "CURRENT", object_type: "INDEX", schema: "APP", parent_schema: "APP", parent_name: "T" }]);+ }+ if (++ordinaryCalls === 1)+ return new Promise<ObjectInfo[]>((resolve) => {+ release = resolve;+ });+ return Promise.resolve([]);+ });+ const { store } = await setup(listObjects);+ store.connections = [{ ...connection, db_type: "oracle" }];+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(ordinaryCalls).toBe(1));+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(exactCalls).toBe(1));+ release([]);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(exactCalls).toBe(1);+ });++ it("replaces only the index window when a flat index page anchor moves", async () => {+ const index = (name: string): ObjectInfo => ({ name, object_type: "INDEX", schema: "APP", parent_schema: "APP", parent_name: "T" });+ const pages = [[index("I1"), index("I2"), index("I3")], [index("I4")], [index("I2"), index("I3"), index("I4")]];+ const listObjects = vi.fn(async (...args: unknown[]) => (args[10] === true ? pages.shift()! : []));+ const { store } = await setup(listObjects, vi.fn().mockResolvedValue([{ name: "TABLE_KEPT", table_type: "TABLE" }]));+ store.connections = [{ ...connection, db_type: "oracle" }];+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(schema.children?.find((node) => node.loadMore?.objectType === "INDEX")).toBeDefined());+ await store.loadMoreObjectGroupChildren(schema.children!.find((node) => node.loadMore?.objectType === "INDEX")!);+ expect(schema.children?.filter((node) => node.type === "index").map((node) => node.objectName)).toEqual(["I2", "I3", "I4"]);+ expect(schema.children?.some((node) => node.label === "TABLE_KEPT")).toBe(true);+ expect(listObjects.mock.calls.filter((args) => args[10] === true).map((args) => args.slice(5, 7))).toEqual([+ [3, 0],+ [3, 2],+ [5, 0],+ ]);+ });++ it("keeps flat legacy objects usable while exposing an exact-index read error", async () => {+ const listObjects = vi.fn().mockImplementation(async (...args: unknown[]) => {+ if (args[10] === true) throw new Error("Cannot verify exact_metadata_identity_v1");+ return [{ name: "T", object_type: "TABLE", schema: "APP" }];+ });+ const { store } = await setup(listObjects);+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(store.connectionErrors[connection.id]).toContain("exact_metadata_identity_v1"));+ expect(schema.children?.some((node) => node.type === "table" && node.label === "T")).toBe(true);+ });++ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("%s schema indexes use exact raw owners and one captured search page", async (dbType) => {+ const objects: ObjectInfo[] = [" Ix(a) ", "ix(A)", "Ix_A_2"].map((name) => ({ name, object_type: "INDEX", schema: " Mixed ", parent_schema: " Other Owner ", parent_name: " T(a) " }));+ const listObjects = vi.fn().mockResolvedValueOnce(objects).mockResolvedValueOnce([objects[2]]);+ const { store, group } = await setup(listObjects);+ store.connections = [{ ...connection, db_type: dbType }];+ group.type = "group-database-indexes";+ group.id = group.id.replace("__procedures", "__indexes");+ group.schema = " Mixed ";+ store.sidebarSearchQuery = "Ix";+ await store.loadObjectGroupChildren(group, { force: true, searchFilter: "Ix", expectedSidebarSearchQuery: "Ix" });+ expect(listObjects).toHaveBeenNthCalledWith(1, connection.id, "APP", " Mixed ", ["INDEX"], "Ix", 3, 0, undefined, undefined, undefined, true);+ expect(group.children?.[0]).toMatchObject({ objectName: " Ix(a) ", schema: " Mixed ", parentSchema: " Other Owner ", parentName: " T(a) ", objectScope: "schema" });+ const more = group.children?.find((node) => node.type === "load-more");+ expect(more).toBeDefined();+ await store.loadMoreObjectGroupChildren(more!);+ expect(listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", " Mixed ", ["INDEX"], "Ix", 3, 2, undefined, undefined, undefined, true);+ expect(group.children?.filter((node) => node.type === "index").map((node) => node.objectName)).toEqual(objects.map((object) => object.name));+ });++ it("does not hydrate a legacy persisted index list or turn an exact capability error into an empty success", async () => {+ const listObjects = vi.fn().mockRejectedValue(new Error("Cannot verify exact_metadata_identity_v1"));+ const { store, group } = await setup(listObjects);+ group.type = "group-database-indexes";+ group.id = group.id.replace("__procedures", "__indexes");+ const api = await import("@/lib/backend/api");+ vi.mocked(api.loadSchemaCache).mockResolvedValue([{ id: "legacy-index", type: "index", label: "WRONG", schema: "APP" }]);+ await expect(store.loadObjectGroupChildren(group)).rejects.toThrow("exact_metadata_identity_v1");+ expect(group.children?.some((node) => node.id === "legacy-index")).toBe(false);+ expect(listObjects).toHaveBeenCalledOnce();+ });++ it("does not reuse a late exact index page after the connection lifetime ends", async () => {+ let release!: (objects: ObjectInfo[]) => void;+ const listObjects = vi+ .fn()+ .mockReturnValueOnce(+ new Promise<ObjectInfo[]>((resolve) => {+ release = resolve;+ }),+ )+ .mockRejectedValueOnce(new Error("new process lacks exact_metadata_identity_v1"));+ const { store, group } = await setup(listObjects);+ group.type = "group-database-indexes";+ group.id = group.id.replace("__procedures", "__indexes");+ const schema = store.treeNodes[0].children![0].children![0];+ const database = store.treeNodes[0].children![0];+ const pending = store.loadObjectGroupChildren(group);+ await vi.waitFor(() => expect(listObjects).toHaveBeenCalledOnce());+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });+ release([{ name: "OLD_CAPABLE_PROCESS", object_type: "INDEX", schema: "APP", parent_schema: "APP", parent_name: "T" }]);+ await pending;+ store.connectedIds.add(connection.id);+ store.treeNodes[0].children = [database];+ database.children = [schema];+ schema.children = [group];+ await expect(store.loadObjectGroupChildren(group)).rejects.toThrow("new process lacks exact_metadata_identity_v1");+ expect(listObjects).toHaveBeenCalledTimes(2);+ expect(group.children?.some((node) => node.objectName === "OLD_CAPABLE_PROCESS")).toBe(false);+ });+it("uses one bounded object stream in simple mode, retaining a package and its body across pages", async () => {const objects: ObjectInfo[] = [{ name: "A_TABLE", schema: "APP", object_type: "TABLE", comment: "table comment" },{ name: "SHARED", schema: "APP", object_type: "PACKAGE" },{ name: "SHARED", schema: "APP", object_type: "PACKAGE_BODY" },];- const listObjects = vi.fn().mockResolvedValueOnce(objects).mockResolvedValueOnce([objects[2]]);+ let ordinaryPage = 0;+ const listObjects = vi.fn().mockImplementation(async (...args: unknown[]) => (args[10] === true ? [] : ordinaryPage++ === 0 ? objects : [objects[2]]));const { store } = await setup(listObjects);const { useSettingsStore } = await import("@/stores/settingsStore");useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";const schema = store.treeNodes[0].children![0].children![0];schema.children = [];await store.loadTables(connection.id, "APP", "APP", { force: true });- expect(listObjects).toHaveBeenCalledTimes(1);+ expect(listObjects.mock.calls.filter((call) => call[10] !== true)).toHaveLength(1);expect(listObjects.mock.calls[0]?.[3]).toEqual(expect.arrayContaining(["TABLE", "PACKAGE", "PACKAGE_BODY"]));expect(listObjects.mock.calls[0]?.slice(5, 7)).toEqual([3, 0]);expect(schema.children?.map((node) => node.type)).toContain("package");expect(schema.children?.map((node) => node.type)).not.toContain("package-body");await store.loadMoreObjectGroupChildren(schema.children!.at(-1)!);- expect(listObjects).toHaveBeenCalledTimes(2);- expect(listObjects.mock.calls[1]?.[3]).toEqual(listObjects.mock.calls[0]?.[3]);- expect(listObjects.mock.calls[1]?.slice(5, 7)).toEqual([3, 2]);+ const ordinaryCalls = listObjects.mock.calls.filter((call) => call[10] !== true);+ expect(ordinaryCalls).toHaveLength(2);+ expect(ordinaryCalls[1]?.[3]).toEqual(ordinaryCalls[0]?.[3]);+ expect(ordinaryCalls[1]?.slice(5, 7)).toEqual([3, 2]);expect(schema.children?.filter((node) => node.label === "SHARED")diff --git a/apps/desktop/src/stores/__tests__/connectionStore.oneTimeCleanup.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.oneTimeCleanup.spec.tsindex dc25c89fea..7443d6930f 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.oneTimeCleanup.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.oneTimeCleanup.spec.ts@@ -132,6 +132,100 @@ describe("connectionStore one_time runtime cleanup", () => {expect(store.getConfig("deeplink-1")).toMatchObject({ name: "Deeplink", one_time: true });});+ it("retains the response-only dialect identity when loading saved connections", async () => {+ installApiMocks();+ const { loadConnections } = await import("@/lib/backend/api");+ const { effectiveDatabaseTypeForConnection } = await import("@/lib/database/jdbcDialect");+ const saved = previewConnection({+ id: "jdbc-oracle-mode",+ one_time: false,+ db_type: "jdbc",+ connection_string: "__DBX_SAVED_CREDENTIAL__:opaque",+ jdbc_dialect: "oceanbase-oracle",+ });+ vi.mocked(loadConnections).mockResolvedValue([saved]);+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();++ await store.initFromDisk();++ expect(store.getConfig(saved.id)?.jdbc_dialect).toBe("oceanbase-oracle");+ expect(effectiveDatabaseTypeForConnection(store.getConfig(saved.id))).toBe("oceanbase-oracle");+ });++ it("does not let an in-flight connection response replace an edit made after the load began", async () => {+ installApiMocks();+ const { loadConnections } = await import("@/lib/backend/api");+ let finishLoad!: (connections: ConnectionConfig[]) => void;+ vi.mocked(loadConnections).mockReturnValueOnce(+ new Promise((resolve) => {+ finishLoad = resolve;+ }),+ );+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const saved = previewConnection({+ id: "jdbc-oracle-mode",+ one_time: false,+ db_type: "jdbc",+ connection_string: "__DBX_SAVED_CREDENTIAL__:opaque",+ jdbc_dialect: "oceanbase-oracle",+ });+ store.connections = [saved];++ const loading = store.initFromDisk();+ await vi.waitFor(() => expect(loadConnections).toHaveBeenCalledOnce());+ const edited = { ...saved, connection_string: "jdbc:oracle:thin:@host/service", jdbc_dialect: undefined };+ store.connections = [edited];+ finishLoad([saved]);+ await loading;++ expect(store.getConfig(saved.id)?.connection_string).toBe(edited.connection_string);+ expect(store.getConfig(saved.id)?.jdbc_dialect).toBeUndefined();+ const { effectiveDatabaseTypeForConnection } = await import("@/lib/database/jdbcDialect");+ expect(effectiveDatabaseTypeForConnection(store.getConfig(saved.id))).toBe("oracle");+ });++ it("does not reconnect for response-only dialect changes and omits the hint from saves", async () => {+ installApiMocks();+ const { saveConnections } = await import("@/lib/backend/api");+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const connection = previewConnection({+ id: "jdbc-oracle-mode",+ one_time: false,+ db_type: "jdbc",+ connection_string: "__DBX_SAVED_CREDENTIAL__:opaque",+ jdbc_dialect: "oceanbase-oracle",+ });+ store.connections = [connection];+ store.connectedIds.add(connection.id);++ await store.updateConnection({ ...connection, jdbc_dialect: undefined });++ expect(store.connectedIds.has(connection.id)).toBe(true);+ const { effectiveDatabaseTypeForConnection } = await import("@/lib/database/jdbcDialect");+ expect(effectiveDatabaseTypeForConnection(store.getConfig(connection.id))).toBe("oceanbase-oracle");+ expect(saveConnections).toHaveBeenCalledOnce();+ const savedConfigs = vi.mocked(saveConnections).mock.calls[0]![0];+ expect(savedConfigs[0]).not.toHaveProperty("jdbc_dialect");+ });++ it.each(["rename", "replace-url", "clear-url", "replace-reference"])("keeps a saved JDBC dialect only for the unchanged protected URL (%s)", async (edit) => {+ installApiMocks();+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { effectiveDatabaseTypeForConnection } = await import("@/lib/database/jdbcDialect");+ const { saveConnections } = await import("@/lib/backend/api");+ const store = useConnectionStore();+ const saved = previewConnection({ id: "jdbc-mode", name: "Saved", one_time: false, db_type: "jdbc", driver_profile: "jdbc", driver_label: "JDBC", jdbc_driver_class: "com.oceanbase.jdbc.Driver", connection_string: "__DBX_SAVED_CREDENTIAL__:original", jdbc_dialect: "oceanbase-oracle" });+ store.connections = [saved];+ const { jdbc_dialect: _hint, ...form } = saved;+ const url = edit === "replace-url" ? "jdbc:oracle:thin:@host/service" : edit === "clear-url" ? "" : edit === "replace-reference" ? "__DBX_SAVED_CREDENTIAL__:other" : saved.connection_string;+ await store.updateConnection({ ...form, name: "Renamed", connection_string: url });+ expect(effectiveDatabaseTypeForConnection(store.getConfig(saved.id))).toBe(edit === "rename" ? "oceanbase-oracle" : edit === "replace-url" ? "oracle" : "jdbc");+ expect(vi.mocked(saveConnections).mock.calls.at(-1)![0][0]).not.toHaveProperty("jdbc_dialect");+ });+it("does not retain a stale saved connection removed from persisted storage", async () => {installApiMocks();const { loadConnections } = await import("@/lib/backend/api");diff --git a/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.tsindex 8b109ab965..0ec99c7703 100644--- a/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts@@ -54,6 +54,36 @@ describe("queryStore database open state", () => {expect(store.tabs.find((tab) => tab.id === firstId)).toMatchObject({ connectionId: "pg-1", database: "", mode: "databases" });});+ it.each(["create", "view"] as const)("does not reuse a consumed Schema index %s navigation request id", async (kind) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const request = kind === "create" ? { create: true } : { view: { schema: "APP", name: "IX_A", parentSchema: "OTHER", parentName: "T" } };+ const id = store.openObjectBrowser("ob", "service", "APP", undefined, undefined, false, "indexes", undefined, request);+ const state = store.tabs.find((tab) => tab.id === id)!.objectBrowser!;+ const firstRequest = kind === "create" ? state.indexCreateRequestId : state.initialViewRequestId;+ state.indexCreateRequestId = undefined;+ state.initialViewRequestId = undefined;+ state.initialViewTarget = undefined;+ expect(store.openObjectBrowser("ob", "service", "APP", undefined, undefined, false, "indexes", undefined, request)).toBe(id);+ const next = store.tabs.find((tab) => tab.id === id)!.objectBrowser!;+ expect(kind === "create" ? next.indexCreateRequestId : next.initialViewRequestId).toBeGreaterThan(firstRequest!);+ });++ it.each(["create", "view"] as const)("supersedes an unconsumed Schema index %s request in the reused tab", async (first) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const view = { schema: "APP", name: "IX_A", parentSchema: "OTHER", parentName: "T" };+ const id = store.openObjectBrowser("ob", "service", "APP", undefined, undefined, false, "indexes", undefined, first === "create" ? { create: true } : { view });+ const sequence = store.tabs.find((tab) => tab.id === id)!.objectBrowser!.indexRequestSequence!;+ expect(store.openObjectBrowser("ob", "service", "APP", undefined, undefined, false, "indexes", undefined, first === "create" ? { view } : { create: true })).toBe(id);+ const state = store.tabs.find((tab) => tab.id === id)!.objectBrowser!;+ expect(state.indexRequestSequence).toBeGreaterThan(sequence);+ expect(state.indexCreateRequestId).toBe(first === "view" ? state.indexRequestSequence : undefined);+ expect(state.initialViewRequestId).toBe(first === "create" ? state.indexRequestSequence : undefined);+ expect(state.initialViewTarget).toEqual(first === "create" ? view : undefined);+ expect(store.tabs.filter((tab) => tab.mode === "objects")).toHaveLength(1);+ });+it("retargets a connection-scoped driver workspace to a database branch", async () => {const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();@@ -162,6 +192,59 @@ describe("queryStore database open state", () => {expect(store.openTableStructure("pg-1", "app", "Sales", "Users")).toBe(quotedTabId);});+ it("never upgrades a legacy structure draft to an exact dictionary target", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const legacy = store.openTableStructure("ob", "service", " Mixed ", " T(a) ");+ const oldTab = store.tabs.find((tab) => tab.id === legacy)!;+ oldTab.structureDraft = { dirty: true, newTableName: "untouched" } as NonNullable<typeof oldTab.structureDraft>;+ const exact = store.openTableStructure("ob", "service", " Mixed ", " T(a) ", "indexes", { kind: "index", name: " Ix(a) " }, undefined, "table", true);+ expect(exact).not.toBe(legacy);+ expect(oldTab.structureDraft.newTableName).toBe("untouched");+ expect(oldTab.structureExactIdentity).toBeUndefined();+ expect(store.tabs.find((tab) => tab.id === exact)).toMatchObject({ schema: " Mixed ", structureTableName: " T(a) ", structureExactIdentity: true });+ expect(store.openTableStructure("ob", "service", " Mixed ", " T(a) ", "indexes", { kind: "index", name: "Ix(a)" }, undefined, "table", true)).toBe(exact);+ expect(store.openTableStructure("ob", "service", "Mixed", "T(a)", "indexes", undefined, undefined, "table", true)).not.toBe(exact);+ });++ it("isolates exact structure refreshes by raw identity, catalog and metadata mode", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ store.invalidateTableStructure("ob", "service", " Mixed ", " T(a) ", true, "catalog");+ expect(store.tableStructureRefreshVersion("ob", "service", " Mixed ", " T(a) ", true, "catalog")).toBe(1);+ expect(store.tableStructureRefreshVersion("ob", "service", " Mixed ", " T(a) ")).toBe(0);+ expect(store.tableStructureRefreshVersion("ob", "service", " Mixed ", " T(a) ", true, "other")).toBe(0);+ expect(store.tableStructureRefreshVersion("ob", "service", " mixed ", " T(a) ", true, "catalog")).toBe(0);+ expect(store.tableStructureRefreshVersion("ob", "service", "Mixed", "T(a)", true, "catalog")).toBe(0);+ store.invalidateTableStructure("ob", "service", "APP", "TABLE");+ expect(store.tableStructureRefreshVersion("ob", "service", "app", "table")).toBe(1);+ });++ it("retains explicit create-index requests without inventing an existing index name", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const create = { kind: "index", name: "", action: "create" } as const;+ const id = store.openTableStructure("ob", "service", "APP", "Items", undefined, create, undefined, "table", true);+ expect(store.tabs.find((tab) => tab.id === id)).toMatchObject({ structureInitialTarget: create, structureInitialTabRequestId: 1 });+ store.openTableStructure("ob", "service", "APP", "Items", undefined, create, undefined, "table", true);+ expect(store.tabs.find((tab) => tab.id === id)).toMatchObject({ structureInitialTarget: create, structureInitialTabRequestId: 2 });+ });++ it("retains raw index owner requests while reusing an exact parent tab with dirty drafts", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const initial = { kind: "index", name: " Ix(a) ", owner: " Owner " } as const;+ const id = store.openTableStructure("ob", "service", " Owner ", " T(a) ", "indexes", initial, undefined, "table", true);+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.structureDraft = { dirty: true, newTableName: "untouched" } as NonNullable<typeof tab.structureDraft>;+ expect(tab.structureInitialTarget).toEqual(initial);++ const deletion = { ...initial, action: "delete" } as const;+ expect(store.openTableStructure("ob", "service", " Owner ", " T(a) ", "indexes", deletion, undefined, "table", true)).toBe(id);+ expect(tab.structureInitialTarget).toEqual(deletion);+ expect(tab.structureDraft.newTableName).toBe("untouched");+ });+it("reuses only matching schema-less structure targets", async () => {const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();diff --git a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.tsindex 722d65ef90..0c9d849a0d 100644--- a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts@@ -9,34 +9,53 @@ vi.stubGlobal("localStorage", {removeItem: (key: string) => localStorageValues.delete(key),});-const executeMulti = vi.fn();-const executeQuery = vi.fn();-const beginManualTransaction = vi.fn();-const executeInManualTransaction = vi.fn();-const cancelQuery = vi.fn();-const analyzeEditableQueryEditability = vi.fn();-const getColumns = vi.fn();-const listIndexes = vi.fn();-const listObjects = vi.fn();-const listTables = vi.fn();-const getConnectionConfig = vi.fn();-const lookupLocalCompletionTables = vi.fn();-const buildSortedQuerySql = vi.fn();-const buildDataGridCountSql = vi.fn();-const prepareQueryPaginationExecutionPlan = vi.fn(async (options) => ({- sqlToExecute: options.sql,- pageSql: undefined,- pageLimit: undefined,- pageOffset: undefined,- countSql: undefined,- useAgentResultSession: false,+const {+ executeMulti,+ executeQuery,+ beginManualTransaction,+ executeInManualTransaction,+ cancelQuery,+ analyzeEditableQueryEditability,+ getColumns,+ listIndexes,+ listObjects,+ listTables,+ getConnectionConfig,+ lookupLocalCompletionTables,+ buildSortedQuerySql,+ buildDataGridCountSql,+ prepareQueryPaginationExecutionPlan,+ editorSettings,+} = vi.hoisted(() => ({+ executeMulti: vi.fn(),+ executeQuery: vi.fn(),+ beginManualTransaction: vi.fn(),+ executeInManualTransaction: vi.fn(),+ cancelQuery: vi.fn(),+ analyzeEditableQueryEditability: vi.fn(),+ getColumns: vi.fn(),+ listIndexes: vi.fn(),+ listObjects: vi.fn(),+ listTables: vi.fn(),+ getConnectionConfig: vi.fn(),+ lookupLocalCompletionTables: vi.fn(),+ buildSortedQuerySql: vi.fn(),+ buildDataGridCountSql: vi.fn(),+ prepareQueryPaginationExecutionPlan: vi.fn(async (options) => ({+ sqlToExecute: options.sql,+ pageSql: undefined,+ pageLimit: undefined,+ pageOffset: undefined,+ countSql: undefined,+ useAgentResultSession: false,+ })),+ editorSettings: {+ pageSize: 100,+ autoCalculateTotalRows: false,+ queryResultMaxRowsEnabled: true,+ queryResultMaxRows: 100_000,+ },}));-const editorSettings = {- pageSize: 100,- autoCalculateTotalRows: false,- queryResultMaxRowsEnabled: true,- queryResultMaxRows: 100_000,-};function deferred<T>() {let resolve!: (value: T) => void;diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.tsindex 62ef282340..4db5b30ea4 100644--- a/apps/desktop/src/stores/connectionStore.ts+++ b/apps/desktop/src/stores/connectionStore.ts@@ -6,6 +6,7 @@ import { containsHan, orderedSubsequenceSpan, pinyinFirstLetters } from "@/lib/cimport { ref, computed, watch, markRaw, reactive } from "vue";import { DEFAULT_QUERY_TIMEOUT_SECS, normalizeManualTransactionTimeoutSecs } from "@/lib/connection/timeoutLimits";import { gaussdbConnectionMode } from "@/lib/database/jdbcDialect";+import { supportsSchemaIndexManagement } from "@/lib/database/databaseObjectCapabilities";import { notifyComponentUpdatesChanged } from "@/lib/updates/componentUpdateEvents";import type {ColumnInfo,@@ -765,7 +766,7 @@ export const useConnectionStore = defineStore("connection", () => {return metadataLoadCoordinator.run(scope, task, { force: options?.force, kind: scope.kind });}- async function loadCachedMetadataListPage<T extends MetadataListPageResult>(scope: MetadataScopeInput, load: () => Promise<T>, options?: { force?: boolean }): Promise<T> {+ async function loadCachedMetadataListPage<T extends MetadataListPageResult>(scope: MetadataScopeInput, load: () => Promise<T>, options?: { force?: boolean; isCurrent?: () => boolean }): Promise<T> {const trace = createMetadataLoadTrace(scope);if (!options?.force) {const cached = metadataListPageCache.get(scope);@@ -781,7 +782,20 @@ export const useConnectionStore = defineStore("connection", () => {logMetadataLoadTrace(metadataTraceLogger, trace, "cache-miss", { cacheStatus: options?.force ? "refresh" : "miss", force: options?.force === true });const errorRevision = connectionErrorRevision(scope.connectionId);+ const exactConfig = scope.extra?.exactIdentity === true && scope.connectionId ? getConfig(scope.connectionId) : undefined;+ const exactFingerprint = exactConfig ? connectionConfigFingerprint(exactConfig) : undefined;const result = await load();+ if (scope.extra?.exactIdentity === true && scope.connectionId) {+ const currentConfig = getConfig(scope.connectionId);+ if (+ scope.extra.connectionRevision !== connectionStateRevision(scope.connectionId) ||+ scope.extra.metadataGeneration !== metadataGenerationFor(scope.connectionId, scope.database ?? undefined) ||+ !currentConfig ||+ exactFingerprint !== connectionConfigFingerprint(currentConfig) ||+ options?.isCurrent?.() === false+ )+ return result;+ }clearConnectionErrorIfUnchanged(scope.connectionId, errorRevision);metadataListPageCache.set(scope, result);logMetadataLoadTrace(metadataTraceLogger, trace, "done", {@@ -1836,7 +1850,6 @@ export const useConnectionStore = defineStore("connection", () => {docs_notes_path: config.docs_notes_path?.trim() ? config.docs_notes_path.trim() : undefined,transport_layers: Array.isArray(config.transport_layers) ? config.transport_layers : [],show_system_schemas: config.show_system_schemas === true,- show_database_links: config.show_database_links !== false,sidebar_auto_load_all_tables: config.sidebar_auto_load_all_tables === true,connect_timeout_secs: connectTimeoutInherit ? settingsStore.editorSettings.globalConnectTimeoutSecs : config.connect_timeout_secs || 10,connect_timeout_inherit: connectTimeoutInherit,@@ -2486,6 +2499,10 @@ export const useConnectionStore = defineStore("connection", () => {}}+ function isSchemaIndexGroup(node: TreeNode): boolean {+ return node.type === "group-database-indexes" && supportsSchemaIndexManagement(effectiveDatabaseTypeForConnection(node.connectionId ? getConfig(node.connectionId) : undefined));+ }+function objectGroupCacheKey(node: TreeNode): string {const config = node.connectionId ? getConfig(node.connectionId) : undefined;const objectTreeProfileCacheKey = driverProfileObjectTreeProfileForConnection(config)?.cacheKey;@@ -2498,7 +2515,7 @@ export const useConnectionStore = defineStore("connection", () => {const defaultCacheVersion = config?.db_type === "tdengine" && node.type === "group-tables" ? "objects-tdengine-v1" : config?.db_type === "oracle" ? "objects-v8" : "objects-v9";const baseCacheVersion = objectTreeCacheVersion(config, node.database, node.schema, defaultCacheVersion);const cacheVersion = objectTreeProfileCacheKey ? `${baseCacheVersion}:${objectTreeProfileCacheKey}` : baseCacheVersion;- return schemaCacheKey(node.connectionId || "", node.database || "", node.schema || "", node.type, cacheVersion);+ return schemaCacheKey(node.connectionId || "", node.database || "", node.schema || "", node.type, isSchemaIndexGroup(node) ? `${cacheVersion}:exact-index-v1` : cacheVersion);}function tableNameFilterScopeKey(parts: { connectionId?: string | null; database?: string | null; schema?: string | null; nodeKind?: string | null; catalog?: string | null }): string {@@ -2616,7 +2633,7 @@ export const useConnectionStore = defineStore("connection", () => {offset: options.offset,sidebarDisplayMode: options.sidebarDisplayMode,driverProfile: metadataListDriverProfile(options.connectionId || undefined),- extra: options.extra,+ extra: options.extra?.exactIdentity === true && options.connectionId ? { ...options.extra, connectionRevision: connectionStateRevision(options.connectionId), metadataGeneration: metadataGenerationFor(options.connectionId, options.database ?? undefined) } : options.extra,};}@@ -2788,9 +2805,9 @@ export const useConnectionStore = defineStore("connection", () => {return fetchPage(0, offset + pageSize);}- function buildLoadMoreNode(parent: TreeNode, offset: number, pageSize: number, anchor?: string, searchFilter?: string): TreeNode {+ function buildLoadMoreNode(parent: TreeNode, offset: number, pageSize: number, anchor?: string, searchFilter?: string, objectType?: "INDEX"): TreeNode {return {- id: `${parent.id}:__load_more:${offset}`,+ id: `${parent.id}:__load_more:${objectType ? `${objectType}:` : ""}${offset}`,label: "tree.loadMore",type: "load-more",connectionId: parent.connectionId,@@ -2799,6 +2816,7 @@ export const useConnectionStore = defineStore("connection", () => {isLoading: false,loadMore: {parentId: parent.id,+ ...(objectType ? { objectType } : {}),offset,pageSize,...(searchFilter !== undefined ? { searchFilter, searchQuery: sidebarSearchQuery.value || "" } : {}),@@ -2975,11 +2993,24 @@ export const useConnectionStore = defineStore("connection", () => {};}- async function loadPagedObjectGroupChildren(options: { node: TreeNode; parentNodeId: string; querySchema: string; effectiveSchema?: string; objectTypes: DatabaseObjectTreeKind[]; offset: number; pageSize: number; searchFilter?: string; force?: boolean }): Promise<PagedTableWindow> {+ async function loadPagedObjectGroupChildren(options: {+ node: TreeNode;+ parentNodeId: string;+ querySchema: string;+ effectiveSchema?: string;+ objectTypes: DatabaseObjectTreeKind[];+ offset: number;+ pageSize: number;+ searchFilter?: string;+ force?: boolean;+ simpleIndexes?: boolean;+ }): Promise<PagedTableWindow> {if (!options.node.connectionId || options.node.database == null) {return { children: [], objectCount: 0, hasMore: false, nextOffset: options.offset };}const searchFilter = options.searchFilter || undefined;+ const exactIdentity = options.simpleIndexes || isSchemaIndexGroup(options.node);+ const querySchema = exactIdentity ? (options.node.schema ?? options.node.database) : options.querySchema;const userTableNameFilter = activeTableNameFilterForScope({connectionId: options.node.connectionId,database: options.node.database,@@ -2988,44 +3019,54 @@ export const useConnectionStore = defineStore("connection", () => {catalog: options.node.catalog,});const tableNameFilter = effectiveTableNameFilterForNode(options.node, userTableNameFilter);- const paginate = !searchFilter || getConfig(options.node.connectionId)?.db_type === "oceanbase-oracle";+ const paginate = exactIdentity || !searchFilter || getConfig(options.node.connectionId)?.db_type === "oceanbase-oracle";const fetchLimit = paginate ? options.pageSize + 1 : undefined;const fetchOffset = paginate ? options.offset : undefined;+ const cacheOwner = exactIdentity ? treeNodeLoads.observe(options.node.id) : undefined;const objects = await loadCachedMetadataListPage<ObjectInfo[]>(metadataListCacheScope({kind: "object-list-page",connectionId: options.node.connectionId,database: options.node.database,- schema: options.querySchema,- nodeKind: options.node.type,+ schema: querySchema,+ nodeKind: options.simpleIndexes ? "simple-indexes" : options.node.type,objectTypes: options.objectTypes,searchFilter,limit: fetchLimit,offset: fetchOffset,sidebarDisplayMode: useSettingsStore().editorSettings.sidebarObjectDisplay,- extra: tableNameFilterMetadataExtra(tableNameFilter),+ extra: { ...tableNameFilterMetadataExtra(tableNameFilter), ...(exactIdentity ? { exactIdentity: true } : {}) },}),() =>- tableNameFilter || options.node.catalog- ? api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter)- : api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset),- { force: options.force },+ exactIdentity+ ? api.listObjects(options.node.connectionId!, options.node.database!, querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter, undefined, true)+ : tableNameFilter || options.node.catalog+ ? api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter)+ : api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset),+ { force: options.force, isCurrent: cacheOwner ? () => cacheOwner.isCurrent() : undefined },);const hasMore = paginate && objects.length > options.pageSize;const pageObjects = hasMore ? objects.slice(0, options.pageSize) : objects;- const children = objectGroupChildrenFromObjects({- node: options.node,- parentNodeId: options.parentNodeId,- effectiveSchema: options.effectiveSchema,- objectTypes: options.objectTypes,- objects: pageObjects,- });+ const children = options.simpleIndexes+ ? buildSimpleObjectTreeNodes({ nodeId: options.parentNodeId, connectionId: options.node.connectionId, database: options.node.database, schema: options.effectiveSchema, objects: pageObjects, databaseType: effectiveDatabaseTypeForConnection(getConfig(options.node.connectionId)) })+ : objectGroupChildrenFromObjects({+ node: options.node,+ parentNodeId: options.parentNodeId,+ effectiveSchema: options.effectiveSchema,+ objectTypes: options.objectTypes,+ objects: pageObjects,+ });return {children,objectCount: children.length,hasMore,nextOffset: options.offset + pageObjects.length,- ...tablePageAnchors(objects, options.pageSize, hasMore, options.effectiveSchema),+ ...(exactIdentity+ ? {+ firstAnchor: objects[0] ? JSON.stringify([objects[0].schema, objects[0].name, objects[0].parent_schema, objects[0].parent_name]) : undefined,+ nextAnchor: hasMore ? JSON.stringify([objects[options.pageSize].schema, objects[options.pageSize].name, objects[options.pageSize].parent_schema, objects[options.pageSize].parent_name]) : undefined,+ }+ : tablePageAnchors(objects, options.pageSize, hasMore, options.effectiveSchema)),};}@@ -3040,7 +3081,13 @@ export const useConnectionStore = defineStore("connection", () => {const querySchema = connectionObjectTreeQuerySchema(config, node.database, node.schema);const effectiveSchema = connectionObjectTreeNodeSchema(config, node.database, node.schema);const pageSize = sidebarObjectGroupPageSize();- let objects: ObjectInfo[] = [];+ const requestGroups = supportsSchemaIndexManagement(effectiveDatabaseTypeForConnection(config))+ ? [+ { objectTypes: objectTypes.filter((type) => type !== "INDEX"), schema: querySchema, exactIdentity: false },+ { objectTypes: objectTypes.filter((type) => type === "INDEX"), schema: node.schema ?? node.database, exactIdentity: true },+ ]+ : [{ objectTypes, schema: querySchema, exactIdentity: false }];+ const objects: ObjectInfo[] = [];const childrenFromObjects = () => {const children = groupTypes? objectGroupChildrenFromObjects({ node, parentNodeId: objectGroupRefreshParentId(node) ?? node.id, effectiveSchema, objectTypes, objects })@@ -3050,56 +3097,74 @@ export const useConnectionStore = defineStore("connection", () => {const publish = () => {if (!signal.aborted) onProgress?.(childrenFromObjects());};- const pageScope = (offset: number) => metadataListCacheScope({ kind: "sidebar-object-search-page", connectionId, database: node.database!, schema: querySchema, nodeKind: node.type, objectTypes, searchFilter: query, limit: pageSize, offset, extra: { catalog: node.catalog ?? "" } });- const loadRemotePage = (offset: number, force: boolean) =>- loadCachedMetadataListPage<ObjectInfo[]>(- pageScope(offset),- async () => {- signal.throwIfAborted();- const executionId = `sidebar-search-${uuid()}`;- const cancel = () => {- void api.cancelQuery(executionId).catch(() => false);- };- signal.addEventListener("abort", cancel, { once: true });- try {- const rows = await api.listObjects(connectionId, node.database!, querySchema, objectTypes, query, pageSize, offset, node.catalog, undefined, executionId);+ for (const request of requestGroups) {+ if (!request.objectTypes.length) continue;+ const groupStart = objects.length;+ const pageScope = (offset: number) =>+ metadataListCacheScope({+ kind: "sidebar-object-search-page",+ connectionId,+ database: node.database!,+ schema: request.schema,+ nodeKind: node.type,+ objectTypes: request.objectTypes,+ searchFilter: query,+ limit: pageSize,+ offset,+ extra: { catalog: node.catalog ?? "", ...(request.exactIdentity ? { exactIdentity: true } : {}) },+ });+ const loadRemotePage = (offset: number, force: boolean) =>+ loadCachedMetadataListPage<ObjectInfo[]>(+ pageScope(offset),+ async () => {signal.throwIfAborted();- if (revision !== sidebarObjectSearchRevision.value) throw new DOMException("Search metadata invalidated", "AbortError");- return rows;- } finally {- signal.removeEventListener("abort", cancel);- }- },- { force },- );+ const executionId = `sidebar-search-${uuid()}`;+ const cancel = () => {+ void api.cancelQuery(executionId).catch(() => false);+ };+ signal.addEventListener("abort", cancel, { once: true });+ try {+ const rows = request.exactIdentity+ ? await api.listObjects(connectionId, node.database!, request.schema, request.objectTypes, query, pageSize, offset, node.catalog, undefined, executionId, true)+ : await api.listObjects(connectionId, node.database!, request.schema, request.objectTypes, query, pageSize, offset, node.catalog, undefined, executionId);+ signal.throwIfAborted();+ if (revision !== sidebarObjectSearchRevision.value) throw new DOMException("Search metadata invalidated", "AbortError");+ return rows;+ } finally {+ signal.removeEventListener("abort", cancel);+ }+ },+ { force },+ );- let offset = 0;- let refreshFromStart = false;-- // Publish consecutive cached pages immediately. A stale page remains useful- // as the first paint. Any cached snapshot is then revalidated from zero so- // a fresh-but-incomplete cache cannot hide objects added outside the app.- while (!signal.aborted && connectedIds.value.has(connectionId)) {- const cached = metadataListPageCache.get(pageScope(offset), { allowStale: true });- if (!cached) break;- refreshFromStart = true;- objects.push(...(cached.value as ObjectInfo[]));- publish();- if (cached.stale || cached.value.length < pageSize) break;- offset += cached.value.length;- }-- if (refreshFromStart) {- objects = [];- offset = 0;- }- while (!signal.aborted && connectedIds.value.has(connectionId)) {- const page = await loadRemotePage(offset, refreshFromStart);- signal.throwIfAborted();- objects.push(...page);- publish();- if (page.length < pageSize) break;- offset += page.length;+ let offset = 0;+ let refreshFromStart = false;++ // Publish consecutive cached pages immediately. A stale page remains useful+ // as the first paint. Any cached snapshot is then revalidated from zero so+ // a fresh-but-incomplete cache cannot hide objects added outside the app.+ while (!signal.aborted && connectedIds.value.has(connectionId)) {+ const cached = metadataListPageCache.get(pageScope(offset), { allowStale: true });+ if (!cached) break;+ refreshFromStart = true;+ objects.push(...(cached.value as ObjectInfo[]));+ publish();+ if (cached.stale || cached.value.length < pageSize) break;+ offset += cached.value.length;+ }++ if (refreshFromStart) {+ objects.splice(groupStart);+ offset = 0;+ }+ while (!signal.aborted && connectedIds.value.has(connectionId)) {+ const page = await loadRemotePage(offset, refreshFromStart);+ signal.throwIfAborted();+ objects.push(...page);+ publish();+ if (page.length < pageSize) break;+ offset += page.length;+ }}if (signal.aborted || !connectedIds.value.has(connectionId)) return [];return childrenFromObjects();@@ -3212,55 +3277,86 @@ export const useConnectionStore = defineStore("connection", () => {}) {if (options.objectTypes.length === 0) return;const searchFilter = activeTreeLoadSearchFilter(options.loadOptions);- if (searchFilter) return;+ const databaseType = effectiveDatabaseTypeForConnection(getConfig(options.connectionId));+ const exactIndexes = supportsSchemaIndexManagement(databaseType) && options.objectTypes.includes("INDEX");+ const ordinaryTypes = exactIndexes ? options.objectTypes.filter((type) => type !== "INDEX") : options.objectTypes;+ const queries = [...(!searchFilter && ordinaryTypes.length ? [{ objectTypes: ordinaryTypes, exactIdentity: false }] : []), ...(exactIndexes ? [{ objectTypes: ["INDEX"] as DatabaseObjectTreeKind[], exactIdentity: true }] : [])];+ for (const query of queries) {+ try {+ if (query.exactIdentity) {+ if (!options.load.isCurrent() || isTreeLoadSearchChanged(searchFilter, options.loadOptions)) return;+ const pageSize = sidebarObjectGroupPageSize();+ const page = await loadPagedObjectGroupChildren({+ node: options.node,+ parentNodeId: options.nodeId,+ querySchema: options.querySchema,+ effectiveSchema: options.effectiveSchema,+ objectTypes: ["INDEX"],+ offset: 0,+ pageSize,+ searchFilter,+ force: options.loadOptions?.force,+ simpleIndexes: true,+ });+ if (isTreeLoadSearchChanged(searchFilter, options.loadOptions)) return;+ const targetNode = treeNodeLoadTarget(options.load);+ if (!targetNode) return;+ const currentChildren = (targetNode.children || []).filter((child) => !(child.type === "index" && child.objectScope === "schema") && child.loadMore?.objectType !== "INDEX");+ const mergedChildren = mergeLocatedTreeChildren(targetNode, currentChildren, page.children, options.connectionId, options.database);+ setChildren(targetNode, page.hasMore ? [...mergedChildren, buildLoadMoreNode(targetNode, page.nextOffset, pageSize, page.nextAnchor, searchFilter || "", "INDEX")] : mergedChildren);+ targetNode.objectCount = mergedChildren.filter((child) => child.type !== "load-more").length;+ continue;+ }+ const querySchema = options.querySchema;+ const objects = await loadCachedMetadataListPage<ObjectInfo[]>(+ metadataListCacheScope({+ kind: "object-list-page",+ connectionId: options.connectionId,+ database: options.database,+ schema: querySchema,+ nodeKind: "simple-supplemental",+ objectTypes: query.objectTypes,+ searchFilter,+ sidebarDisplayMode: "simple",+ }),+ () => api.listObjects(options.connectionId, options.database, querySchema, query.objectTypes),+ { force: options.loadOptions?.force },+ );+ const supplementalObjects = filterSimpleSidebarSupplementalObjects(objects);+ if (supplementalObjects.length === 0) continue;+ let supplementalChildren = buildSimpleObjectTreeNodes({+ nodeId: options.nodeId,+ connectionId: options.connectionId,+ database: options.database,+ schema: options.effectiveSchema,+ objects: supplementalObjects,+ databaseType,+ });+ if (supportsPackageMemberExpansion(databaseType, databaseCompatibilityMode(options.connectionId, options.database))) {+ supplementalChildren = markPackageNodesExpandable(supplementalChildren);+ }+ if (supplementalChildren.length === 0) return;+ if (isTreeLoadSearchChanged(searchFilter, options.loadOptions)) return;+ const targetNode = treeNodeLoadTarget(options.load);+ if (!targetNode) return;- try {- const objects = await loadCachedMetadataListPage<ObjectInfo[]>(- metadataListCacheScope({- kind: "object-list-page",+ const loadMoreNodes = (targetNode.children || []).filter((child) => child.type === "load-more");+ const currentChildren = withoutLoadMoreNodes(targetNode.children);+ const mergedChildren = mergeLocatedTreeChildren(targetNode, currentChildren, supplementalChildren, options.connectionId, options.database);+ const nextChildren = [...mergedChildren, ...loadMoreNodes];+ setChildren(targetNode, nextChildren);+ targetNode.objectCount = mergedChildren.length;+ await savePersistedTreeChildren(options.cacheKey, nextChildren);+ } catch (error) {+ if (query.exactIdentity && !isTreeLoadSearchChanged(searchFilter, options.loadOptions)) recordMetadataLoadError(options.connectionId, error, options.load);+ // Some drivers only expose table metadata; keep the already-rendered table tree usable.+ console.debug("[DBX][metadata:simple-supplemental:error]", {connectionId: options.connectionId,database: options.database,- schema: options.querySchema,- nodeKind: "simple-supplemental",- objectTypes: options.objectTypes,- sidebarDisplayMode: "simple",- }),- () => api.listObjects(options.connectionId, options.database, options.querySchema, options.objectTypes),- { force: options.loadOptions?.force },- );- const supplementalObjects = filterSimpleSidebarSupplementalObjects(objects);- if (supplementalObjects.length === 0) return;- const databaseType = effectiveDatabaseTypeForConnection(getConfig(options.connectionId));- let supplementalChildren = buildSimpleObjectTreeNodes({- nodeId: options.nodeId,- connectionId: options.connectionId,- database: options.database,- schema: options.effectiveSchema,- objects: supplementalObjects,- databaseType,- });- if (supportsPackageMemberExpansion(databaseType, databaseCompatibilityMode(options.connectionId, options.database))) {- supplementalChildren = markPackageNodesExpandable(supplementalChildren);+ schema: options.effectiveSchema,+ error,+ });}- if (supplementalChildren.length === 0) return;- if (isTreeLoadSearchChanged(searchFilter, options.loadOptions)) return;- const targetNode = treeNodeLoadTarget(options.load);- if (!targetNode) return;-- const loadMoreNodes = (targetNode.children || []).filter((child) => child.type === "load-more");- const currentChildren = withoutLoadMoreNodes(targetNode.children);- const mergedChildren = mergeLocatedTreeChildren(targetNode, currentChildren, supplementalChildren, options.connectionId, options.database);- const nextChildren = [...mergedChildren, ...loadMoreNodes];- setChildren(targetNode, nextChildren);- await savePersistedTreeChildren(options.cacheKey, nextChildren);- } catch (error) {- // Some drivers only expose table metadata; keep the already-rendered table tree usable.- console.debug("[DBX][metadata:simple-supplemental:error]", {- connectionId: options.connectionId,- database: options.database,- schema: options.effectiveSchema,- error,- });}}@@ -3288,11 +3384,13 @@ export const useConnectionStore = defineStore("connection", () => {// keep auto-expanding a schema the user collapsed. Expansion state is instead// restored from the live tree (restoreExpandedChildren) within a session.function stripTreeNodeExpansionState(nodes: TreeNode[]): TreeNode[] {- return nodes.map((node) => ({- ...node,- isExpanded: false,- children: node.children ? stripTreeNodeExpansionState(node.children) : node.children,- }));+ return nodes+ .filter((node) => (node.type !== "index" || node.objectScope !== "schema") && node.loadMore?.objectType !== "INDEX")+ .map((node) => ({+ ...node,+ isExpanded: false,+ children: node.children ? stripTreeNodeExpansionState(node.children) : node.children,+ }));}async function loadPersistedTreeChildren(node: TreeNode, cacheKey: string, load: TreeNodeLoadHandle, options?: { freshOnly?: boolean; isCurrent?: () => boolean; acceptChildren?: (children: TreeNode[]) => boolean }): Promise<PersistedTreeChildrenLoadResult> {@@ -4432,6 +4530,10 @@ export const useConnectionStore = defineStore("connection", () => {const idx = connections.value.findIndex((c) => c.id === config.id);if (idx < 0) return;const previousConfig = normalizeConnection(connections.value[idx]);+ const keepsSavedJdbcTarget = previousConfig.db_type === "jdbc" && config.db_type === "jdbc" && previousConfig.driver_profile === config.driver_profile && previousConfig.connection_string === config.connection_string && isSavedCredential(config.connection_string);+ // Edit forms do not own server-derived hints. Retain the previous hint only+ // while its protected URL still refers to the same saved JDBC target.+ config = { ...config, jdbc_dialect: keepsSavedJdbcTarget ? previousConfig.jdbc_dialect : undefined };const previousDatabase = previousConfig.database ?? "";const runtimeConfigChanged = connectionConfigFingerprint(previousConfig) !== connectionConfigFingerprint(config);const shouldReconnectPlugin = runtimeConfigChanged && previousConfig.db_type === "plugin" && config.db_type === "plugin" && connectedIds.value.has(config.id);@@ -7018,6 +7120,9 @@ export const useConnectionStore = defineStore("connection", () => {if (!options?.force && !searchFilter && !tableNameFilter) {const cached = await loadPersistedTreeChildren(node, cacheKey, load);if (cached.hit) {+ if (simpleObjectDisplay && !isSidebarTableSearch && supportsSchemaIndexManagement(effectiveDatabaseTypeForConnection(config))) {+ void loadSimpleSupplementalObjectChildren({ node, nodeId, connectionId, database, querySchema, effectiveSchema, objectTypes: ["INDEX"], cacheKey, loadOptions: { ...options, force: true }, load });+ }if (cached.isStale) refreshStaleTreeNode(node);return;}@@ -7078,7 +7183,8 @@ export const useConnectionStore = defineStore("connection", () => {const currentTargetNode = treeNodeLoadTarget(load);if (!currentTargetNode) return;currentTargetNode.isExpanded = true;- if (simpleObjectDisplay && (config?.db_type !== "oceanbase-oracle" || tableNameFilter) && !searchFilter && !isSidebarTableSearch && nonTableObjectTypes.length > 0) {+ const exactIndexSupplement = supportsSchemaIndexManagement(effectiveDatabaseTypeForConnection(config));+ if (simpleObjectDisplay && (!searchFilter || exactIndexSupplement) && !isSidebarTableSearch && nonTableObjectTypes.length > 0) {void loadSimpleSupplementalObjectChildren({node: currentTargetNode,nodeId,@@ -7086,7 +7192,7 @@ export const useConnectionStore = defineStore("connection", () => {database,querySchema,effectiveSchema,- objectTypes: nonTableObjectTypes,+ objectTypes: config?.db_type === "oceanbase-oracle" && !tableNameFilter ? nonTableObjectTypes.filter((type) => type === "INDEX") : nonTableObjectTypes,cacheKey,loadOptions: options,load,@@ -7130,7 +7236,7 @@ export const useConnectionStore = defineStore("connection", () => {nodeKind: node.type,catalog: node.catalog,});- if (!options?.force && !searchFilter && !options?.sidebarTableSearchParentId && !tableNameFilterForScope) {+ if (!isSchemaIndexGroup(node) && !options?.force && !searchFilter && !options?.sidebarTableSearchParentId && !tableNameFilterForScope) {if (await hydrateTreeNodeFromCache(node, objectGroupCacheKey(node))) {forgetFilteredObjectGroupChildren(node.id);void loadObjectGroupFirstPage(node, { ...options, force: true }).catch(() => undefined);@@ -7179,8 +7285,8 @@ export const useConnectionStore = defineStore("connection", () => {catalog: node.catalog,});const isSidebarTableSearch = !!options?.sidebarTableSearchParentId;- const globalPageSearch = config?.db_type === "oceanbase-oracle" && !isSidebarTableSearch ? searchFilter : undefined;- if (!options?.force && !searchFilter && !tableNameFilter) {+ const globalPageSearch = (config?.db_type === "oceanbase-oracle" || isSchemaIndexGroup(node)) && !isSidebarTableSearch ? searchFilter : undefined;+ if (!isSchemaIndexGroup(node) && !options?.force && !searchFilter && !tableNameFilter) {const cached = await loadPersistedTreeChildren(node, cacheKey, load);if (cached.hit) {forgetFilteredObjectGroupChildren(node.id);@@ -7265,7 +7371,7 @@ export const useConnectionStore = defineStore("connection", () => {if (searchFilter) filteredObjectGroupChildrenIds.add(targetNode.id);else forgetFilteredObjectGroupChildren(targetNode.id);options?.onChildrenApplied?.(targetNode);- if (!searchFilter && !isSidebarTableSearch && !tableNameFilter) {+ if (!isSchemaIndexGroup(node) && !searchFilter && !isSidebarTableSearch && !tableNameFilter) {await savePersistedTreeChildren(cacheKey, children, targetNode);if (isTdengineTableGroup(node) && cacheRevision !== tdengineTreeCacheRevision(node)) return;pruneTableVGroupStaleMembers(targetNode, children, tableVGroupKindOfContainerNode(targetNode) !== null);@@ -7343,7 +7449,7 @@ export const useConnectionStore = defineStore("connection", () => {if (!parent?.connectionId || !hasTreeNodeDatabaseContext(parent)) return;const parentConnectionId = parent.connectionId;const configForScope = getConfig(parentConnectionId);- const objectTypesForScope = objectTypesForGroupNode(parent.type);+ const objectTypesForScope = loadMore.objectType === "INDEX" ? (["INDEX"] as DatabaseObjectTreeKind[]) : objectTypesForGroupNode(parent.type);const searchFilter = loadMore.searchFilter ?? options?.searchFilter;const globalSearchQuery = sidebarSearchQuery.value || "";const scopedSearchQuery = sidebarTableSearchQueries.value[parent.id]?.trim() || "";@@ -7363,6 +7469,7 @@ export const useConnectionStore = defineStore("connection", () => {searchFilter,limit: loadMore.pageSize + 1,offset: loadMore.offset,+ ...(loadMore.objectType ? { extra: { objectType: loadMore.objectType } } : {}),sidebarDisplayMode: useSettingsStore().editorSettings.sidebarObjectDisplay,driverProfile: metadataDriverProfile(configForScope),},@@ -7377,6 +7484,22 @@ export const useConnectionStore = defineStore("connection", () => {await ensureConnected(parentConnectionId);if (!searchIsCurrent()) return;load = reclaimTreeNodeLoad(load, node);+ if (loadMore.objectType === "INDEX") {+ if (!parentEpoch.isCurrent() || !load.isCurrent() || !searchIsCurrent()) return;+ const config = getConfig(parentConnectionId);+ const querySchema = parent.schema ?? parent.database;+ const page = await loadTablePageCheckingAnchor(loadMore.anchor, loadMore.offset, loadMore.pageSize, (offset, pageSize) =>+ loadPagedObjectGroupChildren({ node: parent, parentNodeId: parent.id, querySchema, effectiveSchema: connectionObjectTreeNodeSchema(config, parent.database, parent.schema), objectTypes: ["INDEX"], offset, pageSize, searchFilter, force: options?.force, simpleIndexes: true }),+ );+ const targetParent = treeNodeLoadRelatedTarget(load, parent);+ if (!targetParent || !parentEpoch.isCurrent() || !searchIsCurrent()) return;+ const replacedWindow = loadMore.anchor && page.firstAnchor !== loadMore.anchor;+ const currentChildren = (targetParent.children || []).filter((child) => child.loadMore?.objectType !== "INDEX" && !(replacedWindow && child.type === "index" && child.objectScope === "schema"));+ const mergedChildren = mergeLocatedTreeChildren(targetParent, currentChildren, page.children, parentConnectionId, parent.database);+ setChildren(targetParent, page.hasMore ? [...mergedChildren, buildLoadMoreNode(targetParent, page.nextOffset, loadMore.pageSize, page.nextAnchor, loadMore.searchFilter, "INDEX")] : mergedChildren);+ targetParent.objectCount = mergedChildren.filter((child) => child.type !== "load-more").length;+ return;+ }if (parent.type === "database" || parent.type === "schema" || parent.type === "linked-server-schema") {const parentDatabase = parent.database;if (!hasTreeNodeDatabaseContext(parent)) return;@@ -7467,7 +7590,7 @@ export const useConnectionStore = defineStore("connection", () => {nextChildren = page.hasMore ? [...mergedChildren, buildLoadMoreNode(targetParent, page.nextOffset, loadMore.pageSize, page.nextAnchor, loadMore.searchFilter)] : mergedChildren;targetParent.objectCount = mergedChildren.length;setChildren(targetParent, nextChildren);- if (!searchFilter) {+ if (!isSchemaIndexGroup(targetParent) && !searchFilter) {await savePersistedTreeChildren(objectGroupCacheKey(targetParent), nextChildren);// procedures/triggers 等对象组在此分支提前 return,回收必须在 return 前;// 非分组容器由 prune 内部的类别防护挡下。@@ -8518,7 +8641,7 @@ export const useConnectionStore = defineStore("connection", () => {await loadDatabases(connectionId, { force: true });}- async function refreshObjectListTreeNode(connectionId: string, database: string, schema?: string, catalog?: string) {+ async function refreshObjectListTreeNode(connectionId: string, database: string, schema?: string, catalog?: string, schemaOnly = false) {const match = { connectionId, database, schema };invalidateMetadataCaches(match);void invalidateObjectDdlCache(match);@@ -8526,7 +8649,7 @@ export const useConnectionStore = defineStore("connection", () => {const node = shouldRefreshSchemaNode ? findNode(treeNodes.value, `${connectionId}:${database}:${schema}`) : null;if (node) {await refreshTreeNode(node);- } else {+ } else if (!schemaOnly) {await refreshDatabaseTreeNode(connectionId, database, catalog);}void loadSidebarTableStorage({ connectionId, database, schema: schema || "" }, { force: true });@@ -10092,7 +10215,12 @@ export const useConnectionStore = defineStore("connection", () => {}async function persistConnections(nextConnections: ConnectionConfig[] = connections.value, removedIds: string[] = []) {- const configs = nextConnections.filter((connection) => connection.one_time !== true);+ const configs = nextConnections+ .filter((connection) => connection.one_time !== true)+ .map((connection) => {+ const { jdbc_dialect: _jdbcDialect, ...persistedConfig } = connection;+ return persistedConfig;+ });if (removedIds.length) {await api.saveConnections(configs, removedIds);return;@@ -10890,13 +11018,21 @@ export const useConnectionStore = defineStore("connection", () => {await settingsStore.initEditorSettings();if (!initFromDiskPromise) {initFromDiskPromise = (async () => {+ const startingConfigFingerprints = new Map(connections.value.map((connection) => [connection.id, connectionConfigFingerprint(connection)]));// 整体覆盖内存布局前,先落盘窗口内未写盘的分组编辑(防止 300ms 防抖窗口// 内的编辑被备份轮询/重载带回的旧快照静默回滚)。await flushTableVGroupPersist();const [pinnedOrder, saved, , loadedTableVGroups] = await Promise.all([loadPinnedTreeNodeOrder(), api.loadConnections(), tunnelProfileStore.init(), api.loadTableVGroups()]);setPinnedTreeNodeOrder(pinnedOrder);await migrateTimeoutInheritance(saved);- const loadedConnections = saved.map(normalizeConnection);+ const loadedConnections = saved.map(normalizeConnection).map((loadedConfig) => {+ const currentConfig = connections.value.find((connection) => connection.id === loadedConfig.id);+ const startingFingerprint = startingConfigFingerprints.get(loadedConfig.id);+ if (currentConfig && (startingFingerprint === undefined || connectionConfigFingerprint(currentConfig) !== startingFingerprint)) {+ return currentConfig;+ }+ return loadedConfig;+ });const loadedIds = new Set(loadedConnections.map((connection) => connection.id));// One-time deep-link connections are intentionally filtered from disk// persistence. Keep them in the live list when an unrelated disk reloaddiff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 4fad82b27c..e2bdf458dd 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -1642,13 +1642,14 @@ export const useQueryStore = defineStore("query", () => {let resultCacheTrimRequested = false;let detachedHandoffRevision = 0;- function tableStructureKey(connectionId: string, database: string, schema: string | undefined, tableName: string): string {+ function tableStructureKey(connectionId: string, database: string, schema: string | undefined, tableName: string, exactIdentity = false, catalog?: string): string {+ if (exactIdentity) return JSON.stringify(["exact-v1", connectionId, database, schema ?? "", tableName, catalog ?? ""]);return [connectionId, database, schema || "", tableName].map((part) => part.toLowerCase()).join("\u0000");}- function invalidateTableStructure(connectionId: string, database: string, schema: string | undefined, tableName: string) {+ function invalidateTableStructure(connectionId: string, database: string, schema: string | undefined, tableName: string, exactIdentity = false, catalog?: string) {if (!tableName) return;- const key = tableStructureKey(connectionId, database, schema, tableName);+ const key = tableStructureKey(connectionId, database, schema, tableName, exactIdentity, catalog);tableStructureRefreshVersions.value = {...tableStructureRefreshVersions.value,[key]: (tableStructureRefreshVersions.value[key] ?? 0) + 1,@@ -1659,8 +1660,8 @@ export const useQueryStore = defineStore("query", () => {}}- function tableStructureRefreshVersion(connectionId: string, database: string, schema: string | undefined, tableName: string): number {- return tableStructureRefreshVersions.value[tableStructureKey(connectionId, database, schema, tableName)] ?? 0;+ function tableStructureRefreshVersion(connectionId: string, database: string, schema: string | undefined, tableName: string, exactIdentity = false, catalog?: string): number {+ return tableStructureRefreshVersions.value[tableStructureKey(connectionId, database, schema, tableName, exactIdentity, catalog)] ?? 0;}const MAX_CACHED_RESULTS = 5;const MAX_CACHED_RESULT_BYTES = 128 * 1024 * 1024;@@ -2857,6 +2858,7 @@ export const useQueryStore = defineStore("query", () => {resultAutoSave: t.resultAutoSave,uiState: t.uiState,structureTableName: t.structureTableName,+ structureExactIdentity: t.structureExactIdentity,structureTableType: t.structureTableType,structureDraft: t.structureDraft,objectBrowser: t.objectBrowser,@@ -3558,7 +3560,17 @@ export const useQueryStore = defineStore("query", () => {return id;}- function openObjectBrowser(connectionId: string, database: string, schema?: string, catalog?: string, eventName?: string, eventReadOnly = false, initialObjectFilter?: "tables" | "events", eventCreateRequestId?: number) {+ function openObjectBrowser(+ connectionId: string,+ database: string,+ schema?: string,+ catalog?: string,+ eventName?: string,+ eventReadOnly = false,+ initialObjectFilter?: "tables" | "events" | "indexes",+ eventCreateRequestId?: number,+ indexRequest?: { create?: boolean; view?: import("@/types/database").SchemaIndexIdentity },+ ) {const title = catalog ? `${catalog}.${database} objects` : schema ? `${schema} objects` : `${database} objects`;const existing = tabs.value.find((tab) => tab.mode === "objects" && tab.connectionId === connectionId && tab.database === database && (tab.objectBrowser?.catalog || "") === (catalog || "") && (tab.objectBrowser?.schema || "") === (schema || ""));if (existing) {@@ -3583,6 +3595,17 @@ export const useQueryStore = defineStore("query", () => {eventOpenRequestId: (existing.objectBrowser?.eventOpenRequestId ?? 0) + 1,};}+ if (initialObjectFilter === "indexes" || indexRequest) {+ const requestId = Math.max(existing.objectBrowser?.indexRequestSequence ?? 0, existing.objectBrowser?.indexCreateRequestId ?? 0, existing.objectBrowser?.initialViewRequestId ?? 0) + 1;+ existing.objectBrowser = {+ ...existing.objectBrowser,+ initialObjectFilter: "indexes",+ filter: "indexes",+ ...(indexRequest?.create || indexRequest?.view ? { indexRequestSequence: requestId } : {}),+ ...(indexRequest?.create ? { indexCreateRequestId: requestId, initialViewTarget: undefined, initialViewRequestId: undefined } : {}),+ ...(indexRequest?.view ? { initialViewTarget: indexRequest.view, initialViewRequestId: requestId, indexCreateRequestId: undefined } : {}),+ };+ }switchTab(existing.id);return existing.id;}@@ -3608,6 +3631,9 @@ export const useQueryStore = defineStore("query", () => {initialObjectFilter: initialObjectFilter ?? (eventName || eventCreateRequestId !== undefined ? "events" : undefined),eventOpenRequestId: eventName ? 1 : undefined,eventCreateRequestId,+ ...(indexRequest?.create || indexRequest?.view ? { indexRequestSequence: 1 } : {}),+ ...(indexRequest?.create ? { indexCreateRequestId: 1 } : {}),+ ...(indexRequest?.view ? { initialViewTarget: indexRequest.view, initialViewRequestId: 1 } : {}),},};return registerOpenTab(tab);@@ -4377,16 +4403,20 @@ export const useQueryStore = defineStore("query", () => {}function applyTableStructureInitialTab(tab: QueryTab, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget) {- if (!initialTab && !initialTarget?.name) return;+ const hasTarget = !!initialTarget?.name || initialTarget?.action === "create";+ if (!initialTab && !hasTarget) return;if (initialTab) tab.structureInitialTab = initialTab;- tab.structureInitialTarget = initialTarget?.name ? initialTarget : undefined;+ tab.structureInitialTarget = hasTarget ? initialTarget : undefined;tab.structureInitialTabRequestId = (tab.structureInitialTabRequestId ?? 0) + 1;}- function openTableStructure(connectionId: string, database: string, schema?: string, tableName?: string, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget, catalog?: string, tableType?: "table" | "view") {+ function openTableStructure(connectionId: string, database: string, schema?: string, tableName?: string, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget, catalog?: string, tableType?: "table" | "view", exactIdentity = false) {const resolvedTableName = tableName || "";if (resolvedTableName) {- const existing = tabs.value.find((tab) => tab.mode === "structure" && tab.connectionId === connectionId && tab.database === database && (tab.catalog || "") === (catalog || "") && (tab.schema || "") === (schema || "") && (tab.structureTableName || "") === resolvedTableName);+ const existing = tabs.value.find(+ (tab) =>+ tab.mode === "structure" && tab.connectionId === connectionId && tab.database === database && (tab.catalog || "") === (catalog || "") && (tab.schema || "") === (schema || "") && (tab.structureTableName || "") === resolvedTableName && (tab.structureExactIdentity === true) === exactIdentity,+ );if (existing) {applyTableStructureInitialTab(existing, initialTab, initialTarget);switchTab(existing.id);@@ -4409,10 +4439,11 @@ export const useQueryStore = defineStore("query", () => {isExplaining: false,mode: "structure",structureTableName: resolvedTableName,+ ...(exactIdentity ? { structureExactIdentity: true } : {}),structureTableType: tableType,structureInitialTab: initialTab,- structureInitialTabRequestId: initialTab || initialTarget?.name ? 1 : undefined,- structureInitialTarget: initialTarget?.name ? initialTarget : undefined,+ structureInitialTabRequestId: initialTab || initialTarget?.name || initialTarget?.action === "create" ? 1 : undefined,+ structureInitialTarget: initialTarget?.name || initialTarget?.action === "create" ? initialTarget : undefined,};return registerOpenTab(tab);}@@ -5211,6 +5242,7 @@ export const useQueryStore = defineStore("query", () => {nacosNamespace: original.nacosNamespace,nacosNamespaceName: original.nacosNamespaceName,structureTableName: original.structureTableName,+ structureExactIdentity: original.structureExactIdentity,structureTableType: original.structureTableType,structureDraft: original.structureDraft ? cloneTabDraft(original.structureDraft) : undefined,objectBrowser: original.objectBrowser ? { ...original.objectBrowser } : undefined,diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 195ce4711f..9b3d3ec4d0 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -139,6 +139,8 @@ export interface CompletionAssistantResponse {export interface ConnectionConfig {id: string;name: string;+ /** Read-only response identity retained when a saved JDBC URL is protected. */+ readonly jdbc_dialect?: "oceanbase-oracle";note?: string;db_type: DatabaseType;driver_profile?: string;@@ -1256,6 +1258,8 @@ export interface SqlServerColumnMetadata extends ColumnInfo {}export interface IndexInfo {+ /** Dictionary-derived index owner; absent in older or non-owner metadata. */+ owner?: string | null;name: string;columns: string[];is_unique: boolean;@@ -1911,6 +1915,8 @@ export interface TreeNode {schema?: string;tableName?: string;objectName?: string;+ /** Distinguishes schema indexes from the existing table-child index actions. */+ objectScope?: "schema";signature?: string;customTypeKind?: CustomTypeKind;hasMembers?: boolean;@@ -1947,6 +1953,7 @@ export interface TreeNode {meta?: ColumnInfo | IndexInfo | ForeignKeyInfo | TriggerInfo | ConstraintInfo | PartitionInfo | SubpartitionInfo | ExtensionInfo | EventTriggerInfo | VectorCollectionMeta | MongoCollectionMeta | CustomTypeTreeMemberMeta;loadMore?: {parentId: string;+ objectType?: "INDEX";offset: number;pageSize: number;/** Backend filter and global-search identity for OceanBase metadata pages. */@@ -2015,6 +2022,17 @@ export interface PgTablePartitioning {export interface TableStructureEditorTarget {kind: "column" | "index";name: string;+ /** Raw schema-index owner; omitted by legacy table-child navigation. */+ owner?: string;+ /** Schema-index requests are consumed once by the existing draft editor. */+ action?: "create" | "delete";+}++export interface SchemaIndexIdentity {+ schema: string;+ name: string;+ parentSchema: string;+ parentName: string;}export interface TableStructureEditorDraft {@@ -2071,6 +2089,12 @@ export interface TableStructureEditorDraft {scrollPositions?: Partial<Record<TableInfoTab, TableStructureEditorViewport>>;/** Request id of the structureInitialTab the editor already applied; remounts must not replay a consumed initial tab over the restored draft. */appliedInitialTabRequestId?: number;+ appliedInitialTargetRequestId?: number;+ oracleIndexRecovery?: {+ target: string;+ completedCreates: import("@/lib/database/oracleIndexes").OracleIndexDefinition[];+ refreshError?: string;+ };initialized: boolean;}@@ -2081,7 +2105,7 @@ export interface TableStructureEditorViewport {export type ObjectBrowserViewMode = "list" | "grid" | "compact";-export type ObjectBrowserFilter = "all" | "tables" | "views" | "materializedViews" | "procedures" | "functions" | "triggers" | "events" | "sequences" | "packages" | "types";+export type ObjectBrowserFilter = "all" | "tables" | "views" | "materializedViews" | "procedures" | "functions" | "triggers" | "events" | "sequences" | "indexes" | "packages" | "types";export interface ObjectBrowserViewport {scrollTop: number;@@ -2393,6 +2417,7 @@ export interface QueryTab {nacosTargetRequestId?: number;nacosConfigEditorViewport?: NacosConfigEditorViewport;structureTableName?: string;+ structureExactIdentity?: boolean;/** Navigation type of the opened structure object; views matter for "view data" routing. */structureTableType?: "table" | "view";structureInitialTab?: TableInfoTab;@@ -2409,7 +2434,11 @@ export interface QueryTab {eventOpenRequestId?: number;/** 显式的"新建事件"请求:单调递增,用于让已复用 tab 也能重复进入 CREATE 编辑器 */eventCreateRequestId?: number;- initialObjectFilter?: "tables" | "events";+ initialObjectFilter?: "tables" | "events" | "indexes";+ indexRequestSequence?: number;+ indexCreateRequestId?: number;+ initialViewTarget?: SchemaIndexIdentity;+ initialViewRequestId?: number;filter?: ObjectBrowserFilter;searchQuery?: string;viewport?: ObjectBrowserViewport;diff --git a/crates/dbx-core/assets/agent-protocol-v1.json b/crates/dbx-core/assets/agent-protocol-v1.jsonindex af91085bbf..c7713e1aa7 100644--- a/crates/dbx-core/assets/agent-protocol-v1.json+++ b/crates/dbx-core/assets/agent-protocol-v1.json@@ -2,7 +2,7 @@"protocolVersion": 1,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl"],"commonMethods": [diff --git a/crates/dbx-core/src/data/docs/dbml.rs b/crates/dbx-core/src/data/docs/dbml.rsindex 8a3d18ed55..d369008602 100644--- a/crates/dbx-core/src/data/docs/dbml.rs+++ b/crates/dbx-core/src/data/docs/dbml.rs@@ -591,6 +591,7 @@ mod tests {#[test]fn renders_an_indexes_block() {let index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -620,6 +621,7 @@ mod tests {#[test]fn a_unique_index_carries_the_unique_setting() {let index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -645,6 +647,7 @@ mod tests {#[test]fn the_primary_key_index_is_skipped_because_columns_already_carry_pk() {let index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -673,6 +676,7 @@ mod tests {#[test]fn a_filtered_index_is_omitted_and_warned_about() {let index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -881,6 +885,7 @@ mod tests {#[test]fn warnings_from_table_rendering_reach_the_output() {let index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-core/src/data/docs/relations.rs b/crates/dbx-core/src/data/docs/relations.rsindex 8244424c5b..5ee1296acc 100644--- a/crates/dbx-core/src/data/docs/relations.rs+++ b/crates/dbx-core/src/data/docs/relations.rs@@ -185,6 +185,7 @@ mod tests {fn unique_index(name: &str, columns: &[&str]) -> IndexInfo {IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rsindex 90f453c77d..485c86ab33 100644--- a/crates/dbx-core/src/data/transfer.rs+++ b/crates/dbx-core/src/data/transfer.rs@@ -20682,6 +20682,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_generates_index_and_foreign_key_sql() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20740,6 +20741,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_index_ddl_includes_opclass_for_gin_trigram() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20771,6 +20773,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";// (`syntax error at or near "NOT"`), so the transfer must fall back to the// plain form there (issue #8853).let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20809,6 +20812,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_index_ddl_no_opclass_when_all_default() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20843,6 +20847,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";// `indclass` into `column_opclasses`, so transfer DDL must append it to an// expression key just like a real column.let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20872,6 +20877,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_index_ddl_mixed_opclass_and_default() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20900,6 +20906,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_index_ddl_preserves_per_key_ordering_and_include_columns() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20933,6 +20940,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_index_ddl_ignores_access_method_options_for_non_btree_indexes() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -20962,6 +20970,7 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";#[test]fn postgres_index_ddl_empty_column_opclasses_vec_falls_back_to_no_opclass() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-core/src/data/transfer/structure_plan.rs b/crates/dbx-core/src/data/transfer/structure_plan.rsindex 07f71f665a..e6338d9f83 100644--- a/crates/dbx-core/src/data/transfer/structure_plan.rs+++ b/crates/dbx-core/src/data/transfer/structure_plan.rs@@ -658,6 +658,7 @@ mod tests {#[test]fn structured_ddl_metadata_produces_operation_dtos() {let index = db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-core/src/schema/agent_metadata_fixture.py b/crates/dbx-core/src/schema/agent_metadata_fixture.pyindex 6a0beff33a..34945717a8 100644--- a/crates/dbx-core/src/schema/agent_metadata_fixture.py+++ b/crates/dbx-core/src/schema/agent_metadata_fixture.py@@ -52,6 +52,17 @@ def handle(request):error = rpc_error(category)else:result = [{'name': sessions[session].get('sessionRole', 'workload')}]+ elif method == 'list_objects':+ failure = root / 'objects-error'+ if failure.exists():+ error = rpc_error(failure.read_text())+ else:+ objects = [{'name': 'Ix%d' % i, 'schema': params['schema'], 'object_type': 'INDEX',+ 'parent_schema': ' Other Owner ', 'parent_name': ' T(a) '} for i in range(5)]+ if params.get('filter'):+ objects = [obj for obj in objects if params['filter'].lower() in obj['name'].lower()]+ start = params.get('offset') or 0+ result = objects[start:][:params.get('limit') or len(objects)]elif method in ('execute_query', 'get_table_ddl'):with session_locks[session]:if method == 'get_table_ddl':diff --git a/crates/dbx-core/src/schema/agent_metadata_routing_tests.rs b/crates/dbx-core/src/schema/agent_metadata_routing_tests.rsindex d7fc79a91c..b03ad31e16 100644--- a/crates/dbx-core/src/schema/agent_metadata_routing_tests.rs+++ b/crates/dbx-core/src/schema/agent_metadata_routing_tests.rs@@ -1,6 +1,6 @@use super::{- get_table_comment_core, get_table_ddl_core, list_databases_core, list_object_statistics_core, AppState,- ConnectionConfig, DatabaseType, PoolKind,+ get_table_comment_core, get_table_ddl_core, list_databases_core, list_object_statistics_core, list_objects_core,+ AppState, ConnectionConfig, DatabaseType, PoolKind,};use crate::db::agent_driver::{AgentDriverClient, PooledAgentClient};use serde_json::{json, Value};@@ -103,6 +103,45 @@ impl AgentFixture {}}+#[tokio::test]+async fn oracle_public_object_entry_applies_index_filter_and_offset_once() {+ let fixture = AgentFixture::new(DatabaseType::Oracle).await;+ let types = vec!["INDEX".to_string()];+ let page =+ list_objects_core(&fixture.state, "conn", "configured", " Mixed ", None, Some(2), Some(2), Some(&types), None)+ .await+ .unwrap();+ assert_eq!(page.iter().map(|object| object.name.as_str()).collect::<Vec<_>>(), ["Ix2", "Ix3"]);+ assert_eq!(page[0].parent_schema.as_deref(), Some(" Other Owner "));+ assert_eq!(page[0].parent_name.as_deref(), Some(" T(a) "));+ let filtered = list_objects_core(+ &fixture.state,+ "conn",+ "configured",+ " Mixed ",+ Some("Ix4"),+ Some(2),+ Some(0),+ Some(&types),+ None,+ )+ .await+ .unwrap();+ assert_eq!(filtered.iter().map(|object| object.name.as_str()).collect::<Vec<_>>(), ["Ix4"]);+ let calls = fixture.requests("list_objects");+ assert_eq!(calls.len(), 2);+ assert_eq!(calls[0]["params"]["offset"], 2);+ assert_eq!(calls[1]["params"]["filter"], "Ix4");+ assert_eq!(calls[1]["params"]["limit"], 2);+ std::fs::write(fixture.control_path("objects-error"), "sql").unwrap();+ let error =+ list_objects_core(&fixture.state, "conn", "configured", " Mixed ", None, Some(2), Some(0), Some(&types), None)+ .await+ .unwrap_err();+ assert!(error.contains("fixture sql"));+ fixture.shutdown().await;+}+#[tokio::test]async fn enumeration_creates_metadata_pool_when_only_workload_exists() {let fixture = AgentFixture::new(DatabaseType::Hive).await;diff --git a/crates/dbx-core/src/schema/exact_metadata.rs b/crates/dbx-core/src/schema/exact_metadata.rsnew file mode 100644index 0000000000..392f1ee6aa--- /dev/null+++ b/crates/dbx-core/src/schema/exact_metadata.rs@@ -0,0 +1,619 @@+//! Dictionary-derived identities used by the schema-index entry. Legacy callers+//! retain the ordinary metadata resolution and synonym behavior in schema/mod.rs.++use super::*;+use crate::db::agent_driver::{agent_schema_params, agent_schema_table_params, AgentCapability, AgentMethod};+use serde::de::DeserializeOwned;+use serde_json::{json, Value};++const UNSUPPORTED: &str = "Cannot verify exact_metadata_identity_v1. Update the Agent or JDBC plugin and reconnect.";++fn jdbc_supports_exact_identity(protocol: &Value) -> bool {+ protocol["version"] == 2+ && protocol["capabilities"].as_array().is_some_and(|values| {+ values.iter().any(|value| value.as_str() == Some(AgentCapability::ExactMetadataIdentityV1.as_str()))+ })+}++fn supports_family(config: &ConnectionConfig) -> bool {+ matches!(config.db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng)+ || (config.db_type == DatabaseType::Jdbc+ && config.connection_string.as_deref().is_some_and(|url| {+ let url = url.trim().to_ascii_lowercase();+ url.starts_with("jdbc:oracle:")+ || url.starts_with("jdbc:dm:")+ || url.starts_with("jdbc:oceanbase:oracle://")+ }))+}++fn external_method(method: AgentMethod) -> Option<&'static str> {+ match method {+ AgentMethod::ListTables => Some("listTables"),+ AgentMethod::ListObjects => Some("listObjects"),+ AgentMethod::GetColumns => Some("getColumns"),+ AgentMethod::ListIndexes => Some("listIndexes"),+ AgentMethod::GetTableDdl => Some("getObjectSource"),+ AgentMethod::ExecuteQuery => Some("executeQuery"),+ _ => None,+ }+}++async fn request<T: DeserializeOwned + Send + 'static>(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ client_session_id: Option<&str>,+ method: AgentMethod,+ params: Value,+) -> Result<T, String> {+ if schema.trim().is_empty() {+ return Err("An explicit schema is required for exact metadata identity".into());+ }+ let ephemeral = if client_session_id.is_none() {+ Some(EphemeralAgentMetadataSession::open(state, connection_id, Some(database), "exact-metadata").await)+ } else {+ None+ };+ let session_id = client_session_id.or_else(|| ephemeral.as_ref().and_then(|session| session.client_session_id()));+ let result = retry_metadata_connection_for_session(state, connection_id, Some(database), session_id, || async {+ let pool_key = state.get_or_create_metadata_pool_for_session(connection_id, Some(database), session_id).await?;+ let config = connection_config(state, connection_id).await;+ let timeout = agent_metadata_timeout(config.as_ref());+ let pool = state.pool_handle(&pool_key).await.ok_or("Pool not found")?;+ // A query generated here has raw owner/name predicates; it does not ask+ // an old metadata method to interpret an option it might silently ignore.+ let dictionary_sql = method == AgentMethod::ExecuteQuery;+ match pool {+ PoolKind::Agent(client) => {+ if !config.as_ref().is_some_and(supports_family) {+ return Ok(Err(UNSUPPORTED.into()));+ }+ if method == AgentMethod::ListObjects+ && config.as_ref().is_some_and(|config| {+ config.db_type == DatabaseType::Oracle && !is_default_oracle_agent_config(config)+ })+ {+ // This retained path executes Core-owned raw dictionary SQL;+ // no legacy metadata method is asked to interpret a new flag.+ let types: Option<Vec<String>> =+ serde_json::from_value(params["object_types"].clone()).map_err(|error| error.to_string())?;+ let outcome = oracle_agent_list_objects(+ client,+ database,+ schema,+ params["filter"].as_str(),+ params["limit"].as_u64().map(|value| value as usize),+ params["offset"].as_u64().map(|value| value as usize),+ types.as_deref(),+ true,+ timeout,+ )+ .await?;+ return serde_json::to_value(outcome.objects)+ .and_then(serde_json::from_value::<T>)+ .map(Ok)+ .map_err(|error| error.to_string());+ }+ let mut client = client.lock().await;+ if !dictionary_sql && !client.supports_capability(AgentCapability::ExactMetadataIdentityV1) {+ return Ok(Err(UNSUPPORTED.into()));+ }+ let mut params = params.clone();+ if !dictionary_sql {+ params["exact_identity"] = json!(true);+ }+ client.call_method_with_timeout::<T>(method, params, timeout).await.map(Ok)+ }+ PoolKind::ExternalDriver { config, session, .. } => {+ if !supports_family(&config) {+ return Ok(Err(UNSUPPORTED.into()));+ }+ let Some(plugin_method) = external_method(method) else {+ return Ok(Err("This JDBC metadata facet is not supported".into()));+ };+ if method == AgentMethod::GetTableDdl && params["portable"] == true {+ return Ok(Err("Portable exact DDL is not available from this JDBC metadata method".into()));+ }+ if !dictionary_sql {+ let protocol =+ match session.invoke_with_timeout::<Value>("jdbcSessionProtocol", json!({}), timeout).await {+ Ok(protocol) => protocol,+ Err(error) => return Ok(Err(format!("{UNSUPPORTED} {error}"))),+ };+ if !jdbc_supports_exact_identity(&protocol) {+ return Ok(Err(UNSUPPORTED.into()));+ }+ }+ let mut params = params.clone();+ params["connection"] = serde_json::to_value(config.as_ref()).map_err(|error| error.to_string())?;+ if !dictionary_sql {+ params["exact_identity"] = json!(true);+ }+ session.invoke_with_timeout::<T>(plugin_method, params, timeout).await.map(Ok)+ }+ _ => Ok(Err(UNSUPPORTED.into())),+ }+ })+ .await;+ if let Some(ephemeral) = ephemeral {+ ephemeral.finish(state, connection_id, Some(database)).await;+ }+ // Local contract refusal is not an Agent failure and must not quarantine+ // the legacy session. Only errors from an actual RPC enter recovery above.+ result.and_then(|result| result)+}++#[allow(clippy::too_many_arguments)]+pub async fn objects(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ object_types: Option<&[String]>,+ table_name_filter: Option<&TableNameFilter>,+) -> Result<Vec<db::ObjectInfo>, String> {+ validate_oceanbase_metadata_page(limit, offset)?;+ let mut params = agent_schema_params(database, schema);+ params["filter"] = json!(filter);+ let local_patterns = table_name_filter.is_some_and(|filter| !filter.is_empty());+ if !local_patterns {+ params["limit"] = json!(limit);+ params["offset"] = json!(offset);+ }+ params["object_types"] = json!(object_types);+ let objects = request(state, connection_id, database, schema, None, AgentMethod::ListObjects, params).await?;+ // The opted-in adapters own paging. Never apply their offset a second time.+ Ok(filter_object_infos(+ objects,+ filter,+ limit,+ if local_patterns { offset } else { Some(0) },+ object_types,+ table_name_filter,+ ))+}++#[allow(clippy::too_many_arguments)]+pub async fn tables(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ object_types: Option<&[String]>,+ table_name_filter: Option<&TableNameFilter>,+) -> Result<Vec<db::TableInfo>, String> {+ validate_oceanbase_metadata_page(limit, offset)?;+ let mut params = agent_schema_params(database, schema);+ params["filter"] = json!(filter);+ let local_patterns = table_name_filter.is_some_and(|filter| !filter.is_empty());+ if !local_patterns {+ params["limit"] = json!(limit);+ params["offset"] = json!(offset);+ }+ params["object_types"] = json!(object_types);+ let tables = request(state, connection_id, database, schema, None, AgentMethod::ListTables, params).await?;+ Ok(filter_table_infos(+ tables,+ filter,+ limit,+ if local_patterns { offset } else { Some(0) },+ object_types,+ table_name_filter,+ ))+}++pub async fn columns(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+ client_session_id: Option<&str>,+) -> Result<Vec<db::ColumnInfo>, String> {+ request(+ state,+ connection_id,+ database,+ schema,+ client_session_id,+ AgentMethod::GetColumns,+ agent_schema_table_params(database, schema, table),+ )+ .await+}++pub async fn indexes(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+) -> Result<Vec<db::IndexInfo>, String> {+ request(+ state,+ connection_id,+ database,+ schema,+ None,+ AgentMethod::ListIndexes,+ agent_schema_table_params(database, schema, table),+ )+ .await+}++pub async fn foreign_keys(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+) -> Result<Vec<db::ForeignKeyInfo>, String> {+ request(+ state,+ connection_id,+ database,+ schema,+ None,+ AgentMethod::ListForeignKeys,+ agent_schema_table_params(database, schema, table),+ )+ .await+}++pub async fn constraints(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+) -> Result<Vec<db::ConstraintInfo>, String> {+ request(+ state,+ connection_id,+ database,+ schema,+ None,+ AgentMethod::ListConstraints,+ agent_schema_table_params(database, schema, table),+ )+ .await+}++pub async fn triggers(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+) -> Result<Vec<db::TriggerInfo>, String> {+ request(+ state,+ connection_id,+ database,+ schema,+ None,+ AgentMethod::ListTriggers,+ agent_schema_table_params(database, schema, table),+ )+ .await+}++pub async fn comment(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+) -> Result<Option<String>, String> {+ let sql = oracle_table_comment_sql(schema, table);+ let params = agent_execute_query_params(+ &sql,+ Some(database),+ None,+ QueryExecutionOptions { max_rows: Some(1), ..Default::default() },+ );+ let result = request(state, connection_id, database, schema, None, AgentMethod::ExecuteQuery, params).await?;+ single_table_comment_from_query_result(result)+}++pub async fn ddl(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+ object_type: Option<db::ObjectSourceKind>,+ portable: bool,+) -> Result<String, String> {+ let mut params = agent_schema_table_params(database, schema, table);+ params["name"] = json!(table);+ params["object_type"] = object_type.map_or_else(|| json!("TABLE"), |kind| json!(kind));+ params["portable"] = json!(portable);+ let result: Value = request(state, connection_id, database, schema, None, AgentMethod::GetTableDdl, params).await?;+ result+ .as_str()+ .or_else(|| result.get("source").and_then(Value::as_str))+ .map(str::to_owned)+ .filter(|source| !source.is_empty())+ .ok_or("Exact table DDL is unavailable".into())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::db::agent_driver::{AgentDriverClient, AgentLaunchSpec};++ #[test]+ fn a_jdbc_version_number_alone_cannot_grant_exact_identity() {+ assert!(!jdbc_supports_exact_identity(&json!({"version":2})));+ assert!(!jdbc_supports_exact_identity(&json!({"version":2,"capabilities":["metadata"]})));+ assert!(!jdbc_supports_exact_identity(&json!({"version":1,"capabilities":["exact_metadata_identity_v1"]})));+ assert!(jdbc_supports_exact_identity(&json!({"version":2,"capabilities":["exact_metadata_identity_v1"]})));+ }++ async fn agent_fixture(mode: &str) -> (tempfile::TempDir, AppState, String) {+ let directory = tempfile::tempdir().unwrap();+ let script = directory.path().join("agent.py");+ std::fs::write(&script, r#"import json, pathlib, re, sys+mode, log = sys.argv[1], pathlib.Path(sys.argv[2])+print(json.dumps({'ready': True}), flush=True)+for line in sys.stdin:+ request = json.loads(line)+ method, params = request['method'], request.get('params', {})+ with log.open('a') as output:+ output.write(json.dumps(request) + '\n')+ body = {'result': {}}+ if method == 'handshake':+ if mode == 'missing':+ body = {'error': {'code': -32601, 'message': 'Method not found'}}+ else:+ capabilities = ['metadata']+ if mode in ('v1-exact', 'v2-exact'): capabilities.append('exact_metadata_identity_v1')+ version = 2 if mode == 'v2-exact' else 1+ body = {'result': {'protocolVersion': version, 'agentProtocolVersion': version, 'capabilities': capabilities}}+ elif method in ('list_objects', 'list_tables'):+ if mode == 'default-paged':+ rows = [{'name': 'I%d' % i, 'object_type': 'INDEX', 'schema': 'APP', 'parent_schema': 'APP', 'parent_name': 'T'} for i in range(5)]+ start = params.get('offset') or 0+ rows = rows[start:][:params.get('limit') or len(rows)]+ print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'result': rows}), flush=True)+ continue+ # An old provider accepts unknown options and returns a nearby object.+ exact = params.get('exact_identity', False) and mode.endswith('exact')+ body = {'result': [{'name': ' Ix(a) ' if exact else 'IX(A)', 'object_type': 'INDEX',+ 'schema': params['schema'] if exact else params['schema'].strip().upper(),+ 'parent_schema': ' Other Owner ', 'parent_name': ' T(a) '}]}+ elif method == 'get_columns':+ exact = params.get('exact_identity', False) and mode.endswith('exact')+ body = {'result': [{'name': 'Id' if exact else 'ID', 'data_type': 'NUMBER', 'is_nullable': False,+ 'is_primary_key': True}]}+ elif method == 'execute_query':+ if mode == 'legacy-error':+ body = {'error': {'code': -32000, 'message': 'ORA-01031: insufficient privileges'}}+ else:+ sql = params.get('sql', '')+ rows = [] if mode == 'legacy-empty' or "'INDEX'" not in sql else [['I_noise_%05d' % i, 'INDEX', ' Mixed ', ' Other Owner ', ' T(a) '] for i in range(10001)] + [[name, 'INDEX', ' Mixed ', ' Other Owner ', ' T(a) '] for name in [' needle(a) ', 'needle(A)', 'needle_A_2']]+ upper = re.search(r'ROWNUM <= (\d+)', sql)+ lower = re.search(r'dbx_row_number > (\d+)', sql)+ pattern = re.search(r"LOWER\(object_name\) LIKE '([^']*)'", sql)+ if pattern:+ expression = ''.join('.*' if ch == '%' else '.' if ch == '_' else re.escape(ch) for ch in pattern.group(1))+ rows = [row for row in rows if re.fullmatch(expression, row[0].lower())]+ rows = rows[int(lower.group(1)) if lower else 0:int(upper.group(1)) if upper else len(rows)]+ rows = rows[:params.get('maxRows', 10000)]+ body = {'result': {'columns': [], 'rows': rows, 'affected_rows': 0, 'execution_time_ms': 0}}+ print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], **body}), flush=True)+"#).unwrap();+ let python = if cfg!(windows) { "python" } else { "python3" };+ let mut client = AgentDriverClient::spawn(AgentLaunchSpec::new(python).with_args([+ script.to_string_lossy().to_string(),+ mode.into(),+ directory.path().join("calls").to_string_lossy().to_string(),+ ]))+ .await+ .unwrap();+ client.try_optional_handshake("test").await;+ let storage = crate::persistence::test_storage::open(&directory.path().join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ let config: ConnectionConfig = serde_json::from_value(json!({+ "id":"conn", "name":"Exact metadata test", "db_type":"oracle", "driver_profile": if mode.starts_with("legacy-") { "oracle-legacy" } else { "oracle" },+ "host":"127.0.0.1", "port":1521, "database":"demo", "username":"fixture", "password":"",+ "keepalive_interval_secs":0, "idle_timeout_secs":0,+ })).unwrap();+ state.configs.write().await.insert("conn".into(), config);+ let key =+ format!("{}:role:metadata", state.session_pool_key_for_test("conn", Some("demo"), "exact-test").await);+ state.update_connection_pools(|pools| pools.insert(key.clone(), PoolKind::agent(client))).await;+ (directory, state, key)+ }++ fn requests(directory: &std::path::Path, method: &str) -> Vec<Value> {+ std::fs::read_to_string(directory.join("calls"))+ .unwrap()+ .lines()+ .map(|line| serde_json::from_str::<Value>(line).unwrap())+ .filter(|request| request["method"] == method)+ .collect()+ }++ #[tokio::test]+ async fn old_process_cannot_supply_exact_list_picker_or_baseline_but_legacy_reads_remain_usable() {+ for mode in ["missing", "metadata"] {+ let (directory, state, key) = agent_fixture(mode).await;+ for method in [AgentMethod::ListObjects, AgentMethod::ListTables, AgentMethod::GetColumns] {+ let error = request::<Value>(+ &state,+ "conn",+ "demo",+ " Mixed ",+ Some("exact-test"),+ method,+ agent_schema_table_params("demo", " Mixed ", " T(a) "),+ )+ .await+ .unwrap_err();+ assert!(error.contains("exact_metadata_identity_v1"), "{mode}: {error}");+ assert!(requests(directory.path(), method.as_str()).is_empty());+ }+ let columns = super::super::get_columns_core_for_session_in_context(+ &state,+ "conn",+ "demo",+ "MIXED",+ "T(A)",+ Some("exact-test"),+ None,+ )+ .await+ .unwrap();+ assert_eq!(columns[0].name, "ID");+ assert_eq!(requests(directory.path(), "get_columns").len(), 1);+ assert!(state.pool_handle(&key).await.is_some());+ state.shutdown(Duration::from_secs(2)).await;+ }+ }++ #[tokio::test]+ async fn explicit_v1_and_v2_processes_receive_raw_identities_and_no_casefold_fallback() {+ for mode in ["v1-exact", "v2-exact"] {+ let (directory, state, _key) = agent_fixture(mode).await;+ let objects: Vec<db::ObjectInfo> = request(+ &state,+ "conn",+ "demo",+ " Mixed ",+ Some("exact-test"),+ AgentMethod::ListObjects,+ agent_schema_params("demo", " Mixed "),+ )+ .await+ .unwrap();+ assert_eq!(objects[0].name, " Ix(a) ");+ assert_eq!(objects[0].schema.as_deref(), Some(" Mixed "));+ assert_eq!(objects[0].parent_schema.as_deref(), Some(" Other Owner "));+ assert_eq!(objects[0].parent_name.as_deref(), Some(" T(a) "));+ assert_eq!(+ columns(&state, "conn", "demo", " Mixed ", " T(a) ", Some("exact-test")).await.unwrap()[0].name,+ "Id"+ );+ let calls = requests(directory.path(), "get_columns");+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0]["params"]["schema"], " Mixed ");+ assert_eq!(calls[0]["params"]["table"], " T(a) ");+ assert_eq!(calls[0]["params"]["exact_identity"], true);+ state.shutdown(Duration::from_secs(2)).await;+ }+ }++ #[tokio::test]+ async fn legacy_oracle_keeps_indexes_beyond_ten_thousand_candidates_and_both_raw_owners() {+ let (directory, state, _key) = agent_fixture("legacy-all").await;+ let types = vec!["INDEX".to_string()];+ let outcome = super::super::list_objects_once(+ &state,+ "conn",+ "demo",+ " mixed ",+ None,+ None,+ None,+ None,+ None,+ Some("exact-test"),+ )+ .await+ .unwrap();+ assert!(!outcome.paging_applied);+ assert_eq!(outcome.objects.len(), 10004);+ let page = filter_object_infos(outcome.objects, Some("needle"), Some(2), Some(1), Some(&types), None);+ assert_eq!(page.iter().map(|object| object.name.as_str()).collect::<Vec<_>>(), ["needle(A)", "needle_A_2"]);+ assert_eq!(page[0].schema.as_deref(), Some(" Mixed "));+ assert_eq!(page[0].parent_schema.as_deref(), Some(" Other Owner "));+ assert_eq!(page[0].parent_name.as_deref(), Some(" T(a) "));+ assert!(requests(directory.path(), "list_objects").is_empty());+ assert!(requests(directory.path(), "execute_query").len() >= 2);+ let outcome = super::super::list_objects_once(+ &state,+ "conn",+ "demo",+ " mixed ",+ Some("needle"),+ Some(2),+ Some(1),+ Some(&types),+ None,+ Some("exact-test"),+ )+ .await+ .unwrap();+ assert!(outcome.paging_applied);+ assert_eq!(+ outcome.objects.iter().map(|object| object.name.as_str()).collect::<Vec<_>>(),+ ["needle(A)", "needle_A_2"]+ );+ let objects: Vec<db::ObjectInfo> = request(&state, "conn", "demo", " Mixed ", Some("exact-test"), AgentMethod::ListObjects,+ json!({"database":"demo", "schema":" Mixed ", "object_types":["INDEX"], "filter":"needle", "limit":2, "offset":1})).await.unwrap();+ assert_eq!(objects[0].parent_schema.as_deref(), Some(" Other Owner "));+ assert!(requests(directory.path(), "execute_query").last().unwrap()["params"]["sql"]+ .as_str()+ .unwrap()+ .contains("o.owner = ' Mixed '"));+ state.shutdown(Duration::from_secs(2)).await;+ }++ #[tokio::test]+ async fn legacy_oracle_empty_and_dictionary_failure_are_distinct() {+ for mode in ["legacy-empty", "legacy-error"] {+ let (_directory, state, _key) = agent_fixture(mode).await;+ let result = super::super::list_objects_once(+ &state,+ "conn",+ "demo",+ "APP",+ None,+ Some(2),+ Some(1),+ Some(&["INDEX".into()]),+ None,+ Some("exact-test"),+ )+ .await;+ if mode == "legacy-empty" {+ assert!(result.unwrap().objects.is_empty());+ } else {+ assert!(result.err().unwrap().contains("ORA-01031"));+ }+ state.shutdown(Duration::from_secs(2)).await;+ }+ }++ #[tokio::test]+ async fn default_oracle_marks_its_constrained_page_as_already_paged() {+ let (directory, state, _key) = agent_fixture("default-paged").await;+ let outcome = super::super::list_objects_once(+ &state,+ "conn",+ "demo",+ "APP",+ None,+ Some(2),+ Some(2),+ Some(&["INDEX".into()]),+ None,+ Some("exact-test"),+ )+ .await+ .unwrap();+ assert_eq!(outcome.objects.iter().map(|object| object.name.as_str()).collect::<Vec<_>>(), ["I2", "I3"]);+ assert!(outcome.paging_applied);+ assert_eq!(requests(directory.path(), "list_objects")[0]["params"]["offset"], 2);+ state.shutdown(Duration::from_secs(2)).await;+ }+}diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex d888c06e4d..e294a851b1 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -1,3 +1,4 @@+pub mod exact_metadata;pub mod table_structure_sql;pub use dbx_drivers::metadata::sqlite_ddl;@@ -3256,6 +3257,7 @@ mod tests {#[test]fn reference_keys_require_effective_unfiltered_plain_unique_columns() {let index = |name: &str, columns: &[&str], is_unique: bool, is_primary: bool| db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -6814,13 +6816,6 @@ pub async fn list_objects_core(return Ok(vec![]);}}- let filter_locally_after_oracle_comments = db_config.as_ref().is_some_and(|config| {- config.db_type == DatabaseType::Oracle && filter.is_some_and(|filter| !filter.trim().is_empty())- });- let force_local_table_name_filter = table_name_filter.is_some_and(|filter| !filter.is_empty());- let use_oracle_agent_paging = db_config.as_ref().is_some_and(is_default_oracle_agent_config)- && !filter_locally_after_oracle_comments- && !force_local_table_name_filter;let metadata_session = EphemeralAgentMetadataSession::open(state, connection_id, Some(database), "objects").await;let result = retry_metadata_connection_for_session(state,@@ -6842,13 +6837,7 @@ pub async fn list_objects_core().await.map(|outcome| {- let final_offset = if outcome.paging_applied- || agent_paging_likely_applied(use_oracle_agent_paging, limit, outcome.objects.len())- {- Some(0)- } else {- offset- };+ let final_offset = if outcome.paging_applied { Some(0) } else { offset };filter_object_infos(outcome.objects, filter, limit, final_offset, object_types, table_name_filter)})?;Ok(objects)@@ -7516,14 +7505,28 @@ async fn list_objects_once(let is_oceanbase = db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::OceanbaseOracle);let use_oracle_agent_paging = db_config.as_ref().is_some_and(is_default_oracle_agent_config);let use_agent_paging = use_oracle_agent_paging || is_oceanbase;- let filter_locally_after_oracle_comments =- is_oracle && filter.is_some_and(|filter| !filter.trim().is_empty());+ let filter_locally_after_oracle_comments = is_oracle+ && !object_types.is_some_and(|types| types.len() == 1 && types[0].eq_ignore_ascii_case("INDEX"))+ && filter.is_some_and(|filter| !filter.trim().is_empty());let timeout_duration = agent_metadata_timeout(db_config.as_ref());let fallback_config = db_config.clone();if is_oracle && !use_oracle_agent_paging {- return oracle_agent_list_objects(agent_client, database, schema, timeout_duration)- .await- .map(unpaged_object_list);+ return oracle_agent_list_objects(+ agent_client,+ database,+ schema,+ filter,+ if force_local_table_name_filter { None } else { limit },+ if force_local_table_name_filter { None } else { offset },+ object_types,+ false,+ timeout_duration,+ )+ .await+ .map(|mut outcome| {+ outcome.paging_applied &= !force_local_table_name_filter;+ outcome+ });}// KingbaseES/Vastbase agents list relations, routines and types but// never sequences, so their pg_class-backed sequence list is merged@@ -7577,7 +7580,12 @@ async fn list_objects_once().await?;}- return Ok(unpaged_object_list(with_agent_pg_sequence_objects(objects, &sequence_objects)));+ return Ok(ObjectListOutcome {+ objects: with_agent_pg_sequence_objects(objects, &sequence_objects),+ paging_applied: use_agent_paging+ && !filter_locally_after_oracle_comments+ && !force_local_table_name_filter,+ });}Ok(objects) => {if object_types_only_custom_types(object_types) {@@ -7758,7 +7766,22 @@ async fn list_completion_objects_once(let is_oracle = db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::Oracle);let fallback_config = db_config.clone();let objects = if is_oracle {- oracle_agent_list_objects(client, database, schema, agent_metadata_timeout(db_config.as_ref())).await?+ oracle_agent_list_objects(+ client,+ database,+ schema,+ None,+ None,+ None,+ None,+ false,+ agent_metadata_timeout(db_config.as_ref()),+ )+ .await?+ .objects+ .into_iter()+ .filter(|object| object.object_type != "INDEX")+ .collect()} else {let mut client = client.lock().await;match client@@ -10475,6 +10498,7 @@ async fn external_driver_gaussdb_m_indexes(let is_primary =current_name.to_lowercase().ends_with("_pkey") || current_name.eq_ignore_ascii_case("primary");indexes.push(db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -10550,6 +10574,7 @@ async fn external_driver_gaussdb_m_indexes(if !current_name.is_empty() {let is_primary = current_name.to_lowercase().ends_with("_pkey") || current_name.eq_ignore_ascii_case("primary");indexes.push(db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -11699,12 +11724,17 @@ fn oracle_owner_filter(schema: &str) -> String {}pub fn oracle_list_objects_sql(schema: &str) -> String {+ oracle_list_objects_sql_for_owner(&oracle_owner_filter(schema))+}++fn oracle_list_objects_sql_for_owner(owner: &str) -> String {format!(- "SELECT object_name, CASE object_type WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY' ELSE object_type END AS object_type, owner \- FROM all_objects \- WHERE owner = {} AND object_type IN ('TABLE', 'VIEW', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'PACKAGE', 'PACKAGE BODY') \- ORDER BY CASE object_type WHEN 'TABLE' THEN 0 WHEN 'VIEW' THEN 1 WHEN 'PROCEDURE' THEN 2 WHEN 'FUNCTION' THEN 3 WHEN 'SEQUENCE' THEN 4 WHEN 'PACKAGE' THEN 5 ELSE 6 END, object_name",- oracle_owner_filter(schema)+ "SELECT o.object_name, CASE o.object_type WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY' ELSE o.object_type END AS object_type, o.owner, \+ i.table_owner AS parent_schema, i.table_name AS parent_name \+ FROM all_objects o LEFT JOIN all_indexes i ON o.object_type = 'INDEX' AND i.owner = o.owner AND i.index_name = o.object_name \+ WHERE o.owner = {owner} AND o.object_type IN ('TABLE', 'VIEW', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'PACKAGE', 'PACKAGE BODY', 'INDEX') \+ AND (o.object_type <> 'INDEX' OR i.generated = 'N' OR i.generated IS NULL) \+ ORDER BY CASE o.object_type WHEN 'TABLE' THEN 0 WHEN 'VIEW' THEN 1 WHEN 'PROCEDURE' THEN 2 WHEN 'FUNCTION' THEN 3 WHEN 'SEQUENCE' THEN 4 WHEN 'PACKAGE' THEN 5 WHEN 'PACKAGE BODY' THEN 6 ELSE 7 END, o.object_name")}@@ -11758,25 +11788,52 @@ fn oracle_completion_like_pattern(mask: &str, match_mode: Option<&db::Completion}}+#[allow(clippy::too_many_arguments)]async fn oracle_agent_list_objects(client: Arc<db::agent_driver::PooledAgentClient>,database: &str,schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ object_types: Option<&[String]>,+ exact_identity: bool,timeout_duration: Option<Duration>,-) -> Result<Vec<db::ObjectInfo>, String> {- let sql = oracle_list_objects_sql(schema);- let params = agent_execute_query_params(- &sql,- if database.is_empty() { None } else { Some(database) },- if schema.is_empty() { None } else { Some(schema) },- QueryExecutionOptions { max_rows: Some(10_000), ..Default::default() },- );+) -> Result<ObjectListOutcome, String> {+ let index_only = object_types.is_some_and(|types| types.len() == 1 && types[0].eq_ignore_ascii_case("INDEX"));+ let mut sql = if exact_identity {+ oracle_list_objects_sql_for_owner(&sql_string(schema))+ } else {+ oracle_list_objects_sql(schema)+ };+ if index_only {+ sql = format!("SELECT object_name, object_type, owner, parent_schema, parent_name FROM ({sql}) WHERE object_type = 'INDEX'");+ if let Some(filter) = filter.map(str::trim).filter(|value| !value.is_empty()) {+ let pattern = crate::sql::fuzzy_like_pattern_with_escape(&filter.to_lowercase(), |value| {+ value.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_")+ });+ sql.push_str(&format!(" AND LOWER(object_name) LIKE {} ESCAPE '\\'", sql_string(&pattern)));+ }+ sql.push_str(" ORDER BY object_name, owner");+ }+ const PAGE_SIZE: usize = 1_000;+ let mut start = if index_only { offset.unwrap_or(0) } else { 0 };+ let requested = if index_only { limit.unwrap_or(usize::MAX) } else { usize::MAX };+ let mut objects = Vec::new();let mut client = client.lock().await;- let result: db::QueryResult = client.execute_query_with_timeout(params, timeout_duration).await?;- let mut objects: Vec<db::ObjectInfo> = result- .rows- .into_iter()- .filter_map(|row| {+ while objects.len() < requested {+ let page_size = PAGE_SIZE.min(requested - objects.len());+ let end = start.checked_add(page_size).ok_or("Oracle metadata page overflow")?;+ let page_sql = format!("SELECT object_name, object_type, owner, parent_schema, parent_name FROM (SELECT dbx_objects.*, ROWNUM dbx_row_number FROM ({sql}) dbx_objects WHERE ROWNUM <= {end}) WHERE dbx_row_number > {start}");+ let params = agent_execute_query_params(+ &page_sql,+ (!database.is_empty()).then_some(database),+ None,+ QueryExecutionOptions { max_rows: Some(page_size), ..Default::default() },+ );+ let result: db::QueryResult = client.execute_query_with_timeout(params, timeout_duration).await?;+ let row_count = result.rows.len();+ objects.extend(result.rows.into_iter().filter_map(|row| {let name = row.first()?.as_str()?.to_string();let object_type = row.get(1)?.as_str()?.to_string();let schema = row.get(2).and_then(|value| value.as_str()).map(str::to_string);@@ -11791,15 +11848,19 @@ async fn oracle_agent_list_objects(comment: None,created_at: None,updated_at: None,- parent_schema: None,- parent_name: None,+ parent_schema: row.get(3).and_then(|value| value.as_str()).map(str::to_owned),+ parent_name: row.get(4).and_then(|value| value.as_str()).map(str::to_owned),trigger: None,xugu_type_members_expandable: None,})- })- .collect();+ }));+ if row_count < page_size {+ break;+ }+ start = end;+ }load_oracle_table_comments_for_objects(&mut client, database, schema, &mut objects, timeout_duration).await?;- Ok(objects)+ Ok(ObjectListOutcome { objects, paging_applied: index_only })}async fn oracle_agent_object_source(@@ -12875,8 +12936,10 @@ mod object_source_tests {assert!(sql.contains("'PACKAGE'"));assert!(sql.contains("'PACKAGE BODY'"));assert!(sql.contains("'SEQUENCE'"));- assert!(sql.contains("CASE object_type WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY'"));+ assert!(sql.contains("CASE o.object_type WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY'"));assert!(sql.contains("owner = 'HR'"));+ assert!(sql.contains("'INDEX'"));+ assert!(sql.contains("i.table_owner AS parent_schema, i.table_name AS parent_name"));}#[test]@@ -13283,6 +13346,7 @@ mod ddl_tests {id.is_primary_key = true;let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13300,6 +13364,7 @@ mod ddl_tests {constraint_backed: true,},db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13317,6 +13382,7 @@ mod ddl_tests {constraint_backed: true,},db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13544,6 +13610,7 @@ mod ddl_tests {// expression key just like a real column.let id = column("id", "integer");let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13573,6 +13640,7 @@ mod ddl_tests {fn postgres_table_ddl_preserves_btree_key_order_and_nulls_position() {let id = column("id", "bigint");let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13600,6 +13668,7 @@ mod ddl_tests {fn postgres_primary_index(keys: &[&str]) -> db::IndexInfo {db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13844,6 +13913,7 @@ mod ddl_tests {let mut id = column("id", "integer");id.is_primary_key = true;let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13898,6 +13968,7 @@ mod ddl_tests {#[test]fn postgres_partition_ddl_preserves_local_unique_without_local_primary_key() {let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13966,6 +14037,7 @@ mod ddl_tests {let mut id = column("id", "integer");id.is_primary_key = true;let indexes = vec![db::IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-core/tests/schema_diff_case_options.rs b/crates/dbx-core/tests/schema_diff_case_options.rsindex 56bff24d02..e1ec703b23 100644--- a/crates/dbx-core/tests/schema_diff_case_options.rs+++ b/crates/dbx-core/tests/schema_diff_case_options.rs@@ -20,6 +20,7 @@ fn column(name: &str, data_type: &str) -> ColumnInfo {fn index(name: &str, columns: &[&str]) -> IndexInfo {IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-driver-agent/assets/agent-protocol-v2.json b/crates/dbx-driver-agent/assets/agent-protocol-v2.jsonindex 76d831bce7..3b472f8a5b 100644--- a/crates/dbx-driver-agent/assets/agent-protocol-v2.json+++ b/crates/dbx-driver-agent/assets/agent-protocol-v2.json@@ -2,7 +2,7 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],"commonMethods": [diff --git a/crates/dbx-driver-agent/src/agent_driver.rs b/crates/dbx-driver-agent/src/agent_driver.rsindex e67192ede0..8f4b367d3b 100644--- a/crates/dbx-driver-agent/src/agent_driver.rs+++ b/crates/dbx-driver-agent/src/agent_driver.rs@@ -867,6 +867,7 @@ pub struct AgentDriverClient {stdout: Option<BufReader<ChildStdout>>,stderr_tail: Arc<Mutex<StderrTail>>,handshake: Option<AgentHandshake>,+ session_exact_metadata_identity: Option<bool>,next_id: u64,shared_runtime: Option<Arc<AgentRuntimeClient>>,agent_session_id: Option<String>,@@ -1038,6 +1039,7 @@ impl AgentHandshake {#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AgentCapability {+ ExactMetadataIdentityV1,BlobBindStatementsV1,Connect,TestConnection,@@ -1147,7 +1149,7 @@ fn parse_agent_rpc_error_header(header: &str) -> (Option<i64>, String) {}impl AgentCapability {- pub const ALL: [Self; 29] = [+ pub const ALL: [Self; 30] = [Self::Connect,Self::TestConnection,Self::Metadata,@@ -1174,6 +1176,7 @@ impl AgentCapability {Self::MongoBulkWrite,Self::MongoRenameCollection,Self::MongoFindCursor,+ Self::ExactMetadataIdentityV1,Self::MultiSession,Self::StructuredErrorV1,Self::BlobBindStatementsV1,@@ -1181,6 +1184,7 @@ impl AgentCapability {pub fn as_str(self) -> &'static str {match self {+ Self::ExactMetadataIdentityV1 => "exact_metadata_identity_v1",Self::BlobBindStatementsV1 => "blob_bind_statements_v1",Self::Connect => "connect",Self::TestConnection => "test_connection",@@ -1734,6 +1738,7 @@ impl AgentDriverClient {stdout: Some(stdout),stderr_tail,handshake: None,+ session_exact_metadata_identity: None,next_id: 0,shared_runtime: None,agent_session_id: None,@@ -1750,6 +1755,7 @@ impl AgentDriverClient {stdout: None,stderr_tail: runtime.stderr_tail.clone(),handshake: Some(runtime.handshake().clone()),+ session_exact_metadata_identity: None,next_id: 0,shared_runtime: Some(runtime),agent_session_id: Some(agent_session_id),@@ -2134,7 +2140,13 @@ impl AgentDriverClient {}pub async fn connect(&mut self, params: Value) -> Result<Value, String> {- self.call_method(AgentMethod::Connect, params).await+ let result = self.call_method(AgentMethod::Connect, params).await?;+ self.apply_connect_result(&result);+ Ok(result)+ }++ pub(crate) fn apply_connect_result(&mut self, result: &Value) {+ self.session_exact_metadata_identity = result.get("exactMetadataIdentity").and_then(Value::as_bool);}pub async fn open_session(&mut self, agent_session_id: &str, mut params: Value) -> Result<Value, String> {@@ -3203,6 +3215,8 @@ impl AgentDriverClient {pub fn supports_capability(&self, capability: AgentCapability) -> bool {agent_supports_capability(self.handshake.as_ref(), capability)+ && (capability != AgentCapability::ExactMetadataIdentityV1+ || self.session_exact_metadata_identity != Some(false))}/// Send a shutdown message to the agent and wait for the process to exit.@@ -3300,7 +3314,8 @@ pub fn is_unsupported_handshake_error(error: &str) -> bool {pub fn agent_supports_capability(handshake: Option<&AgentHandshake>, capability: AgentCapability) -> bool {if matches!(capability,- AgentCapability::BlobBindStatementsV1+ AgentCapability::ExactMetadataIdentityV1+ | AgentCapability::BlobBindStatementsV1| AgentCapability::Kv| AgentCapability::KvTtl| AgentCapability::KvCas@@ -3823,6 +3838,7 @@ impl AgentDriverClient {stdout: None,stderr_tail: Arc::new(Mutex::new(StderrTail::default())),handshake: None,+ session_exact_metadata_identity: None,next_id: 0,shared_runtime: None,agent_session_id: None,@@ -3895,6 +3911,7 @@ mod tests {stdout: None,stderr_tail: Arc::new(Mutex::new(StderrTail::default())),handshake: None,+ session_exact_metadata_identity: None,next_id: 0,shared_runtime: None,agent_session_id: None,@@ -3907,6 +3924,70 @@ mod tests {assert!(pool.with_compatibility_mode(Some(" ".into())).compatibility_mode().is_none());}+ #[tokio::test]+ async fn connect_narrows_exact_identity_only_for_the_connected_database() {+ let script = std::env::temp_dir().join(format!("dbx-exact-connect-{}.py", uuid::Uuid::new_v4()));+ std::fs::write(&script, r#"import json, sys+print(json.dumps({'ready': True}), flush=True)+for line in sys.stdin:+ req = json.loads(line)+ params = req.get('params', {})+ if params.get('database') == 'failed':+ print(json.dumps({'jsonrpc': '2.0', 'id': req['id'], 'error': {'code': -1, 'message': 'connect failed'}}), flush=True)+ continue+ if req['method'] == 'handshake':+ result = {'protocolVersion': 2, 'agentProtocolVersion': 2, 'capabilities': ['multi_session', 'exact_metadata_identity_v1']}+ else:+ result = {'ok': True}+ if params.get('database') in ('legacy', 'modern'):+ result['exactMetadataIdentity'] = params['database'] == 'modern'+ print(json.dumps({'jsonrpc': '2.0', 'id': req['id'], 'result': result}), flush=True)+"#).unwrap();+ let launch = AgentLaunchSpec::new(test_python()).with_args([script.to_string_lossy().to_string()]);+ let mut client = AgentDriverClient::spawn(launch.clone()).await.unwrap();+ client.try_optional_handshake("test").await.unwrap();+ assert!(client.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ client.connect(serde_json::json!({"database": "legacy"})).await.unwrap();+ assert!(!client.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ assert!(client.connect(serde_json::json!({"database": "failed"})).await.is_err());+ assert!(!client.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ client.connect(serde_json::json!({"database": "modern"})).await.unwrap();+ assert!(client.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ client.connect(serde_json::json!({"database": "legacy"})).await.unwrap();+ client.connect(serde_json::json!({"database": "old-response"})).await.unwrap();+ assert!(client.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ client.handshake.as_mut().unwrap().capabilities.retain(|capability| capability != "exact_metadata_identity_v1");+ client.connect(serde_json::json!({"database": "modern"})).await.unwrap();+ assert!(!client.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ client.shutdown().await;++ let runtime = AgentRuntimeClient::spawn(launch, "test").await.unwrap();+ let mut legacy = AgentDriverClient::shared_session(runtime.clone(), "legacy".into());+ let mut modern = AgentDriverClient::shared_session(runtime.clone(), "modern".into());+ for (database, session) in [("legacy", &mut legacy), ("modern", &mut modern)] {+ let result = runtime+ .call::<serde_json::Value>(+ "open_session",+ serde_json::json!({"database": database, "agentSessionId": database}),+ Some(Duration::from_secs(2)),+ None,+ )+ .await+ .unwrap();+ session.apply_connect_result(&result);+ }+ assert!(!legacy.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ assert!(modern.supports_capability(AgentCapability::ExactMetadataIdentityV1));+ assert!(runtime.handshake().supports(AgentCapability::ExactMetadataIdentityV1));+ let ordinary = legacy+ .call::<serde_json::Value>("get_columns", serde_json::json!({"schema": "APP", "table": "T"}))+ .await+ .unwrap();+ assert_eq!(ordinary["ok"], true);+ runtime.kill_and_wait().await;+ std::fs::remove_file(script).unwrap();+ }+#[cfg(unix)]#[test]fn spawn_repairs_missing_native_execute_permission_after_eacces() {@@ -4679,6 +4760,7 @@ for line in sys.stdin:stdout: None,stderr_tail: Arc::new(Mutex::new(StderrTail::default())),handshake: None,+ session_exact_metadata_identity: None,next_id: 0,shared_runtime: None,agent_session_id: None,@@ -5957,7 +6039,8 @@ for line in sys.stdin:assert_eq!(AgentCapability::MultiSession.as_str(), "multi_session");assert_eq!(AgentCapability::StructuredErrorV1.as_str(), "structured_error_v1");assert_eq!(AgentCapability::BlobBindStatementsV1.as_str(), "blob_bind_statements_v1");- assert_eq!(AgentCapability::ALL.len(), 29);+ assert_eq!(AgentCapability::ExactMetadataIdentityV1.as_str(), "exact_metadata_identity_v1");+ assert_eq!(AgentCapability::ALL.len(), 30);}#[test]@@ -6336,6 +6419,20 @@ for line in sys.stdin:assert!(!handshake.supports(AgentCapability::Kv));}+ #[test]+ fn exact_metadata_identity_requires_explicit_process_support() {+ assert!(!agent_supports_capability(None, AgentCapability::ExactMetadataIdentityV1));+ let mut handshake = AgentHandshake {+ protocol_version: AGENT_PROTOCOL_VERSION,+ agent_protocol_version: AGENT_PROTOCOL_VERSION,+ capabilities: vec!["metadata".into()],+ };+ assert!(agent_supports_capability(Some(&handshake), AgentCapability::Metadata));+ assert!(!agent_supports_capability(Some(&handshake), AgentCapability::ExactMetadataIdentityV1));+ handshake.capabilities.push("exact_metadata_identity_v1".into());+ assert!(agent_supports_capability(Some(&handshake), AgentCapability::ExactMetadataIdentityV1));+ }+#[test]fn treats_missing_handshake_as_legacy_capability_support() {let handshake = AgentHandshake {diff --git a/crates/dbx-driver-agent/src/agent_runtime.rs b/crates/dbx-driver-agent/src/agent_runtime.rsindex 8c3432ff7f..8c8de4ae6e 100644--- a/crates/dbx-driver-agent/src/agent_runtime.rs+++ b/crates/dbx-driver-agent/src/agent_runtime.rs@@ -128,15 +128,20 @@ pub async fn spawn_shared_connection_client(break (runtime_cell, runtime);}};- if let Err(err) = runtime+ let connect_result = match runtime.call_typed::<serde_json::Value>(AgentMethod::OpenSession.as_str(), session_params, Some(connect_timeout), None).await{- let open_error = shared_connection_open_error(err, runtime.clone());- forget_unused_runtime_after_failed_open(manager, &runtime_key, &runtime_cell, &runtime).await;- return Err(open_error);- }- Ok(AgentDriverClient::shared_session(runtime, agent_session_id))+ Ok(result) => result,+ Err(err) => {+ let open_error = shared_connection_open_error(err, runtime.clone());+ forget_unused_runtime_after_failed_open(manager, &runtime_key, &runtime_cell, &runtime).await;+ return Err(open_error);+ }+ };+ let mut client = AgentDriverClient::shared_session(runtime, agent_session_id);+ client.apply_connect_result(&connect_result);+ Ok(client)}fn shared_connection_open_error(diff --git a/crates/dbx-driver-mongodb/src/mongo_driver.rs b/crates/dbx-driver-mongodb/src/mongo_driver.rsindex 1ca9255678..bdd856a74f 100644--- a/crates/dbx-driver-mongodb/src/mongo_driver.rs+++ b/crates/dbx-driver-mongodb/src/mongo_driver.rs@@ -965,6 +965,7 @@ fn index_info_from_model(model: IndexModel) -> IndexInfo {.and_then(|options| options.partial_filter_expression.as_ref()).map(|filter| bson_to_json(&Bson::Document(filter.clone())).to_string());IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -4502,6 +4503,7 @@ mod tests {#[test]fn index_spec_from_index_info_marks_properties_as_incomplete() {let spec = index_spec_from_index_info(&IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -4533,6 +4535,7 @@ mod tests {#[test]fn index_spec_from_index_info_falls_back_to_columns_without_an_index_type() {let spec = index_spec_from_index_info(&IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -4782,6 +4785,7 @@ mod tests {fn diff_dropped_index_names_reports_removed_indexes() {let before = vec![IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -4799,6 +4803,7 @@ mod tests {constraint_backed: false,},IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -4816,6 +4821,7 @@ mod tests {constraint_backed: false,},IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-driver-mysql/src/manticoresearch.rs b/crates/dbx-driver-mysql/src/manticoresearch.rsindex f182404924..e447fa8174 100644--- a/crates/dbx-driver-mysql/src/manticoresearch.rs+++ b/crates/dbx-driver-mysql/src/manticoresearch.rs@@ -201,6 +201,7 @@ fn index_info_from_row(row: &mysql_async::Row) -> IndexInfo {.collect();IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-driver-mysql/src/mysql.rs b/crates/dbx-driver-mysql/src/mysql.rsindex f6e77b5cf9..cce7dbc168 100644--- a/crates/dbx-driver-mysql/src/mysql.rs+++ b/crates/dbx-driver-mysql/src/mysql.rs@@ -7154,6 +7154,7 @@ pub async fn list_indexes(pool: &MySqlPool, database: &str, table: &str) -> Resulet index_position = indexes.len();index_positions.insert(name.clone(), index_position);indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-driver-mysql/src/mysql_compatible.rs b/crates/dbx-driver-mysql/src/mysql_compatible.rsindex aa71a99dc9..fe4e55cf58 100644--- a/crates/dbx-driver-mysql/src/mysql_compatible.rs+++ b/crates/dbx-driver-mysql/src/mysql_compatible.rs@@ -322,6 +322,7 @@ fn table_key_index(name: &str, line: &str, is_unique: bool, is_primary: bool, inreturn None;}Some(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -348,6 +349,7 @@ fn secondary_index(line: &str) -> Option<IndexInfo> {return None;}Some(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-driver-mysql/src/ob_oracle.rs b/crates/dbx-driver-mysql/src/ob_oracle.rsindex efd2131173..c330ceac6e 100644--- a/crates/dbx-driver-mysql/src/ob_oracle.rs+++ b/crates/dbx-driver-mysql/src/ob_oracle.rs@@ -93,24 +93,27 @@ pub async fn list_tables(pool: &mysql_async::Pool, schema: &str) -> Result<Vec<Tfn list_objects_sql(schema: &str) -> String {format!(- "SELECT TABLE_NAME AS OBJECT_NAME, 'TABLE' AS OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, 0 AS SORT_ORDER \+ "SELECT TABLE_NAME AS OBJECT_NAME, 'TABLE' AS OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, NULL AS PARENT_SCHEMA, NULL AS PARENT_NAME, 0 AS SORT_ORDER \FROM ALL_TABLES WHERE OWNER = {s} \UNION ALL \- SELECT VIEW_NAME AS OBJECT_NAME, 'VIEW' AS OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, 1 AS SORT_ORDER \+ SELECT VIEW_NAME AS OBJECT_NAME, 'VIEW' AS OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, NULL AS PARENT_SCHEMA, NULL AS PARENT_NAME, 1 AS SORT_ORDER \FROM ALL_VIEWS WHERE OWNER = {s} \UNION ALL \- SELECT OBJECT_NAME, OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, \+ SELECT OBJECT_NAME, OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, NULL AS PARENT_SCHEMA, NULL AS PARENT_NAME, \CASE WHEN OBJECT_TYPE = 'PROCEDURE' THEN 2 ELSE 3 END AS SORT_ORDER \FROM ALL_PROCEDURES \WHERE OWNER = {s} AND OBJECT_TYPE IN ('PROCEDURE', 'FUNCTION') AND PROCEDURE_NAME IS NULL \UNION ALL \- SELECT SEQUENCE_NAME AS OBJECT_NAME, 'SEQUENCE' AS OBJECT_TYPE, SEQUENCE_OWNER AS OBJECT_SCHEMA, 4 AS SORT_ORDER \+ SELECT SEQUENCE_NAME AS OBJECT_NAME, 'SEQUENCE' AS OBJECT_TYPE, SEQUENCE_OWNER AS OBJECT_SCHEMA, NULL AS PARENT_SCHEMA, NULL AS PARENT_NAME, 4 AS SORT_ORDER \FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER = {s} \UNION ALL \SELECT OBJECT_NAME, CASE OBJECT_TYPE WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY' ELSE OBJECT_TYPE END AS OBJECT_TYPE, \- OWNER AS OBJECT_SCHEMA, CASE WHEN OBJECT_TYPE = 'PACKAGE' THEN 5 ELSE 6 END AS SORT_ORDER \+ OWNER AS OBJECT_SCHEMA, NULL AS PARENT_SCHEMA, NULL AS PARENT_NAME, CASE WHEN OBJECT_TYPE = 'PACKAGE' THEN 5 ELSE 6 END AS SORT_ORDER \FROM ALL_OBJECTS \WHERE OWNER = {s} AND OBJECT_TYPE IN ('PACKAGE', 'PACKAGE BODY') \+ UNION ALL \+ SELECT INDEX_NAME AS OBJECT_NAME, 'INDEX' AS OBJECT_TYPE, OWNER AS OBJECT_SCHEMA, TABLE_OWNER AS PARENT_SCHEMA, TABLE_NAME AS PARENT_NAME, 7 AS SORT_ORDER \+ FROM ALL_INDEXES WHERE OWNER = {s} AND (GENERATED = 'N' OR GENERATED IS NULL) \ORDER BY SORT_ORDER, OBJECT_NAME",s = metadata_owner_sql(schema),)@@ -122,27 +125,28 @@ pub async fn list_objects(pool: &mysql_async::Pool, schema: &str) -> Result<Vec<let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;- Ok(rows- .iter()- .map(|row| ObjectInfo {- name: get_str(row, 0),- object_type: get_str(row, 1),- schema: get_opt_str(row, 2)- .filter(|schema| !schema.is_empty())- .or_else(|| (!schema.trim().is_empty()).then(|| schema.to_string())),- valid: None,- signature: None,- custom_type_kind: None,- has_members: None,- comment: None,- created_at: None,- updated_at: None,- parent_schema: None,- parent_name: None,- trigger: None,- xugu_type_members_expandable: None,- })- .collect())+ Ok(rows.iter().map(|row| object_info_from_row(row, schema)).collect())+}++fn object_info_from_row(row: &mysql_async::Row, schema: &str) -> ObjectInfo {+ ObjectInfo {+ name: get_str(row, 0),+ object_type: get_str(row, 1),+ schema: get_opt_str(row, 2)+ .filter(|schema| !schema.is_empty())+ .or_else(|| (!schema.trim().is_empty()).then(|| schema.to_string())),+ valid: None,+ signature: None,+ custom_type_kind: None,+ has_members: None,+ comment: None,+ created_at: None,+ updated_at: None,+ parent_schema: get_opt_str(row, 3),+ parent_name: get_opt_str(row, 4),+ trigger: None,+ xugu_type_members_expandable: None,+ }}fn get_columns_sql(schema: &str, table: &str) -> String {@@ -215,16 +219,16 @@ fn list_indexes_sql(schema: &str, table: &str) -> String {format!("SELECT ai.INDEX_NAME, aic.COLUMN_NAME, ai.UNIQUENESS, \CASE WHEN ac.CONSTRAINT_NAME IS NULL THEN 0 ELSE 1 END AS IS_PRIMARY, ai.INDEX_TYPE, ai.PARTITIONED, \- ai.VISIBILITY, aic.DESCEND, aie.COLUMN_EXPRESSION, aic.COLUMN_POSITION \+ ai.VISIBILITY, aic.DESCEND, aie.COLUMN_EXPRESSION, aic.COLUMN_POSITION, ai.OWNER \FROM ALL_INDEXES ai \JOIN ALL_IND_COLUMNS aic ON ai.INDEX_NAME = aic.INDEX_NAME AND ai.OWNER = aic.INDEX_OWNER \AND ai.TABLE_OWNER = aic.TABLE_OWNER AND ai.TABLE_NAME = aic.TABLE_NAME \LEFT JOIN ALL_IND_EXPRESSIONS aie ON aie.INDEX_OWNER = aic.INDEX_OWNER AND aie.INDEX_NAME = aic.INDEX_NAME \AND aie.TABLE_OWNER = aic.TABLE_OWNER AND aie.TABLE_NAME = aic.TABLE_NAME AND aie.COLUMN_POSITION = aic.COLUMN_POSITION \LEFT JOIN ALL_CONSTRAINTS ac ON ac.INDEX_NAME = ai.INDEX_NAME AND ac.OWNER = ai.TABLE_OWNER \- AND ac.TABLE_NAME = ai.TABLE_NAME AND ac.CONSTRAINT_TYPE = 'P' \+ AND ac.TABLE_NAME = ai.TABLE_NAME AND ac.INDEX_OWNER = ai.OWNER AND ac.CONSTRAINT_TYPE = 'P' \WHERE ai.TABLE_OWNER = {s} AND ai.TABLE_NAME = {t} \- ORDER BY ai.INDEX_NAME, aic.COLUMN_POSITION",+ ORDER BY ai.OWNER, ai.INDEX_NAME, aic.COLUMN_POSITION",s = metadata_owner_sql(schema),t = quote_value(table),)@@ -236,16 +240,18 @@ pub async fn list_indexes(pool: &mysql_async::Pool, schema: &str, table: &str) -let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;- let mut indexes = BTreeMap::<String, IndexInfo>::new();+ let mut indexes = BTreeMap::<(String, String), IndexInfo>::new();for row in &rows {let name = get_str(row, 0);+ let owner = get_str(row, 10);let visibility = get_str(row, 6);let partitioned = get_str(row, 5);let direction = get_str(row, 7);let expression = get_opt_str(row, 8).filter(|value| !value.trim().is_empty());let column = get_str(row, 1);let position = row_get::<u64, _>(row, 9).unwrap_or(0) as usize;- let index = indexes.entry(name.clone()).or_insert_with(|| IndexInfo {+ let index = indexes.entry((owner.clone(), name.clone())).or_insert_with(|| IndexInfo {+ owner: Some(owner),key_directions: Vec::new(),visibility: Some(visibility.clone()),key_metadata_complete: true,@@ -368,6 +374,29 @@ pub async fn list_triggers(pool: &mysql_async::Pool, schema: &str, table: &str)mod tests {use super::*;+ #[test]+ fn native_index_row_keeps_separate_raw_parent_identity() {+ use mysql_async::{consts::ColumnType, Column, Value};+ let values = vec![+ Value::from(" Ix (a) "),+ Value::from("INDEX"),+ Value::from(" Index Owner "),+ Value::from(" Parent Owner "),+ Value::from(" T(a) "),+ Value::Int(7),+ ];+ let columns = (0..values.len())+ .map(|index| Column::new(ColumnType::MYSQL_TYPE_VAR_STRING).with_name(format!("c{index}").as_bytes()))+ .collect::<Vec<_>>();+ let row = mysql_common::row::new_row(values, columns.into());+ let object = object_info_from_row(&row, "CURRENT");+ assert_eq!(object.schema.as_deref(), Some(" Index Owner "));+ assert_eq!(object.name, " Ix (a) ");+ assert_eq!(object.parent_schema.as_deref(), Some(" Parent Owner "));+ assert_eq!(object.parent_name.as_deref(), Some(" T(a) "));+ assert!(list_objects_sql(" Owner ").contains("ALL_INDEXES"));+ }+#[test]fn ob_oracle_list_objects_sql_includes_routines() {let sql = list_objects_sql("DLJPM");diff --git a/crates/dbx-driver-postgres/src/postgres.rs b/crates/dbx-driver-postgres/src/postgres.rsindex 0f1a9ec595..aa148cd925 100644--- a/crates/dbx-driver-postgres/src/postgres.rs+++ b/crates/dbx-driver-postgres/src/postgres.rs@@ -5411,6 +5411,7 @@ async fn list_indexes_for_relations_with_sql(let all_key_options: Vec<i16> = row.try_get::<_, Vec<i16>>(12).unwrap_or_default();let key_options = if all_key_options.len() == split_at { all_key_options } else { Vec::new() };result.entry(relid).or_default().push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9965,6 +9966,7 @@ async fn list_indexes_with_sql(let all_key_options: Vec<i16> = row.try_get::<_, Vec<i16>>(11).unwrap_or_default();let key_options = if all_key_options.len() == split_at { all_key_options } else { Vec::new() };IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-driver-sqlserver/src/sqlserver.rs b/crates/dbx-driver-sqlserver/src/sqlserver.rsindex 123511c48e..17656037e9 100644--- a/crates/dbx-driver-sqlserver/src/sqlserver.rs+++ b/crates/dbx-driver-sqlserver/src/sqlserver.rs@@ -3372,6 +3372,7 @@ pub async fn list_indexes(client: &mut SqlServerClient, schema: &str, table: &stlet cols_str = row.get::<&str, _>(1).unwrap_or("");let inc_str = row.get::<&str, _>(5).unwrap_or("");IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-drivers/src/db/clickhouse_driver.rs b/crates/dbx-drivers/src/db/clickhouse_driver.rsindex 68b62a5e1e..b05c2d9b84 100644--- a/crates/dbx-drivers/src/db/clickhouse_driver.rs+++ b/crates/dbx-drivers/src/db/clickhouse_driver.rs@@ -544,6 +544,7 @@ fn clickhouse_index_from_skipping_row(row: &[serde_json::Value]) -> IndexInfo {let index_type = row.get(2).and_then(|v| v.as_str()).unwrap_or("").to_string();let granularity = json_value_as_u64(row.get(3));IndexInfo {+ owner: None,name: row.first().and_then(|v| v.as_str()).unwrap_or("").to_string(),columns: split_clickhouse_expression_list(row.get(1).and_then(|v| v.as_str()).unwrap_or("")),is_unique: false,@@ -808,6 +809,7 @@ pub async fn list_indexes(client: &ChClient, database: &str, table: &str) -> Res.filter(|value| !value.trim().is_empty()){indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs b/crates/dbx-drivers/src/db/cloudflare_d1/mod.rsindex e19244df47..d3739486f0 100644--- a/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs+++ b/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs@@ -300,6 +300,7 @@ pub async fn list_indexes(client: &CloudflareD1Client, _schema: &str, table: &stlet columns =column_result.rows.iter().filter_map(|row| value_by_column(&column_result.columns, row, "name")).collect();indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-drivers/src/db/questdb.rs b/crates/dbx-drivers/src/db/questdb.rsindex 2a98c644da..a30aad63c8 100644--- a/crates/dbx-drivers/src/db/questdb.rs+++ b/crates/dbx-drivers/src/db/questdb.rs@@ -171,6 +171,7 @@ pub async fn list_indexes(pool: &Pool, _schema: &str, table: &str) -> Result<Veclet column: String = row.get::<_, String>(0);let key_cols = vec![column];IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-drivers/src/db/rqlite_driver.rs b/crates/dbx-drivers/src/db/rqlite_driver.rsindex af844b2afd..9cd8678094 100644--- a/crates/dbx-drivers/src/db/rqlite_driver.rs+++ b/crates/dbx-drivers/src/db/rqlite_driver.rs@@ -172,6 +172,7 @@ pub async fn list_indexes(client: &RqliteClient, _schema: &str, table: &str) ->.filter_map(|row| value_by_column(&column_result.columns, row, "name")).collect();indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-drivers/src/db/sqlite.rs b/crates/dbx-drivers/src/db/sqlite.rsindex d1a3ebe749..0da4bf7858 100644--- a/crates/dbx-drivers/src/db/sqlite.rs+++ b/crates/dbx-drivers/src/db/sqlite.rs@@ -2516,6 +2516,7 @@ pub async fn list_indexes(pool: &SqliteHandle, schema: &str, table: &str) -> Res}).collect();indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -2575,6 +2576,7 @@ pub async fn list_indexes(pool: &SqliteHandle, schema: &str, table: &str) -> Res.collect::<Vec<_>>();indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-drivers/src/db/turso_driver.rs b/crates/dbx-drivers/src/db/turso_driver.rsindex fd452420e9..9ee7f8903d 100644--- a/crates/dbx-drivers/src/db/turso_driver.rs+++ b/crates/dbx-drivers/src/db/turso_driver.rs@@ -233,6 +233,7 @@ pub async fn list_indexes(client: &TursoClient, _schema: &str, table: &str) -> R.filter_map(|row| value_by_column(&column_result.columns, row, "name")).collect();indexes.push(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-sql-schema/src/schema_diff.rs b/crates/dbx-sql-schema/src/schema_diff.rsindex d14c210efc..902cadf423 100644--- a/crates/dbx-sql-schema/src/schema_diff.rs+++ b/crates/dbx-sql-schema/src/schema_diff.rs@@ -7074,6 +7074,7 @@ mod tests {fn index(overrides: IndexInfo) -> IndexInfo {IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -7306,6 +7307,7 @@ mod tests {target_column.column_default = Some("target".to_string());target_column.comment = Some("target comment".to_string());options.source_details[0].indexes.push(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -8444,6 +8446,7 @@ mod tests {fn sqlserver_drops_changed_indexes_and_defaults_before_columns() {let target_column = ColumnInfo { column_default: Some("((0))".into()), ..column("legacy_status", "int", None) };let target_index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -8512,6 +8515,7 @@ mod tests {let source_column = column("amount", "bigint", None);let target_column = column("amount", "int", None);let unchanged_index = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -8585,6 +8589,7 @@ mod tests {#[test]fn sqlserver_index_and_foreign_key_forms_follow_tsql() {let btree = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -8609,6 +8614,7 @@ mod tests {assert!(!btree_sql.contains("BTREE"));let columnstore = IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9325,6 +9331,7 @@ mod tests {fn detects_modified_indexes_not_only_added_or_removed_indexes() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9342,6 +9349,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9368,6 +9376,7 @@ mod tests {#[test]fn detects_opclass_change_in_postgres_index() {let source_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9385,6 +9394,7 @@ mod tests {constraint_backed: false,});let target_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9417,6 +9427,7 @@ mod tests {fn detects_mysql_functional_index_changes_and_preserves_expression_ddl() {let functional_key_part = "((case when (`STATUS` = _utf8mb4'online') then _utf8mb4'online' else NULL end))";let source_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9434,6 +9445,7 @@ mod tests {constraint_backed: false,});let target_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9530,6 +9542,7 @@ mod tests {// whole expression as an identifier turned it into a literal (and nonexistent) column.let expression_key_part = "COALESCE(height, '-1'::integer::double precision)";let new_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9601,6 +9614,7 @@ mod tests {let expression_key_part ="(((category)::text = ANY ((ARRAY['industrial'::character varying, 'macro'::character varying])::text[])))";let new_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9675,6 +9689,7 @@ mod tests {// `indoption` is only meaningful for B-tree keys, so a GIN index must not gain// `ASC NULLS LAST` suffixes even when the introspection reports the flags.let new_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9741,6 +9756,7 @@ mod tests {// parts from pg_get_indexdef are left unquoted.let expression_key_part = "COALESCE(height, '-1'::integer::double precision)";let new_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9819,6 +9835,7 @@ mod tests {fn quotes_expression_like_column_names_without_agent_provenance() {for db_type in [DatabaseType::Kingbase, DatabaseType::Vastbase] {let new_index = index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -9941,6 +9958,7 @@ mod tests {diff_type: "modified".to_string(),name: "idx_orders_status".to_string(),source: Some(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -10434,6 +10452,7 @@ mod tests {diff_type: "added".to_string(),name: "idx_orders_status".to_string(),source: Some(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -11169,6 +11188,7 @@ mod tests {column("User ID", "bigint", None),],indexes: vec![index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -11238,6 +11258,7 @@ mod tests {column("user-id", "bigint", None),],indexes: vec![index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -11297,6 +11318,7 @@ mod tests {column("parent id", "TEXT", None),],indexes: vec![index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -12487,6 +12509,7 @@ mod tests {diff_type: "added".to_string(),name: "idx_name".to_string(),source: Some(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -12535,6 +12558,7 @@ mod tests {name: "idx_old".to_string(),source: None,target: Some(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -12957,6 +12981,7 @@ mod tests {fn index_type_diff_btree_vs_hash() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -12974,6 +12999,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -12999,6 +13025,7 @@ mod tests {fn index_type_fulltext_detected() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13016,6 +13043,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13041,6 +13069,7 @@ mod tests {fn index_column_order_different() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13058,6 +13087,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13084,6 +13114,7 @@ mod tests {fn index_included_columns_diff() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13101,6 +13132,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13126,6 +13158,7 @@ mod tests {fn index_included_columns_added() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13143,6 +13176,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13168,6 +13202,7 @@ mod tests {fn index_filter_change() {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13185,6 +13220,7 @@ mod tests {constraint_backed: false,})],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13212,6 +13248,7 @@ mod tests {let diffs = diff_indexes(&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13229,6 +13266,7 @@ mod tests {constraint_backed: false,}),index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13248,6 +13286,7 @@ mod tests {],&[index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13265,6 +13304,7 @@ mod tests {constraint_backed: false,}),index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13647,6 +13687,7 @@ mod tests {diff_type: "added".to_string(),name: "idx_name".into(),source: Some(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -13671,6 +13712,7 @@ mod tests {name: "idx_old".into(),source: None,target: Some(index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -14092,6 +14134,7 @@ mod tests {diff_type: "added".into(),name: "idx_del_flag".into(),source: Some(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -14385,6 +14428,7 @@ mod tests {diff_type: "added".into(),name: "idx_views".into(),source: Some(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,@@ -15806,6 +15850,7 @@ mod tests {fn named_index(name: &str, columns: &[&str], is_unique: bool) -> IndexInfo {index(IndexInfo {+ owner: None,key_directions: Vec::new(),visibility: None,key_metadata_complete: false,diff --git a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rsindex 0ee5abbbc3..9d45d1711a 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs@@ -51,7 +51,7 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut}if let Some(original) = &index.original {- if !has_existing_index_change(index) {+ if !has_existing_index_change_for_database(index, options.database_type) {continue;}if !capabilities.rebuild_index || !capabilities.drop_index || !capabilities.create_index {@@ -92,8 +92,8 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mutcontinue;}let or_replace =- options.database_type == Some(DatabaseType::Dameng) && clean(&index.name) == clean(&original.name);- if dialect == StructureDialect::Oracle {+ options.database_type == Some(DatabaseType::Dameng) && index_name_for_sql(index, true) == original.name;+ if matches!(dialect, StructureDialect::Oracle | StructureDialect::Dameng) {// Oracle-family index edits may require DROP/CREATE. Validate that the// complete replacement plan can be built before exposing its destructive// first step; an empty/invalid target must never become a DROP-only plan.@@ -211,9 +211,8 @@ fn build_dameng_constraint_index_edit(concurrently_supported: bool,warnings: &mut Vec<String>,) -> Vec<String> {- let name = clean(&index.name);- let columns: Vec<String> =- index.columns.iter().map(|column| clean(column)).filter(|column| !column.is_empty()).collect();+ let name = index_name_for_sql(index, true);+ let columns: Vec<String> = index.columns.iter().filter(|column| !column.trim().is_empty()).cloned().collect();// Same guard as `build_create_index_statements`: an empty name or an empty column list// cannot produce a valid replacement (`validate_draft` already reports it as a warning).// Emitting only the DROP would silently delete the constraint, so skip the edit entirely.@@ -271,6 +270,18 @@ pub fn has_existing_index_change(index: &EditableStructureIndex) -> bool {)}+pub(super) fn has_existing_index_change_for_database(+ index: &EditableStructureIndex,+ database_type: Option<DatabaseType>,+) -> bool {+ has_existing_index_change(index)+ || (matches!(database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng))+ && index.original.as_ref().is_some_and(|original| {+ index.columns != original.columns+ || (original.name != clean(&original.name) && index.name != original.name)+ }))+}+/// Compare opclass arrays positionally, skipping expression columns./// When the column list has changed we already detect that above; here we only/// compare opclasses for columns that exist in both the edited and original lists.@@ -403,7 +414,7 @@ fn postgres_index_column_sql(column: &str, is_expression: bool, opclass: Option</// tied to its true ordinal position instead of being re-derived by scanning for a text match/// (#6312 review). A key without explicit provenance is treated as a real column: the editor can/// only add table columns, and guessing from the identifier text breaks valid quoted names.-fn key_expression_flags(index: &EditableStructureIndex, columns: &[String]) -> Vec<bool> {+fn key_expression_flags(index: &EditableStructureIndex, columns: &[String], exact_keys: bool) -> Vec<bool> {let original = match &index.original {Some(original) if !original.key_is_expression.is_empty() => original,_ => return vec![false; columns.len()],@@ -412,11 +423,10 @@ fn key_expression_flags(index: &EditableStructureIndex, columns: &[String]) -> Vcolumns.iter().map(|column| {- let claimed = original- .columns- .iter()- .enumerate()- .find(|(i, original_column)| !consumed[*i] && clean(original_column) == clean(column));+ let claimed = original.columns.iter().enumerate().find(|(i, original_column)| {+ !consumed[*i]+ && if exact_keys { *original_column == column } else { clean(original_column) == clean(column) }+ });match claimed {Some((i, _)) => {consumed[i] = true;@@ -459,7 +469,7 @@ fn oracle_key_directions(.columns.iter().enumerate()- .find(|(position, original_column)| !consumed[*position] && clean(original_column) == clean(column))+ .find(|(position, original_column)| !consumed[*position] && *original_column == column).map(|(position, _)| {consumed[position] = true;original.key_directions[position].clone()@@ -524,6 +534,14 @@ fn key_opclasses(index: &EditableStructureIndex, columns: &[String]) -> Vec<Opti.collect()}+fn index_name_for_sql(index: &EditableStructureIndex, preserve_metadata_identity: bool) -> String {+ if preserve_metadata_identity && index.original.as_ref().is_some_and(|original| original.name == index.name) {+ index.name.clone()+ } else {+ clean(&index.name)+ }+}+pub(super) fn build_drop_index_sql(database_type: Option<DatabaseType>,dialect: StructureDialect,@@ -570,9 +588,15 @@ pub(super) fn build_create_index_statements(driver_profile: Option<&str>,) -> Vec<String> {let capabilities = capabilities_for(database_type_for_dialect(dialect), None);- let name = clean(&index.name);- let columns: Vec<String> =- index.columns.iter().map(|column| clean(column)).filter(|column| !column.is_empty()).collect();+ let exact_keys =+ matches!(database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng));+ let name = index_name_for_sql(index, exact_keys);+ let columns: Vec<String> = index+ .columns+ .iter()+ .map(|column| if exact_keys { column.clone() } else { clean(column) })+ .filter(|column| !column.trim().is_empty())+ .collect();if name.is_empty() || columns.is_empty() {return Vec::new();}@@ -599,7 +623,7 @@ pub(super) fn build_create_index_statements(let unique = if index.is_unique { "UNIQUE " } else { "" };let replace = if or_replace { "OR REPLACE " } else { "" };- let key_is_expression = key_expression_flags(index, &columns);+ let key_is_expression = key_expression_flags(index, &columns, exact_keys);let key_opclasses = key_opclasses(index, &columns);let cols = columns.iter()diff --git a/crates/dbx-sql-schema/src/table_structure_sql/validation.rs b/crates/dbx-sql-schema/src/table_structure_sql/validation.rsindex 363e9adef5..c3cce5c251 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/validation.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/validation.rs@@ -1,6 +1,6 @@use super::column_format::has_dameng_identity;use super::dialect::{capabilities_for, StructureDialect};-use super::indexes::has_existing_index_change;+use super::indexes::{has_existing_index_change, has_existing_index_change_for_database};use super::types::{EditableStructureColumn, TableStructureSqlOptions};use super::util::{clean, normalize_default, original_default};use crate::models::connection::DatabaseType;@@ -46,11 +46,10 @@ pub fn validate_draft(options: &TableStructureSqlOptions) -> Vec<String> {validate_dameng_identity(options, &active_columns, &mut warnings);validate_mysql_literal_defaults(options, &active_columns, &mut warnings);validate_gin_opclass_warnings(options, &mut warnings);- for index in options- .indexes- .iter()- .filter(|index| !index.marked_for_drop && (index.original.is_none() || has_existing_index_change(index)))- {+ for index in options.indexes.iter().filter(|index| {+ !index.marked_for_drop+ && (index.original.is_none() || has_existing_index_change_for_database(index, options.database_type))+ }) {if clean(&index.name).is_empty() {warnings.push("Index name cannot be empty.".to_string());}diff --git a/crates/dbx-sql-schema/tests/oracle_index_fidelity.rs b/crates/dbx-sql-schema/tests/oracle_index_fidelity.rsindex cd5de728e8..ddd88edbbd 100644--- a/crates/dbx-sql-schema/tests/oracle_index_fidelity.rs+++ b/crates/dbx-sql-schema/tests/oracle_index_fidelity.rs@@ -93,6 +93,38 @@ fn oracle_reordered_keys_keep_their_individual_directions() {assert!(result.statements[1].contains("EVENT_TS\" ASC, LOWER(EVENT_NAME) DESC"), "{result:?}");}+#[test]+fn oracle_family_switching_to_a_whitespace_distinct_column_rebuilds_the_index() {+ for database in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle, DatabaseType::Dameng] {+ for (old, new) in [("k", " k "), (" k ", "k")] {+ let mut index = existing_index(vec![new]);+ index["name"] = json!("IX_EVENT");+ index["original"]["columns"] = json!([old]);+ index["original"]["key_is_expression"] = json!([false]);+ index["original"]["key_directions"] = json!(["ASC"]);+ index["original"]["visibility"] = json!("VISIBLE");+ let mut input = options(index);+ input.database_type = Some(database);+ let result = build_table_structure_change_sql(input);+ let expected_count = if database == DatabaseType::Dameng { 1 } else { 2 };+ assert_eq!(result.statements.len(), expected_count, "{database:?}: {old:?} -> {new:?}: {result:?}");+ assert!(result.statements.last().unwrap().contains(&format!("\"{new}\"")), "{result:?}");+ }+ }+}++#[test]+fn other_dialects_keep_the_existing_trimmed_index_key_comparison() {+ for (old, new) in [("k", " k "), (" k ", "k")] {+ let mut index = existing_index(vec![new]);+ index["name"] = json!("IX_EVENT");+ index["original"]["columns"] = json!([old]);+ let mut input = options(index);+ input.database_type = Some(DatabaseType::Postgres);+ assert!(build_table_structure_change_sql(input).statements.is_empty());+ }+}+#[test]fn oceanbase_descending_rebuild_is_rejected_before_drop() {let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);@@ -140,6 +172,37 @@ fn oracle_invalid_rebuild_does_not_drop_without_a_complete_create() {assert!(!result.warnings.is_empty(), "{result:?}");}+#[test]+fn oracle_family_blank_only_keys_cannot_create_or_replace_an_index() {+ for database_type in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle, DatabaseType::Dameng] {+ for existing in [false, true] {+ let mut index = existing_index(vec![" "]);+ if !existing {+ index.as_object_mut().unwrap().remove("original");+ }+ let mut request = options(index);+ request.database_type = Some(database_type);+ let result = build_table_structure_change_sql(request);+ assert!(result.statements.is_empty(), "{database_type:?}, existing={existing}: {result:?}");+ assert!(!result.warnings.is_empty(), "{result:?}");+ }+ }+}++#[test]+fn dameng_constraint_replacement_preserves_nonblank_raw_column_names() {+ let mut index = existing_index(vec![" Id(a) "]);+ index["isUnique"] = json!(true);+ index["original"]["is_unique"] = json!(true);+ index["original"]["constraint_backed"] = json!(true);+ let mut request = options(index);+ request.database_type = Some(DatabaseType::Dameng);+ let result = build_table_structure_change_sql(request);+ assert_eq!(result.warnings, Vec::<String>::new(), "{result:?}");+ assert_eq!(result.statements.len(), 2, "{result:?}");+ assert!(result.statements[1].contains("UNIQUE (\" Id(a) \")"), "{result:?}");+}+#[test]fn indexes_on_other_oracle_dialect_engines_keep_existing_rebuild_behavior() {for database_type in [DatabaseType::Iris, DatabaseType::Yashandb, DatabaseType::Xugu] {@@ -154,3 +217,37 @@ fn indexes_on_other_oracle_dialect_engines_keep_existing_rebuild_behavior() {assert!(result.statements[1].starts_with("CREATE INDEX"), "{database_type:?}: {result:?}");}}++#[test]+fn oracle_family_rebuild_preserves_unchanged_dictionary_names_and_selected_column_identity() {+ for database_type in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle, DatabaseType::Dameng] {+ let input = json!({+ "id":"raw-index", "name":" Ix (a) ", "columns":[" Id(a) "], "isUnique":true, "isPrimary":false,+ "original":{"name":" Ix (a) ", "columns":[" Id(a) "], "is_unique":false, "is_primary":false,+ "index_type":"NORMAL", "key_is_expression":[false], "key_directions":["ASC"],+ "visibility":"VISIBLE", "key_metadata_complete":true}+ });+ let mut request = options(input);+ request.database_type = Some(database_type);+ request.schema = Some(" Owner ".into());+ request.table_name = " T(a) ".into();+ let result = build_table_structure_change_sql(request);+ let create = result+ .statements+ .iter()+ .find(|sql| sql.starts_with("CREATE"))+ .unwrap_or_else(|| panic!("{database_type:?}: {result:?}"));+ assert!(create.contains("INDEX \" Ix (a) \""), "{database_type:?}: {result:?}");+ assert!(create.contains("ON \" Owner \".\" T(a) \""), "{database_type:?}: {result:?}");+ assert!(create.contains("\" Id(a) \""), "{database_type:?}: {result:?}");+ }+}++#[test]+fn oracle_similar_raw_keys_keep_their_own_direction_after_reorder() {+ let input = json!({"id":"raw-keys", "name":"IX_NEW", "columns":["k", " k "], "isUnique":false, "isPrimary":false,+ "original":{"name":"IX_OLD", "columns":[" k ", "k"], "is_unique":false, "is_primary":false,+ "key_is_expression":[false,false], "key_directions":["DESC","ASC"], "visibility":"VISIBLE", "key_metadata_complete":true}});+ let result = build_table_structure_change_sql(options(input));+ assert!(result.statements.iter().any(|sql| sql.contains("(\"k\" ASC, \" k \" DESC)")), "{result:?}");+}diff --git a/crates/dbx-tauri-schema/src/commands.rs b/crates/dbx-tauri-schema/src/commands.rsindex b365b73369..37c89fc932 100644--- a/crates/dbx-tauri-schema/src/commands.rs+++ b/crates/dbx-tauri-schema/src/commands.rs@@ -176,6 +176,7 @@ pub async fn list_data_types(}#[tauri::command]+#[allow(clippy::too_many_arguments)]pub async fn list_tables(state: State<'_, Arc<AppState>>,connection_id: String,@@ -187,7 +188,22 @@ pub async fn list_tables(object_types: Option<Vec<String>>,catalog: Option<String>,table_name_filter: Option<dbx_core::schema::TableNameFilter>,+ exact_identity: Option<bool>,) -> Result<Vec<db::TableInfo>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::tables(+ &state,+ &connection_id,+ &database,+ &schema,+ filter.as_deref(),+ limit,+ offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::list_doris_catalog_tables_core(&state,@@ -224,7 +240,11 @@ pub async fn get_table_comment(schema: String,table: String,catalog: Option<String>,+ exact_identity: Option<bool>,) -> Result<Option<String>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::comment(&state, &connection_id, &database, &schema, &table).await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::get_doris_catalog_table_comment_core(&state,@@ -262,10 +282,25 @@ pub async fn list_objects(catalog: Option<String>,table_name_filter: Option<dbx_core::schema::TableNameFilter>,execution_id: Option<String>,+ exact_identity: Option<bool>,) -> Result<Vec<db::ObjectInfo>, String> {let app = Arc::clone(state.inner());let operation_app = Arc::clone(&app);run_cancellable(&app, execution_id, async move {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::objects(+ &operation_app,+ &connection_id,+ &database,+ &schema,+ filter.as_deref(),+ limit,+ offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await;+ }if let Some(catalog) = external_doris_catalog(&operation_app, &connection_id, catalog.as_deref()).await {let tables = dbx_core::schema::list_doris_catalog_tables_core(&operation_app,@@ -399,7 +434,19 @@ pub async fn get_columns(catalog: Option<String>,client_session_id: Option<String>,current_schema: Option<String>,+ exact_identity: Option<bool>,) -> Result<Vec<db::ColumnInfo>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::columns(+ &state,+ &connection_id,+ &database,+ &schema,+ &table,+ client_session_id.as_deref(),+ )+ .await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::get_doris_catalog_columns_core(&state, &connection_id, &catalog, &database, &table).await;@@ -455,7 +502,11 @@ pub async fn list_indexes(schema: String,table: String,catalog: Option<String>,+ exact_identity: Option<bool>,) -> Result<Vec<db::IndexInfo>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::indexes(&state, &connection_id, &database, &schema, &table).await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::list_doris_catalog_indexes_core(&state, &connection_id, &catalog, &database, &table).await;@@ -507,7 +558,12 @@ pub async fn list_foreign_keys(schema: String,table: String,catalog: Option<String>,+ exact_identity: Option<bool>,) -> Result<Vec<db::ForeignKeyInfo>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::foreign_keys(&state, &connection_id, &database, &schema, &table)+ .await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::list_doris_catalog_foreign_keys_core(&state,@@ -549,7 +605,11 @@ pub async fn list_triggers(schema: String,table: String,catalog: Option<String>,+ exact_identity: Option<bool>,) -> Result<Vec<db::TriggerInfo>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::triggers(&state, &connection_id, &database, &schema, &table).await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::list_doris_catalog_triggers_core(&state, &connection_id, &catalog, &database, &table).await;@@ -565,7 +625,11 @@ pub async fn list_constraints(schema: String,table: String,catalog: Option<String>,+ exact_identity: Option<bool>,) -> Result<Vec<dbx_core::db::ConstraintInfo>, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::constraints(&state, &connection_id, &database, &schema, &table).await;+ }let _ = catalog;dbx_core::schema::list_constraints_core(&state, &connection_id, &database, &schema, &table).await}@@ -636,7 +700,20 @@ pub async fn get_table_ddl(catalog: Option<String>,include_postgres_access: Option<bool>,portable: Option<bool>,+ exact_identity: Option<bool>,) -> Result<String, String> {+ if exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::ddl(+ &state,+ &connection_id,+ &database,+ &schema,+ &table,+ object_type,+ portable.unwrap_or(false),+ )+ .await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {return dbx_core::schema::get_doris_catalog_table_ddl_core(&state, &connection_id, &catalog, &database, &table).await;diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rsindex c0b720eff3..eb4c063654 100644--- a/crates/dbx-types/src/models/connection.rs+++ b/crates/dbx-types/src/models/connection.rs@@ -689,6 +689,45 @@ pub enum ProxyType {include!(concat!(env!("OUT_DIR"), "/database_type.rs"));+/// A dialect fact that is safe to retain on a connection response after its URL is redacted.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum JdbcDialectHint {+ OceanbaseOracle,+}++/// Connection data returned to a client, with response-only metadata flattened into the JSON.+/// This type is never used for persistence, runtime configuration, or request deserialization.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct ConnectionResponse {+ #[serde(flatten)]+ pub config: ConnectionConfig,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub jdbc_dialect: Option<JdbcDialectHint>,+}++impl ConnectionResponse {+ pub fn from_config(config: ConnectionConfig) -> Self {+ let jdbc_dialect = jdbc_dialect_hint(&config);+ Self { config, jdbc_dialect }+ }++ pub fn with_jdbc_dialect(config: ConnectionConfig, jdbc_dialect: Option<JdbcDialectHint>) -> Self {+ Self { config, jdbc_dialect }+ }+}++/// Derive only the approved non-sensitive mode identity from an explicit JDBC URL.+pub fn jdbc_dialect_hint(config: &ConnectionConfig) -> Option<JdbcDialectHint> {+ if config.db_type != DatabaseType::Jdbc {+ return None;+ }+ let url = config.connection_string.as_deref()?.trim();+ url.get(.."jdbc:oceanbase:oracle://".len())+ .filter(|prefix| prefix.eq_ignore_ascii_case("jdbc:oceanbase:oracle://"))+ .map(|_| JdbcDialectHint::OceanbaseOracle)+}+#[derive(Deserialize)]struct ConnectionConfigData {pub id: String,@@ -3182,10 +3221,37 @@ mod tests {use super::{database_info_from_protocol_value, default_query_timeout_secs, default_redis_key_separator,default_ssh_connect_timeout_secs, sqlserver_legacy_compatibility_param,- without_sqlserver_legacy_compatibility_param, ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo,- DatabaseType, IdentifierCase, ProductionBadgeScope, ProxyTunnelConfig, ProxyType, TransportLayerConfig,+ without_sqlserver_legacy_compatibility_param, ConnectionConfig, ConnectionResponse, ConnectionTestResult,+ DatabaseConnectionInfo, DatabaseType, IdentifierCase, ProductionBadgeScope, ProxyTunnelConfig, ProxyType,+ TransportLayerConfig,};+ #[test]+ fn connection_response_derives_only_oceanbase_oracle_from_explicit_jdbc_url() {+ let mut config = mysql_config("root", "", None);+ config.db_type = DatabaseType::Jdbc;+ config.connection_string = Some(" JDBC:OCEANBASE:ORACLE://host/service ".into());+ let response = ConnectionResponse::from_config(config.clone());+ let value = serde_json::to_value(&response).unwrap();+ assert_eq!(value["jdbc_dialect"], "oceanbase-oracle");+ assert_eq!(value["db_type"], "jdbc");+ assert_eq!(response.config, config);++ config.connection_string = Some("jdbc:oracle:thin:@host/service".into());+ assert!(serde_json::to_value(ConnectionResponse::from_config(config.clone()))+ .unwrap()+ .get("jdbc_dialect")+ .is_none());+ config.connection_string = Some("jdbc:oceanbase:oracle://host/service".into());+ config.db_type = DatabaseType::Oracle;+ assert!(serde_json::to_value(ConnectionResponse::from_config(config)).unwrap().get("jdbc_dialect").is_none());++ let mut legacy = serde_json::to_value(&response.config).unwrap();+ legacy["jdbc_dialect"] = serde_json::json!("oceanbase-oracle");+ let restored: ConnectionConfig = serde_json::from_value(legacy).unwrap();+ assert!(serde_json::to_value(restored).unwrap().get("jdbc_dialect").is_none());+ }+#[test]fn default_query_timeout_is_sixty_seconds() {assert_eq!(default_query_timeout_secs(), 60);diff --git a/crates/dbx-types/src/types.rs b/crates/dbx-types/src/types.rsindex 66a7be2046..fdbbcde86e 100644--- a/crates/dbx-types/src/types.rs+++ b/crates/dbx-types/src/types.rs@@ -871,6 +871,9 @@ fn canonical_decimal(value: &str) -> Option<CanonicalDecimal> {#[derive(Debug, Clone, Serialize, Deserialize)]pub struct IndexInfo {+ /// Dictionary-derived index owner, independent of the parent table owner.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub owner: Option<String>,pub name: String,pub columns: Vec<String>,pub is_unique: bool,diff --git a/crates/dbx-types/tests/index_owner.rs b/crates/dbx-types/tests/index_owner.rsnew file mode 100644index 0000000000..f60ebd90df--- /dev/null+++ b/crates/dbx-types/tests/index_owner.rs@@ -0,0 +1,18 @@+use dbx_types::types::IndexInfo;++#[test]+fn index_owner_round_trips_raw_identity_and_remains_optional_for_old_metadata() {+ let payload = serde_json::json!({+ "name": " Ix(a) ", "owner": " Index Owner ", "columns": ["Id"],+ "is_unique": false, "is_primary": false,+ "filter": null, "index_type": null, "included_columns": null, "comment": null+ });+ let index: IndexInfo = serde_json::from_value(payload.clone()).unwrap();+ assert_eq!(index.owner.as_deref(), Some(" Index Owner "));+ assert_eq!(serde_json::to_value(index).unwrap()["owner"], " Index Owner ");+ let mut old = payload;+ old.as_object_mut().unwrap().remove("owner");+ let index: IndexInfo = serde_json::from_value(old).unwrap();+ assert!(index.owner.is_none());+ assert!(serde_json::to_value(index).unwrap().get("owner").is_none());+}diff --git a/crates/dbx-web/src/credentials.rs b/crates/dbx-web/src/credentials.rsindex fdc6d54adc..44b3b6ea59 100644--- a/crates/dbx-web/src/credentials.rs+++ b/crates/dbx-web/src/credentials.rs@@ -2,7 +2,7 @@use std::collections::HashMap;use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};-use dbx_core::models::connection::{ConnectionConfig, TransportLayerConfig};+use dbx_core::models::connection::{jdbc_dialect_hint, ConnectionConfig, ConnectionResponse, TransportLayerConfig};use serde_json::Value;use crate::{error::AppError, state::WebState};@@ -293,12 +293,10 @@ pub fn redact_tunnel(profile: TransportLayerConfig) -> TransportLayerConfig {}impl WebState {- pub fn connection_response(&self, config: ConnectionConfig) -> ConnectionConfig {- if self.password_viewer_enabled {- config- } else {- redact(&config)- }+ pub fn connection_response(&self, config: ConnectionConfig) -> ConnectionResponse {+ let jdbc_dialect = jdbc_dialect_hint(&config);+ let response_config = if self.password_viewer_enabled { config } else { redact(&config) };+ ConnectionResponse::with_jdbc_dialect(response_config, jdbc_dialect)}pub async fn resolve_connection_credentials(&self, config: ConnectionConfig) -> Result<ConnectionConfig, AppError> {@@ -363,7 +361,9 @@ impl WebState {#[cfg(test)]mod tests {use super::*;- use crate::routes::connection::{self, ConnectRequest, SaveConnectionsRequest};+ use crate::routes::connection::{+ self, ConnectRequest, McpAddConnectionRequest, McpDuplicateConnectionRequest, SaveConnectionsRequest,+ };use axum::{extract::State, http::HeaderMap, Json};use std::sync::Arc;@@ -472,32 +472,41 @@ mod tests {let original = config();state.app.storage.save_connections(std::slice::from_ref(&original)).await.unwrap();let Json(mut listed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();- assert!(listed[0].password.starts_with(REFERENCE_PREFIX));+ assert!(listed[0].config.password.starts_with(REFERENCE_PREFIX));assert_eq!(state.app.configs.read().await[&original.id].password, original.password);- listed[0].name = "Renamed".into();+ listed[0].config.name = "Renamed".into();let _ = connection::save_connections(State(state.clone()),HeaderMap::new(),- Json(SaveConnectionsRequest { configs: listed.clone(), removed_ids: Vec::new() }),+ Json(SaveConnectionsRequest {+ configs: listed.iter().map(|response| response.config.clone()).collect(),+ removed_ids: Vec::new(),+ }),).await.unwrap();assert_eq!(state.app.storage.load_connections().await.unwrap()[0].password, original.password);- listed[0].password = "replacement".into();+ listed[0].config.password = "replacement".into();let _ = connection::save_connections(State(state.clone()),HeaderMap::new(),- Json(SaveConnectionsRequest { configs: listed.clone(), removed_ids: Vec::new() }),+ Json(SaveConnectionsRequest {+ configs: listed.iter().map(|response| response.config.clone()).collect(),+ removed_ids: Vec::new(),+ }),).await.unwrap();assert_eq!(state.app.storage.load_connections().await.unwrap()[0].password, "replacement");let Json(mut listed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();- listed[0].save_password = false;+ listed[0].config.save_password = false;let _ = connection::save_connections(State(state.clone()),HeaderMap::new(),- Json(SaveConnectionsRequest { configs: listed, removed_ids: Vec::new() }),+ Json(SaveConnectionsRequest {+ configs: listed.into_iter().map(|response| response.config).collect(),+ removed_ids: Vec::new(),+ }),).await.unwrap();@@ -506,6 +515,113 @@ mod tests {assert!(state.ensure_secret_export_allowed(false).is_ok());}+ #[tokio::test]+ async fn jdbc_dialect_response_hint_survives_redaction_but_never_persists_or_trusts_input() {+ let (mut state, _dir) = web_state().await;+ let original: ConnectionConfig = serde_json::from_value(serde_json::json!({+ "id": "saved-jdbc", "name": "JDBC connection", "db_type": "jdbc", "driver_profile": "jdbc",+ "host": "host", "port": 2881, "username": "user", "password": "database-secret",+ "connection_string": "jdbc:oceanbase:oracle://host/service"+ }))+ .unwrap();+ state.app.storage.save_connections(std::slice::from_ref(&original)).await.unwrap();++ let Json(mut listed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();+ let response_json = serde_json::to_value(&listed[0]).unwrap();+ assert_eq!(response_json["jdbc_dialect"], "oceanbase-oracle");+ assert!(listed[0].config.connection_string.as_deref().unwrap().starts_with(REFERENCE_PREFIX));+ assert!(!serde_json::to_string(&response_json).unwrap().contains("jdbc:oceanbase:oracle://host/service"));+ assert!(!serde_json::to_string(&response_json).unwrap().contains("database-secret"));++ let mut rename = listed.remove(0).config;+ rename.name = "Renamed JDBC connection".into();+ let _ = connection::save_connections(+ State(state.clone()),+ HeaderMap::new(),+ Json(SaveConnectionsRequest { configs: vec![rename], removed_ids: Vec::new() }),+ )+ .await+ .unwrap();+ let persisted = state.app.storage.load_connections().await.unwrap();+ assert_eq!(persisted[0].name, "Renamed JDBC connection");+ assert_eq!(persisted[0].connection_string.as_deref(), Some("jdbc:oceanbase:oracle://host/service"));+ assert!(serde_json::to_value(&persisted[0]).unwrap().get("jdbc_dialect").is_none());++ Arc::get_mut(&mut state).unwrap().password_viewer_enabled = true;+ let Json(viewed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();+ assert_eq!(viewed[0].jdbc_dialect, Some(dbx_core::models::connection::JdbcDialectHint::OceanbaseOracle));+ assert_eq!(viewed[0].config.connection_string.as_deref(), original.connection_string.as_deref());+ assert_eq!(viewed[0].config.password, original.password);+ Arc::get_mut(&mut state).unwrap().password_viewer_enabled = false;++ let Json(mut listed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();+ assert_eq!(listed[0].jdbc_dialect, Some(dbx_core::models::connection::JdbcDialectHint::OceanbaseOracle));+ let mut changed_url = serde_json::to_value(listed.remove(0).config).unwrap();+ changed_url["connection_string"] = serde_json::json!("jdbc:oracle:thin:@host/service");+ changed_url["jdbc_dialect"] = serde_json::json!("oceanbase-oracle");+ changed_url["password"] = serde_json::json!("replacement-secret");+ let changed_url: ConnectionConfig = serde_json::from_value(changed_url).unwrap();+ let _ = connection::save_connections(+ State(state.clone()),+ HeaderMap::new(),+ Json(SaveConnectionsRequest { configs: vec![changed_url], removed_ids: Vec::new() }),+ )+ .await+ .unwrap();+ let Json(listed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();+ assert!(listed[0].jdbc_dialect.is_none());+ assert_eq!(+ state.app.storage.load_connections().await.unwrap()[0].connection_string.as_deref(),+ Some("jdbc:oracle:thin:@host/service")+ );++ let mut cleared_url = serde_json::to_value(&listed[0].config).unwrap();+ cleared_url["connection_string"] = Value::Null;+ cleared_url["jdbc_dialect"] = serde_json::json!("oceanbase-oracle");+ cleared_url["password"] = serde_json::json!("replacement-secret-2");+ let cleared_url: ConnectionConfig = serde_json::from_value(cleared_url).unwrap();+ let _ = connection::save_connections(+ State(state.clone()),+ HeaderMap::new(),+ Json(SaveConnectionsRequest { configs: vec![cleared_url], removed_ids: Vec::new() }),+ )+ .await+ .unwrap();+ let Json(listed) = connection::load_connections(State(state.clone()), HeaderMap::new()).await.unwrap();+ assert!(listed[0].jdbc_dialect.is_none());+ assert!(state.app.storage.load_connections().await.unwrap()[0].connection_string.is_none());+ }++ #[tokio::test]+ async fn mcp_added_and_duplicated_connections_use_the_same_flat_dialect_response() {+ let (state, _dir) = web_state().await;+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({+ "id": "mcp-jdbc", "name": "MCP JDBC", "db_type": "jdbc", "driver_profile": "jdbc",+ "host": "host", "port": 2881, "username": "user", "password": "",+ "connection_string": "jdbc:oceanbase:oracle://host/service"+ }))+ .unwrap();+ let Json(added) =+ connection::mcp_add_connection(State(state.clone()), Json(McpAddConnectionRequest { config }))+ .await+ .unwrap();+ let value = serde_json::to_value(&added).unwrap();+ assert_eq!(value["jdbc_dialect"], "oceanbase-oracle");+ assert!(value.get("config").is_none());+ let Json(duplicated) = connection::mcp_duplicate_connection(+ State(state.clone()),+ Json(McpDuplicateConnectionRequest {+ source_id: "mcp-jdbc".into(),+ copy_id: "mcp-copy".into(),+ copy_name: "Copy".into(),+ }),+ )+ .await+ .unwrap();+ assert_eq!(serde_json::to_value(&duplicated).unwrap()["jdbc_dialect"], "oceanbase-oracle");+ assert_eq!(duplicated.config.id, "mcp-copy");+ }+#[cfg(feature = "sqlite-sqlcipher")]#[tokio::test]async fn connect_and_test_use_server_held_password_including_temporary_drafts() {diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 6345808035..3cf5424c31 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -791,6 +791,7 @@ async fn serve() -> Result<(), String> {.route("/schema/mysql/auto-increment", get(routes::schema::get_mysql_table_auto_increment)).route("/schema/schemas", get(routes::schema::list_schemas)).route("/schema/tables", get(routes::schema::list_tables))+ .route("/schema/table-comment", get(routes::schema::get_table_comment)).route("/schema/objects", get(routes::schema::list_objects)).route("/schema/object-statistics", get(routes::schema::list_object_statistics)).route("/schema/completion-objects", get(routes::schema::list_completion_objects))diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rsindex 3ff3549ef4..60b441f1d3 100644--- a/crates/dbx-web/src/routes/connection.rs+++ b/crates/dbx-web/src/routes/connection.rs@@ -11,7 +11,7 @@ use dbx_core::connection::{connection_configs_pool_equivalent, connection_configs_session_credentials_compatible, AppState, PoolKind,};use dbx_core::models::connection::{- ConnectionConfig, ConnectionIdleClosedEvent, ConnectionLivenessMessage, ConnectionTestResult,+ ConnectionConfig, ConnectionIdleClosedEvent, ConnectionLivenessMessage, ConnectionResponse, ConnectionTestResult,DatabaseConnectionInfo, DatabaseType,};use dbx_core::nacos::config::{@@ -932,7 +932,7 @@ pub async fn save_connections(pub async fn mcp_add_connection(State(state): State<Arc<WebState>>,Json(body): Json<McpAddConnectionRequest>,-) -> Result<Json<ConnectionConfig>, AppError> {+) -> Result<Json<ConnectionResponse>, AppError> {let config = state.resolve_connection_credentials(body.config).await?;let saved = state.app.storage.add_connection_for_mcp(config).await.map_err(AppError::from)?;state.app.session_credentials.clear_connection(&saved.id);@@ -944,7 +944,7 @@ pub async fn mcp_add_connection(pub async fn mcp_duplicate_connection(State(state): State<Arc<WebState>>,Json(body): Json<McpDuplicateConnectionRequest>,-) -> Result<Json<ConnectionConfig>, AppError> {+) -> Result<Json<ConnectionResponse>, AppError> {let saved = state.app.storage@@ -978,7 +978,7 @@ pub async fn mcp_remove_connection(pub async fn load_connections(State(state): State<Arc<WebState>>,_headers: HeaderMap,-) -> Result<Json<Vec<ConnectionConfig>>, AppError> {+) -> Result<Json<Vec<ConnectionResponse>>, AppError> {let configs = state.app.storage.load_connections().await.map_err(AppError::from)?;let sync = sync_connection_configs(&state, &configs).await;remove_connection_pools_for_connection_ids(&state, &sync.connection_pool_ids_to_drop).await;@@ -2060,14 +2060,14 @@ done.await.unwrap_or_else(|error| panic!("{}", error.message)).0;- assert_eq!(state.app.configs.read().await.get(&copied.id), Some(&copied));+ assert_eq!(state.app.configs.read().await.get(&copied.config.id), Some(&copied.config));let persisted = state.app.storage.load_connections().await.unwrap();assert_eq!(persisted.iter().find(|config| config.id == existing.id).unwrap().host, existing.host);assert!(persisted.iter().any(|config| config.id == added.id));let layout = state.app.storage.load_sidebar_layout().await.unwrap().unwrap();assert_eq!(layout["concurrentField"], "keep");assert_eq!(layout["order"][0]["children"][0]["id"], existing.id);- assert_eq!(layout["order"][0]["children"][1]["id"], copied.id);+ assert_eq!(layout["order"][0]["children"][1]["id"], copied.config.id);assert_eq!(layout["order"][1]["id"], added.id);let _ = std::fs::remove_dir_all(dir);@@ -2588,7 +2588,7 @@ donemcp_add_connection(State(state.clone()), Json(McpAddConnectionRequest { config: recreated.clone() })).await.unwrap_or_else(|error| panic!("{}", error.message));- assert_eq!(reused.0.host, recreated.host);+ assert_eq!(reused.0.config.host, recreated.host);assert!(!state.app.session_credentials.has("token-a", "conn-a"));assert!(!state.app.session_credentials.has("token-b", "conn-a"));assert!(!state.app.session_credentials.has_pool_owner("conn-a"));diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rsindex 3610a3beb2..b963693623 100644--- a/crates/dbx-web/src/routes/schema.rs+++ b/crates/dbx-web/src/routes/schema.rs@@ -32,6 +32,7 @@ pub struct SchemaQuery {pub include_postgres_access: Option<bool>,pub portable: Option<bool>,pub execution_id: Option<String>,+ pub exact_identity: Option<bool>,}async fn run_cancellable<T, F>(state: &Arc<WebState>, execution_id: Option<String>, future: F) -> Result<T, AppError>@@ -244,6 +245,22 @@ pub async fn list_tables(.table_name_filter.as_deref().and_then(|value| serde_json::from_str::<dbx_core::schema::TableNameFilter>(value).ok());+ if q.exact_identity.unwrap_or(false) {+ let result = dbx_core::schema::exact_metadata::tables(+ &state.app,+ &q.connection_id,+ database,+ schema,+ q.filter.as_deref(),+ q.limit,+ q.offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await+ .map_err(AppError::from)?;+ return Ok(Json(serde_json::to_value(result).map_err(|error| AppError::from(error.to_string()))?));+ }let result = if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {dbx_core::schema::list_doris_catalog_tables_core(&state.app,@@ -294,6 +311,20 @@ pub async fn list_objects(.as_deref().and_then(|value| serde_json::from_str::<dbx_core::schema::TableNameFilter>(value).ok());let result = run_cancellable(&state, execution_id, async {+ if q.exact_identity.unwrap_or(false) {+ return dbx_core::schema::exact_metadata::objects(+ &state.app,+ &connection_id,+ &database,+ &schema,+ filter.as_deref(),+ q.limit,+ q.offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await;+ }if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {let tables = dbx_core::schema::list_doris_catalog_tables_core(&state.app,@@ -506,6 +537,21 @@ pub async fn list_columns(let database = q.database.as_deref().unwrap_or("");let schema = q.schema.as_deref().unwrap_or("");let table = q.table.as_deref().unwrap_or("");+ // Exact reads revalidate the current process contract and never reuse a+ // persisted ordinary/synonym-resolved snapshot as an editing baseline.+ if q.exact_identity.unwrap_or(false) {+ let result = dbx_core::schema::exact_metadata::columns(+ &state.app,+ &q.connection_id,+ database,+ schema,+ table,+ q.client_session_id.as_deref(),+ )+ .await+ .map_err(AppError::from)?;+ return Ok(Json(serde_json::to_value(result).map_err(|error| AppError::from(error.to_string()))?));+ }let catalog = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await;let load_columns = || async {if let Some(catalog) = catalog.as_deref() {@@ -573,6 +619,12 @@ pub async fn list_indexes(let database = q.database.as_deref().unwrap_or("");let schema = q.schema.as_deref().unwrap_or("");let table = q.table.as_deref().unwrap_or("");+ if q.exact_identity.unwrap_or(false) {+ let result = dbx_core::schema::exact_metadata::indexes(&state.app, &q.connection_id, database, schema, table)+ .await+ .map_err(AppError::from)?;+ return Ok(Json(serde_json::to_value(result).map_err(|error| AppError::from(error.to_string()))?));+ }let catalog = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await;let result = cached_metadata(&state.app,@@ -651,6 +703,13 @@ pub async fn list_foreign_keys(let database = q.database.as_deref().unwrap_or("");let schema = q.schema.as_deref().unwrap_or("");let table = q.table.as_deref().unwrap_or("");+ if q.exact_identity.unwrap_or(false) {+ let result =+ dbx_core::schema::exact_metadata::foreign_keys(&state.app, &q.connection_id, database, schema, table)+ .await+ .map_err(AppError::from)?;+ return Ok(Json(serde_json::to_value(result).map_err(|error| AppError::from(error.to_string()))?));+ }let catalog = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await;let result = cached_metadata(&state.app,@@ -697,6 +756,25 @@ pub async fn list_foreign_keys_for_database(Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))}+pub async fn get_table_comment(+ State(state): State<Arc<WebState>>,+ Query(q): Query<SchemaQuery>,+) -> Result<Json<Option<String>>, AppError> {+ let database = q.database.as_deref().unwrap_or("");+ let schema = q.schema.as_deref().unwrap_or("");+ let table = q.table.as_deref().unwrap_or("");+ let result = if q.exact_identity.unwrap_or(false) {+ dbx_core::schema::exact_metadata::comment(&state.app, &q.connection_id, database, schema, table).await+ } else if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {+ dbx_core::schema::get_doris_catalog_table_comment_core(&state.app, &q.connection_id, &catalog, database, table)+ .await+ } else {+ dbx_core::schema::get_table_comment_core(&state.app, &q.connection_id, database, schema, table).await+ }+ .map_err(AppError::from)?;+ Ok(Json(result))+}+pub async fn list_triggers(State(state): State<Arc<WebState>>,Query(q): Query<SchemaQuery>,@@ -704,7 +782,11 @@ pub async fn list_triggers(let database = q.database.as_deref().unwrap_or("");let schema = q.schema.as_deref().unwrap_or("");let table = q.table.as_deref().unwrap_or("");- let result = if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {+ let result = if q.exact_identity.unwrap_or(false) {+ dbx_core::schema::exact_metadata::triggers(&state.app, &q.connection_id, database, schema, table)+ .await+ .map_err(AppError::from)?+ } else if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {dbx_core::schema::list_doris_catalog_triggers_core(&state.app, &q.connection_id, &catalog, database, table).await.map_err(AppError::from)?@@ -724,9 +806,12 @@ pub async fn list_constraints(let schema = q.schema.as_deref().unwrap_or("");let table = q.table.as_deref().unwrap_or("");let _ = q.catalog.as_deref();- let result = dbx_core::schema::list_constraints_core(&state.app, &q.connection_id, database, schema, table)- .await- .map_err(AppError::from)?;+ let result = if q.exact_identity.unwrap_or(false) {+ dbx_core::schema::exact_metadata::constraints(&state.app, &q.connection_id, database, schema, table).await+ } else {+ dbx_core::schema::list_constraints_core(&state.app, &q.connection_id, database, schema, table).await+ }+ .map_err(AppError::from)?;Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))}@@ -802,7 +887,19 @@ pub async fn get_ddl(let database = q.database.as_deref().unwrap_or("");let schema = q.schema.as_deref().unwrap_or("");let table = q.table.as_deref().unwrap_or("");- let result = if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {+ let result = if q.exact_identity.unwrap_or(false) {+ dbx_core::schema::exact_metadata::ddl(+ &state.app,+ &q.connection_id,+ database,+ schema,+ table,+ q.object_type,+ q.portable.unwrap_or(false),+ )+ .await+ .map_err(AppError::from)?+ } else if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {dbx_core::schema::get_doris_catalog_table_ddl_core(&state.app, &q.connection_id, &catalog, database, table).await.map_err(AppError::from)?diff --git a/docs/content/docs/object-browser.cn.mdx b/docs/content/docs/object-browser.cn.mdxindex 91debf95fc..a8d9d68f5b 100644--- a/docs/content/docs/object-browser.cn.mdx+++ b/docs/content/docs/object-browser.cn.mdx@@ -50,6 +50,27 @@ description: 使用列表或网格集中查看数据库对象、统计信息、具体操作由数据库 capability、连接只读状态和当前权限决定。+## 从 Schema 管理索引++Oracle、OceanBase Oracle 和达梦支持 Schema 索引分组与对象浏览器的**索引**筛选,也适用于对应方言的 JDBC 连接。OceanBase JDBC 须明确使用 Oracle 模式 URL;普通 OceanBase/MySQL URL 不会被推断为 Oracle 模式。新入口需要驱动提供精确对象身份;提示无法核实时,更新 Agent 或 JDBC 插件并重新连接。原表级入口保持原有使用条件。++Schema 索引只在索引分组或**索引**筛选中按页加载,不混入**全部**列表。窄窗口中可从工具栏的更多操作菜单切换筛选。++### 新增第一个索引++1. 打开 Schema 的索引分组菜单,或切换对象浏览器的**索引**筛选,点击**新增索引**。空列表也提供此入口。+2. 搜索并选择当前连接、数据库和 Schema 中可见的父表,确认后进入该表的结构编辑器。选表和导航不执行 DDL。+3. 在自动添加的索引草稿中选择列、填写名称,检查 SQL 预览,再应用。生产连接仍须经过原有确认。++### 查看、修改和删除++- 在索引筛选中搜索名称,使用**加载更多**查看后续结果,或刷新当前列表。复制名称保留字典中的大小写和空格。+- 查看索引时,信息面板读取真实父表的索引、列和 DDL。同 owner 索引可进入父表结构编辑器,并精确定位原索引;已有未保存草稿会保留。+- 修改索引后,检查可能包含删除和重建的 SQL,再应用。**删除索引**或 Delete 只进入父表的删除草稿,不直接执行 `DROP INDEX`;应用前可撤销删除标记。+- 索引与父表 owner 不同,或无法核实索引 owner 时,新入口只读查看;缺少父表身份时保留复制和刷新,不猜测目标。约束支撑索引、不完整元数据和不支持的索引类型仍由原编辑器阻断或引导处理。++已应用后若元数据刷新失败,界面保留已应用结果并提供刷新重试;重试不会重新执行 DDL。部分成功或结果未知时,先核对逐条结果并刷新数据库状态,再处理剩余草稿。+## 多选与批量操作对象浏览器支持复选框多选。批量操作可能包括:@@ -57,7 +78,7 @@ description: 使用列表或网格集中查看数据库对象、统计信息、- 打开或复制多个对象名称- 批量导出或生成 SQL- 删除、清空或截断所选表-- 删除所选索引+- Schema 索引按父表逐项管理,不执行集中批量删除,也不参与表复制和表导出- 对 PostgreSQL 等数据库使用带 `CASCADE` 的批量对象操作<Callout type="warn">批量删除、清空和截断可能影响大量对象。生产环境先确认所选范围、生成 SQL、备份和依赖关系。</Callout>diff --git a/docs/content/docs/object-browser.mdx b/docs/content/docs/object-browser.mdxindex 84ce7176ef..69183698fa 100644--- a/docs/content/docs/object-browser.mdx+++ b/docs/content/docs/object-browser.mdx@@ -50,6 +50,27 @@ Context menus can also provide:Available actions depend on database capabilities, connection read-only state, and account privileges.+## Manage Indexes from a Schema++Oracle, OceanBase Oracle, and Dameng provide a schema index group and an **Indexes** filter, including connections using their corresponding JDBC dialects. OceanBase JDBC must explicitly use an Oracle-mode URL; an ordinary OceanBase/MySQL URL does not select Oracle mode. The new entry requires verified exact object identities. If verification is unavailable, update the Agent or JDBC plugin and reconnect. Existing table-level entry points retain their original requirements.++Schema indexes load in pages through the index group or **Indexes** filter, not the **All** list. In narrow windows, change the filter through the toolbar's more-actions menu.++### Create the First Index++1. Choose **Add Index** from the schema index group menu or the object browser's **Indexes** filter. The action is available even when the list is empty.+2. Search for a visible parent table in the current connection, database, and schema. Confirm to open that table's structure editor. Selection and navigation execute no DDL.+3. Complete the automatically added index draft, review the SQL, and apply it. Production connections retain the existing confirmation step.++### Inspect, Edit, and Drop++- Search the index list, load more results, or refresh it. Copying a name preserves dictionary spelling, case, and spaces.+- Inspection reads the actual parent table's indexes, columns, and DDL. A same-owner index can open the table structure editor at the exact original index without discarding existing drafts.+- Review the SQL before applying an edit: it may drop and rebuild the index. **Drop Index** or Delete opens a deletion draft in the parent editor; it does not execute `DROP INDEX` directly. Unmark the deletion before applying to cancel it.+- Cross-owner indexes and indexes with an unverified owner are read-only through the new entry. Missing parent identities retain copy and refresh actions without guessing a target. Constraint-backed indexes, incomplete metadata, and unsupported variants retain the editor's existing checks and guidance.++If metadata refresh fails after an applied operation, the result remains applied and refresh can be retried without executing DDL again. For partial or unknown results, inspect each statement and refresh the database state before handling the remaining drafts.+## Multi-Select and Bulk ActionsUse checkboxes to select multiple objects. Depending on the database, bulk actions can include:@@ -57,7 +78,7 @@ Use checkboxes to select multiple objects. Depending on the database, bulk actio- Open or copy multiple object names- Export or generate SQL in bulk- Drop, empty, or truncate selected tables-- Drop selected indexes+- Manage schema indexes individually through their parent tables, without central batch drop, table copy, or table export- Use cascade-aware batch actions for PostgreSQL and similar databases<Callout type="warn">Bulk drop, empty, and truncate operations can affect many objects. In production, verify selection, generated SQL, backups, and dependencies first.</Callout>diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.javaindex cf5e064cba..d667a80c69 100644--- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java@@ -182,6 +182,7 @@ public final class DbxJdbcPlugin {new JdbcDriverQuirkRule("jdbc:yasdb:", YASHAN_QUIRKS),new JdbcDriverQuirkRule("jdbc:iris:", IRIS_QUIRKS),new JdbcDriverQuirkRule("jdbc:oracle:", ORACLE_QUIRKS),+ new JdbcDriverQuirkRule("jdbc:oceanbase:oracle://", ORACLE_QUIRKS),new JdbcDriverQuirkRule("jdbc:dm:", ORACLE_QUIRKS),new JdbcDriverQuirkRule("jdbc:taos:", TAOS_QUIRKS),new JdbcDriverQuirkRule("jdbc:taos-ws:", TAOS_QUIRKS),@@ -629,7 +630,9 @@ public final class DbxJdbcPlugin {JsonNode params = request.path("params");connection = params.path("connection");if ("jdbcSessionProtocol".equals(method)) {- response.set("result", MAPPER.createObjectNode().put("version", 2));+ ObjectNode protocol = MAPPER.createObjectNode().put("version", 2);+ protocol.set("capabilities", MAPPER.createArrayNode().add("exact_metadata_identity_v1"));+ response.set("result", protocol);return response;}if (params.hasNonNull("jdbcSessionId")) {@@ -733,6 +736,10 @@ public final class DbxJdbcPlugin {private static JsonNode handle(String method, JsonNode params, JsonNode connection) throws Exception {String database = optionalText(params, "database");+ boolean exactIdentity = params.path("exact_identity").asBoolean(false);+ if (exactIdentity && !driverQuirks(connection).useOracleMetadata()) {+ throw new SQLException("Exact metadata identity is not supported for this JDBC dialect");+ }if (isPostgresJdbcUrl(optionalText(connection, "connection_string"))) {database = postgresDatabase(params);if (database != null) {@@ -797,40 +804,40 @@ public final class DbxJdbcPlugin {case "listTables" -> listTables(connection,database,- optionalText(params, "schema"),+ metadataText(params, "schema", exactIdentity),optionalText(params, "filter"),nonNegativeInt(params, "limit", 0),nonNegativeInt(params, "offset", 0),- optionalStringList(params, "object_types")+ optionalStringList(params, "object_types"), exactIdentity);case "listObjects", "list_objects" -> listObjects(connection,database,- optionalText(params, "schema"),+ metadataText(params, "schema", exactIdentity),optionalText(params, "filter"),nonNegativeInt(params, "limit", 0),nonNegativeInt(params, "offset", 0),- optionalStringList(params, "object_types")+ optionalStringList(params, "object_types"), exactIdentity);case "listIndexes", "list_indexes" -> listIndexes(connection,database,- optionalText(params, "schema"),- requireText(params, "table")+ metadataText(params, "schema", exactIdentity),+ metadataText(params, "table", exactIdentity), exactIdentity);case "listDataTypes", "list_data_types" -> listDataTypes(connection, database);case "getObjectSource", "get_object_source" -> getObjectSource(connection,database,- optionalText(params, "schema"),- requireText(params, "name"),- requireText(params, "object_type")+ metadataText(params, "schema", exactIdentity),+ exactIdentity ? metadataText(params, "name", true) : requireText(params, "name"),+ requireText(params, "object_type"), exactIdentity);case "getColumns" -> getColumns(connection,database,- optionalText(params, "schema"),- requireText(params, "table")+ metadataText(params, "schema", exactIdentity),+ metadataText(params, "table", exactIdentity), exactIdentity);case "getExplainInfo" -> getExplainInfo(connection,@@ -2700,14 +2707,15 @@ public final class DbxJdbcPlugin {String filter,int limit,int offset,- List<String> objectTypes+ List<String> objectTypes,+ boolean exactIdentity) throws SQLException {ArrayNode result = MAPPER.createArrayNode();Connection conn = openConnection(connection);JdbcDriverQuirks quirks = driverQuirks(connection);if (quirks.useOracleMetadata()) {return filterMetadataNodes(- (ArrayNode) oracleListTables(conn, oracleEffectiveSchema(conn, schema)),+ (ArrayNode) oracleListTables(conn, exactIdentity ? schema : oracleEffectiveSchema(conn, schema), exactIdentity),filter,limit,offset,@@ -2751,13 +2759,21 @@ public final class DbxJdbcPlugin {String filter,int limit,int offset,- List<String> objectTypes+ List<String> objectTypes,+ boolean exactIdentity) throws SQLException {ArrayNode result = MAPPER.createArrayNode();Connection conn = openConnection(connection);if (driverQuirks(connection).useOracleMetadata()) {+ String owner = exactIdentity ? schema : oracleEffectiveSchema(conn, schema);+ Set<String> types = normalizedObjectTypes(objectTypes);+ boolean indexes = types.contains("INDEX") || (exactIdentity && types.isEmpty());+ ArrayNode objects = types.size() == 1 && indexes ? MAPPER.createArrayNode() : (ArrayNode) oracleListObjects(conn, owner, schema);+ if (indexes) {+ appendOracleSchemaIndexes(conn, owner, objects);+ }return filterMetadataNodes(- (ArrayNode) oracleListObjects(conn, oracleEffectiveSchema(conn, schema), schema),+ objects,filter,limit,offset,@@ -3012,14 +3028,18 @@ public final class DbxJdbcPlugin {return result;}- private static JsonNode listIndexes(JsonNode connection, String database, String schema, String table)+ private static JsonNode listIndexes(JsonNode connection, String database, String schema, String table) throws SQLException {+ return listIndexes(connection, database, schema, table, false);+ }++ private static JsonNode listIndexes(JsonNode connection, String database, String schema, String table, boolean exactIdentity)throws SQLException {Connection conn = openConnection(connection);JdbcDriverQuirks quirks = driverQuirks(connection);if (quirks.useOracleMetadata()) {- String owner = oracleEffectiveSchema(conn, schema);- String resolvedTable = oracleResolveTable(conn, owner, table);- return oracleListIndexes(conn, owner, resolvedTable == null ? table : resolvedTable);+ String owner = exactIdentity ? schema : oracleEffectiveSchema(conn, schema);+ String resolvedTable = exactIdentity ? table : oracleResolveTable(conn, owner, table);+ return oracleListIndexes(conn, owner, resolvedTable == null ? table : resolvedTable, exactIdentity);}DatabaseMetaData meta = conn.getMetaData();@@ -3165,10 +3185,14 @@ public final class DbxJdbcPlugin {}private static JsonNode getColumns(JsonNode connection, String database, String schema, String table) throws SQLException {+ return getColumns(connection, database, schema, table, false);+ }++ private static JsonNode getColumns(JsonNode connection, String database, String schema, String table, boolean exactIdentity) throws SQLException {ArrayNode result = MAPPER.createArrayNode();Connection conn = openConnection(connection);if (driverQuirks(connection).useOracleMetadata()) {- return oracleGetColumns(conn, oracleEffectiveSchema(conn, schema), table);+ return oracleGetColumns(conn, exactIdentity ? schema : oracleEffectiveSchema(conn, schema), table, exactIdentity);}if (isKingbaseUrl(optionalText(connection, "connection_string"))) {return kingbaseGetColumns(conn, schema, table);@@ -4456,6 +4480,10 @@ public final class DbxJdbcPlugin {}private static JsonNode oracleListTables(Connection conn, String owner) throws SQLException {+ return oracleListTables(conn, owner, false);+ }++ private static JsonNode oracleListTables(Connection conn, String owner, boolean exactIdentity) throws SQLException {ArrayNode result = MAPPER.createArrayNode();String sql ="SELECT table_name AS name, 'TABLE' AS table_type, comments " +@@ -4478,6 +4506,7 @@ public final class DbxJdbcPlugin {return result;}} catch (SQLException e) {+ if (exactIdentity) throw e;result.removeAll();try {appendTables(result, conn.getMetaData(), null, owner, new String[]{"TABLE", "VIEW"}, null, 0, 0);@@ -4598,24 +4627,54 @@ public final class DbxJdbcPlugin {}private static JsonNode oracleListIndexes(Connection conn, String owner, String table) throws SQLException {+ return oracleListIndexes(conn, owner, table, false);+ }++ private static void appendOracleSchemaIndexes(Connection conn, String owner, ArrayNode result) throws SQLException {+ String sql = "SELECT owner, index_name, table_owner, table_name FROM all_indexes WHERE owner = ? ORDER BY index_name";+ try (PreparedStatement statement = conn.prepareStatement(sql)) {+ statement.setString(1, owner);+ try (ResultSet rows = statement.executeQuery()) {+ while (rows.next()) {+ ObjectNode index = MAPPER.createObjectNode();+ index.put("name", rows.getString("index_name"));+ index.put("object_type", "INDEX");+ putNullable(index, "schema", rows.getString("owner"));+ putNullable(index, "parent_schema", rows.getString("table_owner"));+ putNullable(index, "parent_name", rows.getString("table_name"));+ index.putNull("comment");+ result.add(index);+ }+ }+ }+ }++ private static JsonNode oracleListIndexes(Connection conn, String owner, String table, boolean exactIdentity) throws SQLException {String sql =- "SELECT i.index_name, i.uniqueness, i.index_type, ic.column_name, " +- "CASE WHEN pk.index_name IS NULL THEN 0 ELSE 1 END AS is_primary " ++ "SELECT ie.column_expression, i.index_name, i.uniqueness, i.index_type, ic.column_name, " ++ "ic.column_position, i.partitioned, i.visibility, ic.descend, " ++ "CASE WHEN pk.index_name IS NULL THEN 0 ELSE 1 END AS is_primary, i.owner AS index_owner " +"FROM all_indexes i " +"JOIN all_ind_columns ic ON ic.index_owner = i.owner AND ic.index_name = i.index_name " +"AND ic.table_owner = i.table_owner AND ic.table_name = i.table_name " +- "LEFT JOIN (SELECT owner, index_name, table_name FROM all_constraints WHERE constraint_type = 'P') pk " +- "ON pk.owner = i.owner AND pk.index_name = i.index_name AND pk.table_name = i.table_name " ++ "LEFT JOIN all_ind_expressions ie ON ie.index_owner = ic.index_owner AND ie.index_name = ic.index_name " ++ "AND ie.table_owner = ic.table_owner AND ie.table_name = ic.table_name AND ie.column_position = ic.column_position " ++ "LEFT JOIN (SELECT owner, index_owner, index_name, table_name FROM all_constraints WHERE constraint_type = 'P') pk " ++ "ON pk.owner = i.table_owner AND pk.index_owner = i.owner AND pk.index_name = i.index_name AND pk.table_name = i.table_name " +"WHERE i.table_owner = ? AND i.table_name = ? " +- "ORDER BY i.index_name, ic.column_position";+ "ORDER BY i.owner, i.index_name, ic.column_position";LinkedHashMap<String, ObjectNode> indexes = new LinkedHashMap<>();try (PreparedStatement ps = conn.prepareStatement(sql)) {ps.setString(1, owner);ps.setString(2, table);try (ResultSet rs = ps.executeQuery()) {while (rs.next()) {+ // COLUMN_EXPRESSION is LONG on Oracle; read it before the other fields.+ String expression = rs.getString("column_expression");String name = rs.getString("index_name");- ObjectNode item = indexes.get(name);+ String indexOwner = rs.getString("index_owner");+ String identity = MAPPER.createArrayNode().add(indexOwner).add(name).toString();+ ObjectNode item = indexes.get(identity);if (item == null) {item = indexNode(name,@@ -4623,15 +4682,34 @@ public final class DbxJdbcPlugin {rs.getInt("is_primary") != 0,rs.getString("index_type"));- indexes.put(name, item);+ item.set("key_is_expression", MAPPER.createArrayNode());+ putNullable(item, "owner", indexOwner);+ item.set("key_directions", MAPPER.createArrayNode());+ putNullable(item, "visibility", rs.getString("visibility"));+ item.put("key_metadata_complete", true);+ indexes.put(identity, item);}String column = rs.getString("column_name");- if (column != null && !column.isBlank()) {- ((ArrayNode) item.path("columns")).add(column);+ boolean isExpression = expression != null && !expression.isBlank();+ String direction = rs.getString("descend");+ String visibility = rs.getString("visibility");+ String indexType = rs.getString("index_type");+ if (rs.getInt("column_position") != item.path("columns").size() + 1+ || !("ASC".equals(direction) || "DESC".equals(direction))+ || !("VISIBLE".equals(visibility) || "INVISIBLE".equals(visibility))+ || !java.util.Objects.equals(item.path("visibility").asText(null), visibility)+ || !"NO".equals(rs.getString("partitioned"))+ || !("NORMAL".equals(indexType) || "FUNCTION-BASED NORMAL".equals(indexType))+ || (!isExpression && (column == null || column.isEmpty() || (column.startsWith("SYS_NC") && column.endsWith("$"))))) {+ item.put("key_metadata_complete", false);}+ ((ArrayNode) item.path("columns")).add(isExpression ? expression : column == null ? "" : column);+ ((ArrayNode) item.path("key_is_expression")).add(isExpression);+ ((ArrayNode) item.path("key_directions")).add(direction == null ? "" : direction);}}} catch (SQLException e) {+ if (exactIdentity) throw e;indexes.clear();try {DatabaseMetaData meta = conn.getMetaData();@@ -4663,10 +4741,15 @@ public final class DbxJdbcPlugin {}private static JsonNode getObjectSource(JsonNode connection, String database, String schema, String name, String objectType)+ throws SQLException {+ return getObjectSource(connection, database, schema, name, objectType, false);+ }++ private static JsonNode getObjectSource(JsonNode connection, String database, String schema, String name, String objectType, boolean exactIdentity)throws SQLException {Connection conn = openConnection(connection);if (driverQuirks(connection).useOracleMetadata()) {- String owner = oracleEffectiveSchema(conn, schema);+ String owner = exactIdentity ? schema : oracleEffectiveSchema(conn, schema);String metadataType = oracleMetadataObjectType(objectType);String sql = "SELECT DBMS_METADATA.GET_DDL(?, ?, ?) FROM DUAL";try (PreparedStatement ps = conn.prepareStatement(sql)) {@@ -5092,14 +5175,18 @@ public final class DbxJdbcPlugin {}private static JsonNode oracleGetColumns(Connection conn, String owner, String table) throws SQLException {+ return oracleGetColumns(conn, owner, table, false);+ }++ private static JsonNode oracleGetColumns(Connection conn, String owner, String table, boolean exactIdentity) throws SQLException {ArrayNode result = MAPPER.createArrayNode();- String resolvedTable = oracleResolveTable(conn, owner, table);- Set<String> pks = oraclePrimaryKeys(conn, owner, resolvedTable);+ String resolvedTable = exactIdentity ? table : oracleResolveTable(conn, owner, table);+ Set<String> pks = oraclePrimaryKeys(conn, owner, resolvedTable, exactIdentity);// data_default is a LONG column — it must be read first in JDBC, before any other// column, otherwise the data is truncated. We put it at position 1 for this reason.String sql ="SELECT c.data_default, c.column_name, c.data_type, c.nullable, " +- "c.data_precision, c.data_scale, c.char_length, cc.comments " ++ "c.data_precision, c.data_scale, c.char_length, c.data_length, c.char_used, cc.comments " +"FROM all_tab_columns c " +"LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name AND cc.column_name = c.column_name " +"WHERE c.owner = ? AND c.table_name = ? ORDER BY c.column_id";@@ -5112,7 +5199,7 @@ public final class DbxJdbcPlugin {String dataDefault = rs.getString("data_default");String name = rs.getString("column_name");ObjectNode item = columnNode(result, name);- item.put("data_type", rs.getString("data_type"));+ item.put("data_type", oracleColumnDataType(rs));item.put("is_nullable", !"N".equals(rs.getString("nullable")));putNullablePreferValue(item, "column_default", dataDefault);item.put("is_primary_key", pks.contains(name));@@ -5125,6 +5212,7 @@ public final class DbxJdbcPlugin {return result;}} catch (SQLException e) {+ if (exactIdentity) throw e;result.removeAll();try {DatabaseMetaData meta = conn.getMetaData();@@ -5136,7 +5224,47 @@ public final class DbxJdbcPlugin {}}+ private static String oracleColumnDataType(ResultSet rows) throws SQLException {+ String base = rows.getString("data_type");+ if (base == null || base.isBlank()) return "";+ Integer precision = oracleMetadataInteger(rows, "data_precision");+ Integer scale = oracleMetadataInteger(rows, "data_scale");+ Integer bytes = oracleMetadataInteger(rows, "data_length");+ Integer characters = oracleMetadataInteger(rows, "char_length");+ String unit = rows.getString("char_used");+ return switch (base.toUpperCase(Locale.ROOT)) {+ case "VARCHAR2", "CHAR" -> {+ if ("B".equalsIgnoreCase(unit) && bytes != null) yield base + "(" + bytes + " BYTE)";+ if ("C".equalsIgnoreCase(unit) && characters != null) yield base + "(" + characters + " CHAR)";+ Integer length = characters == null ? bytes : characters;+ yield length == null ? base : base + "(" + length + ")";+ }+ case "NVARCHAR2", "NCHAR" -> {+ Integer length = characters == null ? bytes : characters;+ yield length == null ? base : base + "(" + length + ")";+ }+ case "NUMBER" -> {+ if (precision == null && scale != null) yield base + "(*," + scale + ")";+ if (precision != null && scale != null && scale != 0) yield base + "(" + precision + "," + scale + ")";+ if (precision != null && precision > 0) yield base + "(" + precision + ")";+ yield base;+ }+ case "FLOAT" -> precision != null && precision > 0 ? base + "(" + precision + ")" : base;+ case "RAW" -> bytes == null ? base : base + "(" + bytes + ")";+ default -> base;+ };+ }++ private static Integer oracleMetadataInteger(ResultSet rows, String column) throws SQLException {+ Object value = rows.getObject(column);+ return value instanceof Number number ? number.intValue() : null;+ }+private static Set<String> oraclePrimaryKeys(Connection conn, String owner, String table) throws SQLException {+ return oraclePrimaryKeys(conn, owner, table, false);+ }++ private static Set<String> oraclePrimaryKeys(Connection conn, String owner, String table, boolean exactIdentity) throws SQLException {String sql ="SELECT cols.column_name FROM all_constraints cons " +"JOIN all_cons_columns cols ON cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner " +@@ -5152,6 +5280,7 @@ public final class DbxJdbcPlugin {return keys;}} catch (SQLException e) {+ if (exactIdentity) throw e;return safePrimaryKeys(conn.getMetaData(), null, owner, table);}}@@ -5549,6 +5678,13 @@ public final class DbxJdbcPlugin {return value;}+ private static String metadataText(JsonNode node, String field, boolean exactIdentity) {+ if (!exactIdentity) return "table".equals(field) ? requireText(node, field) : optionalText(node, field);+ JsonNode value = node.path(field);+ if (!value.isTextual() || value.asText().isEmpty()) throw new IllegalArgumentException(field + " is required for exact metadata identity");+ return value.asText();+ }+private static String optionalText(JsonNode node, String field) {JsonNode value = node.path(field);if (value.isMissingNode() || value.isNull()) {diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.javaindex 2e18e15198..0524b94d3a 100644--- a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java@@ -64,6 +64,18 @@ final class DbxJdbcPluginTest {""".formatted(CONNECTION));}+ @Test+ void jdbcProtocolExplicitlyAdvertisesExactMetadataAndRejectsUnconfirmedDialects() throws Exception {+ JsonNode protocol = request("jdbcSessionProtocol", "{}").path("result");+ assertEquals(2, protocol.path("version").asInt());+ assertTrue(protocol.path("capabilities").toString().contains("exact_metadata_identity_v1"));+ JsonNode ordinary = request("getColumns", """+ {"connection":%s,"schema":"PUBLIC","table":"T","exact_identity":true}+ """.formatted(CONNECTION));+ assertTrue(ordinary.has("error"), ordinary.toString());+ assertTrue(ordinary.path("error").path("message").asText().contains("Exact metadata identity"));+ }+@Testvoid parsesTdengineTimezoneDescription() {assertEquals(ZoneId.of("Asia/Shanghai"), DbxJdbcPlugin.parseTdengineTimezone("Asia/Shanghai (CST, +0800)"));@@ -3333,11 +3345,11 @@ final class DbxJdbcPluginTest {@Testvoid oracleListIndexesGroupsColumnsAndMarksPrimaryKey() throws Exception {ResultSet rows = rowsResultSet(- new String[] { "index_name", "uniqueness", "index_type", "column_name", "is_primary" },+ new String[] { "index_name", "uniqueness", "index_type", "column_name", "is_primary", "column_position", "partitioned", "visibility", "descend", "column_expression" },new Object[][] {- { "CODEX_7046_CODE_IDX", "NONUNIQUE", "NORMAL", "CODE", 0 },- { "CODEX_7046_PK", "UNIQUE", "NORMAL", "ID", 1 },- { "CODEX_7046_PK", "UNIQUE", "NORMAL", "TENANT_ID", 1 }+ { "CODEX_7046_CODE_IDX", "NONUNIQUE", "NORMAL", "CODE", 0, 1, "NO", "VISIBLE", "ASC", null },+ { "CODEX_7046_PK", "UNIQUE", "NORMAL", "ID", 1, 1, "NO", "VISIBLE", "ASC", null },+ { "CODEX_7046_PK", "UNIQUE", "NORMAL", "TENANT_ID", 1, 2, "NO", "VISIBLE", "ASC", null }});Connection conn = preparedStatementConnection(rows);@@ -3361,6 +3373,156 @@ final class DbxJdbcPluginTest {assertEquals(false, secondary.path("is_unique").asBoolean());}+ @Test+ void oracleIndexMetadataPreservesGuardFidelity() throws Exception {+ ResultSet rows = rowsResultSet(+ new String[]{"index_name", "uniqueness", "index_type", "column_name", "is_primary", "column_position", "partitioned", "visibility", "descend", "column_expression", "index_owner"},+ new Object[][]{+ {" Ix(a) ", "NONUNIQUE", "FUNCTION-BASED NORMAL", "SYS_NC0001$", 0, 1, "NO", "INVISIBLE", "DESC", "LOWER(\" Code \" )", " Index Owner "},+ {" Ix(a) ", "NONUNIQUE", "FUNCTION-BASED NORMAL", "ID", 0, 2, "NO", "INVISIBLE", "ASC", null, " Index Owner "},+ {"UNKNOWN", "UNIQUE", "NORMAL", "ID", 0, 1, null, "VISIBLE", "ASC", null, "Other"}+ });+ Method method = DbxJdbcPlugin.class.getDeclaredMethod("oracleListIndexes", Connection.class, String.class, String.class);+ method.setAccessible(true);+ JsonNode indexes = (JsonNode) method.invoke(null, preparedStatementConnection(rows), "Owner", " T(a) ");++ JsonNode index = findByName(indexes, " Ix(a) ");+ assertEquals(" Index Owner ", index.path("owner").asText());+ assertEquals("LOWER(\" Code \" )", index.path("columns").path(0).asText());+ assertEquals(true, index.path("key_is_expression").path(0).asBoolean());+ assertEquals(false, index.path("key_is_expression").path(1).asBoolean());+ assertEquals("DESC", index.path("key_directions").path(0).asText());+ assertEquals("ASC", index.path("key_directions").path(1).asText());+ assertEquals("INVISIBLE", index.path("visibility").asText());+ assertEquals(true, index.path("key_metadata_complete").asBoolean());+ assertEquals(false, findByName(indexes, "UNKNOWN").path("key_metadata_complete").asBoolean());+ }++ @Test+ void exactOracleMetadataReadsLongValuesBeforeOtherColumns() throws Exception {+ ResultSet columns = longFirstResultSet("data_default", new String[] {+ "data_default", "column_name", "data_type", "nullable", "data_precision", "data_scale",+ "char_length", "data_length", "char_used", "comments"+ }, new Object[][] {+ {"'first default'", " Code ", "VARCHAR2", "Y", null, null, 8, 32, "C", "raw column"},+ {null, "ID", "NUMBER", "N", 12, 0, null, 22, null, null}+ });+ ResultSet indexes = longFirstResultSet("column_expression", new String[] {+ "column_expression", "index_name", "uniqueness", "index_type", "column_name", "column_position",+ "partitioned", "visibility", "descend", "is_primary", "index_owner"+ }, new Object[][] {+ {"LOWER(\" Code \")", " Ix (a) ", "NONUNIQUE", "FUNCTION-BASED NORMAL", "SYS_NC0001$", 1, "NO", "VISIBLE", "ASC", 0, " Index Owner "},+ {null, " Ix (a) ", "NONUNIQUE", "FUNCTION-BASED NORMAL", "ID", 2, "NO", "VISIBLE", "DESC", 0, " Index Owner "}+ });+ Connection conn = (Connection) Proxy.newProxyInstance(+ DbxJdbcPluginTest.class.getClassLoader(), new Class<?>[] {Connection.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "prepareStatement" -> {+ String sql = String.valueOf(args[0]);+ if (sql.contains("FROM all_constraints cons")) {+ yield preparedStatement(rowsResultSet(new String[] {"column_name"}, new Object[][] {{"ID"}}));+ }+ yield preparedStatement(sql.contains("FROM all_tab_columns c") ? columns : indexes);+ }+ case "isClosed" -> false;+ default -> defaultValue(method.getReturnType());+ });+ String config = "{\"connection_string\":\"jdbc:oracle:dbx-long-first\"}";+ Driver driver = testDriver("jdbc:oracle:dbx-long-first", conn);+ DriverManager.registerDriver(driver);+ try {+ JsonNode columnResponse = request("getColumns", """+ {"connection":%s,"schema":"Owner","table":" T(a) ","exact_identity":true}+ """.formatted(config));+ assertFalse(columnResponse.has("error"), columnResponse.toString());+ assertEquals("'first default'", columnResponse.path("result").path(0).path("column_default").asText());+ assertEquals("VARCHAR2(8 CHAR)", columnResponse.path("result").path(0).path("data_type").asText());+ assertTrue(columnResponse.path("result").path(1).path("is_primary_key").asBoolean());+ JsonNode indexResponse = request("listIndexes", """+ {"connection":%s,"schema":"Owner","table":" T(a) ","exact_identity":true}+ """.formatted(config));+ assertFalse(indexResponse.has("error"), indexResponse.toString());+ JsonNode index = indexResponse.path("result").path(0);+ assertEquals(" Index Owner ", index.path("owner").asText());+ assertEquals("LOWER(\" Code \")", index.path("columns").path(0).asText());+ assertEquals("ID", index.path("columns").path(1).asText());+ assertTrue(index.path("key_metadata_complete").asBoolean());+ } finally {+ closeAndDeregister(config, driver);+ }+ }++ @Test+ void exactOracleIndexesSeparateEqualNamesByDictionaryOwner() throws Exception {+ ResultSet rows = rowsResultSet(+ new String[]{"index_name", "uniqueness", "index_type", "column_name", "is_primary", "column_position", "partitioned", "visibility", "descend", "column_expression", "index_owner"},+ new Object[][]{+ {" Ix(a) ", "NONUNIQUE", "NORMAL", "ID", 0, 1, "NO", "VISIBLE", "ASC", null, " Index Owner "},+ {" Ix(a) ", "NONUNIQUE", "NORMAL", "CODE", 0, 1, "NO", "VISIBLE", "ASC", null, "Other"}+ });+ Method method = DbxJdbcPlugin.class.getDeclaredMethod("oracleListIndexes", Connection.class, String.class, String.class, boolean.class);+ method.setAccessible(true);+ JsonNode indexes = (JsonNode) method.invoke(null, preparedStatementConnection(rows), " Parent ", " T(a) ", true);+ assertEquals(2, indexes.size());+ assertEquals(" Index Owner ", indexes.get(0).path("owner").asText());+ assertEquals("Other", indexes.get(1).path("owner").asText());+ assertEquals(1, indexes.get(0).path("columns").size());+ assertEquals(1, indexes.get(1).path("columns").size());+ }++ @Test+ void exactOracleColumnsPropagatePrimaryKeyDictionaryFailure() throws Exception {+ try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:exact_pk_failure", "sa", "")) {+ conn.createStatement().execute("CREATE SCHEMA DM6_SCHEMA");+ conn.createStatement().execute("CREATE TABLE DM6_SCHEMA.DM6_TABLE (id INT PRIMARY KEY)");+ String config = "{\"connection_string\":\"jdbc:oracle:dbx-exact-pk-error\"}";+ Driver driver = testDriver("jdbc:oracle:dbx-exact-pk-error", conn);+ DriverManager.registerDriver(driver);+ try {+ JsonNode response = request("getColumns", """+ {"connection":%s,"schema":"DM6_SCHEMA","table":"DM6_TABLE","exact_identity":true}+ """.formatted(config));+ assertTrue(response.has("error"), response.toString());+ assertTrue(response.path("error").path("message").asText().toLowerCase().contains("all_constraints"), response.toString());+ } finally {+ closeAndDeregister(config, driver);+ }+ }+ }++ @Test+ void explicitOracleFamilyIndexRequestsPreserveBothOwnersAndPageOnce() throws Exception {+ for (String prefix : List.of("jdbc:oracle:", "jdbc:dm:", "jdbc:oceanbase:oracle://")) {+ try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:schema_index_" + prefix.hashCode(), "sa", "")) {+ conn.createStatement().execute("CREATE TABLE all_indexes (owner VARCHAR, index_name VARCHAR, table_owner VARCHAR, table_name VARCHAR)");+ conn.createStatement().execute("INSERT INTO all_indexes VALUES (' Index Owner ', ' Ix (a) ', 'Table Owner', ' T(a) '), (' Index Owner ', 'IxB', 'Table Owner', 'T'), (' Index Owner ', 'IxC', 'Table Owner', 'T'), ('INDEX OWNER', 'WRONG', 'WRONG', 'WRONG')");+ String config = MAPPER.createObjectNode().put("connection_string", prefix + "dbx-index-exact").toString();+ Driver driver = testDriver(prefix, conn);+ DriverManager.registerDriver(driver);+ try {+ JsonNode response = request("listObjects", """+ {"connection":%s,"schema":" Index Owner ","object_types":["INDEX"],"exact_identity":true,"limit":1,"offset":0}+ """.formatted(config));+ assertFalse(response.has("error"), response.toString());+ JsonNode index = response.path("result").path(0);+ assertEquals(1, response.path("result").size());+ assertEquals(" Ix (a) ", index.path("name").asText());+ assertEquals(" Index Owner ", index.path("schema").asText());+ assertEquals("Table Owner", index.path("parent_schema").asText());+ assertEquals(" T(a) ", index.path("parent_name").asText());+ JsonNode page = request("listObjects", """+ {"connection":%s,"schema":" Index Owner ","object_types":["INDEX"],"exact_identity":true,"limit":1,"offset":1}+ """.formatted(config));+ assertFalse(page.has("error"), page.toString());+ assertEquals(1, page.path("result").size());+ assertEquals("IxB", page.path("result").path(0).path("name").asText());+ } finally {+ closeAndDeregister(config, driver);+ }+ }+ }+ }+@Testvoid listIndexesDegradesToEmptyWhenDriverRejectsIndexMetadata() throws Exception {for (Throwable failure : List.of(@@ -3486,6 +3648,35 @@ final class DbxJdbcPluginTest {}}+ @Test+ void oracleGetColumnsPreservesLengthAndNumberSemantics() throws Exception {+ Method method = DbxJdbcPlugin.class.getDeclaredMethod("oracleGetColumns", Connection.class, String.class, String.class);+ method.setAccessible(true);+ try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:oracle_column_semantics", "sa", "")) {+ conn.createStatement().execute("CREATE TABLE all_tab_comments (owner VARCHAR, table_name VARCHAR, table_type VARCHAR)");+ conn.createStatement().execute("INSERT INTO all_tab_comments VALUES ('Owner', ' T(a) ', 'TABLE')");+ conn.createStatement().execute("CREATE TABLE all_tab_columns (owner VARCHAR, table_name VARCHAR, column_name VARCHAR, data_type VARCHAR, nullable VARCHAR, data_default VARCHAR, data_precision INT, data_scale INT, char_length INT, data_length INT, char_used VARCHAR, column_id INT)");+ conn.createStatement().execute("CREATE TABLE all_col_comments (owner VARCHAR, table_name VARCHAR, column_name VARCHAR, comments VARCHAR)");+ conn.createStatement().execute("CREATE TABLE all_constraints (owner VARCHAR, table_name VARCHAR, constraint_name VARCHAR, constraint_type VARCHAR)");+ conn.createStatement().execute("CREATE TABLE all_cons_columns (owner VARCHAR, table_name VARCHAR, constraint_name VARCHAR, column_name VARCHAR)");+ conn.createStatement().execute("INSERT INTO all_tab_columns VALUES " ++ "('Owner',' T(a) ','A','VARCHAR2','Y','''x''',NULL,NULL,4,16,'C',1)," ++ "('Owner',' T(a) ','B','CHAR','Y',NULL,NULL,NULL,8,8,'B',2)," ++ "('Owner',' T(a) ','C','NVARCHAR2','Y',NULL,NULL,NULL,3,6,NULL,3)," ++ "('Owner',' T(a) ','D','NCHAR','Y',NULL,NULL,NULL,2,4,NULL,4)," ++ "('Owner',' T(a) ','E','NUMBER','Y',NULL,12,2,NULL,22,NULL,5)," ++ "('Owner',' T(a) ','F','NUMBER','Y',NULL,NULL,-2,NULL,22,NULL,6)," ++ "('Owner',' T(a) ','G','FLOAT','Y',NULL,63,NULL,NULL,22,NULL,7)," ++ "('Owner',' T(a) ','H','RAW','Y',NULL,NULL,NULL,NULL,16,NULL,8)," ++ "('Owner',' T(a) ','I','VARCHAR2','Y',NULL,NULL,NULL,NULL,NULL,NULL,9)");+ JsonNode columns = (JsonNode) method.invoke(null, conn, "Owner", " T(a) ");+ List<String> types = new ArrayList<>();+ columns.forEach(column -> types.add(column.path("data_type").asText()));+ assertEquals(List.of("VARCHAR2(4 CHAR)", "CHAR(8 BYTE)", "NVARCHAR2(3)", "NCHAR(2)", "NUMBER(12,2)", "NUMBER(*,-2)", "FLOAT(63)", "RAW(16)", "VARCHAR2"), types);+ assertEquals("'x'", columns.path(0).path("column_default").asText());+ }+ }+@Testvoid oraclePrimaryKeysFallsBackToJdbcWhenAllConstraintsIsMissing() throws Exception {Method method = DbxJdbcPlugin.class.getDeclaredMethod("oraclePrimaryKeys", Connection.class, String.class, String.class);@@ -3615,7 +3806,7 @@ final class DbxJdbcPluginTest {conn.createStatement().execute("CREATE TABLE all_tab_columns (" +"owner VARCHAR(64), table_name VARCHAR(64), column_name VARCHAR(64), data_type VARCHAR(32), " +- "nullable VARCHAR(1), data_default VARCHAR(64), data_precision INT, data_scale INT, char_length INT, column_id INT)"+ "nullable VARCHAR(1), data_default VARCHAR(64), data_precision INT, data_scale INT, char_length INT, data_length INT, char_used VARCHAR(1), column_id INT)");conn.createStatement().execute("CREATE TABLE all_col_comments (owner VARCHAR(64), table_name VARCHAR(64), column_name VARCHAR(64), comments VARCHAR(128))"@@ -4118,6 +4309,29 @@ final class DbxJdbcPluginTest {);}+ private static ResultSet longFirstResultSet(String longColumn, String[] columns, Object[][] rows) {+ ResultSet delegate = rowsResultSet(columns, rows);+ return (ResultSet) Proxy.newProxyInstance(+ DbxJdbcPluginTest.class.getClassLoader(), new Class<?>[] {ResultSet.class},+ new java.lang.reflect.InvocationHandler() {+ private boolean firstRead;++ @Override+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {+ if (method.getName().equals("next")) firstRead = true;+ if (method.getName().startsWith("get") && firstRead) {+ assertEquals(longColumn, args[0], "Read LONG before advancing to other JDBC columns");+ firstRead = false;+ }+ try {+ return method.invoke(delegate, args);+ } catch (java.lang.reflect.InvocationTargetException e) {+ throw e.getCause();+ }+ }+ });+ }+private static String stringValue(String[] columns, Object[] row, Object key) {Object value = columnValue(columns, row, key);return value == null ? null : String.valueOf(value);diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rsindex 5f44ea28bf..96482ecd4f 100644--- a/src-tauri/src/commands/connection.rs+++ b/src-tauri/src/commands/connection.rs@@ -18,7 +18,7 @@ use dbx_core::db;use dbx_core::db::agent_driver::{AgentDriverClient, AgentMethod};use dbx_core::models::connection::{database_info_from_protocol_value, rewrite_jdbc_url_host, ConnectionConfig, ConnectionLivenessMessage,- ConnectionTestResult, DatabaseConnectionInfo, DatabaseType,+ ConnectionResponse, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType,};pub use dbx_core::path_utils::expand_tilde;use dbx_core::runtime_config::{release_runtime_config_on_disconnect, should_retain_runtime_config};@@ -219,22 +219,62 @@ async fn connect_agent_pool(#[cfg(test)]mod tests {- #[cfg(feature = "mq-admin")]- use super::load_connection_configs;use super::{connect_db, connect_sqlite_from_config, gaussdb_m_jdbc_command_config, jdbc_command_config_for_endpoint,- mark_mongo_legacy_driver, mongo_legacy_connect_params, mongo_legacy_fallback_error,- persist_mongo_legacy_driver_profile, save_connection_configs, sync_connection_configs,- test_connection_with_info_inner, MONGO_LEGACY_DRIVER_LABEL, MONGO_LEGACY_DRIVER_PROFILE,+ load_connection_configs, load_connection_responses, mark_mongo_legacy_driver, mongo_legacy_connect_params,+ mongo_legacy_fallback_error, persist_mongo_legacy_driver_profile, save_connection_configs,+ sync_connection_configs, test_connection_with_info_inner, MONGO_LEGACY_DRIVER_LABEL,+ MONGO_LEGACY_DRIVER_PROFILE,};use dbx_core::connection::{AppState, PoolKind};use dbx_core::models::connection::{- AttachedDatabaseConfig, ConnectionConfig, DatabaseType, ProxyTunnelConfig, ProxyType, TransportLayerConfig,+ AttachedDatabaseConfig, ConnectionConfig, ConnectionResponse, DatabaseType, ProxyTunnelConfig, ProxyType,+ TransportLayerConfig,};use std::sync::Arc;use std::time::Duration;use tauri::Manager;+ #[tokio::test]+ async fn tauri_load_response_is_flat_and_does_not_put_hint_in_storage_or_runtime_cache() {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("storage.db")).await.unwrap();+ let state = AppState::new_with_plugin_dir(storage, dir.path().join("plugins"));+ let mut input = serde_json::json!({+ "id": "jdbc-oracle-mode", "name": "JDBC", "db_type": "jdbc", "driver_profile": "jdbc",+ "host": "host", "port": 2881, "username": "user", "password": "", "save_password": false,+ "connection_string": "jdbc:oceanbase:oracle://host/service", "jdbc_dialect": "oceanbase-oracle"+ });+ let config: ConnectionConfig = serde_json::from_value(input.clone()).unwrap();+ save_connection_configs(&state, std::slice::from_ref(&config), Vec::new()).await.unwrap();++ let responses = load_connection_responses(&state).await.unwrap();+ let output = serde_json::to_value(&responses[0]).unwrap();+ assert_eq!(output["jdbc_dialect"], "oceanbase-oracle");+ assert_eq!(output["db_type"], "jdbc");+ assert!(output.get("config").is_none());+ assert_eq!(responses[0].config.db_type, DatabaseType::Jdbc);+ assert_eq!(responses[0].config.connection_string.as_deref(), config.connection_string.as_deref());+ assert!(serde_json::to_value(state.configs.read().await[&config.id].clone())+ .unwrap()+ .get("jdbc_dialect")+ .is_none());+ let persisted = state.storage.load_connections().await.unwrap();+ assert!(serde_json::to_value(&persisted[0]).unwrap().get("jdbc_dialect").is_none());++ input["jdbc_dialect"] = serde_json::json!("oracle");+ let forged: ConnectionConfig = serde_json::from_value(input).unwrap();+ assert_eq!(+ ConnectionResponse::from_config(forged).jdbc_dialect,+ Some(dbx_core::models::connection::JdbcDialectHint::OceanbaseOracle)+ );+ assert!(load_connection_configs(&state)+ .await+ .unwrap()+ .iter()+ .all(|loaded| loaded.db_type == DatabaseType::Jdbc));+ }+fn rocketmq_config(password: &str) -> ConnectionConfig {let mut config = mongodb_config();config.id = "rocketmq-desktop".into();@@ -1277,8 +1317,12 @@ async fn remove_connection_pools_for_connection_ids(state: &AppState, connection}#[tauri::command]-pub async fn load_connections(state: State<'_, Arc<AppState>>) -> Result<Vec<ConnectionConfig>, String> {- load_connection_configs(state.inner()).await+pub async fn load_connections(state: State<'_, Arc<AppState>>) -> Result<Vec<ConnectionResponse>, String> {+ load_connection_responses(state.inner()).await+}++async fn load_connection_responses(state: &AppState) -> Result<Vec<ConnectionResponse>, String> {+ Ok(load_connection_configs(state).await?.into_iter().map(ConnectionResponse::from_config).collect())}async fn load_connection_configs(state: &AppState) -> Result<Vec<ConnectionConfig>, String> {