ci(server): refuse SQL text in repositories and seeders, move the gallery oracle to tests

The repository rule that keeps dialect SQL in sql-functions.ts only
matched raw() and the sql tag, so a SQL string handed straight to the
connection, em.getConnection().execute('INSERT OR IGNORE ...'), passed
unseen, and the seeders sat outside every repository rule. A new block
refuses a string or template whose text starts like a statement as the
first argument of execute, run, all or get in src/db/repositories and
src/db/seeders; a result mode such as qb.execute('run') stays legal.
The files that already hold such SQL are named one by one so the list
can only shrink: MaintenanceRepository (PRAGMA, VACUUM INTO),
DemoRepository and six of the seven seeders.

The selector groups are named once in eslint.config.mjs, and the
selector test now also checks the new block per path, its exceptions,
and that raw() stays forbidden in repositories.

journey-gallery-order.ts exported raw SQLite ORDER BY text from
src/nest that no production code read any more since the gallery reads
moved onto JourneyPhotosRepository. Two parity tests still compare the
Kysely rebuild against it, so it moves to tests/helpers as their oracle.
This commit is contained in:
Maurice
2026-10-08 11:59:47 +02:00
parent 3fbe0418eb
commit a86aa4e819
9 changed files with 115 additions and 12 deletions
@@ -0,0 +1,42 @@
/**
* How the journey gallery is ordered (#2200), as the raw SQLite text the gallery
* reads used before JourneyPhotosRepository.galleryRead rebuilt it in Kysely.
* Kept here as the oracle the parity tests compare that rebuild against; no
* production code reads it, and raw SQL has no place in src/nest any more.
*
*
* `journey_photos.sort_order` is nothing but MAX+1 at insert time and no surface
* ever writes it again, so ordering by it is ordering by "whenever this got
* added". Upload day one's pictures after day two's and the gallery stays
* shuffled, with nothing in the UI to straighten it out.
*
* The anchor is instead the best time TREK knows for the picture:
*
* 1. its capture time, when EXIF or the photo provider gave one up,
* 2. otherwise the date of the earliest entry it hangs on, which is where the
* journey itself says the reader was standing when it was taken,
* 3. otherwise the moment it was added, the old behaviour and the only thing
* left to go on for a loose photo whose EXIF was stripped.
*
* All three are compared as ISO text. Entry dates are local wall clock and
* capture times are UTC, which only disagree in the hours either side of
* midnight, and a gallery is read by the day.
*
* `sort_order`, then the row id, break ties: insertion order still decides
* between two pictures taken in the same minute, and the id makes the order
* total, so paging through the gallery cannot show or skip a photo twice.
*
* Consumers must alias journey_photos as `gp` and trek_photos as `tp`.
*/
export const GALLERY_CHRONOLOGICAL_ORDER = `
ORDER BY COALESCE(
NULLIF(tp.taken_at, ''),
(SELECT MIN(je.entry_date || 'T' || COALESCE(NULLIF(je.entry_time, ''), '00:00'))
FROM journey_entry_photos jep
JOIN journey_entries je ON je.id = jep.entry_id
WHERE jep.journey_photo_id = gp.id),
strftime('%Y-%m-%dT%H:%M:%SZ', gp.created_at / 1000, 'unixepoch')
) ASC,
gp.sort_order ASC,
gp.id ASC
`;
@@ -1128,7 +1128,7 @@ describe('sql-functions (sqlite)', () => {
});
// Plan 3g Task 0 (R1) — unixEpochToIsoKysely, the third fallback tier of
// `GALLERY_CHRONOLOGICAL_ORDER` (journey-gallery-order.ts). No consumer
// `GALLERY_CHRONOLOGICAL_ORDER` (tests/helpers/legacy-gallery-order.ts). No consumer
// yet: Task 1 (getJourneyFull) and Task 3 (getPublicJourney) each fold this
// into their own rebuild of the constant. The full composed ORDER BY proof
// (coalesce + nullif + correlated subquery + this helper, on a seeded
@@ -1337,7 +1337,7 @@ describe('sql-functions (sqlite)', () => {
/**
* Plan 3g Task 0 (R1) — the full Kysely rebuild of
* `journey-gallery-order.ts`'s `GALLERY_CHRONOLOGICAL_ORDER`, as a worked
* `GALLERY_CHRONOLOGICAL_ORDER` (tests/helpers/legacy-gallery-order.ts), as a worked
* example: `COALESCE(NULLIF(tp.taken_at, ''), <correlated MIN+concat
* subquery over journey_entry_photos/journey_entries>, <unixEpochToIsoKysely
* of gp.created_at>) ASC, gp.sort_order ASC, gp.id ASC`. NOT exported from
@@ -4,7 +4,7 @@ import { ESLint, Linter } from 'eslint';
import path from 'path';
import { beforeAll, describe, expect, it } from 'vitest';
// The outbound-timeout guard is no-restricted-syntax selectors in
// The outbound-timeout and raw-SQL guards are no-restricted-syntax selectors in
// eslint.config.mjs, and a selector that stops matching fails silently: the
// lint stays green and nothing is checked. This asks ESLint for the options it
// really applies to a given path (so the flat-config blocks and their ignores
@@ -90,3 +90,53 @@ describe('outbound fetch timeout selectors', () => {
expect(messages(repo, `${PRELUDE}\nvoid safeFetch(url, undefined, {});`)).toEqual([TIMEOUT]);
});
});
describe('raw SQL string selectors', () => {
const SQL = `
declare const connection: { execute(sql: string, params?: unknown[], mode?: string): Promise<unknown> };
declare const qb: { execute(mode: string): Promise<unknown> };
declare const repo: { run(sql: string, params?: unknown[]): Promise<unknown>; get(key: string): unknown };
`;
const hits = (options: unknown[], code: string) =>
messages(options, `${SQL}\n${code}`).filter((m) => m.startsWith('A SQL string handed to the connection'));
it('flags a SQL string handed to the connection in a repository and in a seeder', async () => {
for (const file of ['src/db/repositories/Probe.repository.ts', 'src/db/seeders/ProbeSeeder.ts']) {
const options = await selectorsFor(file);
expect(hits(options, "void connection.execute('INSERT OR IGNORE INTO t (a) VALUES (?)', [1]);")).toHaveLength(1);
expect(hits(options, 'void connection.execute(` select * from t where id = ?`, [1]);')).toHaveLength(1);
expect(hits(options, "void repo.run('PRAGMA wal_checkpoint(TRUNCATE)');")).toHaveLength(1);
// A result mode and a map lookup are not SQL.
expect(hits(options, "void qb.execute('run'); void repo.get('key');")).toEqual([]);
}
});
it('still forbids raw() and the sql tag in a repository', async () => {
const options = await selectorsFor('src/db/repositories/Probe.repository.ts');
const found = messages(options, "declare function raw(s: string): unknown;\nvoid raw('now()');");
expect(found.some((m) => m.startsWith('Dialect SQL goes through'))).toBe(true);
});
it('leaves the named adapters alone, and only them', async () => {
for (const file of [
'src/db/repositories/MaintenanceRepository.ts',
'src/db/repositories/DemoRepository.ts',
'src/db/seeders/AddonSeeder.ts',
'src/db/seeders/AdminSeeder.ts',
'src/db/seeders/CategorySeeder.ts',
'src/db/seeders/DocumentProviderSeeder.ts',
'src/db/seeders/PhotoProviderSeeder.ts',
'src/db/seeders/SchemaVersionSeeder.ts',
]) {
const options = await selectorsFor(file);
expect(hits(options, "void connection.execute('PRAGMA wal_checkpoint(TRUNCATE)');"), file).toEqual([]);
// The rest of the guard still applies to them.
expect(messages(options, `${PRELUDE}\nvoid safeFetch(url);`), file).toContain(TIMEOUT);
}
});
it('does not reach outside src/db', async () => {
const options = await selectorsFor('src/nest/memories/probe.service.ts');
expect(hits(options, "void connection.execute('SELECT 1');")).toEqual([]);
});
});
@@ -59,7 +59,7 @@ import {
// M5d (task-5-review.md) — full-key parity tests for Task 2's read models,
// ported from the reviewer's probe (scratchpad r3g/probe/zz-r3g-parity-probe.test.ts).
import { todayUtc } from '@trek/shared';
import { GALLERY_CHRONOLOGICAL_ORDER } from '../../../src/nest/journey/journey-gallery-order';
import { GALLERY_CHRONOLOGICAL_ORDER } from '../../helpers/legacy-gallery-order';
let svc: JourneyDomainService;
// Plan 3g Task 1's own additions (below, "repositories (R9's parity + mutation
@@ -49,7 +49,7 @@ import { createTestJourneyShareTokensRepo } from '../../helpers/journey-share-re
import type { JourneyPublicGalleryRow, JourneyShareTokensRepository } from '../../../src/db/repositories/JourneyShareTokens.repository';
import type { JourneyEntriesRepository } from '../../../src/db/repositories/JourneyEntries.repository';
import type { JourneyEntryPhotosRepository } from '../../../src/db/repositories/JourneyEntryPhotos.repository';
import { GALLERY_CHRONOLOGICAL_ORDER } from '../../../src/nest/journey/journey-gallery-order';
import { GALLERY_CHRONOLOGICAL_ORDER } from '../../helpers/legacy-gallery-order';
let svc: JourneyShareService;
let t: TestOrm;