feat(influxdb): add guarded point deletion

Closes #9818
This commit is contained in:
t8y2 committed 2026-09-27 12:36:33 +00:00
1 parent 9c23e3198b
commit 0fd1d6108f
12 files changed
+1007 -184

No files matched your search

+48 -42
View File
@@ -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<number, Readon
return true;
}
// Salesforce applies one REST call per record with no transaction, so every grid
// save is reviewed here first. The identity lines are advisory only — Salesforce
// enforces the real object/field permissions, and a failed identity lookup just
// omits the line rather than blocking the write.
// Non-transactional or specialized mutations can require a final review of the
// exact statements after changes have been staged. Salesforce and guarded
// InfluxDB 1.x deletion share the promise-backed dialog state below.
const {
open: salesforceSaveConfirmOpen,
updates: salesforceSaveConfirmUpdates,
inserts: salesforceSaveConfirmInserts,
deletes: salesforceSaveConfirmDeletes,
total: salesforceSaveConfirmTotal,
targetLabel: salesforceSaveConfirmTarget,
statements: salesforceSaveConfirmStatements,
request: requestSalesforceSaveConfirmation,
confirm: confirmSalesforceSave,
} = useSalesforceSaveConfirmation();
open: saveConfirmOpen,
updates: saveConfirmUpdates,
inserts: saveConfirmInserts,
deletes: saveConfirmDeletes,
total: saveConfirmTotal,
targetLabel: saveConfirmTarget,
statements: saveConfirmStatements,
request: requestDataGridSaveConfirmation,
confirm: confirmDataGridSave,
} = useDataGridSaveConfirmation();
const isSalesforceGrid = computed(() => 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<ContextMenuItem[]>(() => {
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<ContextMenuItem[]>(() => {
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"
/>
<!-- Salesforce applies each record with its own REST call and cannot roll back, so the
save is reviewed here first. Cancel (or closing) denies it and keeps the edits staged. -->
<DangerConfirmDialog
v-model:open="salesforceSaveConfirmOpen"
:title="t('grid.salesforceSaveConfirmTitle')"
:message="t('grid.salesforceSaveConfirmMessage', { count: salesforceSaveConfirmTotal })"
:details-text="salesforceSaveConfirmDetails"
:sql="salesforceSaveConfirmSql"
:confirm-label="t('grid.salesforceSaveConfirm')"
:close-on-confirm="false"
@confirm="confirmSalesforceSave"
/>
<!-- Specialized non-transactional saves are reviewed here first. Cancel (or closing)
denies the request and keeps the pending rows staged. -->
<DangerConfirmDialog v-model:open="saveConfirmOpen" :title="saveConfirmTitle" :message="saveConfirmMessage" :details-text="saveConfirmDetails" :sql="saveConfirmSql" :confirm-label="saveConfirmLabel" :close-on-confirm="false" @confirm="confirmDataGridSave" />
<ImagePreviewDialog v-if="imagePreviewMounted" v-model:open="imagePreviewOpen" :src="imagePreviewSrc" :title="imagePreviewTitle" />
<component v-if="previewDialogOpen && previewDialogConfig" :is="previewDialogConfig.component" v-model:open="previewDialogOpen" v-bind="previewDialogConfig.props" />
<ExportProgressDialog
@@ -177,6 +177,7 @@ import type { SqlInsertMode } from "@/lib/export/sqlInsertMode";
import { queryResultExportBaseName } from "@/lib/export/saveTextFile";
import { applyMongoGridChangesToDocument, applyMongoGridChangesToDocumentBaseline, serializeMongoDocumentId, type MongoInputValue } from "@/lib/mongo/mongoDocumentValues";
import { buildMongoQueryResultOperations, formatMongoQueryResultOperationPreview } from "@/lib/mongo/mongoQueryResultEditing";
import { buildInfluxDbV1DeleteStatements, canDeleteInfluxDbV1Row, resolveInfluxDbV1DeleteTarget } from "@/lib/influxdb/influxDbV1Delete";
import type { DataGridSortMode } from "@/lib/dataGrid/dataGridSort";
import { isDataGridToolbarCompact, type DataGridReloadIntent } from "@/lib/dataGrid/dataGridToolbar";
import { useTabScroll } from "@/composables/useTabScroll";
@@ -715,6 +716,45 @@ const mongoQueryResultSaveHandler = computed<CustomSaveHandler | undefined>(() =
return { save, preview, applySavedChanges, canInsert: false, canDelete: true, supportsInsert: false, readonlyColumns: [target.idColumn], targetLabel: target.collection };
});
const influxDbV1DeleteSaveHandler = computed<CustomSaveHandler | undefined>(() => {
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<CustomSaveHandler["preview"]> = 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"
@@ -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<typeof import("@/lib/backend/api")>()), 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<Element>; 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<HTMLElement>('[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");
});
});
@@ -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<number>;
prepareFullReload?: () => void;
customSaveHandler?: { save: ReturnType<typeof vi.fn> };
customSaveHandler?: CustomSaveHandler;
confirmSaveRequest?: (request: import("@/composables/useDataGridEditor").DataGridSaveConfirmationRequest) => Promise<boolean>;
manualTransactionSessionId?: string;
ensureManualTransactionSession?: () => Promise<string>;
@@ -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 () => {
@@ -80,18 +80,21 @@ export interface CustomSaveHandler {
save: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; newRowMeta: GridNewRowMeta[]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<void>;
applySavedChanges?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; columns: string[] }) => void;
preview?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; newRowMeta: GridNewRowMeta[]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<string[]>;
/** 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<RowStatusFilter>;
dataGridQuickEntryEnabled?: ComputedRef<boolean>;
confirmDangerousRowDeletion?: ComputedRef<boolean>;
/**
* 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<boolean>) | undefined>;
/** `生成 SQL 时包含数据库名` — qualify saved tables with their database. */
includeDatabaseNameInSaveSql?: ComputedRef<boolean>;
@@ -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;
}
@@ -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<DataGridSaveConfirmationRequest | null>;
open: WritableComputedRef<boolean>;
updates: ComputedRef<number>;
inserts: ComputedRef<number>;
deletes: ComputedRef<number>;
total: ComputedRef<number>;
targetLabel: ComputedRef<string | undefined>;
statements: ComputedRef<string[]>;
request: (request: DataGridSaveConfirmationRequest) => Promise<boolean>;
confirm: () => void;
cancel: () => void;
} {
const pending = ref<DataGridSaveConfirmationRequest | null>(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<boolean> {
return new Promise<boolean>((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 };
}
@@ -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<DataGridSaveConfirmationRequest | null>;
open: WritableComputedRef<boolean>;
updates: ComputedRef<number>;
inserts: ComputedRef<number>;
deletes: ComputedRef<number>;
total: ComputedRef<number>;
targetLabel: ComputedRef<string | undefined>;
statements: ComputedRef<string[]>;
request: (request: DataGridSaveConfirmationRequest) => Promise<boolean>;
confirm: () => void;
cancel: () => void;
} {
const pending = ref<DataGridSaveConfirmationRequest | null>(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<boolean> {
return new Promise<boolean>((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";
+4
View File
@@ -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",
+4
View File
@@ -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: "只读结果",
@@ -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<ConnectionConfig, "db_type" | "external_config" | "url_params"> {
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<Array<string | number | boolean | null>>, deletedRows = new Set([0])) {
return {
dirtyRows: new Map<number, Map<number, string | number | boolean | null>>(),
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/);
});
});
@@ -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<number, ReadonlyMap<number, CellValue>>;
newRows: readonly (readonly CellValue[])[];
deletedRows: ReadonlySet<number>;
columns: readonly string[];
rows: readonly (readonly CellValue[])[];
}
function configuredInfluxDbVersion(connection: Pick<ConnectionConfig, "db_type" | "external_config">): 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<string, unknown>).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<ConnectionConfig, "db_type" | "external_config"> | undefined): boolean {
if (connection?.db_type !== "influxdb") return false;
const version = configuredInfluxDbVersion(connection);
return version === undefined || version === "1" || version === "v1";
}
function influxColumnRole(column: Pick<ColumnInfo, "extra">): "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<ConnectionConfig, "db_type" | "external_config" | "url_params"> | 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<string, ColumnInfo>();
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<string>();
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<string>();
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};`);
}