From 0fd1d6108f53474e104599f4414712f3447b4348 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 27 Sep 2026 12:29:05 +0000 Subject: [PATCH] feat(influxdb): add guarded point deletion Closes #9818 --- apps/desktop/src/components/grid/DataGrid.vue | 90 ++++--- .../src/components/layout/ContentArea.vue | 43 +++- .../ContentArea.influxDbV1Delete.spec.ts | 192 ++++++++++++++ .../__tests__/useDataGridEditor.spec.ts | 58 ++++- .../src/composables/useDataGridEditor.ts | 67 +++-- .../useDataGridSaveConfirmation.ts | 64 +++++ .../useSalesforceSaveConfirmation.ts | 79 +----- apps/desktop/src/i18n/locales/en.ts | 4 + apps/desktop/src/i18n/locales/zh-CN.ts | 4 + .../__tests__/influxDbV1Delete.spec.ts | 176 +++++++++++++ .../src/lib/influxdb/influxDbV1Delete.ts | 243 ++++++++++++++++++ crates/dbx-drivers/src/db/influxdb_driver.rs | 171 ++++++++---- 12 files changed, 1007 insertions(+), 184 deletions(-) create mode 100644 apps/desktop/src/components/layout/__tests__/ContentArea.influxDbV1Delete.spec.ts create mode 100644 apps/desktop/src/composables/useDataGridSaveConfirmation.ts create mode 100644 apps/desktop/src/lib/influxdb/__tests__/influxDbV1Delete.spec.ts create mode 100644 apps/desktop/src/lib/influxdb/influxDbV1Delete.ts diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue index 780df53bd1..069931fe35 100644 --- a/apps/desktop/src/components/grid/DataGrid.vue +++ b/apps/desktop/src/components/grid/DataGrid.vue @@ -374,7 +374,7 @@ import { useDataGridColumnFormatter } from "@/composables/useDataGridColumnForma import { useDataGridTableMetadataLoaders } from "@/composables/useDataGridTableMetadataLoaders"; import { DATA_GRID_SERVER_COLUMN_FILTER_LIMIT, useDataGridColumnFilters } from "@/composables/useDataGridColumnFilters"; import { useDataGridLargeValues } from "@/composables/useDataGridLargeValues"; -import { useSalesforceSaveConfirmation } from "@/composables/useSalesforceSaveConfirmation"; +import { useDataGridSaveConfirmation } from "@/composables/useDataGridSaveConfirmation"; const SqlPreviewPanel = defineAsyncComponent(() => import("@/components/editor/SqlPreviewPanel.vue")); const ImagePreviewDialog = defineAsyncComponent(() => import("@/components/grid/ImagePreviewDialog.vue")); @@ -3274,6 +3274,7 @@ const resultSourceColumns = computed(() => props.result.columns.map((column, ind const canEditExistingRows = computed( () => !!props.customSaveHandler || (canEditExistingTableRows(props.databaseType, hiveTableTransactional.value, props.tableMeta?.primaryKeys ?? []) && hasCompleteTdengineRowIdentity(props.databaseType, props.tableMeta?.primaryKeys ?? [], resultSourceColumns.value)), ); +const canUpdateExistingRows = computed(() => canEditExistingRows.value && props.customSaveHandler?.canUpdate !== false); const customReadonlyColumns = computed(() => new Set((props.customSaveHandler?.readonlyColumns ?? []).map((column) => column.toLowerCase()))); const hasDataGridSaveTarget = computed(() => !!props.tableMeta || !!props.customSaveHandler); const hasDataGridInsertTarget = computed(() => { @@ -3813,22 +3814,22 @@ async function refreshSavedRows(request: { dirtyRows: ReadonlyMap resolvedDatabaseType.value === "salesforce"); +const isInfluxDbV1DeleteGrid = computed(() => props.customSaveHandler?.confirmation === "influxdb-v1-delete"); const salesforceIdentity = computed(() => (isSalesforceGrid.value && props.connectionId ? connectionStore.salesforceCurrentUser(props.connectionId) : null)); const salesforceIdentityLabel = computed(() => { const identity = salesforceIdentity.value; @@ -3837,9 +3838,9 @@ const salesforceIdentityLabel = computed(() => { }); const salesforceSaveConfirmSummary = computed(() => { const parts: string[] = []; - if (salesforceSaveConfirmUpdates.value > 0) parts.push(t("grid.salesforceSaveUpdates", { count: salesforceSaveConfirmUpdates.value })); - if (salesforceSaveConfirmInserts.value > 0) parts.push(t("grid.salesforceSaveInserts", { count: salesforceSaveConfirmInserts.value })); - if (salesforceSaveConfirmDeletes.value > 0) parts.push(t("grid.salesforceSaveDeletes", { count: salesforceSaveConfirmDeletes.value })); + if (saveConfirmUpdates.value > 0) parts.push(t("grid.salesforceSaveUpdates", { count: saveConfirmUpdates.value })); + if (saveConfirmInserts.value > 0) parts.push(t("grid.salesforceSaveInserts", { count: saveConfirmInserts.value })); + if (saveConfirmDeletes.value > 0) parts.push(t("grid.salesforceSaveDeletes", { count: saveConfirmDeletes.value })); return parts.join(" · "); }); // The save dialog names the profile alongside the user: writability comes from @@ -3849,7 +3850,7 @@ const salesforceIdentityProfile = computed(() => { return profileName ? t("grid.salesforceSaveProfile", { name: profileName }) : t("toolbar.salesforceIdentityUnknownProfile"); }); const salesforceSaveConfirmDetails = computed(() => { - const lines = [salesforceSaveConfirmSummary.value, t("grid.salesforceSaveTarget", { object: salesforceSaveConfirmTarget.value || t("grid.salesforceSaveUnknownObject") })]; + const lines = [salesforceSaveConfirmSummary.value, t("grid.salesforceSaveTarget", { object: saveConfirmTarget.value || t("grid.salesforceSaveUnknownObject") })]; if (salesforceIdentity.value) { const identity = { user: salesforceIdentityLabel.value, profile: salesforceIdentityProfile.value }; if (salesforceIdentity.value.isAdmin === true) lines.push(t("grid.salesforceSaveAdminIdentity", identity)); @@ -3858,9 +3859,13 @@ const salesforceSaveConfirmDetails = computed(() => { } return lines.filter((line) => !!line).join("\n"); }); -const salesforceSaveConfirmSql = computed(() => salesforceSaveConfirmStatements.value.join("\n")); -watch(salesforceSaveConfirmOpen, (isOpen) => { - if (!isOpen || !props.connectionId) return; +const saveConfirmSql = computed(() => saveConfirmStatements.value.join("\n")); +const saveConfirmTitle = computed(() => (isInfluxDbV1DeleteGrid.value ? t("grid.influxDeleteConfirmTitle") : t("grid.salesforceSaveConfirmTitle"))); +const saveConfirmMessage = computed(() => (isInfluxDbV1DeleteGrid.value ? t("grid.influxDeleteConfirmMessage", { count: saveConfirmDeletes.value }) : t("grid.salesforceSaveConfirmMessage", { count: saveConfirmTotal.value }))); +const saveConfirmDetails = computed(() => (isInfluxDbV1DeleteGrid.value ? t("grid.influxDeleteTarget", { measurement: saveConfirmTarget.value || "—" }) : salesforceSaveConfirmDetails.value)); +const saveConfirmLabel = computed(() => (isInfluxDbV1DeleteGrid.value ? t("grid.influxDeleteConfirm") : t("grid.salesforceSaveConfirm"))); +watch(saveConfirmOpen, (isOpen) => { + if (!isOpen || !isSalesforceGrid.value || !props.connectionId) return; void connectionStore.loadSalesforceCurrentUser(props.connectionId); }); @@ -3888,8 +3893,7 @@ const editor = useDataGridEditor({ rowStatusFilter, dataGridQuickEntryEnabled: computed(() => settingsStore.editorSettings.dataGridQuickEntry), confirmDangerousRowDeletion: computed(() => settingsStore.editorSettings.confirmDangerousSqlExecution), - // Only Salesforce opts in: its writes cannot be rolled back once issued. - confirmSaveRequest: computed(() => (isSalesforceGrid.value ? requestSalesforceSaveConfirmation : undefined)), + confirmSaveRequest: computed(() => (isSalesforceGrid.value || isInfluxDbV1DeleteGrid.value ? requestDataGridSaveConfirmation : undefined)), includeDatabaseNameInSaveSql: computed(() => settingsStore.editorSettings.generateSqlIncludeDatabaseName), initialEditColumn: firstVisibleColumnIndex, cellEditorText: cellEditorTextForValue, @@ -4083,7 +4087,8 @@ function canEditRowItem(item: RowItem | undefined): boolean { } function canEditCellItem(item: RowItem | undefined, columnIndex: number): boolean { - if (!canEditRowItem(item) || !canEditColumn(columnIndex)) return false; + if (!canEditRowItem(item) || !item || !canEditColumn(columnIndex)) return false; + if (!item.isNew && !item.isDraft && !canUpdateExistingRows.value) return false; if (isSavingNewRow(item)) return false; const column = props.result.columns[columnIndex] ?? ""; if (customReadonlyColumns.value.has(column.toLowerCase())) return false; @@ -4346,7 +4351,7 @@ function isDecimalColumnType(dataType: string): boolean { function canDeleteRowItem(item: RowItem | undefined): boolean { if (!item) return false; - return canDeleteGridRowItem({ + const canDelete = canDeleteGridRowItem({ editable: !!props.editable && canDeleteRows.value, isDraft: !!item.isDraft, isDeleted: item.isDeleted, @@ -4354,6 +4359,8 @@ function canDeleteRowItem(item: RowItem | undefined): boolean { canEditExistingRows: canEditExistingRows.value && canDeleteExistingRows.value, isSavingNewRow: isSavingNewRow(item), }); + if (!canDelete || item.isNew || !props.customSaveHandler?.canDeleteRow) return canDelete; + return item.sourceIndex !== undefined && props.customSaveHandler.canDeleteRow(item.sourceIndex, item.data); } function resetInfiniteScrollState() { @@ -5743,7 +5750,11 @@ function affectedRowIds(): number[] { } function deletableRowIds(rowIds: number[]): number[] { - return rowIds.filter((rowId) => canDeleteRowItem(getRowItem(rowId))); + const eligible = rowIds.filter((rowId) => canDeleteRowItem(getRowItem(rowId))); + // A custom row-safety predicate is an all-or-nothing contract. Never silently + // drop an unsafe row from a multi-row request while deleting its neighbors. + if (props.customSaveHandler?.canDeleteRow && eligible.length !== rowIds.length) return []; + return eligible; } function exportSelectedRowsCsv() { @@ -8370,7 +8381,7 @@ function selectedRangeTargetsOnlyDraftRow(): boolean { return displayItemAt(range.startRow)?.isDraft === true; } -const replaceAvailable = computed(() => !!props.editable && hasDataGridSaveTarget.value && canEditExistingRows.value && !resolvedConnectionConfig.value?.read_only && !isConditionalUpdateActive.value); +const replaceAvailable = computed(() => !!props.editable && hasDataGridSaveTarget.value && canUpdateExistingRows.value && !resolvedConnectionConfig.value?.read_only && !isConditionalUpdateActive.value); const replaceResolving = ref(false); const replaceBusy = computed(() => replaceResolving.value || isSaving.value || gridSurfaceBusy.value || props.loading === true); @@ -11918,6 +11929,8 @@ function exportSubmenu(): ContextMenuItem { const gridContextMenuItems = computed(() => { const row = contextRowItem.value; const rowLabels = rowActionLabels(); + const rowIdsForDelete = isMultiRow.value ? affectedRowIds() : row ? [row.id] : []; + const deletableContextRowIds = deletableRowIds(rowIdsForDelete); const hasEditableSelection = selectionHasEditableCells(); const selectedColumnCount = selectedVisibleColumnIndexes().length; const gridSnapshotContext = contextHeaderColumn.value && hasColumnSelection.value ? "columns" : contextCell.value?.col === -1 && affectedRowIds().length > 0 ? "rows" : contextCell.value && hasCellSelection.value && selectedCellMatrix.value ? "cells" : null; @@ -12087,13 +12100,15 @@ const gridContextMenuItems = computed(() => { hasRow: !!row, canClone: !!row && canInsertRows.value && !row.isDraft, deleted: !!row?.isDeleted, - canDelete: !!row && canDeleteRowItem(row), + canDelete: deletableContextRowIds.length > 0, labels: rowLabels, icons: { clone: CopyPlus, restore: Undo2, delete: Trash2 }, actions: { clone: () => void (isMultiRow.value ? cloneRows(affectedRowIds()) : row && cloneRow(row.id)), restore: () => (isMultiRow.value ? restoreRows(affectedRowIds()) : row && restoreRow(row.id)), - delete: () => (isMultiRow.value ? requestDeleteRows(deletableRowIds(affectedRowIds())) : row && requestDeleteRow(row.id)), + delete: () => { + if (deletableContextRowIds.length > 0) requestDeleteRows(deletableContextRowIds); + }, }, }), [exportSubmenu()], @@ -14289,18 +14304,9 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val :close-on-confirm="false" @confirm="confirmDropAllMongoIndexes" /> - - + + (() = return { save, preview, applySavedChanges, canInsert: false, canDelete: true, supportsInsert: false, readonlyColumns: [target.idColumn], targetLabel: target.collection }; }); +const influxDbV1DeleteSaveHandler = computed(() => { + const tab = props.activeTab; + const result = tab.result; + const tableMeta = activeTableMeta.value; + const connection = connectionStore.getConfig(tab.connectionId) ?? props.activeConnection; + const database = activeDataTabExecutionDatabase.value; + if (tab.mode !== "data" || tab.tableMetaPending || !result || !tableMeta || !tab.connectionId || !database.trim()) return undefined; + + const target = resolveInfluxDbV1DeleteTarget({ + connection, + measurement: tableMeta.tableName, + tableColumns: tableMeta.columns, + resultColumns: result.columns, + }); + if (!target) return undefined; + + const preview: NonNullable = async (changes) => buildInfluxDbV1DeleteStatements(target, changes); + const save: CustomSaveHandler["save"] = async (changes) => { + const statements = buildInfluxDbV1DeleteStatements(target, changes); + if (statements.length === 0) throw new Error("InfluxDB deletion requires at least one guarded statement."); + for (const statement of statements) { + await api.executeQuery(tab.connectionId, database, statement); + } + }; + + return { + save, + preview, + canInsert: false, + canUpdate: false, + canDelete: true, + canDeleteRow: (_sourceIndex, row) => canDeleteInfluxDbV1Row(target, row), + confirmation: "influxdb-v1-delete", + reloadOnFailure: true, + supportsInsert: false, + readonlyColumns: [...result.columns], + targetLabel: target.measurement, + }; +}); const resultsPaneOpen = ref(false); const resultsPaneSize = ref(Number(safeLocalStorageGet("dbx-results-pane-size")) || DEFAULT_QUERY_RESULTS_PANE_SIZE); // In editor-only mode the results pane is never mounted in this splitpanes, @@ -2748,7 +2788,8 @@ defineExpose({ :initial-order-by-input="activeTab.orderByInput" :sql="activeTab.sql" :loading="activeTab.isExecuting" - :editable="!activeTab.tableMetaPending && isTableDataEditable(activeEffectiveDatabaseType, activeTableMeta?.primaryKeys ?? [], activeTableMeta?.tableType)" + :editable="!activeTab.tableMetaPending && (isTableDataEditable(activeEffectiveDatabaseType, activeTableMeta?.primaryKeys ?? [], activeTableMeta?.tableType) || !!influxDbV1DeleteSaveHandler)" + :custom-save-handler="influxDbV1DeleteSaveHandler" context="table-data" :initial-where-input="activeTab.whereInput" :database-type="activeEffectiveDatabaseType" diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.influxDbV1Delete.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.influxDbV1Delete.spec.ts new file mode 100644 index 0000000000..f87d71cbbe --- /dev/null +++ b/apps/desktop/src/components/layout/__tests__/ContentArea.influxDbV1Delete.spec.ts @@ -0,0 +1,192 @@ +// @vitest-environment happy-dom +import { createApp, defineComponent, h, nextTick, type App } from "vue"; +import { createPinia, setActivePinia } from "pinia"; +import { createI18n } from "vue-i18n"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ColumnInfo, ConnectionConfig, QueryResult, QueryTab } from "@/types/database"; +import type { CustomSaveHandler } from "@/composables/useDataGridEditor"; +import { INFLUXDB_V1_FIELD_COLUMN_EXTRA, INFLUXDB_V1_TAG_COLUMN_EXTRA, INFLUXDB_V1_TIME_COLUMN_EXTRA } from "@/lib/influxdb/influxDbV1Delete"; + +const mocks = vi.hoisted(() => ({ executeQuery: vi.fn(), handler: undefined as unknown })); + +vi.mock("@/components/editor/QueryEditor.vue", () => ({ default: { render: () => null } })); +vi.mock("@/components/grid/DataGridColumnLayoutPopover.vue", () => ({ default: { render: () => null } })); +vi.mock("@/lib/backend/api", async (importOriginal) => ({ ...(await importOriginal()), executeQuery: mocks.executeQuery })); +vi.mock("@/components/grid/DataGrid.vue", () => ({ + __esModule: true, + default: defineComponent({ + name: "DataGridStub", + props: { + editable: Boolean, + customSaveHandler: Object, + result: Object, + }, + setup(props) { + return () => { + const handler = props.customSaveHandler as CustomSaveHandler | undefined; + mocks.handler = handler; + const result = props.result as QueryResult; + return h("div", { + "data-test": "data-grid", + "data-editable": String(props.editable), + "data-delete-handler": handler?.confirmation ?? "none", + "data-can-update": String(handler?.canUpdate ?? false), + "data-reload-on-failure": String(handler?.reloadOnFailure ?? false), + "data-readonly-columns": handler?.readonlyColumns?.join(",") ?? "", + "data-first-row-deletable": String(handler?.canDeleteRow?.(0, result.rows[0] ?? []) ?? false), + }); + }; + }, + }), +})); + +import ContentArea from "../ContentArea.vue"; +import { useConnectionStore } from "@/stores/connectionStore"; + +const mounted: Array<{ app: App; host: HTMLElement }> = []; + +function column(name: string, extra: string, primary = false): ColumnInfo { + return { + name, + data_type: extra === INFLUXDB_V1_TIME_COLUMN_EXTRA ? "timestamp" : "string", + is_nullable: extra !== INFLUXDB_V1_TIME_COLUMN_EXTRA, + column_default: null, + is_primary_key: primary, + extra, + }; +} + +function connection(db_type: ConnectionConfig["db_type"], version?: string): ConnectionConfig { + return { + id: `connection-${db_type}-${version ?? "legacy"}`, + name: "Influx test", + db_type, + host: "localhost", + port: 8086, + username: "", + password: "", + database: "metrics", + external_config: version === undefined ? undefined : { version }, + }; +} + +function dataTab(connectionId: string, options: { tagValue?: string | null; metadataRole?: string } = {}): QueryTab { + const columns = [column("time", INFLUXDB_V1_TIME_COLUMN_EXTRA, true), column("host", options.metadataRole ?? INFLUXDB_V1_TAG_COLUMN_EXTRA, true), column("usage", INFLUXDB_V1_FIELD_COLUMN_EXTRA)]; + return { + id: "data-cpu", + title: "cpu", + connectionId, + database: "metrics", + mode: "data", + sql: "cpu", + isExecuting: false, + result: { + columns: ["time", "host", "usage"], + rows: [["2026-09-27T10:11:12Z", options.tagValue === undefined ? "web01" : options.tagValue, 42]], + affected_rows: 1, + execution_time_ms: 1, + }, + tableMeta: { tableName: "cpu", columns, primaryKeys: ["time", "host"] }, + }; +} + +async function mount(connectionConfig: ConnectionConfig, tab = dataTab(connectionConfig.id)) { + const pinia = createPinia(); + setActivePinia(pinia); + useConnectionStore().connections = [connectionConfig]; + const host = document.createElement("div"); + document.body.appendChild(host); + const app = createApp( + defineComponent({ + setup: () => () => + h(ContentArea, { + activeTab: tab, + activeConnection: connectionConfig, + activeOutputView: "result", + executableSql: "", + formatSqlRequest: null, + compressSqlRequest: null, + selectedSql: "", + cursorPos: 0, + blockDangerousRedisCommands: false, + }), + }), + ); + app.use(pinia); + app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false })); + app.mount(host); + mounted.push({ app, host }); + await nextTick(); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + const grid = host.querySelector('[data-test="data-grid"]'); + expect(grid).not.toBeNull(); + return grid!; +} + +afterEach(() => { + for (const { app, host } of mounted.splice(0)) { + app.unmount(); + host.remove(); + } + mocks.executeQuery.mockReset(); + mocks.handler = undefined; + localStorage.clear(); +}); + +describe("ContentArea InfluxDB 1.x delete gating", () => { + it("enables only the delete handler while keeping every value column read-only", async () => { + const grid = await mount(connection("influxdb", "1")); + + expect(grid.dataset.editable).toBe("true"); + expect(grid.dataset.deleteHandler).toBe("influxdb-v1-delete"); + expect(grid.dataset.canUpdate).toBe("false"); + expect(grid.dataset.reloadOnFailure).toBe("true"); + expect(grid.dataset.readonlyColumns).toBe("time,host,usage"); + expect(grid.dataset.firstRowDeletable).toBe("true"); + }); + + it("executes the guarded preview verbatim and propagates backend failures", async () => { + const config = connection("influxdb", "1"); + await mount(config); + const handler = mocks.handler as CustomSaveHandler; + const changes = { + dirtyRows: new Map(), + newRows: [], + newRowMeta: [], + deletedRows: new Set([0]), + columns: ["time", "host", "usage"], + rows: [["2026-09-27T10:11:12Z", "web01", 42]], + }; + const statements = await handler.preview!(changes); + mocks.executeQuery.mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 }); + + await handler.save(changes); + + expect(mocks.executeQuery).toHaveBeenCalledWith(config.id, "metrics", statements[0]); + + mocks.executeQuery.mockRejectedValueOnce(new Error("InfluxDB rejected the delete")); + await expect(handler.save(changes)).rejects.toThrow("InfluxDB rejected the delete"); + }); + + it("keeps a row with a missing tag unavailable for deletion", async () => { + const config = connection("influxdb", "1"); + const grid = await mount(config, dataTab(config.id, { tagValue: null })); + + expect(grid.dataset.deleteHandler).toBe("influxdb-v1-delete"); + expect(grid.dataset.firstRowDeletable).toBe("false"); + }); + + it.each([ + { dbType: "influxdb" as const, version: "2", metadataRole: INFLUXDB_V1_TAG_COLUMN_EXTRA, existingEditable: false }, + { dbType: "influxdb3" as const, version: "3", metadataRole: INFLUXDB_V1_TAG_COLUMN_EXTRA, existingEditable: true }, + { dbType: "influxdb" as const, version: "1", metadataRole: "", existingEditable: false }, + ])("does not add the delete path for an unsupported engine or metadata shape ($dbType/$version)", async ({ dbType, version, metadataRole, existingEditable }) => { + const config = connection(dbType, version); + const grid = await mount(config, dataTab(config.id, { metadataRole })); + + expect(grid.dataset.editable).toBe(String(existingEditable)); + expect(grid.dataset.deleteHandler).toBe("none"); + expect(grid.dataset.firstRowDeletable).toBe("false"); + }); +}); diff --git a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts index 5f584766ac..b772d48e0b 100644 --- a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts +++ b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { computed, nextTick, ref, type Ref } from "vue"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { clearDataGridPendingSnapshot, DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID, useDataGridEditor } from "@/composables/useDataGridEditor"; +import { clearDataGridPendingSnapshot, DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID, useDataGridEditor, type CustomSaveHandler } from "@/composables/useDataGridEditor"; import { clearDataGridClipboardCopy, parseDataGridClipboard, rememberDataGridClipboardCopy } from "@/lib/dataGrid/dataGridClipboard"; import { buildMongoUpdateDocument, MONGO_DOCUMENT_GRID_NULL, mongoDocumentGridInputValue, mongoDocumentGridValue } from "@/lib/mongo/mongoDocumentValues"; import type { CellValue } from "@/lib/dataGrid/cellValue"; @@ -947,7 +947,7 @@ describe("useDataGridEditor saveChanges reload", () => { queryResult?: { columns: string[]; rows: CellValue[][] }; currentPage?: Ref; prepareFullReload?: () => void; - customSaveHandler?: { save: ReturnType }; + customSaveHandler?: CustomSaveHandler; confirmSaveRequest?: (request: import("@/composables/useDataGridEditor").DataGridSaveConfirmationRequest) => Promise; manualTransactionSessionId?: string; ensureManualTransactionSession?: () => Promise; @@ -1394,6 +1394,60 @@ describe("useDataGridEditor saveChanges reload", () => { expect(emit).not.toHaveBeenCalledWith("reload", expect.anything()); }); + it("previews and confirms a guarded custom delete before execution, then reloads", async () => { + const customSave = vi.fn().mockResolvedValue(undefined); + const preview = vi.fn().mockResolvedValue(["DELETE FROM guarded WHERE exact_identity"]); + const confirmSaveRequest = vi.fn().mockResolvedValue(true); + const prepareFullReload = vi.fn(); + const { editor, emit } = createSaveTestEditor({ + customSaveHandler: { save: customSave, preview, confirmation: "influxdb-v1-delete", canDelete: true }, + confirmSaveRequest, + prepareFullReload, + databaseType: "influxdb", + }); + editor.deletedRows.value.add(0); + + await editor.saveChanges(); + + expect(preview).toHaveBeenCalledTimes(1); + expect(confirmSaveRequest).toHaveBeenCalledWith({ updates: 0, inserts: 0, deletes: 1, targetLabel: undefined, statements: ["DELETE FROM guarded WHERE exact_identity"] }); + expect(customSave).toHaveBeenCalledTimes(1); + expect(editor.deletedRows.value.size).toBe(0); + expect(prepareFullReload).toHaveBeenCalledTimes(1); + expect(emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0); + }); + + it("keeps a guarded delete staged when declined and refreshes after an execution failure", async () => { + const preview = vi.fn().mockResolvedValue(["DELETE FROM guarded WHERE exact_identity"]); + const declinedSave = vi.fn(); + const declined = createSaveTestEditor({ + customSaveHandler: { save: declinedSave, preview, confirmation: "influxdb-v1-delete", canDelete: true }, + confirmSaveRequest: vi.fn().mockResolvedValue(false), + databaseType: "influxdb", + }); + declined.editor.deletedRows.value.add(0); + + await declined.editor.saveChanges(); + + expect(declinedSave).not.toHaveBeenCalled(); + expect(declined.editor.deletedRows.value).toEqual(new Set([0])); + expect(declined.emit).not.toHaveBeenCalledWith("reload", expect.anything()); + + const failedSave = vi.fn().mockRejectedValue(new Error("server rejected delete")); + const failed = createSaveTestEditor({ + customSaveHandler: { save: failedSave, preview, confirmation: "influxdb-v1-delete", reloadOnFailure: true, canDelete: true }, + confirmSaveRequest: vi.fn().mockResolvedValue(true), + databaseType: "influxdb", + }); + failed.editor.deletedRows.value.add(1); + + await failed.editor.saveChanges(); + + expect(failed.editor.saveError.value).toContain("server rejected delete"); + expect(failed.editor.deletedRows.value).toEqual(new Set([1])); + expect(failed.emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0); + }); + // Engines that cannot roll a partial batch back (Salesforce: one REST call per // record) hand the operation list to the host for review before it is written. it("summarizes inserts, updates and deletes for the host save confirmation and writes once accepted", async () => { diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts index ec77ffc400..c64dba8306 100644 --- a/apps/desktop/src/composables/useDataGridEditor.ts +++ b/apps/desktop/src/composables/useDataGridEditor.ts @@ -80,18 +80,21 @@ export interface CustomSaveHandler { save: (changes: { dirtyRows: Map>; newRows: CellValue[][]; newRowMeta: GridNewRowMeta[]; deletedRows: Set; columns: string[]; rows: CellValue[][] }) => Promise; applySavedChanges?: (changes: { dirtyRows: Map>; columns: string[] }) => void; preview?: (changes: { dirtyRows: Map>; newRows: CellValue[][]; newRowMeta: GridNewRowMeta[]; deletedRows: Set; columns: string[]; rows: CellValue[][] }) => Promise; + /** Optional per-existing-row safety gate used before a deletion can be staged. */ + canDeleteRow?: (sourceIndex: number, row: readonly CellValue[]) => boolean; + /** Selects an unconditional, statement-previewing confirmation before save. */ + confirmation?: "influxdb-v1-delete"; + /** Refresh after an execution error when a non-transactional batch may have partially succeeded. */ + reloadOnFailure?: boolean; canInsert?: boolean; + canUpdate?: boolean; canDelete?: boolean; readonlyColumns?: string[]; supportsInsert?: boolean; targetLabel?: string; } -/** - * Summary handed to `confirmSaveRequest` so an engine whose writes cannot be - * rolled back (Salesforce REST: one record per request, no transactions) can - * show the operator exactly what is about to happen before anything is sent. - */ +/** Summary handed to `confirmSaveRequest` for a final mutation review. */ export interface DataGridSaveConfirmationRequest { /** Rows with edited cells (one write per row). */ updates: number; @@ -99,7 +102,7 @@ export interface DataGridSaveConfirmationRequest { deletes: number; /** Save target name (table / sObject), when known. */ targetLabel?: string; - /** The statements about to be executed — for Salesforce these are `DBX SALESFORCE DML` pseudo-commands. */ + /** The SQL or pseudo-statements about to be executed. */ statements: string[]; } @@ -135,11 +138,7 @@ export interface UseDataGridEditorOptions { rowStatusFilter: Ref; dataGridQuickEntryEnabled?: ComputedRef; confirmDangerousRowDeletion?: ComputedRef; - /** - * Optional operator review before a save is executed. Return `false` to cancel: - * the pending edits stay in the grid and nothing is sent. Engines whose writes - * cannot be rolled back (Salesforce REST) use this; auto-save never bypasses it. - */ + /** Optional operator review before a save is executed. Auto-save never bypasses it. */ confirmSaveRequest?: ComputedRef<((request: DataGridSaveConfirmationRequest) => Promise) | undefined>; /** `生成 SQL 时包含数据库名` — qualify saved tables with their database. */ includeDatabaseNameInSaveSql?: ComputedRef; @@ -1923,17 +1922,47 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { const shouldReloadAfterSqlSave = shouldReloadAfterSave || snapshot.dirtyRows.size > 0; if (customHandler) { - try { - await customHandler.save({ - dirtyRows: snapshot.dirtyRows, - newRows: snapshot.newRows, - newRowMeta: snapshot.newRowMeta, - deletedRows: snapshot.deletedRows, - columns: result.value.columns, - rows: result.value.rows, + const customChanges = { + dirtyRows: snapshot.dirtyRows, + newRows: snapshot.newRows, + newRowMeta: snapshot.newRowMeta, + deletedRows: snapshot.deletedRows, + columns: result.value.columns, + rows: result.value.rows, + }; + const confirmSaveRequest = options.confirmSaveRequest?.value; + if (confirmSaveRequest) { + if (saveOptions.autoSave) { + await finishInterruptedSaveChanges(snapshot); + return; + } + let statements: string[]; + try { + if (!customHandler.preview) throw new Error("This data source cannot safely preview the pending changes."); + statements = await customHandler.preview(customChanges); + if (statements.length === 0) throw new Error("This data source did not produce a safe mutation preview."); + } catch (e: any) { + saveError.value = normalizeDataGridSaveError(databaseType.value, e); + await finishInterruptedSaveChanges(snapshot); + return; + } + const saveConfirmed = await confirmSaveRequest({ + updates: snapshot.dirtyRows.size, + inserts: snapshot.newRows.length, + deletes: snapshot.deletedRows.size, + targetLabel: customHandler.targetLabel, + statements, }); + if (!saveConfirmed) { + await finishInterruptedSaveChanges(snapshot); + return; + } + } + try { + await customHandler.save(customChanges); } catch (e: any) { saveError.value = normalizeDataGridSaveError(databaseType.value, e); + if (customHandler.reloadOnFailure && shouldReloadAfterSave) reloadCurrentData(); await finishInterruptedSaveChanges(snapshot); return; } diff --git a/apps/desktop/src/composables/useDataGridSaveConfirmation.ts b/apps/desktop/src/composables/useDataGridSaveConfirmation.ts new file mode 100644 index 0000000000..2e956134dd --- /dev/null +++ b/apps/desktop/src/composables/useDataGridSaveConfirmation.ts @@ -0,0 +1,64 @@ +import { computed, onScopeDispose, ref, type ComputedRef, type Ref, type WritableComputedRef } from "vue"; +import type { DataGridSaveConfirmationRequest } from "@/composables/useDataGridEditor"; + +/** Parks a grid save until its confirmation dialog explicitly accepts or rejects it. */ +export function useDataGridSaveConfirmation(): { + pending: Ref; + open: WritableComputedRef; + updates: ComputedRef; + inserts: ComputedRef; + deletes: ComputedRef; + total: ComputedRef; + targetLabel: ComputedRef; + statements: ComputedRef; + request: (request: DataGridSaveConfirmationRequest) => Promise; + confirm: () => void; + cancel: () => void; +} { + const pending = ref(null); + let resolvePending: ((confirmed: boolean) => void) | undefined; + + const open = computed({ + get: () => !!pending.value, + set: (next: boolean) => { + if (!next) settle(false); + }, + }); + + const updates = computed(() => pending.value?.updates ?? 0); + const inserts = computed(() => pending.value?.inserts ?? 0); + const deletes = computed(() => pending.value?.deletes ?? 0); + const total = computed(() => updates.value + inserts.value + deletes.value); + const targetLabel = computed(() => pending.value?.targetLabel); + const statements = computed(() => pending.value?.statements ?? []); + + function settle(confirmed: boolean) { + const resolve = resolvePending; + resolvePending = undefined; + pending.value = null; + resolve?.(confirmed); + } + + function request(saveRequest: DataGridSaveConfirmationRequest): Promise { + return new Promise((resolve) => { + if (pending.value) { + resolve(false); + return; + } + pending.value = saveRequest; + resolvePending = resolve; + }); + } + + function confirm() { + settle(true); + } + + function cancel() { + settle(false); + } + + onScopeDispose(() => settle(false)); + + return { pending, open, updates, inserts, deletes, total, targetLabel, statements, request, confirm, cancel }; +} diff --git a/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts b/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts index 0f283c5d34..e01415f286 100644 --- a/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts +++ b/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts @@ -1,76 +1,3 @@ -import { computed, onScopeDispose, ref, type ComputedRef, type Ref, type WritableComputedRef } from "vue"; -import type { DataGridSaveConfirmationRequest } from "@/composables/useDataGridEditor"; - -/** - * Salesforce writes go out as one REST call per record and cannot be rolled back, - * so every grid save is reviewed before it runs. This composable turns the - * `confirmSaveRequest` hook from `useDataGridEditor` into a dialog decision: - * `request()` parks the save on a promise the dialog settles. - * - * The pending request is transient — never persisted and never outliving the - * component — so a dismissed grid denies the write instead of leaving it hanging. - */ -export function useSalesforceSaveConfirmation(): { - pending: Ref; - open: WritableComputedRef; - updates: ComputedRef; - inserts: ComputedRef; - deletes: ComputedRef; - total: ComputedRef; - targetLabel: ComputedRef; - statements: ComputedRef; - request: (request: DataGridSaveConfirmationRequest) => Promise; - confirm: () => void; - cancel: () => void; -} { - const pending = ref(null); - let resolvePending: ((confirmed: boolean) => void) | undefined; - - const open = computed({ - get: () => !!pending.value, - set: (next: boolean) => { - if (!next) settle(false); - }, - }); - - const updates = computed(() => pending.value?.updates ?? 0); - const inserts = computed(() => pending.value?.inserts ?? 0); - const deletes = computed(() => pending.value?.deletes ?? 0); - const total = computed(() => updates.value + inserts.value + deletes.value); - const targetLabel = computed(() => pending.value?.targetLabel); - const statements = computed(() => pending.value?.statements ?? []); - - function settle(confirmed: boolean) { - const resolve = resolvePending; - resolvePending = undefined; - pending.value = null; - resolve?.(confirmed); - } - - function request(saveRequest: DataGridSaveConfirmationRequest): Promise { - return new Promise((resolve) => { - if (pending.value) { - // A grid only saves once at a time, but never strand a second caller: - // deny it so that save unwinds instead of waiting on a dialog it cannot see. - resolve(false); - return; - } - pending.value = saveRequest; - resolvePending = resolve; - }); - } - - function confirm() { - settle(true); - } - - function cancel() { - settle(false); - } - - // The dialog is the only way to settle the promise; if it goes away first (tab - // closed mid-review) the parked save must be denied, not leaked. - onScopeDispose(() => settle(false)); - - return { pending, open, updates, inserts, deletes, total, targetLabel, statements, request, confirm, cancel }; -} +// Kept as a compatibility name for the focused composable tests and any callers +// outside the desktop grid. The confirmation state itself is data-source agnostic. +export { useDataGridSaveConfirmation as useSalesforceSaveConfirmation } from "@/composables/useDataGridSaveConfirmation"; diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index d8af162d21..5a654e9a0d 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -2817,6 +2817,10 @@ export default { salesforceSaveNonAdminIdentity: "Signed in as {user} ({profile}).\nFields you cannot write are already read-only here;\nfailures from record sharing or validation rules come back per row, in Salesforce’s own words.", salesforceSaveUnknownRights: "Signed in as {user} ({profile}); could not determine whether this profile has “Modify All Data” — Salesforce still enforces its own permissions and reports failures per row.", salesforceSaveConfirm: "Apply to Salesforce", + influxDeleteConfirmTitle: "Delete InfluxDB Points", + influxDeleteConfirmMessage: "Permanently delete {count} selected point(s) from InfluxDB 1.x? Each predicate uses the exact time and every available tag. Deletes cannot be undone, and an error may occur after earlier points were deleted.", + influxDeleteTarget: "Measurement: {measurement}", + influxDeleteConfirm: "Delete Points", keylessEditWarning: "No primary key", keylessEditWarningHint: "This table has no primary key. Updates and deletes use all original row values in the WHERE clause; exact duplicate rows may be affected together.", queryEditReadOnly: "Read-only result", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index e39edb6afb..99c9e5adc1 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -2730,6 +2730,10 @@ export default withEnglishFallback({ salesforceSaveNonAdminIdentity: "当前身份:{user}({profile})\n不可写字段已按你的权限设为只读;\n记录级共享或验证规则导致的失败会按行返回 Salesforce 原文。", salesforceSaveUnknownRights: "当前身份:{user}({profile});未能确认该简档是否具有“修改所有数据”权限——Salesforce 仍会按自身权限校验,失败按行返回原文。", salesforceSaveConfirm: "写入 Salesforce", + influxDeleteConfirmTitle: "删除 InfluxDB 数据点", + influxDeleteConfirmMessage: "确定永久删除所选的 {count} 个 InfluxDB 1.x 数据点吗?每条删除条件都包含精确时间和全部可用标签。删除无法撤销,若中途报错,之前的数据点可能已被删除。", + influxDeleteTarget: "Measurement:{measurement}", + influxDeleteConfirm: "删除数据点", keylessEditWarning: "无主键", keylessEditWarningHint: "这张表没有主键。保存更新或删除时会使用整行原始值作为 WHERE 条件;如果存在完全重复的行,可能会影响多行。", queryEditReadOnly: "只读结果", diff --git a/apps/desktop/src/lib/influxdb/__tests__/influxDbV1Delete.spec.ts b/apps/desktop/src/lib/influxdb/__tests__/influxDbV1Delete.spec.ts new file mode 100644 index 0000000000..907b8f5330 --- /dev/null +++ b/apps/desktop/src/lib/influxdb/__tests__/influxDbV1Delete.spec.ts @@ -0,0 +1,176 @@ +import { describe, expect, it } from "vitest"; +import type { ColumnInfo, ConnectionConfig } from "@/types/database"; +import { getDatabaseCapability } from "@/lib/database/databaseTableDataCapabilities"; +import { buildInfluxDbV1DeleteStatements, canDeleteInfluxDbV1Row, INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA, INFLUXDB_V1_FIELD_COLUMN_EXTRA, INFLUXDB_V1_TAG_COLUMN_EXTRA, INFLUXDB_V1_TIME_COLUMN_EXTRA, isInfluxDbV1Connection, resolveInfluxDbV1DeleteTarget } from "@/lib/influxdb/influxDbV1Delete"; + +function connection(version?: unknown, url_params?: string): Pick { + return { + db_type: "influxdb", + external_config: version === undefined ? undefined : { version }, + url_params, + }; +} + +function column(name: string, role: string, primary = false): ColumnInfo { + return { + name, + data_type: role === INFLUXDB_V1_TIME_COLUMN_EXTRA ? "timestamp" : "string", + is_nullable: role !== INFLUXDB_V1_TIME_COLUMN_EXTRA, + column_default: null, + is_primary_key: primary, + extra: role, + }; +} + +const metadata = [column("time", INFLUXDB_V1_TIME_COLUMN_EXTRA, true), column("host", INFLUXDB_V1_TAG_COLUMN_EXTRA, true), column("region", INFLUXDB_V1_TAG_COLUMN_EXTRA, true), column("usage", INFLUXDB_V1_FIELD_COLUMN_EXTRA)]; + +function target(options: { measurement?: string; tableColumns?: ColumnInfo[]; resultColumns?: string[]; version?: unknown; urlParams?: string } = {}) { + const resolved = resolveInfluxDbV1DeleteTarget({ + connection: connection(options.version, options.urlParams), + measurement: options.measurement ?? "cpu", + tableColumns: options.tableColumns ?? metadata, + resultColumns: options.resultColumns ?? ["time", "host", "region", "usage"], + }); + if (!resolved) throw new Error("expected a safe InfluxDB delete target"); + return resolved; +} + +function changes(rows: Array>, deletedRows = new Set([0])) { + return { + dirtyRows: new Map>(), + newRows: [], + deletedRows, + columns: ["time", "host", "region", "usage"], + rows, + }; +} + +describe("InfluxDB 1.x result-grid delete", () => { + it("is gated to explicit or legacy-v1 InfluxDB connections", () => { + expect(getDatabaseCapability("influxdb").tableData).toMatchObject({ insert: false, existingRowsReadonly: true, readonly: true }); + expect(isInfluxDbV1Connection(connection())).toBe(true); + expect(isInfluxDbV1Connection(connection("1"))).toBe(true); + expect(isInfluxDbV1Connection(connection("V1"))).toBe(true); + expect(isInfluxDbV1Connection(connection(1))).toBe(true); + expect(isInfluxDbV1Connection(connection("2"))).toBe(false); + expect(isInfluxDbV1Connection(connection("V2"))).toBe(false); + expect(isInfluxDbV1Connection(connection("3"))).toBe(false); + expect(isInfluxDbV1Connection({ ...connection("1"), db_type: "influxdb3" })).toBe(false); + expect(isInfluxDbV1Connection({ ...connection("1"), db_type: "victoriametrics" })).toBe(false); + }); + + it("requires explicit metadata roles, one time column, every tag, and an unmodified result shape", () => { + expect(resolveInfluxDbV1DeleteTarget({ connection: connection("1"), measurement: "cpu", tableColumns: metadata, resultColumns: ["time", "host", "region", "usage"] })).toBeDefined(); + expect(resolveInfluxDbV1DeleteTarget({ connection: connection("2"), measurement: "cpu", tableColumns: metadata, resultColumns: ["time", "host", "region", "usage"] })).toBeUndefined(); + expect(resolveInfluxDbV1DeleteTarget({ connection: connection("1"), measurement: "cpu", tableColumns: metadata, resultColumns: ["time", "host", "usage"] })).toBeUndefined(); + expect(resolveInfluxDbV1DeleteTarget({ connection: connection("1"), measurement: "cpu", tableColumns: metadata, resultColumns: ["time", "host", "region", "computed"] })).toBeUndefined(); + expect(resolveInfluxDbV1DeleteTarget({ connection: connection("1"), measurement: "cpu", tableColumns: metadata, resultColumns: ["time", "host", "host", "region", "usage"] })).toBeUndefined(); + expect( + resolveInfluxDbV1DeleteTarget({ + connection: connection("1"), + measurement: "cpu", + tableColumns: metadata.map((item) => ({ ...item, extra: item.name === "host" ? null : item.extra })), + resultColumns: ["time", "host", "region", "usage"], + }), + ).toBeUndefined(); + expect( + resolveInfluxDbV1DeleteTarget({ + connection: connection("1"), + measurement: "cpu", + tableColumns: metadata.map((item) => ({ ...item, extra: item.name === "host" ? INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA : item.extra })), + resultColumns: ["time", "host", "region", "usage"], + }), + ).toBeUndefined(); + expect( + resolveInfluxDbV1DeleteTarget({ + connection: connection("1"), + measurement: "cpu", + tableColumns: metadata.map((item) => ({ ...item, is_primary_key: item.name === "host" ? false : item.is_primary_key })), + resultColumns: ["time", "host", "region", "usage"], + }), + ).toBeUndefined(); + }); + + it("quotes identifiers and tag literals and builds one guarded statement per selected row", () => { + const deleteTarget = target({ measurement: 'cpu" load\\prod' }); + const statements = buildInfluxDbV1DeleteStatements( + deleteTarget, + changes( + [ + ["2026-09-27T10:11:12.123456789Z", "web'01", "us\\west", "field value must not appear"], + ["2026-09-27T10:11:13+08:00", "web02", "cn", "DELETE FROM other"], + ], + new Set([1, 0]), + ), + ); + + expect(statements).toEqual([ + "DELETE FROM \"cpu\\\" load\\\\prod\" WHERE (time = '2026-09-27T10:11:12.123456789Z' AND \"host\" = 'web\\'01' AND \"region\" = 'us\\\\west');", + 'DELETE FROM "cpu\\" load\\\\prod" WHERE (time = \'2026-09-27T10:11:13+08:00\' AND "host" = \'web02\' AND "region" = \'cn\');', + ]); + expect(statements.join("\n")).not.toContain("field value must not appear"); + expect(statements.join("\n")).not.toContain("DELETE FROM other"); + }); + + it("accepts exact nanosecond epoch values but rejects lossy or unsafe numeric time values", () => { + const nanosecondTarget = target({ urlParams: "epoch=ns" }); + expect(buildInfluxDbV1DeleteStatements(nanosecondTarget, changes([["1727431200123456789", "web01", "us", 10]]))).toEqual(['DELETE FROM "cpu" WHERE (time = 1727431200123456789 AND "host" = \'web01\' AND "region" = \'us\');']); + expect(canDeleteInfluxDbV1Row(nanosecondTarget, [1_727_431_200, "web01", "us", 10])).toBe(true); + expect(canDeleteInfluxDbV1Row(target({ urlParams: "epoch=ms" }), [1_727_431_200_123, "web01", "us", 10])).toBe(false); + expect(canDeleteInfluxDbV1Row(target(), [1_727_431_200, "web01", "us", 10])).toBe(false); + expect(canDeleteInfluxDbV1Row(nanosecondTarget, [Number.MAX_SAFE_INTEGER + 1, "web01", "us", 10])).toBe(false); + expect(canDeleteInfluxDbV1Row(nanosecondTarget, ["9223372036854775807", "web01", "us", 10])).toBe(false); + }); + + it("allows a tagless measurement to use measurement plus time as its complete identity", () => { + const taglessMetadata = [column("time", INFLUXDB_V1_TIME_COLUMN_EXTRA, true), column("value", INFLUXDB_V1_FIELD_COLUMN_EXTRA)]; + const deleteTarget = target({ tableColumns: taglessMetadata, resultColumns: ["time", "value"] }); + const taglessChanges = changes([["2026-09-27T10:11:12Z", 42]]); + taglessChanges.columns = ["time", "value"]; + + expect(buildInfluxDbV1DeleteStatements(deleteTarget, taglessChanges)).toEqual(["DELETE FROM \"cpu\" WHERE (time = '2026-09-27T10:11:12Z');"]); + }); + + it.each([ + { label: "null time", row: [null, "web01", "us", 10] }, + { label: "invalid timestamp", row: ["2026-02-30T00:00:00Z", "web01", "us", 10] }, + { label: "out-of-range timestamp", row: ["1600-01-01T00:00:00Z", "web01", "us", 10] }, + { label: "missing tag", row: ["2026-09-27T10:11:12Z", "web01", null, 10] }, + { label: "non-string tag", row: ["2026-09-27T10:11:12Z", "web01", 7, 10] }, + { label: "short row", row: ["2026-09-27T10:11:12Z", "web01", "us"] }, + ])("fails closed for $label", ({ row }) => { + expect(canDeleteInfluxDbV1Row(target(), row)).toBe(false); + expect(() => buildInfluxDbV1DeleteStatements(target(), changes([row]))).toThrow(/Cannot safely delete/); + }); + + it("rejects duplicate point targets even when their field values differ", () => { + expect(() => + buildInfluxDbV1DeleteStatements( + target(), + changes( + [ + ["2026-09-27T10:11:12Z", "web01", "us", 10], + ["2026-09-27T10:11:12Z", "web01", "us", 99], + ], + new Set([0, 1]), + ), + ), + ).toThrow(/duplicate target/); + }); + + it("rejects stale or invalid selected row indexes", () => { + const rows = [["2026-09-27T10:11:12Z", "web01", "us", 10]]; + expect(() => buildInfluxDbV1DeleteStatements(target(), changes(rows, new Set([2])))).toThrow(/no longer present/); + expect(() => buildInfluxDbV1DeleteStatements(target(), changes(rows, new Set([-1])))).toThrow(/invalid row index/); + }); + + it("rejects any attempt to route inserts or updates through the delete-only path", () => { + const update = changes([["2026-09-27T10:11:12Z", "web01", "us", 10]]); + update.dirtyRows.set(0, new Map([[3, 11]])); + expect(() => buildInfluxDbV1DeleteStatements(target(), update)).toThrow(/delete-only/); + + const insert = changes([["2026-09-27T10:11:12Z", "web01", "us", 10]]); + insert.newRows.push(["2026-09-27T10:11:13Z", "web02", "us", 11]); + expect(() => buildInfluxDbV1DeleteStatements(target(), insert)).toThrow(/delete-only/); + }); +}); diff --git a/apps/desktop/src/lib/influxdb/influxDbV1Delete.ts b/apps/desktop/src/lib/influxdb/influxDbV1Delete.ts new file mode 100644 index 0000000000..fb8ec3b75e --- /dev/null +++ b/apps/desktop/src/lib/influxdb/influxDbV1Delete.ts @@ -0,0 +1,243 @@ +import type { CellValue } from "@/lib/dataGrid/cellValue"; +import type { ColumnInfo, ConnectionConfig } from "@/types/database"; + +export const INFLUXDB_V1_TIME_COLUMN_EXTRA = "influxdb:time"; +export const INFLUXDB_V1_TAG_COLUMN_EXTRA = "influxdb:tag"; +export const INFLUXDB_V1_FIELD_COLUMN_EXTRA = "influxdb:field"; +export const INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA = "influxdb:ambiguous"; + +const INFLUXDB_MIN_TIMESTAMP = -9_223_372_036_854_775_806n; +const INFLUXDB_MAX_TIMESTAMP = 9_223_372_036_854_775_806n; + +export interface InfluxDbV1DeleteTarget { + measurement: string; + resultColumns: string[]; + timeColumnIndex: number; + tagColumns: Array<{ name: string; resultColumnIndex: number }>; + integerTimeIsNanoseconds: boolean; +} + +export interface InfluxDbV1DeleteChanges { + dirtyRows: ReadonlyMap>; + newRows: readonly (readonly CellValue[])[]; + deletedRows: ReadonlySet; + columns: readonly string[]; + rows: readonly (readonly CellValue[])[]; +} + +function configuredInfluxDbVersion(connection: Pick): string | undefined { + const external = connection.external_config; + if (external == null) return undefined; + if (typeof external !== "object" || Array.isArray(external)) return "unknown"; + const version = (external as Record).version; + if (version == null) return undefined; + if (typeof version === "number") return String(version); + return typeof version === "string" ? version.trim().toLowerCase() : "unknown"; +} + +/** Legacy InfluxDB connections without a version marker are v1, matching the Rust driver. */ +export function isInfluxDbV1Connection(connection: Pick | undefined): boolean { + if (connection?.db_type !== "influxdb") return false; + const version = configuredInfluxDbVersion(connection); + return version === undefined || version === "1" || version === "v1"; +} + +function influxColumnRole(column: Pick): "time" | "tag" | "field" | "ambiguous" | undefined { + switch (column.extra?.trim().toLowerCase()) { + case INFLUXDB_V1_TIME_COLUMN_EXTRA: + return "time"; + case INFLUXDB_V1_TAG_COLUMN_EXTRA: + return "tag"; + case INFLUXDB_V1_FIELD_COLUMN_EXTRA: + return "field"; + case INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA: + return "ambiguous"; + default: + return undefined; + } +} + +function singleColumnIndex(columns: readonly string[], name: string): number | undefined { + let found: number | undefined; + for (let index = 0; index < columns.length; index++) { + if (columns[index] !== name) continue; + if (found !== undefined) return undefined; + found = index; + } + return found; +} + +function integerTimeIsNanoseconds(urlParams: string | undefined): boolean { + if (!urlParams) return false; + const params = new URLSearchParams(urlParams.startsWith("?") ? urlParams.slice(1) : urlParams); + const epochs = params.getAll("epoch").map((value) => value.trim().toLowerCase()); + return epochs.length === 1 && epochs[0] === "ns"; +} + +/** + * Resolves the only result shape that may use the guarded delete path. + * + * The InfluxDB driver annotates schema metadata with explicit column roles. + * Requiring those roles, exact column names, and every tag prevents an aliased, + * computed, stale, or otherwise ambiguous result from being treated as points. + */ +export function resolveInfluxDbV1DeleteTarget(options: { connection: Pick | undefined; measurement: string | undefined; tableColumns: readonly ColumnInfo[]; resultColumns: readonly string[] }): InfluxDbV1DeleteTarget | undefined { + if (!options.connection || !isInfluxDbV1Connection(options.connection) || options.measurement === undefined || options.measurement.length === 0 || options.tableColumns.length === 0 || options.resultColumns.length === 0) { + return undefined; + } + + const metadataByName = new Map(); + let timeColumn: ColumnInfo | undefined; + const tagColumns: ColumnInfo[] = []; + for (const column of options.tableColumns) { + if (!column.name || metadataByName.has(column.name)) return undefined; + const role = influxColumnRole(column); + if (!role || role === "ambiguous") return undefined; + metadataByName.set(column.name, column); + if (role === "time") { + if (timeColumn || column.name !== "time" || !column.is_primary_key) return undefined; + timeColumn = column; + } else if (role === "tag") { + if (!column.is_primary_key) return undefined; + tagColumns.push(column); + } else if (column.is_primary_key) { + return undefined; + } + } + if (!timeColumn) return undefined; + + const resultColumnNames = new Set(); + for (const column of options.resultColumns) { + if (resultColumnNames.has(column) || !metadataByName.has(column)) return undefined; + resultColumnNames.add(column); + } + + const timeColumnIndex = singleColumnIndex(options.resultColumns, timeColumn.name); + if (timeColumnIndex === undefined) return undefined; + const resolvedTags: InfluxDbV1DeleteTarget["tagColumns"] = []; + for (const tag of tagColumns) { + const resultColumnIndex = singleColumnIndex(options.resultColumns, tag.name); + if (resultColumnIndex === undefined) return undefined; + resolvedTags.push({ name: tag.name, resultColumnIndex }); + } + + return { + measurement: options.measurement, + resultColumns: [...options.resultColumns], + timeColumnIndex, + tagColumns: resolvedTags, + integerTimeIsNanoseconds: integerTimeIsNanoseconds(options.connection.url_params), + }; +} + +function quoteInfluxIdentifier(value: string): string { + return `"${value.replaceAll("\\", "\\\\").replaceAll("\r", "\\r").replaceAll("\n", "\\n").replaceAll('"', '\\"')}"`; +} + +function quoteInfluxString(value: string): string { + return `'${value.replaceAll("\\", "\\\\").replaceAll("\r", "\\r").replaceAll("\n", "\\n").replaceAll("'", "\\'")}'`; +} + +function isLeapYear(year: number): boolean { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + +function validRfc3339Timestamp(value: string): boolean { + const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/.exec(value); + if (!match) return false; + const [, yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, zone] = match; + const year = Number(yearText); + const month = Number(monthText); + const day = Number(dayText); + const hour = Number(hourText); + const minute = Number(minuteText); + const second = Number(secondText); + const daysInMonth = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1]! || hour > 23 || minute > 59 || second > 59) return false; + if (zone !== "Z") { + const zoneHour = Number(zone.slice(1, 3)); + const zoneMinute = Number(zone.slice(4, 6)); + if (zoneHour > 23 || zoneMinute > 59) return false; + } + const milliseconds = Date.parse(`${yearText}-${monthText}-${dayText}T${hourText}:${minuteText}:${secondText}${zone}`); + if (!Number.isFinite(milliseconds)) return false; + const nanoseconds = BigInt(milliseconds) * 1_000_000n + BigInt((fractionText ?? "").padEnd(9, "0") || "0"); + return nanoseconds >= INFLUXDB_MIN_TIMESTAMP && nanoseconds <= INFLUXDB_MAX_TIMESTAMP; +} + +function influxTimeLiteral(value: CellValue, integerTimeIsNanoseconds: boolean): string | undefined { + if (typeof value === "string") { + if (validRfc3339Timestamp(value)) return quoteInfluxString(value); + if (!integerTimeIsNanoseconds || !/^-?\d+$/.test(value)) return undefined; + try { + const timestamp = BigInt(value); + return timestamp >= INFLUXDB_MIN_TIMESTAMP && timestamp <= INFLUXDB_MAX_TIMESTAMP ? timestamp.toString() : undefined; + } catch { + return undefined; + } + } + if (typeof value !== "number" || !Number.isSafeInteger(value) || !integerTimeIsNanoseconds) return undefined; + const timestamp = BigInt(value); + return timestamp >= INFLUXDB_MIN_TIMESTAMP && timestamp <= INFLUXDB_MAX_TIMESTAMP ? timestamp.toString() : undefined; +} + +function deleteCondition(target: InfluxDbV1DeleteTarget, row: readonly CellValue[]): string { + if (row.length !== target.resultColumns.length) throw new Error("Cannot safely delete this InfluxDB point because the result row shape does not match its columns."); + const time = influxTimeLiteral(row[target.timeColumnIndex] ?? null, target.integerTimeIsNanoseconds); + if (!time) throw new Error("Cannot safely delete this InfluxDB point because its time value is missing or invalid."); + + const conditions = [`time = ${time}`]; + // Generic grid delete generators commonly fall back to every visible value + // when no key exists. That is invalid for InfluxQL: only time and tag keys + // are legal here, so field-role columns are deliberately never inspected. + for (const tag of target.tagColumns) { + const value = row[tag.resultColumnIndex]; + if (typeof value !== "string" || value.length === 0) { + throw new Error(`Cannot safely delete this InfluxDB point because tag ${quoteInfluxIdentifier(tag.name)} is missing or invalid.`); + } + conditions.push(`${quoteInfluxIdentifier(tag.name)} = ${quoteInfluxString(value)}`); + } + return conditions.join(" AND "); +} + +export function canDeleteInfluxDbV1Row(target: InfluxDbV1DeleteTarget, row: readonly CellValue[]): boolean { + try { + deleteCondition(target, row); + return true; + } catch { + return false; + } +} + +/** + * Builds one InfluxQL DELETE statement per point. InfluxDB 1.x rejects time + * conditions joined through OR, so multi-row deletion cannot safely be folded + * into one predicate. Callers must stop on the first failure and refresh after + * an error because earlier statements may already have succeeded. + */ +export function buildInfluxDbV1DeleteStatements(target: InfluxDbV1DeleteTarget, changes: InfluxDbV1DeleteChanges): string[] { + if (changes.dirtyRows.size > 0 || changes.newRows.length > 0) { + throw new Error("InfluxDB result rows are delete-only; field and tag values cannot be edited or inserted here."); + } + if (changes.columns.length !== target.resultColumns.length || changes.columns.some((column, index) => column !== target.resultColumns[index])) { + throw new Error("Cannot safely delete InfluxDB points because the result columns changed."); + } + if (changes.deletedRows.size === 0) return []; + + const conditions: string[] = []; + const uniqueTargets = new Set(); + for (const rowIndex of [...changes.deletedRows].sort((left, right) => left - right)) { + if (!Number.isInteger(rowIndex) || rowIndex < 0) throw new Error("Cannot safely delete an InfluxDB point with an invalid row index."); + const row = changes.rows[rowIndex]; + if (!row) throw new Error("Cannot safely delete an InfluxDB point that is no longer present in the result."); + const condition = deleteCondition(target, row); + if (uniqueTargets.has(condition)) { + throw new Error("Cannot safely delete InfluxDB points because the selected rows contain a duplicate target."); + } + uniqueTargets.add(condition); + conditions.push(`(${condition})`); + } + + const measurement = quoteInfluxIdentifier(target.measurement); + return conditions.map((condition) => `DELETE FROM ${measurement} WHERE ${condition};`); +} diff --git a/crates/dbx-drivers/src/db/influxdb_driver.rs b/crates/dbx-drivers/src/db/influxdb_driver.rs index a23c4c6d24..f34232077f 100644 --- a/crates/dbx-drivers/src/db/influxdb_driver.rs +++ b/crates/dbx-drivers/src/db/influxdb_driver.rs @@ -1,7 +1,7 @@ use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use reqwest::{Certificate, Client as HttpClient, Response}; use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::time::{Duration, Instant}; @@ -204,6 +204,13 @@ struct InfluxSeries { tags: BTreeMap, } +// Stable `ColumnInfo.extra` wire markers consumed by the desktop's guarded +// InfluxDB delete path. Keep them distinct from ordinary display-only extras. +const INFLUXDB_V1_TIME_COLUMN_EXTRA: &str = "influxdb:time"; +const INFLUXDB_V1_TAG_COLUMN_EXTRA: &str = "influxdb:tag"; +const INFLUXDB_V1_FIELD_COLUMN_EXTRA: &str = "influxdb:field"; +const INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA: &str = "influxdb:ambiguous"; + #[derive(Deserialize)] struct InfluxBucketsResult { #[serde(default)] @@ -239,6 +246,10 @@ fn encode_url_param(value: &str) -> String { utf8_percent_encode(value, NON_ALPHANUMERIC).to_string() } +fn quote_influx_identifier(value: &str) -> String { + format!("\"{}\"", value.replace('\\', "\\\\").replace('\r', "\\r").replace('\n', "\\n").replace('"', "\\\"")) +} + fn build_v2_buckets_url(client: &InfluxdbClient, offset: usize) -> Result { let org = client.org.as_deref().ok_or_else(|| "InfluxDB 2.x organization is required".to_string())?; Ok(format!("{}/api/v2/buckets?org={}&limit=100&offset={offset}", client.base_url, encode_url_param(org))) @@ -436,64 +447,86 @@ pub async fn get_columns(client: &InfluxdbClient, database: &str, table: &str) - } let empty = vec![]; - let tag_sql = format!("SHOW TAG KEYS FROM \"{}\"", table); + let measurement = quote_influx_identifier(table); + let tag_sql = format!("SHOW TAG KEYS FROM {measurement}"); let tag_result = influx_query(client, &tag_sql, Some(database)).await?; let tag_series = tag_result.results.first().map(|r| &r.series).unwrap_or(&empty); - let field_sql = format!("SHOW FIELD KEYS FROM \"{}\"", table); + let field_sql = format!("SHOW FIELD KEYS FROM {measurement}"); let field_result = influx_query(client, &field_sql, Some(database)).await?; let field_series = field_result.results.first().map(|r| &r.series).unwrap_or(&empty); - let time_col = ColumnInfo { - name: "time".to_string(), - data_type: "timestamp".to_string(), - is_nullable: false, + Ok(influx_v1_columns(tag_series, field_series)) +} + +fn influx_v1_column(name: String, data_type: String, is_primary_key: bool, role: &str) -> ColumnInfo { + ColumnInfo { + name, + data_type, + is_nullable: role != INFLUXDB_V1_TIME_COLUMN_EXTRA, column_default: None, - is_primary_key: true, - extra: None, + is_primary_key, + extra: Some(role.to_string()), comment: None, numeric_precision: None, numeric_scale: None, character_maximum_length: None, enum_values: None, ..Default::default() - }; + } +} - let cols: Vec = std::iter::once(time_col) - .chain(tag_series.first().into_iter().flat_map(|s| s.values.iter()).map(|row| ColumnInfo { - name: row[0].as_str().unwrap_or("").to_string(), - data_type: "string".to_string(), - is_nullable: true, - column_default: None, - is_primary_key: true, - extra: None, - comment: None, - numeric_precision: None, - numeric_scale: None, - character_maximum_length: None, - enum_values: None, - ..Default::default() - })) - .chain(field_series.first().into_iter().flat_map(|s| s.values.iter()).map(|row| { - let data_type = row.get(1).and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); - ColumnInfo { - name: row[0].as_str().unwrap_or("").to_string(), - data_type, - is_nullable: true, - column_default: None, - is_primary_key: false, - extra: None, - comment: None, - numeric_precision: None, - numeric_scale: None, - character_maximum_length: None, - enum_values: None, - ..Default::default() - } - })) - .collect(); +/// Preserve the database's tag/field distinction in the metadata sent to the +/// desktop. InfluxQL DELETE predicates may use time and tags, but never fields. +/// A key that exists in both namespaces is marked ambiguous so mutation callers +/// can fail closed instead of guessing which value a result column represents. +fn influx_v1_columns(tag_series: &[InfluxSeries], field_series: &[InfluxSeries]) -> Vec { + let mut tag_names = Vec::new(); + let mut seen_tags = BTreeSet::new(); + for name in tag_series + .iter() + .flat_map(|series| &series.values) + .filter_map(|row| row.first().and_then(serde_json::Value::as_str)) + .filter(|name| !name.is_empty()) + { + if seen_tags.insert(name.to_string()) { + tag_names.push(name.to_string()); + } + } - Ok(cols) + let mut fields = Vec::new(); + let mut seen_fields = BTreeSet::new(); + for row in field_series.iter().flat_map(|series| &series.values) { + let Some(name) = row.first().and_then(serde_json::Value::as_str).filter(|name| !name.is_empty()) else { + continue; + }; + if seen_fields.insert(name.to_string()) { + fields.push(( + name.to_string(), + row.get(1).and_then(serde_json::Value::as_str).unwrap_or("unknown").to_string(), + )); + } + } + let field_names = fields.iter().map(|(name, _)| name.as_str()).collect::>(); + + let mut columns = + vec![influx_v1_column("time".to_string(), "timestamp".to_string(), true, INFLUXDB_V1_TIME_COLUMN_EXTRA)]; + for name in tag_names { + let ambiguous = field_names.contains(name.as_str()); + columns.push(influx_v1_column( + name, + "string".to_string(), + !ambiguous, + if ambiguous { INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA } else { INFLUXDB_V1_TAG_COLUMN_EXTRA }, + )); + } + columns.extend( + fields + .into_iter() + .filter(|(name, _)| !seen_tags.contains(name)) + .map(|(name, data_type)| influx_v1_column(name, data_type, false, INFLUXDB_V1_FIELD_COLUMN_EXTRA)), + ); + columns } pub async fn execute_query(client: &InfluxdbClient, database: &str, sql: &str) -> Result { @@ -813,6 +846,11 @@ mod tests { assert_eq!(url, "http://localhost:8086/query?db=sample&q=SHOW%20DATABASES"); } + #[test] + fn quotes_influx_identifiers_with_influxql_escapes() { + assert_eq!(quote_influx_identifier("cpu\" west\\rack\n2"), "\"cpu\\\" west\\\\rack\\n2\""); + } + #[test] fn merges_v1_series_and_promotes_tags_to_columns() { let first = InfluxSeries { @@ -840,6 +878,51 @@ mod tests { ); } + #[test] + fn v1_column_metadata_distinguishes_time_tags_fields_and_ambiguity() { + let tags = vec![ + InfluxSeries { + name: "cpu".to_string(), + columns: vec!["tagKey".to_string()], + values: vec![vec![json!("host")], vec![json!("shared")]], + tags: BTreeMap::new(), + }, + InfluxSeries { + name: "cpu".to_string(), + columns: vec!["tagKey".to_string()], + values: vec![vec![json!("region")], vec![json!("host")]], + tags: BTreeMap::new(), + }, + ]; + let fields = vec![InfluxSeries { + name: "cpu".to_string(), + columns: vec!["fieldKey".to_string(), "fieldType".to_string()], + values: vec![vec![json!("usage"), json!("float")], vec![json!("shared"), json!("string")]], + tags: BTreeMap::new(), + }]; + + let columns = influx_v1_columns(&tags, &fields); + + assert_eq!( + columns.iter().map(|column| column.name.as_str()).collect::>(), + vec!["time", "host", "shared", "region", "usage"] + ); + assert_eq!( + columns.iter().map(|column| column.extra.as_deref()).collect::>(), + vec![ + Some(INFLUXDB_V1_TIME_COLUMN_EXTRA), + Some(INFLUXDB_V1_TAG_COLUMN_EXTRA), + Some(INFLUXDB_V1_AMBIGUOUS_COLUMN_EXTRA), + Some(INFLUXDB_V1_TAG_COLUMN_EXTRA), + Some(INFLUXDB_V1_FIELD_COLUMN_EXTRA), + ] + ); + assert_eq!( + columns.iter().map(|column| column.is_primary_key).collect::>(), + vec![true, true, false, true, false] + ); + } + #[test] fn v2_config_uses_token_auth_and_org_urls() { let config: ConnectionConfig = serde_json::from_value(json!({