fix(db): PK reads refresh past the identity map; typed owned-lookup generics; e2e ORM module mirrors production config

This commit is contained in:
jubnl
2026-09-22 12:38:59 +02:00
parent c2da9d62f7
commit 4209343328
8 changed files with 247 additions and 38 deletions
@@ -11,13 +11,28 @@ export interface AppSettingsRow {
const _appSettingsRowKeys: AssertRowKeys<AppSettingsRow, AppSettings> = true;
export class AppSettingsRepository extends EntityRepository<AppSettings> {
/** `SELECT value FROM app_settings WHERE key = ?` */
/**
* `SELECT value FROM app_settings WHERE key = ?`
*
* `refresh: true` (Task 0 review, I1): this is a primary-key lookup, so
* without it MikroORM answers a repeat call from the identity map rather
* than re-querying — invisible to a raw/native write or `deleteValue` on
* the same key inside the same request, which is exactly the coexistence
* case this plan is built on (raw SQL and the ORM sharing one connection
* while callers convert one at a time). `refresh` keeps this a single
* query either way; only a stale identity-map hit is avoided.
*/
async getValue(key: string): Promise<string | null> {
const row = await this.findOne({ key }, { fields: ['value'] });
const row = await this.findOne({ key }, { fields: ['value'], refresh: true });
return row?.value ?? null;
}
/** `SELECT key, value FROM app_settings WHERE key IN (?, ?, ...)` */
/**
* `SELECT key, value FROM app_settings WHERE key IN (?, ?, ...)` — a
* NULL-valued row is silently dropped from the returned Map, matching the
* legacy callers, which never distinguished "row present with a NULL
* value" from "no row" (both read as absent).
*/
async getValues(keys: string[]): Promise<Map<string, string>> {
const rows = await this.find({ key: { $in: keys } });
const values = new Map<string, string>();
@@ -38,6 +53,15 @@ export class AppSettingsRepository extends EntityRepository<AppSettings> {
* with no other column whose reset by REPLACE could be observable, both
* spellings are exactly `em.upsert`'s job, with the sole unique field
* (`key`, the primary key) as the conflict target.
*
* The one difference from `INSERT OR REPLACE` — verified, unobservable
* here — is the row's implicit SQLite rowid: REPLACE deletes and
* reinserts (rowid moves), `em.upsert`'s `ON CONFLICT ... DO UPDATE`
* keeps the original row (rowid stays). `app_settings` has no `INTEGER
* PRIMARY KEY`, no `AUTOINCREMENT`, no trigger and no foreign key
* referencing it, so nothing here reads the rowid — but the next table
* converted off `INSERT OR REPLACE` that does have one of those needs its
* own check, not an assumption from this comment.
*/
async setValue(key: string, value: string): Promise<void> {
await this.upsert({ key, value }, { onConflictFields: ['key'], onConflictAction: 'merge' });
+14 -4
View File
@@ -9,14 +9,22 @@ import { EntityRepository } from '@mikro-orm/sql';
* name outside this union fails `tsc` rather than reaching a query.
*
* This repository is the union's source of truth; `instance-api-keys.ts`
* imports it rather than keeping its own copy (Task 5 wires that import).
* will import it rather than keeping its own copy (Task 5 wires that import
* — it still declares the identical union itself today).
*/
export type InstanceApiKeyName = 'maps_api_key' | 'unsplash_api_key' | 'amap_api_key';
export class UsersRepository extends EntityRepository<Users> {
/** `SELECT email FROM users WHERE id = ?` */
/**
* `SELECT email FROM users WHERE id = ?`
*
* `refresh: true` (Task 0 review, I1): a primary-key `findOne` is answered
* from the identity map on a repeat call, which would hide a raw/native
* `UPDATE users SET email = ...` on the same id inside the same request.
* `refresh` keeps this a single query and always sees the current row.
*/
async getEmail(userId: number): Promise<string | null> {
const row = await this.findOne({ id: userId }, { fields: ['email'] });
const row = await this.findOne({ id: userId }, { fields: ['email'], refresh: true });
return row?.email ?? null;
}
@@ -25,9 +33,11 @@ export class UsersRepository extends EntityRepository<Users> {
* `SELECT <name> FROM users WHERE id = ?`. `name` is the typed union above,
* not an interpolated column — MikroORM's `fields` option only accepts a
* real property of `Users`, so this can never select an arbitrary column.
*
* `refresh: true` for the same identity-map reason as `getEmail` above.
*/
async getApiKeyColumn(userId: number, name: InstanceApiKeyName): Promise<string | null> {
const row = await this.findOne({ id: userId }, { fields: [name] });
const row = await this.findOne({ id: userId }, { fields: [name], refresh: true });
return row ? (row[name] ?? null) : null;
}
}
@@ -1,4 +1,4 @@
import type { EntityRepository, FilterQuery, OrderDefinition } from '@mikro-orm/core';
import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from '@mikro-orm/core';
/**
* Shared lookup shapes for entities scoped to a user, some of which also
@@ -15,23 +15,35 @@ import type { EntityRepository, FilterQuery, OrderDefinition } from '@mikro-orm/
* = ?`), so it stays a plain `findOne({ id })` rather than either helper
* here; changing that would be a behaviour change, not a refactor.
*
* `ownerField`/`orderField` are taken as parameters (`keyof T`) rather than
* hard-coded so one helper serves every entity shaped this way; the `as
* FilterQuery<T>`/`as Record<string, 'asc'>` casts are the one place that
* type is asserted rather than inferred; the entity's own properties still
* decide, at the call site, which literal `ownerField`/`orderField` values
* are legal (`keyof T`).
* These helpers return live MikroORM entities, not rows — unlike every other
* repository method in this codebase (D4: "repositories return rows, never a
* live entity"). They are an internal building block for `CategoriesRepository`
* /`TagsRepository`, which stay the actual public API and must run the result
* through `toRow` before it leaves the repository.
*
* Typing (Task 0 review, I2): `T extends { id: unknown }` and `K extends
* keyof T` tie `ownerField` to a real property of `T` and `ownerId` to
* `FilterValue<T[K]>` — the same value shape MikroORM's own `FilterObject`
* accepts for that property (`T[K]` directly is too strict for a relation
* property: `Tags['user']` is `Ref<Users>`, but every call site here filters
* it with the raw foreign-key id, which `FilterValue` allows and a bare
* `T[K]` would not). `id`/`ownerId` are no longer `unknown` — a call for an
* entity without an `id` column, or with an `ownerId` of the wrong shape, now
* fails `tsc` instead of only failing at runtime; the `as FilterQuery<T>`/
* `as OrderDefinition<T>` casts are the one place the shape is still
* asserted rather than inferred, exactly at the computed-property-key
* boundary TypeScript cannot check on its own.
*/
/**
* List every row owned by `ownerId`, ordered by `orderField` ascending:
* `SELECT * FROM <table> WHERE <ownerField> = ? ORDER BY <orderField> ASC`.
*/
export async function listForOwner<T extends object>(
export async function listForOwner<T extends { id: unknown }, K extends keyof T, OF extends keyof T>(
repo: EntityRepository<T>,
ownerField: keyof T,
ownerId: unknown,
orderField: keyof T,
ownerField: K,
ownerId: FilterValue<T[K]>,
orderField: OF,
): Promise<T[]> {
return repo.find({ [ownerField]: ownerId } as FilterQuery<T>, {
orderBy: { [orderField]: 'asc' } as OrderDefinition<T>,
@@ -42,11 +54,11 @@ export async function listForOwner<T extends object>(
* Find one row by id, strictly scoped to an owner:
* `SELECT * FROM <table> WHERE id = ? AND <ownerField> = ?`.
*/
export async function findOwnedByUser<T extends object>(
export async function findOwnedByUser<T extends { id: unknown }, K extends keyof T>(
repo: EntityRepository<T>,
id: unknown,
ownerField: keyof T,
ownerId: unknown,
id: T['id'],
ownerField: K,
ownerId: FilterValue<T[K]>,
): Promise<T | null> {
return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery<T>);
}
@@ -57,11 +69,11 @@ export async function findOwnedByUser<T extends object>(
* `SELECT * FROM <table> WHERE id = ? AND (<ownerField> = ? OR <ownerField>
* IS NULL)`.
*/
export async function findOwnedOrGlobal<T extends object>(
export async function findOwnedOrGlobal<T extends { id: unknown }, K extends keyof T>(
repo: EntityRepository<T>,
id: unknown,
ownerField: keyof T,
ownerId: unknown,
id: T['id'],
ownerField: K,
ownerId: FilterValue<T[K]>,
): Promise<T | null> {
return repo.findOne({
id,
+7 -1
View File
@@ -169,7 +169,13 @@ export class SettingsService {
if (ENCRYPTED_SETTING_KEYS.has(settingKey)) {
defaults[settingKey] = row.value ? (decrypt_api_key(row.value) ?? '') : '';
} else {
defaults[settingKey] = parseValue(row.value ?? '');
// Parity with the legacy `parseValue(row.value)` call this replaced:
// `JSON.parse(null)` coerces its argument to the string "null" and
// returns the JS value `null`, so a NULL-valued row parsed to `null`.
// `row.value ?? ''` would instead call `parseValue('')`, which throws
// inside JSON.parse and falls back to the empty string — a silent
// divergence for a case parseValue never actually threw on before.
defaults[settingKey] = row.value === null ? null : parseValue(row.value);
}
}
return defaults;