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(data-grid): support cloning rows without primary keys

zipg3d1601c8073f
diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts
index f3801264d7..3cc6bd568d 100644
--- a/apps/desktop/src/composables/useDataGridEditor.ts
+++ b/apps/desktop/src/composables/useDataGridEditor.ts
@@ -871,7 +871,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
function clonedRowData(item: RowItem): CellValue[] {
const columnInfoByName = new Map((tableMeta.value?.columns ?? []).map((column) => [column.name.toLowerCase(), column]));
return item.data.map((val, i) => {
- const columnName = result.value.columns[i];
+ const columnName = sourceColumns.value?.[i] ?? result.value.columns[i];
const columnInfo = columnInfoByName.get(columnName.toLowerCase());
return shouldClearClonedColumn(columnName, columnInfo) ? null : val;
});
diff --git a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts
index 8bb2125982..e96378eb99 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts
@@ -146,6 +146,32 @@ describe("queryStore hidden primary key editing", () => {
expect(tab.queryEditabilityReason).toBeUndefined();
});
+ it("keeps insert disabled when a MySQL table has a physical primary key named like DBX ROWID", async () => {
+ getColumns.mockResolvedValue([
+ { name: "__DBX_ROWID", data_type: "varchar", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
+ { name: "name", data_type: "varchar", is_nullable: true, column_default: null, is_primary_key: false, extra: null },
+ ]);
+ analyzeEditableQueryEditability.mockImplementation(async (sql: string) => ({
+ editable: true,
+ analysis: {
+ schema: undefined,
+ tableName: "users",
+ selectStar: false,
+ columns: [{ sourceName: "name", resultName: "name", expression: "name" }, ...(sql.includes("__DBX_PK_0") ? [{ sourceName: "__DBX_ROWID", resultName: "__DBX_PK_0", expression: "`__DBX_ROWID`" }] : [])],
+ },
+ }));
+
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+ const tabId = store.createTab("mysql-1", "app", "Query");
+
+ await store.executeTabSql(tabId, "SELECT name FROM users");
+
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ await vi.waitFor(() => expect(tab.querySourceColumns).toEqual(["name", "__DBX_ROWID"]));
+ expect(tab.queryAnalysis?.allowInsert).toBe(false);
+ });
+
it("uses the connection default database for SQL library tabs without a saved database", async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
@@ -266,7 +292,7 @@ describe("queryStore hidden primary key editing", () => {
await vi.waitFor(() => expect(tab.querySourceColumns).toEqual(["ID", "PLATFORM", "__DBX_ROWID"]));
expect(tab.tableMeta?.primaryKeys).toEqual(["__DBX_ROWID"]);
expect(tab.queryAnalysis).toBeDefined();
- expect(tab.queryAnalysis?.allowInsert).toBe(false);
+ expect(tab.queryAnalysis?.allowInsert).not.toBe(false);
expect(tab.queryEditabilityReason).toBeUndefined();
});
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index d6ab51affe..e3dad59c7e 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -72,6 +72,10 @@ const CANCEL_ACK_SETTLE_TIMEOUT_MS = 2_000;
const SAVED_SQL_EDITOR_POSITION_PERSIST_DELAY_MS = 500;
type CloseConfirmContext = "tab" | "batch" | "app";
+function hasHiddenPhysicalRowKey(databaseType: DatabaseType | undefined, hiddenPrimaryKeys: HiddenPrimaryKeyProjection[]): boolean {
+ return hiddenPrimaryKeys.some((projection) => !usesSyntheticRowIdKey(databaseType, [projection.sourceName]));
+}
+
function cloneTabDraft<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
@@ -2794,13 +2798,13 @@ export const useQueryStore = defineStore("query", () => {
}
}
- function analyzeQueryMetadataInBackground(tabId: string, sql: string, result: QueryResult, executionDatabase: string, traceId: string, elapsed: () => string, hiddenPrimaryKeys: HiddenPrimaryKeyProjection[] = []) {
+ function analyzeQueryMetadataInBackground(tabId: string, sql: string, result: QueryResult, executionDatabase: string, traceId: string, elapsed: () => string, databaseType: DatabaseType | undefined, hiddenPrimaryKeys: HiddenPrimaryKeyProjection[] = []) {
void (async () => {
const tab = tabs.value.find((t) => t.id === tabId);
if (!tab || tab.result !== result) return;
queryExecutionLog("info", "metadata:start", { traceId, elapsed: elapsed() });
const patch = await buildQueryMetadataPatch(tab, sql, executionDatabase, traceId, elapsed, hiddenPrimaryKeys);
- if (patch?.queryAnalysis && hiddenPrimaryKeys.length > 0) {
+ if (patch?.queryAnalysis && hasHiddenPhysicalRowKey(databaseType, hiddenPrimaryKeys)) {
patch.queryAnalysis = { ...patch.queryAnalysis, allowInsert: false };
}
const current = tabs.value.find((t) => t.id === tabId);
@@ -3637,7 +3641,7 @@ export const useQueryStore = defineStore("query", () => {
elapsed: elapsed(),
});
if (current.mode === "query" && current.result) {
- analyzeQueryMetadataInBackground(id, displayedQueryMetadataSql(current, queryMetadataSql), current.result, executionDatabase, traceId, elapsed, hiddenPrimaryKeys);
+ analyzeQueryMetadataInBackground(id, displayedQueryMetadataSql(current, queryMetadataSql), current.result, executionDatabase, traceId, elapsed, effectiveDbType, hiddenPrimaryKeys);
}
} else {
queryExecutionLog("warn", "stale-result", {
@@ -4088,7 +4092,7 @@ export const useQueryStore = defineStore("query", () => {
const metadataStartedAt = performance.now();
const connection = useConnectionStore().getConfig(tab.connectionId);
const executionDatabase = dataTabExecutionDatabase(connection, tab.database, tab.catalog);
- analyzeQueryMetadataInBackground(id, sourceStatement, tab.result, executionDatabase, uuid().slice(0, 8), () => `${Math.round(performance.now() - metadataStartedAt)}ms`);
+ analyzeQueryMetadataInBackground(id, sourceStatement, tab.result, executionDatabase, uuid().slice(0, 8), () => `${Math.round(performance.now() - metadataStartedAt)}ms`, effectiveDatabaseTypeForConnection(connection));
}
}
diff --git a/crates/dbx-core/src/data_grid_sql.rs b/crates/dbx-core/src/data_grid_sql.rs
index a3c853de62..17a87c1846 100644
--- a/crates/dbx-core/src/data_grid_sql.rs
+++ b/crates/dbx-core/src/data_grid_sql.rs
@@ -5951,6 +5951,41 @@ mod tests {
}
}
+ #[test]
+ fn prepare_data_grid_save_omits_hidden_oracle_rowid_from_cloned_row_insert() {
+ let result = prepare_data_grid_save(DataGridSaveStatementOptions {
+ database_type: Some(DatabaseType::Oracle),
+ identifier_quote: None,
+ table_meta: DataGridTableMeta {
+ catalog: None,
+ database: None,
+ schema: Some("APP".to_string()),
+ table_name: "TT_PLATFORM_CARS".to_string(),
+ primary_keys: vec![DBX_ROWID_COLUMN.to_string()],
+ columns: Some(vec![
+ column("ID", "NUMBER", false, None),
+ column("PLATFORM", "VARCHAR2(100)", true, None),
+ ]),
+ },
+ columns: vec!["ID".to_string(), "PLATFORM".to_string(), "__DBX_PK_0".to_string()],
+ source_columns: Some(vec![
+ Some("ID".to_string()),
+ Some("PLATFORM".to_string()),
+ Some(DBX_ROWID_COLUMN.to_string()),
+ ]),
+ rows: vec![],
+ dirty_rows: vec![],
+ deleted_rows: vec![],
+ new_rows: vec![vec![json!(72), json!("轻卡"), Value::Null]],
+ });
+
+ assert_eq!(result.validation_error, None);
+ assert_eq!(
+ result.statements,
+ vec![r#"INSERT INTO "APP"."TT_PLATFORM_CARS" ("ID", "PLATFORM") VALUES (72, '轻卡');"#]
+ );
+ }
+
#[test]
fn prepare_data_grid_save_skips_sqlite_autoincrement_pk_validation() {
let result = prepare_data_grid_save(DataGridSaveStatementOptions {
diff --git a/packages/app-tests/dataGridEditor.test.ts b/packages/app-tests/dataGridEditor.test.ts
index dadb87d5d9..5343bb1e02 100644
--- a/packages/app-tests/dataGridEditor.test.ts
+++ b/packages/app-tests/dataGridEditor.test.ts
@@ -429,6 +429,60 @@ test("cloning a row clears auto-generated key columns", async () => {
assert.deepEqual(editor.newRows.value, [[null, "Ada"]]);
});
+test("cloning an Oracle keyless row clears the hidden ROWID source column", async () => {
+ setActivePinia(createPinia());
+ installBrowserTestGlobals();
+
+ const result = computed(() => ({
+ columns: ["ID", "PLATFORM", "__DBX_PK_0"],
+ rows: [[72, "轻卡", "AAAPr9AAEAAAACXAAA"] as CellValue[]],
+ }));
+ const rowStatusFilter = ref<"all" | "changed" | "edited" | "new" | "deleted">("all");
+ let editor: ReturnType<typeof useDataGridEditor>;
+
+ editor = useDataGridEditor({
+ result,
+ editable: computed(() => true),
+ databaseType: computed(() => "oracle"),
+ connectionId: computed(() => undefined),
+ database: computed(() => undefined),
+ tableMeta: computed(() => ({
+ tableName: "TT_PLATFORM_CARS",
+ columns: [column("ID"), column("PLATFORM")],
+ primaryKeys: ["__DBX_ROWID"],
+ })),
+ sourceColumns: computed(() => ["ID", "PLATFORM", "__DBX_ROWID"]),
+ onExecuteSql: computed(() => undefined),
+ customSaveHandler: computed(() => undefined),
+ sql: computed(() => undefined),
+ searchText: ref(""),
+ whereFilterInput: ref(""),
+ orderByInput: ref(""),
+ currentWhereInput: computed(() => undefined),
+ rowStatusFilter,
+ pageSize: ref(100),
+ currentPage: ref(1),
+ getRowItem: (rowId) => {
+ if (rowId !== 0) return undefined;
+ return {
+ id: 0,
+ sourceIndex: 0,
+ data: result.value.rows[0],
+ isNew: false,
+ isDeleted: false,
+ isDirtyCol: [false, false, false],
+ status: "clean",
+ };
+ },
+ emit: () => {},
+ });
+
+ editor.cloneRow(0);
+ await nextTick();
+
+ assert.deepEqual(editor.newRows.value, [[72, "轻卡", null]]);
+});
+
test("saving deleted rows reloads current table data", async () => {
setActivePinia(createPinia());
installBrowserTestGlobals();