@ultimat3/entity 31.8.0 → 31.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,127 @@
1
+ // Single responsibility: bound a page by BYTES, measured on the rows a driver answered before one
2
+ // of them is decoded. `MAX_PAGE_SIZE` bounds rows, and 10,000 rows of a 1 MiB `jsonb` is 10 GiB
3
+ // that `decodeRow` would then copy again. Both drivers call `assertPageBytes` on one number, so a
4
+ // test against memory refuses the page production would.
5
+
6
+ import { columnName } from './column';
7
+ import type { EntityCore } from './entity';
8
+ import { EntityError } from './entity-error';
9
+
10
+ /**
11
+ * 64 MiB of cells. Measured 2026-11-11 over every `findMany` page in the reference app's and the
12
+ * demo app's suites: the heaviest is 16,560 bytes (120 `users` rows), so the bound sits over three
13
+ * orders of magnitude above every legitimate page, and well below what a container survives once
14
+ * the page is decoded. A constant, as `MAX_PAGE_SIZE` is: the fix for a heavy page is `select()`
15
+ * or a smaller `limit()`, never a wider bound.
16
+ */
17
+ export const MAX_PAGE_BYTES = 64 * 1024 * 1024;
18
+
19
+ /** A number, a boolean, a `Date`, a `null`, an object's or an array's own header. */
20
+ const SCALAR_BYTES = 8;
21
+
22
+ type Cells = Readonly<Record<string, unknown>>;
23
+
24
+ /**
25
+ * A cell's approximate weight: a string by its length (the wire's bytes for ASCII), binary by its
26
+ * `byteLength`, a parsed `jsonb` walked. Every object visited adds its header, so a cyclic value
27
+ * still grows the total and the walk ends at `stopAt` — a driver never answers one, an app's
28
+ * memory row might.
29
+ */
30
+ const cellBytes = (cell: unknown, stopAt: number): number => {
31
+ if (typeof cell === 'string') return cell.length;
32
+ if (cell === null || typeof cell !== 'object' || cell instanceof Date) return SCALAR_BYTES;
33
+ if (ArrayBuffer.isView(cell)) return cell.byteLength;
34
+ let total = 0;
35
+ const pending: unknown[] = [cell];
36
+ while (pending.length > 0 && total <= stopAt) {
37
+ const next = pending.pop();
38
+ if (typeof next === 'string') total += next.length;
39
+ else if (next === null || typeof next !== 'object' || next instanceof Date) {
40
+ total += SCALAR_BYTES;
41
+ } else if (ArrayBuffer.isView(next)) total += next.byteLength;
42
+ else if (next instanceof ArrayBuffer) total += next.byteLength;
43
+ else if (Array.isArray(next)) {
44
+ total += SCALAR_BYTES;
45
+ for (const item of next) pending.push(item);
46
+ } else {
47
+ total += SCALAR_BYTES;
48
+ // `for … in`, not `Object.entries`: measured 0.13 µs against 0.61 µs for a small `jsonb`,
49
+ // and this runs on every page. A parsed `jsonb` is a plain object, so nothing is inherited.
50
+ const record = next as Record<string, unknown>;
51
+ for (const key in record) {
52
+ total += key.length;
53
+ pending.push(record[key]);
54
+ }
55
+ }
56
+ }
57
+ return total;
58
+ };
59
+
60
+ /** How many rows were counted, and what they weighed, stopping at the row that passes `stopAt`. */
61
+ const measure = (rows: readonly Cells[], stopAt: number): { bytes: number; counted: number } => {
62
+ let bytes = 0;
63
+ let counted = 0;
64
+ for (const row of rows) {
65
+ for (const key in row) bytes += cellBytes(row[key], stopAt - bytes);
66
+ counted += 1;
67
+ if (bytes > stopAt) break;
68
+ }
69
+ return { bytes, counted };
70
+ };
71
+
72
+ /** What a page weighs, counted until it passes `stopAt` — past that the exact figure buys nothing. */
73
+ export const pageBytes = (rows: readonly Cells[], stopAt: number): number =>
74
+ measure(rows, stopAt).bytes;
75
+
76
+ /** Per column, on the refusal path only: which cell made the page heavy. */
77
+ const heaviestColumn = (rows: readonly Cells[], stopAt: number): string | undefined => {
78
+ const weights = new Map<string, number>();
79
+ for (const row of rows) {
80
+ for (const key in row) weights.set(key, (weights.get(key) ?? 0) + cellBytes(row[key], stopAt));
81
+ }
82
+ let heaviest: string | undefined;
83
+ let most = -1;
84
+ for (const [key, weight] of weights) {
85
+ if (weight > most) [heaviest, most] = [key, weight];
86
+ }
87
+ return heaviest;
88
+ };
89
+
90
+ /** A physical name back to the property the author declared; memory rows already use properties. */
91
+ const propertyOf = <Row>(entity: EntityCore<Row>, key: string): string => {
92
+ if (key in entity.$columns) return key;
93
+ for (const [property, column] of Object.entries(entity.$columns)) {
94
+ if (columnName(property, column.$meta) === key) return property;
95
+ }
96
+ return key;
97
+ };
98
+
99
+ const mib = (bytes: number): string => (bytes / (1024 * 1024)).toFixed(1);
100
+
101
+ /**
102
+ * Refuses a page heavier than `bound`, before a row of it is decoded. `bound` is the test seam;
103
+ * every driver passes nothing and gets `MAX_PAGE_BYTES`.
104
+ */
105
+ export const assertPageBytes = <Row>(
106
+ entity: EntityCore<Row>,
107
+ operation: string,
108
+ rows: readonly Cells[],
109
+ bound: number = MAX_PAGE_BYTES,
110
+ ): void => {
111
+ const { bytes, counted } = measure(rows, bound);
112
+ if (bytes <= bound) return;
113
+ // Judged on the rows counted before the bound broke, never a recount of the whole page: the
114
+ // refusal must stay as bounded as the read it refuses. Their average row is what sizes `limit`.
115
+ const weighed = rows.slice(0, counted);
116
+ const heavy = heaviestColumn(weighed, bound);
117
+ const heaviest = heavy === undefined ? undefined : propertyOf(entity, heavy);
118
+ const kept = Object.keys(entity.$columns).filter((property) => property !== heaviest);
119
+ const fits = Math.max(1, Math.floor((counted * bound) / bytes));
120
+ // The chain's own spelling — `select({ id: true })` — so the fix pastes onto the read as written.
121
+ const select = `{ ${kept.map((property) => `${property}: true`).join(', ')} }`;
122
+ throw new EntityError({
123
+ code: 'X_ENTITY_PAGE_TOO_LARGE',
124
+ cause: `${entity.$name}.${operation}() answered ${rows.length} rows, and the first ${counted} of them already weigh ${mib(bytes)} MiB before decoding — past the ${mib(bound)} MiB page bound, and every row would be decoded and held at once${heaviest === undefined ? '' : `. '${heaviest}' is the heaviest column`}`,
125
+ fix: `${entity.$name}.where(…).select(${select}).limit(${fits}) # on that read: only the columns the page renders, and a page that fits — or .inBatches(${fits}) to visit every row`,
126
+ });
127
+ };
@@ -0,0 +1,163 @@
1
+ // Single responsibility: the Postgres driver's row-batch writes — `insert`, `insertAll`,
2
+ // `upsertAll`, their count-only forms, `copyAll` and `updateMany`. Split from `pg-driver.ts` at its
3
+ // ceiling. One judging loop for every insert form, so a row refused by one is refused by all of
4
+ // them; what differs is only what crosses back (`returning *`, a count, or COPY's row count).
5
+
6
+ import type { DbClient } from '@ultimat3/db';
7
+ import { conflictKeys, insertColumns, statementColumns, upsertPlan } from './bulk-write';
8
+ import { countChunks, writeChunks } from './bulk-write-send';
9
+ import { narrowRow } from './columns';
10
+ import { copyColumns } from './copy-plan';
11
+ import type { EntityCore } from './entity';
12
+ import { copyRows } from './pg-copy';
13
+ import { bindValues } from './pg-row';
14
+ import { updateManyStatements } from './pg-update-many-sql';
15
+ import type { ConflictTarget } from './pg-write-sql';
16
+ import type { Repo, UpsertArgs } from './repo';
17
+ import { writtenRowsSink } from './search-written-rows';
18
+ import { assertRowTenant } from './tenancy';
19
+ import type { RowPatch, RowWrite } from './types';
20
+ import { updateManyPlan } from './update-many';
21
+ import { sendUpdateMany, updateManyReturns } from './update-many-send';
22
+
23
+ /** What `postgresRepo` already holds and these writes send through. */
24
+ export interface PgWriteContext<Row> {
25
+ readonly entity: EntityCore<Row>;
26
+ /** The connection for this call — the open transaction, the pinned client, or the pool. */
27
+ readonly client: () => DbClient;
28
+ /** The repository's pinned client, where a transaction it needs is opened. */
29
+ readonly pinned: DbClient | undefined;
30
+ readonly attributed: <T>(op: string, send: () => Promise<T>) => Promise<T>;
31
+ /** `pg-driver.ts`'s `writing`: preloads dropped, history actor stamped, the write tagged. */
32
+ readonly writing: <T>(send: () => Promise<T>) => Promise<T>;
33
+ }
34
+
35
+ export type PgBulkWrites<Row> = Required<
36
+ Pick<
37
+ Repo<Row>,
38
+ | 'insert'
39
+ | 'insertAll'
40
+ | 'upsertAll'
41
+ | 'insertAllCount'
42
+ | 'upsertAllCount'
43
+ | 'copyAll'
44
+ | 'updateMany'
45
+ >
46
+ >;
47
+
48
+ export const postgresBulkWrites = <Row>(context: PgWriteContext<Row>): PgBulkWrites<Row> => {
49
+ const { entity, client, pinned, attributed, writing } = context;
50
+
51
+ /** Where a batch stops being wide — before `upsertPlan` or a bind reads a row (`narrowRow`). */
52
+ const narrowed = (batch: readonly RowWrite<Row>[]): readonly Row[] =>
53
+ batch.map((row) => narrowRow<Row>(entity.$columns, row));
54
+
55
+ /**
56
+ * The whole batch judged before any statement exists, tenant and invariants together, in one
57
+ * loop and for one reason: Postgres refuses a statement as one, so a row this actor may not
58
+ * write must stop the rows beside it too. `memoryRepo`'s `write` runs the same pair — an insert
59
+ * builds no read plan, so this is the only place its tenant is checked. Then bound.
60
+ */
61
+ const judged = (op: string, batch: readonly Row[]): readonly ReadonlyMap<string, unknown>[] => {
62
+ for (const row of batch) {
63
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, row);
64
+ entity.$assert(row);
65
+ }
66
+ return batch.map((row) => bindValues(entity, row));
67
+ };
68
+
69
+ /**
70
+ * The one insert path, for one row or ten thousand: the batch's own column list, split into as
71
+ * many statements as Postgres's bind count allows. `insert(row)` comes through here too, so
72
+ * there is no second builder for the two to drift apart in. All or nothing however many
73
+ * statements it takes (`bulk-write-send.ts`). Attributed to the call that asked — the op.
74
+ */
75
+ const writeRows = async (
76
+ op: string,
77
+ batch: readonly Row[],
78
+ conflict: ConflictTarget | undefined,
79
+ ): Promise<readonly Row[]> => {
80
+ if (batch.length === 0) return [];
81
+ const bound = judged(op, batch);
82
+ const shape = { columns: statementColumns(entity, batch), conflict };
83
+ return attributed(op, () => writing(() => writeChunks(entity, bound, shape, client(), pinned)));
84
+ };
85
+
86
+ /** `writeRows` with no `returning *`: the same statements, a count back and nothing decoded. */
87
+ const countRows = async (
88
+ op: string,
89
+ batch: readonly Row[],
90
+ conflict: ConflictTarget | undefined,
91
+ ): Promise<number> => {
92
+ if (batch.length === 0) return 0;
93
+ const bound = judged(op, batch);
94
+ const shape = { columns: statementColumns(entity, batch), conflict, returning: false };
95
+ return attributed(op, () => writing(() => countChunks(entity, bound, shape, client(), pinned)));
96
+ };
97
+
98
+ /** The conflict target an upsert batch resolves against, refused where the drivers would differ. */
99
+ const upserting = (rows: readonly Row[], args: UpsertArgs<Row>): ConflictTarget => {
100
+ const { onConflict, onMatch = 'update', overwrites } = args;
101
+ const plan = upsertPlan(entity, rows, onConflict, onMatch, overwrites);
102
+ // A batch repeating a conflict target is `21000` in Postgres and a silent overwrite in memory.
103
+ conflictKeys(entity, plan, rows);
104
+ return { columns: insertColumns(entity, plan.on), set: insertColumns(entity, plan.set) };
105
+ };
106
+
107
+ return {
108
+ async insert(values) {
109
+ const row = narrowRow<Row>(entity.$columns, values);
110
+ const [written] = await writeRows('insert', [row], undefined);
111
+ // `returning *` is the row Postgres stored, defaults included. The fallback is the NARROWED
112
+ // row: handing the caller's back would answer with a `bigint` minor unit.
113
+ return written ?? row;
114
+ },
115
+
116
+ insertAll: async (batch) => writeRows('insertAll', narrowed(batch), undefined),
117
+
118
+ async upsertAll(batch, args) {
119
+ const rows = narrowed(batch);
120
+ return writeRows('upsertAll', rows, upserting(rows, args));
121
+ },
122
+
123
+ insertAllCount: async (batch) => countRows('insertAll', narrowed(batch), undefined),
124
+
125
+ async upsertAllCount(batch, args) {
126
+ const rows = narrowed(batch);
127
+ return countRows('upsertAll', rows, upserting(rows, args));
128
+ },
129
+
130
+ /**
131
+ * `COPY … FROM STDIN`: judged as `insertAll` judges, every row naming the same columns because
132
+ * COPY has no per-row `default` (`copy-plan.ts`). A client that cannot stream COPY — PGlite, a
133
+ * transaction wrapper, row security installed — sends the count-only inserts instead.
134
+ */
135
+ async copyAll(batch) {
136
+ const rows = narrowed(batch);
137
+ if (rows.length === 0) return 0;
138
+ const properties = copyColumns(entity, rows as readonly RowPatch<Row>[]);
139
+ const bound = judged('copyAll', rows);
140
+ const columns = insertColumns(entity, properties);
141
+ return attributed('copyAll', () =>
142
+ writing(() => copyRows(entity, bound, columns, client(), pinned)),
143
+ );
144
+ },
145
+
146
+ /**
147
+ * One `update … from (values …)` per bind-count chunk. Rows come back only when something
148
+ * still needs them: a JS-only invariant judging them, or the search mirror asking.
149
+ */
150
+ async updateMany(rows, options) {
151
+ const plan = updateManyPlan(entity, rows, options);
152
+ if (plan.patches.length === 0) return 0;
153
+ const sink = writtenRowsSink();
154
+ const returning = updateManyReturns(entity, plan, sink !== undefined);
155
+ const statements = updateManyStatements(entity, plan, returning);
156
+ const { count, rows: written } = await attributed('updateMany', () =>
157
+ writing(() => sendUpdateMany(entity, statements, returning, client(), pinned)),
158
+ );
159
+ if (sink !== undefined && returning) sink(written);
160
+ return count;
161
+ },
162
+ };
163
+ };
package/src/pg-copy.ts ADDED
@@ -0,0 +1,87 @@
1
+ // Single responsibility: `copyAll`'s send on Postgres — `COPY … FROM STDIN` in chunks of at most
2
+ // `MAX_ROWS_PER_COPY` when the client can stream one, the count-only insert when it cannot. The batch arrives judged
3
+ // and bound (`pg-bulk-repo.ts`); what is decided here is only which wire carries it, so the rows
4
+ // stored are the same either way.
5
+
6
+ import {
7
+ canCopyIn,
8
+ type DbClient,
9
+ identifier,
10
+ join,
11
+ type SqlFragment,
12
+ sql,
13
+ withTransaction,
14
+ } from '@ultimat3/db';
15
+ import { countChunks } from './bulk-write-send';
16
+ import type { EntityCore } from './entity';
17
+ import { allColumns } from './pg-row';
18
+
19
+ /**
20
+ * The statement a copy streams into. Identifiers only — the entity's own table and columns — and
21
+ * no value: COPY binds nothing, which `copyIn` refuses before any send.
22
+ */
23
+ export const copyStatement = <Row>(
24
+ entity: EntityCore<Row>,
25
+ columns: readonly string[],
26
+ ): SqlFragment =>
27
+ sql`copy ${identifier(entity.$table)} (${join(columns.map(identifier))}) from stdin`;
28
+
29
+ /** Each bound row as its cells in `columns`' order — lazily, so 100k rows are never a second array. */
30
+ function* cellsOf(
31
+ bound: readonly ReadonlyMap<string, unknown>[],
32
+ columns: readonly string[],
33
+ ): Generator<readonly unknown[]> {
34
+ for (const row of bound) yield columns.map((column) => row.get(column));
35
+ }
36
+
37
+ /**
38
+ * Rows per COPY statement. One statement must stay inside the role's `statement_timeout` and the
39
+ * pool's unanswered-statement sweep, which a single COPY of an unbounded batch does not: measured
40
+ * 2026-11-11 on loopback Postgres 17 at load 20+, a 50,000-row, 12-column COPY took 0.3-0.6 s.
41
+ */
42
+ export const MAX_ROWS_PER_COPY = 50_000;
43
+
44
+ /**
45
+ * Rows stored. Each chunk is one COPY; several are one transaction — a SAVEPOINT inside an open
46
+ * one — exactly as `countChunks` holds several inserts, so the batch is all or nothing. Inside a
47
+ * caller's transaction `direct` is that transaction's own client, and its pin copies.
48
+ *
49
+ * The insert is taken instead, and stores the same rows, when COPY would not mean the same thing:
50
+ * a client with no copy stream (PGlite, a fake), row security armed (`canCopyIn`: Postgres refuses
51
+ * COPY FROM under RLS), a row that does not bind every listed column (only a cell can spell
52
+ * `default`), or no column named at all (`copy t () from stdin` is a syntax error; an insert
53
+ * writes `default` in every cell).
54
+ */
55
+ export const copyRows = async <Row>(
56
+ entity: EntityCore<Row>,
57
+ bound: readonly ReadonlyMap<string, unknown>[],
58
+ columns: readonly string[],
59
+ direct: DbClient,
60
+ pinned: DbClient | undefined,
61
+ ): Promise<number> => {
62
+ if (bound.length === 0) return 0;
63
+ const complete = columns.length > 0 && bound.every((row) => columns.every((c) => row.has(c)));
64
+ if (!complete || !canCopyIn(direct)) {
65
+ // No column named is `statementColumns`' case too: every column listed, every cell `default`.
66
+ const listed = columns.length > 0 ? columns : allColumns(entity);
67
+ return countChunks(entity, bound, { columns: listed, returning: false }, direct, pinned);
68
+ }
69
+ const target = copyStatement(entity, columns);
70
+ if (bound.length <= MAX_ROWS_PER_COPY) return direct.copyIn(target, cellsOf(bound, columns));
71
+ const chunks: (readonly ReadonlyMap<string, unknown>[])[] = [];
72
+ for (let from = 0; from < bound.length; from += MAX_ROWS_PER_COPY) {
73
+ chunks.push(bound.slice(from, from + MAX_ROWS_PER_COPY));
74
+ }
75
+ return withTransaction(
76
+ async (tx) => {
77
+ let count = 0;
78
+ for (const chunk of chunks) {
79
+ count += canCopyIn(tx)
80
+ ? await tx.copyIn(target, cellsOf(chunk, columns))
81
+ : await countChunks(entity, chunk, { columns, returning: false }, tx, undefined);
82
+ }
83
+ return count;
84
+ },
85
+ pinned === undefined ? {} : { client: pinned },
86
+ );
87
+ };
package/src/pg-driver.ts CHANGED
@@ -17,11 +17,8 @@ import {
17
17
  withStatementAttribution,
18
18
  } from '@ultimat3/db';
