style: format server and shared with prettier

A mechanical prettier --write over server/src, server/tests, server/scripts
and shared/src with the workspaces' .prettierrc; nothing but layout and
import order changes, and every file keeps the same set of imports. shared
is formatted throughout and its format baseline is empty. The server
baseline keeps the 35 files that Prettier would grow past their lint:size
limit (they need a split first, which is not a formatting change), and the
generated entity files stay as their generator writes them.
This commit is contained in:
Maurice
2026-10-10 21:23:37 +02:00
parent f4e518b2df
commit 724c88c201
1978 changed files with 78448 additions and 39347 deletions
+21 -6
View File
@@ -14,9 +14,7 @@
* method unprobeable: the report lists it instead of guessing, and the
* baseline's `uncovered` list must name it, so a new one fails the run.
*/
import path from 'node:path';
import ts from 'typescript';
export type Sample = { ok: true; value: unknown } | { ok: false; reason: string };
@@ -118,7 +116,13 @@ function sampleObjectType(checker: ts.TypeChecker, type: ts.ObjectType, name: st
return sampleObject(checker, type, name, depth);
}
function sampleCollection(checker: ts.TypeChecker, type: ts.ObjectType, kind: string, name: string, depth: number): Sample {
function sampleCollection(
checker: ts.TypeChecker,
type: ts.ObjectType,
kind: string,
name: string,
depth: number,
): Sample {
const args = checker.getTypeArguments(type as ts.TypeReference);
const samples = args.map((arg, i) => sampleFor(checker, arg, i === 0 ? singular(name) : name, depth + 1));
const failed = samples.find((sample) => !sample.ok);
@@ -152,7 +156,10 @@ function isPublicMethod(member: ts.ClassElement): member is ts.MethodDeclaration
}
/** The sample argument list for one method, or why there is none. */
export function planMethod(checker: ts.TypeChecker, method: ts.MethodDeclaration): { args: unknown[] } | { unprobeable: string } {
export function planMethod(
checker: ts.TypeChecker,
method: ts.MethodDeclaration,
): { args: unknown[] } | { unprobeable: string } {
const args: unknown[] = [];
for (const parameter of method.parameters) {
const name = ts.isIdentifier(parameter.name) ? parameter.name.text : 'options';
@@ -169,7 +176,11 @@ export function planMethod(checker: ts.TypeChecker, method: ts.MethodDeclaration
}
/** Every public method of every exported class declared in `files`, with its sample arguments. */
export function planRepositories(files: readonly string[], compilerOptions: ts.CompilerOptions, root: string): MethodPlan[] {
export function planRepositories(
files: readonly string[],
compilerOptions: ts.CompilerOptions,
root: string,
): MethodPlan[] {
const program = ts.createProgram({ rootNames: [...files], options: { ...compilerOptions, noEmit: true } });
const checker = program.getTypeChecker();
const wanted = new Set(files.map((file) => path.resolve(file)));
@@ -186,7 +197,11 @@ export function planRepositories(files: readonly string[], compilerOptions: ts.C
if (!isPublicMethod(member)) continue;
const method = (member.name as ts.Identifier).text;
const plan = planMethod(checker, member);
plans.push('args' in plan ? { className, file, method, args: plan.args } : { className, file, method, unprobeable: plan.unprobeable });
plans.push(
'args' in plan
? { className, file, method, args: plan.args }
: { className, file, method, unprobeable: plan.unprobeable },
);
}
}
}
+4 -3
View File
@@ -31,7 +31,6 @@
* measurement, written by `--update` or taken from the CI artifact, is
* committed.
*/
import { readFileSync } from 'node:fs';
export interface ProbeBaseline {
@@ -104,7 +103,8 @@ function parseFailing(failing: unknown, source: string): Record<string, number>
/** A missing `uncovered` key reads as unmeasured, so a baseline written before the list existed gets it seeded. */
function parseUncovered(uncovered: unknown, source: string): string[] | null {
if (uncovered === undefined || uncovered === null) return null;
if (!Array.isArray(uncovered)) throw new Error(`${source}: "uncovered" must be null or an array of Class.method names`);
if (!Array.isArray(uncovered))
throw new Error(`${source}: "uncovered" must be null or an array of Class.method names`);
const seen = new Set<string>();
for (const method of uncovered as unknown[]) {
if (typeof method !== 'string' || !METHOD_KEY.test(method)) {
@@ -169,7 +169,8 @@ export function lowerBaseline(
if (now > 0) next[method] = now;
}
}
const uncovered = baseline.uncovered === null ? [...uncoveredNow] : baseline.uncovered.filter((method) => uncoveredNow.has(method));
const uncovered =
baseline.uncovered === null ? [...uncoveredNow] : baseline.uncovered.filter((method) => uncoveredNow.has(method));
return {
failing: Object.fromEntries(Object.entries(next).sort(([a], [b]) => a.localeCompare(b))),
uncovered: [...new Set(uncovered)].sort((a, b) => a.localeCompare(b)),
+61 -19
View File
@@ -5,21 +5,34 @@
* SQLite database the helper cases are compared on, and the loop that calls
* every repository method.
*/
import path from 'node:path';
import { RequestContext, type Configuration, type EntityManager, type EntityProperty } from '@mikro-orm/core';
import { MikroORM, PostgreSqlConnection, PostgreSqlDriver, type Options } from '@mikro-orm/postgresql';
import { SqlitePlatform } from '@mikro-orm/sql';
import Database from 'better-sqlite3';
import { DummyDriver, Kysely, SqliteAdapter, SqliteIntrospector, SqliteQueryCompiler, type PostgresDialect } from 'kysely';
import { ALL_ENTITIES } from '../../src/db/entities';
import type { MethodPlan } from './arg-samples';
import { VALUES_TABLE, VALUES_TABLE_DDL, type HelperEngine, type KyselySelect, type RawSelect, type ValuesDB, type ValuesRow } from './helper-cases';
import {
VALUES_TABLE,
VALUES_TABLE_DDL,
type HelperEngine,
type KyselySelect,
type RawSelect,
type ValuesDB,
type ValuesRow,
} from './helper-cases';
import { ProbePostgresDialect, type StatementRecorder } from './recorder';
import type { MethodResult } from './report';
import { adjustColumns, NOCASE_COLLATION_SQL, splitStatements, type ColumnMeta } from './schema';
import { RequestContext, type Configuration, type EntityManager, type EntityProperty } from '@mikro-orm/core';
import { MikroORM, PostgreSqlConnection, PostgreSqlDriver, type Options } from '@mikro-orm/postgresql';
import { SqlitePlatform } from '@mikro-orm/sql';
import Database from 'better-sqlite3';
import {
DummyDriver,
Kysely,
SqliteAdapter,
SqliteIntrospector,
SqliteQueryCompiler,
type PostgresDialect,
} from 'kysely';
import path from 'node:path';
/** Marks a database the probe built, so a rerun may drop what it finds there and nothing else. */
const MARKER_TABLE = 'trek_pg_probe_marker';
@@ -42,9 +55,14 @@ export function connectSetupOrm(url: string): Promise<MikroORM> {
}
/** A Postgres driver whose Kysely dialect records every statement (see recorder.ts). */
export function createProbeDriverClass(recorder: StatementRecorder, statementTimeoutMs: number): typeof PostgreSqlDriver {
export function createProbeDriverClass(
recorder: StatementRecorder,
statementTimeoutMs: number,
): typeof PostgreSqlDriver {
class ProbeConnection extends PostgreSqlConnection {
override createKyselyDialect(overrides: Parameters<PostgreSqlConnection['createKyselyDialect']>[0]): PostgresDialect {
override createKyselyDialect(
overrides: Parameters<PostgreSqlConnection['createKyselyDialect']>[0],
): PostgresDialect {
return new ProbePostgresDialect(super.createKyselyDialect(overrides), recorder, statementTimeoutMs);
}
}
@@ -58,7 +76,11 @@ export function createProbeDriverClass(recorder: StatementRecorder, statementTim
};
}
export function connectProbeOrm(url: string, recorder: StatementRecorder, statementTimeoutMs: number): Promise<MikroORM> {
export function connectProbeOrm(
url: string,
recorder: StatementRecorder,
statementTimeoutMs: number,
): Promise<MikroORM> {
return MikroORM.init({ ...baseOptions(url), driver: createProbeDriverClass(recorder, statementTimeoutMs) });
}
@@ -74,7 +96,9 @@ async function resetDatabase(orm: MikroORM): Promise<void> {
);
const names = tables.map((row) => row.table_name);
if (names.length > 0 && !names.includes(MARKER_TABLE)) {
throw new Error(`refusing to run: the database holds ${names.length} table(s) the probe did not create. Point it at an empty database.`);
throw new Error(
`refusing to run: the database holds ${names.length} table(s) the probe did not create. Point it at an empty database.`,
);
}
if (names.length > 0) {
await connection.execute('drop schema public cascade');
@@ -89,7 +113,9 @@ export interface SchemaFailure {
}
/** Resets the database and builds the probe schema; returns the DDL statements Postgres refused. */
export async function prepareDatabase(orm: MikroORM): Promise<{ failures: SchemaFailure[]; adjusted: number; statements: number }> {
export async function prepareDatabase(
orm: MikroORM,
): Promise<{ failures: SchemaFailure[]; adjusted: number; statements: number }> {
await resetDatabase(orm);
const connection = orm.em.getConnection();
const failures: SchemaFailure[] = [];
@@ -128,7 +154,10 @@ export function postgresHelperEngine(orm: MikroORM): HelperEngine {
},
async selectKysely(select: KyselySelect) {
const platform = orm.em.getPlatform();
const row = await kysely.selectFrom(VALUES_TABLE).select((eb) => select(platform, eb).as('v')).executeTakeFirst();
const row = await kysely
.selectFrom(VALUES_TABLE)
.select((eb) => select(platform, eb).as('v'))
.executeTakeFirst();
return row?.v;
},
};
@@ -153,7 +182,13 @@ export function sqliteHelperEngine(): HelperEngine & { close(): void } {
platform,
async writeRow(row: ValuesRow) {
db.prepare(`delete from ${VALUES_TABLE}`).run();
db.prepare(`insert into ${VALUES_TABLE} (id, a, b, n, x) values (?, ?, ?, ?, ?)`).run(row.id, row.a, row.b, row.n, row.x);
db.prepare(`insert into ${VALUES_TABLE} (id, a, b, n, x) values (?, ?, ?, ?, ?)`).run(
row.id,
row.a,
row.b,
row.n,
row.x,
);
},
async selectRaw(select: RawSelect) {
const sql = `select ${select.sql}${select.column ? '' : ' as v'} from ${VALUES_TABLE}`;
@@ -161,7 +196,10 @@ export function sqliteHelperEngine(): HelperEngine & { close(): void } {
return row?.[select.column ?? 'v'];
},
async selectKysely(select: KyselySelect) {
const compiled = compiler.selectFrom(VALUES_TABLE).select((eb) => select(platform, eb).as('v')).compile();
const compiled = compiler
.selectFrom(VALUES_TABLE)
.select((eb) => select(platform, eb).as('v'))
.compile();
const row = db.prepare(compiled.sql).get(...compiled.parameters.map(bind)) as Record<string, unknown> | undefined;
return row?.v;
},
@@ -172,7 +210,11 @@ export function sqliteHelperEngine(): HelperEngine & { close(): void } {
type RepositoryFactory = (em: EntityManager) => object;
/** How to reach each repository class: through its entity, or `new X(em)` for the two that have none. */
function repositoryFactories(orm: MikroORM, plans: readonly MethodPlan[], serverRoot: string): Map<string, RepositoryFactory | string> {
function repositoryFactories(
orm: MikroORM,
plans: readonly MethodPlan[],
serverRoot: string,
): Map<string, RepositoryFactory | string> {
const byEntity = new Map<string, RepositoryFactory>();
for (const meta of orm.getMetadata().getAll().values()) {
const repository = meta.repository?.();
+203 -48
View File
@@ -15,10 +15,15 @@
* Unlike the repository statements, nothing here is baselined: every case
* must pass on both engines.
*/
import type { Platform } from '@mikro-orm/core';
import type { AliasableExpression, ExpressionBuilder } from 'kysely';
import {
castIntegerKysely,
concatKysely,
currentTimestampKysely,
nowPlusSecondsKysely,
startsWithIsoDateKysely,
substringKysely,
unixEpochToIsoKysely,
} from '../../src/db/dialect/kysely-functions';
import {
absDifference,
caseWhenEquals,
@@ -53,15 +58,9 @@ import {
substring,
trim,
} from '../../src/db/dialect/sql-functions';
import {
castIntegerKysely,
concatKysely,
currentTimestampKysely,
nowPlusSecondsKysely,
startsWithIsoDateKysely,
substringKysely,
unixEpochToIsoKysely,
} from '../../src/db/dialect/kysely-functions';
import type { Platform } from '@mikro-orm/core';
import type { AliasableExpression, ExpressionBuilder } from 'kysely';
export type Engine = 'sqlite' | 'postgres';
@@ -92,7 +91,10 @@ export interface RawSelect {
column?: string;
}
export type KyselySelect = (platform: Platform, eb: ExpressionBuilder<ValuesDB, 'trek_pg_probe_values'>) => AliasableExpression<unknown>;
export type KyselySelect = (
platform: Platform,
eb: ExpressionBuilder<ValuesDB, 'trek_pg_probe_values'>,
) => AliasableExpression<unknown>;
export type Expectation =
| { equals: string | number | boolean | null }
@@ -118,7 +120,10 @@ const rawOf = (fragment: { sql: string; params: readonly unknown[] }, column?: s
});
/** `(<key> = <value>)` for the helpers used as a filter key. */
const comparison = (key: { sql: string; params: readonly unknown[] }, value: { sql: string; params: readonly unknown[] }): RawSelect => ({
const comparison = (
key: { sql: string; params: readonly unknown[] },
value: { sql: string; params: readonly unknown[] },
): RawSelect => ({
sql: `(${key.sql} = ${value.sql})`,
params: [...key.params, ...value.params],
});
@@ -133,9 +138,24 @@ export function isoSeconds(ms: number): string {
const EPOCH_MS = 1_758_459_909_123;
export const HELPER_CASES: readonly HelperCase[] = [
{ name: 'dateOf', row: { a: '2026-09-21 13:05:09' }, raw: (p) => rawOf(dateOf(p, 'a')), expect: { equals: '2026-09-21' } },
{ name: 'dateAdd forward', row: { a: '2026-09-21 13:05:09' }, raw: (p) => rawOf(dateAdd(p, 'a', 10)), expect: { equals: '2026-10-01' } },
{ name: 'dateAdd back', row: { a: '2026-09-21 13:05:09' }, raw: (p) => rawOf(dateAdd(p, 'a', -10)), expect: { equals: '2026-09-11' } },
{
name: 'dateOf',
row: { a: '2026-09-21 13:05:09' },
raw: (p) => rawOf(dateOf(p, 'a')),
expect: { equals: '2026-09-21' },
},
{
name: 'dateAdd forward',
row: { a: '2026-09-21 13:05:09' },
raw: (p) => rawOf(dateAdd(p, 'a', 10)),
expect: { equals: '2026-10-01' },
},
{
name: 'dateAdd back',
row: { a: '2026-09-21 13:05:09' },
raw: (p) => rawOf(dateAdd(p, 'a', -10)),
expect: { equals: '2026-09-11' },
},
{ name: 'currentTimestamp', row: {}, raw: (p) => rawOf(currentTimestamp(p)), expect: { timestamp: 0 } },
{ name: 'nowMinusDays', row: {}, raw: (p) => rawOf(nowMinusDays(p, 30)), expect: { timestamp: -30 * DAY_MS } },
{ name: 'nowMinusHours', row: {}, raw: (p) => rawOf(nowMinusHours(p, 20)), expect: { timestamp: -20 * 3_600_000 } },
@@ -143,28 +163,98 @@ export const HELPER_CASES: readonly HelperCase[] = [
{ name: 'nowDateOffset back', row: {}, raw: (p) => rawOf(nowDateOffset(p, -400)), expect: { date: -400 } },
{ name: 'nowDateOffset forward', row: {}, raw: (p) => rawOf(nowDateOffset(p, 1)), expect: { date: 1 } },
{ name: 'columnRef', row: { n: 7 }, raw: (p) => rawOf(columnRef(p, 'n')), expect: { equals: 7 } },
{ name: 'columnIncrementedBy', row: { n: 7 }, raw: (p) => rawOf(columnIncrementedBy(p, 'n', -2)), expect: { equals: 5 } },
{
name: 'columnIncrementedBy',
row: { n: 7 },
raw: (p) => rawOf(columnIncrementedBy(p, 'n', -2)),
expect: { equals: 5 },
},
{ name: 'lower', row: { a: 'Probe@X.com' }, raw: (p) => rawOf(lower(p, 'a')), expect: { equals: 'probe@x.com' } },
{ name: 'lower = lowerParam', row: { a: 'Probe@X.com' }, raw: (p) => comparison(lower(p, 'a'), lowerParam(p, 'PROBE@x.COM')), expect: { equals: true } },
{
name: 'lower = lowerParam',
row: { a: 'Probe@X.com' },
raw: (p) => comparison(lower(p, 'a'), lowerParam(p, 'PROBE@x.COM')),
expect: { equals: true },
},
{ name: 'trim', row: { a: ' probe ' }, raw: (p) => rawOf(trim(p, 'a')), expect: { equals: 'probe' } },
{ name: 'lowerTrim', row: { a: ' AbC ' }, raw: (p) => rawOf(lowerTrim(p, 'a')), expect: { equals: 'abc' } },
{ name: 'lowerTrim = lowerTrimParam', row: { a: ' AbC ' }, raw: (p) => comparison(lowerTrim(p, 'a'), lowerTrimParam(p, ' aBc')), expect: { equals: true } },
{ name: 'coalesce', row: { a: null, b: 'fallback' }, raw: (p) => rawOf(coalesce(p, 'a', 'b')), expect: { equals: 'fallback' } },
{ name: 'coalesceParam keeps the column', row: { a: 'stored' }, raw: (p) => rawOf(coalesceParam(p, 'a', 'new')), expect: { equals: 'stored' } },
{ name: 'coalesceParam fills a null', row: { a: null }, raw: (p) => rawOf(coalesceParam(p, 'a', 'new')), expect: { equals: 'new' } },
{ name: 'coalesceOverride prefers the value', row: { a: 'stored' }, raw: (p) => rawOf(coalesceOverride(p, 'new', 'a')), expect: { equals: 'new' } },
{ name: 'coalesceOverride keeps on null', row: { a: 'stored' }, raw: (p) => rawOf(coalesceOverride(p, null, 'a')), expect: { equals: 'stored' } },
{
name: 'lowerTrim = lowerTrimParam',
row: { a: ' AbC ' },
raw: (p) => comparison(lowerTrim(p, 'a'), lowerTrimParam(p, ' aBc')),
expect: { equals: true },
},
{
name: 'coalesce',
row: { a: null, b: 'fallback' },
raw: (p) => rawOf(coalesce(p, 'a', 'b')),
expect: { equals: 'fallback' },
},
{
name: 'coalesceParam keeps the column',
row: { a: 'stored' },
raw: (p) => rawOf(coalesceParam(p, 'a', 'new')),
expect: { equals: 'stored' },
},
{
name: 'coalesceParam fills a null',
row: { a: null },
raw: (p) => rawOf(coalesceParam(p, 'a', 'new')),
expect: { equals: 'new' },
},
{
name: 'coalesceOverride prefers the value',
row: { a: 'stored' },
raw: (p) => rawOf(coalesceOverride(p, 'new', 'a')),
expect: { equals: 'new' },
},
{
name: 'coalesceOverride keeps on null',
row: { a: 'stored' },
raw: (p) => rawOf(coalesceOverride(p, null, 'a')),
expect: { equals: 'stored' },
},
{ name: 'absDifference', row: { x: 4 }, raw: (p) => rawOf(absDifference(p, 'x', 6.5)), expect: { equals: 2.5 } },
{ name: 'countAll', row: {}, raw: (p) => rawOf(countAll(p, 'c'), 'c'), expect: { equals: 1 } },
{ name: 'countAllRef', row: {}, raw: (p) => rawOf(countAllRef(p)), expect: { equals: 1 } },
{ name: 'minOf', row: { n: 3 }, raw: (p) => rawOf(minOf(p, 'n', 'lo'), 'lo'), expect: { equals: 3 } },
{ name: 'maxOf', row: { n: 3 }, raw: (p) => rawOf(maxOf(p, 'n', 'hi'), 'hi'), expect: { equals: 3 } },
{ name: 'caseWhenEquals', row: { n: 7 }, raw: (p) => rawOf(caseWhenEquals(p, 'n', 7, 'owner', 'member')), expect: { equals: 'owner' } },
{ name: 'caseWhenEquals else', row: { n: 8 }, raw: (p) => rawOf(caseWhenEquals(p, 'n', 7, 'owner', 'member')), expect: { equals: 'member' } },
{ name: 'startsWithIsoDate yes', row: { a: '2026-09-21T10:00' }, raw: (p) => rawOf(startsWithIsoDate(p, 'a')), expect: { equals: true } },
{ name: 'startsWithIsoDate no', row: { a: 'abcd-ef-gh' }, raw: (p) => rawOf(startsWithIsoDate(p, 'a')), expect: { equals: false } },
{ name: 'substring with length', row: { a: '2026-09-21T10:00' }, raw: (p) => rawOf(substring(p, 'a', 1, 10)), expect: { equals: '2026-09-21' } },
{ name: 'substring to the end', row: { a: '2026-09-21T10:00' }, raw: (p) => rawOf(substring(p, 'a', 12)), expect: { equals: '10:00' } },
{
name: 'caseWhenEquals',
row: { n: 7 },
raw: (p) => rawOf(caseWhenEquals(p, 'n', 7, 'owner', 'member')),
expect: { equals: 'owner' },
},
{
name: 'caseWhenEquals else',
row: { n: 8 },
raw: (p) => rawOf(caseWhenEquals(p, 'n', 7, 'owner', 'member')),
expect: { equals: 'member' },
},
{
name: 'startsWithIsoDate yes',
row: { a: '2026-09-21T10:00' },
raw: (p) => rawOf(startsWithIsoDate(p, 'a')),
expect: { equals: true },
},
{
name: 'startsWithIsoDate no',
row: { a: 'abcd-ef-gh' },
raw: (p) => rawOf(startsWithIsoDate(p, 'a')),
expect: { equals: false },
},
{
name: 'substring with length',
row: { a: '2026-09-21T10:00' },
raw: (p) => rawOf(substring(p, 'a', 1, 10)),
expect: { equals: '2026-09-21' },
},
{
name: 'substring to the end',
row: { a: '2026-09-21T10:00' },
raw: (p) => rawOf(substring(p, 'a', 12)),
expect: { equals: '10:00' },
},
{
name: 'concat',
row: { a: '2026-09-21', b: '10:00' },
@@ -173,15 +263,30 @@ export const HELPER_CASES: readonly HelperCase[] = [
},
{ name: 'castInteger of 14.0', row: { a: '14.0' }, raw: (p) => rawOf(castInteger(p, 'a')), expect: { equals: 14 } },
{ name: 'castInteger of 14', row: { a: '14' }, raw: (p) => rawOf(castInteger(p, 'a')), expect: { equals: 14 } },
{ name: 'dayDistance', row: { a: '2026-09-21' }, raw: (p) => rawOf(dayDistance(p, 'a', '2026-09-24')), expect: { equals: 3 } },
{ name: 'collateNoCase', row: { a: 'Probe' }, raw: (p) => comparison(collateNoCase(p, 'a'), bound('pROBE')), expect: { equals: true } },
{
name: 'dayDistance',
row: { a: '2026-09-21' },
raw: (p) => rawOf(dayDistance(p, 'a', '2026-09-24')),
expect: { equals: 3 },
},
{
name: 'collateNoCase',
row: { a: 'Probe' },
raw: (p) => comparison(collateNoCase(p, 'a'), bound('pROBE')),
expect: { equals: true },
},
{
name: 'foundAgainState recovers',
row: { a: 'remote_missing', b: 'file-1' },
raw: (p) => rawOf(foundAgainState(p, 'a', 'b')),
expect: { equals: 'synced' },
},
{ name: 'foundAgainState passes through', row: { a: 'error', b: 'file-1' }, raw: (p) => rawOf(foundAgainState(p, 'a', 'b')), expect: { equals: 'error' } },
{
name: 'foundAgainState passes through',
row: { a: 'error', b: 'file-1' },
raw: (p) => rawOf(foundAgainState(p, 'a', 'b')),
expect: { equals: 'error' },
},
{
name: 'coalesceOverrideWhileSame keeps for the same key',
row: { a: 'https://a', n: 1 },
@@ -194,24 +299,61 @@ export const HELPER_CASES: readonly HelperCase[] = [
raw: (p) => rawOf(coalesceOverrideWhileSame(p, null, 'n', 'a', 'https://b')),
expect: { equals: 0 },
},
{ name: 'caseWhenNotNull', row: { a: 'x', b: 'route' }, raw: (p) => rawOf(caseWhenNotNull(p, 'a', 'b')), expect: { equals: 'route' } },
{ name: 'caseWhenNotNull null', row: { a: null, b: 'route' }, raw: (p) => rawOf(caseWhenNotNull(p, 'a', 'b')), expect: { equals: null } },
{
name: 'caseWhenNotNull',
row: { a: 'x', b: 'route' },
raw: (p) => rawOf(caseWhenNotNull(p, 'a', 'b')),
expect: { equals: 'route' },
},
{
name: 'caseWhenNotNull null',
row: { a: null, b: 'route' },
raw: (p) => rawOf(caseWhenNotNull(p, 'a', 'b')),
expect: { equals: null },
},
{
name: 'startsWithIsoDateKysely',
row: { a: '2026-09-21 10:00:00' },
kysely: (p, eb) => eb.case().when(startsWithIsoDateKysely(p, eb, 'a')).then('yes').else('no').end(),
kysely: (p, eb) =>
eb
.case()
.when(startsWithIsoDateKysely(p, eb, 'a'))
.then('yes')
.else('no')
.end(),
expect: { equals: 'yes' },
},
{ name: 'substringKysely', row: { a: '2026-09-21T10:00' }, kysely: (p, eb) => substringKysely(p, eb, 'a', 1, 10), expect: { equals: '2026-09-21' } },
{
name: 'substringKysely',
row: { a: '2026-09-21T10:00' },
kysely: (p, eb) => substringKysely(p, eb, 'a', 1, 10),
expect: { equals: '2026-09-21' },
},
{
name: 'concatKysely',
row: { a: '2026-09-21', b: 'xx10:00' },
kysely: (p, eb) => concatKysely(p, eb, { column: 'a' }, { value: 'T' }, { expression: substringKysely(p, eb, 'b', 3) }),
kysely: (p, eb) =>
concatKysely(p, eb, { column: 'a' }, { value: 'T' }, { expression: substringKysely(p, eb, 'b', 3) }),
expect: { equals: '2026-09-21T10:00' },
},
{ name: 'castIntegerKysely', row: { a: '14.0' }, kysely: (p, eb) => castIntegerKysely(p, eb, 'a'), expect: { equals: 14 } },
{ name: 'unixEpochToIsoKysely', row: { n: EPOCH_MS }, kysely: (p, eb) => unixEpochToIsoKysely(p, eb, 'n'), expect: { equals: isoSeconds(EPOCH_MS) } },
{ name: 'nowPlusSecondsKysely', row: {}, kysely: (p, eb) => nowPlusSecondsKysely(p, eb, 45), expect: { timestamp: 45_000 } },
{
name: 'castIntegerKysely',
row: { a: '14.0' },
kysely: (p, eb) => castIntegerKysely(p, eb, 'a'),
expect: { equals: 14 },
},
{
name: 'unixEpochToIsoKysely',
row: { n: EPOCH_MS },
kysely: (p, eb) => unixEpochToIsoKysely(p, eb, 'n'),
expect: { equals: isoSeconds(EPOCH_MS) },
},
{
name: 'nowPlusSecondsKysely',
row: {},
kysely: (p, eb) => nowPlusSecondsKysely(p, eb, 45),
expect: { timestamp: 45_000 },
},
{ name: 'currentTimestampKysely', row: {}, kysely: (p) => currentTimestampKysely(p), expect: { timestamp: 0 } },
];
@@ -222,14 +364,17 @@ const DATE_TEXT = /^\d{4}-\d{2}-\d{2}$/;
export function checkValue(expectation: Expectation, value: unknown, engine: Engine, now: number): string | null {
if ('perEngine' in expectation) return checkValue(expectation.perEngine[engine], value, engine, now);
if ('timestamp' in expectation) {
if (typeof value !== 'string' || !TIMESTAMP_TEXT.test(value)) return `expected timestamp text, got ${JSON.stringify(value)}`;
if (typeof value !== 'string' || !TIMESTAMP_TEXT.test(value))
return `expected timestamp text, got ${JSON.stringify(value)}`;
const off = Date.parse(`${value.replace(' ', 'T')}Z`) - (now + expectation.timestamp);
return Math.abs(off) <= CLOCK_TOLERANCE_MS ? null : `${value} is ${Math.round(off / 1000)}s off`;
}
if ('date' in expectation) {
if (typeof value !== 'string' || !DATE_TEXT.test(value)) return `expected date text, got ${JSON.stringify(value)}`;
const wanted = Date.parse(new Date(now + expectation.date * DAY_MS).toISOString().slice(0, 10));
return Math.abs(Date.parse(value) - wanted) <= DAY_MS ? null : `${value} is not ${expectation.date} day(s) from today`;
return Math.abs(Date.parse(value) - wanted) <= DAY_MS
? null
: `${value} is not ${expectation.date} day(s) from today`;
}
const expected = expectation.equals;
if (expected === null) return value === null ? null : `expected null, got ${JSON.stringify(value)}`;
@@ -239,8 +384,15 @@ export function checkValue(expectation: Expectation, value: unknown, engine: Eng
return (expected ? truthy : falsy) ? null : `expected ${expected}, got ${JSON.stringify(value)}`;
}
if (typeof expected === 'number') {
const n = typeof value === 'bigint' ? Number(value) : typeof value === 'string' || typeof value === 'number' ? Number(value) : Number.NaN;
return Math.abs(n - expected) < 1e-9 ? null : `expected ${expected}, got ${JSON.stringify(typeof value === 'bigint' ? String(value) : value)}`;
const n =
typeof value === 'bigint'
? Number(value)
: typeof value === 'string' || typeof value === 'number'
? Number(value)
: Number.NaN;
return Math.abs(n - expected) < 1e-9
? null
: `expected ${expected}, got ${JSON.stringify(typeof value === 'bigint' ? String(value) : value)}`;
}
return value === expected ? null : `expected ${JSON.stringify(expected)}, got ${JSON.stringify(value)}`;
}
@@ -260,7 +412,10 @@ export interface HelperResult {
failure: string | null;
}
export async function runHelperCases(engine: HelperEngine, cases: readonly HelperCase[] = HELPER_CASES): Promise<HelperResult[]> {
export async function runHelperCases(
engine: HelperEngine,
cases: readonly HelperCase[] = HELPER_CASES,
): Promise<HelperResult[]> {
const results: HelperResult[] = [];
for (const helperCase of cases) {
let failure: string | null;
+7 -5
View File
@@ -21,9 +21,6 @@
* AsyncLocalStorage, so a straggler from a timed-out method can never be
* counted against the next one.
*/
import { AsyncLocalStorage } from 'node:async_hooks';
import {
CompiledQuery,
type DatabaseConnection,
@@ -35,6 +32,7 @@ import {
type QueryCompiler,
type QueryResult,
} from 'kysely';
import { AsyncLocalStorage } from 'node:async_hooks';
export type StatementOutcome = { ok: true } | { ok: false; code: string; message: string };
@@ -44,7 +42,8 @@ export interface StatementRecord {
}
/** Transaction control a probed method sends; each statement already runs in its own rolled-back transaction. */
const TRANSACTION_CONTROL = /^\s*(begin|commit|rollback|end|abort|start\s+transaction|savepoint|release(\s+savepoint)?)\b/i;
const TRANSACTION_CONTROL =
/^\s*(begin|commit|rollback|end|abort|start\s+transaction|savepoint|release(\s+savepoint)?)\b/i;
export function isTransactionControl(sql: string): boolean {
return TRANSACTION_CONTROL.test(sql);
@@ -114,7 +113,10 @@ export class ProbeConnection implements DatabaseConnection {
this.recorder.record(key, { sql: compiled.sql, outcome: { ok: true } });
return result;
} catch (error) {
this.recorder.record(key, { sql: compiled.sql, outcome: { ok: false, code: sqlState(error), message: errorLine(error) } });
this.recorder.record(key, {
sql: compiled.sql,
outcome: { ok: false, code: sqlState(error), message: errorLine(error) },
});
return { rows: [] };
} finally {
await this.inner.executeQuery(CompiledQuery.raw('rollback'));
+64 -21
View File
@@ -2,7 +2,6 @@
* Turns what the Postgres probe saw into counts, a console log and the
* Markdown the CI job writes to its step summary.
*/
import { countsTowardRatchet, type BaselineVerdict } from './baseline';
import type { HelperResult } from './helper-cases';
import type { StatementRecord } from './recorder';
@@ -77,7 +76,10 @@ export function summarize(results: readonly MethodResult[]): ProbeSummary {
summary.timedOut += 1;
summary.uncovered.set(result.key, 'timed out');
} else if (result.statements.length === 0) {
summary.uncovered.set(result.key, result.threw === undefined ? 'sent no SQL' : `threw before any statement: ${result.threw}`);
summary.uncovered.set(
result.key,
result.threw === undefined ? 'sent no SQL' : `threw before any statement: ${result.threw}`,
);
}
if (result.statements.length === 0) summary.withoutSql += 1;
const seen = new Set<string>();
@@ -93,7 +95,13 @@ export function summarize(results: readonly MethodResult[]): ProbeSummary {
if (!('code' in outcome)) continue;
const dialect = countsTowardRatchet(outcome.code);
if (dialect) counted += 1;
summary.failedStatements.push({ method: result.key, code: outcome.code, message: outcome.message, sql: statement.sql, counted: dialect });
summary.failedStatements.push({
method: result.key,
code: outcome.code,
message: outcome.message,
sql: statement.sql,
counted: dialect,
});
summary.failuresByCode.set(outcome.code, (summary.failuresByCode.get(outcome.code) ?? 0) + 1);
}
summary.failingByMethod.set(result.key, counted);
@@ -102,7 +110,10 @@ export function summarize(results: readonly MethodResult[]): ProbeSummary {
}
/** Refused statements the ratchet holds (dialect errors) and the ones it only reports. */
export function splitRefusals(summary: Pick<ProbeSummary, 'failedStatements'>): { counted: FailedStatement[]; reported: FailedStatement[] } {
export function splitRefusals(summary: Pick<ProbeSummary, 'failedStatements'>): {
counted: FailedStatement[];
reported: FailedStatement[];
} {
return {
counted: summary.failedStatements.filter((failed) => failed.counted),
reported: summary.failedStatements.filter((failed) => !failed.counted),
@@ -163,11 +174,16 @@ export function formatConsole(input: ReportInput): string {
const { summary, verdict } = input;
const lines: string[] = [];
const failures = helperFailures(input.helpers);
lines.push(`Dialect helpers: ${input.helpers.length - failures.length}/${input.helpers.length} cases pass on SQLite and Postgres.`);
lines.push(
`Dialect helpers: ${input.helpers.length - failures.length}/${input.helpers.length} cases pass on SQLite and Postgres.`,
);
for (const failure of failures) lines.push(` FAIL [${failure.engine}] ${failure.name}: ${failure.failure}`);
if (input.schemaFailures.length > 0) {
lines.push(`Schema: ${input.schemaFailures.length} DDL statement(s) Postgres refused (their tables are missing below):`);
for (const failure of input.schemaFailures) lines.push(` ${failure.message} <- ${oneLine(failure.statement, 120)}`);
lines.push(
`Schema: ${input.schemaFailures.length} DDL statement(s) Postgres refused (their tables are missing below):`,
);
for (const failure of input.schemaFailures)
lines.push(` ${failure.message} <- ${oneLine(failure.statement, 120)}`);
}
lines.push(
`Repositories: ${summary.methods} methods, ${summary.called} called, ${summary.unprobeable} unprobeable, ` +
@@ -187,10 +203,13 @@ export function formatConsole(input: ReportInput): string {
}
if (summary.uncovered.size > 0) {
lines.push(`Unmeasured: ${summary.uncovered.size} method(s) whose SQL the probe did not see:`);
for (const [method, why] of [...summary.uncovered.entries()].sort(([a], [b]) => a.localeCompare(b))) lines.push(` ${method}: ${why}`);
for (const [method, why] of [...summary.uncovered.entries()].sort(([a], [b]) => a.localeCompare(b)))
lines.push(` ${method}: ${why}`);
}
if (probedNothing(summary)) {
lines.push(`FAIL No repository method was called (${summary.methods} planned); there is nothing to hold to the baseline.`);
lines.push(
`FAIL No repository method was called (${summary.methods} planned); there is nothing to hold to the baseline.`,
);
}
if (verdict.unseeded) {
lines.push(
@@ -202,7 +221,9 @@ export function formatConsole(input: ReportInput): string {
lines.push(`FAIL ${entry.method} sends ${entry.now} statement(s) Postgres refuses, ${entry.allowed} allowed.`);
}
for (const entry of verdict.stale) {
lines.push(`FAIL ${entry.method} is held at ${entry.allowed} failing statement(s) but fails ${entry.now} now; lower the baseline.`);
lines.push(
`FAIL ${entry.method} is held at ${entry.allowed} failing statement(s) but fails ${entry.now} now; lower the baseline.`,
);
}
for (const method of verdict.newlyUncovered) {
lines.push(
@@ -223,16 +244,21 @@ export function formatMarkdown(input: ReportInput): string {
const out: string[] = ['## Postgres probe', ''];
out.push(passed(input) ? 'Result: **passed**' : 'Result: **failed**', '');
out.push('| | |', '|---|---|');
out.push(`| Dialect helper cases (SQLite and Postgres) | ${input.helpers.length - failures.length} of ${input.helpers.length} pass |`);
out.push(
`| Dialect helper cases (SQLite and Postgres) | ${input.helpers.length - failures.length} of ${input.helpers.length} pass |`,
);
out.push(`| Schema statements refused | ${input.schemaFailures.length} |`);
const refusals = splitRefusals(summary);
out.push(`| Repository methods | ${summary.methods} (${summary.called} called, ${summary.unprobeable} unprobeable) |`);
out.push(
`| Repository methods | ${summary.methods} (${summary.called} called, ${summary.unprobeable} unprobeable) |`,
);
out.push(`| Methods whose SQL the probe did not see | ${summary.uncovered.size} |`);
out.push(`| Distinct statements | ${summary.statements} |`);
out.push(`| Refused by Postgres as SQL (held) | ${refusals.counted.length} |`);
out.push(`| Refused over a sample value or the empty tables (reported only) | ${refusals.reported.length} |`);
out.push('');
if (probedNothing(summary)) out.push('No repository method was called, so there is nothing to hold to the baseline.', '');
if (probedNothing(summary))
out.push('No repository method was called, so there is nothing to hold to the baseline.', '');
if (verdict.unseeded) {
out.push(
'The baseline has not been measured yet, which fails the run. Commit `pg-probe-baseline.json` from the `pg-probe-baseline` artifact as `server/scripts/pg-probe-baseline.json`.',
@@ -241,33 +267,50 @@ export function formatMarkdown(input: ReportInput): string {
}
if (verdict.grown.length > 0 || verdict.stale.length > 0) {
out.push('### Ratchet', '', '| Method | Allowed | Now |', '|---|---|---|');
for (const entry of [...verdict.grown, ...verdict.stale]) out.push(`| ${cell(entry.method)} | ${entry.allowed} | ${entry.now} |`);
for (const entry of [...verdict.grown, ...verdict.stale])
out.push(`| ${cell(entry.method)} | ${entry.allowed} | ${entry.now} |`);
out.push('');
}
if (verdict.newlyUncovered.length > 0 || verdict.nowCovered.length > 0) {
out.push('### Coverage ratchet', '', '| Method | Baseline | Now |', '|---|---|---|');
for (const method of verdict.newlyUncovered) out.push(`| ${cell(method)} | measured | ${cell(summary.uncovered.get(method) ?? 'unmeasured')} |`);
for (const method of verdict.newlyUncovered)
out.push(`| ${cell(method)} | measured | ${cell(summary.uncovered.get(method) ?? 'unmeasured')} |`);
for (const method of verdict.nowCovered) out.push(`| ${cell(method)} | uncovered | measured or gone |`);
out.push('');
}
if (failures.length > 0) {
out.push('### Helper cases that failed', '', '| Engine | Case | Why |', '|---|---|---|');
for (const failure of failures) out.push(`| ${failure.engine} | ${cell(failure.name)} | ${cell(failure.failure ?? '')} |`);
for (const failure of failures)
out.push(`| ${failure.engine} | ${cell(failure.name)} | ${cell(failure.failure ?? '')} |`);
out.push('');
}
if (summary.failuresByCode.size > 0) {
out.push('### Refused statements by SQLSTATE', '', '| SQLSTATE | Statements |', '|---|---|');
for (const [code, count] of [...summary.failuresByCode.entries()].sort((a, b) => b[1] - a[1])) out.push(`| ${code} | ${count} |`);
for (const [code, count] of [...summary.failuresByCode.entries()].sort((a, b) => b[1] - a[1]))
out.push(`| ${code} | ${count} |`);
out.push('');
out.push('<details><summary>Every refused statement</summary>', '', '| Method | SQLSTATE | Held | Message |', '|---|---|---|---|');
out.push(
'<details><summary>Every refused statement</summary>',
'',
'| Method | SQLSTATE | Held | Message |',
'|---|---|---|---|',
);
for (const failed of summary.failedStatements) {
out.push(`| ${cell(failed.method)} | ${failed.code} | ${failed.counted ? 'yes' : 'no'} | ${cell(failed.message)} |`);
out.push(
`| ${cell(failed.method)} | ${failed.code} | ${failed.counted ? 'yes' : 'no'} | ${cell(failed.message)} |`,
);
}
out.push('', '</details>', '');
}
if (summary.uncovered.size > 0) {
out.push('<details><summary>Methods whose SQL the probe did not see</summary>', '', '| Method | Why |', '|---|---|');
for (const [method, why] of [...summary.uncovered.entries()].sort(([a], [b]) => a.localeCompare(b))) out.push(`| ${cell(method)} | ${cell(why)} |`);
out.push(
'<details><summary>Methods whose SQL the probe did not see</summary>',
'',
'| Method | Why |',
'|---|---|',
);
for (const [method, why] of [...summary.uncovered.entries()].sort(([a], [b]) => a.localeCompare(b)))
out.push(`| ${cell(method)} | ${cell(why)} |`);
out.push('', '</details>', '');
}
return `${out.join('\n')}\n`;
+6 -3
View File
@@ -19,7 +19,6 @@
*
* Unique and partial unique indexes stay, because `ON CONFLICT` needs them.
*/
import { pgTimestampText, PG_UTC_NOW } from '../../src/db/dialect/platform';
/** SQLite's timestamp text on Postgres, for a column default. */
@@ -31,9 +30,13 @@ export const NOCASE_COLLATION_SQL =
/** The Postgres spelling of a column default the entities carry in SQLite's. */
export function portableDefault(raw: string): string {
const text = raw.trim().replace(/^\((.*)\)$/s, '$1').trim();
const text = raw
.trim()
.replace(/^\((.*)\)$/s, '$1')
.trim();
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text)) return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
return raw;
}