From 53d9ec5678909d1a1754f1955117145138074971 Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 8 Oct 2026 16:16:19 +0200 Subject: [PATCH] refactor(db): move the Kysely dialect helpers into kysely-functions.ts sql-functions.ts sat at 1007 lines, held there by the size baseline, so it had no room for the Postgres branch every helper is meant to grow. The Kysely-expression twins are a separate family already (a Kysely Expression and a MikroORM RawQueryFragment do not convert into each other), so they move to src/db/dialect/kysely-functions.ts, and the platform check plus the fail-closed unsupported() move to platform.ts, which both files share. No helper changes behaviour or spelling. lint:dialect now skips the whole src/db/dialect/ directory instead of the one file, and the size baseline drops its sql-functions.ts entry. --- server/CLAUDE.md | 6 +- server/scripts/dialect-lint.mjs | 14 +- server/scripts/size-baseline.json | 1 - server/src/db/dialect/kysely-functions.ts | 233 ++++++++++++++ server/src/db/dialect/platform.ts | 18 ++ server/src/db/dialect/sql-functions.ts | 294 +++--------------- server/src/db/repositories/DemoRepository.ts | 2 +- .../DocumentSyncItems.repository.ts | 3 +- .../repositories/JourneyPhotos.repository.ts | 2 +- .../PluginOauthTokens.repository.ts | 2 +- .../PushSubscriptions.repository.ts | 3 +- .../repositories/Reservations.repository.ts | 5 +- .../db/repositories/ShareTokens.repository.ts | 2 +- .../unit/db/dialect/sql-functions.test.ts | 16 +- .../DocumentSyncItems.repository.test.ts | 2 +- .../PluginOauthTokens.repository.test.ts | 2 +- .../tests/unit/scripts/dialect-lint.test.ts | 1 + 17 files changed, 319 insertions(+), 287 deletions(-) create mode 100644 server/src/db/dialect/kysely-functions.ts create mode 100644 server/src/db/dialect/platform.ts diff --git a/server/CLAUDE.md b/server/CLAUDE.md index 6e4710867..40ee0758f 100644 --- a/server/CLAUDE.md +++ b/server/CLAUDE.md @@ -35,7 +35,7 @@ Single test: `npx vitest run tests/unit/nest/weather.controller.test.ts`, or `np **Build emits even with type errors** (`scripts/build.mjs` catches `tsc` failures and warns). `npm run build` succeeding does **not** mean the code typechecks — run `npm run typecheck`. -**`lint:dialect`** (`scripts/dialect-lint.mjs`) reads every string and template literal under `src/` (comments do not count) and every `.insertId` read, and counts the SQLite-only spellings per file and rule: `INSERT OR IGNORE`/`REPLACE`, `datetime()`/`julianday()`/`unixepoch()` (also as the bare name handed to `eb.fn`), `strftime`, `json_extract` and its siblings, `GLOB`, `last_insert_rowid`, `AUTOINCREMENT`, a `PRAGMA` statement outside the `src/db/*.ts` lifecycle files and the migrations, and `||` concatenation in SQL. The counts are held to `scripts/dialect-baseline.json`; a new hit fails, and so does an entry above what its file holds now, so the change that removes one runs `npm run lint:dialect -- --update` (it never raises or adds an entry). `src/db/dialect/sql-functions.ts` is not scanned, and neither are the migrations up to `FROZEN_MIGRATIONS_THROUGH` in the script; a newer migration is held to the DML rules, while its DDL stays engine specific. +**`lint:dialect`** (`scripts/dialect-lint.mjs`) reads every string and template literal under `src/` (comments do not count) and every `.insertId` read, and counts the SQLite-only spellings per file and rule: `INSERT OR IGNORE`/`REPLACE`, `datetime()`/`julianday()`/`unixepoch()` (also as the bare name handed to `eb.fn`), `strftime`, `json_extract` and its siblings, `GLOB`, `last_insert_rowid`, `AUTOINCREMENT`, a `PRAGMA` statement outside the `src/db/*.ts` lifecycle files and the migrations, and `||` concatenation in SQL. The counts are held to `scripts/dialect-baseline.json`; a new hit fails, and so does an entry above what its file holds now, so the change that removes one runs `npm run lint:dialect -- --update` (it never raises or adds an entry). The dialect layer `src/db/dialect/` is not scanned, and neither are the migrations up to `FROZEN_MIGRATIONS_THROUGH` in the script; a newer migration is held to the DML rules, while its DDL stays engine specific. ## Architecture invariants @@ -68,11 +68,11 @@ SQLite is the engine today and Postgres is the planned second one. Code under `s - **Build statements, don't spell them.** Use the MikroORM QueryBuilder or entity methods, or `this.kysely>()` on the generated table types. Repositories and seeders may not hold SQL text at all (ESLint), and `lint:dialect` holds every other file to its baseline. - **Insert or ignore / upsert**: `.onConflict((oc) => oc.columns([...]).doNothing())` or `.doUpdateSet({...})`, or `em.upsert`. Name the conflict target where there is one. Never `INSERT OR IGNORE`/`INSERT OR REPLACE`. - **The new id**: `.returning('id').executeTakeFirstOrThrow()`. Never `InsertResult.insertId` or `last_insert_rowid()`; both are SQLite's rowid and undefined on Postgres. -- **Time**: `currentTimestamp`/`currentTimestampKysely`, `nowMinusDays`, `nowMinusHours`, `nowPlusSeconds`/`nowPlusSecondsKysely`, `nowDateOffset`, `dateOf`, `dateAdd`, `unixEpochToIsoKysely` from `src/db/dialect/sql-functions.ts`. Never `datetime('now')`, `strftime` or `julianday`. +- **Time**: `currentTimestamp`/`currentTimestampKysely`, `nowMinusDays`, `nowMinusHours`, `nowPlusSeconds`/`nowPlusSecondsKysely`, `nowDateOffset`, `dateOf`, `dateAdd`, `unixEpochToIsoKysely` from `src/db/dialect/sql-functions.ts` (the MikroORM `raw()` helpers) and `src/db/dialect/kysely-functions.ts` (their Kysely-expression twins). Never `datetime('now')`, `strftime` or `julianday`. - **Strings and casts**: `concat`/`concatKysely` instead of `||`, `substring`/`substringKysely`, `lower`/`lowerTrim`, `collateNoCase`, `castInteger`/`castIntegerKysely`, and `startsWithIsoDate`/`startsWithIsoDateKysely` instead of `GLOB`. - **JSON columns** are read whole and parsed in the service; no `json_extract` in SQL. - **PRAGMA** belongs to the `src/db/` lifecycle files (`database.ts`, `connection.ts`, `durability.ts`, the migrations). `MaintenanceRepository` is the baselined SQLite maintenance adapter (`wal_checkpoint`, `VACUUM INTO`). -- **A missing helper** goes into `sql-functions.ts`, dispatching on the live platform: a SQLite branch now, `unsupported(platform)` for the rest until the second engine lands. That file is the only one allowed to spell an engine's own SQL. +- **A missing helper** goes into `sql-functions.ts` (or `kysely-functions.ts` for a Kysely expression), dispatching on the live platform through `src/db/dialect/platform.ts`: a SQLite branch now, `unsupported(platform)` for the rest until the second engine lands. `src/db/dialect/` is the only place allowed to spell an engine's own SQL. - **Migrations** that have shipped are frozen as they are. A new migration's data statements follow the rules above; its DDL is written for the engine it runs on. - **Storage model**: the generated Kysely types describe what SQLite stores (0/1 integers for flags, TEXT timestamps, JSON in TEXT). Convert at the service boundary, as the contracts already require. - **MySQL/MariaDB are out of scope.** The repositories rely on `INSERT ... ON CONFLICT` (Kysely's `onConflict`, often a target-less `doNothing()`) and on `RETURNING`, and MySQL has neither: it would need an insert-ignore/upsert wrapper in the dialect layer and a different way to read new ids before it could be considered. diff --git a/server/scripts/dialect-lint.mjs b/server/scripts/dialect-lint.mjs index 75388ca8f..c8933d735 100644 --- a/server/scripts/dialect-lint.mjs +++ b/server/scripts/dialect-lint.mjs @@ -7,9 +7,9 @@ * INSERT OR IGNORE, datetime('now'), strftime, json_extract, GLOB, * last_insert_rowid, PRAGMA, AUTOINCREMENT and `||` string concatenation. * Each of them has a dialect-neutral form: the query builder's onConflict(), - * returning('id'), or a helper in src/db/dialect/sql-functions.ts, which - * dispatches on the live platform and is the one file allowed to spell the - * SQLite forms. + * returning('id'), or a helper in src/db/dialect/ (sql-functions.ts and its + * Kysely twin kysely-functions.ts), which dispatches on the live platform + * and is the one place allowed to spell an engine's own forms. * * The check reads every string and template literal under src/ (comments * never count) and every `.insertId` read, counts the hits per file and rule, @@ -17,7 +17,7 @@ * does a baseline entry above what its file holds now, so the change that * removes one lowers the baseline with --update in the same commit. * - * Not scanned: src/db/dialect/sql-functions.ts (the dialect layer itself) and + * Not scanned: src/db/dialect/ (the dialect layer itself) and * the migrations that have shipped (append-only, never edited again; the last * one is FROZEN_MIGRATIONS_THROUGH). A newer migration is scanned for the * DML rules; its DDL may still be engine specific. PRAGMA is allowed in the @@ -40,8 +40,8 @@ const ts = require('typescript'); /** The last migration that shipped before this check existed. Later ones are scanned. */ export const FROZEN_MIGRATIONS_THROUGH = 'Migration20200101042400'; -/** The dialect layer: the one file that may spell SQLite's own SQL. */ -const DIALECT_LAYER = 'src/db/dialect/sql-functions.ts'; +/** The dialect layer: the one place that may spell an engine's own SQL. */ +const DIALECT_LAYER = 'src/db/dialect/'; const SQL_KEYWORDS = /\b(SELECT|UPDATE|INSERT|DELETE|WHERE|SET|CASE|WHEN|COALESCE|CAST|VALUES|FROM)\b/i; @@ -117,7 +117,7 @@ const TEST = /\.(?:test|spec)\./; /** 'skip', 'migration' (a newer one, DML rules only) or 'source'. */ export function classify(file) { - if (file === DIALECT_LAYER) return 'skip'; + if (file.startsWith(DIALECT_LAYER)) return 'skip'; const migration = /^src\/db\/migrations\/(Migration\d+)_/.exec(file); if (migration) return migration[1] <= FROZEN_MIGRATIONS_THROUGH ? 'skip' : 'migration'; if (file.startsWith('src/db/migrations/')) return 'skip'; diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index a4899be30..b808ba761 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -1,7 +1,6 @@ { "scripts/db-call-graph.mjs": 1036, "scripts/generate-entities.ts": 2259, - "src/db/dialect/sql-functions.ts": 1007, "src/db/repositories/Places.repository.ts": 1440, "src/db/repositories/Reservations.repository.ts": 1676, "src/db/repositories/Trips.repository.ts": 1121, diff --git a/server/src/db/dialect/kysely-functions.ts b/server/src/db/dialect/kysely-functions.ts new file mode 100644 index 000000000..e2689116c --- /dev/null +++ b/server/src/db/dialect/kysely-functions.ts @@ -0,0 +1,233 @@ +import type { Platform } from '@mikro-orm/core'; +import { sql, type Expression, type ExpressionBuilder, type ExpressionWrapper, type RawBuilder, type ReferenceExpression, type SqlBool, type StringReference } from 'kysely'; +import { isSqlite, unsupported } from './platform'; + +/** + * The Kysely-expression half of the dialect layer: the twins of the MikroORM + * `raw()` helpers in `sql-functions.ts`, for statements built with + * `this.kysely<...>()`. Same contract as that file: every helper takes the + * live MikroORM `Platform`, dispatches on it at runtime and fails closed on a + * platform it does not know. Values are bound or validated, never spliced in. + */ + +// --------------------------------------------------------------------------- +// Plan 3d Task 0 review (H1/L1) — the helpers in `sql-functions.ts` return a +// MikroORM `RawQueryFragment`. Handed into a Kysely statement, a `RawQueryFragment` +// stringifies through its own `[Symbol.toPrimitive]('string')` coercion into +// the literal text `?` (its parameter-placeholder marker, meant for the +// MikroORM QueryBuilder's OWN parameter interpolation, not Kysely's) — Kysely +// binds it as an actual `?` value parameter and the statement fails at +// execution (verified directly, not assumed: `db.selectFrom(...).where(..., +// startsWithIsoDate(platform, 'col'))` throws `SqliteError: near "?": syntax +// error` the first time it runs). Task 2 absorbed this finding (its report, +// H1/L1) — these are genuinely separate functions, not a wrapper over the +// ones above, because a Kysely `Expression` and a MikroORM `RawQueryFragment` +// are different types with no conversion between them. Each takes the +// caller's own `ExpressionBuilder` (the same "no consumer-facing +// generic DB" shape `_shared/reservation-visibility.ts`'s `publicStayExists` +// documents is the only one that survives `tsc` for a shared Kysely helper — +// unlike that one, these ARE fully generic over ``, because they only +// ever call `eb.fn`/`eb.cast`/`eb(...)`, none of which hit the QueryBuilder +// method-chaining inference limit that forced `publicStayExists` to fix its +// shape). Platform-dispatched and fail-closed like every helper in +// `sql-functions.ts`; each has an SQLF-0xx test pinning its compiled +// `{sql, parameters}` AND a raw-statement equivalence on seeded rows +// (`tests/unit/db/dialect/sql-functions.test.ts`). +// --------------------------------------------------------------------------- + +/** + * The Kysely-expression twin of {@link startsWithIsoDate}: ` GLOB + * '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`, spelled through SQLite's + * function form (`glob(X, Y)` is exactly `Y GLOB X` — the inventory's own + * §19 finding, since Kysely's `ComparisonOperator` union has no `GLOB` + * entry). Returns a boolean `Expression`, usable in a `.where()` + * or inside a `CASE WHEN` condition. Same digit-class pattern as the + * MikroORM version — NOT the wider `'????-??-??*'` shorthand (a `?` in + * SQLite GLOB matches any character, letters included). + */ +export function startsWithIsoDateKysely( + platform: Platform, + eb: ExpressionBuilder, + ref: ReferenceExpression, +): ExpressionWrapper { + if (isSqlite(platform)) { + return eb.fn('glob', [eb.val('[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'), ref]); + } + return unsupported(platform); +} + +/** + * The Kysely-expression twin of {@link substring}: `substr(, + * [, ])`, 1-based on both ends. `start`/`length` are + * validated integers, the same guard `substring()` above applies, and bound + * as genuine parameters here (`eb.val`) rather than spelled into the SQL + * text — Kysely's `fn()` takes `ReferenceExpression`s, not a raw text + * fragment, so there is no equivalent "spell a constant into the SQL" + * shape to match; a bound integer literal renders identically. + */ +export function substringKysely( + platform: Platform, + eb: ExpressionBuilder, + ref: ReferenceExpression, + start: number, + length?: number, +): ExpressionWrapper { + if (!Number.isInteger(start) || start < 1) { + throw new Error(`sql-functions: substringKysely needs a 1-based integer start, got ${start}`); + } + if (length !== undefined && (!Number.isInteger(length) || length < 0)) { + throw new Error(`sql-functions: substringKysely needs a non-negative integer length, got ${length}`); + } + if (isSqlite(platform)) { + const args: ReferenceExpression[] = length === undefined + ? [ref, eb.val(start)] + : [ref, eb.val(start), eb.val(length)]; + return eb.fn('substr', args); + } + return unsupported(platform); +} + +/** A part of a `concatKysely()` expression — a column reference, a bound value, or a nested Kysely `Expression` (composes freely, unlike `concat()`'s MikroORM `RawQueryFragment` form). */ +export type KyselyConcatPart = + | { column: StringReference } + | { value: string } + | { expression: Expression }; + +/** + * The Kysely-expression twin of {@link concat}: ` || || …`, + * SQLite's/Postgres's string concatenation operator, built through the + * expression builder's own binary-operator call (`eb(lhs, '||', rhs)`) so + * it composes with {@link substringKysely}/{@link castIntegerKysely} — + * exactly the composition `concat()`'s MikroORM form cannot do (its + * docstring explains why). + */ +export function concatKysely( + platform: Platform, + eb: ExpressionBuilder, + ...parts: readonly KyselyConcatPart[] +): ExpressionWrapper { + if (parts.length < 2) { + throw new Error(`sql-functions: concatKysely needs at least two parts, got ${parts.length}`); + } + if (!isSqlite(platform)) return unsupported(platform); + const operand = (part: KyselyConcatPart): Expression => + 'column' in part ? eb.ref(part.column).$castTo() : 'value' in part ? eb.val(part.value) : part.expression; + let acc: Expression = operand(parts[0]!); + for (const part of parts.slice(1)) { + acc = eb(acc, '||', operand(part)); + } + // The loop above always runs at least once (the `parts.length < 2` guard + // above throws otherwise), so `acc` is always the result of the `eb(...)` + // binary-operator call — a real `ExpressionWrapper`, not the bare + // `Expression` interface `operand()`'s own return type declares. + return acc as ExpressionWrapper; +} + +/** + * The Kysely-expression twin of {@link castInteger}: `CAST( AS + * INTEGER)`, for `reservations.accommodation_id` (TEXT) compared against an + * INTEGER column inside a Kysely statement (RS20/RV2's join shape — a + * correlated `EXISTS`/scalar-subquery context the MikroORM QueryBuilder + * cannot express, per the inventory's own T6 ruling). + */ +export function castIntegerKysely( + platform: Platform, + eb: ExpressionBuilder, + ref: ReferenceExpression, +): ExpressionWrapper { + if (isSqlite(platform)) return eb.cast(ref, 'integer'); + return unsupported(platform); +} + +// --------------------------------------------------------------------------- +// Plan 3g Task 0 (R1) — no consumer yet: Task 1 (`getJourneyFull`'s gallery +// read) and Task 3 (`getPublicJourney`'s gallery read) each fold this into +// their own rebuild of the legacy `GALLERY_CHRONOLOGICAL_ORDER` (tests/helpers/) +// text (a `COALESCE(NULLIF(tp.taken_at, ''), , +// )` ORDER BY, worked out in full in Task 0's report for both to paste +// in verbatim, neither re-deriving it). Added here, Kysely-only (no MikroORM +// `raw()` sibling): the shape it exists for is genuinely Kysely-only (a +// correlated scalar subquery cannot be expressed through the MikroORM +// QueryBuilder — the same "T6 ruling" `castIntegerKysely`'s own docstring +// cites for RS20/RV2), and nothing else in this plan's inventory needs a +// MikroORM-form epoch-to-ISO conversion (§6: "no other strftime/julianday +// sites found elsewhere in this cluster"). A raw twin can be added later, +// same as every other helper here, the moment a real consumer needs one. +// --------------------------------------------------------------------------- + +/** + * `strftime('%Y-%m-%dT%H:%M:%SZ', / 1000, 'unixepoch')` — the last of + * `GALLERY_CHRONOLOGICAL_ORDER`'s three fallback tiers (R1): when a gallery + * photo has neither a capture time (`tp.taken_at`) nor a linked entry to + * borrow a date from, the moment it was added is what is left to order by. + * `` is an epoch-MILLISECONDS column (`journey_photos.created_at`, like + * every other `*_at` epoch column in this codebase) — SQLite's `unixepoch` + * modifier expects whole SECONDS, so the division is load-bearing, not + * decorative, and matches the legacy text's own `gp.created_at / 1000` + * exactly. SQLite's `/` on two integers truncates instead of rounding; that + * sub-second loss is the legacy statement's own behaviour, preserved here + * rather than "fixed" into a float divide that would render a different ISO + * string for any timestamp not an exact multiple of 1000ms. + * + * Named for what it computes, not the SQL function it spells — matching + * every other `*Kysely` twin in this file (`castIntegerKysely`, not + * `castKysely`; `startsWithIsoDateKysely`, not `globKysely`). + */ +export function unixEpochToIsoKysely( + platform: Platform, + eb: ExpressionBuilder, + ref: ReferenceExpression, +): ExpressionWrapper { + if (isSqlite(platform)) { + const seconds = eb(ref, '/', eb.val(1000)); + return eb.fn('strftime', [eb.val('%Y-%m-%dT%H:%M:%SZ'), seconds, eb.val('unixepoch')]); + } + return unsupported(platform); +} + +/** + * The Kysely-expression twin of {@link nowPlusSeconds}: DS23/DS24's + * `ON CONFLICT ... DO UPDATE` / `INSERT ... VALUES` (R3) is a hand-typed + * Kysely statement — MikroORM's `em.upsert` cannot express a + * partial-unique-index conflict target (R3's own ruling) — so the + * `next_attempt_at` computation inside its `CASE WHEN` needs a Kysely + * `Expression`, not a MikroORM `RawQueryFragment` (SQLF-048: a + * `RawQueryFragment` throws when handed into a Kysely statement). Same + * validation, same always-non-negative-integer trust boundary as the + * MikroORM form in `sql-functions.ts`. + */ +export function nowPlusSecondsKysely( + platform: Platform, + eb: ExpressionBuilder, + seconds: number, +): ExpressionWrapper { + if (!Number.isInteger(seconds) || seconds < 0) { + throw new Error(`sql-functions: nowPlusSecondsKysely needs a non-negative integer second count, got ${seconds}`); + } + if (isSqlite(platform)) { + return eb.fn('datetime', [eb.val('now'), eb.val(`+${seconds} seconds`)]); + } + return unsupported(platform); +} + +/** + * The Kysely-expression twin of {@link currentTimestamp}: the bare + * `CURRENT_TIMESTAMP` keyword, for a value position inside a hand-typed + * Kysely statement (DS24's `ON CONFLICT ... DO UPDATE SET last_seen_at = + * CURRENT_TIMESTAMP` — R3's partial-index upsert). Verified directly against + * `better-sqlite3` that SQLite accepts the bare keyword (`SELECT + * CURRENT_TIMESTAMP`) but rejects it called as a function + * (`SELECT CURRENT_TIMESTAMP()` → `near "(": syntax error`), so + * `eb.fn('current_timestamp', [])` — every other helper in this file's + * usual Kysely shape — is not an option here; the whole point of a keyword + * literal is that it takes no parentheses. This is this file's one + * Kysely-side use of the `sql` template tag — confined here, the sanctioned + * escape hatch this file already is for every raw-SQL spelling in the + * codebase (the MikroORM helpers in `sql-functions.ts` use `raw()` for the + * identical reason), never inline in a repository (the TRAP list's "Kysely + * `sql` banned under repositories" is about repository FILES, not this one). + */ +export function currentTimestampKysely(platform: Platform): RawBuilder { + if (isSqlite(platform)) return sql`CURRENT_TIMESTAMP`; + return unsupported(platform); +} diff --git a/server/src/db/dialect/platform.ts b/server/src/db/dialect/platform.ts new file mode 100644 index 000000000..4ddc361ce --- /dev/null +++ b/server/src/db/dialect/platform.ts @@ -0,0 +1,18 @@ +import type { Platform } from '@mikro-orm/core'; +import { SqlitePlatform } from '@mikro-orm/sql'; + +/** + * Which engine a dialect helper is spelling for. + * + * Every helper in `sql-functions.ts` and `kysely-functions.ts` dispatches on + * the live MikroORM platform (`em.getPlatform()`). Anything the dialect layer + * has no spelling for fails closed through {@link unsupported} rather than + * guessing. + */ +export function isSqlite(platform: Platform): boolean { + return platform instanceof SqlitePlatform; +} + +export function unsupported(platform: Platform): never { + throw new Error(`sql-functions: no implementation for platform ${platform.constructor.name}`); +} diff --git a/server/src/db/dialect/sql-functions.ts b/server/src/db/dialect/sql-functions.ts index bf6a6498c..500a603f2 100644 --- a/server/src/db/dialect/sql-functions.ts +++ b/server/src/db/dialect/sql-functions.ts @@ -1,6 +1,5 @@ import { raw, type Platform, type RawQueryFragment } from '@mikro-orm/core'; -import { SqlitePlatform } from '@mikro-orm/sql'; -import { sql, type Expression, type ExpressionBuilder, type ExpressionWrapper, type RawBuilder, type ReferenceExpression, type SqlBool, type StringReference } from 'kysely'; +import { isSqlite, unsupported } from './platform'; /** * The only place a repository may spell a database function. @@ -12,6 +11,8 @@ import { sql, type Expression, type ExpressionBuilder, type ExpressionWrapper, t * runtime property of the live connection, not a build-time swap: when the * Postgres driver arrives this file grows a second branch and no repository * changes. An unknown platform fails closed rather than guessing a spelling. + * The Kysely-expression twins live in `kysely-functions.ts`, the platform + * checks in `platform.ts`. * * Values are never interpolated — the day count in `dateAdd` is checked to be * an integer before it is spelled. @@ -24,20 +25,16 @@ function column(ref: string): string { return ref; } -function unsupported(platform: Platform): never { - throw new Error(`sql-functions: no implementation for platform ${platform.constructor.name}`); -} - /** The calendar date (`YYYY-MM-DD`) of a timestamp column. */ export function dateOf(platform: Platform, ref: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`date(${column(ref)})`); + if (isSqlite(platform)) return raw(`date(${column(ref)})`); return unsupported(platform); } /** The timestamp column shifted by whole days, as a calendar date. */ export function dateAdd(platform: Platform, ref: string, days: number): RawQueryFragment { if (!Number.isInteger(days)) throw new Error(`sql-functions: dateAdd needs an integer day count, got ${days}`); - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { const sign = days < 0 ? '-' : '+'; return raw(`date(${column(ref)}, '${sign}${Math.abs(days)} days')`); } @@ -46,7 +43,7 @@ export function dateAdd(platform: Platform, ref: string, days: number): RawQuery /** The database clock, in the same text the column defaults produce. */ export function currentTimestamp(platform: Platform): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw('CURRENT_TIMESTAMP'); + if (isSqlite(platform)) return raw('CURRENT_TIMESTAMP'); return unsupported(platform); } @@ -60,7 +57,7 @@ export function currentTimestamp(platform: Platform): RawQueryFragment { * `no-restricted-syntax` rule for `src/db/repositories/**` can enforce. */ export function columnRef(platform: Platform, ref: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(column(ref)); + if (isSqlite(platform)) return raw(column(ref)); return unsupported(platform); } @@ -69,7 +66,7 @@ export function columnIncrementedBy(platform: Platform, ref: string, amount: num if (!Number.isInteger(amount)) { throw new Error(`sql-functions: columnIncrementedBy needs an integer amount, got ${amount}`); } - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { const sign = amount < 0 ? '-' : '+'; return raw(`${column(ref)} ${sign} ${Math.abs(amount)}`); } @@ -107,7 +104,7 @@ export function columnIncrementedBy(platform: Platform, ref: string, amount: num * helpers here are only ever used as VALUES, where that brand isn't needed. */ export function lower(platform: Platform, ref: string): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`LOWER(${column(ref)})`); + if (isSqlite(platform)) return raw(`LOWER(${column(ref)})`); return unsupported(platform); } @@ -124,7 +121,7 @@ export function lower(platform: Platform, ref: string): RawQueryFragment & symbo * the mixed-engine bug this helper exists to close. */ export function lowerParam(platform: Platform, value: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw('LOWER(?)', [value]); + if (isSqlite(platform)) return raw('LOWER(?)', [value]); return unsupported(platform); } @@ -154,7 +151,7 @@ export function nowMinusDays(platform: Platform, days: number): RawQueryFragment if (!Number.isInteger(days) || days < 0) { throw new Error(`sql-functions: nowMinusDays needs a non-negative integer day count, got ${days}`); } - if (platform instanceof SqlitePlatform) return raw(`datetime('now', '-${days} days')`); + if (isSqlite(platform)) return raw(`datetime('now', '-${days} days')`); return unsupported(platform); } @@ -170,7 +167,7 @@ export function nowMinusDays(platform: Platform, days: number): RawQueryFragment * `lowerTrim()` below for the composed shape. */ export function trim(platform: Platform, ref: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`TRIM(${column(ref)})`); + if (isSqlite(platform)) return raw(`TRIM(${column(ref)})`); return unsupported(platform); } @@ -184,7 +181,7 @@ export function trim(platform: Platform, ref: string): RawQueryFragment { * `TRIM()`. */ export function lowerTrim(platform: Platform, ref: string): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`LOWER(TRIM(${column(ref)}))`); + if (isSqlite(platform)) return raw(`LOWER(TRIM(${column(ref)}))`); return unsupported(platform); } @@ -205,7 +202,7 @@ export function lowerTrim(platform: Platform, ref: string): RawQueryFragment & s * are different shapes). */ export function coalesce(platform: Platform, ref: string, fallbackRef: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`COALESCE(${column(ref)}, ${column(fallbackRef)})`); + if (isSqlite(platform)) return raw(`COALESCE(${column(ref)}, ${column(fallbackRef)})`); return unsupported(platform); } @@ -226,7 +223,7 @@ export function coalesce(platform: Platform, ref: string, fallbackRef: string): * behaviour change (the function body is untouched). */ export function coalesceParam(platform: Platform, ref: string, value: string | number | null): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`COALESCE(${column(ref)}, ?)`, [value]); + if (isSqlite(platform)) return raw(`COALESCE(${column(ref)}, ?)`, [value]); return unsupported(platform); } @@ -250,7 +247,7 @@ export function coalesceParam(platform: Platform, ref: string, value: string | n * ?)` always preferred the non-null existing value). */ export function coalesceOverride(platform: Platform, value: string | number | null, ref: string): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`COALESCE(?, ${column(ref)})`, [value]); + if (isSqlite(platform)) return raw(`COALESCE(?, ${column(ref)})`, [value]); return unsupported(platform); } @@ -265,7 +262,7 @@ export function coalesceOverride(platform: Platform, value: string | number | nu * brand only lives on that typing for values meant to be used as a key. */ export function absDifference(platform: Platform, ref: string, value: number): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`ABS(${column(ref)} - ?)`, [value]); + if (isSqlite(platform)) return raw(`ABS(${column(ref)} - ?)`, [value]); return unsupported(platform); } @@ -286,19 +283,19 @@ function alias(name: string): string { /** `COUNT(*) as `, for a single-row totals read or a `GROUP BY` count column. */ export function countAll(platform: Platform, aliasName: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`COUNT(*) as ${alias(aliasName)}`); + if (isSqlite(platform)) return raw(`COUNT(*) as ${alias(aliasName)}`); return unsupported(platform); } /** `MIN() as `. */ export function minOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`MIN(${column(ref)}) as ${alias(aliasName)}`); + if (isSqlite(platform)) return raw(`MIN(${column(ref)}) as ${alias(aliasName)}`); return unsupported(platform); } /** `MAX() as `. */ export function maxOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`MAX(${column(ref)}) as ${alias(aliasName)}`); + if (isSqlite(platform)) return raw(`MAX(${column(ref)}) as ${alias(aliasName)}`); return unsupported(platform); } @@ -328,7 +325,7 @@ export function maxOf(platform: Platform, ref: string, aliasName: string): RawQu * non-finite `value` before calling.) */ export function caseWhenEquals(platform: Platform, ref: string, value: number, whenTrue: string, whenFalse: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`CASE WHEN ${column(ref)} = ? THEN ? ELSE ? END`, [value, whenTrue, whenFalse]); + if (isSqlite(platform)) return raw(`CASE WHEN ${column(ref)} = ? THEN ? ELSE ? END`, [value, whenTrue, whenFalse]); return unsupported(platform); } @@ -352,7 +349,7 @@ export function caseWhenEquals(platform: Platform, ref: string, value: number, w * `.orderBy({ [countAllRef(platform)]: 'desc' })`. */ export function countAllRef(platform: Platform): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw('COUNT(*)'); + if (isSqlite(platform)) return raw('COUNT(*)'); return unsupported(platform); } @@ -388,7 +385,7 @@ export function countAllRef(platform: Platform): RawQueryFragment & symbol { * for this shape until a second platform is added. */ export function startsWithIsoDate(platform: Platform, ref: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { return raw(`${column(ref)} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`); } return unsupported(platform); @@ -416,7 +413,7 @@ export function substring(platform: Platform, ref: string, start: number, length if (length !== undefined && (!Number.isInteger(length) || length < 0)) { throw new Error(`sql-functions: substring needs a non-negative integer length, got ${length}`); } - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { if (length === undefined) return raw(`substr(${column(ref)}, ${start})`); return raw(`substr(${column(ref)}, ${start}, ${length})`); } @@ -462,7 +459,7 @@ export function concat(platform: Platform, ...parts: readonly ConcatPart[]): Raw if (parts.length < 2) { throw new Error(`sql-functions: concat needs at least two parts, got ${parts.length}`); } - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { const bindings: string[] = []; const sql = parts .map((part) => { @@ -498,7 +495,7 @@ export function concat(platform: Platform, ...parts: readonly ConcatPart[]): Raw * precedent) for a caller that only needs the cast INTEGER value itself. */ export function castInteger(platform: Platform, ref: string): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`CAST(${column(ref)} AS INTEGER)`); + if (isSqlite(platform)) return raw(`CAST(${column(ref)} AS INTEGER)`); return unsupported(platform); } @@ -521,135 +518,7 @@ export function castInteger(platform: Platform, ref: string): RawQueryFragment & * comment documents; ordering by the EXPRESSION itself is what works). */ export function dayDistance(platform: Platform, ref: string, isoDate: string): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]); - return unsupported(platform); -} - -// --------------------------------------------------------------------------- -// Plan 3d Task 0 review (H1/L1) — the five helpers above return a MikroORM -// `RawQueryFragment`. Handed into a Kysely statement, a `RawQueryFragment` -// stringifies through its own `[Symbol.toPrimitive]('string')` coercion into -// the literal text `?` (its parameter-placeholder marker, meant for the -// MikroORM QueryBuilder's OWN parameter interpolation, not Kysely's) — Kysely -// binds it as an actual `?` value parameter and the statement fails at -// execution (verified directly, not assumed: `db.selectFrom(...).where(..., -// startsWithIsoDate(platform, 'col'))` throws `SqliteError: near "?": syntax -// error` the first time it runs). Task 2 absorbed this finding (its report, -// H1/L1) — these are genuinely separate functions, not a wrapper over the -// ones above, because a Kysely `Expression` and a MikroORM `RawQueryFragment` -// are different types with no conversion between them. Each takes the -// caller's own `ExpressionBuilder` (the same "no consumer-facing -// generic DB" shape `_shared/reservation-visibility.ts`'s `publicStayExists` -// documents is the only one that survives `tsc` for a shared Kysely helper — -// unlike that one, these ARE fully generic over ``, because they only -// ever call `eb.fn`/`eb.cast`/`eb(...)`, none of which hit the QueryBuilder -// method-chaining inference limit that forced `publicStayExists` to fix its -// shape). Platform-dispatched and fail-closed like every helper above; each -// has an SQLF-0xx test pinning its compiled `{sql, parameters}` AND a -// raw-statement equivalence on seeded rows (`tests/unit/db/dialect/sql-functions.test.ts`). -// --------------------------------------------------------------------------- - -/** - * The Kysely-expression twin of {@link startsWithIsoDate}: ` GLOB - * '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`, spelled through SQLite's - * function form (`glob(X, Y)` is exactly `Y GLOB X` — the inventory's own - * §19 finding, since Kysely's `ComparisonOperator` union has no `GLOB` - * entry). Returns a boolean `Expression`, usable in a `.where()` - * or inside a `CASE WHEN` condition. Same digit-class pattern as the - * MikroORM version — NOT the wider `'????-??-??*'` shorthand (a `?` in - * SQLite GLOB matches any character, letters included). - */ -export function startsWithIsoDateKysely( - platform: Platform, - eb: ExpressionBuilder, - ref: ReferenceExpression, -): ExpressionWrapper { - if (platform instanceof SqlitePlatform) { - return eb.fn('glob', [eb.val('[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'), ref]); - } - return unsupported(platform); -} - -/** - * The Kysely-expression twin of {@link substring}: `substr(, - * [, ])`, 1-based on both ends. `start`/`length` are - * validated integers, the same guard `substring()` above applies, and bound - * as genuine parameters here (`eb.val`) rather than spelled into the SQL - * text — Kysely's `fn()` takes `ReferenceExpression`s, not a raw text - * fragment, so there is no equivalent "spell a constant into the SQL" - * shape to match; a bound integer literal renders identically. - */ -export function substringKysely( - platform: Platform, - eb: ExpressionBuilder, - ref: ReferenceExpression, - start: number, - length?: number, -): ExpressionWrapper { - if (!Number.isInteger(start) || start < 1) { - throw new Error(`sql-functions: substringKysely needs a 1-based integer start, got ${start}`); - } - if (length !== undefined && (!Number.isInteger(length) || length < 0)) { - throw new Error(`sql-functions: substringKysely needs a non-negative integer length, got ${length}`); - } - if (platform instanceof SqlitePlatform) { - const args: ReferenceExpression[] = length === undefined - ? [ref, eb.val(start)] - : [ref, eb.val(start), eb.val(length)]; - return eb.fn('substr', args); - } - return unsupported(platform); -} - -/** A part of a `concatKysely()` expression — a column reference, a bound value, or a nested Kysely `Expression` (composes freely, unlike `concat()`'s MikroORM `RawQueryFragment` form). */ -export type KyselyConcatPart = - | { column: StringReference } - | { value: string } - | { expression: Expression }; - -/** - * The Kysely-expression twin of {@link concat}: ` || || …`, - * SQLite's/Postgres's string concatenation operator, built through the - * expression builder's own binary-operator call (`eb(lhs, '||', rhs)`) so - * it composes with {@link substringKysely}/{@link castIntegerKysely} — - * exactly the composition `concat()`'s MikroORM form cannot do (its - * docstring explains why). - */ -export function concatKysely( - platform: Platform, - eb: ExpressionBuilder, - ...parts: readonly KyselyConcatPart[] -): ExpressionWrapper { - if (parts.length < 2) { - throw new Error(`sql-functions: concatKysely needs at least two parts, got ${parts.length}`); - } - if (!(platform instanceof SqlitePlatform)) return unsupported(platform); - const operand = (part: KyselyConcatPart): Expression => - 'column' in part ? eb.ref(part.column).$castTo() : 'value' in part ? eb.val(part.value) : part.expression; - let acc: Expression = operand(parts[0]!); - for (const part of parts.slice(1)) { - acc = eb(acc, '||', operand(part)); - } - // The loop above always runs at least once (the `parts.length < 2` guard - // above throws otherwise), so `acc` is always the result of the `eb(...)` - // binary-operator call — a real `ExpressionWrapper`, not the bare - // `Expression` interface `operand()`'s own return type declares. - return acc as ExpressionWrapper; -} - -/** - * The Kysely-expression twin of {@link castInteger}: `CAST( AS - * INTEGER)`, for `reservations.accommodation_id` (TEXT) compared against an - * INTEGER column inside a Kysely statement (RS20/RV2's join shape — a - * correlated `EXISTS`/scalar-subquery context the MikroORM QueryBuilder - * cannot express, per the inventory's own T6 ruling). - */ -export function castIntegerKysely( - platform: Platform, - eb: ExpressionBuilder, - ref: ReferenceExpression, -): ExpressionWrapper { - if (platform instanceof SqlitePlatform) return eb.cast(ref, 'integer'); + if (isSqlite(platform)) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]); return unsupported(platform); } @@ -694,7 +563,7 @@ export function castIntegerKysely( * difference between the two shapes. */ export function collateNoCase(platform: Platform, ref: string): RawQueryFragment & symbol { - if (platform instanceof SqlitePlatform) return raw(`${column(ref)} COLLATE NOCASE`); + if (isSqlite(platform)) return raw(`${column(ref)} COLLATE NOCASE`); return unsupported(platform); } @@ -712,7 +581,7 @@ export function nowMinusHours(platform: Platform, hours: number): RawQueryFragme if (!Number.isInteger(hours) || hours < 0) { throw new Error(`sql-functions: nowMinusHours needs a non-negative integer hour count, got ${hours}`); } - if (platform instanceof SqlitePlatform) return raw(`datetime('now', '-${hours} hours')`); + if (isSqlite(platform)) return raw(`datetime('now', '-${hours} hours')`); return unsupported(platform); } @@ -729,53 +598,7 @@ export function nowMinusHours(platform: Platform, hours: number): RawQueryFragme * rule 18: mixing engines is the bug this pairing exists to avoid). */ export function lowerTrimParam(platform: Platform, value: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw('LOWER(TRIM(?))', [value]); - return unsupported(platform); -} - -// --------------------------------------------------------------------------- -// Plan 3g Task 0 (R1) — no consumer yet: Task 1 (`getJourneyFull`'s gallery -// read) and Task 3 (`getPublicJourney`'s gallery read) each fold this into -// their own rebuild of the legacy `GALLERY_CHRONOLOGICAL_ORDER` (tests/helpers/) -// text (a `COALESCE(NULLIF(tp.taken_at, ''), , -// )` ORDER BY, worked out in full in Task 0's report for both to paste -// in verbatim, neither re-deriving it). Added here, Kysely-only (no MikroORM -// `raw()` sibling): the shape it exists for is genuinely Kysely-only (a -// correlated scalar subquery cannot be expressed through the MikroORM -// QueryBuilder — the same "T6 ruling" `castIntegerKysely`'s own docstring -// cites for RS20/RV2), and nothing else in this plan's inventory needs a -// MikroORM-form epoch-to-ISO conversion (§6: "no other strftime/julianday -// sites found elsewhere in this cluster"). A raw twin can be added later, -// same as every other helper here, the moment a real consumer needs one. -// --------------------------------------------------------------------------- - -/** - * `strftime('%Y-%m-%dT%H:%M:%SZ', / 1000, 'unixepoch')` — the last of - * `GALLERY_CHRONOLOGICAL_ORDER`'s three fallback tiers (R1): when a gallery - * photo has neither a capture time (`tp.taken_at`) nor a linked entry to - * borrow a date from, the moment it was added is what is left to order by. - * `` is an epoch-MILLISECONDS column (`journey_photos.created_at`, like - * every other `*_at` epoch column in this codebase) — SQLite's `unixepoch` - * modifier expects whole SECONDS, so the division is load-bearing, not - * decorative, and matches the legacy text's own `gp.created_at / 1000` - * exactly. SQLite's `/` on two integers truncates instead of rounding; that - * sub-second loss is the legacy statement's own behaviour, preserved here - * rather than "fixed" into a float divide that would render a different ISO - * string for any timestamp not an exact multiple of 1000ms. - * - * Named for what it computes, not the SQL function it spells — matching - * every other `*Kysely` twin in this file (`castIntegerKysely`, not - * `castKysely`; `startsWithIsoDateKysely`, not `globKysely`). - */ -export function unixEpochToIsoKysely( - platform: Platform, - eb: ExpressionBuilder, - ref: ReferenceExpression, -): ExpressionWrapper { - if (platform instanceof SqlitePlatform) { - const seconds = eb(ref, '/', eb.val(1000)); - return eb.fn('strftime', [eb.val('%Y-%m-%dT%H:%M:%SZ'), seconds, eb.val('unixepoch')]); - } + if (isSqlite(platform)) return raw('LOWER(TRIM(?))', [value]); return unsupported(platform); } @@ -837,7 +660,7 @@ export function nowDateOffset(platform: Platform, days: number): RawQueryFragmen if (!Number.isInteger(days)) { throw new Error(`sql-functions: nowDateOffset needs an integer day count, got ${days}`); } - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { const sign = days < 0 ? '-' : '+'; return raw(`date('now', '${sign}${Math.abs(days)} days')`); } @@ -866,32 +689,7 @@ export function nowPlusSeconds(platform: Platform, seconds: number): RawQueryFra if (!Number.isInteger(seconds) || seconds < 0) { throw new Error(`sql-functions: nowPlusSeconds needs a non-negative integer second count, got ${seconds}`); } - if (platform instanceof SqlitePlatform) return raw(`datetime('now', '+${seconds} seconds')`); - return unsupported(platform); -} - -/** - * The Kysely-expression twin of {@link nowPlusSeconds}: DS23/DS24's - * `ON CONFLICT ... DO UPDATE` / `INSERT ... VALUES` (R3) is a hand-typed - * Kysely statement — MikroORM's `em.upsert` cannot express a - * partial-unique-index conflict target (R3's own ruling) — so the - * `next_attempt_at` computation inside its `CASE WHEN` needs a Kysely - * `Expression`, not a MikroORM `RawQueryFragment` (SQLF-048: a - * `RawQueryFragment` throws when handed into a Kysely statement). Same - * validation, same always-non-negative-integer trust boundary as the - * MikroORM form above. - */ -export function nowPlusSecondsKysely( - platform: Platform, - eb: ExpressionBuilder, - seconds: number, -): ExpressionWrapper { - if (!Number.isInteger(seconds) || seconds < 0) { - throw new Error(`sql-functions: nowPlusSecondsKysely needs a non-negative integer second count, got ${seconds}`); - } - if (platform instanceof SqlitePlatform) { - return eb.fn('datetime', [eb.val('now'), eb.val(`+${seconds} seconds`)]); - } + if (isSqlite(platform)) return raw(`datetime('now', '+${seconds} seconds')`); return unsupported(platform); } @@ -922,7 +720,7 @@ export function nowPlusSecondsKysely( * part of this fragment — the caller sets it alongside). */ export function foundAgainState(platform: Platform, stateRef: string, fileIdRef: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { return raw( `CASE WHEN ${column(stateRef)} = 'remote_missing' AND ${column(fileIdRef)} IS NOT NULL THEN 'synced' ELSE ${column(stateRef)} END`, ); @@ -930,28 +728,6 @@ export function foundAgainState(platform: Platform, stateRef: string, fileIdRef: return unsupported(platform); } -/** - * The Kysely-expression twin of {@link currentTimestamp}: the bare - * `CURRENT_TIMESTAMP` keyword, for a value position inside a hand-typed - * Kysely statement (DS24's `ON CONFLICT ... DO UPDATE SET last_seen_at = - * CURRENT_TIMESTAMP` — R3's partial-index upsert). Verified directly against - * `better-sqlite3` that SQLite accepts the bare keyword (`SELECT - * CURRENT_TIMESTAMP`) but rejects it called as a function - * (`SELECT CURRENT_TIMESTAMP()` → `near "(": syntax error`), so - * `eb.fn('current_timestamp', [])` — every other helper in this file's - * usual Kysely shape — is not an option here; the whole point of a keyword - * literal is that it takes no parentheses. This is this file's one - * Kysely-side use of the `sql` template tag — confined here, the sanctioned - * escape hatch this file already is for every raw-SQL spelling in the - * codebase (the MikroORM helpers above use `raw()` for the identical - * reason), never inline in a repository (the TRAP list's "Kysely `sql` - * banned under repositories" is about repository FILES, not this one). - */ -export function currentTimestampKysely(platform: Platform): RawBuilder { - if (platform instanceof SqlitePlatform) return sql`CURRENT_TIMESTAMP`; - return unsupported(platform); -} - // --------------------------------------------------------------------------- // `UsersRepository.setImmichSettings` (IM4, #2475): the self-signed switch is // trusted for ONE server, so whether a null incoming value may keep the stored @@ -973,7 +749,7 @@ export function currentTimestampKysely(platform: Platform): RawBuilder { * the fragment has two value slots and `raw()` binds positionally. */ export function coalesceOverrideWhileSame(platform: Platform, value: number | null, ref: string, keyRef: string, keyValue: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) { + if (isSqlite(platform)) { return raw(`CASE WHEN ${column(keyRef)} IS ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`, [keyValue, value, value]); } return unsupported(platform); @@ -992,6 +768,6 @@ export function coalesceOverrideWhileSame(platform: Platform, value: number | nu * ELSE is deliberate: a null test column yields SQL NULL. */ export function caseWhenNotNull(platform: Platform, testRef: string, thenRef: string): RawQueryFragment { - if (platform instanceof SqlitePlatform) return raw(`CASE WHEN ${column(testRef)} IS NOT NULL THEN ${column(thenRef)} END`); + if (isSqlite(platform)) return raw(`CASE WHEN ${column(testRef)} IS NOT NULL THEN ${column(thenRef)} END`); return unsupported(platform); } diff --git a/server/src/db/repositories/DemoRepository.ts b/server/src/db/repositories/DemoRepository.ts index 8a0628695..c36a7360e 100644 --- a/server/src/db/repositories/DemoRepository.ts +++ b/server/src/db/repositories/DemoRepository.ts @@ -4,7 +4,7 @@ import { Users } from '../entities/Users.entity'; import type { NewAdminUserRow } from './Users.repository'; import { AppSettings } from '../entities/AppSettings.entity'; import { Trips } from '../entities/Trips.entity'; -import { currentTimestampKysely } from '../dialect/sql-functions'; +import { currentTimestampKysely } from '../dialect/kysely-functions'; import type { DB } from '../kysely/db'; /** The tables the example-trip seed writes through Kysely. */ diff --git a/server/src/db/repositories/DocumentSyncItems.repository.ts b/server/src/db/repositories/DocumentSyncItems.repository.ts index c599c838c..703db5f45 100644 --- a/server/src/db/repositories/DocumentSyncItems.repository.ts +++ b/server/src/db/repositories/DocumentSyncItems.repository.ts @@ -1,5 +1,6 @@ import type { EntityData } from '@mikro-orm/core'; -import { coalesceOverride, currentTimestamp, currentTimestampKysely, foundAgainState, nowPlusSeconds, nowPlusSecondsKysely } from '../dialect/sql-functions'; +import { coalesceOverride, currentTimestamp, foundAgainState, nowPlusSeconds } from '../dialect/sql-functions'; +import { currentTimestampKysely, nowPlusSecondsKysely } from '../dialect/kysely-functions'; import type { DocumentSyncItems } from '../entities/DocumentSyncItems.entity'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; diff --git a/server/src/db/repositories/JourneyPhotos.repository.ts b/server/src/db/repositories/JourneyPhotos.repository.ts index 090935a29..baa31456b 100644 --- a/server/src/db/repositories/JourneyPhotos.repository.ts +++ b/server/src/db/repositories/JourneyPhotos.repository.ts @@ -2,7 +2,7 @@ import type { Platform } from '@mikro-orm/core'; import type { ExpressionBuilder } from 'kysely'; import type { GalleryPhoto } from '../../types'; import type { JourneyPhotos } from '../entities/JourneyPhotos.entity'; -import { concatKysely, unixEpochToIsoKysely } from '../dialect/sql-functions'; +import { concatKysely, unixEpochToIsoKysely } from '../dialect/kysely-functions'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; import type { DB } from '../kysely/db'; diff --git a/server/src/db/repositories/PluginOauthTokens.repository.ts b/server/src/db/repositories/PluginOauthTokens.repository.ts index a8ae9e662..94498a7b5 100644 --- a/server/src/db/repositories/PluginOauthTokens.repository.ts +++ b/server/src/db/repositories/PluginOauthTokens.repository.ts @@ -1,5 +1,5 @@ import type { PluginOauthTokens } from '../entities/PluginOauthTokens.entity'; -import { currentTimestampKysely } from '../dialect/sql-functions'; +import { currentTimestampKysely } from '../dialect/kysely-functions'; import { TrekRepository } from './_shared/trek-repository'; import type { DB } from '../kysely/db'; diff --git a/server/src/db/repositories/PushSubscriptions.repository.ts b/server/src/db/repositories/PushSubscriptions.repository.ts index 1a5d6c493..1dcb83a78 100644 --- a/server/src/db/repositories/PushSubscriptions.repository.ts +++ b/server/src/db/repositories/PushSubscriptions.repository.ts @@ -1,5 +1,6 @@ import type { PushSubscriptions } from '../entities/PushSubscriptions.entity'; -import { columnIncrementedBy, currentTimestamp, currentTimestampKysely } from '../dialect/sql-functions'; +import { columnIncrementedBy, currentTimestamp } from '../dialect/sql-functions'; +import { currentTimestampKysely } from '../dialect/kysely-functions'; import type { AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; import type { DB } from '../kysely/db'; diff --git a/server/src/db/repositories/Reservations.repository.ts b/server/src/db/repositories/Reservations.repository.ts index 5f6e3e980..c1b8abaff 100644 --- a/server/src/db/repositories/Reservations.repository.ts +++ b/server/src/db/repositories/Reservations.repository.ts @@ -1,7 +1,8 @@ import type { Reservations } from '../entities/Reservations.entity'; import { DayAssignments } from '../entities/DayAssignments.entity'; import { Days } from '../entities/Days.entity'; -import { castIntegerKysely, coalesceOverride, columnRef, concatKysely, dayDistance, startsWithIsoDateKysely, substringKysely } from '../dialect/sql-functions'; +import { coalesceOverride, columnRef, dayDistance } from '../dialect/sql-functions'; +import { castIntegerKysely, concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions'; import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility'; import type { DayAssignmentRow } from './DayAssignments.repository'; import { TrekRepository } from './_shared/trek-repository'; @@ -697,7 +698,7 @@ export class ReservationsRepository extends TrekRepository { * 11) END WHERE accommodation_id = :accId AND type = 'hotel'`. Kysely (the * `CASE WHEN … ELSE … || SUBSTR(...)` shape has no typed-filter * equivalent — the T6 tier per the inventory's own ruling), through - * `concatKysely`/`substringKysely` (`sql-functions.ts`'s Kysely-expression + * `concatKysely`/`substringKysely` (`kysely-functions.ts`, the Kysely-expression * twins of `concat`/`substring` — the MikroORM `RawQueryFragment` forms * render as a literal `?` token inside a Kysely statement and throw at * execution, Task 0 review H1). `accommodation_id` (TEXT) compared against diff --git a/server/src/db/repositories/ShareTokens.repository.ts b/server/src/db/repositories/ShareTokens.repository.ts index 5f248c8ba..9b37ed22d 100644 --- a/server/src/db/repositories/ShareTokens.repository.ts +++ b/server/src/db/repositories/ShareTokens.repository.ts @@ -1,5 +1,5 @@ import type { ShareTokens } from '../entities/ShareTokens.entity'; -import { currentTimestampKysely } from '../dialect/sql-functions'; +import { currentTimestampKysely } from '../dialect/kysely-functions'; import { TrekRepository } from './_shared/trek-repository'; import type { DB } from '../kysely/db'; diff --git a/server/tests/unit/db/dialect/sql-functions.test.ts b/server/tests/unit/db/dialect/sql-functions.test.ts index 14bceb2d9..4874523f6 100644 --- a/server/tests/unit/db/dialect/sql-functions.test.ts +++ b/server/tests/unit/db/dialect/sql-functions.test.ts @@ -11,7 +11,6 @@ import { caseWhenEquals, caseWhenNotNull, castInteger, - castIntegerKysely, coalesce, coalesceOverride, coalesceOverrideWhileSame, @@ -20,11 +19,9 @@ import { columnIncrementedBy, columnRef, concat, - concatKysely, countAll, countAllRef, currentTimestamp, - currentTimestampKysely, dateAdd, dateOf, dayDistance, @@ -39,14 +36,19 @@ import { nowMinusDays, nowMinusHours, nowPlusSeconds, - nowPlusSecondsKysely, startsWithIsoDate, - startsWithIsoDateKysely, substring, - substringKysely, trim, - unixEpochToIsoKysely, } from '../../../../src/db/dialect/sql-functions'; +import { + castIntegerKysely, + concatKysely, + currentTimestampKysely, + nowPlusSecondsKysely, + startsWithIsoDateKysely, + substringKysely, + unixEpochToIsoKysely, +} from '../../../../src/db/dialect/kysely-functions'; import { createJourney, createJourneyEntry } from '../../../helpers/factories'; /** The `users` columns the Kysely-expression tests below read/write, narrowed the same way every other Kysely-typed repository method in this program declares its own `TDB`. */ diff --git a/server/tests/unit/db/repositories/DocumentSyncItems.repository.test.ts b/server/tests/unit/db/repositories/DocumentSyncItems.repository.test.ts index af82d0cce..19ca6da29 100644 --- a/server/tests/unit/db/repositories/DocumentSyncItems.repository.test.ts +++ b/server/tests/unit/db/repositories/DocumentSyncItems.repository.test.ts @@ -12,7 +12,7 @@ import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; import { createTrip, createUser } from '../../../helpers/factories'; import { DocumentSyncItems } from '../../../../src/db/entities/DocumentSyncItems.entity'; import type { DocumentSyncItemsRepository } from '../../../../src/db/repositories/DocumentSyncItems.repository'; -import { currentTimestampKysely } from '../../../../src/db/dialect/sql-functions'; +import { currentTimestampKysely } from '../../../../src/db/dialect/kysely-functions'; const testDb = createSnapshotTestDb(); let t: TestOrm; diff --git a/server/tests/unit/db/repositories/PluginOauthTokens.repository.test.ts b/server/tests/unit/db/repositories/PluginOauthTokens.repository.test.ts index d32846be2..0e0faac01 100644 --- a/server/tests/unit/db/repositories/PluginOauthTokens.repository.test.ts +++ b/server/tests/unit/db/repositories/PluginOauthTokens.repository.test.ts @@ -16,7 +16,7 @@ import { resetTestDb } from '../../../helpers/test-db'; import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; import { PluginOauthTokens } from '../../../../src/db/entities/PluginOauthTokens.entity'; import type { PluginOauthTokensRepository } from '../../../../src/db/repositories/PluginOauthTokens.repository'; -import { currentTimestampKysely } from '../../../../src/db/dialect/sql-functions'; +import { currentTimestampKysely } from '../../../../src/db/dialect/kysely-functions'; const testDb = createSnapshotTestDb(); let t: TestOrm; diff --git a/server/tests/unit/scripts/dialect-lint.test.ts b/server/tests/unit/scripts/dialect-lint.test.ts index b024439fe..694292516 100644 --- a/server/tests/unit/scripts/dialect-lint.test.ts +++ b/server/tests/unit/scripts/dialect-lint.test.ts @@ -106,6 +106,7 @@ describe('dialect-lint.mjs', () => { it('DIALECT-004: never scans the dialect layer or a migration that has shipped', () => { const dir = serverRoot({ 'src/db/dialect/sql-functions.ts': "export const now = `datetime('now')`;\nexport const s = 'strftime';\n", + 'src/db/dialect/kysely-functions.ts': "export const g = 'glob';\nexport const s = 'strftime';\n", 'src/db/migrations/Migration20200101000000_baseline_schema.ts': "export const t = 'CREATE TABLE t (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT DEFAULT (datetime(\\'now\\')))';\n", });