19
19
  import { appendOnlyRepo } from './append-only';
20
- import { conflictKeys, insertColumns, statementColumns, upsertPlan } from './bulk-write';
21
- import { writeChunks } from './bulk-write-send';
22
20
  import { entityNow } from './clock';
23
21
  import { coalesceFindById } from './coalesce';
24
- import { narrowRow } from './columns';
25
22
  import { cursorFor, seekFrom } from './cursor';
26
23
  import type { Driver } from './database';
27
24
  import { noteDriverStore } from './driver-registry';
@@ -31,22 +28,24 @@ import { stampHistoryActor } from './history-actor';
31
28
  import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
32
29
  import { forgetPreloaded, tagSiblings } from './jit-preload';
33
30
  import { judgedWrite } from './judged-write';
31
+ import { assertPageBytes } from './page-bytes';
34
32
  import { postgresAggregates } from './pg-aggregates';
33
+ import { postgresBulkWrites } from './pg-bulk-repo';
35
34
  import { postgresLocks } from './pg-lock';
36
35
  import { bindValues, decodeRow, type PhysicalRow, physicalName, sortPrecision } from './pg-row';
37
36
  import { countStatement, type ReadShape, selectStatement } from './pg-sql';
38
37
  import { postgresTransactor } from './pg-transactor';
