Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(oceanbase): preserve partition DDL and toggle storage options

efeirefe0dd02f2b1b
diff --git a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java
index 4d751e2a24..1924d958ea 100644
--- a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java
+++ b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java
@@ -147,6 +147,14 @@ public interface DatabaseAgent {
List<TriggerInfo> listTriggers(String schema, String table);
+ default List<PartitionInfo> listPartitions(String schema, String table) {
+ return Collections.emptyList();
+ }
+
+ default List<PartitionInfo> listSubpartitions(String schema, String table) {
+ return Collections.emptyList();
+ }
+
default QueryResult executeQuery(String sql, String schema) {
return executeQuery(sql, schema, new ExecuteQueryOptions());
}
diff --git a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java
index 7a267fbe97..88b2a2b34c 100644
--- a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java
+++ b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java
@@ -246,6 +246,14 @@ public final class JsonRpcServer {
switchCatalog(params);
return agent.listTriggers(params.get("schema").getAsString(), params.get("table").getAsString());
}
+ if (AgentProtocol.METHOD_LIST_PARTITIONS.equals(method)) {
+ switchCatalog(params);
+ return agent.listPartitions(params.get("schema").getAsString(), params.get("table").getAsString());
+ }
+ if (AgentProtocol.METHOD_LIST_SUBPARTITIONS.equals(method)) {
+ switchCatalog(params);
+ return agent.listSubpartitions(params.get("schema").getAsString(), params.get("table").getAsString());
+ }
if (AgentProtocol.METHOD_EXECUTE_QUERY.equals(method)) {
return agent.executeQuery(
params.get("sql").getAsString(),
diff --git a/agents/common/src/main/java/com/dbx/agent/PartitionInfo.java b/agents/common/src/main/java/com/dbx/agent/PartitionInfo.java
new file mode 100644
index 0000000000..7787384a01
--- /dev/null
+++ b/agents/common/src/main/java/com/dbx/agent/PartitionInfo.java
@@ -0,0 +1,5 @@
+package com.dbx.agent;
+
+/** Shared wire shape for partition and subpartition metadata. */
+public record PartitionInfo(String name, int position, String value, String partition_type, String partition_key) {
+}
diff --git a/agents/drivers/oceanbase-oracle/scripts/README.md b/agents/drivers/oceanbase-oracle/scripts/README.md
new file mode 100644
index 0000000000..7463138f3b
--- /dev/null
+++ b/agents/drivers/oceanbase-oracle/scripts/README.md
@@ -0,0 +1,27 @@
+# OceanBase Oracle partition DDL verification
+
+Build with JDK 21 from the repository root:
+
+```sh
+./agents/gradlew -p agents :common:test :oceanbase-oracle:test :oceanbase-oracle:shadowJar
+```
+
+Set `OB_HOST`, `OB_PORT` (default 2881), `OB_TENANT`, and `OB_PASSWORD` in your environment. `OB_PASSWORD` is the SYS password for a **disposable Oracle tenant**. Then run:
+
+```sh
+pnpm exec tsx --tsconfig apps/desktop/tsconfig.json agents/drivers/oceanbase-oracle/scripts/verify-partition-ddl.ts
+```
+
+The script starts the built agent over JSON-RPC, creates three isolated `DBX7055_` schemas, and replays eight tables into two of them: once with storage options omitted and once with full DDL. It checks partition and subpartition counts, keys and bounds, column metadata, defaults, comments, LOCAL indexes, and primary/check/foreign-key enforcement. It also covers quoted identifiers and a global temporary table whose internal session index must not be exported.
+
+DDL files and `verification.json` are written under `agents/drivers/oceanbase-oracle/build/partition-ddl-evidence` (override with `OB_TEST_OUTPUT`). Schemas are intentionally retained for manual DBX inspection; their exact names are printed in the report. Remove only those test schemas with `DROP USER "<reported name>" CASCADE` after disconnecting their sessions. No credentials are written to evidence files.
+
+## UI verification
+
+Install the built agent as described in the root CONTRIBUTING.md and use the current frontend. Expand a partitioned table's Partitions and Subpartitions groups. Open its DDL and check that **Omit storage attributes** is enabled by default. Copy and export the script, turn the switch off, and repeat. Partition clauses, constraints, LOCAL indexes, defaults and comments must remain in both outputs. Changing the option does not re-fetch or overwrite the cached original. In the structure editor the switch is disabled while DDL has unsaved edits.
+
+The preference applies only to OceanBase Oracle and removes these known table options: `COMPRESS FOR ARCHIVE [HIGH|LOW]`, `NOCOMPRESS`, `REPLICA_NUM`, `BLOCK_SIZE`, `TABLET_SIZE`, `PCTFREE`, and `USE_BLOOM_FILTER`. Unknown options and partition clauses are preserved.
+
+## Verified environment
+
+The script passed against OceanBase 4.2.5.7 in Oracle mode, with RANGE, LIST, HASH and RANGE/LIST tables, compound partition keys, constraints, defaults/comments and temporary tables. It uses `DBMS_METADATA.GET_DDL` supported by the [OceanBase 4.2.5 documentation](https://www.oceanbase.com/docs/common-oceanbase-database-cn-1000000001503693). Separate native index DDL and comments are appended because this version's TABLE result omits them.
diff --git a/agents/drivers/oceanbase-oracle/scripts/verify-partition-ddl.ts b/agents/drivers/oceanbase-oracle/scripts/verify-partition-ddl.ts
new file mode 100644
index 0000000000..6cf38e66ac
--- /dev/null
+++ b/agents/drivers/oceanbase-oracle/scripts/verify-partition-ddl.ts
@@ -0,0 +1,146 @@
+import { spawn } from "node:child_process";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { randomUUID } from "node:crypto";
+import { createInterface } from "node:readline";
+import assert from "node:assert/strict";
+import { applyDdlStoragePreference } from "../../../../apps/desktop/src/lib/sql/ddlStorage";
+import { splitSqlStatementRanges } from "../../../../apps/desktop/src/lib/sql/sqlStatementRanges";
+
+async function main() {
+ const password = process.env.OB_PASSWORD;
+ const host = process.env.OB_HOST;
+ const tenant = process.env.OB_TENANT;
+ assert.ok(password && host && tenant, "Set OB_HOST, OB_TENANT and OB_PASSWORD for a disposable Oracle tenant");
+ const java = process.env.JAVA_HOME ? join(process.env.JAVA_HOME, "bin", process.platform === "win32" ? "java.exe" : "java") : "java";
+ const jar = "agents/drivers/oceanbase-oracle/build/libs/dbx-agent-oceanbase-oracle.jar";
+ const output = process.env.OB_TEST_OUTPUT ?? join("agents/drivers/oceanbase-oracle/build", "partition-ddl-evidence");
+ mkdirSync(output, { recursive: true });
+ const child = spawn(java, ["-jar", jar], { stdio: ["pipe", "pipe", "pipe"] });
+ child.stderr.resume();
+ let id = 0;
+ const pending = new Map<number, { resolve: (x: any) => void; reject: (x: any) => void }>();
+ createInterface({ input: child.stdout }).on("line", (line) => {
+ if (!line.startsWith("{")) return;
+ const response = JSON.parse(line);
+ const task = pending.get(response.id);
+ if (!task) return;
+ pending.delete(response.id);
+ response.error ? task.reject(new Error(response.error.message)) : task.resolve(response.result);
+ });
+ child.on("exit", () => {
+ for (const request of pending.values()) request.reject(new Error("Agent exited"));
+ pending.clear();
+ });
+ child.on("error", (error) => {
+ for (const request of pending.values()) request.reject(error);
+ pending.clear();
+ });
+ function call(method: string, params: any = {}) {
+ return new Promise<any>((resolve, reject) => {
+ const requestId = ++id;
+ const timeout = setTimeout(() => {
+ pending.delete(requestId);
+ reject(new Error("Agent request timed out: " + method));
+ }, 60_000);
+ pending.set(requestId, {
+ resolve: (value) => {
+ clearTimeout(timeout);
+ resolve(value);
+ },
+ reject: (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ },
+ });
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: requestId, method, params }) + "\n");
+ });
+ }
+ const connect = (user: string, session: string) => call("open_session", { agentSessionId: session, host, port: Number(process.env.OB_PORT ?? 2881), database: user, username: user + "@" + tenant, password });
+ const sql = (text: string, session = "admin") =>
+ call("execute_query", { agentSessionId: session, sql: text, maxRows: 1000, timeoutSecs: 30 }).catch((e) => {
+ throw new Error((text.startsWith("CREATE USER") ? "CREATE USER [redacted]" : text) + "\n" + e.message);
+ });
+ const qi = (s: string) => '"' + s.replaceAll('"', '""') + '"';
+ const suffix = randomUUID().slice(0, 8).toUpperCase();
+ const source = "DBX7055_S" + suffix,
+ logical = "DBX7055_L" + suffix,
+ physical = "DBX7055_P" + suffix;
+ const fixtures = [
+ ["PARENT", "(ID NUMBER PRIMARY KEY)"],
+ [
+ "RANGE_LIST",
+ `(ID NUMBER NOT NULL, REGION VARCHAR2(30) DEFAULT 'PCTFREE = 20', NOTE VARCHAR2(100), CONSTRAINT C_PK PRIMARY KEY(ID,REGION), CONSTRAINT C_CK CHECK(ID>0)) PARTITION BY RANGE(ID) SUBPARTITION BY LIST(REGION) (PARTITION P1 VALUES LESS THAN(100) (SUBPARTITION P1_E VALUES('east'), SUBPARTITION P1_D VALUES(DEFAULT)), PARTITION PM VALUES LESS THAN(MAXVALUE) (SUBPARTITION PM_E VALUES('east'), SUBPARTITION PM_D VALUES(DEFAULT)))`,
+ ],
+ ["RANGE_T", `(ID NUMBER, D DATE) PARTITION BY RANGE(ID,D) (PARTITION P1 VALUES LESS THAN(100,DATE '2027-01-01'), PARTITION PM VALUES LESS THAN(MAXVALUE,MAXVALUE))`],
+ ["LIST_T", `(REGION VARCHAR2(30), ID NUMBER) PARTITION BY LIST(REGION) (PARTITION PE VALUES ('east','PCTFREE = 20'), PARTITION PD VALUES(DEFAULT))`],
+ ["HASH_T", "(ID NUMBER, NOTE VARCHAR2(100)) PARTITION BY HASH(ID) PARTITIONS 4"],
+ ["CHILD", "(ID NUMBER PRIMARY KEY, PARENT_ID NUMBER, CONSTRAINT C_FK FOREIGN KEY(PARENT_ID) REFERENCES " + qi(source) + ".PARENT(ID))"],
+ ["Mixed Table", `("PCTFREE" VARCHAR2(100) DEFAULT 'can''t ; ) PCTFREE=12', "ID" NUMBER)`],
+ ];
+ const tables = fixtures.map((x) => x[0]);
+ tables.push("TEMP_T");
+ try {
+ await call("handshake");
+ await connect("SYS", "admin");
+ for (const owner of [source, logical, physical]) {
+ await sql("CREATE USER " + qi(owner) + " IDENTIFIED BY " + qi(password));
+ await sql("GRANT CREATE SESSION, CREATE TABLE TO " + qi(owner));
+ }
+ for (const [name, definition] of fixtures) await sql("CREATE TABLE " + qi(source) + "." + qi(name) + " " + definition);
+ await sql("CREATE GLOBAL TEMPORARY TABLE " + qi(source) + ".TEMP_T(ID NUMBER) ON COMMIT PRESERVE ROWS");
+ await sql("CREATE INDEX " + qi(source) + ".C_LOCAL ON " + qi(source) + ".RANGE_LIST(NOTE) LOCAL");
+ await sql("COMMENT ON TABLE " + qi(source) + ".RANGE_LIST IS 'table''s PCTFREE = 20'");
+ await sql("COMMENT ON COLUMN " + qi(source) + ".RANGE_LIST.NOTE IS 'note ; ) COMPRESS FOR ARCHIVE'");
+ await connect(source, "source");
+ await connect(logical, "logical");
+ await connect(physical, "physical");
+ const checks: any[] = [];
+ for (const name of tables) {
+ const params = { schema: source, table: name, agentSessionId: "source" };
+ const ddl: string = await call("get_table_ddl", params);
+ const parts = await call("list_partitions", params),
+ subs = await call("list_subpartitions", params);
+ const expected: Record<string, [number, number]> = { RANGE_LIST: [2, 4], RANGE_T: [2, 0], LIST_T: [2, 0], HASH_T: [4, 0] };
+ if (expected[name]) assert.deepEqual([parts.length, subs.length], expected[name]);
+ const simple = applyDdlStoragePreference(ddl, "oceanbase-oracle");
+ assert.equal(applyDdlStoragePreference(ddl, "oceanbase-oracle", false), ddl);
+ assert.ok(!simple.includes("REPLICA_NUM = "));
+ for (const [owner, session, script] of [
+ [logical, "logical", simple],
+ [physical, "physical", ddl],
+ ]) {
+ for (const statement of splitSqlStatementRanges(script.replaceAll(qi(source) + ".", qi(owner) + "."), "oceanbase-oracle").map((s) => s.sql)) await sql(statement, session);
+ assert.deepEqual(await call("list_partitions", { ...params, schema: owner, agentSessionId: session }), parts);
+ assert.deepEqual(await call("list_subpartitions", { ...params, schema: owner, agentSessionId: session }), subs);
+ assert.deepEqual(await call("get_columns", { ...params, schema: owner, agentSessionId: session }), await call("get_columns", params));
+ }
+ writeFileSync(join(output, name.replaceAll('"', "") + ".full.sql"), ddl);
+ writeFileSync(join(output, name.replaceAll('"', "") + ".logical.sql"), simple);
+ checks.push({ table: name, partitions: parts.length, subpartitions: subs.length, replayed: ["logical", "physical"] });
+ }
+ for (const session of ["source", "logical", "physical"]) {
+ await sql("INSERT INTO RANGE_LIST VALUES(1,'east','first')", session);
+ await sql("INSERT INTO RANGE_LIST VALUES(101,'west','second')", session);
+ await assert.rejects(sql("INSERT INTO RANGE_LIST VALUES(-1,'east','bad')", session));
+ await assert.rejects(sql("INSERT INTO RANGE_LIST VALUES(1,'east','duplicate')", session));
+ await sql("INSERT INTO PARENT VALUES(1)", session);
+ await sql("INSERT INTO CHILD VALUES(1,1)", session);
+ await assert.rejects(sql("INSERT INTO CHILD VALUES(2,999)", session));
+ const comment = await sql("SELECT COMMENTS FROM USER_TAB_COMMENTS WHERE TABLE_NAME='RANGE_LIST'", session);
+ assert.equal(comment.rows[0][0], "table's PCTFREE = 20");
+ const local = await sql("SELECT INDEX_NAME, LOCALITY FROM USER_PART_INDEXES WHERE TABLE_NAME='RANGE_LIST'", session);
+ assert.ok(local.rows.some((r: any[]) => r.includes("C_LOCAL") && r.includes("LOCAL")));
+ }
+ const report = { source, logical, physical, checks, semanticChecks: "partition bounds, keys, columns/defaults/comments, local index, primary/check/foreign-key enforcement" };
+ writeFileSync(join(output, "verification.json"), JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report, null, 2));
+ } finally {
+ child.stdin.end();
+ child.kill();
+ }
+}
+main().catch((e) => {
+ console.error(e.message);
+ process.exitCode = 1;
+});
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.java
index 40f4501ad9..7b53ef05a6 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
@@ -15,6 +15,7 @@ import com.dbx.agent.MetadataListConstraints;
import com.dbx.agent.ObjectInfo;
import com.dbx.agent.ObjectSource;
import com.dbx.agent.OracleObjectPrivilege;
+import com.dbx.agent.PartitionInfo;
import com.dbx.agent.TableInfo;
import com.dbx.agent.TriggerInfo;
@@ -32,6 +33,8 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
private static final long MICROS_PER_SECOND = 1_000_000L;
@@ -536,45 +539,121 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
@Override
public String getTableDdl(String schema, String table) {
- List<IndexInfo> indexes;
- try {
- indexes = listIndexes(schema, table);
- } catch (RuntimeException e) {
- indexes = Collections.emptyList();
- }
+ return unchecked(() -> {
+ String owner = normalizeSchema(schema);
+ String ddl = queryDbmsMetadataSource(owner, table, "TABLE");
+ if (ddl == null || ddl.isBlank()) {
+ throw new SQLException("DBMS_METADATA.GET_DDL returned empty DDL for " + owner + "." + table);
+ }
+ // OceanBase 4.2.5 omits the owner from CREATE TABLE, even for another schema.
+ var header = Pattern.compile("(?i)^(\\s*CREATE\\s+(?:GLOBAL\\s+TEMPORARY\\s+)?TABLE\\s+)"
+ + Pattern.quote(quoteIdentifier(table)) + "(?=\\s*\\()").matcher(ddl);
+ if (header.find()) {
+ ddl = header.replaceFirst(Matcher.quoteReplacement(header.group(1) + quoteIdentifier(owner) + "." + quoteIdentifier(table)));
+ }
+ ddl = ddl.strip();
+ if (!ddl.endsWith(";")) ddl += ";";
- List<ForeignKeyInfo> foreignKeys;
- try {
- foreignKeys = listForeignKeys(schema, table);
- } catch (RuntimeException e) {
- foreignKeys = Collections.emptyList();
- }
+ // GET_DDL(TABLE) includes constraints/partitioning, but not secondary indexes or comments.
+ String indexSql = """
+ SELECT i.INDEX_NAME FROM ALL_INDEXES i
+ WHERE i.TABLE_OWNER = ? AND i.TABLE_NAME = ?
+ AND NOT EXISTS (SELECT 1 FROM ALL_CONSTRAINTS c
+ WHERE c.OWNER = i.OWNER AND c.INDEX_NAME = i.INDEX_NAME
+ AND c.CONSTRAINT_TYPE IN ('P', 'U'))
+ AND NOT (i.INDEX_NAME = 'IDX_FOR_HEAP_GTT_' || i.TABLE_NAME
+ AND EXISTS (SELECT 1 FROM ALL_TABLES t WHERE t.OWNER = i.TABLE_OWNER
+ AND t.TABLE_NAME = i.TABLE_NAME AND t.TEMPORARY = 'Y')
+ AND EXISTS (SELECT 1 FROM ALL_IND_COLUMNS c WHERE c.INDEX_OWNER = i.OWNER
+ AND c.INDEX_NAME = i.INDEX_NAME AND c.COLUMN_NAME = 'SYS_SESSION_ID'))
+ ORDER BY i.INDEX_NAME
+ """;
+ List<String> indexNames = new ArrayList<>();
+ try (var stmt = requireConnection().prepareStatement(indexSql)) {
+ stmt.setString(1, owner);
+ stmt.setString(2, table);
+ try (ResultSet rs = stmt.executeQuery()) {
+ while (rs.next()) indexNames.add(rs.getString(1));
+ }
+ }
+ for (String index : indexNames) {
+ String indexDdl = queryDbmsMetadataSource(owner, index, "INDEX");
+ if (indexDdl == null || indexDdl.isBlank()) throw new SQLException("Empty index DDL: " + index);
+ ddl = DdlBuilder.appendTrailingSql(ddl, indexDdl);
+ }
+ String tableRef = quoteIdentifier(owner) + "." + quoteIdentifier(table);
+ String comment = getTableComment(owner, table);
+ if (comment != null && !comment.isBlank()) {
+ ddl = DdlBuilder.appendTrailingSql(ddl, "COMMENT ON TABLE " + tableRef + " IS '" + comment.replace("'", "''") + "';");
+ }
+ String commentSql = "SELECT COLUMN_NAME, COMMENTS FROM ALL_COL_COMMENTS WHERE OWNER = ? AND TABLE_NAME = ? AND COMMENTS IS NOT NULL ORDER BY COLUMN_NAME";
+ try (var stmt = requireConnection().prepareStatement(commentSql)) {
+ stmt.setString(1, owner);
+ stmt.setString(2, table);
+ try (ResultSet rs = stmt.executeQuery()) {
+ while (rs.next()) {
+ String text = rs.getString("COMMENTS");
+ if (text == null || text.isBlank()) continue;
+ ddl = DdlBuilder.appendTrailingSql(ddl, "COMMENT ON COLUMN " + tableRef + "." + quoteIdentifier(rs.getString("COLUMN_NAME")) + " IS '" + text.replace("'", "''") + "';");
+ }
+ }
+ }
+ try {
+ ddl = DdlBuilder.appendTrailingSql(ddl, queryObjectGrantSql(owner, table));
+ } catch (RuntimeException | SQLException ignored) {
+ // Privilege metadata remains optional for users without access to grant views.
+ }
+ return ddl;
+ });
+ }
- String tableComment = null;
- try {
- tableComment = getTableComment(schema, table);
- } catch (RuntimeException e) {
- // Table comment is optional; DDL generation should still succeed without it.
- }
+ private static String quoteIdentifier(String name) {
+ return "\"" + name.replace("\"", "\"\"") + "\"";
+ }
- String ddl = DdlBuilder.buildTableDdl(
- schema,
- table,
- getColumns(schema, table),
- indexes,
- foreignKeys,
- java.util.Collections.emptyList(),
- false,
- true,
- tableComment
- );
- try {
+ @Override
+ public List<PartitionInfo> listPartitions(String schema, String table) {
+ return queryPartitions(schema, table, false);
+ }
+
+ @Override
+ public List<PartitionInfo> listSubpartitions(String schema, String table) {
+ return queryPartitions(schema, table, true);
+ }
+
+ private List<PartitionInfo> queryPartitions(String schema, String table, boolean subpartition) {
+ return unchecked(() -> {
String owner = normalizeSchema(schema);
- return DdlBuilder.appendTrailingSql(ddl, queryObjectGrantSql(owner, table));
- } catch (RuntimeException | SQLException ignored) {
- // Privilege metadata is optional; CREATE TABLE DDL should still succeed without it.
- return ddl;
- }
+ String prefix = subpartition ? "SUBPARTITION" : "PARTITION";
+ String keysView = subpartition ? "ALL_SUBPART_KEY_COLUMNS" : "ALL_PART_KEY_COLUMNS";
+ List<String> keys = new ArrayList<>();
+ try (var stmt = requireConnection().prepareStatement("SELECT COLUMN_NAME FROM " + keysView
+ + " WHERE OWNER = ? AND NAME = ? AND OBJECT_TYPE = 'TABLE' ORDER BY COLUMN_POSITION")) {
+ stmt.setString(1, owner);
+ stmt.setString(2, table);
+ try (ResultSet rs = stmt.executeQuery()) {
+ while (rs.next()) keys.add(quoteIdentifier(rs.getString(1)));
+ }
+ }
+ String sql = "SELECT p." + prefix + "_NAME AS NAME, p." + prefix + "_POSITION AS POSITION, p.HIGH_VALUE, t."
+ + prefix + "ING_TYPE AS PARTITION_TYPE FROM " + (subpartition ? "ALL_TAB_SUBPARTITIONS" : "ALL_TAB_PARTITIONS")
+ + " p JOIN ALL_PART_TABLES t ON t.OWNER = p.TABLE_OWNER AND t.TABLE_NAME = p.TABLE_NAME"
+ + " WHERE p.TABLE_OWNER = ? AND p.TABLE_NAME = ? ORDER BY "
+ + (subpartition ? "p.PARTITION_NAME, " : "") + "p." + prefix + "_POSITION";
+ List<PartitionInfo> result = new ArrayList<>();
+ try (var stmt = requireConnection().prepareStatement(sql)) {
+ stmt.setString(1, owner);
+ stmt.setString(2, table);
+ try (ResultSet rs = stmt.executeQuery()) {
+ while (rs.next()) {
+ String value = rs.getString("HIGH_VALUE");
+ result.add(new PartitionInfo(rs.getString("NAME"), rs.getInt("POSITION"), value == null ? "" : value,
+ rs.getString("PARTITION_TYPE"), String.join(", ", keys)));
+ }
+ }
+ }
+ return result;
+ });
}
private String queryObjectGrantSql(String owner, String table) throws SQLException {
diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java
index d13f0d5b68..2515043958 100644
--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java
+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java
@@ -465,11 +465,11 @@ class OceanBaseOracleAgentTest {
OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
TestSupport.setPrivateConnection(agent, preparedConnection(new ArrayList<>(),
resultSet(
- new String[]{"INDEX_NAME", "COLUMN_NAME", "COLUMN_POSITION", "UNIQUENESS", "CONSTRAINT_TYPE", "INDEX_TYPE"},
- new Object[][]{}
+ new String[]{"DDL"},
+ new Object[][]{{"CREATE TABLE \"AUDIT_LOG\" (\"CREATED_AT\" TIMESTAMP DEFAULT SYSDATE NOT NULL, \"INTERNAL_NOTE\" VARCHAR2(100))"}}
),
resultSet(
- new String[]{"CONSTRAINT_NAME", "COLUMN_NAME", "TABLE_NAME", "REF_COLUMN_NAME"},
+ new String[]{"INDEX_NAME"},
new Object[][]{}
),
resultSet(
@@ -492,7 +492,7 @@ class OceanBaseOracleAgentTest {
String ddl = agent.getTableDdl("APP", "AUDIT_LOG");
- Assertions.assertTrue(ddl.contains("\"CREATED_AT\" TIMESTAMP NOT NULL DEFAULT SYSDATE"), ddl);
+ Assertions.assertTrue(ddl.contains("\"CREATED_AT\" TIMESTAMP DEFAULT SYSDATE NOT NULL"), ddl);
Assertions.assertTrue(
ddl.contains("COMMENT ON COLUMN \"APP\".\"AUDIT_LOG\".\"CREATED_AT\" IS 'Created timestamp';"),
ddl
@@ -508,11 +508,11 @@ class OceanBaseOracleAgentTest {
OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
TestSupport.setPrivateConnection(agent, preparedConnection(sql,
resultSet(
- new String[]{"INDEX_NAME", "COLUMN_NAME", "COLUMN_POSITION", "UNIQUENESS", "CONSTRAINT_TYPE", "INDEX_TYPE"},
- new Object[][]{}
+ new String[]{"DDL"},
+ new Object[][]{{"CREATE TABLE \"USERS\" (\"ID\" NUMBER PRIMARY KEY, \"NAME\" VARCHAR2(100)) PARTITION BY RANGE(\"ID\") (PARTITION P1 VALUES LESS THAN(MAXVALUE))"}}
),
resultSet(
- new String[]{"CONSTRAINT_NAME", "COLUMN_NAME", "TABLE_NAME", "REF_COLUMN_NAME"},
+ new String[]{"INDEX_NAME"},
new Object[][]{}
),
resultSet(
@@ -567,11 +567,11 @@ class OceanBaseOracleAgentTest {
OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
TestSupport.setPrivateConnection(agent, dbaFallbackPrivilegeConnection(sql,
resultSet(
- new String[]{"INDEX_NAME", "COLUMN_NAME", "COLUMN_POSITION", "UNIQUENESS", "CONSTRAINT_TYPE", "INDEX_TYPE"},
- new Object[][]{}
+ new String[]{"DDL"},
+ new Object[][]{{"CREATE TABLE \"USERS\" (\"ID\" NUMBER PRIMARY KEY, \"NAME\" VARCHAR2(100)) PARTITION BY RANGE(\"ID\") (PARTITION P1 VALUES LESS THAN(MAXVALUE))"}}
),
resultSet(
- new String[]{"CONSTRAINT_NAME", "COLUMN_NAME", "TABLE_NAME", "REF_COLUMN_NAME"},
+ new String[]{"INDEX_NAME"},
new Object[][]{}
),
resultSet(
@@ -616,11 +616,11 @@ class OceanBaseOracleAgentTest {
OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
TestSupport.setPrivateConnection(agent, privilegeFailingDdlConnection(sql,
resultSet(
- new String[]{"INDEX_NAME", "COLUMN_NAME", "COLUMN_POSITION", "UNIQUENESS", "CONSTRAINT_TYPE", "INDEX_TYPE"},
- new Object[][]{}
+ new String[]{"DDL"},
+ new Object[][]{{"CREATE TABLE \"USERS\" (\"ID\" NUMBER PRIMARY KEY, \"NAME\" VARCHAR2(100)) PARTITION BY RANGE(\"ID\") (PARTITION P1 VALUES LESS THAN(MAXVALUE))"}}
),
resultSet(
- new String[]{"CONSTRAINT_NAME", "COLUMN_NAME", "TABLE_NAME", "REF_COLUMN_NAME"},
+ new String[]{"INDEX_NAME"},
new Object[][]{}
),
resultSet(
@@ -642,6 +642,59 @@ class OceanBaseOracleAgentTest {
);
}
+ @Test
+ void tableDdlPreservesPartitionsAndNativeLocalIndexes() {
+ var agent = new OceanBaseOracleAgent();
+ String nativeTable = "CREATE TABLE \"T\" (\"ID\" NUMBER, CONSTRAINT \"CK\" CHECK (\"ID\" > 0)) "
+ + "REPLICA_NUM = 1 PARTITION BY RANGE(\"ID\") (PARTITION P1 VALUES LESS THAN(MAXVALUE))";
+ String nativeIndex = "CREATE INDEX \"APP\".\"IX\" ON \"APP\".\"T\"(\"ID\") LOCAL;";
+ TestSupport.setPrivateConnection(agent, preparedConnection(new ArrayList<>(),
+ resultSet(new String[]{"DDL"}, new Object[][]{{nativeTable}}),
+ resultSet(new String[]{"INDEX_NAME"}, new Object[][]{{"IX"}}),
+ resultSet(new String[]{"DDL"}, new Object[][]{{nativeIndex}}),
+ resultSet(new String[]{"COMMENTS"}, new Object[][]{{"Owner's table"}}),
+ resultSet(new String[]{"COLUMN_NAME", "COMMENTS"}, new Object[][]{}),
+ resultSet(new String[]{"GRANTEE", "PRIVILEGE", "GRANTABLE"}, new Object[][]{}),
+ resultSet(new String[]{"GRANTEE", "COLUMN_NAME", "PRIVILEGE", "GRANTABLE"}, new Object[][]{})
+ ));
+ String ddl = agent.getTableDdl("APP", "T");
+ Assertions.assertTrue(ddl.startsWith(nativeTable.replace("CREATE TABLE \"T\"", "CREATE TABLE \"APP\".\"T\"") + ";"), ddl);
+ Assertions.assertTrue(ddl.contains(nativeIndex), ddl);
+ Assertions.assertTrue(ddl.contains("COMMENT ON TABLE \"APP\".\"T\" IS 'Owner''s table';"), ddl);
+ }
+
+ @Test
+ void emptyMetadataDdlFailsInsteadOfReturningAnIncompleteTable() {
+ var agent = new OceanBaseOracleAgent();
+ TestSupport.setPrivateConnection(agent, preparedConnection(new ArrayList<>(),
+ resultSet(new String[]{"DDL"}, new Object[][]{{" "}})));
+ Assertions.assertThrows(RuntimeException.class, () -> agent.getTableDdl("APP", "T"));
+ }
+
+ @Test
+ void partitionsPreserveDictionaryOrderCompositeKeysAndNullHashBounds() {
+ List<String> sql = new ArrayList<>();
+ var agent = new OceanBaseOracleAgent();
+ TestSupport.setPrivateConnection(agent, preparedConnection(sql,
+ resultSet(new String[]{"COLUMN_NAME"}, new Object[][]{{"ID"}, {"A\"B"}}),
+ resultSet(new String[]{"NAME", "POSITION", "HIGH_VALUE", "PARTITION_TYPE"}, new Object[][]{
+ {"P1", 1, "100, 'East'", "RANGE"}, {"PM", 2, "MAXVALUE, MAXVALUE", "RANGE"}}),
+ resultSet(new String[]{"COLUMN_NAME"}, new Object[][]{{"REGION"}}),
+ resultSet(new String[]{"NAME", "POSITION", "HIGH_VALUE", "PARTITION_TYPE"}, new Object[][]{
+ {"S1", 1, null, "HASH"}})
+ ));
+ var partitions = agent.listPartitions("APP", "T");
+ Assertions.assertEquals(List.of("P1", "PM"), partitions.stream().map(com.dbx.agent.PartitionInfo::name).toList());
+ Assertions.assertEquals("\"ID\", \"A\"\"B\"", partitions.get(0).partition_key());
+ Assertions.assertEquals("100, 'East'", partitions.get(0).value());
+ var subpartitions = agent.listSubpartitions("APP", "T");
+ Assertions.assertEquals("", subpartitions.get(0).value());
+ Assertions.assertEquals("HASH", subpartitions.get(0).partition_type());
+ Assertions.assertTrue(sql.get(0).contains("ORDER BY COLUMN_POSITION"));
+ Assertions.assertTrue(sql.get(1).contains("WHERE p.TABLE_OWNER = ? AND p.TABLE_NAME = ?"));
+ Assertions.assertTrue(sql.get(3).contains("ALL_TAB_SUBPARTITIONS"));
+ }
+
private static ResultSet columnResultSet(Object[][] rows) {
return resultSet(
new String[]{
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 8ef87675d5..e3588e523d 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -197,6 +197,7 @@ import { usesLocalOnlyEditorCompletionMetadata, usesOnDemandOnlyEditorColumnMeta
import { loadTableMetadata } from "@/lib/metadata/tableMetadataCache";
import { analyzeIntentionActions, prepareExpandWildcardContext, buildExpandWildcardReplacement, type IntentionAction } from "@/lib/editor/sqlIntentionActions";
import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";
+import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
import { loadObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";
import { queryContextObjectActions, queryContextObjectRoute, queryTableCandidateAtSqlPosition, queryTableNavigationTargetAtSqlPosition, resolveQueryContextCandidateDatabase, resolveQueryContextObjectTarget, type QueryContextObjectAction } from "@/lib/sql/queryCursorTableTarget";
import * as api from "@/lib/backend/api";
@@ -3397,7 +3398,7 @@ async function resolveSqlHoverTooltip(currentView: EditorViewType, pos: number)
// views. Hover only removes PostgreSQL's appended access-control tail.
try {
const { ddl } = await loadObjectDdl(objectMetadataRequest);
- const rawDdl = ddlForHoverPreview(ddl);
+ const rawDdl = ddlForHoverPreview(applyDdlStoragePreference(ddl, props.databaseType, settingsStore.editorSettings.excludeDdlStorage));
if (rawDdl && rawDdl.trim()) {
// A view's display DDL wraps the raw (often single-line) view source
// in `CREATE ... VIEW ... AS`; the table-oriented reformatter cannot
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index aefa6e389c..b4effb1c29 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -1,4 +1,7 @@
<script setup lang="ts">
+import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
+import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
+
import { useUpdateBlocker } from "@/lib/app/updatePreparation";
import { computed, nextTick, onMounted, onUnmounted, onActivated, onDeactivated, ref, shallowRef, toRaw, useSlots, watch, defineAsyncComponent, type Component, type CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
@@ -10287,7 +10290,8 @@ const showTableInfo = ref(false);
const activeTableInfoTab = ref<TableInfoTab>(settingsStore.editorSettings.tableInfoActiveTab);
const canPinTableInfo = computed(() => props.context === "table-data");
const tableInfoDrawerPinned = computed(() => settingsStore.editorSettings.tableInfoDrawerPinned);
-const ddlContent = ref("");
+const rawDdlContent = ref("");
+const ddlContent = computed(() => applyDdlStoragePreference(rawDdlContent.value, resolvedDatabaseType.value, settingsStore.editorSettings.excludeDdlStorage));
const tableInfoColumns = ref<ColumnInfo[]>(props.tableMeta?.columns ?? []);
const tableInfoColumnsLoading = ref(false);
const tableInfoColumnsRequestGeneration = ref(0);
@@ -10507,7 +10511,7 @@ const canShowTableIndexes = computed(() => tableMetadataCapabilities.value.index
const metadataLoaders = useDataGridTableMetadataLoaders({
props,
state: {
- ddlContent,
+ ddlContent: rawDdlContent,
ddlLoading,
tableInfoColumns,
tableInfoColumnsLoading,
@@ -10677,7 +10681,7 @@ watch(
tableOwnerLoading.value = false;
tableOwnerError.value = "";
tableOwnerRequestGeneration.value += 1;
- ddlContent.value = "";
+ rawDdlContent.value = "";
indexes.value = [];
indexesLoaded.value = false;
indexesLoading.value = false;
@@ -13422,16 +13426,18 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
@request-drop-mongo-index="requestDropMongoIndex"
/>
- <pre
- v-else-if="activeTableInfoTab === 'ddl' && !ddlLoading"
- ref="ddlPreRef"
- data-native-clipboard
- tabindex="0"
- class="flex-1 min-w-0 text-xs font-mono p-3 overflow-auto ddl-code leading-5 select-text outline-none"
- :class="settingsStore.editorSettings.tableDdlWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"
- v-html="filteredDdlContent"
- @keydown="onDdlKeydown"
- ></pre>
+ <template v-else-if="activeTableInfoTab === 'ddl' && !ddlLoading">
+ <DdlStorageToggle :database-type="resolvedDatabaseType" class="border-b px-3 py-2" />
+ <pre
+ ref="ddlPreRef"
+ data-native-clipboard
+ tabindex="0"
+ class="flex-1 min-w-0 text-xs font-mono p-3 overflow-auto ddl-code leading-5 select-text outline-none"
+ :class="settingsStore.editorSettings.tableDdlWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"
+ v-html="filteredDdlContent"
+ @keydown="onDdlKeydown"
+ ></pre>
+ </template>
<div v-else class="flex-1 flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
diff --git a/apps/desktop/src/components/objects/DdlStorageToggle.vue b/apps/desktop/src/components/objects/DdlStorageToggle.vue
new file mode 100644
index 0000000000..e3c1638383
--- /dev/null
+++ b/apps/desktop/src/components/objects/DdlStorageToggle.vue
@@ -0,0 +1,19 @@
+<script setup lang="ts">
+import { useId } from "vue";
+import { useI18n } from "vue-i18n";
+import { useSettingsStore } from "@/stores/settingsStore";
+import { Switch } from "@/components/ui/switch";
+import type { DatabaseType } from "@/types/database";
+
+defineProps<{ databaseType?: DatabaseType; disabled?: boolean }>();
+const settings = useSettingsStore();
+const { t } = useI18n();
+const id = useId();
+</script>
+
+<template>
+ <div v-if="databaseType === 'oceanbase-oracle'" class="flex shrink-0 items-center gap-2 text-xs" :title="t('contextMenu.excludeDdlStorageHint')">
+ <Switch :id="id" size="sm" :disabled="disabled" :model-value="settings.editorSettings.excludeDdlStorage !== false" @update:model-value="settings.updateEditorSettings({ excludeDdlStorage: $event })" />
+ <label :for="id" class="cursor-pointer">{{ t("contextMenu.excludeDdlStorage") }}</label>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/objects/DdlViewDialog.vue b/apps/desktop/src/components/objects/DdlViewDialog.vue
index 076a0a015d..dc785e94f2 100644
--- a/apps/desktop/src/components/objects/DdlViewDialog.vue
+++ b/apps/desktop/src/components/objects/DdlViewDialog.vue
@@ -1,4 +1,6 @@
<script setup lang="ts">
+import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
+import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
import { computed, nextTick, onUnmounted, ref, shallowRef, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Clipboard, Loader2, RefreshCw } from "@lucide/vue";
@@ -47,7 +49,8 @@ const { toast } = useToast();
const { isDark, themePalette } = useTheme();
const settingsStore = useSettingsStore();
-const ddlContent = ref("");
+const rawDdlContent = ref("");
+const ddlContent = computed(() => applyDdlStoragePreference(rawDdlContent.value, props.databaseType, settingsStore.editorSettings.excludeDdlStorage));
const ddlLoading = ref(false);
const ddlError = ref("");
const ddlEditorContainer = ref<HTMLDivElement>();
@@ -128,7 +131,7 @@ async function loadDdl(force = false) {
);
const formatDialect = props.formatDialect ?? props.dialect;
const formatted = await formatSqlForDisplay(ddl, formatDialect, settingsStore.editorSettings.sqlFormatter);
- ddlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, formatDialect);
+ rawDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, formatDialect);
} catch (e: any) {
ddlError.value = e?.message || String(e);
} finally {
@@ -144,7 +147,7 @@ watch(
if (!open) return;
const active = document.activeElement;
editorRootToRestoreFocus = active instanceof HTMLElement ? active.closest(".cm-editor") : null;
- ddlContent.value = "";
+ rawDdlContent.value = "";
await loadDdl(settingsStore.editorSettings.refreshDdlOnOpen);
},
{ immediate: true },
@@ -247,6 +250,11 @@ function copyDdlContent() {
}
}
+watch(ddlContent, (content) => {
+ const view = ddlEditorView.value;
+ if (view) view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: content } });
+});
+
// When DDL finishes loading, create the editor inside the dialog.
watch(ddlLoading, (loading) => {
if (!loading && ddlContent.value && props.open) {
@@ -270,7 +278,7 @@ onUnmounted(() => {
});
function retry() {
- ddlContent.value = "";
+ rawDdlContent.value = "";
void loadDdl(true);
}
@@ -307,6 +315,7 @@ function onClose() {
<EditorSearchPanel v-if="ddlEditorView" ref="ddlSearchPanelRef" :view="ddlEditorView" />
</div>
</div>
+ <DdlStorageToggle :database-type="props.databaseType" :disabled="ddlLoading || !!ddlError" />
<DialogFooter>
<div class="mr-auto flex items-center gap-2 text-sm text-muted-foreground">
<Switch id="ddl-refresh-on-open" size="sm" :model-value="settingsStore.editorSettings.refreshDdlOnOpen" @update:model-value="setRefreshDdlOnOpen" />
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index bb555d5b37..d891fe7030 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -1,4 +1,7 @@
<script setup lang="ts">
+import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
+import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
+
import { computed, createApp, nextTick, onActivated, onBeforeUnmount, ref, watch, type Component } from "vue";
import { RecycleScroller } from "vue-virtual-scroller";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
@@ -246,7 +249,8 @@ const tableInfoTab = ref<TableInfoTab>("ddl");
const tableColumns = ref<ColumnInfo[]>([]);
const tableColumnsLoading = ref(false);
const tableColumnsLoaded = ref(false);
-const tableDdlContent = ref("");
+const rawTableDdlContent = ref("");
+const tableDdlContent = computed(() => applyDdlStoragePreference(rawTableDdlContent.value, effectiveDatabaseType.value, settingsStore.editorSettings.excludeDdlStorage));
const tableDdlLoading = ref(false);
const tableDdlLoaded = ref(false);
const tableIndexes = ref<IndexInfo[]>([]);
@@ -1134,7 +1138,7 @@ async function openTableInfo(row: ObjectBrowserRow, initialTab?: TableInfoTab) {
sidePanelGuard.bump();
// Reset state
tableColumns.value = [];
- tableDdlContent.value = "";
+ rawTableDdlContent.value = "";
tableIndexes.value = [];
tableForeignKeys.value = [];
tableTriggers.value = [];
@@ -1185,11 +1189,11 @@ async function fetchTableDdl(force = settingsStore.editorSettings.refreshDdlOnOp
const { ddl } = await loadObjectDdl(tableMetadataRequest(row), { force });
if (sidePanelGuard.isStale(epoch)) return;
const formatDialect = sqlFormatDialectForDbType(effectiveDatabaseType.value);
- tableDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? ddl : omitDdlIdentifierQuotes(ddl, formatDialect);
+ rawTableDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? ddl : omitDdlIdentifierQuotes(ddl, formatDialect);
loadedSuccessfully = true;
} catch (e: any) {
if (sidePanelGuard.isStale(epoch)) return;
- tableDdlContent.value = `-- Error: ${e?.message || e}`;
+ rawTableDdlContent.value = `-- Error: ${e?.message || e}`;
} finally {
if (sidePanelGuard.isFresh(epoch)) {
tableDdlLoaded.value = loadedSuccessfully;
@@ -1323,7 +1327,7 @@ async function refreshActiveTableInfo() {
sidePanelGuard.bump();
if (tableInfoTab.value === "ddl") {
- tableDdlContent.value = "";
+ rawTableDdlContent.value = "";
tableDdlLoaded.value = false;
await fetchTableDdl(true);
} else if (tableInfoTab.value === "columns") {
@@ -2090,7 +2094,7 @@ async function exportStructure(row: ObjectBrowserRow) {
try {
const schema = row.schema || selectedSchema.value || props.database;
const ddl = await api.getTableDdl(props.connection.id, props.database, schema, row.name, tableDdlObjectType(row.type), props.catalog, true);
- await saveFileContent(buildSingleDdlExportFileContent(ddl), `${row.name}.sql`, "SQL", "sql");
+ await saveFileContent(buildSingleDdlExportFileContent(applyDdlStoragePreference(ddl, effectiveDatabaseType.value, settingsStore.editorSettings.excludeDdlStorage)), `${row.name}.sql`, "SQL", "sql");
} catch (e: any) {
console.error("Export structure failed:", e);
}
@@ -3790,6 +3794,9 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': activeTableInfoLoading }" />
</Button>
</div>
+ <div v-if="tableInfoTab === 'ddl' && effectiveDatabaseType === 'oceanbase-oracle'" class="border-b px-3 py-2">
+ <DdlStorageToggle :database-type="effectiveDatabaseType" :disabled="tableDdlLoading" />
+ </div>
<div v-if="tableInfoTab === 'columns'" class="flex-1 min-h-0 overflow-auto">
<div v-if="tableColumnsLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts
index cf1eeab727..ba81818fc2 100644
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts
+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts
@@ -30,7 +30,7 @@ describe("ObjectBrowser table metadata refresh", () => {
expect(refreshTableInfo).toContain('sidePanelMode.value !== "table-info" || !sidePanelRow.value');
expect(refreshTableInfo).toContain("sidePanelGuard.bump();");
- expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "ddl"[\s\S]*?tableDdlContent\.value = "";[\s\S]*?await fetchTableDdl\(true\);/);
+ expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "ddl"[\s\S]*?rawTableDdlContent\.value = "";[\s\S]*?await fetchTableDdl\(true\);/);
expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "columns"[\s\S]*?tableColumns\.value = \[\];[\s\S]*?await fetchTableColumns\(true\);/);
expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "indexes"[\s\S]*?tableIndexes\.value = \[\];[\s\S]*?await fetchTableIndexes\(true\);/);
expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "foreignKeys"[\s\S]*?tableForeignKeys\.value = \[\];[\s\S]*?await fetchTableForeignKeys\(true\);/);
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue b/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue
index 19241527ad..084de2cedd 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue
@@ -1,4 +1,6 @@
<script setup lang="ts">
+import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
+import { structurePreviewHasOceanBase } from "./sidebarTreeDialogState";
import { computed, toRefs, watch } from "vue";
import { AlertTriangle, Check, Loader2, Clipboard, Plus, Trash2, Upload } from "@lucide/vue";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
@@ -433,6 +435,7 @@ watch(
<pre v-else class="max-h-[56vh] min-h-64 overflow-auto rounded bg-muted p-3 text-xs whitespace-pre-wrap" v-html="highlight(structurePreviewSql)"></pre>
</div>
<DialogFooter>
+ <DdlStorageToggle :database-type="structurePreviewHasOceanBase ? 'oceanbase-oracle' : undefined" :disabled="isLoadingStructurePreview || !!structurePreviewError" class="mr-auto" />
<Button variant="outline" @click="showStructurePreviewDialog = false">{{ t("dangerDialog.cancel") }}</Button>
<Button variant="outline" :disabled="isLoadingStructurePreview || !structurePreviewSql" @click="copyStructurePreview">
<Clipboard class="h-4 w-4" />
diff --git a/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts b/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts
index e3c911eef5..5a3c52dd12 100644
--- a/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts
+++ b/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts
@@ -29,6 +29,7 @@ export const showBatchTruncateConfirm = ref(false);
export const showStructurePreviewDialog = ref(false);
export const showStructureDocCopyDialog = ref(false);
export const structurePreviewSql = ref("");
+export const structurePreviewHasOceanBase = ref(false);
export const structurePreviewTitle = ref("");
export const structurePreviewDefaultFileName = ref("structure.sql");
export const structurePreviewError = ref("");
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index 7d3f3a6ad4..fa96699a7f 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -1,4 +1,7 @@
<script setup lang="ts">
+import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
+import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
+
import { computed, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, shallowRef, watch } from "vue";
import { uuid } from "@/lib/common/utils";
import { useI18n } from "vue-i18n";
@@ -173,7 +176,9 @@ const indexesLoading = ref(false);
const foreignKeysLoading = ref(false);
const constraintsLoading = ref(false);
const triggersLoading = ref(false);
-const ddlContent = ref("");
+const rawDdlContent = ref("");
+const ddlStorageExcluded = ref(settingsStore.editorSettings.excludeDdlStorage);
+const ddlContent = computed(() => applyDdlStoragePreference(rawDdlContent.value, databaseType.value, ddlStorageExcluded.value));
const ddlLoading = ref(false);
const ddlEditorContainer = ref<HTMLDivElement>();
const ddlSearchPanelRef = ref<InstanceType<typeof EditorSearchPanel>>();
@@ -194,6 +199,12 @@ const ddlDraft = ref<string | null>(null);
*/
const ddlEditingEnabled = computed(() => !isCreateMode.value && !!ddlContent.value.trim());
const ddlDirty = computed(() => ddlDraft.value !== null && ddlDraft.value.trim() !== ddlContent.value.trim());
+watch([() => settingsStore.editorSettings.excludeDdlStorage, ddlDirty], ([exclude, dirty]) => {
+ if (!dirty && ddlStorageExcluded.value !== exclude) {
+ ddlDraft.value = null;
+ ddlStorageExcluded.value = exclude;
+ }
+});
function ddlEditorDocument(): string {
return ddlDraft.value ?? (ddlContent.value || t("structureEditor.emptyReadonly"));
@@ -348,10 +359,10 @@ async function fetchDdl(force = false) {
const { ddl } = await loadObjectDdl(ddlRequest(), { force });
const dialect = sqlFormatDialectForDbType(databaseType.value);
const formatted = await formatSqlForDisplay(ddl, dialect, settingsStore.editorSettings.sqlFormatter);
- ddlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, dialect);
+ rawDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, dialect);
ddlFetched.value = true;
} catch (e: any) {
- ddlContent.value = `-- Error: ${e?.message || e}`;
+ rawDdlContent.value = `-- Error: ${e?.message || e}`;
ddlFetched.value = true;
} finally {
ddlLoading.value = false;
@@ -1394,6 +1405,8 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {
// Only carried alongside an actual edit: without a draft the baseline is
// refetched, and copying every table's DDL into every draft is pure weight.
ddlContent: ddlDraft.value === null ? undefined : ddlContent.value,
+ rawDdlContent: ddlDraft.value === null ? undefined : rawDdlContent.value,
+ excludeDdlStorage: ddlStorageExcluded.value,
newTableName: newTableName.value,
tableComment: tableComment.value,
originalTableComment: originalTableComment.value,
@@ -1433,7 +1446,8 @@ function restoreDraft(draft: TableStructureEditorDraft) {
// Restore the DDL baseline alongside the edit, otherwise the restored script
// would read as dirty (or clean) against the wrong reference text.
if (draft.ddlContent) {
- ddlContent.value = draft.ddlContent;
+ rawDdlContent.value = draft.rawDdlContent ?? draft.ddlContent;
+ ddlStorageExcluded.value = draft.excludeDdlStorage ?? false;
ddlFetched.value = true;
}
ddlDraft.value = draft.ddlDraft ?? null;
@@ -1504,7 +1518,7 @@ async function hydrateRestoredDraftFromDatabase() {
const { ddl } = await loadObjectDdl({ connectionId, database, schema, tableName, catalog });
const dialect = sqlFormatDialectForDbType(databaseType.value);
const formatted = await formatSqlForDisplay(ddl, dialect, settingsStore.editorSettings.sqlFormatter);
- ddlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, dialect);
+ rawDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, dialect);
ddlFetched.value = true;
nextColumns = applyManticoreDdlColumnExtras(nextColumns, ddl);
} catch {
@@ -1835,7 +1849,7 @@ function resetState() {
triggers.value = [];
triggersLoaded.value = false;
clearColumnSelection();
- ddlContent.value = "";
+ rawDdlContent.value = "";
ddlDraft.value = null;
ddlFetched.value = false;
loadedMetadataFacets.clear();
@@ -2164,7 +2178,7 @@ async function loadStructure(
const { ddl } = await loadObjectDdl({ connectionId, database, schema, tableName, catalog }, { force: options.forceDdl });
const dialect = sqlFormatDialectForDbType(databaseType.value);
const formatted = await formatSqlForDisplay(ddl, dialect, settingsStore.editorSettings.sqlFormatter);
- ddlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, dialect);
+ rawDdlContent.value = settingsStore.editorSettings.generateSqlQuoteIdentifiers ? formatted : omitDdlIdentifierQuotes(formatted, dialect);
ddlFetched.value = true;
nextColumns = applyManticoreDdlColumnExtras(nextColumns, ddl);
} catch {
@@ -3773,7 +3787,7 @@ async function applyChanges() {
warnings.value = [];
sqliteSchemaRevision.value = undefined;
ddlFetched.value = false;
- ddlContent.value = "";
+ rawDdlContent.value = "";
ddlDraft.value = null;
if (isCreateMode.value) {
clearDraft();
@@ -5179,6 +5193,7 @@ watch(
</div>
<template v-else>
<div v-if="ddlContent && !ddlSearchOpen" class="absolute right-3 top-3 z-10 flex items-center gap-1.5">
+ <DdlStorageToggle :database-type="databaseType" :disabled="ddlDirty" />
<Button v-if="ddlDirty" variant="outline" size="sm" class="h-7 gap-1 px-2" :title="t('structureEditor.resetDdl')" @click="resetDdlDraft">
<RotateCcw class="h-3.5 w-3.5" />
{{ t("structureEditor.resetDdl") }}
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts
index 583db6d818..e590f34f61 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
-import { createApp, nextTick, ref, type App } from "vue";
+import { createApp, nextTick, reactive, ref, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
getTablePartitionStatus: vi.fn(),
getTableOwner: vi.fn(),
toast: vi.fn(),
+ copyToClipboard: vi.fn(),
}));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
@@ -47,6 +48,7 @@ vi.mock("@lucide/vue", async () => {
Maximize2: Icon,
Plus: Icon,
RefreshCw: Icon,
+ RotateCcw: Icon,
Save: Icon,
Search: Icon,
Settings: Icon,
@@ -174,12 +176,11 @@ vi.mock("@/stores/connectionStore", () => ({
vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: vi.fn() }) }));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({ tableStructureRefreshVersion: () => 0 }) }));
vi.mock("@/stores/historyStore", () => ({ useHistoryStore: () => ({ add: vi.fn() }) }));
+const settings = reactive({ editorSettings: { structureEditorDensity: "compact", sqlFormatter: {}, tableColumnTemplateFields: [], theme: "default", fontSize: 13, fontFamily: "monospace", generateSqlQuoteIdentifiers: true, excludeDdlStorage: true } });
vi.mock("@/stores/settingsStore", () => ({
- useSettingsStore: () => ({
- editorSettings: { structureEditorDensity: "compact", sqlFormatter: {}, tableColumnTemplateFields: [], theme: "default", fontSize: 13, fontFamily: "monospace", generateSqlQuoteIdentifiers: true },
- updateEditorSettings: vi.fn(),
- }),
+ useSettingsStore: () => ({ ...settings, updateEditorSettings: (patch: object) => Object.assign(settings.editorSettings, patch) }),
}));
+vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: mocks.copyToClipboard }));
vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: ref(false), themePalette: ref({}) }) }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
vi.mock("@/lib/sql/sqlHighlighter", () => ({ createShikiSqlHighlighter: vi.fn(async () => (sql: string) => sql) }));
@@ -231,6 +232,8 @@ function selectTab(button: HTMLButtonElement) {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.connection.db_type = "postgres";
+ settings.editorSettings.excludeDdlStorage = true;
mocks.ensureConnected.mockResolvedValue(undefined);
mocks.executeQuery.mockResolvedValue({ columns: [], rows: [] });
mocks.listDataTypes.mockResolvedValue([]);
@@ -252,6 +255,37 @@ afterEach(() => {
});
describe("TableStructureEditor DDL tab lifecycle", () => {
+ it("toggles OceanBase storage, copies the displayed DDL and protects an edited draft", async () => {
+ mocks.connection.db_type = "oceanbase-oracle";
+ const ddl = 'CREATE TABLE "T" ("ID" NUMBER) PCTFREE=0 PARTITION BY HASH("ID") PARTITIONS 2;';
+ mocks.loadObjectDdl.mockResolvedValue({ ddl, cacheStatus: "remote" });
+ const root = document.createElement("div");
+ document.body.append(root);
+ app = createApp(TableStructureEditor, { connectionId: mocks.connection.id, database: "APP", schema: "APP", tableName: "T", initialTab: "ddl" });
+ app.mount(root);
+ const content = () => root.querySelector(".cm-content")?.textContent ?? "";
+ const toggle = () => root.querySelector<HTMLButtonElement>('[role="switch"]')!;
+ await vi.waitFor(() => expect(content()).toContain("PARTITION BY HASH"));
+ expect(content()).not.toContain("PCTFREE");
+ expect(toggle().getAttribute("aria-checked")).toBe("true");
+ toggle().click();
+ await vi.waitFor(() => expect(content()).toContain("PCTFREE"));
+ buttonWithText(root, "grid.copyDdl").click();
+ await vi.waitFor(() => expect(mocks.copyToClipboard).toHaveBeenLastCalledWith(content()));
+ const { EditorView } = await import("@codemirror/view");
+ const view = EditorView.findFromDOM(root.querySelector(".cm-content")!)!;
+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n-- local edit" } });
+ await nextTick();
+ expect(toggle().disabled).toBe(true);
+ settings.editorSettings.excludeDdlStorage = true;
+ await nextTick();
+ expect(content()).toContain("PCTFREE");
+ expect(content()).toContain("-- local edit");
+ buttonWithText(root, "structureEditor.resetDdl").click();
+ await vi.waitFor(() => expect(content()).not.toContain("PCTFREE"));
+ expect(content()).not.toContain("-- local edit");
+ expect(mocks.loadObjectDdl).toHaveBeenCalledTimes(1);
+ });
it("restores cached DDL after switching to columns and back", async () => {
const root = document.createElement("div");
document.body.append(root);
diff --git a/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts b/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts
index 17faa997d3..40904a80da 100644
--- a/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts
@@ -1,10 +1,11 @@
import { readFileSync } from "node:fs";
-import { shallowRef } from "vue";
+import { shallowRef, reactive, nextTick, effectScope } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ColumnInfo, TreeNode } from "@/types/database";
const source = readFileSync(new URL("../useSidebarTreeExportRuntime.ts", import.meta.url), "utf8");
const toastMock = vi.hoisted(() => vi.fn());
+const copyToClipboardMock = vi.hoisted(() => vi.fn());
const addExportTaskMock = vi.hoisted(() => vi.fn());
const updateTableExportTaskMock = vi.hoisted(() => vi.fn());
const apiMock = vi.hoisted(() => ({
@@ -20,6 +21,7 @@ const apiMock = vi.hoisted(() => ({
}));
vi.mock("@/lib/backend/api", () => apiMock);
+vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: copyToClipboardMock }));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: toastMock }) }));
vi.mock("@/composables/useExportTracker", () => ({ useExportTracker: () => ({ addTask: addExportTaskMock, updateTableExportTask: updateTableExportTaskMock }) }));
@@ -36,7 +38,7 @@ vi.mock("vue-i18n", () => ({
import { useSidebarTreeExportRuntime } from "@/composables/useSidebarTreeExportRuntime";
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS } from "@/lib/dataGrid/dataGridCopyExtractor";
-import { showStructurePreviewDialog, structurePreviewSql, structurePreviewTitle } from "@/components/sidebar/sidebarTreeDialogState";
+import { isLoadingStructurePreview, showStructurePreviewDialog, structurePreviewDefaultFileName, structurePreviewError, structurePreviewSql, structurePreviewTitle } from "@/components/sidebar/sidebarTreeDialogState";
function functionBody(name: string): string {
const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
@@ -84,9 +86,44 @@ function exportSettings() {
};
}
+function structureRuntimeFixture(databaseType: "mysql" | "oceanbase-oracle" = "mysql") {
+ const scope = effectScope();
+ const firstNode = { id: "first-table", type: "table", label: "A", connectionId: "conn-1", database: "db", schema: "app" } as TreeNode;
+ const secondNode = { ...firstNode, id: "second-table", label: "B" } as TreeNode;
+ const activeNode = shallowRef(firstNode);
+ const settingsStore = reactive({ editorSettings: { excludeDdlStorage: true } });
+ const connectionStore = { ensureConnected: vi.fn(), getConfig: () => ({ db_type: databaseType }), treeNodes: [firstNode, secondNode], selectedTreeNodeIds: [] };
+ const runtime = scope.run(() => useSidebarTreeExportRuntime({ activeNode, connectionStore: connectionStore as never, settingsStore: settingsStore as never, acceptedSelectionIds: () => null }))!;
+ return { scope, activeNode, secondNode, settingsStore, runtime };
+}
+
describe("useSidebarTreeExportRuntime", () => {
+ it("toggles OceanBase structure exports from the original DDL without querying again", async () => {
+ const scope = effectScope();
+ const ddl = 'CREATE TABLE "T" ("ID" NUMBER) REPLICA_NUM=1 PCTFREE=0 PARTITION BY HASH("ID") PARTITIONS 2';
+ apiMock.getTableDdl.mockResolvedValue(ddl);
+ const node = { id: "ob-table", type: "table", label: "T", connectionId: "ob", database: "SYS", schema: "APP" } as TreeNode;
+ const settingsStore = reactive({ editorSettings: { excludeDdlStorage: true } });
+ const connectionStore = { ensureConnected: vi.fn(), getConfig: () => ({ db_type: "oceanbase-oracle" }), treeNodes: [node], selectedTreeNodeIds: [] };
+ const runtime = scope.run(() => useSidebarTreeExportRuntime({ activeNode: shallowRef(node), connectionStore: connectionStore as never, settingsStore: settingsStore as never, acceptedSelectionIds: () => null }))!;
+ try {
+ await runtime.exportStructure();
+ expect(structurePreviewSql.value).not.toContain("REPLICA_NUM");
+ expect(structurePreviewSql.value).toContain('PARTITION BY HASH("ID") PARTITIONS 2');
+ settingsStore.editorSettings.excludeDdlStorage = false;
+ await nextTick();
+ expect(structurePreviewSql.value).toBe(ddl + ";\n");
+ settingsStore.editorSettings.excludeDdlStorage = true;
+ await nextTick();
+ expect(structurePreviewSql.value).not.toContain("PCTFREE");
+ expect(apiMock.getTableDdl).toHaveBeenCalledOnce();
+ } finally {
+ scope.stop();
+ }
+ });
beforeEach(() => {
vi.clearAllMocks();
+ apiMock.getTableDdl.mockReset();
addExportTaskMock.mockImplementation((tableName: string, format: string, filePath: string) => ({
exportId: "export-1",
tableName,
@@ -102,6 +139,101 @@ describe("useSidebarTreeExportRuntime", () => {
structurePreviewTitle.value = "";
});
+ it.each(["older-first", "newer-first"])("isolates overlapping structure requests completed %s", async (order) => {
+ const { scope, activeNode, secondNode, runtime } = structureRuntimeFixture();
+ const firstDdl = deferred<string>();
+ const secondDdl = deferred<string>();
+ apiMock.getTableDdl.mockReturnValueOnce(firstDdl.promise).mockReturnValueOnce(secondDdl.promise);
+ const firstRequest = runtime.exportStructure();
+ await vi.waitFor(() => expect(apiMock.getTableDdl).toHaveBeenCalledTimes(1));
+ activeNode.value = secondNode;
+ const secondRequest = runtime.exportStructure();
+ await vi.waitFor(() => expect(apiMock.getTableDdl).toHaveBeenCalledTimes(2));
+ try {
+ if (order === "older-first") {
+ firstDdl.resolve("CREATE TABLE A(id INT)");
+ await firstRequest;
+ expect(isLoadingStructurePreview.value).toBe(true);
+ expect(structurePreviewSql.value).toBe("");
+ secondDdl.resolve("CREATE TABLE B(id INT)");
+ await secondRequest;
+ } else {
+ secondDdl.resolve("CREATE TABLE B(id INT)");
+ await secondRequest;
+ firstDdl.resolve("CREATE TABLE A(id INT)");
+ await firstRequest;
+ }
+ expect(structurePreviewSql.value).toBe("CREATE TABLE B(id INT);\n");
+ expect(structurePreviewDefaultFileName.value).toBe("B.sql");
+ expect(isLoadingStructurePreview.value).toBe(false);
+ await runtime.copyStructurePreview();
+ expect(copyToClipboardMock).toHaveBeenLastCalledWith("CREATE TABLE B(id INT);\n");
+ } finally {
+ firstDdl.resolve("CREATE TABLE A(id INT)");
+ secondDdl.resolve("CREATE TABLE B(id INT)");
+ await Promise.all([firstRequest, secondRequest]);
+ scope.stop();
+ }
+ });
+
+ it.each(["close", "dispose"])("ignores pending structure responses after %s", async (action) => {
+ const { scope, runtime } = structureRuntimeFixture();
+ const pendingDdl = deferred<string>();
+ apiMock.getTableDdl.mockReturnValueOnce(pendingDdl.promise);
+ const pendingRequest = runtime.exportStructure();
+ await vi.waitFor(() => expect(apiMock.getTableDdl).toHaveBeenCalledOnce());
+ if (action === "close") showStructurePreviewDialog.value = false;
+ else scope.stop();
+ pendingDdl.resolve("CREATE TABLE A(id INT)");
+ try {
+ await pendingRequest;
+ expect(structurePreviewSql.value).toBe("");
+ expect(isLoadingStructurePreview.value).toBe(false);
+ } finally {
+ scope.stop();
+ }
+ });
+
+ it("ignores an older failure after another structure request succeeds", async () => {
+ const { scope, activeNode, secondNode, runtime } = structureRuntimeFixture();
+ const firstDdl = deferred<string>();
+ apiMock.getTableDdl.mockReturnValueOnce(firstDdl.promise).mockResolvedValueOnce("CREATE TABLE B(id INT)");
+ const firstRequest = runtime.exportStructure();
+ await vi.waitFor(() => expect(apiMock.getTableDdl).toHaveBeenCalledOnce());
+ activeNode.value = secondNode;
+ await runtime.exportStructure();
+ firstDdl.reject(new Error("old request failed"));
+ try {
+ await firstRequest;
+ expect(structurePreviewSql.value).toBe("CREATE TABLE B(id INT);\n");
+ expect(structurePreviewError.value).toBe("");
+ expect(isLoadingStructurePreview.value).toBe(false);
+ } finally {
+ scope.stop();
+ }
+ });
+
+ it("uses the latest storage preference when a structure request completes", async () => {
+ const { scope, settingsStore, runtime } = structureRuntimeFixture("oceanbase-oracle");
+ const pendingDdl = deferred<string>();
+ const ddl = "CREATE TABLE A(id INT) PCTFREE=0";
+ apiMock.getTableDdl.mockReturnValueOnce(pendingDdl.promise);
+ const pendingRequest = runtime.exportStructure();
+ await vi.waitFor(() => expect(apiMock.getTableDdl).toHaveBeenCalledOnce());
+ settingsStore.editorSettings.excludeDdlStorage = false;
+ pendingDdl.resolve(ddl);
+ try {
+ await pendingRequest;
+ expect(structurePreviewSql.value).toBe(ddl + ";\n");
+ settingsStore.editorSettings.excludeDdlStorage = true;
+ await nextTick();
+ expect(structurePreviewSql.value).not.toContain("PCTFREE");
+ expect(apiMock.getTableDdl).toHaveBeenCalledOnce();
+ } finally {
+ scope.stop();
+ }
+ });
+
it("translates direct executeQuery errors for sidebar JSON export", async () => {
apiMock.executeQuery.mockRejectedValueOnce(new Error("The previous DuckDB query is still stopping. Please try again shortly."));
const activeNode = shallowRef({ id: "table-1", type: "table", label: "users", connectionId: "conn-1", database: "db", schema: "main", children: [] } as TreeNode);
@@ -201,13 +333,14 @@ describe("useSidebarTreeExportRuntime", () => {
const activeNode = shallowRef(first);
const connectionStore = {
ensureConnected: vi.fn(),
+ getConfig: vi.fn(() => ({ db_type: "postgres" })),
treeNodes: [group],
selectedTreeNodeIds: [second.id, first.id],
};
const runtime = useSidebarTreeExportRuntime({
activeNode,
connectionStore: connectionStore as never,
- settingsStore: {} as never,
+ settingsStore: exportSettings() as never,
acceptedSelectionIds: () => null,
});
diff --git a/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts b/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts
index 17c7cae0a5..a10f107f39 100644
--- a/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts
+++ b/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts
@@ -1,4 +1,5 @@
-import { createApp, type ShallowRef } from "vue";
+import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
+import { watch, createApp, getCurrentScope, onScopeDispose, type ShallowRef } from "vue";
import { useI18n } from "vue-i18n";
import i18n from "@/i18n";
import { useExportTracker, type ExportTask } from "@/composables/useExportTracker";
@@ -18,7 +19,18 @@ import { fetchTableDataForExport } from "@/lib/table/tableDataExport";
import { forceCsvTextForTemporalColumns } from "@/lib/dataGrid/columnFormatter";
import XlsxHeaderDialog from "@/components/export/XlsxHeaderDialog.vue";
import { buildXlsxHeaderOverrides, hasXlsxHeaderComments, type XlsxExportOptions, type XlsxHeaderMode } from "@/lib/export/xlsxHeader";
-import { isLoadingStructurePreview, showStructureDocCopyDialog, showStructurePreviewDialog, structureDocCopyText, structureDocCopyTitle, structurePreviewDefaultFileName, structurePreviewError, structurePreviewSql, structurePreviewTitle } from "@/components/sidebar/sidebarTreeDialogState";
+import {
+ isLoadingStructurePreview,
+ showStructureDocCopyDialog,
+ showStructurePreviewDialog,
+ structureDocCopyText,
+ structureDocCopyTitle,
+ structurePreviewDefaultFileName,
+ structurePreviewError,
+ structurePreviewSql,
+ structurePreviewTitle,
+ structurePreviewHasOceanBase,
+} from "@/components/sidebar/sidebarTreeDialogState";
import type { CsvQuoteMode } from "@/lib/export/csvQuoteMode";
type StructureCopyFormat = "tsv" | "markdown";
@@ -126,28 +138,62 @@ export function useSidebarTreeExportRuntime(options: SidebarTreeExportRuntimeOpt
return sidebarTableDataExportTargets(activeNode.value, connectionStore.treeNodes, options.acceptedSelectionIds() ?? connectionStore.selectedTreeNodeIds);
}
+ let structureSource: Array<{ ddl: string; databaseType: ReturnType<typeof effectiveDatabaseTypeForConnection> }> = [];
+ let structureRequestId = 0;
+ function invalidateStructureRequest() {
+ structureRequestId++;
+ structureSource = [];
+ isLoadingStructurePreview.value = false;
+ }
+ watch(
+ showStructurePreviewDialog,
+ (visible) => {
+ if (!visible) invalidateStructureRequest();
+ },
+ { flush: "sync" },
+ );
+ if (getCurrentScope()) onScopeDispose(invalidateStructureRequest);
+ function renderStructurePreview() {
+ structurePreviewSql.value = joinExportedDdls(structureSource.map(({ ddl, databaseType }) => applyDdlStoragePreference(ddl, databaseType, settingsStore.editorSettings.excludeDdlStorage)));
+ }
+ watch(
+ () => settingsStore.editorSettings.excludeDdlStorage,
+ () => {
+ if (showStructurePreviewDialog.value && structureSource.length) renderStructurePreview();
+ },
+ );
+
async function exportStructure() {
const targets = structureExportTargets();
if (!targets.length) return;
+ const requestId = ++structureRequestId;
+ const requestSource: typeof structureSource = [];
isLoadingStructurePreview.value = true;
structurePreviewError.value = "";
structurePreviewSql.value = "";
+ structurePreviewHasOceanBase.value = false;
+ structureSource = [];
structurePreviewTitle.value = targets.length === 1 ? t("contextMenu.exportStructurePreviewTitle", { name: targets[0]!.label }) : t("contextMenu.exportStructurePreviewTitleMultiple", { count: targets.length });
structurePreviewDefaultFileName.value = targets.length === 1 ? `${targets[0]!.label}.sql` : "structures.sql";
showStructurePreviewDialog.value = true;
try {
- const parts: string[] = [];
for (const target of targets) {
await connectionStore.ensureConnected(target.connectionId);
+ if (requestId !== structureRequestId) return;
const ddl = await api.getTableDdl(target.connectionId, target.database, target.schema || target.database, target.label, tableDdlObjectTypeForNode(target.type), target.catalog, true);
- parts.push(ddl.trim());
+ if (requestId !== structureRequestId) return;
+ const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(target.connectionId));
+ requestSource.push({ ddl, databaseType });
}
- structurePreviewSql.value = joinExportedDdls(parts);
+ structureSource = requestSource;
+ structurePreviewHasOceanBase.value = requestSource.some(({ databaseType }) => databaseType === "oceanbase-oracle");
+ renderStructurePreview();
} catch (error: any) {
+ if (requestId !== structureRequestId) return;
structurePreviewError.value = error?.message || String(error);
console.error("Export structure failed:", error);
} finally {
- isLoadingStructurePreview.value = false;
+ if (requestId === structureRequestId) isLoadingStructurePreview.value = false;
}
}
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index b58f5dbbc1..1904793a77 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -3367,6 +3367,8 @@ export default withEnglishFallback({
viewDdl: "DDL-ə bax",
viewDdlLoading: "DDL yüklənir...",
ddlCopied: "DDL kopyalandı",
+ excludeDdlStorage: "Saxlama atributlarını çıxar",
+ excludeDdlStorageHint: "OceanBase Oracle DDL-in göstərilməsinə, kopyalanmasına və strukturun ixracına tətbiq olunur. Sıxılma, replika və saxlama parametrlərini saxlamaq üçün söndürün. Bölmələr və məhdudiyyətlər həmişə saxlanılır.",
refreshDdlOnOpen: "Hər açılışda yenilə",
refreshDdlOnOpenHint: "Aktiv olduqda DDL hər açılışda verilənlər bazasından yenidən yüklənir; deaktiv olduqda keşdəki məlumatlara üstünlük verilir",
dropObject: "Obyekti sil",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 6df11519ba..5791ad3c83 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -3537,6 +3537,8 @@ export default {
viewDdl: "View DDL",
viewDdlLoading: "Loading DDL...",
ddlCopied: "DDL copied",
+ excludeDdlStorage: "Exclude storage attributes",
+ excludeDdlStorageHint: "Applies to OceanBase Oracle DDL display, copying and structure export. Disable to retain compression, replica and storage options. Partitions and constraints are preserved.",
refreshDdlOnOpen: "Refresh each time it opens",
refreshDdlOnOpenHint: "When enabled, DDL is reloaded from the database each time it opens; when disabled, cached data is preferred",
dropObject: "Drop Object",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 54c374bdb6..1a951e9b07 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -3389,6 +3389,8 @@ export default withEnglishFallback({
viewDdl: "Ver DDL",
viewDdlLoading: "Cargando DDL...",
ddlCopied: "DDL copiado",
+ excludeDdlStorage: "Excluir atributos de almacenamiento",
+ excludeDdlStorageHint: "Se aplica a la visualización y copia de DDL y a la exportación de estructuras de OceanBase Oracle. Desactiva esta opción para conservar los parámetros de compresión, réplicas y almacenamiento. Las particiones y restricciones se conservan siempre.",
refreshDdlOnOpen: "Actualizar cada vez que se abra",
refreshDdlOnOpenHint: "Si se activa, el DDL se vuelve a cargar de la base de datos cada vez que se abre; si se desactiva, se usan primero los datos en caché",
dropObject: "Eliminar objeto",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index dc7770f8c4..f7e16d9ec3 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -3387,6 +3387,8 @@ export default withEnglishFallback({
viewDdl: "Visualizza DDL",
viewDdlLoading: "Caricamento DDL...",
ddlCopied: "DDL copiato",
+ excludeDdlStorage: "Escludi attributi di archiviazione",
+ excludeDdlStorageHint: "Si applica alla visualizzazione e alla copia del DDL e all'esportazione della struttura in OceanBase Oracle. Disattiva questa opzione per mantenere i parametri di compressione, replica e archiviazione. Le partizioni e i vincoli vengono sempre mantenuti.",
refreshDdlOnOpen: "Aggiorna a ogni apertura",
refreshDdlOnOpenHint: "Se attivo, il DDL viene ricaricato dal database a ogni apertura; se disattivo, vengono usati prima i dati memorizzati nella cache",
dropObject: "Elimina Oggetto",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 4839bd3ee1..e9068e7703 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -3625,6 +3625,8 @@ export default withEnglishFallback({
instanceInfo: "インスタンス情報",
viewDdlLoading: "DDLを読み込み中...",
ddlCopied: "DDLをコピーしました",
+ excludeDdlStorage: "ストレージ属性を除外",
+ excludeDdlStorageHint: "OceanBase Oracle の DDL の表示・コピーと構造のエクスポートに適用されます。無効にすると、圧縮・レプリカ・ストレージのパラメーターを保持します。パーティションと制約は常に保持されます。",
refreshDdlOnOpen: "開くたびに更新",
refreshDdlOnOpenHint: "有効にすると開くたびにデータベースから DDL を再取得し、無効にするとキャッシュを優先して使用します",
manageExtension: "拡張機能を管理...",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 032c339373..9c0c0f33f1 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -3291,6 +3291,8 @@ export default withEnglishFallback({
viewDdl: "DDL 보기",
viewDdlLoading: "DDL을 불러오는 중...",
ddlCopied: "DDL을 복사했습니다",
+ excludeDdlStorage: "스토리지 속성 제외",
+ excludeDdlStorageHint: "OceanBase Oracle의 DDL 표시, 복사 및 구조 내보내기에 적용됩니다. 끄면 압축, 복제본 및 스토리지 매개변수를 유지합니다. 파티션과 제약 조건은 항상 유지됩니다.",
dropObject: "객체 삭제",
dropView: "뷰 삭제",
dropColumn: "컬럼 삭제",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index bffbe10d2a..e354a6f5bd 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -3385,6 +3385,8 @@ export default withEnglishFallback({
viewDdl: "Ver DDL",
viewDdlLoading: "Carregando DDL...",
ddlCopied: "DDL copiado",
+ excludeDdlStorage: "Excluir atributos de armazenamento",
+ excludeDdlStorageHint: "Aplica-se à exibição e cópia de DDL e à exportação de estruturas do OceanBase Oracle. Desative esta opção para manter os parâmetros de compressão, réplicas e armazenamento. As partições e restrições são sempre mantidas.",
refreshDdlOnOpen: "Atualizar sempre que abrir",
refreshDdlOnOpenHint: "Quando ativado, o DDL é recarregado do banco de dados sempre que é aberto; quando desativado, os dados em cache têm prioridade",
dropObject: "Remover Objeto",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 933642ecbd..94065eef39 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -3339,6 +3339,8 @@ export default withEnglishFallback({
viewDdl: "DDL'i Görüntüle",
viewDdlLoading: "DDL yükleniyor...",
ddlCopied: "DDL kopyalandı",
+ excludeDdlStorage: "Depolama özelliklerini hariç tut",
+ excludeDdlStorageHint: "OceanBase Oracle DDL görüntüleme, kopyalama ve yapı dışa aktarma işlemlerine uygulanır. Sıkıştırma, replika ve depolama parametrelerini korumak için kapatın. Bölümler ve kısıtlamalar her zaman korunur.",
refreshDdlOnOpen: "Her açılışta yenile",
refreshDdlOnOpenHint: "Etkinleştirildiğinde DDL her açılışta veritabanından yeniden yüklenir; kapatıldığında önbellekteki veri tercih edilir",
dropObject: "Nesneyi Sil",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f6d702deba..c622ecea66 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -3451,6 +3451,8 @@ export default withEnglishFallback({
viewDdl: "查看 DDL",
viewDdlLoading: "正在读取 DDL...",
ddlCopied: "DDL 已复制",
+ excludeDdlStorage: "去掉存储属性",
+ excludeDdlStorageHint: "用于 OceanBase Oracle 的 DDL 显示、复制和结构导出。关闭后保留压缩、副本和存储参数;分区和约束始终保留。",
refreshDdlOnOpen: "每次打开时刷新",
refreshDdlOnOpenHint: "开启后每次打开都会从数据库重新读取;关闭时优先使用缓存",
dropObject: "删除对象",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 09159b194d..2c41bf283f 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -3389,6 +3389,8 @@ export default withEnglishFallback({
viewDdl: "檢視 DDL",
viewDdlLoading: "正在讀取 DDL...",
ddlCopied: "DDL 已複製",
+ excludeDdlStorage: "移除儲存屬性",
+ excludeDdlStorageHint: "用於 OceanBase Oracle 的 DDL 顯示、複製和結構匯出。關閉後保留壓縮、副本和儲存參數;分割區和約束條件一律保留。",
refreshDdlOnOpen: "每次開啟時重新整理",
refreshDdlOnOpenHint: "開啟後每次開啟都會從資料庫重新讀取;關閉時優先使用快取",
dropObject: "刪除物件",
diff --git a/apps/desktop/src/lib/sql/__tests__/ddlStorage.spec.ts b/apps/desktop/src/lib/sql/__tests__/ddlStorage.spec.ts
new file mode 100644
index 0000000000..f5400b1601
--- /dev/null
+++ b/apps/desktop/src/lib/sql/__tests__/ddlStorage.spec.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vitest";
+import { applyDdlStoragePreference } from "../ddlStorage";
+
+const raw = `CREATE TABLE "APP"."SALES" (
+ "ID" NUMBER NOT NULL,
+ "REGION" VARCHAR2(30) DEFAULT 'PCTFREE = 20',
+ CONSTRAINT "CK" CHECK ("ID" > 0)
+) COMPRESS FOR ARCHIVE REPLICA_NUM = 1 BLOCK_SIZE = 16384 USE_BLOOM_FILTER = FALSE TABLET_SIZE = 134217728 PCTFREE = 0
+partition by range("ID") subpartition by list("REGION")
+(partition "P1" values less than (100) (subpartition "S1" values ('PCTFREE = 20')));
+CREATE INDEX "I" ON "APP"."SALES"("REGION") LOCAL;
+COMMENT ON TABLE "APP"."SALES" IS 'COMPRESS FOR ARCHIVE';`;
+
+describe("OceanBase Oracle DDL storage preference", () => {
+ it("omits table storage by default and preserves the semantic DDL and comments", () => {
+ const logical = applyDdlStoragePreference(raw, "oceanbase-oracle");
+ expect(logical).not.toContain("REPLICA_NUM");
+ expect(logical).not.toContain("BLOCK_SIZE");
+ expect(logical).not.toContain("TABLET_SIZE");
+ expect(logical).not.toContain("PCTFREE = 0");
+ expect(logical).toContain("DEFAULT 'PCTFREE = 20'");
+ expect(logical.slice(logical.indexOf("partition by"))).toBe(raw.slice(raw.indexOf("partition by")));
+ expect(logical).toContain('CONSTRAINT "CK" CHECK ("ID" > 0)');
+ });
+ it("returns the complete original when disabled and leaves other databases unchanged", () => {
+ expect(applyDdlStoragePreference(raw, "oceanbase-oracle", false)).toBe(raw);
+ expect(applyDdlStoragePreference(raw, "oracle")).toBe(raw);
+ expect(applyDdlStoragePreference(raw, undefined)).toBe(raw);
+ });
+ it("preserves quoted identifiers, Oracle alternative strings, temporary-table semantics and comments", () => {
+ const ddl = `CREATE GLOBAL TEMPORARY TABLE "PCTFREE" ("A" VARCHAR2(100) DEFAULT q'[can't ) PCTFREE=42]') /* PCTFREE=9 */ PCTFREE=0 ON COMMIT PRESERVE ROWS;`;
+ expect(applyDdlStoragePreference(ddl, "oceanbase-oracle")).toBe(ddl.replace(" PCTFREE=0", " "));
+ });
+ it("filters each table without altering unknown attributes, non-table statements or incomplete SQL", () => {
+ const ddl = `CREATE TABLE T(A NUMBER) PCTFREE 0 TABLE_MODE='QUEUING'; CREATE TABLE U(A NUMBER) NOCOMPRESS PCTFREE=10; ALTER TABLE T PCTFREE 20;`;
+ expect(applyDdlStoragePreference(ddl, "oceanbase-oracle")).toBe(`CREATE TABLE T(A NUMBER) TABLE_MODE='QUEUING'; CREATE TABLE U(A NUMBER) ; ALTER TABLE T PCTFREE 20;`);
+ const broken = `CREATE TABLE T(A VARCHAR2(100) DEFAULT 'unclosed) PCTFREE=10`;
+ expect(applyDdlStoragePreference(broken, "oceanbase-oracle")).toBe(broken);
+ });
+});
diff --git a/apps/desktop/src/lib/sql/ddlStorage.ts b/apps/desktop/src/lib/sql/ddlStorage.ts
new file mode 100644
index 0000000000..eda1def772
--- /dev/null
+++ b/apps/desktop/src/lib/sql/ddlStorage.ts
@@ -0,0 +1,51 @@
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
+import type { DatabaseType } from "@/types/database";
+
+/** Remove only known OceanBase table storage options, keeping the cached source intact. */
+export function applyDdlStoragePreference(sql: string, databaseType: DatabaseType | undefined, excludeStorage = true): string {
+ if (databaseType !== "oceanbase-oracle" || !excludeStorage) return sql;
+ const tokens = tokenizeSqlSemantic(sql, "oracle");
+ if (tokens.some((token) => token.closed === false)) return sql;
+ const removals: Array<{ start: number; end: number }> = [];
+ let table = false;
+ let options = false;
+ for (let i = 0; i < tokens.length; i++) {
+ const token = tokens[i]!;
+ if (token.depth !== 0) continue;
+ if (token.text === ";") {
+ table = options = false;
+ continue;
+ }
+ if (token.kind === "word" && token.normalized === "create") {
+ const offset = tokens[i + 1]?.normalized === "global" && tokens[i + 2]?.normalized === "temporary" ? 3 : 1;
+ table = tokens[i + offset]?.normalized === "table";
+ options = false;
+ }
+ if (!table) continue;
+ if (token.text === ")") options = true;
+ if (!options || token.kind !== "word") continue;
+ // Partition expressions and bounds must never be treated as table options.
+ if (token.normalized === "partition") {
+ table = options = false;
+ continue;
+ }
+ let last = i;
+ if (token.normalized === "compress" && tokens[i + 1]?.normalized === "for" && tokens[i + 2]?.normalized === "archive") {
+ last = i + 2;
+ if (["high", "low"].includes(tokens[last + 1]?.normalized ?? "")) last++;
+ } else if (token.normalized === "nocompress") {
+ last = i;
+ } else if (["replica_num", "block_size", "tablet_size", "pctfree", "use_bloom_filter"].includes(token.normalized)) {
+ const valueIndex = tokens[i + 1]?.text === "=" ? i + 2 : i + 1;
+ const value = tokens[valueIndex];
+ const valid = token.normalized === "use_bloom_filter" ? value?.kind === "word" && ["true", "false"].includes(value.normalized) : value?.kind === "number" && /^\d+$/.test(value.text);
+ if (!valid) continue;
+ last = valueIndex;
+ } else continue;
+ removals.push({ start: token.span.start, end: tokens[last]!.span.end });
+ i = last;
+ }
+ let result = sql;
+ for (const { start, end } of removals.reverse()) result = result.slice(0, start) + result.slice(end);
+ return result;
+}
diff --git a/apps/desktop/src/lib/sql/semantic/tokens.ts b/apps/desktop/src/lib/sql/semantic/tokens.ts
index 47abaa31c5..2b759af593 100644
--- a/apps/desktop/src/lib/sql/semantic/tokens.ts
+++ b/apps/desktop/src/lib/sql/semantic/tokens.ts
@@ -149,6 +149,15 @@ export function tokenizeSqlSemantic(input: string, dialectId = "mysql", options?
continue;
}
+ if (dialectId === "oracle" && (ch === "q" || ch === "Q") && next === "'" && input[index + 2]) {
+ const opener = input[index + 2]!;
+ const closer = ({ "[": "]", "{": "}", "(": ")", "<": ">" } as Record<string, string>)[opener] ?? opener;
+ const end = input.indexOf(closer + "'", index + 3);
+ index = end < 0 ? input.length : end + 2;
+ tokens.push(token("string", input.slice(start, index), start, index, depth, "q'", end >= 0));
+ continue;
+ }
+
if (ch === "'") {
const quoted = readQuotedString(input, start, "'", mysqlBackslashEscape);
index = quoted.end;
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.xuguTableChildren.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.xuguTableChildren.spec.ts
index 08d6630d34..ba3c6d803a 100644
--- a/apps/desktop/src/stores/__tests__/connectionStore.xuguTableChildren.spec.ts
+++ b/apps/desktop/src/stores/__tests__/connectionStore.xuguTableChildren.spec.ts
@@ -115,6 +115,24 @@ describe("connectionStore Xugu table child metadata", () => {
expect(childTypes).toEqual(["group-columns", "group-fkeys", "group-triggers", "group-indexes"]);
});
+ it("loads OceanBase Oracle partitions and subpartitions through the metadata tree", async () => {
+ const partition = { name: "P1", position: 1, value: "100", partition_type: "RANGE", partition_key: '"ID"' };
+ const subpartition = { name: "P1_E", position: 1, value: "'east'", partition_type: "LIST", partition_key: '"REGION"' };
+ const { api, config, store, tableId } = await setup("oceanbase-oracle", {
+ listPartitions: vi.fn().mockResolvedValue([partition]),
+ listSubpartitions: vi.fn().mockResolvedValue([subpartition]),
+ });
+ const partitions = findNode(store.treeNodes, `${tableId}:__table-partitions`)!;
+ const subpartitions = findNode(store.treeNodes, `${tableId}:__table-subpartitions`)!;
+ expect(partitions).toBeDefined();
+ expect(subpartitions).toBeDefined();
+ await store.loadTreeNodeChildren(partitions);
+ await store.loadTreeNodeChildren(subpartitions);
+ expect(api.listPartitions).toHaveBeenCalledWith(config.id, "SHOP_DEMO", "SYSDBA", "SHOP_ORDERS", undefined);
+ expect(partitions.children?.[0]).toMatchObject({ label: "P1 (RANGE: 100)", meta: partition });
+ expect(subpartitions.children?.[0]).toMatchObject({ label: "P1_E (LIST: 'east')", meta: subpartition });
+ });
+
it("routes Xugu child groups to their dedicated metadata calls, including empty results", async () => {
const listConstraints = vi.fn().mockResolvedValue([
{
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index cbec431135..186d769c99 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -6608,34 +6608,34 @@ export const useConnectionStore = defineStore("connection", () => {
children: [],
});
}
- if (supportsXuguChildMetadata) {
- children.push(
- {
- id: `${parentId}:__table-partitions`,
- label: "tree.partitions",
- type: "group-table-partitions",
- connectionId,
- database,
- schema,
- catalog,
- tableName: table,
- isExpanded: false,
- children: [],
- },
- {
- id: `${parentId}:__table-subpartitions`,
- label: "tree.subpartitions",
- type: "group-table-subpartitions",
- connectionId,
- database,
- schema,
- catalog,
- tableName: table,
- isExpanded: false,
- children: [],
- },
- );
- }
+ }
+ if (supportsXuguChildMetadata || effectiveDbType === "oceanbase-oracle") {
+ children.push(
+ {
+ id: `${parentId}:__table-partitions`,
+ label: "tree.partitions",
+ type: "group-table-partitions",
+ connectionId,
+ database,
+ schema,
+ catalog,
+ tableName: table,
+ isExpanded: false,
+ children: [],
+ },
+ {
+ id: `${parentId}:__table-subpartitions`,
+ label: "tree.subpartitions",
+ type: "group-table-subpartitions",
+ connectionId,
+ database,
+ schema,
+ catalog,
+ tableName: table,
+ isExpanded: false,
+ children: [],
+ },
+ );
}
}
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index b52e14abc1..c462d4c771 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -775,6 +775,7 @@ export interface EditorSettings {
wordWrap: boolean;
tableDdlWordWrap: boolean;
refreshDdlOnOpen: boolean;
+ excludeDdlStorage: boolean;
vimModeEnabled: boolean;
autoCloseBrackets: boolean;
sqlSemanticDiagnosticsMode: SqlSemanticDiagnosticsMode;
@@ -1019,6 +1020,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
wordWrap: false,
tableDdlWordWrap: true,
refreshDdlOnOpen: false,
+ excludeDdlStorage: true,
vimModeEnabled: false,
autoCloseBrackets: true,
sqlSemanticDiagnosticsMode: "auto",
@@ -1501,6 +1503,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
selectFirstCompletionOnOpen: typeof settings.selectFirstCompletionOnOpen === "boolean" ? settings.selectFirstCompletionOnOpen : DEFAULT_EDITOR_SETTINGS.selectFirstCompletionOnOpen,
wordWrap: settings.wordWrap ?? DEFAULT_EDITOR_SETTINGS.wordWrap,
tableDdlWordWrap: typeof settings.tableDdlWordWrap === "boolean" ? settings.tableDdlWordWrap : DEFAULT_EDITOR_SETTINGS.tableDdlWordWrap,
+ excludeDdlStorage: typeof settings.excludeDdlStorage === "boolean" ? settings.excludeDdlStorage : DEFAULT_EDITOR_SETTINGS.excludeDdlStorage,
refreshDdlOnOpen: typeof settings.refreshDdlOnOpen === "boolean" ? settings.refreshDdlOnOpen : DEFAULT_EDITOR_SETTINGS.refreshDdlOnOpen,
vimModeEnabled: typeof settings.vimModeEnabled === "boolean" ? settings.vimModeEnabled : DEFAULT_EDITOR_SETTINGS.vimModeEnabled,
autoCloseBrackets: typeof settings.autoCloseBrackets === "boolean" ? settings.autoCloseBrackets : DEFAULT_EDITOR_SETTINGS.autoCloseBrackets,
@@ -2264,6 +2267,7 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.selectFirstCompletionOnOpen !== undefined) editorSettings.value.selectFirstCompletionOnOpen = partial.selectFirstCompletionOnOpen === true;
if (partial.wordWrap !== undefined) editorSettings.value.wordWrap = partial.wordWrap;
if (partial.tableDdlWordWrap !== undefined) editorSettings.value.tableDdlWordWrap = partial.tableDdlWordWrap === true;
+ if (partial.excludeDdlStorage !== undefined) editorSettings.value.excludeDdlStorage = partial.excludeDdlStorage === true;
if (partial.refreshDdlOnOpen !== undefined) editorSettings.value.refreshDdlOnOpen = partial.refreshDdlOnOpen === true;
if (partial.vimModeEnabled !== undefined) editorSettings.value.vimModeEnabled = partial.vimModeEnabled === true;
if (partial.autoCloseBrackets !== undefined) editorSettings.value.autoCloseBrackets = partial.autoCloseBrackets === true;
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 2a1c073554..2e799c16f2 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1499,6 +1499,9 @@ export interface TableStructureEditorDraft {
activeTab: TableInfoTab;
/** DDL as loaded from the database — the baseline `ddlDraft` is compared against. */
ddlContent?: string;
+ /** Original DDL and display preference retained so restoring a draft cannot change its baseline. */
+ rawDdlContent?: string;
+ excludeDdlStorage?: boolean;
/** Edited DDL script, or null/undefined when the DDL tab was left untouched. */
ddlDraft?: string | null;
newTableName: string;