fix(sqlite): reject ambiguous keyless updates on duplicate rows
This commit is contained in:
1 parent
9e0381f737
commit
5814ff0088
4 files changed
+377
-5
No files matched your search
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
|
||||
cancelConditionalUpdate: vi.fn(),
|
||||
executeInTransaction: vi.fn(),
|
||||
executeInManualTransaction: vi.fn(),
|
||||
executeQuery: vi.fn(),
|
||||
addHistory: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -22,6 +23,7 @@ vi.mock("@/lib/backend/api", () => ({
|
||||
cancelConditionalUpdate: mocks.cancelConditionalUpdate,
|
||||
executeInTransaction: mocks.executeInTransaction,
|
||||
executeInManualTransaction: mocks.executeInManualTransaction,
|
||||
executeQuery: mocks.executeQuery,
|
||||
unlockConnectionWrites: vi.fn(),
|
||||
lockConnectionWrites: vi.fn(),
|
||||
connectionWriteUnlockState: vi.fn().mockResolvedValue(0),
|
||||
@@ -621,6 +623,7 @@ describe("useDataGridEditor saveChanges reload", () => {
|
||||
mocks.cancelConditionalUpdate.mockReset();
|
||||
mocks.executeInTransaction.mockReset();
|
||||
mocks.executeInManualTransaction.mockReset();
|
||||
mocks.executeQuery.mockReset();
|
||||
mocks.addHistory.mockReset();
|
||||
mocks.getConfig.mockReset();
|
||||
});
|
||||
@@ -635,6 +638,9 @@ describe("useDataGridEditor saveChanges reload", () => {
|
||||
manualTransactionSessionId?: string;
|
||||
refreshSavedRows?: ReturnType<typeof vi.fn>;
|
||||
onManualTransactionMutation?: ReturnType<typeof vi.fn>;
|
||||
connectionId?: string;
|
||||
primaryKeys?: string[];
|
||||
onExecuteSql?: (sql: string) => Promise<void>;
|
||||
} = {},
|
||||
) {
|
||||
const emit = vi.fn();
|
||||
@@ -651,7 +657,7 @@ describe("useDataGridEditor saveChanges reload", () => {
|
||||
result: computed(() => result.value),
|
||||
editable: computed(() => true),
|
||||
databaseType: computed(() => "mysql"),
|
||||
connectionId: computed(() => "connection-1"),
|
||||
connectionId: computed(() => ("connectionId" in options ? options.connectionId : "connection-1")),
|
||||
database: computed(() => "app"),
|
||||
tableMeta: computed(() => ({
|
||||
tableName: "orders_test",
|
||||
@@ -659,11 +665,11 @@ describe("useDataGridEditor saveChanges reload", () => {
|
||||
{ name: "id", data_type: "int" },
|
||||
{ name: "status", data_type: "varchar" },
|
||||
],
|
||||
primaryKeys: ["id"],
|
||||
primaryKeys: options.primaryKeys ?? ["id"],
|
||||
})),
|
||||
sourceColumns: computed(() => undefined),
|
||||
joinedWriteTargets: computed(() => options.joinedWriteTargets),
|
||||
onExecuteSql: computed(() => undefined),
|
||||
onExecuteSql: computed(() => options.onExecuteSql),
|
||||
customSaveHandler: computed(() => options.customSaveHandler),
|
||||
manualTransactionSessionId: computed(() => options.manualTransactionSessionId),
|
||||
onManualTransactionMutation: options.onManualTransactionMutation,
|
||||
@@ -685,6 +691,69 @@ describe("useDataGridEditor saveChanges reload", () => {
|
||||
return { editor, emit, currentPage };
|
||||
}
|
||||
|
||||
// https://github.com/t8y2/dbx/issues/8321: without a primary key the row is
|
||||
// addressed by matching every column value, and the loaded page cannot show
|
||||
// whether another physical row matches the same condition.
|
||||
const keylessGuard = {
|
||||
sql: "SELECT COUNT(*) AS dbx_keyless_row_matches FROM orders_test WHERE (status = 'pending')",
|
||||
maxMatchedRows: 1,
|
||||
message: "Cannot safely update or delete this row: more than one row matches.",
|
||||
};
|
||||
|
||||
it("refuses a keyless save when the server counts more than one row matching the predicate the save sends", async () => {
|
||||
mocks.prepareDataGridSave.mockResolvedValue({
|
||||
statements: ["UPDATE orders_test SET status='shipped' WHERE status = 'pending'"],
|
||||
rollbackStatements: [],
|
||||
keylessGuards: [keylessGuard],
|
||||
});
|
||||
mocks.executeQuery.mockResolvedValue({ columns: ["dbx_keyless_row_matches"], rows: [[2]] });
|
||||
|
||||
const { editor } = createSaveTestEditor({ primaryKeys: [] });
|
||||
editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
|
||||
|
||||
await editor.saveChanges();
|
||||
|
||||
expect(mocks.executeQuery).toHaveBeenCalledWith("connection-1", "app", keylessGuard.sql, undefined);
|
||||
expect(mocks.executeBatch).not.toHaveBeenCalled();
|
||||
expect(editor.saveError.value).toBe(keylessGuard.message);
|
||||
});
|
||||
|
||||
it("runs a keyless save once the server confirms the predicate matches a single row", async () => {
|
||||
mocks.prepareDataGridSave.mockResolvedValue({
|
||||
statements: ["UPDATE orders_test SET status='shipped' WHERE status = 'pending'"],
|
||||
rollbackStatements: [],
|
||||
keylessGuards: [keylessGuard],
|
||||
});
|
||||
mocks.executeQuery.mockResolvedValue({ columns: ["dbx_keyless_row_matches"], rows: [[1]] });
|
||||
mocks.executeBatch.mockResolvedValue({ affected_rows: 1 });
|
||||
|
||||
const { editor } = createSaveTestEditor({ primaryKeys: [] });
|
||||
editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
|
||||
|
||||
await editor.saveChanges();
|
||||
|
||||
expect(mocks.executeBatch).toHaveBeenCalledTimes(1);
|
||||
expect(editor.saveError.value).toBeFalsy();
|
||||
});
|
||||
|
||||
it("refuses a keyless save when the guard cannot be counted on the server at all", async () => {
|
||||
const onExecuteSql = vi.fn().mockResolvedValue(undefined);
|
||||
mocks.prepareDataGridSave.mockResolvedValue({
|
||||
statements: ["UPDATE orders_test SET status='shipped' WHERE status = 'pending'"],
|
||||
rollbackStatements: [],
|
||||
keylessGuards: [keylessGuard],
|
||||
});
|
||||
|
||||
const { editor } = createSaveTestEditor({ primaryKeys: [], connectionId: undefined, onExecuteSql });
|
||||
editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
|
||||
|
||||
await editor.saveChanges();
|
||||
|
||||
expect(onExecuteSql).not.toHaveBeenCalled();
|
||||
expect(mocks.executeQuery).not.toHaveBeenCalled();
|
||||
expect(editor.saveError.value).toContain("could not check on the server");
|
||||
});
|
||||
|
||||
it("reloads after a pure row update, so database-computed columns (e.g. ON UPDATE CURRENT_TIMESTAMP) refresh without a manual page reload", async () => {
|
||||
mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders_test SET status='shipped' WHERE id=1"], rollbackStatements: [] });
|
||||
mocks.executeBatch.mockResolvedValue({ affected_rows: 1 });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { joinedSaveOptions } from "@/lib/dataGrid/joinedRowChanges";
|
||||
import { ref, shallowRef, triggerRef, computed, nextTick, watch, getCurrentInstance, onActivated, onBeforeUnmount, onDeactivated, onMounted, toRaw, type ComputedRef, type Ref } from "vue";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import type { DataGridSaveGuard } from "@/lib/backend/tauri";
|
||||
import type { CellValue } from "@/lib/dataGrid/cellValue";
|
||||
import { coerceDataGridCellValue, dataGridCellEditorText } from "@/lib/dataGrid/dataGridCellCoercion";
|
||||
import { focusDataGridEditorWithoutScrolling, preserveDataGridScrollPosition } from "@/lib/dataGrid/dataGridEditorFocus";
|
||||
@@ -20,6 +21,8 @@ import { normalizeBackendError } from "@/lib/backend/errorUtils";
|
||||
import { uuid } from "@/lib/common/utils";
|
||||
import i18n from "@/i18n";
|
||||
|
||||
const KEYLESS_GUARD_UNVERIFIED_ERROR = "Cannot safely update or delete this row: the table has no primary key, and DBX could not check on the server whether the row can be targeted uniquely. Add a primary key or unique index before editing.";
|
||||
|
||||
interface RowItem {
|
||||
id: number;
|
||||
sourceIndex?: number;
|
||||
@@ -1507,18 +1510,44 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
dirtyRows: new Map(stmtOptions.dirtyRows.map(([index, changes]) => [index, new Map(changes)])),
|
||||
deletedRows: new Set(stmtOptions.deletedRows),
|
||||
});
|
||||
const prepared: Awaited<ReturnType<typeof api.prepareDataGridSave>> = { statements: [], rollbackStatements: [] };
|
||||
const prepared: Awaited<ReturnType<typeof api.prepareDataGridSave>> = { statements: [], rollbackStatements: [], keylessGuards: [] };
|
||||
for (const group of groups) {
|
||||
const part = await api.prepareDataGridSave(group, saveDriverProfile());
|
||||
if (part.validationError) return part;
|
||||
prepared.statements.push(...part.statements);
|
||||
prepared.rollbackStatements.unshift(...part.rollbackStatements);
|
||||
prepared.keylessGuards!.push(...(part.keylessGuards ?? []));
|
||||
if (prepared.executionSchema && part.executionSchema && prepared.executionSchema !== part.executionSchema) throw new Error("Joined source tables require incompatible execution schemas.");
|
||||
prepared.executionSchema ??= part.executionSchema;
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
// A keyless save can only be trusted once the server confirms that each
|
||||
// predicate it sends addresses a single physical row; the loaded page cannot
|
||||
// see rows outside it. Returns the error to fail with, or undefined to allow.
|
||||
async function verifyKeylessGuards(guards: DataGridSaveGuard[], executionSchema?: string) {
|
||||
if (!guards.length) return undefined;
|
||||
const txnSessionId = manualTransactionSessionId.value;
|
||||
// Without a connection to count against there is no way to verify the
|
||||
// predicate, and an unverified keyless write is exactly what must not run.
|
||||
if (!hasBackendSaveTarget.value) return KEYLESS_GUARD_UNVERIFIED_ERROR;
|
||||
for (const guard of guards) {
|
||||
let matched: unknown;
|
||||
if (txnSessionId) {
|
||||
const results = await api.executeInManualTransaction(txnSessionId, guard.sql, database.value ?? "", executionSchema, 1);
|
||||
matched = (results.find((result) => result.columns.length > 0) ?? results[results.length - 1])?.rows?.[0]?.[0];
|
||||
} else {
|
||||
const result = await api.executeQuery(connectionId.value!, database.value ?? "", guard.sql, executionSchema);
|
||||
matched = result?.rows?.[0]?.[0];
|
||||
}
|
||||
const count = Number(matched);
|
||||
if (!Number.isFinite(count)) return KEYLESS_GUARD_UNVERIFIED_ERROR;
|
||||
if (count > guard.maxMatchedRows) return guard.message;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function saveDriverProfile() {
|
||||
const id = connectionId.value;
|
||||
return id ? connectionStore.getConfig(id)?.driver_profile : undefined;
|
||||
@@ -1844,6 +1873,18 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
return;
|
||||
}
|
||||
const rollbackStmts = preparedSave?.rollbackStatements ?? [];
|
||||
try {
|
||||
const guardError = await verifyKeylessGuards(preparedSave?.keylessGuards ?? [], preparedSave?.executionSchema);
|
||||
if (guardError) {
|
||||
saveError.value = guardError;
|
||||
await finishInterruptedSaveChanges(snapshot);
|
||||
return;
|
||||
}
|
||||
} catch (e: any) {
|
||||
saveError.value = normalizeDataGridSaveError(databaseType.value, e);
|
||||
await finishInterruptedSaveChanges(snapshot);
|
||||
return;
|
||||
}
|
||||
const productionAssessment = assessProductionSql(stmts.join(";\n"), connection, database.value);
|
||||
if (productionAssessment.active && productionAssessment.isMutation) {
|
||||
// Autosave must never write production data without an operator reviewing the generated statements.
|
||||
|
||||
@@ -1840,11 +1840,23 @@ export async function analyzeEditableQueryEditability(sql: string): Promise<Quer
|
||||
return invoke("analyze_editable_query_editability", { sql });
|
||||
}
|
||||
|
||||
/// A server-side check that must pass before `statements` may run. Without a
|
||||
/// primary key a row is addressed by matching every column value, so the same
|
||||
/// predicate can match rows outside the loaded page; `sql` counts the matches
|
||||
/// of a predicate the save actually sends, and the save must be refused with
|
||||
/// `message` unless the returned count is at most `maxMatchedRows`.
|
||||
export interface DataGridSaveGuard {
|
||||
sql: string;
|
||||
maxMatchedRows: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface DataGridSavePreparation {
|
||||
validationError?: string;
|
||||
statements: string[];
|
||||
rollbackStatements: string[];
|
||||
executionSchema?: string;
|
||||
keylessGuards?: DataGridSaveGuard[];
|
||||
}
|
||||
|
||||
export async function prepareDataGridSave(options: DataGridSaveStatementOptions, driverProfile?: string): Promise<DataGridSavePreparation> {
|
||||
|
||||
Reference in new issue
Block a user