39
- import { type ConflictTarget, deleteStatement, updateStatement } from './pg-write-sql';
40
- import { deletePlan, idPlan, readPlan, updatePlan } from './plan';
41
- import type { FindManyArgs, Repo, UpsertArgs } from './repo';
38
+ import { deleteStatement, updateStatement } from './pg-write-sql';
39
+ import { idPlan, readPlan } from './plan';
40
+ import type { FindManyArgs, Repo } from './repo';
42
41
  import { rowKey } from './row-key';
43
42
  import { sealedRepo } from './sealed-repo';
44
43
  import { deletionStamp } from './search-index-version';
45
44
  import { writtenRowsSink } from './search-written-rows';
46
45
  import type { QueryPlan } from './tenancy';
47
46
  import { assertRowTenant } from './tenancy';
48
- import type { RowWrite } from './types';
49
47
  import { taggedWrite } from './write-tag';
48
+ import { updateWherePlan, writeWherePlan } from './write-where';
50
49
 
51
50
  export interface PostgresDriverOptions {
52
51
  /**
@@ -112,11 +111,6 @@ export const postgresRepo = <Row>(
112
111
  /** The cursor's id — `row-key.ts`, the spelling the memory driver stores a row under. */
113
112
  const idOf = (row: Row): string => rowKey(entity, row);
114
113
 
115
- /** Where a batch stops being wide — before `writeRows` or `upsertPlan` read a row. `narrowRow`
116
- * says why the position matters, and `memoryRepo` narrows at the same one. */
117
- const narrowed = (batch: readonly RowWrite<Row>[]): readonly Row[] =>
118
- batch.map((row) => narrowRow<Row>(entity.$columns, row));
119
-
120
114
  /**
121
115
  * A soft delete's SET list: the stamp, plus a searchable entity's version — advanced past the
122
116
  * stored one in the statement (`pg-write-sql.ts`), so a deletion is a newer version too.
@@ -238,39 +232,6 @@ export const postgresRepo = <Row>(
238
232
  ? judgedRows(op, plan, softDeletion(), shapeOf({}))
239
233
  : counted(op, plan, removalShape(), (returning) => removal(plan, returning));
240
234
 
241
- /**
242
- * The one insert path, for one row or ten thousand: the batch's own column list, split into as
243
- * many statements as Postgres's bind count allows, and the rows the server stored. `insert(row)`
244
- * comes through here too, so there is no second builder for the two to drift apart in. All or
245
- * nothing however many statements it takes (`bulk-write-send.ts`).
246
- */
247
- const writeRows = async (
248
- op: string,
249
- batch: readonly Row[],
250
- conflict: ConflictTarget | undefined,
251
- ): Promise<readonly Row[]> => {
252
- if (batch.length === 0) return [];
253
- // The whole batch is judged before any statement exists, tenant and invariants together, in
254
- // the same loop and for the same reason: Postgres refuses one statement as one, so a row this
255
- // actor may not write must stop the rows beside it too. `memoryRepo`'s `write` runs the same
256
- // pair — an insert builds no read plan, so this is the only place the tenant is checked.
257
- for (const row of batch) {
258
- assertRowTenant(entity.$name, entity.$tenantColumn, op, row);
259
- entity.$assert(row);
260
- }
261
- const bound = batch.map((row) => bindValues(entity, row));
262
- const shape = {
263
- columns: statementColumns(entity, batch),
264
- ...(conflict === undefined ? {} : { conflict }),
265
- };
266
- // Attributed here rather than in each of the three callers: a batch wide enough to split is
267
- // several statements sent inside this call, and every one of them belongs to the call that
268
- // asked for it — `insert`, `insertAll` or `upsertAll`, which is why the op is a parameter.
269
- return attributed(op, () =>
270
- writing(() => writeChunks(entity, bound, shape, client(), config.client)),
271
- );
272
- };
273
-
274
235
  const repo: Repo<Row> = {
275
236
  async findById(id, options) {
276
237
  const op = 'findById';
@@ -299,7 +260,10 @@ export const postgresRepo = <Row>(
299
260
  selectStatement(entity, plan, shapeOf(args, seekFrom(entity, plan)), plan.limit + 1),
300
261
  ),
301
262
  );
263
+ // Weighed raw, before a row is decoded — the PAGE, not the look-ahead row past it, or the
264
+ // `limit(n)` the refusal names would itself be refused.
302
265
  const page = found.slice(0, plan.limit);
266
+ assertPageBytes(entity, op, page);
303
267
  const rows = page.map((row) => decodeRow(entity, row));
304
268
  // What the page leaves behind: its foreign key values, so the first `findById` for any one
305
269
  // of them resolves the key for the whole page. A `for … of` loop over these rows costs one
@@ -323,30 +287,13 @@ export const postgresRepo = <Row>(
323
287
  );
324
288
  },
325
289
 
326
- async insert(values) {
327
- const row = narrowRow<Row>(entity.$columns, values);
328
- const [written] = await writeRows('insert', [row], undefined);
329
- // `returning *` is the row Postgres actually stored, defaults included. The fallback is the
330
- // NARROWED row: handing the caller's back would answer with a `bigint` minor unit.
331
- return written ?? row;
332
- },
333
-
334
- async insertAll(batch) {
335
- return writeRows('insertAll', narrowed(batch), undefined);
336
- },
337
-
338
- async upsertAll(batch, args: UpsertArgs<Row>) {
339
- const rows = narrowed(batch);
340
- const { onConflict, onMatch = 'update', overwrites } = args;
341
- const plan = upsertPlan(entity, rows, onConflict, onMatch, overwrites);
342
- // Refused here, not by the server: a batch that repeats a conflict target is `21000` in
343
- // Postgres and a silent overwrite in memory, and the two drivers have to mean one thing.
344
- conflictKeys(entity, plan, rows);
345
- return writeRows('upsertAll', rows, {
346
- columns: insertColumns(entity, plan.on),
347
- set: insertColumns(entity, plan.set),
348
- });
349
- },
290
+ ...postgresBulkWrites({
291
+ entity,
292
+ client,
293
+ pinned: config.client,
294
+ attributed,
295
+ writing,
296
+ }),
350
297
 
351
298
  async update(id, given, options) {
352
299
  // Here and in `memory-repo.ts`, the one door: a value `insert` refuses, a fragment included.
@@ -397,14 +344,14 @@ export const postgresRepo = <Row>(
397
344
  async deleteWhere(filter, options) {
398
345
  const op = 'deleteWhere';
399
346
  // The plan is built before the write is announced: a refused filter never happened.
400
- const plan = deletePlan(entity, filter, options, op);
347
+ const plan = writeWherePlan(entity, filter, options, op);
401
348
  return removed(op, plan);
402
349
  },
403
350
 
404
351
  async updateWhere(filter, given, options) {
405
352
  const patch = entity.$parsePatch(given);
406
353
  const op = 'updateWhere';
407
- const plan = updatePlan(entity, filter, patch, options, op);
354
+ const plan = updateWherePlan(entity, filter, patch, options, op);
408
355
  // The same move, filtered: one statement can hand away every row it matches.
409
356
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
410
357
  const values = bindValues(entity, patch);
@@ -0,0 +1,103 @@
1
+ // Single responsibility: compile an `updateMany` batch into `update … from (…) as v` statements —
2
+ // a different value per row, one statement per bind-count chunk. Nothing is interpolated: every
3
+ // cell is bound and every identifier is the entity's or one of the closed aliases written here.
4
+ //
5
+ // Measured (Postgres 17, Bun's `sql`): a bound `values ($1, $2), …` list resolves its columns as
6
+ // `text`, so `uuid = text` refuses the join. A `select <columns> from <table> where false` head,
7
+ // `union all`-ed with one `select $…` per row, types every column from the TABLE instead: a leaf's
8
+ // unknown parameters take the union's common type. No type name is spelled here, so none can drift.
9
+
10
+ import { identifier, join, type SqlFragment, sql } from '@ultimat3/db';
11
+ import { MAX_BIND_PARAMETERS } from './bulk-write';
12
+ import { columnName } from './column';
13
+ import type { EntityCore } from './entity';
14
+ import { bindValues, physicalName } from './pg-row';
15
+ import { conditions } from './pg-sql';
16
+ import { VERSION_STEP_SQL } from './pg-write-sql';
17
+ import { advancingVersionColumn } from './search-index-version';
18
+ import type { UpdateManyPlan } from './update-many';
19
+
20
+ /**
21
+ * The source's column names. Upper case, which no physical column can be (`seekAlias` relies on
22
+ * the same rule), so the scope's unqualified `"org_id" = $n` can never be ambiguous with them.
23
+ */
24
+ const KEY_ALIAS = 'K$UM';
25
+ const aliasOf = (position: number): string => `C${position}$UM`;
26
+ const SOURCE = identifier('v');
27
+
28
+ /** Physical `jsonb` columns, resolved once per batch. */
29
+ const jsonColumns = <Row>(entity: EntityCore<Row>): ReadonlySet<string> => {
30
+ const names = new Set<string>();
31
+ for (const [property, column] of Object.entries(entity.$columns)) {
32
+ if (column.$meta.kind === 'jsonb') names.add(columnName(property, column.$meta));
33
+ }
34
+ return names;
35
+ };
36
+
37
+ /** A searchable entity's version column, physical: advanced past the stored one, never set back. */
38
+ const versionColumn = <Row>(entity: EntityCore<Row>): string | undefined => {
39
+ const property = advancingVersionColumn(entity as EntityCore<unknown>);
40
+ return property === undefined ? undefined : physicalName(entity, property);
41
+ };
42
+
43
+ /** Rows per statement: what the bind budget left after the scope's own binds, over one row's width. */
44
+ const chunked = <T>(items: readonly T[], width: number, reserved: number): readonly T[][] => {
45
+ const size = Math.max(1, Math.floor((MAX_BIND_PARAMETERS - reserved) / width));
46
+ const chunks: T[][] = [];
47
+ for (let from = 0; from < items.length; from += size) chunks.push(items.slice(from, from + size));
48
+ return chunks;
49
+ };
50
+
51
+ /**
52
+ * One statement per chunk. `returning` is `"<table>".*`, never `*`: a bare star would add the
53
+ * source's columns to every row handed back. Without it the answer is a count.
54
+ */
55
+ export const updateManyStatements = <Row>(
56
+ entity: EntityCore<Row>,
57
+ plan: UpdateManyPlan<Row>,
58
+ returning: boolean,
59
+ ): readonly SqlFragment[] => {
60
+ if (plan.patches.length === 0) return [];
61
+ const table = identifier(entity.$table);
62
+ const keyColumn = physicalName(entity, plan.key);
63
+ const bound = plan.patches.map(({ id, patch }) => ({
64
+ key: bindValues(entity, { [plan.key]: id } as typeof patch).get(keyColumn),
65
+ values: bindValues(entity, patch),
66
+ }));
67
+ // Every patch names the same properties (`updateManyPlan`), so the first row's physical columns
68
+ // are every row's — money's two or three included.
69
+ const columns = [...(bound[0]?.values.keys() ?? [])];
70
+ const json = jsonColumns(entity);
71
+ const version = versionColumn(entity);
72
+ const where = conditions(entity, plan.scope, { includeDeleted: false });
73
+ const head = sql`select ${join([
74
+ sql`${identifier(keyColumn)} as ${identifier(KEY_ALIAS)}`,
75
+ ...columns.map((column, at) => sql`${identifier(column)} as ${identifier(aliasOf(at))}`),
76
+ ])} from ${table} where false`;
77
+ const set = join(
78
+ columns.map((column, at) => {
79
+ const next = sql`${SOURCE}.${identifier(aliasOf(at))}`;
80
+ return column === version
81
+ ? sql`${identifier(column)} = greatest(${next}, ${table}.${identifier(column)} + ${VERSION_STEP_SQL})`
82
+ : sql`${identifier(column)} = ${next}`;
83
+ }),
84
+ );
85
+ const tail = returning ? sql` returning ${table}.*` : sql``;
86
+ return chunked(bound, columns.length + 1, where.values.length).map((chunk) => {
87
+ const legs = chunk.map(
88
+ (row) =>
89
+ sql`select ${join([
90
+ sql`${row.key}`,
91
+ ...columns.map((column) =>
92
+ json.has(column)
93
+ ? sql`${row.values.get(column)}::text::jsonb`
94
+ : sql`${row.values.get(column)}`,
95
+ ),
96
+ ])}`,
97
+ );
98
+ const source = join([head, ...legs], ' union all ');
99
+ return sql`update ${table} set ${set} from (${source}) as ${SOURCE} where ${table}.${identifier(
100
+ keyColumn,
101
+ )} = ${SOURCE}.${identifier(KEY_ALIAS)} and ${where}${tail}`;
102
+ });
103
+ };