From aa1067035fbe85129d6726adab5ac4849d074043 Mon Sep 17 00:00:00 2001 From: jubnl Date: Tue, 22 Sep 2026 13:54:13 +0200 Subject: [PATCH] refactor(categories, tags): repositories replace raw SQL --- .../db/repositories/Categories.repository.ts | 102 +++++++++- server/src/db/repositories/Tags.repository.ts | 108 ++++++++++- .../db/repositories/_shared/owned-lookup.ts | 69 ++++--- .../src/nest/categories/categories.module.ts | 9 +- .../src/nest/categories/categories.service.ts | 69 +++---- server/src/nest/tags/tags.module.ts | 13 +- server/src/nest/tags/tags.service.ts | 56 +++--- server/tests/helpers/test-uow.ts | 33 ++++ .../Categories.repository.test.ts | 175 +++++++++++++++++ .../db/repositories/Tags.repository.test.ts | 182 ++++++++++++++++++ .../repositories/_shared/owned-lookup.test.ts | 62 +++--- .../tests/unit/mcp/tools-categories.test.ts | 4 +- .../unit/nest/categories.service.test.ts | 62 +++--- server/tests/unit/nest/tags.service.test.ts | 62 +++--- 14 files changed, 798 insertions(+), 208 deletions(-) create mode 100644 server/tests/unit/db/repositories/Categories.repository.test.ts create mode 100644 server/tests/unit/db/repositories/Tags.repository.test.ts diff --git a/server/src/db/repositories/Categories.repository.ts b/server/src/db/repositories/Categories.repository.ts index 63b6e40ed..fc0c94ce0 100644 --- a/server/src/db/repositories/Categories.repository.ts +++ b/server/src/db/repositories/Categories.repository.ts @@ -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 {} +/** 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 = true; + +export class CategoriesRepository extends EntityRepository { + /** `SELECT * FROM categories ORDER BY name ASC` */ + async list(): Promise { + 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 { + 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 { + 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 { + 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 { + return this.nativeDelete({ id }); + } +} diff --git a/server/src/db/repositories/Tags.repository.ts b/server/src/db/repositories/Tags.repository.ts index 2104195f5..b2f9a4285 100644 --- a/server/src/db/repositories/Tags.repository.ts +++ b/server/src/db/repositories/Tags.repository.ts @@ -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 {} +/** 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 = true; + +export class TagsRepository extends EntityRepository { + /** + * `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 { + const tags = await listForOwner(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 { + const tag = await findOwnedByUser(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 { + 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 { + 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 { + 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. +} diff --git a/server/src/db/repositories/_shared/owned-lookup.ts b/server/src/db/repositories/_shared/owned-lookup.ts index d0d7a70de..336af5c5d 100644 --- a/server/src/db/repositories/_shared/owned-lookup.ts +++ b/server/src/db/repositories/_shared/owned-lookup.ts @@ -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', userId, 'name'); * findOwnedByUser(tags, id, 'user', userId); - * findOwnedOrGlobal(categories, id, 'user', userId); + * findOwnedByUser(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 WHERE id = ? AND = ?`. + * + * `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( repo: EntityRepository, id: T['id'], ownerField: K, ownerId: FilterValue, + options?: { refresh?: boolean }, ): Promise { - return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery); -} - -/** - * 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 WHERE id = ? AND ( = ? OR - * IS NULL)`. - */ -export async function findOwnedOrGlobal( - repo: EntityRepository, - id: T['id'], - ownerField: K, - ownerId: FilterValue, -): Promise { - return repo.findOne({ - id, - $or: [{ [ownerField]: ownerId }, { [ownerField]: null }], - } as unknown as FilterQuery); + return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery, options); } diff --git a/server/src/nest/categories/categories.module.ts b/server/src/nest/categories/categories.module.ts index 22644ecf7..2f2ea05ad 100644 --- a/server/src/nest/categories/categories.module.ts +++ b/server/src/nest/categories/categories.module.ts @@ -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). diff --git a/server/src/nest/categories/categories.service.ts b/server/src/nest/categories/categories.service.ts index 5921c6a3b..20a753856 100644 --- a/server/src/nest/categories/categories.service.ts +++ b/server/src/nest/categories/categories.service.ts @@ -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(...)`'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 { - return this.db.all('SELECT * FROM categories ORDER BY name ASC'); + return (await this.categories.list()) as unknown as Category[]; } async getById(id: string | number): Promise { - return this.db.get('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 { - 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( - '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 { - 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('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 { - this.db.run('DELETE FROM categories WHERE id = ?', id); + await this.categories.remove(Number(id)); } } diff --git a/server/src/nest/tags/tags.module.ts b/server/src/nest/tags/tags.module.ts index a4fa80c3a..1681a96b2 100644 --- a/server/src/nest/tags/tags.module.ts +++ b/server/src/nest/tags/tags.module.ts @@ -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 diff --git a/server/src/nest/tags/tags.service.ts b/server/src/nest/tags/tags.service.ts index 0d4cc020a..fb65f83e1 100644 --- a/server/src/nest/tags/tags.service.ts +++ b/server/src/nest/tags/tags.service.ts @@ -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(...)`'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 { - return this.db.all('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 { - return this.db.get('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 { - 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('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 { - this.db.run( - 'UPDATE tags SET name = COALESCE(?, name), color = COALESCE(?, color) WHERE id = ?', - name || null, - color || null, - id, - ); - return this.db.get('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 { - this.db.run('DELETE FROM tags WHERE id = ?', id); + await this.tags.remove(Number(id)); } } diff --git a/server/tests/helpers/test-uow.ts b/server/tests/helpers/test-uow.ts index 1c2dcaeb5..7cbc65aa8 100644 --- a/server/tests/helpers/test-uow.ts +++ b/server/tests/helpers/test-uow.ts @@ -4,9 +4,15 @@ import { UnitOfWork } from '../../src/nest/database/unit-of-work'; import { createTestOrm, type TestOrm } from './test-orm'; import { AppSettings } from '../../src/db/entities/AppSettings.entity'; import type { AppSettingsRepository } from '../../src/db/repositories/AppSettings.repository'; +import { Categories } from '../../src/db/entities/Categories.entity'; +import type { CategoriesRepository } from '../../src/db/repositories/Categories.repository'; +import { Tags } from '../../src/db/entities/Tags.entity'; +import type { TagsRepository } from '../../src/db/repositories/Tags.repository'; const perHandle = new WeakMap>(); const appSettingsPerHandle = new WeakMap>(); +const categoriesPerHandle = new WeakMap>(); +const tagsPerHandle = new WeakMap>(); // ONE MikroORM per handle, shared by createTestUnitOfWork and // createTestAppSettingsRepo (task-2-review.md I2): each used to call // createTestOrm(db) independently, which opened a SECOND MikroORM.init over the @@ -75,6 +81,33 @@ export function createTestAppSettingsRepo(db: Database.Database): Promise { + const existing = categoriesPerHandle.get(db); + if (existing !== undefined) return existing; + const pending = sharedTestOrm(db).then((t) => t.repo(Categories) as CategoriesRepository); + categoriesPerHandle.set(db, pending); + return pending; +} + +/** + * The `TagsRepository` a hand-constructed `TagsService` needs (Plan 3a Task + * 3), same memoisation as `createTestCategoriesRepo`. + */ +export function createTestTagsRepo(db: Database.Database): Promise { + const existing = tagsPerHandle.get(db); + if (existing !== undefined) return existing; + const pending = sharedTestOrm(db).then((t) => t.repo(Tags) as TagsRepository); + tagsPerHandle.set(db, pending); + return pending; +} + /** * The same `UnitOfWork`, as a **global** Nest module. * diff --git a/server/tests/unit/db/repositories/Categories.repository.test.ts b/server/tests/unit/db/repositories/Categories.repository.test.ts new file mode 100644 index 000000000..e8636177c --- /dev/null +++ b/server/tests/unit/db/repositories/Categories.repository.test.ts @@ -0,0 +1,175 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; +import { createCategory, createUser } from '../../../helpers/factories'; +import { Categories } from '../../../../src/db/entities/Categories.entity'; +import type { CategoriesRepository } from '../../../../src/db/repositories/Categories.repository'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let categories: CategoriesRepository; + +beforeAll(async () => { + t = await createTestOrm(testDb); + categories = t.repo(Categories) as CategoriesRepository; +}); +// `categories` is a KEEP_TABLES table (tests/helpers/test-db.ts): resetTestDb +// never clears it and re-seeds the ten defaults by name, so rows created by +// one `it` persist into the next within this file — every case below reads +// back by the id/name it just created rather than assuming a fresh table. +beforeEach(() => { resetTestDb(testDb); t.clear(); }); +afterAll(async () => { await t.close(); testDb.close(); }); + +function rawCategory(id: number): unknown { + return testDb.prepare('SELECT * FROM categories WHERE id = ?').get(id); +} + +async function withQueryCount(fn: () => Promise): Promise<{ value: T; queries: number }> { + const connection = t.orm.em.getConnection(); + const spy = vi.spyOn(connection, 'execute'); + try { + const value = await fn(); + return { value, queries: spy.mock.calls.length }; + } finally { + spy.mockRestore(); + } +} + +describe('CategoriesRepository', () => { + describe('list', () => { + it('CATREPO-001: a row read through list is the SELECT * row, key for key', async () => { + const { user } = createUser(testDb); + const created = createCategory(testDb, { name: 'RepoListRow', user_id: user.id }); + const rows = await categories.list(); + const row = rows.find((r) => r.id === created.id); + expect(row).toStrictEqual(rawCategory(created.id)); + }); + + it('CATREPO-002: ordered by name ascending', async () => { + createCategory(testDb, { name: 'RepoZZZ' }); + createCategory(testDb, { name: 'RepoAAA' }); + const names = (await categories.list()).map((r) => r.name); + expect(names.indexOf('RepoAAA')).toBeLessThan(names.indexOf('RepoZZZ')); + }); + + it('CATREPO-003: unfiltered — includes rows owned by any user and globally-shared (user_id NULL) rows alike', async () => { + const { user: a } = createUser(testDb); + const { user: b } = createUser(testDb); + const before = (await categories.list()).length; + createCategory(testDb, { name: 'RepoOwnedA', user_id: a.id }); + createCategory(testDb, { name: 'RepoOwnedB', user_id: b.id }); + createCategory(testDb, { name: 'RepoGlobal', user_id: null }); + expect(await categories.list()).toHaveLength(before + 3); + }); + }); + + describe('findById', () => { + it('CATREPO-004: returns the row for a valid id', async () => { + const created = createCategory(testDb, { name: 'RepoFindMe' }); + expect(await categories.findById(created.id)).toStrictEqual(rawCategory(created.id)); + }); + + it('CATREPO-005: returns null for a non-existent id', async () => { + expect(await categories.findById(99999999)).toBeNull(); + }); + + it('CATREPO-006: no owner filter — a row owned by one user is found looked up plainly (no ownerId parameter exists on this method)', async () => { + const { user } = createUser(testDb); + const created = createCategory(testDb, { name: 'RepoAnyonesFind', user_id: user.id }); + expect((await categories.findById(created.id))?.id).toBe(created.id); + }); + + it('CATREPO-007: the scalar user_id twin hydrates without loading the user relation', async () => { + const { user } = createUser(testDb); + const created = createCategory(testDb, { name: 'RepoTwin', user_id: user.id }); + const entity = await t.repo(Categories).findOne({ id: created.id }); + expect(entity?.user_id).toBe(user.id); + expect(entity?.user?.isInitialized()).toBe(false); + }); + + // I1 (Task 0 review): findById carries `refresh: true`, the ruling every + // Plan 3 PK read follows. This unrestricted (no `fields` option) findOne + // always re-queries and merges fresh data regardless of `refresh` — see + // CategoriesRepository's docstring — so this proves the (still correct) + // outcome in one query rather than a refresh-vs-no-refresh contrast. + it('CATREPO-008: a raw UPDATE on the same row then findById reads the new value, in one query', async () => { + const created = createCategory(testDb, { name: 'RepoStale', color: '#111111' }); + expect((await categories.findById(created.id))?.color).toBe('#111111'); // populate the identity map + testDb.prepare('UPDATE categories SET color = ? WHERE id = ?').run('#222222', created.id); + const { value, queries } = await withQueryCount(() => categories.findById(created.id)); + expect(value?.color).toBe('#222222'); + expect(queries).toBe(1); + }); + }); + + describe('createCategory', () => { + it('CATREPO-009: inserts and returns exactly the row the legacy re-select returned', async () => { + const { user } = createUser(testDb); + const row = await categories.createCategory({ name: 'RepoCreated', color: '#ff5500', icon: '🍽️', user_id: user.id }); + expect(row).toStrictEqual(rawCategory(row.id)); + expect(row.name).toBe('RepoCreated'); + expect(row.color).toBe('#ff5500'); + expect(row.icon).toBe('🍽️'); + expect(row.user_id).toBe(user.id); + expect(typeof row.created_at).toBe('string'); + }); + + it('CATREPO-010: writes exactly what it is given — no defaulting inside the repository', async () => { + const { user } = createUser(testDb); + const row = await categories.createCategory({ name: 'RepoNoDefault', color: 'literal-color', icon: 'literal-icon', user_id: user.id }); + expect(row.color).toBe('literal-color'); + expect(row.icon).toBe('literal-icon'); + }); + }); + + describe('patch', () => { + it('CATREPO-011: updates name, color, and icon when all three are given', async () => { + const created = createCategory(testDb, { name: 'RepoOld', color: '#aaaaaa', icon: '❓' }); + const updated = await categories.patch(created.id, { name: 'RepoNew', color: '#bbbbbb', icon: '✅' }); + expect(updated).toStrictEqual(rawCategory(created.id)); + expect(updated?.name).toBe('RepoNew'); + expect(updated?.color).toBe('#bbbbbb'); + expect(updated?.icon).toBe('✅'); + }); + + it('CATREPO-012: an omitted key is left untouched — does not touch other columns', async () => { + const created = createCategory(testDb, { name: 'RepoKeepName', color: '#cccccc', icon: '⭐' }); + const updated = await categories.patch(created.id, { color: '#dddddd' }); + expect(updated?.name).toBe('RepoKeepName'); + expect(updated?.color).toBe('#dddddd'); + expect(updated?.icon).toBe('⭐'); + }); + + it('CATREPO-013: an empty changes object leaves every column untouched', async () => { + const created = createCategory(testDb, { name: 'RepoUnchanged', color: '#eeeeee', icon: '🔥' }); + const before = rawCategory(created.id); + const updated = await categories.patch(created.id, {}); + expect(updated).toStrictEqual(before); + }); + + it('CATREPO-014: returns null for a non-existent id', async () => { + expect(await categories.patch(99999999, { name: 'Nope' })).toBeNull(); + }); + }); + + describe('remove', () => { + it('CATREPO-015: deletes the row and returns the affected count', async () => { + const created = createCategory(testDb, { name: 'RepoToDelete' }); + expect(await categories.remove(created.id)).toBe(1); + expect(await categories.findById(created.id)).toBeNull(); + }); + + it('CATREPO-016: removing a non-existent id returns 0 and does not throw', async () => { + await expect(categories.remove(99999999)).resolves.toBe(0); + }); + + it('CATREPO-017: removing one row does not affect others', async () => { + const keep = createCategory(testDb, { name: 'RepoKeep' }); + const gone = createCategory(testDb, { name: 'RepoGone' }); + await categories.remove(gone.id); + expect(await categories.findById(keep.id)).not.toBeNull(); + expect(await categories.findById(gone.id)).toBeNull(); + }); + }); +}); diff --git a/server/tests/unit/db/repositories/Tags.repository.test.ts b/server/tests/unit/db/repositories/Tags.repository.test.ts new file mode 100644 index 000000000..726e32740 --- /dev/null +++ b/server/tests/unit/db/repositories/Tags.repository.test.ts @@ -0,0 +1,182 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; +import { createTag, createUser } from '../../../helpers/factories'; +import { Tags } from '../../../../src/db/entities/Tags.entity'; +import type { TagsRepository } from '../../../../src/db/repositories/Tags.repository'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let tags: TagsRepository; + +beforeAll(async () => { + t = await createTestOrm(testDb); + tags = t.repo(Tags) as TagsRepository; +}); +beforeEach(() => { resetTestDb(testDb); t.clear(); }); +afterAll(async () => { await t.close(); testDb.close(); }); + +function rawTag(id: number): unknown { + return testDb.prepare('SELECT * FROM tags WHERE id = ?').get(id); +} + +async function withQueryCount(fn: () => Promise): Promise<{ value: T; queries: number }> { + const connection = t.orm.em.getConnection(); + const spy = vi.spyOn(connection, 'execute'); + try { + const value = await fn(); + return { value, queries: spy.mock.calls.length }; + } finally { + spy.mockRestore(); + } +} + +describe('TagsRepository', () => { + describe('listByUser', () => { + it('TAGREPO-001: a row read through listByUser is the SELECT * row, key for key', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'RepoListRow' }); + const [row] = await tags.listByUser(user.id); + expect(row).toStrictEqual(rawTag(created.id)); + }); + + it('TAGREPO-002: ordered by name ascending', async () => { + const { user } = createUser(testDb); + createTag(testDb, user.id, { name: 'Zebra' }); + createTag(testDb, user.id, { name: 'Apple' }); + createTag(testDb, user.id, { name: 'Mango' }); + expect((await tags.listByUser(user.id)).map((r) => r.name)).toEqual(['Apple', 'Mango', 'Zebra']); + }); + + it('TAGREPO-003: owner visibility — excludes another user\'s tags entirely (tags has no globally-shared row, unlike categories)', async () => { + const { user: a } = createUser(testDb); + const { user: b } = createUser(testDb); + createTag(testDb, a.id, { name: 'MineA' }); + createTag(testDb, b.id, { name: 'MineB' }); + const rows = await tags.listByUser(a.id); + expect(rows).toHaveLength(1); + expect(rows[0].name).toBe('MineA'); + }); + + it('TAGREPO-004: an owner with no tags gets an empty list', async () => { + const { user } = createUser(testDb); + expect(await tags.listByUser(user.id)).toEqual([]); + }); + }); + + describe('findByIdAndUser', () => { + it('TAGREPO-005: finds a row the given user owns', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'FindMe' }); + expect(await tags.findByIdAndUser(created.id, user.id)).toStrictEqual(rawTag(created.id)); + }); + + it('TAGREPO-006: owner visibility — refuses a tag owned by a different user', async () => { + const { user: owner } = createUser(testDb); + const { user: stranger } = createUser(testDb); + const created = createTag(testDb, owner.id, { name: 'Private' }); + expect(await tags.findByIdAndUser(created.id, stranger.id)).toBeNull(); + }); + + it('TAGREPO-007: returns null for a non-existent id', async () => { + const { user } = createUser(testDb); + expect(await tags.findByIdAndUser(99999999, user.id)).toBeNull(); + }); + + it('TAGREPO-008: the scalar user_id twin hydrates without loading the user relation', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'Twin' }); + const entity = await t.repo(Tags).findOne({ id: created.id, user: user.id }); + expect(entity?.user_id).toBe(user.id); + expect(entity?.user.isInitialized()).toBe(false); + }); + + // I1 (Task 0 review): findByIdAndUser carries `{ refresh: true }` (via + // the shared findOwnedByUser helper), the ruling every Plan 3 PK read + // follows. This unrestricted (no `fields` option) findOne always + // re-queries and merges fresh data regardless of `refresh` — see + // TagsRepository's docstring — so this proves the (still correct) + // outcome in one query rather than a refresh-vs-no-refresh contrast. + it('TAGREPO-009: a raw UPDATE on the same row then findByIdAndUser reads the new value, in one query', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'Stale', color: '#111111' }); + expect((await tags.findByIdAndUser(created.id, user.id))?.color).toBe('#111111'); // populate the identity map + testDb.prepare('UPDATE tags SET color = ? WHERE id = ?').run('#222222', created.id); + const { value, queries } = await withQueryCount(() => tags.findByIdAndUser(created.id, user.id)); + expect(value?.color).toBe('#222222'); + expect(queries).toBe(1); + }); + }); + + describe('createTag', () => { + it('TAGREPO-010: inserts and returns exactly the row the legacy re-select returned', async () => { + const { user } = createUser(testDb); + const row = await tags.createTag({ user_id: user.id, name: 'Beach', color: '#ff0000' }); + expect(row).toStrictEqual(rawTag(row.id)); + expect(row.name).toBe('Beach'); + expect(row.color).toBe('#ff0000'); + expect(row.user_id).toBe(user.id); + expect(typeof row.created_at).toBe('string'); + }); + + it('TAGREPO-011: writes exactly what it is given — no defaulting inside the repository', async () => { + const { user } = createUser(testDb); + const row = await tags.createTag({ user_id: user.id, name: 'NoDefault', color: 'literal-color' }); + expect(row.color).toBe('literal-color'); + }); + }); + + describe('patch', () => { + it('TAGREPO-012: updates both name and color when both are given', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'Old', color: '#aaaaaa' }); + const updated = await tags.patch(created.id, { name: 'New', color: '#bbbbbb' }); + expect(updated).toStrictEqual(rawTag(created.id)); + expect(updated?.name).toBe('New'); + expect(updated?.color).toBe('#bbbbbb'); + }); + + it('TAGREPO-013: an omitted key is left untouched — does not touch other columns', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'KeepName', color: '#cccccc' }); + const updated = await tags.patch(created.id, { color: '#dddddd' }); + expect(updated?.name).toBe('KeepName'); + expect(updated?.color).toBe('#dddddd'); + }); + + it('TAGREPO-014: not scoped by user_id, matching the legacy statement exactly — patches a row regardless of which user owns it', async () => { + const { user: owner } = createUser(testDb); + const created = createTag(testDb, owner.id, { name: 'AnyonesToPatch' }); + const updated = await tags.patch(created.id, { name: 'Patched' }); + expect(updated?.name).toBe('Patched'); + }); + + it('TAGREPO-015: returns null for a non-existent id', async () => { + expect(await tags.patch(99999999, { name: 'Nope' })).toBeNull(); + }); + }); + + describe('remove', () => { + it('TAGREPO-016: deletes the row and returns the affected count', async () => { + const { user } = createUser(testDb); + const created = createTag(testDb, user.id, { name: 'ToDelete' }); + expect(await tags.remove(created.id)).toBe(1); + expect(await tags.findByIdAndUser(created.id, user.id)).toBeNull(); + }); + + it('TAGREPO-017: removing a non-existent id returns 0 and does not throw', async () => { + await expect(tags.remove(99999999)).resolves.toBe(0); + }); + + it('TAGREPO-018: removing one tag does not affect others', async () => { + const { user } = createUser(testDb); + const keep = createTag(testDb, user.id, { name: 'Keep' }); + const gone = createTag(testDb, user.id, { name: 'Gone' }); + await tags.remove(gone.id); + const remaining = await tags.listByUser(user.id); + expect(remaining).toHaveLength(1); + expect(remaining[0].id).toBe(keep.id); + }); + }); +}); diff --git a/server/tests/unit/db/repositories/_shared/owned-lookup.test.ts b/server/tests/unit/db/repositories/_shared/owned-lookup.test.ts index ed8ce9055..0d640a5d2 100644 --- a/server/tests/unit/db/repositories/_shared/owned-lookup.test.ts +++ b/server/tests/unit/db/repositories/_shared/owned-lookup.test.ts @@ -1,22 +1,18 @@ -import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { createSnapshotTestDb } from '../../../../helpers/db-mock'; import { resetTestDb } from '../../../../helpers/test-db'; import { createTestOrm, type TestOrm } from '../../../../helpers/test-orm'; -import { createCategory, createTag, createUser } from '../../../../helpers/factories'; -import { Categories } from '../../../../../src/db/entities/Categories.entity'; +import { createTag, createUser } from '../../../../helpers/factories'; import { Tags } from '../../../../../src/db/entities/Tags.entity'; -import type { CategoriesRepository } from '../../../../../src/db/repositories/Categories.repository'; import type { TagsRepository } from '../../../../../src/db/repositories/Tags.repository'; -import { findOwnedByUser, findOwnedOrGlobal, listForOwner } from '../../../../../src/db/repositories/_shared/owned-lookup'; +import { findOwnedByUser, listForOwner } from '../../../../../src/db/repositories/_shared/owned-lookup'; const testDb = createSnapshotTestDb(); let t: TestOrm; -let categories: CategoriesRepository; let tags: TagsRepository; beforeAll(async () => { t = await createTestOrm(testDb); - categories = t.repo(Categories) as CategoriesRepository; tags = t.repo(Tags) as TagsRepository; }); beforeEach(() => { resetTestDb(testDb); t.clear(); }); @@ -63,33 +59,29 @@ describe('findOwnedByUser', () => { const { user: owner } = createUser(testDb); expect(await findOwnedByUser(tags, 999999, 'user', owner.id)).toBeNull(); }); -}); -describe('findOwnedOrGlobal', () => { - it('OWNEDLOOKUP-006: finds a row the given user owns — Categories (a permissively-owned entity, user_id nullable)', async () => { + // Task 0 review I1's PK-read ruling, extended to this helper (Task 3): + // `options.refresh` passes through to `findOne`. For an unrestricted + // (full-row) findOne like this one, MikroORM already re-queries and merges + // fresh data on every call regardless of `refresh` (proven below: a raw + // write on the same row is visible either way) — `refresh`'s + // identity-map-skip optimisation (and the staleness it can cause without + // it) only engages when `options.fields` is also set, which is why + // AppSettingsRepository.getValue (a `fields: ['value']`-scoped findOne) + // needed it to fix a real bug and this one does not. It stays on this + // helper regardless, matching the Task 0 review's blanket PK-read ruling + // and staying correct if a future caller adds a `fields` restriction here. + it('OWNEDLOOKUP-006: { refresh: true } sees a raw UPDATE on the same row in the same request, in one query', async () => { const { user: owner } = createUser(testDb); - const category = createCategory(testDb, { name: 'Mine', user_id: owner.id }); - const found = await findOwnedOrGlobal(categories, category.id, 'user', owner.id); - expect(found?.id).toBe(category.id); - }); - - it('OWNEDLOOKUP-007: finds a row with no owner at all (a globally-shared row)', async () => { - const { user: someone } = createUser(testDb); - const global = createCategory(testDb, { name: 'Global', user_id: null }); - const found = await findOwnedOrGlobal(categories, global.id, 'user', someone.id); - expect(found?.id).toBe(global.id); - }); - - it('OWNEDLOOKUP-008: refuses a row owned by somebody else — a non-null owner that is not the caller is not global', async () => { - const { user: owner } = createUser(testDb); - const { user: stranger } = createUser(testDb); - const category = createCategory(testDb, { name: 'Theirs', user_id: owner.id }); - expect(await findOwnedOrGlobal(categories, category.id, 'user', stranger.id)).toBeNull(); - }); - - it('OWNEDLOOKUP-009: returns null for an id that does not exist', async () => { - const { user: someone } = createUser(testDb); - expect(await findOwnedOrGlobal(categories, 999999, 'user', someone.id)).toBeNull(); + const tag = createTag(testDb, owner.id, { name: 'Old' }); + expect((await findOwnedByUser(tags, tag.id, 'user', owner.id))?.name).toBe('Old'); // populate the identity map + testDb.prepare('UPDATE tags SET name = ? WHERE id = ?').run('New', tag.id); + const connection = t.orm.em.getConnection(); + const spy = vi.spyOn(connection, 'execute'); + const found = await findOwnedByUser(tags, tag.id, 'user', owner.id, { refresh: true }); + expect(found?.name).toBe('New'); + expect(spy.mock.calls.length).toBe(1); + spy.mockRestore(); }); }); @@ -124,12 +116,6 @@ function typeProbes(): void { // orderField must be a real property of Tags. // @ts-expect-error 'not_a_column' is not a key of Tags void listForOwner(tags, 'user', 1, 'not_a_column'); - - // Same two shapes for findOwnedOrGlobal. - // @ts-expect-error AppSettings has no `id` property - void findOwnedOrGlobal(appSettingsRepoForProbe, 1, 'value', 'whatever'); - // @ts-expect-error ownerId is not a value `Categories['user']` can be filtered by - void findOwnedOrGlobal(categories, 1, 'user', { nonsense: true }); } void typeProbes; declare const appSettingsRepoForProbe: import('../../../../../src/db/repositories/AppSettings.repository').AppSettingsRepository; diff --git a/server/tests/unit/mcp/tools-categories.test.ts b/server/tests/unit/mcp/tools-categories.test.ts index 0925412a8..4a17e9167 100644 --- a/server/tests/unit/mcp/tools-categories.test.ts +++ b/server/tests/unit/mcp/tools-categories.test.ts @@ -50,7 +50,7 @@ import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.serv import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service'; -import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow'; +import { createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo } from '../../helpers/test-uow'; beforeAll(() => { createTables(testDb); @@ -83,7 +83,7 @@ const categoriesDb = new DatabaseService(testDb); let categoriesMcp: CategoriesMcp; beforeAll(async () => { categoriesMcp = new CategoriesMcp( - new CategoriesService(categoriesDb), + new CategoriesService(await createTestCategoriesRepo(categoriesDb.connection)), categoriesDb, new RuntimeEnvService(), new McpToolGuardsService(categoriesDb, new PermissionsService(await createTestAppSettingsRepo(categoriesDb.connection), await createTestUnitOfWork(categoriesDb.connection)), new RealtimeService()), diff --git a/server/tests/unit/nest/categories.service.test.ts b/server/tests/unit/nest/categories.service.test.ts index 5d2cbce76..4582173e7 100644 --- a/server/tests/unit/nest/categories.service.test.ts +++ b/server/tests/unit/nest/categories.service.test.ts @@ -1,57 +1,47 @@ /** * Unit tests for CategoriesService — CAT-SVC-001 through CAT-SVC-015. - * Uses a real in-memory SQLite DB so SQL logic is exercised faithfully. - * The service is constructed directly (new CategoriesService(new DatabaseService(db))) - * — no Nest container needed. (CAT-SVC-016 covered the deleted - * categories.bridge; the plugin RPC host now injects CategoriesService directly.) + * Uses a real in-memory SQLite DB so SQL logic is exercised faithfully. The + * service is constructed directly (new CategoriesService(repo)) over a + * CategoriesRepository resolved from the suite's own ORM (Plan 3a Task 3; + * `createTestCategoriesRepo`/`sharedTestOrm` from tests/helpers/test-uow.ts, + * same pattern as audit.service.test.ts) — no Nest container needed. + * (CAT-SVC-016 covered the deleted categories.bridge; the plugin RPC host + * now injects CategoriesService directly.) */ -import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; - -// ── DB setup ────────────────────────────────────────────────────────────────── - -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - db.exec('PRAGMA busy_timeout = 5000'); - const mock = { - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - canAccessTrip: () => null, - isOwner: () => false, - }; - return { testDb: db, dbMock: mock }; -}); - -vi.mock('../../../src/db/database', () => dbMock); -vi.mock('../../../src/config', () => ({ - JWT_SECRET: 'test-secret', - ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2', - updateJwtSecret: () => {}, -})); - +import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; +import Database from 'better-sqlite3'; import { createTables } from '../../../src/db/schema'; import { runMigrations } from '../../../src/db/migrations'; import { resetTestDb } from '../../helpers/test-db'; import { createUser } from '../../helpers/factories'; -import { DatabaseService } from '../../../src/nest/database/database.service'; +import { createTestCategoriesRepo, sharedTestOrm } from '../../helpers/test-uow'; +import type { TestOrm } from '../../helpers/test-orm'; import { CategoriesService } from '../../../src/nest/categories/categories.service'; -const svc = new CategoriesService(new DatabaseService(testDb)); +// ── DB setup ────────────────────────────────────────────────────────────────── -beforeAll(() => { +const testDb = new Database(':memory:'); +testDb.exec('PRAGMA journal_mode = WAL'); +testDb.exec('PRAGMA foreign_keys = ON'); +testDb.exec('PRAGMA busy_timeout = 5000'); + +let t: TestOrm; +let svc: CategoriesService; + +beforeAll(async () => { createTables(testDb); runMigrations(testDb); + t = await sharedTestOrm(testDb); + svc = new CategoriesService(await createTestCategoriesRepo(testDb)); }); beforeEach(() => { resetTestDb(testDb); + t.clear(); }); -afterAll(() => { +afterAll(async () => { + await t.close(); testDb.close(); }); diff --git a/server/tests/unit/nest/tags.service.test.ts b/server/tests/unit/nest/tags.service.test.ts index 257da9d78..f17e59729 100644 --- a/server/tests/unit/nest/tags.service.test.ts +++ b/server/tests/unit/nest/tags.service.test.ts @@ -1,57 +1,47 @@ /** * Unit tests for TagsService — TAG-SVC-001 through TAG-SVC-015. - * Uses a real in-memory SQLite DB so SQL logic is exercised faithfully. - * The service is constructed directly (new TagsService(new DatabaseService(db))) - * — no Nest container needed. (TAG-SVC-016..020 covered the deleted - * tags.bridge; the plugin RPC host now injects TagsService directly.) + * Uses a real in-memory SQLite DB so SQL logic is exercised faithfully. The + * service is constructed directly (new TagsService(repo)) over a + * TagsRepository resolved from the suite's own ORM (Plan 3a Task 3; + * `createTestTagsRepo`/`sharedTestOrm` from tests/helpers/test-uow.ts, same + * pattern as audit.service.test.ts) — no Nest container needed. + * (TAG-SVC-016..020 covered the deleted tags.bridge; the plugin RPC host now + * injects TagsService directly.) */ -import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; - -// ── DB setup ────────────────────────────────────────────────────────────────── - -const { testDb, dbMock } = vi.hoisted(() => { - const Database = require('better-sqlite3'); - const db = new Database(':memory:'); - db.exec('PRAGMA journal_mode = WAL'); - db.exec('PRAGMA foreign_keys = ON'); - db.exec('PRAGMA busy_timeout = 5000'); - const mock = { - db, - closeDb: () => {}, - reinitialize: () => {}, - getPlaceWithTags: () => null, - canAccessTrip: () => null, - isOwner: () => false, - }; - return { testDb: db, dbMock: mock }; -}); - -vi.mock('../../../src/db/database', () => dbMock); -vi.mock('../../../src/config', () => ({ - JWT_SECRET: 'test-secret', - ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2', - updateJwtSecret: () => {}, -})); - +import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; +import Database from 'better-sqlite3'; import { createTables } from '../../../src/db/schema'; import { runMigrations } from '../../../src/db/migrations'; import { resetTestDb } from '../../helpers/test-db'; import { createUser } from '../../helpers/factories'; -import { DatabaseService } from '../../../src/nest/database/database.service'; +import { createTestTagsRepo, sharedTestOrm } from '../../helpers/test-uow'; +import type { TestOrm } from '../../helpers/test-orm'; import { TagsService } from '../../../src/nest/tags/tags.service'; -const svc = new TagsService(new DatabaseService(testDb)); +// ── DB setup ────────────────────────────────────────────────────────────────── -beforeAll(() => { +const testDb = new Database(':memory:'); +testDb.exec('PRAGMA journal_mode = WAL'); +testDb.exec('PRAGMA foreign_keys = ON'); +testDb.exec('PRAGMA busy_timeout = 5000'); + +let t: TestOrm; +let svc: TagsService; + +beforeAll(async () => { createTables(testDb); runMigrations(testDb); + t = await sharedTestOrm(testDb); + svc = new TagsService(await createTestTagsRepo(testDb)); }); beforeEach(() => { resetTestDb(testDb); + t.clear(); }); -afterAll(() => { +afterAll(async () => { + await t.close(); testDb.close(); });