refactor(categories, tags): repositories replace raw SQL

This commit is contained in:
jubnl
2026-09-22 13:54:13 +02:00
parent e9391a9ae1
commit aa1067035f
14 changed files with 798 additions and 208 deletions
@@ -1,4 +1,104 @@
import type { Categories } from '../entities/Categories.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { EntityRepository } from '@mikro-orm/sql';
export class CategoriesRepository extends EntityRepository<Categories> {}
/** A `categories` row as the API emits it. */
export interface CategoryRow {
id: number;
name: string;
color: string | null;
icon: string | null;
user_id: number | null;
created_at: string | null;
}
const _categoryRowKeys: AssertRowKeys<CategoryRow, Categories> = true;
export class CategoriesRepository extends EntityRepository<Categories> {
/** `SELECT * FROM categories ORDER BY name ASC` */
async list(): Promise<CategoryRow[]> {
const categories = await this.find({}, { orderBy: { name: 'asc' } });
return categories.map((category) => toRow(category) as CategoryRow);
}
/**
* `SELECT * FROM categories WHERE id = ?` — no owner filter. `user_id`
* being nullable makes a row *look* ownable, but this legacy statement
* never scoped by it: any id answers regardless of who created the row.
* Plain PK `findOne`, not `findOwnedOrGlobal` — that helper had no caller
* across categories or tags (neither site actually filters "owner or
* global") and was deleted rather than kept as dead code (Task 0
* re-review, R6; see `_shared/owned-lookup.ts`'s docstring).
*
* `refresh: true` (Task 0 review, I1 — the ruling every Plan 3 repository
* follows for a PK read). For this unrestricted (no `fields` option)
* findOne, MikroORM already re-queries and merges fresh data on every call
* regardless of `refresh` — its identity-map-skip optimisation only
* engages together with a `fields` restriction (the case
* `AppSettingsRepository.getValue` actually needed it for). `refresh`
* stays on this read to match the blanket ruling and to stay correct if a
* future caller adds `fields` here.
*/
async findById(id: number): Promise<CategoryRow | null> {
const category = await this.findOne({ id }, { refresh: true });
return category ? (toRow(category) as CategoryRow) : null;
}
/**
* The column set of the legacy INSERT:
* `INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)`.
* The `#6366f1`/`📍` defaulting stays in `CategoriesService` (D4's defaults
* rule) — this writes exactly what it is given.
*
* Named `createCategory`, not `create`: `EntityRepository#create` is a
* synchronous, non-persisting factory with an incompatible signature —
* shadowing it would fail to compile, the same collision Task 1 hit
* naming a method `insert`.
*
* Followed by `em.refresh` before `toRow` (D4's create rule): the insert's
* `RETURNING` clause already carries the generated `id` and the
* `defaultRaw` `created_at`, but calling `refresh` documents the
* one-extra-SELECT parity with the legacy statement pair (INSERT, then a
* re-select by id) rather than leaning on driver-specific RETURNING
* behaviour.
*/
async createCategory(input: { name: string; color: string; icon: string; user_id: number }): Promise<CategoryRow> {
const category = this.create({
name: input.name,
color: input.color,
icon: input.icon,
user: input.user_id,
});
await this.getEntityManager().persist(category).flush();
await this.getEntityManager().refresh(category);
return toRow(category) as CategoryRow;
}
/**
* `UPDATE categories SET name = COALESCE(?, name), color = COALESCE(?,
* color), icon = COALESCE(?, icon) WHERE id = ?`, re-selected. `assign`
* only touches the keys present on `changes` — the entity-API equivalent
* of `COALESCE` against a bind parameter — so the caller must omit a field
* entirely (not pass it as `undefined`) to leave it untouched, which is
* how `CategoriesService` reproduces the legacy `|| null`
* coalesce-away-empty-string behaviour. Returns `null` when no row matches
* `id`, mirroring the legacy re-select's `undefined`.
*
* No re-`findOne`/`refresh` after `flush`: `assign` already mutated the
* managed entity in place, and no column here is DB-computed on UPDATE
* (unlike `created_at` on insert), so the in-memory entity already holds
* exactly what was written.
*/
async patch(id: number, changes: { name?: string; color?: string; icon?: string }): Promise<CategoryRow | null> {
const category = await this.findOne({ id });
if (!category) return null;
this.assign(category, changes);
await this.getEntityManager().flush();
return toRow(category) as CategoryRow;
}
/** `DELETE FROM categories WHERE id = ?`. Returns the affected row count. */
async remove(id: number): Promise<number> {
return this.nativeDelete({ id });
}
}
+107 -1
View File
@@ -1,4 +1,110 @@
import type { Tags } from '../entities/Tags.entity';
import { findOwnedByUser, listForOwner } from './_shared/owned-lookup';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { EntityRepository } from '@mikro-orm/sql';
export class TagsRepository extends EntityRepository<Tags> {}
/** A `tags` row as the API emits it. */
export interface TagRow {
id: number;
user_id: number;
name: string;
color: string | null;
created_at: string | null;
}
const _tagRowKeys: AssertRowKeys<TagRow, Tags> = true;
export class TagsRepository extends EntityRepository<Tags> {
/**
* `SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC`, via the shared
* `listForOwner` helper (`tags.user_id` is `NOT NULL`, a strictly-owned
* entity — see `_shared/owned-lookup.ts`).
*/
async listByUser(userId: number): Promise<TagRow[]> {
const tags = await listForOwner<Tags, 'user', 'name'>(this, 'user', userId, 'name');
return tags.map((tag) => toRow(tag) as TagRow);
}
/**
* `SELECT * FROM tags WHERE id = ? AND user_id = ?`, via the shared
* `findOwnedByUser` helper — an ownership check (RPC/MCP writes re-verify
* with this before mutating), not a re-select following this repository's
* own write (`createTag`/`patch` refresh/return their own entity
* directly).
*
* `refresh: true` (Task 0 review, I1 — the ruling every Plan 3 repository
* follows for a PK-scoped read). For this unrestricted (no `fields`
* option) findOne, MikroORM already re-queries and merges fresh data on
* every call regardless of `refresh` — its identity-map-skip optimisation
* only engages together with a `fields` restriction (the case
* `AppSettingsRepository.getValue` actually needed it for). `refresh`
* stays on this read to match the blanket ruling and to stay correct if a
* future caller adds `fields` here. `findOwnedByUser`'s optional `options`
* parameter (added here, not duplicated — Task 0's helper had no reads
* that needed it yet) passes straight through to the underlying
* `findOne`.
*/
async findByIdAndUser(id: number, userId: number): Promise<TagRow | null> {
const tag = await findOwnedByUser<Tags, 'user'>(this, id, 'user', userId, { refresh: true });
return tag ? (toRow(tag) as TagRow) : null;
}
/**
* The column set of the legacy INSERT:
* `INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)`. The
* `#10b981` defaulting stays in `TagsService` (D4's defaults rule) — this
* writes exactly what it is given.
*
* Named `createTag`, not `create`: `EntityRepository#create` is a
* synchronous, non-persisting factory with an incompatible signature —
* shadowing it would fail to compile, the same collision Task 1 hit
* naming a method `insert`.
*
* Followed by `em.refresh` before `toRow` (D4's create rule), same as
* `CategoriesRepository.createCategory`.
*/
async createTag(input: { user_id: number; name: string; color: string }): Promise<TagRow> {
const tag = this.create({
user: input.user_id,
name: input.name,
color: input.color,
});
await this.getEntityManager().persist(tag).flush();
await this.getEntityManager().refresh(tag);
return toRow(tag) as TagRow;
}
/**
* `UPDATE tags SET name = COALESCE(?, name), color = COALESCE(?, color)
* WHERE id = ?`, re-selected — no `user_id` filter, matching the legacy
* statement exactly. `assign` only touches the keys present on `changes`
* (the entity-API equivalent of `COALESCE` against a bind parameter), so
* `TagsService` omits a field entirely, rather than passing it as
* `undefined`, to leave it untouched — reproducing the legacy `|| null`
* coalesce-away-empty-string behaviour. Returns `null` when no row matches
* `id`, mirroring the legacy re-select's `undefined`.
*
* No re-`findOne`/`refresh` after `flush`, same reasoning as
* `CategoriesRepository.patch`: `assign` already mutated the managed
* entity in place, and no column here is DB-computed on UPDATE.
*/
async patch(id: number, changes: { name?: string; color?: string }): Promise<TagRow | null> {
const tag = await this.findOne({ id });
if (!tag) return null;
this.assign(tag, changes);
await this.getEntityManager().flush();
return toRow(tag) as TagRow;
}
/** `DELETE FROM tags WHERE id = ?`. Returns the affected row count. */
async remove(id: number): Promise<number> {
return this.nativeDelete({ id });
}
// `loadForPlaces` (a batch `findByPlaceIds`-style tag loader) is reserved
// here for Plan 3c, which moves QueryHelpersService's tag batch loader
// (`query-helpers.service.ts:42`, `SELECT t.*, pt.place_id FROM tags t …`)
// onto TagsRepository (spec D4). Not implemented in Plan 3a Task 3 — no
// throwing stub, just this reservation, so `nest/places`'s later migration
// doesn't duplicate the method name.
}
@@ -1,25 +1,30 @@
import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from '@mikro-orm/core';
/**
* Shared lookup shapes for entities scoped to a user, some of which also
* allow a globally-shared row (a nullable owner column).
* Shared lookup shapes for entities scoped to a user.
*
* Built for `CategoriesRepository`/`TagsRepository` (Plan 3a Task 3), whose
* `list`/`getById`/`getByIdAndUser` methods are the same two query shapes
* over different tables: list-scoped-to-owner and find-one-by-id with an
* ownership check that is either strict (`tags`, whose `user_id` column is
* `NOT NULL`) or permissive (`categories`, whose `user_id` is nullable and
* `NULL` rows are read as globally shared). Task 3 decides, per call site,
* which shape a given legacy statement actually used — `categories.getById`
* today has no ownership filter at all (`SELECT * FROM categories WHERE id
* = ?`), so it stays a plain `findOne({ id })` rather than either helper
* here; changing that would be a behaviour change, not a refactor.
* Built for `TagsRepository` (Plan 3a Task 3): `listByUser`/`findByIdAndUser`
* are the same two query shapes every strictly-owned entity needs
* (`tags.user_id` is `NOT NULL`) — list-scoped-to-owner and find-one-by-id
* with an ownership check. `CategoriesRepository` uses neither: its legacy
* `list`/`getById` (`SELECT * FROM categories ORDER BY name ASC` / `SELECT *
* FROM categories WHERE id = ?`) have no owner filter at all, despite
* `categories.user_id` being nullable — changing that would be a behaviour
* change, not a refactor, so it stays plain `find`/`findOne`.
*
* A third helper, `findOwnedOrGlobal` (id match OR a NULL owner column —
* the shape `categories.getById` would need if it were ever scoped), was
* built alongside these two and then deleted: Task 0 re-review flagged that
* no categories or tags site actually filters "owner or global", so it had
* only test coverage and no real caller (R6 — "dead code is worse than a
* missing helper"). If a future entity needs that shape, recover it from
* git history rather than reintroducing it speculatively.
*
* 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.
* live entity"). They are an internal building block for `TagsRepository`,
* which stays the actual public API and must run the result through `toRow`
* before it leaves the repository.
*
* Call-site convention (Task 0 re-review): type arguments are ALWAYS explicit —
* inference from the repository argument alone resolves `T` to the
@@ -31,7 +36,7 @@ import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from
*
* listForOwner<Tags, 'user', 'name'>(tags, 'user', userId, 'name');
* findOwnedByUser<Tags, 'user'>(tags, id, 'user', userId);
* findOwnedOrGlobal<Categories, 'user'>(categories, id, 'user', userId);
* findOwnedByUser<Tags, 'user'>(tags, id, 'user', userId, { refresh: true });
*
* 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
@@ -65,30 +70,24 @@ export async function listForOwner<T extends { id: unknown }, K extends keyof T,
/**
* Find one row by id, strictly scoped to an owner:
* `SELECT * FROM <table> WHERE id = ? AND <ownerField> = ?`.
*
* `options.refresh` passes straight through to the underlying `findOne`
* (Task 0 review, I1's PK-read ruling: a caller whose read can follow a
* raw/native write on the same row within the same request sets it). For an
* unrestricted call like this one (no `fields` option), MikroORM already
* re-queries and merges fresh data on every call regardless of `refresh` —
* its identity-map-skip optimisation, and the staleness it can cause without
* `refresh`, only engages together with a `fields` restriction (the case
* `AppSettingsRepository.getValue` actually hit). `refresh` is still
* threaded through here to match the blanket ruling and to stay correct if a
* caller ever adds `fields` on top of it.
*/
export async function findOwnedByUser<T extends { id: unknown }, K extends keyof T>(
repo: EntityRepository<T>,
id: T['id'],
ownerField: K,
ownerId: FilterValue<T[K]>,
options?: { refresh?: boolean },
): Promise<T | null> {
return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery<T>);
}
/**
* Find one row by id, matching either a row `ownerId` owns or a row with no
* owner at all (a nullable owner column used for globally-shared rows):
* `SELECT * FROM <table> WHERE id = ? AND (<ownerField> = ? OR <ownerField>
* IS NULL)`.
*/
export async function findOwnedOrGlobal<T extends { id: unknown }, K extends keyof T>(
repo: EntityRepository<T>,
id: T['id'],
ownerField: K,
ownerId: FilterValue<T[K]>,
): Promise<T | null> {
return repo.findOne({
id,
$or: [{ [ownerField]: ownerId }, { [ownerField]: null }],
} as unknown as FilterQuery<T>);
return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery<T>, options);
}
@@ -1,6 +1,8 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { AppConfigModule } from '../app-config/app-config.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { Categories } from '../../db/entities/Categories.entity';
import { CategoriesController } from './categories.controller';
import { CategoriesMcp } from './categories.mcp';
import { CategoriesService } from './categories.service';
@@ -12,8 +14,11 @@ import { CategoriesRpc } from './categories.rpc';
// RuntimeEnvService and the users table rather than AuthService, which keeps
// the partial e2e TestingModule for this domain down to two tables.
// McpSharedModule is not @Global, and AppConfigModule is imported explicitly
// for the same reason budget/ does it.
imports: [McpSharedModule, AppConfigModule],
// for the same reason budget/ does it. MikroOrmModule.forFeature registers
// CategoriesRepository for @InjectRepository(Categories) in the service —
// the forFeature + @InjectRepository wiring pattern every domain copies
// (settings.module.ts's precedent comment).
imports: [McpSharedModule, AppConfigModule, MikroOrmModule.forFeature([Categories])],
controllers: [CategoriesController],
providers: [CategoriesService, CategoriesMcp, CategoriesRpc],
// For in-container consumers (CategoriesRpc).
@@ -1,57 +1,60 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import type { Category } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { Categories } from '../../db/entities/Categories.entity';
import type { CategoriesRepository } from '../../db/repositories/Categories.repository';
/**
* Categories domain service — owns the category SQL (moved 1:1 from the legacy
* services/categoryService.ts: identical statements, the #6366f1/📍 defaults
* and the COALESCE update semantics). All consumers are in-container now — the
* plugin RPC surface injects this class into CategoriesRpc.
* Categories domain service — owns the category business rules (moved off
* `DatabaseService`/raw SQL onto `CategoriesRepository`, Plan 3a Task 3): the
* `#6366f1`/`📍` defaults and the COALESCE-via-`assign` update semantics stay
* here, exactly as they did over raw SQL, while the SQL itself lives in the
* repository. All consumers are in-container — the plugin RPC surface
* injects this class into CategoriesRpc.
*/
@Injectable()
export class CategoriesService {
constructor(private readonly db: DatabaseService) {}
constructor(@InjectRepository(Categories) private readonly categories: CategoriesRepository) {}
// `CategoryRow`'s `color`/`icon`/`created_at` are nullable (the DB columns
// carry no NOT NULL constraint); the `@trek/shared` `Category` contract
// narrows them to non-nullable/optional. The legacy code trusted the same
// gap unchecked (`this.db.all<Category>(...)`'s generic parameter is not a
// runtime check either) — these casts keep that same trust boundary at the
// service layer instead of inside a raw-SQL call.
async list(): Promise<Category[]> {
return this.db.all<Category>('SELECT * FROM categories ORDER BY name ASC');
return (await this.categories.list()) as unknown as Category[];
}
async getById(id: string | number): Promise<Category | undefined> {
return this.db.get<Category>('SELECT * FROM categories WHERE id = ?', id);
const category = await this.categories.findById(Number(id));
return (category as unknown as Category | null) ?? undefined;
}
async create(userId: number, name: string, color?: string, icon?: string): Promise<Category> {
const result = this.db.run(
'INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)',
const category = await this.categories.createCategory({
name,
color || '#6366f1',
icon || '📍',
userId,
);
return this.db.get<Category>(
'SELECT * FROM categories WHERE id = ?',
result.lastInsertRowid,
) as Category;
color: color || '#6366f1',
icon: icon || '📍',
user_id: userId,
});
return category as unknown as Category;
}
async update(id: string | number, name?: string, color?: string, icon?: string): Promise<Category> {
this.db.run(
`
UPDATE categories SET
name = COALESCE(?, name),
color = COALESCE(?, color),
icon = COALESCE(?, icon)
WHERE id = ?
`,
name || null,
color || null,
icon || null,
id,
);
return this.db.get<Category>('SELECT * FROM categories WHERE id = ?', id) as Category;
// `|| null` fed a `COALESCE(?, col)` bind parameter in the legacy
// statement, so any falsy value (undefined or an empty string) meant
// "keep the existing column" — reproduced here by omitting the key from
// `changes` entirely, which is what `CategoriesRepository.patch`'s
// `assign` needs to leave that column untouched.
const changes: { name?: string; color?: string; icon?: string } = {};
if (name) changes.name = name;
if (color) changes.color = color;
if (icon) changes.icon = icon;
return (await this.categories.patch(Number(id), changes)) as unknown as Category;
}
async remove(id: string | number): Promise<void> {
this.db.run('DELETE FROM categories WHERE id = ?', id);
await this.categories.remove(Number(id));
}
}
+11 -2
View File
@@ -1,13 +1,22 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { TagsController } from './tags.controller';
import { TagsMcp } from './tags.mcp';
import { TagsRpc } from './tags.rpc';
import { TagsService } from './tags.service';
import { AuthModule } from '../auth/auth.module';
import { Tags } from '../../db/entities/Tags.entity';
/** Tags domain (L5 leaf module). Registered in AppModule. */
/**
* Tags domain (L5 leaf module). Registered in AppModule.
*
* MikroOrmModule.forFeature registers TagsRepository for
* @InjectRepository(Tags) in the service — the forFeature +
* @InjectRepository wiring pattern every domain copies (settings.module.ts's
* precedent comment).
*/
@Module({
imports: [AuthModule],
imports: [AuthModule, MikroOrmModule.forFeature([Tags])],
controllers: [TagsController],
// TagsRpc must stay in providers: the plugin RPC registry discovers marked
// PROVIDERS only, and a missing entry here would leave tags.* answering
+34 -22
View File
@@ -1,46 +1,58 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import type { Tag } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { Tags } from '../../db/entities/Tags.entity';
import type { TagsRepository } from '../../db/repositories/Tags.repository';
/**
* Tags domain service — owns the tag SQL (moved 1:1 from the legacy
* services/tagService.ts: identical statements, the #10b981 default and the
* COALESCE update semantics). All consumers are in-container now — the plugin
* RPC surface injects this class into TagsRpc.
* Tags domain service — owns the tag business rules (moved off
* `DatabaseService`/raw SQL onto `TagsRepository`, Plan 3a Task 3): the
* `#10b981` default and the COALESCE-via-`assign` update semantics stay
* here, exactly as they did over raw SQL, while the SQL itself lives in the
* repository. All consumers are in-container — the plugin RPC surface
* injects this class into TagsRpc.
*/
@Injectable()
export class TagsService {
constructor(private readonly db: DatabaseService) {}
constructor(@InjectRepository(Tags) private readonly tags: TagsRepository) {}
// `TagRow`'s `color`/`created_at` are nullable (the DB columns carry no NOT
// NULL constraint); the `@trek/shared` `Tag` contract narrows them to
// non-nullable/optional. The legacy code trusted the same gap unchecked
// (`this.db.all<Tag>(...)`'s generic parameter is not a runtime check
// either) — these casts keep that same trust boundary at the service layer
// instead of inside a raw-SQL call.
async list(userId: number): Promise<Tag[]> {
return this.db.all<Tag>('SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC', userId);
return (await this.tags.listByUser(userId)) as unknown as Tag[];
}
async getByIdAndUser(id: string | number, userId: number): Promise<Tag | undefined> {
return this.db.get<Tag>('SELECT * FROM tags WHERE id = ? AND user_id = ?', id, userId);
const tag = await this.tags.findByIdAndUser(Number(id), userId);
return (tag as unknown as Tag | null) ?? undefined;
}
async create(userId: number, name: string, color?: string): Promise<Tag> {
const result = this.db.run(
'INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)',
userId,
const tag = await this.tags.createTag({
user_id: userId,
name,
color || '#10b981',
);
return this.db.get<Tag>('SELECT * FROM tags WHERE id = ?', result.lastInsertRowid) as Tag;
color: color || '#10b981',
});
return tag as unknown as Tag;
}
async update(id: string | number, name?: string, color?: string): Promise<Tag> {
this.db.run(
'UPDATE tags SET name = COALESCE(?, name), color = COALESCE(?, color) WHERE id = ?',
name || null,
color || null,
id,
);
return this.db.get<Tag>('SELECT * FROM tags WHERE id = ?', id) as Tag;
// `|| null` fed a `COALESCE(?, col)` bind parameter in the legacy
// statement, so any falsy value (undefined or an empty string) meant
// "keep the existing column" — reproduced here by omitting the key from
// `changes` entirely, which is what `TagsRepository.patch`'s `assign`
// needs to leave that column untouched.
const changes: { name?: string; color?: string } = {};
if (name) changes.name = name;
if (color) changes.color = color;
return (await this.tags.patch(Number(id), changes)) as unknown as Tag;
}
async remove(id: string | number): Promise<void> {
this.db.run('DELETE FROM tags WHERE id = ?', id);
await this.tags.remove(Number(id));
}
}