import type { AnyOrm } from '../../src/db/orm';
import type { CompiledQuery, Kysely } from 'kysely';
import { vi } from 'vitest';
/**
* A stand-in for the Postgres side of the SQLite move
* (`src/db/engine/postgres/sqlite-move/`), for the unit tests in the SQLite
* lane: it answers exactly the statements the move sends, keeps the rows it
* is given in memory and reads them back as Postgres's `::text` would. The
* real database is the Postgres lane's (`tests/postgres/sqlite-move.test.ts`).
*/
interface FakeColumn {
name: string;
dataType: string;
nullable?: boolean;
}
export interface FakeTableDef {
name: string;
columns: FakeColumn[];
primaryKey: string[];
/** Foreign keys: `columns` of this table point at `references`. */
foreignKeys?: Array<{ columns: string[]; references: string }>;
/** Columns a sequence fills. */
serial?: string[];
/** Unique indexes besides the primary key's (`
_pkey`). */
unique?: Array<{ name: string; columns: string[] }>;
}
interface FakeTable {
columns: string[];
rows: unknown[][];
}
const QUOTED = /"((?:[^"]|"")*)"/g;
function unquote(text: string): string[] {
return [...text.matchAll(QUOTED)].map((match) => match[1].replaceAll('""', '"'));
}
/** A value as Postgres would print it with `::text` and `bytea_output = hex`. */
function asText(value: unknown): string | null {
if (value === null || value === undefined) return null;
if (Buffer.isBuffer(value)) return `\\x${value.toString('hex')}`;
return String(value);
}
export class FakePostgres {
/** Every statement, in order. */
readonly statements: string[] = [];
readonly tables = new Map();
readonly sequences = new Map();
/** Tables the database holds before anything runs (the move refuses them). */
existing: string[] = [];
pluginSchemas: string[] = [];
/** A statement matching this fails, as Postgres would refuse it. */
failOn: RegExp | null = null;
/** What the refusal of `failOn` carries besides its message: by default a broken key without a SQLSTATE. */
failWith: Record = { detail: 'Key (id)=(1)', constraint: 'fake_key' };
/** Rows the read-back answers in place of the stored ones, by table: a copy that came out wrong. */
tamper = new Map unknown[][]>();
private cursor: Array> = [];
private bootstrapped = false;
constructor(readonly schema: FakeTableDef[]) {}
/** What the engine's bootstrap leaves: every table of the schema, with a seeded row or two. */
bootstrap(): void {
this.bootstrapped = true;
for (const table of this.schema) {
this.tables.set(`"${table.name}"`, { columns: table.columns.map((column) => column.name), rows: [] });
}
const first = this.schema[0];
this.tables.get(`"${first.name}"`)?.rows.push(first.columns.map(() => null));
}
rowsOf(target: string): unknown[][] {
return this.tables.get(target)?.rows ?? [];
}
async executeQuery(query: CompiledQuery): Promise<{ rows: R[] }> {
const sql = query.sql;
const params = [...query.parameters];
this.statements.push(sql);
if (this.failOn?.test(sql)) {
throw Object.assign(new Error('refused by the fake'), this.failWith);
}
return { rows: this.answer(sql, params) as R[] };
}
/** `db.transaction().execute(fn)`: the fake has no isolation, only the order of statements. */
transaction() {
return { execute: (work: (trx: Kysely