Skip to content

A local-first personal finance app

:hedgehog: Make saving transaction edits slightly faster on big budgets (#8944)

Michael Clark5a131c7c8821
diff --git a/packages/loot-core/src/platform/server/sqlite/index.test.ts b/packages/loot-core/src/platform/server/sqlite/index.test.ts
index 5afdec72e3..01f8c240e2 100644
--- a/packages/loot-core/src/platform/server/sqlite/index.test.ts
+++ b/packages/loot-core/src/platform/server/sqlite/index.test.ts
@@ -85,6 +85,54 @@ describe('Web sqlite', () => {
expect(rows[2].number).toBe(6);
});
+ it('should use the crdt index for a batched cell lookup', async () => {
+ // Mirrors the query `compareMessages` in server/sync builds for a
+ // full chunk. If the planner ever falls back to a table scan on the
+ // web build's SQLite, bulk edits get slow again.
+ const db = await openDatabase();
+ execQuery(
+ db,
+ `
+ CREATE TABLE messages_crdt (
+ id INTEGER PRIMARY KEY,
+ timestamp TEXT NOT NULL UNIQUE,
+ dataset TEXT NOT NULL,
+ row TEXT NOT NULL,
+ column TEXT NOT NULL,
+ value BLOB NOT NULL
+ );
+ CREATE INDEX messages_crdt_search ON messages_crdt(dataset, row, column, timestamp);
+ `,
+ );
+
+ const termCount = 100;
+ const term = '(dataset = ? AND row = ? AND column = ? AND timestamp >= ?)';
+ const sql =
+ 'SELECT dataset, row, column, timestamp FROM messages_crdt WHERE ' +
+ Array(termCount).fill(term).join(' OR ');
+ const params = Array.from({ length: termCount }, (_, index) => [
+ 'transactions',
+ `row${index}`,
+ 'amount',
+ '2024-01-01T00:00:00.000Z-0000-0000000000000000',
+ ]).flat();
+
+ const plan = runQuery<{ detail: string }>(
+ db,
+ 'EXPLAIN QUERY PLAN ' + sql,
+ params,
+ true,
+ );
+ expect(plan.length).toBeGreaterThan(0);
+ expect(plan.some(step => step.detail.includes('SCAN'))).toBe(false);
+ expect(
+ plan.some(step => step.detail.includes('messages_crdt_search')),
+ ).toBe(true);
+
+ // And the query itself runs within the parameter limits
+ expect(runQuery(db, sql, params, true)).toEqual([]);
+ });
+
it('should match regex on text fields', async () => {
const db = await openDatabase();
execQuery(db, initSQL);
diff --git a/packages/loot-core/src/platform/server/sqlite/index.ts b/packages/loot-core/src/platform/server/sqlite/index.ts
index 950f3ddf53..d523dc7360 100644
--- a/packages/loot-core/src/platform/server/sqlite/index.ts
+++ b/packages/loot-core/src/platform/server/sqlite/index.ts
@@ -218,9 +218,13 @@ export async function openDatabase(pathOrBuffer?: string | Uint8Array) {
// @ts-expect-error 2nd argument missed in sql.js types
{ filename: true },
);
+ // absurd-sql serves every page cache miss with a synchronous
+ // round trip to IndexedDB, so allow the cache to hold a whole
+ // large budget file. SQLite allocates cache pages lazily, so
+ // small files don't pay for the ceiling. The value is in KiB.
db.exec(`
PRAGMA journal_mode=MEMORY;
- PRAGMA cache_size=-10000;
+ PRAGMA cache_size=-64000;
`);
}
}
diff --git a/packages/loot-core/src/server/sync/compare-messages.test.ts b/packages/loot-core/src/server/sync/compare-messages.test.ts
new file mode 100644
index 0000000000..58710e572f
--- /dev/null
+++ b/packages/loot-core/src/server/sync/compare-messages.test.ts
@@ -0,0 +1,213 @@
+import { getClock, Timestamp } from '@actual-app/crdt';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import * as budget from '#server/budget/base';
+import * as db from '#server/db';
+import * as sheet from '#server/sheet';
+
+import { applyMessages, setSyncingMode } from './index';
+import type { Message } from './index';
+
+beforeEach(() => {
+ setSyncingMode('enabled');
+ return global.emptyDatabase()();
+});
+
+afterEach(() => {
+ setSyncingMode('disabled');
+});
+
+function sendTimestamp(): Timestamp {
+ const timestamp = Timestamp.send();
+ if (timestamp == null) {
+ throw new Error('Timestamp.send() returned null');
+ }
+ return timestamp;
+}
+
+function amountMessage(
+ row: string,
+ amount: number,
+ timestamp: Timestamp,
+): Message {
+ return {
+ dataset: 'transactions',
+ row,
+ column: 'amount',
+ value: amount,
+ timestamp,
+ };
+}
+
+function getCrdtRows(): db.DbCrdtMessage[] {
+ return db.runQuery<db.DbCrdtMessage>(
+ 'SELECT * FROM messages_crdt ORDER BY timestamp',
+ [],
+ true,
+ );
+}
+
+async function getAmount(row: string): Promise<number | undefined> {
+ const result = await db.first<{ amount: number }>(
+ 'SELECT amount FROM transactions WHERE id = ?',
+ [row],
+ );
+ return result?.amount;
+}
+
+// `applyMessages` only returns nothing in import mode, which these
+// tests never use
+async function applyAll(messages: Message[]): Promise<Message[]> {
+ const applied = await applyMessages(messages);
+ if (applied == null) {
+ throw new Error('applyMessages returned nothing');
+ }
+ return applied;
+}
+
+function findByTimestamp(messages: Message[], timestamp: Timestamp) {
+ return messages.find(
+ message => message.timestamp.toString() === timestamp.toString(),
+ );
+}
+
+describe('compareMessages', () => {
+ it('handles several messages for the same cell in one batch', async () => {
+ const earliest = sendTimestamp();
+ const middle = sendTimestamp();
+ const latest = sendTimestamp();
+
+ await applyMessages([amountMessage('t1', 100, middle)]);
+
+ const applied = await applyAll([
+ amountMessage('t1', 50, earliest),
+ amountMessage('t1', 200, latest),
+ ]);
+
+ expect(applied.length).toBe(2);
+ expect(findByTimestamp(applied, earliest)?.old).toBe(true);
+ expect(findByTimestamp(applied, latest)?.old).toBeUndefined();
+ expect(await getAmount('t1')).toBe(200);
+ expect(getCrdtRows().length).toBe(3);
+ });
+
+ it('drops a message whose timestamp is already in the log', async () => {
+ const first = sendTimestamp();
+ const second = sendTimestamp();
+
+ await applyMessages([amountMessage('t1', 100, first)]);
+
+ const applied = await applyAll([
+ amountMessage('t1', 100, first),
+ amountMessage('t2', 300, second),
+ ]);
+
+ expect(applied.map(message => message.row)).toEqual(['t2']);
+ expect(await getAmount('t2')).toBe(300);
+ expect(getCrdtRows().length).toBe(2);
+ });
+
+ it('flags old and new messages correctly across more than one chunk', async () => {
+ const rowCount = 250;
+ const rows = Array.from({ length: rowCount }, (_, index) => `t${index}`);
+
+ const earlyTimestamps = rows.map(() => sendTimestamp());
+ const loggedTimestamps = rows.map(() => sendTimestamp());
+ const lateTimestamps = rows.map(() => sendTimestamp());
+
+ await applyMessages(
+ rows.map((row, index) =>
+ amountMessage(row, 1000, loggedTimestamps[index]),
+ ),
+ );
+
+ // Even rows get an older value, odd rows get a newer one
+ const applied = await applyAll(
+ rows.map((row, index) =>
+ index % 2 === 0
+ ? amountMessage(row, 1, earlyTimestamps[index])
+ : amountMessage(row, 2, lateTimestamps[index]),
+ ),
+ );
+
+ expect(applied.length).toBe(rowCount);
+ expect(applied.filter(message => message.old).length).toBe(rowCount / 2);
+ for (let index = 0; index < rowCount; index++) {
+ const isOld = index % 2 === 0;
+ const message = findByTimestamp(
+ applied,
+ isOld ? earlyTimestamps[index] : lateTimestamps[index],
+ );
+ expect(message?.old).toBe(isOld ? true : undefined);
+ expect(await getAmount(rows[index])).toBe(isOld ? 1000 : 2);
+ }
+ expect(getCrdtRows().length).toBe(rowCount * 2);
+ });
+
+ it('rolls back the whole batch when one message fails to apply', async () => {
+ const merkleBefore = JSON.stringify(getClock().merkle);
+
+ await expect(
+ applyMessages([
+ amountMessage('t1', 100, sendTimestamp()),
+ {
+ dataset: 'transactions',
+ row: 't1',
+ column: 'brand_new_column',
+ value: 'hello',
+ timestamp: sendTimestamp(),
+ },
+ ]),
+ ).rejects.toMatchObject({ reason: 'invalid-schema' });
+
+ expect(getCrdtRows().length).toBe(0);
+ expect(await getAmount('t1')).toBeUndefined();
+ expect(JSON.stringify(getClock().merkle)).toBe(merkleBefore);
+ });
+
+ it('switches the budget type when the preference arrives via sync', async () => {
+ await db.insertCategoryGroup({
+ id: 'income-group',
+ name: 'Income',
+ is_income: 1,
+ });
+ await db.insertCategory({
+ id: 'income-cat',
+ name: 'Income',
+ cat_group: 'income-group',
+ is_income: 1,
+ });
+ await db.insertCategoryGroup({
+ id: 'group1',
+ name: 'group1',
+ is_income: 0,
+ });
+ await db.insertCategory({
+ id: 'cat1',
+ name: 'cat1',
+ cat_group: 'group1',
+ is_income: 0,
+ });
+ await sheet.loadSpreadsheet(db);
+ await budget.createBudget(['2024-01']);
+ expect(sheet.get().meta().budgetType).toBe('envelope');
+
+ await applyMessages([
+ {
+ dataset: 'preferences',
+ row: 'budgetType',
+ column: 'value',
+ value: 'tracking',
+ timestamp: sendTimestamp(),
+ },
+ ]);
+ await sheet.waitOnSpreadsheet();
+
+ expect(sheet.get().meta().budgetType).toBe('tracking');
+ const preference = await db.first<{ value: string }>(
+ 'SELECT value FROM preferences WHERE id = ?',
+ ['budgetType'],
+ );
+ expect(preference?.value).toBe('tracking');
+ });
+});
diff --git a/packages/loot-core/src/server/sync/index.ts b/packages/loot-core/src/server/sync/index.ts
index b98efa1b44..f865f81bb4 100644
--- a/packages/loot-core/src/server/sync/index.ts
+++ b/packages/loot-core/src/server/sync/index.ts
@@ -174,7 +174,7 @@ function apply(
}
// TODO: convert to `whereIn`
-async function fetchAll(table, ids) {
+function fetchAll(table: string, ids: string[]) {
let results = [];
// was 500, but that caused a stack overflow in Safari
@@ -227,6 +227,21 @@ async function fetchAll(table, ids) {
// TODO make this type stricter.
type DataMap = Map<string, unknown>;
+
+function fetchData(idsPerTable: Record<string, string[]>): DataMap {
+ const data: DataMap = new Map();
+
+ for (const table of Object.keys(idsPerTable)) {
+ const rows = fetchAll(table, idsPerTable[table]);
+
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i];
+ setIn(data, [table, row.id], row);
+ }
+ }
+
+ return data;
+}
type SyncListener = (oldData: DataMap, newData: DataMap) => unknown;
let _syncListeners: SyncListener[] = [];
@@ -238,28 +253,110 @@ export function addSyncListener(func: SyncListener) {
};
}
-async function compareMessages(messages: Message[]): Promise<Message[]> {
- const newMessages = [];
+// Cells per `messages_crdt` lookup in `compareMessages`. The last chunk
+// is padded up to one of these sizes so only a handful of distinct
+// prepared statements ever live in `db.cache`. 100 terms is well inside
+// SQLITE_MAX_EXPR_DEPTH and still uses the messages_crdt_search index.
+const COMPARE_CHUNK_SIZES = [1, 10, 100];
+const compareMessagesSqlByTermCount = new Map<number, string>();
+
+function compareMessagesSql(termCount: number): string {
+ let sql = compareMessagesSqlByTermCount.get(termCount);
+ if (sql == null) {
+ const term = '(dataset = ? AND row = ? AND column = ? AND timestamp >= ?)';
+ sql =
+ 'SELECT dataset, row, column, timestamp FROM messages_crdt WHERE ' +
+ Array(termCount).fill(term).join(' OR ');
+ compareMessagesSqlByTermCount.set(termCount, sql);
+ }
+ return sql;
+}
+
+type CompareKey = {
+ dataset: string;
+ row: string;
+ column: string;
+ timestamp: string;
+};
- for (let i = 0; i < messages.length; i++) {
- const message = messages[i];
- const { dataset, row, column, timestamp } = message;
- const timestampStr = timestamp.toString();
+function cellKey(dataset: string, row: string, column: string): string {
+ return `${dataset}\0${row}\0${column}`;
+}
- const res = db.runQuery<Pick<db.DbCrdtMessage, 'timestamp'>>(
- db.cache(
- 'SELECT timestamp FROM messages_crdt WHERE dataset = ? AND row = ? AND column = ? AND timestamp >= ?',
- ),
- [dataset, row, column, timestampStr],
- true,
+// Filters out messages that are already in the crdt log and flags a
+// message as "old" when a later value for the same cell already exists.
+// Old messages aren't applied but still go into the merkle trie.
+//
+// This does one query per chunk of distinct cells rather than one per
+// message: on the web backend every statement outside a transaction is
+// a separate lock/commit cycle against IndexedDB, and bulk edits and
+// incoming syncs can carry thousands of messages.
+function compareMessages(messages: Message[]): Message[] {
+ if (messages.length === 0) {
+ return [];
+ }
+
+ // The oldest timestamp per cell in this batch. Log rows at or after
+ // it cover every message for that cell.
+ const cells = new Map<string, CompareKey>();
+ for (const message of messages) {
+ const { dataset, row, column } = message;
+ const timestampStr = message.timestamp.toString();
+ const key = cellKey(dataset, row, column);
+ const existing = cells.get(key);
+ if (!existing || timestampStr < existing.timestamp) {
+ cells.set(key, { dataset, row, column, timestamp: timestampStr });
+ }
+ }
+
+ const loggedTimestamps = new Map<string, string[]>();
+ const cellList = [...cells.values()];
+ const largestChunk = COMPARE_CHUNK_SIZES[COMPARE_CHUNK_SIZES.length - 1];
+ for (let start = 0; start < cellList.length; start += largestChunk) {
+ const chunk = cellList.slice(start, start + largestChunk);
+ const chunkSize = COMPARE_CHUNK_SIZES.find(size => size >= chunk.length);
+ // Pad with a repeated cell so the statement shape matches a bucket
+ while (chunk.length < chunkSize) {
+ chunk.push(chunk[chunk.length - 1]);
+ }
+
+ const params = chunk.flatMap(cell => [
+ cell.dataset,
+ cell.row,
+ cell.column,
+ cell.timestamp,
+ ]);
+ const rows = db.runQuery<
+ Pick<db.DbCrdtMessage, 'dataset' | 'row' | 'column' | 'timestamp'>
+ >(db.cache(compareMessagesSql(chunkSize)), params, true);
+
+ for (const logged of rows) {
+ const key = cellKey(logged.dataset, logged.row, logged.column);
+ const timestamps = loggedTimestamps.get(key);
+ if (timestamps) {
+ timestamps.push(logged.timestamp);
+ } else {
+ loggedTimestamps.set(key, [logged.timestamp]);
+ }
+ }
+ }
+
+ const newMessages: Message[] = [];
+ for (const message of messages) {
+ const timestampStr = message.timestamp.toString();
+ const logged = loggedTimestamps.get(
+ cellKey(message.dataset, message.row, message.column),
);
- // Returned message is any one that is "later" than this message,
- // meaning if the result exists this message is an old one
- if (res.length === 0) {
+ if (!logged) {
newMessages.push(message);
- } else if (res[0].timestamp !== timestampStr) {
+ } else if (logged.includes(timestampStr)) {
+ // Exactly this message is already in the log: nothing to do
+ } else if (logged.some(timestamp => timestamp > timestampStr)) {
+ // A later message for this cell exists, so this one is old
newMessages.push({ ...message, old: true });
+ } else {
+ newMessages.push(message);
}
}
@@ -306,57 +403,8 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
if (checkSyncingMode('import')) {
applyMessagesForImport(messages);
return undefined;
- } else if (checkSyncingMode('enabled')) {
- // Compare the messages with the existing crdt. This filters out
- // already applied messages and determines if a message is old or
- // not. An "old" message doesn't need to be applied, but it still
- // needs to be put into the merkle trie to maintain the hash.
- messages = await compareMessages(messages);
- }
-
- messages = [...messages].sort((m1, m2) => {
- const t1 = m1.timestamp ? m1.timestamp.toString() : '';
- const t2 = m2.timestamp ? m2.timestamp.toString() : '';
- if (t1 < t2) {
- return -1;
- } else if (t1 > t2) {
- return 1;
- }
- return 0;
- });
-
- const idsPerTable: Record<string, string[]> = {};
- messages.forEach(msg => {
- if (msg.dataset === 'prefs') {
- return;
- }
-
- if (idsPerTable[msg.dataset] == null) {
- idsPerTable[msg.dataset] = [];
- }
- idsPerTable[msg.dataset].push(msg.row);
- });
-
- async function fetchData(): Promise<DataMap> {
- const data = new Map();
-
- for (const table of Object.keys(idsPerTable)) {
- const rows = await fetchAll(table, idsPerTable[table]);
-
- for (let i = 0; i < rows.length; i++) {
- const row = rows[i];
- setIn(data, [table, row.id], row);
- }
- }
-
- return data;
}
- const prefsToSet: MetadataPrefs = {};
- const oldData = await fetchData();
-
- undo.appendMessages(messages, oldData);
-
// It's important to not mutate the clock while processing the
// messages. We only want to mutate it if the transaction succeeds.
// The merkle variable will be updated while applying the messages and
@@ -372,15 +420,57 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
sheet.get().startCacheBarrier();
}
- // Now that we have all of the data, go through and apply the
- // messages carefully. This transaction is **crucial**: it
- // guarantees that everything is atomically committed to the
- // database, and if any part of it fails everything aborts and
- // nothing is changed. This is critical to maintain consistency. We
- // also avoid any side effects to in-memory objects, and apply them
- // after this succeeds.
+ const prefsToSet: MetadataPrefs = {};
+ let budgetTypeToSet: Message['value'] | undefined;
const deferredMessages = new Set<Message>();
+ const idsPerTable: Record<string, string[]> = {};
+ let oldData: DataMap = new Map();
+ let newData: DataMap = new Map();
+
+ // Everything that touches the database runs in one transaction: the
+ // crdt lookup, reading the affected rows before and after, and the
+ // writes themselves. This transaction is **crucial**: it guarantees
+ // that everything is atomically committed to the database, and if
+ // any part of it fails everything aborts and nothing is changed. It
+ // also matters for speed: on the web backend every statement outside
+ // a transaction is a separate lock/commit cycle against IndexedDB. We
+ // avoid any side effects to in-memory objects, and apply them after
+ // this succeeds.
db.transaction(() => {
+ if (checkSyncingMode('enabled')) {
+ // Compare the messages with the existing crdt. This filters out
+ // already applied messages and determines if a message is old or
+ // not. An "old" message doesn't need to be applied, but it still
+ // needs to be put into the merkle trie to maintain the hash.
+ messages = compareMessages(messages);
+ }
+
+ messages = [...messages].sort((m1, m2) => {
+ const t1 = m1.timestamp ? m1.timestamp.toString() : '';
+ const t2 = m2.timestamp ? m2.timestamp.toString() : '';
+ if (t1 < t2) {
+ return -1;
+ } else if (t1 > t2) {
+ return 1;
+ }
+ return 0;
+ });
+
+ messages.forEach(msg => {
+ if (msg.dataset === 'prefs') {
+ return;
+ }
+
+ if (idsPerTable[msg.dataset] == null) {
+ idsPerTable[msg.dataset] = [];
+ }
+ idsPerTable[msg.dataset].push(msg.row);
+ });
+
+ oldData = fetchData(idsPerTable);
+
+ // Now that we have all of the data, go through and apply the
+ // messages carefully.
const added = new Set();
for (const msg of messages) {
@@ -408,9 +498,11 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
// Special treatment for some synced prefs. Applied messages
// only — an old or deferred message must not flip the
- // in-memory budget type
+ // in-memory budget type. Remember it here and switch after
+ // the commit: switching mutates the in-memory spreadsheet,
+ // which a rollback could not undo
if (dataset === 'preferences' && row === 'budgetType') {
- void setBudgetType(value);
+ budgetTypeToSet = value;
}
}
} else {
@@ -444,11 +536,19 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
[serializeClock({ ...clock, merkle: currentMerkle })],
);
}
+
+ newData = fetchData(idsPerTable);
});
+ // The transaction succeeded, so we can update in-memory objects now
+ undo.appendMessages(messages, oldData);
+
+ if (budgetTypeToSet !== undefined) {
+ void setBudgetType(budgetTypeToSet);
+ }
+
if (checkSyncingMode('enabled')) {
- // The transaction succeeded, so we can update in-memory objects
- // now. Update the in-memory clock.
+ // Update the in-memory clock.
clock.merkle = currentMerkle;
}
@@ -458,8 +558,6 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
connection.send('prefs-updated');
}
- const newData = await fetchData();
-
// In testing, sometimes the spreadsheet isn't loaded, and that's ok
if (sheet.get()) {
// Need to clean up these APIs and make them consistent
diff --git a/packages/loot-core/src/server/transactions/index.test.ts b/packages/loot-core/src/server/transactions/index.test.ts
new file mode 100644
index 0000000000..b95851be4d
--- /dev/null
+++ b/packages/loot-core/src/server/transactions/index.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import * as db from '#server/db';
+
+import { batchUpdateTransactions } from './index';
+
+beforeEach(global.emptyDatabase());
+
+describe('batchUpdateTransactions', () => {
+ it('returns the added, updated and deleted transactions separately', async () => {
+ await db.insertAccount({ id: 'one', name: 'one' });
+ await db.insertTransaction({
+ id: 'to-update',
+ account: 'one',
+ amount: 100,
+ date: '2024-01-01',
+ });
+ await db.insertTransaction({
+ id: 'to-delete',
+ account: 'one',
+ amount: 200,
+ date: '2024-01-02',
+ });
+
+ const result = await batchUpdateTransactions({
+ added: [{ id: 'added', account: 'one', amount: 300, date: '2024-01-03' }],
+ updated: [{ id: 'to-update', amount: 150 }],
+ deleted: [{ id: 'to-delete' }],
+ // With transfers enabled the returned updates only carry
+ // transfer changes; this test is about the partitioning
+ runTransfers: false,
+ });
+
+ expect(result.added.map(transaction => transaction.id)).toEqual(['added']);
+ expect(result.updated.map(transaction => transaction?.id)).toEqual([
+ 'to-update',
+ ]);
+ expect(result.deleted.map(transaction => transaction.id)).toEqual([
+ 'to-delete',
+ ]);
+ expect(result.errors).toEqual([]);
+
+ const remaining = await db.all<{ id: string; amount: number }>(
+ 'SELECT id, amount FROM v_transactions_internal WHERE tombstone = 0 ORDER BY id',
+ );
+ expect(remaining).toEqual([
+ { id: 'added', amount: 300 },
+ { id: 'to-update', amount: 150 },
+ ]);
+ });
+
+ it('does not add any transactions when only editing a field', async () => {
+ await db.insertAccount({ id: 'one', name: 'one' });
+ await db.insertTransaction({
+ id: 't1',
+ account: 'one',
+ amount: 100,
+ date: '2024-01-01',
+ });
+
+ const result = await batchUpdateTransactions({
+ updated: [{ id: 't1', notes: 'hello' }],
+ runTransfers: false,
+ });
+
+ expect(result.added).toEqual([]);
+ expect(result.deleted).toEqual([]);
+ expect(result.updated.map(transaction => transaction?.id)).toEqual(['t1']);
+ const updated = await db.first<{ notes: string }>(
+ 'SELECT notes FROM transactions WHERE id = ?',
+ ['t1'],
+ );
+ expect(updated?.notes).toBe('hello');
+ });
+});
diff --git a/packages/loot-core/src/server/transactions/index.ts b/packages/loot-core/src/server/transactions/index.ts
index 02ba8f2d9a..ebb8f8277e 100644
--- a/packages/loot-core/src/server/transactions/index.ts
+++ b/packages/loot-core/src/server/transactions/index.ts
@@ -57,9 +57,15 @@ export async function batchUpdateTransactions({
: [];
const oldPayees = new Set<PayeeEntity['id']>();
- const accounts = await db.all<db.DbAccount>(
- 'SELECT * FROM accounts WHERE tombstone = 0',
- );
+
+ // Accounts are only needed to clear the category of off-budget
+ // transactions, so skip the read for edits that don't set an account
+ const needsAccounts =
+ (added?.length ?? 0) > 0 ||
+ (updated?.some(transaction => transaction.account) ?? false);
+ const accounts = needsAccounts
+ ? await db.all<db.DbAccount>('SELECT * FROM accounts WHERE tombstone = 0')
+ : [];
// We need to get all the payees of updated transactions _before_
// making changes
@@ -125,9 +131,24 @@ export async function batchUpdateTransactions({
// needed to run any cascading logic that depends on the full
// transaction. Things like transfers, analyzing rule updates, and
// more
- const allAdded = await getTransactionsByIds(addedIds);
- const allUpdated = await getTransactionsByIds(updatedIds);
- const allDeleted = await getTransactionsByIds(deletedIds);
+ //
+ // One read for all of them: on the web backend every query is a
+ // separate lock/commit cycle against IndexedDB
+ const changedTransactions = await getTransactionsByIds([
+ ...new Set([...addedIds, ...updatedIds, ...deletedIds]),
+ ]);
+ const changedById = new Map(
+ changedTransactions.map(transaction => [transaction.id, transaction]),
+ );
+ const pickTransactions = (ids: string[]) =>
+ [...new Set(ids)]
+ .map(id => changedById.get(id))
+ .filter((transaction): transaction is TransactionEntity =>
+ Boolean(transaction),
+ );
+ const allAdded = pickTransactions(addedIds);
+ const allUpdated = pickTransactions(updatedIds);
+ const allDeleted = pickTransactions(deletedIds);
// Post-processing phase: first do any updates to transfers.
// Transfers update the transactions and we need to return updates
diff --git a/upcoming-release-notes/batch-sync-writes.md b/upcoming-release-notes/batch-sync-writes.md
new file mode 100644
index 0000000000..c20ef662f1
--- /dev/null
+++ b/upcoming-release-notes/batch-sync-writes.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [MikesGlitch]
+---
+
+Speed up saving transaction edits, especially on large budgets in the browser