// `postgresDriver()` against a real Postgres. `pg-driver.test.ts` asserts the statement text a // plan compiles to; nothing there proves Postgres accepts it, that the table the framework's own // migration generator writes is the table the driver reads, or that a value survives the round // trip. Both bugs this file was written to catch were invisible to a recording client: an entity // with a `unique()` column generated a migration Postgres refused (`42P07`, the same index twice) // and money's currency generated as bare `char` — `char(1)` — which no three-letter code fits. // // The whole chain runs here: entity() -> describe() -> generateMigration() -> a live server -> // postgresDriver() -> decoded row. Skips unless `TEST_DATABASE_URL` is set, the same as // `db-integration.test.ts`; CI's `postgres` service container sets it. import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import type { Page } from '@ultimat3/core'; import { ctxOf, runWithContext, subscribe, userActor } from '@ultimat3/core'; import { generateMigration, type PostgresClient, postgresClient, raw, setDbClient, statementsOf, } from '@ultimat3/db'; import { boolean, money, text, timestamp, uuid } from './columns'; import { database } from './database'; import { entity } from './entity'; import { postgresDriver, postgresRepo } from './pg-driver'; import { postgresTransactor } from './pg-transactor'; import { clearRegistry } from './registry'; import type { FindManyArgs } from './repo'; // `TEST_DATABASE_URL` only. `beforeAll`/`afterAll` here run `drop table … cascade`, so falling // back to the app's own `DATABASE_URL` would hand this file whatever database a developer had // exported — a skip is the right answer, and CI sets the test url anyway. const adminUrl = Bun.env['TEST_DATABASE_URL']; const hasPostgres = typeof adminUrl === 'string' && adminUrl.length > 0; const orgs = entity('pg_live_orgs', { columns: { id: uuid().primaryKey(), slug: text({ max: 40 }).unique() }, }); const invoices = entity('pg_live_invoices', { columns: { id: uuid().primaryKey(), orgId: uuid() .references(() => orgs.id) .tenant(), reference: text({ max: 40 }), total: money(), paid: boolean().default(false), note: text().nullable(), issuedAt: timestamp().defaultNow(), deletedAt: timestamp().nullable(), }, }); /** * A composite primary key AND a tenant column — the two things a filtered delete has to survive * together. `delete(id)` cannot address a row here at all, which is the defect `deleteWhere` fixes, * and asserting the statement text proves nothing about whether Postgres accepts `delete … where * "invoice_id" = $1 and "label" = $2 and "org_id" = $3` or removes only the rows it names. */ const invoiceTags = entity('pg_live_invoice_tags', { columns: { invoiceId: uuid().references(() => invoices.id, { onDelete: 'cascade' }), label: text({ max: 40 }), orgId: uuid() .references(() => orgs.id) .tenant(), /** A non-key column, so `updateWhere` has something to write that is not part of the key. */ note: text().nullable(), }, primaryKey: ['invoiceId', 'label'], }); type Invoice = typeof invoices.$row; const DROP = 'drop table if exists "pg_live_invoice_tags", "pg_live_invoices", "pg_live_orgs" cascade'; describe.skipIf(!hasPostgres)('live · postgres · postgresDriver', () => { let client: PostgresClient; let migration: ReturnType; let acme = ''; let other = ''; beforeAll(async () => { client = postgresClient({ url: adminUrl ?? '' }); setDbClient(client); await client.execute(raw(DROP)); migration = generateMigration({ // Declaration order is dependency order: the foreign key needs `pg_live_orgs` first. entities: [orgs.$describe(), invoices.$describe(), invoiceTags.$describe()], name: 'live driver', now: new Date('2026-08-10T00:00:00.000Z'), }); for (const statement of statementsOf(migration.up)) await client.execute(raw(statement)); const db = database({ orgs }, { driver: postgresDriver() }); acme = (await db.orgs.insert({ slug: 'acme' })).id; other = (await db.orgs.insert({ slug: 'globex' })).id; }); afterAll(async () => { await client.execute(raw(DROP)); await client.close(); setDbClient(undefined); }); const db = () => database({ orgs, invoices }, { driver: postgresDriver() }); const repo = () => postgresRepo(invoices); const write = (orgId: string, reference: string, patch: Partial = {}) => db().invoices.insert({ orgId, reference, total: { minor: 1000, currency: 'USD' }, ...patch, }); /** * A request, as the coalescer needs one and as production hands it over: a context whose actor * carries the tenant. Coalescing is keyed on the ctx, so these tests have always needed one — * what they never needed to say before is who was asking, and the tenant is now derived from * that. The `{ orgId }` arguments below stay exactly as they were: they name the actor's own * org, so they are a restatement, and the statement asserted here is the proof — a second * tenant predicate would show up as an extra bind. */ const inRequestFor = (orgId: string, work: () => Promise): Promise => runWithContext(ctxOf({ actor: userActor({ id: 'live-reader', orgId }) }), work); /** A page walk asserts over a whole tenant, so each one needs a tenant nobody else wrote to. */ const newOrg = async (slug: string): Promise => (await database({ orgs }, { driver: postgresDriver() }).orgs.insert({ slug })).id; /** Pages to exhaustion from `cursor`, in the order the driver handed the rows back. */ const _walkFrom = async (args: FindManyArgs, cursor: string | null): Promise => { const rows: Invoice[] = []; let next = cursor; let more = true; // Bounded: a seek that stops advancing has to fail the test, never hang the run. for (let page = 0; page < 12 && more; page += 1) { const result: Page = await repo().findMany({ ...args, cursor: next }); rows.push(...result.rows); next = result.nextCursor; more = next !== null; } expect(next).toBeNull(); return rows; }; const _referencesOf = (rows: readonly Invoice[]): string[] => rows.map((row) => row.reference); /** The cursor a page had to hand back — otherwise `string | null` leaks into every caller. */ const _cursorOf = (page: Page): string => { expect(page.nextCursor).toBeTypeOf('string'); return page.nextCursor ?? ''; }; test('the generated migration is a migration Postgres accepts', () => { // Both halves are load-bearing and both were wrong: the unique column must not also get an // explicit `create unique index` (Postgres already made one under that exact name), and the // currency must carry its length or the CHECK on the same line can never be satisfied. expect(migration.up).toContain('"slug" text not null unique'); expect(migration.up).not.toContain('create unique index "pg_live_orgs_slug_key"'); expect(migration.up).toContain('"total_currency" char(3)'); // The third money column, nullable and range-checked — emitted by the same projection. expect(migration.up).toContain('"total_scale" integer'); // beforeAll applied it; a table that did not exist would have failed every statement after. expect(statementsOf(migration.up).length).toBeGreaterThan(0); }); test('a row survives the round trip through real column types', async () => { const written = await write(acme, 'INV-round-trip', { total: { minor: 12_500, currency: 'EUR' }, }); // Every one of these came back from Postgres, not from the object that was passed in. expect(written.total).toEqual({ minor: 12_500, currency: 'EUR' }); expect(written.paid).toBe(false); expect(written.note).toBeNull(); expect(written.issuedAt).toBeInstanceOf(Date); expect(Number.isNaN(written.issuedAt.getTime())).toBe(false); expect(written.id).toMatch(/^[0-9a-f-]{36}$/); const read = await repo().findById(written.id, { orgId: acme }); expect(read?.total).toEqual({ minor: 12_500, currency: 'EUR' }); expect(read?.reference).toBe('INV-round-trip'); }); // `col in ($1, $2)` with a NULL bound is `col = null` — UNKNOWN, so the very row the caller // listed is the one Postgres leaves out, while `memoryRepo`'s `matches` includes it through // `sameValue(null, null)`. Only a real server can prove the emitted `(… in (…) or … is null)` // is the pair that closes the gap; the statement TEXT is `pg-sql.test.ts`'s half. test('an `in` list carrying a null matches the null rows too, as memory does', async () => { const org = await newOrg('in-null'); await write(org, 'INV-noted', { note: 'kept' }); await write(org, 'INV-blank', { note: null }); const found = await repo().findMany({ orgId: org, where: [{ column: 'note', op: 'in', value: ['kept', null] }], }); expect(found.rows.map((row) => row.reference).sort()).toEqual(['INV-blank', 'INV-noted']); }); test('an `in` operand that is not a list matches nothing, as memory answers for it', async () => { const org = await newOrg('in-scalar'); await write(org, 'INV-solo'); const found = await repo().findMany({ orgId: org, where: [{ column: 'reference', op: 'in', value: 'INV-solo' }], }); expect(found.rows).toEqual([]); }); test('a SCALED amount survives the round trip, and an absent scale stays absent', async () => { // The third money column against a real int2/int4: `{ minor: 16, currency: 'USD', scale: 5 }` // is $0.00016, and the entity layer used to store and read it back as $16.00 — a 10,000x // reinterpretation with no error anywhere. A recording client cannot prove the column exists. const scaled = await write(acme, 'INV-scaled', { total: { minor: 16, currency: 'USD', scale: 5 }, }); expect(scaled.total).toEqual({ minor: 16, currency: 'USD', scale: 5 }); expect((await repo().findById(scaled.id, { orgId: acme }))?.total).toEqual({ minor: 16, currency: 'USD', scale: 5, }); // NULL in the column is "the currency's own minor unit", and it must decode to an ABSENT key: // `scale: 0` is a different value — whole units — and would be a 100x error on every price. const plain = await write(acme, 'INV-unscaled', { total: { minor: 1250, currency: 'USD' } }); const read = await repo().findById(plain.id, { orgId: acme }); expect(read?.total).toEqual({ minor: 1250, currency: 'USD' }); expect(Object.hasOwn(read?.total ?? {}, 'scale')).toBe(false); }); test('the scale column carries its own CHECK, so a psql session cannot write 42 either', async () => { const insert = client.execute( raw( `insert into "pg_live_invoices" ("org_id", "reference", "total_minor", "total_currency", "total_scale")` + ` values ('${acme}', 'INV-badscale', 100, 'USD', 42)`, ), ); await expect(insert).rejects.toThrow(); }); test('a CHECK the entity declared is enforced by Postgres, not only by $assert', async () => { // `total_currency ~ '^[A-Z]{3}$'` is a real constraint on a real table. Reaching it means // going around `$assert`, which is exactly what a second writer to the same database does. const insert = client.execute( raw( `insert into "pg_live_invoices" ("org_id", "reference", "total_minor", "total_currency")` + ` values ('${acme}', 'INV-bad', 100, 'us')`, ), ); await expect(insert).rejects.toThrow(); }); test('update writes the patch and returns the row Postgres stored', async () => { const written = await write(acme, 'INV-update'); const updated = await repo().update( written.id, { paid: true, note: 'settled', total: { minor: 999, currency: 'GBP' } }, { orgId: acme }, ); expect(updated.paid).toBe(true); expect(updated.note).toBe('settled'); expect(updated.total).toEqual({ minor: 999, currency: 'GBP' }); expect((await repo().findById(written.id, { orgId: acme }))?.note).toBe('settled'); }); test('soft delete hides the row and includeDeleted brings it back', async () => { const written = await write(acme, 'INV-soft'); await repo().delete(written.id, { orgId: acme }); expect(await repo().findById(written.id, { orgId: acme })).toBeNull(); const revealed = await repo().findById(written.id, { orgId: acme, includeDeleted: true }); expect(revealed?.deletedAt).toBeInstanceOf(Date); }); test('point lookups in one request are one statement, and it answers like the singles did', async () => { const first = await write(acme, 'INV-batch-1'); const second = await write(acme, 'INV-batch-2'); const hidden = await write(acme, 'INV-batch-3'); await repo().delete(hidden.id, { orgId: acme }); const foreign = await write(other, 'INV-batch-4'); // The observer is how "one statement" is asserted against a real server: there is no // recording client here, and the count is the whole claim. const reads: string[] = []; const offStatements = subscribe('db.statement', ({ payload: event }) => { if (event.text.includes('from "pg_live_invoices"')) reads.push(event.text); }); try { const rows = await inRequestFor(acme, () => Promise.all([ repo().findById(first.id, { orgId: acme }), repo().findById(second.id, { orgId: acme }), repo().findById(hidden.id, { orgId: acme }), repo().findById(foreign.id, { orgId: acme }), repo().findById(first.id, { orgId: acme }), ]), ); expect(reads).toHaveLength(1); // Five lookups, four binds: the repeated id is one of them. expect(reads[0]).toContain('"id" in ($1, $2, $3, $4)'); // Every answer is the one the single statement gave — Postgres applied the tenant predicate // and the `deleted_at is null` clause inside the coalesced statement, not the process after. expect(rows.map((row) => row?.reference ?? null)).toEqual([ 'INV-batch-1', 'INV-batch-2', null, null, 'INV-batch-1', ]); } finally { offStatements(); } }); test('a sequential loop over a page of tags is two statements against the invoices it points at', async () => { // The JIT-preload half of the same claim, against a real server: `findMany` on `invoiceTags` // leaves its page's `invoiceId` values behind, so a `for … of` loop that follows — one // `await` per iteration, no two lookups sharing a microtask — costs one widened `in` query // for the whole page, not one `select` per row. const org = await newOrg('jit-live'); const tags = () => postgresRepo(invoiceTags); const written = await Promise.all( ['JIT-1', 'JIT-2', 'JIT-3'].map((reference) => write(org, reference)), ); for (const invoice of written) { await tags().insert({ invoiceId: invoice.id, orgId: org, label: 'primary', note: null }); } // Filtered to the two tables under test, as the sibling test above is: any incidental // statement in this window — a connection-checkout `set`, a pool keepalive, a `begin` — would // otherwise read as "expected 2, got 3" with nothing naming the intruder. const statements: string[] = []; const offStatements = subscribe('db.statement', ({ payload: event }) => { if (/from "pg_live_(?:invoice_tags|invoices)"/.test(event.text)) statements.push(event.text); }); try { const references = await inRequestFor(org, async () => { const page = await tags().findMany({ orgId: org }); const seen: string[] = []; for (const tagRow of page.rows) { const invoice = await repo().findById(tagRow.invoiceId, { orgId: org }); seen.push(invoice?.reference ?? 'missing'); } return seen; }); // The tags page, and one `in (…)` statement for the three invoices it named — never three. expect(statements).toHaveLength(2); const invoiceReads = statements.filter((text) => text.includes('from "pg_live_invoices"')); expect(invoiceReads).toHaveLength(1); expect(invoiceReads[0]).toContain('"id" in ($1, $2, $3)'); expect(references.slice().sort()).toEqual(['JIT-1', 'JIT-2', 'JIT-3']); } finally { offStatements(); } }); test('delete on an entity without a soft-delete column removes the row', async () => { const target = await database({ orgs }, { driver: postgresDriver() }).orgs.insert({ slug: 'hard-delete', }); await postgresRepo(orgs).delete(target.id); expect(await postgresRepo(orgs).findById(target.id)).toBeNull(); const rows = await client.query<{ count: string }>( raw(`select count(*) as count from "pg_live_orgs" where "slug" = 'hard-delete'`), ); expect(Number(rows[0]?.count)).toBe(0); }); test('updateWhere cannot reach a soft-deleted row, and rolls back with its transaction', async () => { const org = await newOrg('update-where'); const target = await write(org, 'PATCH-a'); await write(org, 'PATCH-b'); expect(await repo().updateWhere({ paid: false }, { note: 'both' }, { orgId: org })).toBe(2); expect((await repo().findById(target.id, { orgId: org }))?.note).toBe('both'); // Soft-delete one, then patch the pair again: only the live row is reachable, exactly as // `update(id, patch)` on the deleted one would have been X_NOT_FOUND. await repo().delete(target.id, { orgId: org }); expect(await repo().updateWhere({ paid: false }, { note: 'live only' }, { orgId: org })).toBe( 1, ); expect((await repo().findById(target.id, { orgId: org, includeDeleted: true }))?.note).toBe( 'both', ); const failed = postgresTransactor().run(async () => { expect(await repo().updateWhere({ paid: false }, { note: 'rolled' }, { orgId: org })).toBe(1); throw new Error('roll it back'); }); await expect(failed).rejects.toThrow('roll it back'); expect( (await repo().findMany({ orgId: org })).rows.every((row) => row.note === 'live only'), ).toBe(true); }); test('deleteWhere soft-deletes where delete(id) would, and rolls back with its transaction', async () => { const org = await newOrg('delete-where-soft'); for (const reference of ['SOFT-a', 'SOFT-b']) await write(org, reference); expect(await repo().deleteWhere({ paid: false }, { orgId: org })).toBe(2); expect(await repo().count({ orgId: org })).toBe(0); expect(await repo().count({ orgId: org, includeDeleted: true })).toBe(2); // Already stamped, so the `deleted_at is null` clause means a second call matches nothing — // the row's original deletion time survives. expect(await repo().deleteWhere({ paid: false }, { orgId: org })).toBe(0); const survivor = await newOrg('delete-where-rollback'); await write(survivor, 'ROLL-a'); const failed = postgresTransactor().run(async () => { expect(await repo().deleteWhere({ reference: 'ROLL-a' }, { orgId: survivor })).toBe(1); throw new Error('roll it back'); }); await expect(failed).rejects.toThrow('roll it back'); expect(await repo().count({ orgId: survivor })).toBe(1); }); }); // Outside the block above and unconditional: bun runs no hook inside a skipped `describe`, and the // registry is process-wide. `live-registry-cleanup.test.ts` is the rule that keeps it here. afterAll(() => { clearRegistry(); });