fix: save and delete a split in one transaction (#513)

saveSplitAdjustment and deleteSplitAdjustment sent their statements one by
one through getDb(), outside any SQL transaction: an error in the middle
left a half-written split that the reports add up as it is (entries without
their offset line, children without the parent's split flag), and a parent
that could not be found threw after its children were already deleted.

Both now run in withTransaction, through a private *InTransaction function
that issues BEGIN, the statements on the transaction's handle, then COMMIT,
and ROLLBACK then rethrow on any error (the pattern of
applyKeywordInTransaction and updateTransactionCategoryInTransaction). The
save reads the parent first, so a missing parent throws before any write.
The statements and their values are those of main, in the same order once
the parent read is moved before the DELETE: same entries, same offset line
(the parent's description and category, -offsetTotal), same split flag.

Both notify the data-change channel once withTransaction returns, after the
COMMIT and with the DB lock released, never after a ROLLBACK (ADR 0022: a
split writes rows of transactions, which the getting-started counters read).

Tests: the same statements and values as before (green on the base too),
the BEGIN/read/writes/COMMIT order and one notification after the lock is
released, a missing parent (BEGIN, read, ROLLBACK, nothing written), a
failure of each write (ROLLBACK right after it, error rethrown, no
notification), and every statement through the transaction's handle, none
through getDb(). The callers (useTransactions, AdjustmentsPage) are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-27 22:37:31 -04:00
commit e09994ada2
2 changed files with 334 additions and 53 deletions

View file

@ -11,8 +11,10 @@ vi.mock("./db", () => {
import { getDb, withTransaction } from "./db";
import { subscribeDataChanged } from "./dataEvents";
import {
deleteSplitAdjustment,
getTransactionCount,
insertBatch,
saveSplitAdjustment,
updateTransactionCategory,
updateTransactionNotes,
} from "./transactionService";
@ -71,13 +73,15 @@ const targetOf = (write: { params: unknown[] }) => write.params[write.params.len
/**
* Answers the two reads of the offset propagation (#454): the row of the
* transaction being recategorized, by its id, and the children of a split, by
* `parent_transaction_id`. Any other read fails the test.
* `parent_transaction_id`. The same `WHERE id = $1` answers the parent read of
* a split being saved (#513), with no row for `null`. Any other read fails the
* test.
*/
function answerSplitReads(row: Record<string, unknown>, children: Array<Record<string, unknown>>) {
function answerSplitReads(row: Record<string, unknown> | null, children: Array<Record<string, unknown>>) {
mockSelect.mockImplementation(async (sql: string) => {
const flat = String(sql).replace(/\s+/g, " ");
if (/WHERE parent_transaction_id = \$1/.test(flat)) return children;
if (/WHERE id = \$1/.test(flat)) return [row];
if (/WHERE id = \$1/.test(flat)) return row ? [row] : [];
throw new Error(`unexpected read: ${flat}`);
});
}
@ -274,3 +278,229 @@ describe("insertBatch — data-change notification (#396)", () => {
expect(notified).toEqual([]);
});
});
/** A statement's SQL with its whitespace collapsed, as `writes()` gives it. */
const collapse = (sql: unknown) => String(sql).replace(/\s+/g, " ").trim();
type Statement = { sql: string; params: unknown[] };
/** Every statement sent, the reads with the writes, in the order they were sent. */
const statements = (): Statement[] =>
[
...mockSelect.mock.calls.map(([sql, params], i) => ({ at: mockSelect.mock.invocationCallOrder[i], sql, params })),
...mockExecute.mock.calls.map(([sql, params], i) => ({ at: mockExecute.mock.invocationCallOrder[i], sql, params })),
]
.sort((a, b) => a.at - b.at)
.map(({ sql, params }) => ({ sql: collapse(sql), params: (params ?? []) as unknown[] }));
const TRANSACTION_CONTROL = ["BEGIN", "COMMIT", "ROLLBACK"];
// The statements of a split, as `main` writes them before #513.
const READ_PARENT = "SELECT * FROM transactions WHERE id = $1";
const DELETE_CHILDREN = "DELETE FROM transactions WHERE parent_transaction_id = $1";
const INSERT_CHILD =
"INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)";
const MARK_SPLIT = "UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1";
const UNMARK_SPLIT = "UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1";
// A transaction of −120 in category 3, split from the Transactions page: −50 to
// category 8 with the parent's description, −20 to category 11 with its own.
const SAVED_PARENT = {
id: 5,
date: "2026-10-01",
description: "EPICERIE METRO",
amount: -120,
category_id: 3,
source_id: 2,
file_id: 4,
original_description: "EPICERIE METRO 0042",
is_split: 0,
parent_transaction_id: null,
};
const SAVED_ENTRIES = [
{ category_id: 8, amount: -50, description: "EPICERIE METRO" },
{ category_id: 11, amount: -20, description: "PHARMACIE" },
];
/** The writes of that split, BEGIN and COMMIT aside. */
const SAVED_WRITES = [
{ sql: DELETE_CHILDREN, params: [5] },
{ sql: INSERT_CHILD, params: ["2026-10-01", "EPICERIE METRO", -50, 8, 2, 4, "EPICERIE METRO 0042", 5] },
{ sql: INSERT_CHILD, params: ["2026-10-01", "PHARMACIE", -20, 11, 2, 4, "EPICERIE METRO 0042", 5] },
// The offset line: the parent's description and category, minus the entries' total.
{ sql: INSERT_CHILD, params: ["2026-10-01", "EPICERIE METRO", 70, 3, 2, 4, "EPICERIE METRO 0042", 5] },
{ sql: MARK_SPLIT, params: [5] },
];
describe("a split is saved or deleted in one transaction (#513)", () => {
/** At each notification: the last statement sent, and whether the DB lock was held. */
const seen: Array<{ last: string; inLock: boolean }> = [];
let inLock = false;
let stop: () => void = () => undefined;
beforeEach(() => {
seen.length = 0;
inLock = false;
vi.mocked(withTransaction).mockImplementation(async (fn) => {
inLock = true;
try {
return await fn((await getDb()) as never);
} finally {
inLock = false;
}
});
stop = subscribeDataChanged(() => {
const sent = writes();
seen.push({ last: sent[sent.length - 1]?.sql ?? "", inLock });
});
});
afterEach(() => {
stop();
vi.mocked(withTransaction).mockImplementation(async (fn) => fn((await getDb()) as never));
});
/** Fails, with "disk full", every statement `failing` matches; any other one succeeds. */
function failOn(failing: (write: Statement) => boolean) {
mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => {
if (failing({ sql: collapse(sql), params: params ?? [] })) throw new Error("disk full");
return { rowsAffected: 1 };
});
}
/** Runs `run` with getDb() rejecting and the transaction's handle on the mocked database. */
async function handleOnly(run: () => Promise<void>) {
const outside = vi.fn(async () => {
throw new Error("getDb() inside the transaction deadlocks");
});
vi.mocked(getDb).mockResolvedValue({ select: outside, execute: outside } as never);
vi.mocked(withTransaction).mockImplementationOnce(async (fn) => fn(mockDb as never));
await run();
return outside;
}
describe("saveSplitAdjustment", () => {
it("writes the same statements, with the same values, as before #513", async () => {
answerSplitReads(SAVED_PARENT, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES);
expect(writes().filter((w) => !TRANSACTION_CONTROL.includes(w.sql))).toEqual(SAVED_WRITES);
});
it("writes the fallbacks of a parent without category, source, file or original description as before", async () => {
answerSplitReads(
{ ...SAVED_PARENT, category_id: null, source_id: null, file_id: null, original_description: null },
[],
);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await saveSplitAdjustment(SAVED_PARENT.id, [SAVED_ENTRIES[0]]);
expect(writes().filter((w) => w.sql === INSERT_CHILD).map((w) => w.params)).toEqual([
["2026-10-01", "EPICERIE METRO", -50, 8, null, null, "", 5],
["2026-10-01", "EPICERIE METRO", 50, null, null, null, "", 5],
]);
});
it("reads the parent first, writes between one BEGIN and its COMMIT, then notifies once, lock released", async () => {
answerSplitReads(SAVED_PARENT, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES);
expect(statements()).toEqual([
{ sql: "BEGIN", params: [] },
{ sql: READ_PARENT, params: [5] },
...SAVED_WRITES,
{ sql: "COMMIT", params: [] },
]);
expect(seen).toEqual([{ last: "COMMIT", inLock: false }]);
});
it("throws before any write when the parent cannot be found, rolls back and does not notify", async () => {
answerSplitReads(null, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await expect(saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES)).rejects.toThrow(
"Parent transaction not found",
);
expect(statements()).toEqual([
{ sql: "BEGIN", params: [] },
{ sql: READ_PARENT, params: [5] },
{ sql: "ROLLBACK", params: [] },
]);
expect(seen).toEqual([]);
});
it.each<[string, (w: Statement) => boolean]>([
["the DELETE of the former children", (w) => w.sql === DELETE_CHILDREN],
["the INSERT of an entry", (w) => w.sql === INSERT_CHILD && w.params[2] === -20],
["the INSERT of the offset line", (w) => w.sql === INSERT_CHILD && w.params[2] === 70],
["the UPDATE of the split flag", (w) => w.sql === MARK_SPLIT],
])("rolls back right after %s fails, rethrows and does not notify", async (_label, failing) => {
answerSplitReads(SAVED_PARENT, []);
failOn(failing);
await expect(saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES)).rejects.toThrow("disk full");
const sent = statements();
expect(sent[0].sql).toBe("BEGIN");
expect(failing(sent[sent.length - 2])).toBe(true);
expect(sent[sent.length - 1].sql).toBe("ROLLBACK");
expect(sent.map((s) => s.sql)).not.toContain("COMMIT");
expect(seen).toEqual([]);
});
// Under the real lock, a getDb() call inside the callback waits for the
// transaction that waits for it: a deadlock (#408).
it("sends every statement through the transaction's handle, none through getDb()", async () => {
answerSplitReads(SAVED_PARENT, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
const outside = await handleOnly(() => saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES));
expect(outside).not.toHaveBeenCalled();
expect(statements().map((s) => s.sql)).toEqual([
"BEGIN",
READ_PARENT,
...SAVED_WRITES.map((w) => w.sql),
"COMMIT",
]);
});
});
describe("deleteSplitAdjustment", () => {
const DELETED_WRITES = [
{ sql: DELETE_CHILDREN, params: [5] },
{ sql: UNMARK_SPLIT, params: [5] },
];
it("writes the same statements, with the same values, as before #513", async () => {
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await deleteSplitAdjustment(5);
expect(writes().filter((w) => !TRANSACTION_CONTROL.includes(w.sql))).toEqual(DELETED_WRITES);
});
it("deletes the children and clears the split flag between one BEGIN and its COMMIT, then notifies once, lock released", async () => {
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await deleteSplitAdjustment(5);
expect(statements()).toEqual([
{ sql: "BEGIN", params: [] },
...DELETED_WRITES,
{ sql: "COMMIT", params: [] },
]);
expect(seen).toEqual([{ last: "COMMIT", inLock: false }]);
});
it.each([
["the DELETE of the children", DELETE_CHILDREN],
["the UPDATE of the split flag", UNMARK_SPLIT],
])("rolls back right after %s fails, rethrows and does not notify", async (_label, failingSql) => {
failOn((w) => w.sql === failingSql);
await expect(deleteSplitAdjustment(5)).rejects.toThrow("disk full");
const sent = statements();
expect(sent[0].sql).toBe("BEGIN");
expect(sent[sent.length - 2].sql).toBe(failingSql);
expect(sent[sent.length - 1].sql).toBe("ROLLBACK");
expect(sent.map((s) => s.sql)).not.toContain("COMMIT");
expect(seen).toEqual([]);
});
it("sends every statement through the transaction's handle, none through getDb()", async () => {
mockExecute.mockResolvedValue({ rowsAffected: 1 });
const outside = await handleOnly(() => deleteSplitAdjustment(5));
expect(outside).not.toHaveBeenCalled();
expect(statements().map((s) => s.sql)).toEqual(["BEGIN", DELETE_CHILDREN, UNMARK_SPLIT, "COMMIT"]);
});
});
});

View file

@ -434,76 +434,127 @@ export async function getSplitChildren(parentId: number): Promise<SplitChild[]>
);
}
/**
* Writes the split of `parentId`: its entries, then the offset line that
* cancels in the parent's category the part sent to the other categories, then
* the parent's split flag. One transaction (#513): an error on any statement
* rolls the whole split back, and a parent that cannot be found throws before
* any write.
*/
export async function saveSplitAdjustment(
parentId: number,
entries: Array<{ category_id: number; amount: number; description: string }>
): Promise<void> {
const db = await getDb();
// Delete any existing children
await db.execute(
`DELETE FROM transactions WHERE parent_transaction_id = $1`,
[parentId]
await withTransaction((db) =>
saveSplitAdjustmentInTransaction(db, parentId, entries)
);
// Reached only after the COMMIT (a ROLLBACK rethrows), once the DB lock is
// released: a split writes rows of `transactions`, which the getting-started
// counters read (ADR 0022).
notifyDataChanged();
}
// Fetch parent transaction
const [parent] = await db.select<Transaction[]>(
`SELECT * FROM transactions WHERE id = $1`,
[parentId]
);
if (!parent) throw new Error("Parent transaction not found");
async function saveSplitAdjustmentInTransaction(
db: Database,
parentId: number,
entries: Array<{ category_id: number; amount: number; description: string }>
): Promise<void> {
// `withTransaction` only holds the DB lock: the BEGIN, the COMMIT and the
// ROLLBACK are this function's.
await db.execute("BEGIN");
try {
// Fetch the parent before any write: a parent that cannot be found throws
// with nothing written.
const [parent] = await db.select<Transaction[]>(
`SELECT * FROM transactions WHERE id = $1`,
[parentId]
);
if (!parent) throw new Error("Parent transaction not found");
// Insert each split child
let offsetTotal = 0;
for (const entry of entries) {
// Delete any existing children
await db.execute(
`DELETE FROM transactions WHERE parent_transaction_id = $1`,
[parentId]
);
// Insert each split child
let offsetTotal = 0;
for (const entry of entries) {
await db.execute(
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)`,
[
parent.date,
entry.description,
entry.amount,
entry.category_id,
parent.source_id ?? null,
parent.file_id ?? null,
parent.original_description ?? "",
parentId,
]
);
offsetTotal += entry.amount;
}
// Insert offset child (cancels the redistributed portion from the original category)
await db.execute(
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)`,
[
parent.date,
entry.description,
entry.amount,
entry.category_id,
parent.description,
-offsetTotal,
parent.category_id ?? null,
parent.source_id ?? null,
parent.file_id ?? null,
parent.original_description ?? "",
parentId,
]
);
offsetTotal += entry.amount;
// Mark parent as split
await db.execute(
`UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1`,
[parentId]
);
await db.execute("COMMIT");
} catch (e) {
await db.execute("ROLLBACK");
throw e;
}
// Insert offset child (cancels the redistributed portion from the original category)
await db.execute(
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)`,
[
parent.date,
parent.description,
-offsetTotal,
parent.category_id ?? null,
parent.source_id ?? null,
parent.file_id ?? null,
parent.original_description ?? "",
parentId,
]
);
// Mark parent as split
await db.execute(
`UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1`,
[parentId]
);
}
/**
* Removes the split of `parentId`: its children, then its split flag, in one
* transaction (#513).
*/
export async function deleteSplitAdjustment(parentId: number): Promise<void> {
const db = await getDb();
await db.execute(
`DELETE FROM transactions WHERE parent_transaction_id = $1`,
[parentId]
);
await db.execute(
`UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1`,
[parentId]
);
await withTransaction((db) => deleteSplitAdjustmentInTransaction(db, parentId));
// Reached only after the COMMIT (a ROLLBACK rethrows), once the DB lock is
// released, as for a saved split (ADR 0022).
notifyDataChanged();
}
async function deleteSplitAdjustmentInTransaction(
db: Database,
parentId: number
): Promise<void> {
// `withTransaction` only holds the DB lock: the BEGIN, the COMMIT and the
// ROLLBACK are this function's.
await db.execute("BEGIN");
try {
await db.execute(
`DELETE FROM transactions WHERE parent_transaction_id = $1`,
[parentId]
);
await db.execute(
`UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1`,
[parentId]
);
await db.execute("COMMIT");
} catch (e) {
await db.execute("ROLLBACK");
throw e;
}
}