Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ service's integration suite, not here.
| `src/stamp.ts` | Soft-delete and authorship, as one middleware. |
| `src/access-scope.ts` | Row-level access-scope middleware. |
| `src/audit.ts` | Audit-trail middleware, writing through its own pool. |
| `src/audited.ts` | Internal: the tables a derivation records, keyed by its relation map. |
| `src/archive.ts` | Row-archiving installer (aged rows → mirror `archive` schema, pg_cron). |
| `src/change-notify.ts` | Postgres row-change `NOTIFY` trigger installer. |
| `src/pretty-sql.ts` | `prettifySql()` SQL pretty-printer for query logging. |
Expand Down Expand Up @@ -112,6 +113,13 @@ service's integration suite, not here.
narrows the read it replaced: soft-delete and access scope both filter
updates. `test/unit/repository.spec.ts` counts the statements against the
real client and a recording pool.
- **A trail sees only rows a statement returns.** A bulk count (`deleteAndCount`,
`updateAndCount`) returns none, and a `select` narrows `RETURNING`, so on a
recorded table `Repository` sends `… RETURNING` with the whole row and cuts
the result down to the `select` itself. Other tables keep the bare count.
`repositoriesFor` learns which tables are recorded from the `relations` map
`deriveDataLayer` returned (`src/audited.ts`), because callers pass that map
alone; `audited` overrides it.
- **`silently()` flips a shared module flag** — it is for pre-request one-offs
(startup DDL), not interleaved concurrent traffic.

Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ export const db = postgres<Contract>({
caller never orders them, and so cannot order them wrongly. Call
`layer.close()` on shutdown to release the audit pool.

The trail records a write from the rows the database returns. So
`repositoriesFor(db, { relations: layer.derived.relations })` makes every write
to a recorded table return its rows whole: `removeBulk` and `updateBulk` send
`… RETURNING` instead of a bare count, and a `select` narrows what the caller
gets back, not what the trail sees. Tables in `auditExclude` keep the bare
count. Without a trail at all, pass `audited: {}` to keep it everywhere.

## Access scope

Scope is the one thing that cannot be derived from the contract — Prisma Next
Expand Down
59 changes: 59 additions & 0 deletions src/audited.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*!
* @imqueue/pg-prisma — the tables a derivation records, by its relation map
*
* I'm Queue Software Project
* Copyright (C) 2026 imqueue.com <support@imqueue.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* If you want to use this code in a closed source (commercial) project, you can
* purchase a proprietary commercial license. Please contact us at
* <support@imqueue.com> to get commercial licensing options.
*/

/**
* Internal, and not in the barrel.
*
* @remarks
* `repositoriesFor` is handed the relation map alone, as every caller already
* builds it, yet has to know which tables a trail records: their bulk writes
* must return rows for the trail to see. The derivation that made the map
* knows, so it says so here, keyed by the map it handed out.
*/
const AUDITED = new WeakMap<object, Readonly<Record<string, string>>>();

/**
* Note the tables recorded alongside the relation map derived with them.
*
* @param relations - The relation map a derivation returned.
* @param tables - Its audited tables, physical table to model.
*/
export function noteAudited(
relations: object,
tables: Readonly<Record<string, string>>,
): void {
AUDITED.set(relations, tables);
}

/**
* The tables recorded alongside a relation map, if a derivation made it.
*
* @param relations - The relation map a repository was given.
* @returns Physical table to model, or undefined for a map built by hand.
*/
export function auditedWith(
relations: object,
): Readonly<Record<string, string>> | undefined {
return AUDITED.get(relations);
}
25 changes: 15 additions & 10 deletions src/derive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* <support@imqueue.com> to get commercial licensing options.
*/

import { noteAudited } from './audited.js';
import { TIMESTAMP_CODECS } from './iso-dates.js';

/** The slice of an emitted `contract.json` this derivation reads. */
Expand Down Expand Up @@ -294,6 +295,18 @@ export function deriveDataLayer({
: {}),
};
};
const audit = Object.fromEntries(
entries
.filter(entry => !excluded.has(entry.model))
.map(entry => [entry.table, entry.model]),
);
const relations: RelationMap = Object.fromEntries(
entries
.filter(entry => Object.keys(entry.relations).length > 0)
.map(entry => [entry.model, entry.relations]),
);

noteAudited(relations, audit);

return {
dates: new Set(
Expand All @@ -310,11 +323,7 @@ export function deriveDataLayer({
.map(entry => [entry.table, stamped(entry)] as const)
.filter(([, columns]) => Object.keys(columns).length > 0),
),
audit: Object.fromEntries(
entries
.filter(entry => !excluded.has(entry.model))
.map(entry => [entry.table, entry.model]),
),
audit,
scope: Object.fromEntries(
Object.entries(scope).map(([model, levels]) => [
byModel.get(model)?.table ?? model,
Expand All @@ -328,10 +337,6 @@ export function deriveDataLayer({
),
]),
),
relations: Object.fromEntries(
entries
.filter(entry => Object.keys(entry.relations).length > 0)
.map(entry => [entry.model, entry.relations]),
),
relations,
};
}
87 changes: 76 additions & 11 deletions src/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* <support@imqueue.com> to get commercial licensing options.
*/

import { auditedWith } from './audited.js';
import type { RelationInfo, RelationMap } from './derive.js';
import {
type Fields,
Expand Down Expand Up @@ -144,6 +145,9 @@ export interface Repository<Entity = unknown> {
removeBulk(args: { where?: Where }): Promise<BulkCount>;
}

/** Rows a write returns: awaited whole, or streamed. */
type Rows = PromiseLike<unknown[]> & AsyncIterable<unknown>;

/** The ORM collection this façade drives. */
interface Collection {
where(predicate: unknown): Collection;
Expand All @@ -156,7 +160,8 @@ interface Collection {
first(): Promise<unknown>;
create(input: object): Promise<unknown>;
update(input: object): Promise<unknown>;
updateAll(input: object): PromiseLike<unknown[]>;
updateAll(input: object): Rows;
deleteAll(): Rows;
createAll(rows: readonly object[]): Promise<unknown[]>;
upsert(args: {
create: object;
Expand All @@ -176,6 +181,43 @@ export interface RepositoryOptions {
relations: RelationMap;
/** Namespace the models live in. Defaults to `public`. */
namespace?: string;
/**
* Tables the audit trail records, physical table to model, as
* `deriveDataLayer` gives them in `audit`.
*
* @remarks
* A trail records a write from the rows the database returns, so a write
* to one of these returns its rows whole: a bulk update or delete is
* `… RETURNING` rather than a bare count, and a `select` narrows what the
* caller is given rather than what the statement returns. Every other
* table keeps the count alone.
*
* Omitted, it is the `audit` of the `deriveDataLayer` call `relations`
* came from. Pass `{}` where no trail is kept.
*/
audited?: Readonly<Record<string, string>>;
}

/** Count rows as they stream, without holding them. */
async function counted(rows: AsyncIterable<unknown>): Promise<number> {
let count = 0;

for await (const _row of rows) {
count += 1;
}

return count;
}

/** A written row cut down to the fields its `select` named. */
function picked(row: unknown, fields: readonly string[]): unknown {
if (row === null || row === undefined) {
return row;
}

return Object.fromEntries(
fields.map(field => [field, (row as Record<string, unknown>)[field]]),
);
}

/** Apply a projection's scalar half and its relation branches. */
Expand Down Expand Up @@ -233,9 +275,12 @@ export function repositoriesFor<
orm: Record<string, Record<string, Collection>>;
transaction?: Transactional['transaction'];
},
{ relations, namespace = 'public' }: RepositoryOptions,
{ relations, namespace = 'public', audited }: RepositoryOptions,
): Repositories {
const models = db.orm[namespace] ?? {};
const recorded = new Set(
Object.values(audited ?? auditedWith(relations) ?? {}),
);

// A nested create is several inserts, so it has to commit as one. Already
// inside a transaction the client has no `transaction` of its own and the
Expand All @@ -254,6 +299,10 @@ export function repositoriesFor<
scope: Record<string, Collection> = models,
): Repository => {
const collection = (): Collection => scope[model] as Collection;
// The trail records what a statement returns. A bulk count returns
// nothing, and a narrowed RETURNING can leave out the id it keys on,
// so a recorded table's writes return the whole row.
const whole = recorded.has(model);
const filtered = (where?: Where): Collection => {
const predicate = toPredicate(relations, model, where);

Expand Down Expand Up @@ -282,13 +331,15 @@ export function repositoriesFor<
? []
: (projection?.fields ?? []);
const written = await run(
scalars.length > 0
scalars.length > 0 && !whole
? collection().select(...scalars)
: collection(),
);

if (!projection?.includes.length) {
return written;
return scalars.length > 0 && whole
? picked(written, scalars)
: written;
}

return project(
Expand All @@ -314,11 +365,17 @@ export function repositoriesFor<
? []
: (projection?.fields ?? []);

return (await (
scalars.length > 0
const rows = await (
scalars.length > 0 && !whole
? collection().select(...scalars)
: collection()
).createAll(args.input)) as Entity[];
).createAll(args.input);

return (
scalars.length > 0 && whole
? rows.map(row => picked(row, scalars))
: rows
) as Entity[];
},
async create<Entity>(args: {
input: object;
Expand Down Expand Up @@ -504,14 +561,22 @@ export function repositoriesFor<
where?: Where;
input: object;
}): Promise<BulkCount> {
const query = filtered(args.where);

return {
count: await filtered(args.where).updateAndCount(
args.input,
),
count: whole
? await counted(query.updateAll(args.input))
: await query.updateAndCount(args.input),
};
},
async removeBulk(args: { where?: Where }): Promise<BulkCount> {
return { count: await filtered(args.where).deleteAndCount() };
const query = filtered(args.where);

return {
count: whole
? await counted(query.deleteAll())
: await query.deleteAndCount(),
};
},
};
};
Expand Down
Loading
Loading