Skip to content

A local-first personal finance app

[TypeScript] Make `db.runQuery` generic to make it easy to type DB query results (#4247)

Joel Jeremy Marquezcab24df3cecf
diff --git a/packages/loot-core/src/server/budget/base.ts b/packages/loot-core/src/server/budget/base.ts
index 56505d8d6d..a3fcb075e1 100644
--- a/packages/loot-core/src/server/budget/base.ts
+++ b/packages/loot-core/src/server/budget/base.ts
@@ -41,7 +41,7 @@ function createCategory(cat, sheetName, prevSheetName, start, end) {
initialValue: 0,
run: () => {
// Making this sync is faster!
- const rows = db.runQuery(
+ const rows = db.runQuery<{ amount: number }>(
`SELECT SUM(amount) as amount FROM v_transactions_internal_alive t
LEFT JOIN accounts a ON a.id = t.account
WHERE t.date >= ${start} AND t.date <= ${end}
@@ -86,7 +86,7 @@ function createCategoryGroup(group, sheetName) {
function handleAccountChange(months, oldValue, newValue) {
if (!oldValue || oldValue.offbudget !== newValue.offbudget) {
- const rows = db.runQuery(
+ const rows = db.runQuery<Pick<db.DbTransaction, 'category'>>(
`
SELECT DISTINCT(category) as category FROM transactions
WHERE acct = ?
diff --git a/packages/loot-core/src/server/budget/statements.ts b/packages/loot-core/src/server/budget/statements.ts
index 43a1af7d94..13e4707a5f 100644
--- a/packages/loot-core/src/server/budget/statements.ts
+++ b/packages/loot-core/src/server/budget/statements.ts
@@ -1,5 +1,5 @@
import * as db from '../db';
-import { Schedule } from '../db/types';
+import { DbSchedule } from '../db';
import { GOAL_PREFIX, TEMPLATE_PREFIX } from './template-notes';
@@ -41,7 +41,7 @@ export async function getCategoriesWithTemplateNotes(): Promise<
);
}
-export async function getActiveSchedules(): Promise<Schedule[]> {
+export async function getActiveSchedules(): Promise<DbSchedule[]> {
return await db.all(
'SELECT id, rule, active, completed, posts_transaction, tombstone, name from schedules WHERE name NOT NULL AND tombstone = 0',
);
diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.ts
index 2621b03273..81709dc63e 100644
--- a/packages/loot-core/src/server/budget/template-notes.test.ts
+++ b/packages/loot-core/src/server/budget/template-notes.test.ts
@@ -1,5 +1,4 @@
import * as db from '../db';
-import { Schedule } from '../db/types';
import {
CategoryWithTemplateNote,
@@ -20,7 +19,7 @@ function mockGetTemplateNotesForCategories(
);
}
-function mockGetActiveSchedules(schedules: Schedule[]) {
+function mockGetActiveSchedules(schedules: db.DbSchedule[]) {
(getActiveSchedules as jest.Mock).mockResolvedValue(schedules);
}
@@ -277,7 +276,7 @@ describe('checkTemplates', () => {
);
});
-function mockSchedules(): Schedule[] {
+function mockSchedules(): db.DbSchedule[] {
return [
{
id: 'mock-schedule-1',
diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.ts
index dc324fca85..12e80e07a1 100644
--- a/packages/loot-core/src/server/db/index.ts
+++ b/packages/loot-core/src/server/db/index.ts
@@ -15,11 +15,7 @@ import * as fs from '../../platform/server/fs';
import * as sqlite from '../../platform/server/sqlite';
import * as monthUtils from '../../shared/months';
import { groupById } from '../../shared/util';
-import {
- CategoryEntity,
- CategoryGroupEntity,
- PayeeEntity,
-} from '../../types/models';
+import { CategoryEntity, CategoryGroupEntity } from '../../types/models';
import {
schema,
schemaConfig,
@@ -37,6 +33,16 @@ import {
import { sendMessages, batchMessages } from '../sync';
import { shoveSortOrders, SORT_INCREMENT } from './sort';
+import {
+ DbAccount,
+ DbCategory,
+ DbCategoryGroup,
+ DbPayee,
+ DbTransaction,
+ DbViewTransaction,
+} from './types';
+
+export * from './types';
export { toDateRepr, fromDateRepr } from '../models';
@@ -100,17 +106,24 @@ export function runQuery(
sql: string,
params?: Array<string | number>,
fetchAll?: false,
-);
-export function runQuery(
+): { changes: unknown };
+
+export function runQuery<T>(
sql: string,
params: Array<string | number> | undefined,
fetchAll: true,
-);
-export function runQuery(sql, params, fetchAll) {
- // const unrecord = perf.record('sqlite');
- const result = sqlite.runQuery(db, sql, params, fetchAll);
- // unrecord();
- return result;
+): T[];
+
+export function runQuery<T>(
+ sql: string,
+ params: (string | number)[],
+ fetchAll: boolean,
+) {
+ if (fetchAll) {
+ return sqlite.runQuery<T>(db, sql, params, true);
+ } else {
+ return sqlite.runQuery(db, sql, params, false);
+ }
}
export function execQuery(sql: string) {
@@ -147,19 +160,28 @@ export function asyncTransaction(fn: () => Promise<void>) {
// async. We return a promise here until we've audited all the code to
// make sure nothing calls `.then` on this.
export async function all(sql, params?: (string | number)[]) {
- return runQuery(sql, params, true);
+ // TODO: In the next phase, we will make this function generic
+ // and pass the type of the return type to `runQuery`.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return runQuery(sql, params, true) as any[];
}
export async function first(sql, params?: (string | number)[]) {
const arr = await runQuery(sql, params, true);
- return arr.length === 0 ? null : arr[0];
+ // TODO: In the next phase, we will make this function generic
+ // and pass the type of the return type to `runQuery`.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return arr.length === 0 ? null : (arr[0] as any);
}
// The underlying sql system is now sync, but we can't update `first` yet
// without auditing all uses of it
export function firstSync(sql, params?: (string | number)[]) {
const arr = runQuery(sql, params, true);
- return arr.length === 0 ? null : arr[0];
+ // TODO: In the next phase, we will make this function generic
+ // and pass the type of the return type to `runQuery`.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return arr.length === 0 ? null : (arr[0] as any);
}
// This function is marked as async because `runQuery` is no longer
@@ -175,7 +197,10 @@ export async function select(table, id) {
[id],
true,
);
- return rows[0];
+ // TODO: In the next phase, we will make this function generic
+ // and pass the type of the return type to `runQuery`.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return rows[0] as any;
}
export async function update(table, params) {
@@ -252,9 +277,12 @@ export async function deleteAll(table: string) {
export async function selectWithSchema(table, sql, params) {
const rows = await runQuery(sql, params, true);
- return rows
+ const convertedRows = rows
.map(row => convertFromSelect(schema, schemaConfig, table, row))
.filter(Boolean);
+ // TODO: Make convertFromSelect generic so we don't need this cast
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return convertedRows as any[];
}
export async function selectFirstWithSchema(table, sql, params) {
@@ -282,16 +310,18 @@ export function updateWithSchema(table, fields) {
// Data-specific functions. Ideally this would be split up into
// different files
+// TODO: Fix return type. This should returns a DbCategory[].
export async function getCategories(
- ids?: Array<CategoryEntity['id']>,
+ ids?: Array<DbCategory['id']>,
): Promise<CategoryEntity[]> {
const whereIn = ids ? `c.id IN (${toSqlQueryParameters(ids)}) AND` : '';
const query = `SELECT c.* FROM categories c WHERE ${whereIn} c.tombstone = 0 ORDER BY c.sort_order, c.id`;
return ids ? await all(query, [...ids]) : await all(query);
}
+// TODO: Fix return type. This should returns a [DbCategoryGroup, ...DbCategory].
export async function getCategoriesGrouped(
- ids?: Array<CategoryGroupEntity['id']>,
+ ids?: Array<DbCategoryGroup['id']>,
): Promise<Array<CategoryGroupEntity>> {
const categoryGroupWhereIn = ids
? `cg.id IN (${toSqlQueryParameters(ids)}) AND`
@@ -432,7 +462,11 @@ export function updateCategory(category) {
return update('categories', category);
}
-export async function moveCategory(id, groupId, targetId?: string) {
+export async function moveCategory(
+ id: DbCategory['id'],
+ groupId: DbCategoryGroup['id'],
+ targetId?: DbCategory['id'],
+) {
if (!groupId) {
throw new Error('moveCategory: groupId is required');
}
@@ -449,7 +483,10 @@ export async function moveCategory(id, groupId, targetId?: string) {
await update('categories', { id, sort_order, cat_group: groupId });
}
-export async function deleteCategory(category, transferId?: string) {
+export async function deleteCategory(
+ category: Pick<DbCategory, 'id'>,
+ transferId?: DbCategory['id'],
+) {
if (transferId) {
// We need to update all the deleted categories that currently
// point to the one we're about to delete so they all are
@@ -469,11 +506,11 @@ export async function deleteCategory(category, transferId?: string) {
return delete_('categories', category.id);
}
-export async function getPayee(id) {
+export async function getPayee(id: DbPayee['id']) {
return first(`SELECT * FROM payees WHERE id = ?`, [id]);
}
-export async function getAccount(id) {
+export async function getAccount(id: DbAccount['id']) {
return first(`SELECT * FROM accounts WHERE id = ?`, [id]);
}
@@ -487,7 +524,7 @@ export async function insertPayee(payee) {
return id;
}
-export async function deletePayee(payee) {
+export async function deletePayee(payee: Pick<DbPayee, 'id'>) {
const { transfer_acct } = await first('SELECT * FROM payees WHERE id = ?', [
payee.id,
]);
@@ -506,7 +543,7 @@ export async function deletePayee(payee) {
return delete_('payees', payee.id);
}
-export async function deleteTransferPayee(payee) {
+export async function deleteTransferPayee(payee: Pick<DbPayee, 'id'>) {
// This allows deleting transfer payees
return delete_('payees', payee.id);
}
@@ -516,9 +553,12 @@ export function updatePayee(payee) {
return update('payees', payee);
}
-export async function mergePayees(target: string, ids: string[]) {
+export async function mergePayees(
+ target: DbPayee['id'],
+ ids: Array<DbPayee['id']>,
+) {
// Load in payees so we can check some stuff
- const dbPayees: PayeeEntity[] = await all('SELECT * FROM payees');
+ const dbPayees: DbPayee[] = await all('SELECT * FROM payees');
const payees = groupById(dbPayees);
// Filter out any transfer payees
@@ -613,7 +653,7 @@ export async function getOrphanedPayees() {
return rows.map(row => row.id);
}
-export async function getPayeeByName(name) {
+export async function getPayeeByName(name: DbPayee['name']) {
return first(
`SELECT * FROM payees WHERE UNICODE_LOWER(name) = ? AND tombstone = 0`,
[name.toLowerCase()],
@@ -632,7 +672,7 @@ export function getAccounts() {
export async function insertAccount(account) {
const accounts = await all(
'SELECT * FROM accounts WHERE offbudget = ? ORDER BY sort_order, name',
- [account.offbudget != null ? account.offbudget : 0],
+ [account.offbudget ? 1 : 0],
);
// Don't pass a target in, it will default to appending at the end
@@ -651,7 +691,10 @@ export function deleteAccount(account) {
return delete_('accounts', account.id);
}
-export async function moveAccount(id, targetId) {
+export async function moveAccount(
+ id: DbAccount['id'],
+ targetId: DbAccount['id'],
+) {
const account = await first('SELECT * FROM accounts WHERE id = ?', [id]);
let accounts;
if (account.closed) {
@@ -661,7 +704,7 @@ export async function moveAccount(id, targetId) {
} else {
accounts = await all(
`SELECT id, sort_order FROM accounts WHERE tombstone = 0 AND offbudget = ? ORDER BY sort_order, name`,
- [account.offbudget],
+ [account.offbudget ? 1 : 0],
);
}
@@ -674,7 +717,7 @@ export async function moveAccount(id, targetId) {
});
}
-export async function getTransaction(id) {
+export async function getTransaction(id: DbViewTransaction['id']) {
const rows = await selectWithSchema(
'transactions',
'SELECT * FROM v_transactions WHERE id = ?',
@@ -683,7 +726,7 @@ export async function getTransaction(id) {
return rows[0];
}
-export async function getTransactions(accountId) {
+export async function getTransactions(accountId: DbTransaction['acct']) {
if (arguments.length > 1) {
throw new Error(
'`getTransactions` was given a second argument, it now only takes a single argument `accountId`',
diff --git a/packages/loot-core/src/server/db/mappings.ts b/packages/loot-core/src/server/db/mappings.ts
index 81b0c280db..f7423cab5f 100644
--- a/packages/loot-core/src/server/db/mappings.ts
+++ b/packages/loot-core/src/server/db/mappings.ts
@@ -22,14 +22,12 @@ let unlistenSync;
export async function loadMappings() {
// The mappings are separated into tables specific to the type of
// data. But you know, we really could keep a global mapping table.
- const categories = (await db.all('SELECT * FROM category_mapping')).map(r => [
- r.id,
- r.transferId,
- ]);
- const payees = (await db.all('SELECT * FROM payee_mapping')).map(r => [
- r.id,
- r.targetId,
- ]);
+ const categories = (await db.all('SELECT * FROM category_mapping')).map(
+ r => [r.id, r.transferId] as const,
+ );
+ const payees = (await db.all('SELECT * FROM payee_mapping')).map(
+ r => [r.id, r.targetId] as const,
+ );
// All ids are unique, so we can just keep a global table of mappings
allMappings = new Map(categories.concat(payees));
diff --git a/packages/loot-core/src/server/db/types.d.ts b/packages/loot-core/src/server/db/types.d.ts
deleted file mode 100644
index b6fdd94ec3..0000000000
--- a/packages/loot-core/src/server/db/types.d.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export type Schedule = {
- id: string;
- rule: string;
- active: number;
- completed: number;
- posts_transaction: number;
- tombstone: number;
- name: string | null;
-};
diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.ts
new file mode 100644
index 0000000000..c6accb44f0
--- /dev/null
+++ b/packages/loot-core/src/server/db/types/index.ts
@@ -0,0 +1,315 @@
+// These are the types that exactly match the database schema.
+// The `Entity` types e.g. `TransactionEntity`, `AccountEntity`, etc
+// are specific to the AQL query framework and does not necessarily
+// match the actual database schema.
+
+type JsonString = string;
+
+export type DbAccount = {
+ id: string;
+ name: string;
+ offbudget: 1 | 0;
+ closed: 1 | 0;
+ tombstone: 1 | 0;
+ sort_order: number;
+ account_id?: string | null;
+ balance_current?: number | null;
+ balance_available?: number | null;
+ balance_limit?: number | null;
+ mask?: string | null;
+ official_name?: string | null;
+ type?: string | null;
+ subtype?: string | null;
+ bank?: string | null;
+ account_sync_source?: 'simpleFin' | 'goCardless' | null;
+};
+
+export type DbBank = {
+ id: string;
+ bank_id: string;
+ name: string;
+ tombstone: 1 | 0;
+};
+
+export type DbCategory = {
+ id: string;
+ name: string;
+ is_income: 1 | 0;
+ cat_group: DbCategoryGroup['id'];
+ sort_order: number;
+ hidden: 1 | 0;
+ goal_def?: JsonString | null;
+ tombstone: 1 | 0;
+};
+
+export type DbCategoryGroup = {
+ id: string;
+ name: string;
+ is_income: 1 | 0;
+ sort_order: number;
+ hidden: 1 | 0;
+ tombstone: 1 | 0;
+};
+
+export type DbCategoryMapping = {
+ id: DbCategory['id'];
+ transferId: DbCategory['id'];
+};
+
+export type DbKvCache = {
+ key: string;
+ value: string;
+};
+
+export type DbKvCacheKey = {
+ id: number;
+ key: number;
+};
+
+export type DbClockMessage = {
+ id: string;
+ clock: string;
+};
+
+export type DbCrdtMessage = {
+ id: string;
+ timestamp: string;
+ dataset: string;
+ row: string;
+ column: string;
+ value: Uint8Array;
+};
+
+export type DbNote = {
+ id: string;
+ note: string;
+};
+
+export type DbPayeeMapping = {
+ id: DbPayee['id'];
+ targetId: DbPayee['id'];
+};
+
+export type DbPayee = {
+ id: string;
+ name: string;
+ transfer_acct?: DbAccount['id'] | null;
+ favorite: 1 | 0;
+ learn_categories: 1 | 0;
+ tombstone: 1 | 0;
+ // Unused in the codebase
+ category?: string | null;
+};
+
+export type DbRule = {
+ id: string;
+ stage: string;
+ conditions: JsonString;
+ actions: JsonString;
+ tombstone: 1 | 0;
+ conditions_op: string;
+};
+
+export type DbSchedule = {
+ id: string;
+ name: string;
+ rule: DbRule['id'];
+ active: 1 | 0;
+ completed: 1 | 0;
+ posts_transaction: 1 | 0;
+ tombstone: 1 | 0;
+};
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+type DbScheduleJsonPath = {
+ schedule_id: DbSchedule['id'];
+ payee: string;
+ account: string;
+ amount: string;
+ date: string;
+};
+
+export type DbScheduleNextDate = {
+ id: string;
+ schedule_id: DbSchedule['id'];
+ local_next_date: number;
+ local_next_date_ts: number;
+ base_next_date: number;
+ base_next_date_ts: number;
+};
+
+// This is unused in the codebase.
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+type DbPendingTransaction = {
+ id: string;
+ acct: number;
+ amount: number;
+ description: string;
+ date: string;
+};
+
+export type DbTransaction = {
+ id: string;
+ isParent: 1 | 0;
+ isChild: 1 | 0;
+ date: number;
+ acct: DbAccount['id'];
+ amount: number;
+ sort_order: number;
+ parent_id?: DbTransaction['id'] | null;
+ category?: DbCategory['id'] | null;
+ description?: string | null;
+ notes?: string | null;
+ financial_id?: string | null;
+ error?: string | null;
+ imported_description?: string | null;
+ transferred_id?: DbTransaction['id'] | null;
+ schedule?: DbSchedule['id'] | null;
+ starting_balance_flag: 1 | 0;
+ tombstone: 1 | 0;
+ cleared: 1 | 0;
+ reconciled: 1 | 0;
+ // Unused in the codebase
+ pending?: 1 | 0 | null;
+ location?: string | null;
+ type?: string | null;
+};
+
+export type DbReflectBudget = {
+ id: string;
+ month: number;
+ category: string;
+ amount: number;
+ carryover: number;
+ goal: number;
+ long_goal: number;
+};
+
+export type DbZeroBudgetMonth = {
+ id: string;
+ buffered: number;
+};
+
+export type DbZeroBudget = {
+ id: string;
+ month: number;
+ category: string;
+ amount: number;
+ carryover: number;
+ goal: number;
+ long_goal: number;
+};
+
+export type DbTransactionFilter = {
+ id: string;
+ name: string;
+ conditions: JsonString;
+ conditions_op: string;
+ tombstone: 1 | 0;
+};
+
+export type DbPreference = {
+ id: string;
+ value: string;
+};
+
+export type DbCustomReport = {
+ id: string;
+ name: string;
+ start_date: string;
+ end_date: string;
+ date_static: number;
+ date_range: string;
+ mode: string;
+ group_by: string;
+ balance_type: string;
+ show_empty: 1 | 0;
+ show_offbudget: 1 | 0;
+ show_hidden: 1 | 0;
+ show_uncateogorized: 1 | 0;
+ selected_categories: string;
+ graph_type: string;
+ conditions: JsonString;
+ conditions_op: string;
+ metadata: JsonString;
+ interval: string;
+ color_scheme: string;
+ include_current: 1 | 0;
+ sort_by: string;
+ tombstone: 1 | 0;
+};
+
+export type DbDashboard = {
+ id: string;
+ type: string;
+ width: number;
+ height: number;
+ x: number;
+ y: number;
+ meta: JsonString;
+ tombstone: 1 | 0;
+};
+
+export type DbViewTransactionInternal = {
+ id: DbTransaction['id'];
+ is_parent: DbTransaction['isParent'];
+ is_child: DbTransaction['isChild'];
+ date: DbTransaction['date'];
+ account: DbAccount['id'];
+ amount: DbTransaction['amount'];
+ parent_id: DbTransaction['parent_id'] | null;
+ category: DbCategory['id'] | null;
+ payee: DbPayee['id'] | null;
+ notes: DbTransaction['notes'] | null;
+ imported_id: DbTransaction['financial_id'] | null;
+ error: DbTransaction['error'] | null;
+ imported_payee: DbTransaction['imported_description'] | null;
+ starting_balance_flag: DbTransaction['starting_balance_flag'] | null;
+ transfer_id: DbTransaction['transferred_id'] | null;
+ schedule: DbSchedule['id'] | null;
+ sort_order: DbTransaction['sort_order'];
+ cleared: DbTransaction['cleared'];
+ tombstone: DbTransaction['tombstone'];
+ reconciled: DbTransaction['reconciled'];
+};
+
+export type DbViewTransactionInternalAlive = DbViewTransactionInternal;
+export type DbViewTransaction = DbViewTransactionInternalAlive;
+
+export type DbViewCategory = {
+ id: DbCategory['id'];
+ name: DbCategory['name'];
+ is_income: DbCategory['is_income'];
+ hidden: DbCategory['hidden'];
+ group: DbCategoryGroup['id'];
+ sort_order: DbCategory['sort_order'];
+ tombstone: DbCategory['tombstone'];
+};
+
+export type DbViewPayee = {
+ id: DbPayee['id'];
+ name: DbAccount['name'] | DbPayee['name'];
+ transfer_acct: DbPayee['transfer_acct'];
+ tombstone: DbPayee['tombstone'];
+};
+
+export type DbViewSchedule = {
+ id: DbSchedule['id'];
+ name: DbSchedule['name'];
+ rule: DbSchedule['rule'];
+ next_date:
+ | DbScheduleNextDate['local_next_date_ts']
+ | DbScheduleNextDate['local_next_date']
+ | DbScheduleNextDate['base_next_date'];
+ active: DbSchedule['active'];
+ completed: DbSchedule['completed'];
+ posts_transaction: DbSchedule['posts_transaction'];
+ tombstone: DbSchedule['tombstone'];
+ _payee: DbPayeeMapping['targetId'];
+ _account: DbAccount['id'];
+ _amount: number;
+ _amountOp: string;
+ _date: JsonString;
+ _conditions: JsonString;
+ _actions: JsonString;
+};
diff --git a/packages/loot-core/src/server/main.ts b/packages/loot-core/src/server/main.ts
index d57f94dcfe..c7d866a921 100644
--- a/packages/loot-core/src/server/main.ts
+++ b/packages/loot-core/src/server/main.ts
@@ -420,7 +420,7 @@ handlers['category-group-delete'] = mutator(async function ({
});
handlers['must-category-transfer'] = async function ({ id }) {
- const res = await db.runQuery(
+ const res = await db.runQuery<{ count: number }>(
`SELECT count(t.id) as count FROM transactions t
LEFT JOIN category_mapping cm ON cm.id = t.category
WHERE cm.transferId = ? AND t.tombstone = 0`,
@@ -778,7 +778,9 @@ handlers['account-close'] = mutator(async function ({
if (numTransactions === 0) {
await db.deleteAccount({ id });
} else if (forced) {
- const rows = await db.runQuery(
+ const rows = await db.runQuery<
+ Pick<db.DbViewTransaction, 'id' | 'transfer_id'>
+ >(
'SELECT id, transfer_id FROM v_transactions WHERE account = ?',
[id],
true,
@@ -1105,7 +1107,9 @@ handlers['accounts-bank-sync'] = async function ({ ids = [] }) {
'user-key',
]);
- const accounts = await db.runQuery(
+ const accounts = await db.runQuery<
+ db.DbAccount & { bankId: db.DbBank['bank_id'] }
+ >(
`
SELECT a.*, b.bank_id as bankId
FROM accounts a
@@ -1164,7 +1168,9 @@ handlers['accounts-bank-sync'] = async function ({ ids = [] }) {
};
handlers['simplefin-batch-sync'] = async function ({ ids = [] }) {
- const accounts = await db.runQuery(
+ const accounts = await db.runQuery<
+ db.DbAccount & { bankId: db.DbBank['bank_id'] }
+ >(
`SELECT a.*, b.bank_id as bankId FROM accounts a
LEFT JOIN banks b ON a.bank = b.id
WHERE
@@ -1223,7 +1229,7 @@ handlers['simplefin-batch-sync'] = async function ({ ids = [] }) {
const errors = [];
for (const account of accounts) {
retVal.push({
- accountId: account.accountId,
+ accountId: account.id,
res: {
errors,
newTransactions: [],
diff --git a/packages/loot-core/src/server/sync/index.ts b/packages/loot-core/src/server/sync/index.ts
index 7c4b03adb5..5888fb768a 100644
--- a/packages/loot-core/src/server/sync/index.ts
+++ b/packages/loot-core/src/server/sync/index.ts
@@ -198,7 +198,7 @@ async function compareMessages(messages: Message[]): Promise<Message[]> {
const { dataset, row, column, timestamp } = message;
const timestampStr = timestamp.toString();
- const res = db.runQuery(
+ const res = db.runQuery<Pick<db.DbCrdtMessage, 'timestamp'>>(
db.cache(
'SELECT timestamp FROM messages_crdt WHERE dataset = ? AND row = ? AND column = ? AND timestamp >= ?',
),
diff --git a/packages/loot-core/src/server/sync/migrate.test.ts b/packages/loot-core/src/server/sync/migrate.test.ts
index 6959766b23..7fec886fcd 100644
--- a/packages/loot-core/src/server/sync/migrate.test.ts
+++ b/packages/loot-core/src/server/sync/migrate.test.ts
@@ -79,7 +79,11 @@ describe('sync migrations', () => {
tracer.expectNow('applied', ['trans1/child1']);
await tracer.expectWait('applied', ['trans1/child1']);
- const transactions = db.runQuery('SELECT * FROM transactions', [], true);
+ const transactions = db.runQuery<db.DbTransaction>(
+ 'SELECT * FROM transactions',
+ [],
+ true,
+ );
expect(transactions.length).toBe(1);
expect(transactions[0].parent_id).toBe('trans1');
diff --git a/packages/loot-core/src/server/tools/app.ts b/packages/loot-core/src/server/tools/app.ts
index bc6b0321c3..ceb535c498 100644
--- a/packages/loot-core/src/server/tools/app.ts
+++ b/packages/loot-core/src/server/tools/app.ts
@@ -52,7 +52,7 @@ app.method('tools/fix-split-transactions', async () => {
`);
await runMutator(async () => {
- const updated = deletedRows.map(row => ({ id: row.id, tombstone: 1 }));
+ const updated = deletedRows.map(row => ({ id: row.id, tombstone: true }));
await batchUpdateTransactions({ updated });
});
diff --git a/upcoming-release-notes/4247.md b/upcoming-release-notes/4247.md
new file mode 100644
index 0000000000..ca01ecc5b5
--- /dev/null
+++ b/upcoming-release-notes/4247.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [joel-jeremy]
+---
+
+[TypeScript] Make `runQuery` generic to make it easy to type DB query results.
\ No newline at end of file