@ultimat3/entity 31.7.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.
- package/CLAUDE.md +1 -1
- package/README.md +30 -1
- package/package.json +5 -5
- package/src/adapter.ts +2 -2
- package/src/append-only-errors.ts +2 -1
- package/src/append-only.ts +16 -1
- package/src/batch-bytes.ts +34 -0
- package/src/bulk-write-send.ts +38 -5
- package/src/copy-plan.ts +40 -0
- package/src/declared-index.ts +3 -2
- package/src/describe.ts +3 -2
- package/src/driver-repo-reads.ts +5 -4
- package/src/driver-repo-writes.ts +81 -5
- package/src/entity-error.ts +2 -0
- package/src/index-identity.ts +13 -8
- package/src/index-init.ts +3 -0
- package/src/index.ts +6 -2
- package/src/memory-observed.ts +4 -0
- package/src/memory-repo.ts +43 -5
- package/src/memory-update.ts +10 -3
- package/src/page-bytes.ts +127 -0
- package/src/pg-bulk-repo.ts +163 -0
- package/src/pg-copy.ts +87 -0
- package/src/pg-driver.ts +18 -71
- package/src/pg-update-many-sql.ts +103 -0
- package/src/pg-values-list.ts +55 -0
- package/src/pg-write-sql.ts +10 -22
- package/src/plan.ts +1 -56
- package/src/query-write.ts +169 -0
- package/src/query.ts +24 -47
- package/src/registry.ts +4 -3
- package/src/repo.ts +40 -2
- package/src/row-observer.ts +39 -1
- package/src/sealed-repo.ts +48 -7
- package/src/search-mirrored-repo.ts +53 -0
- package/src/type-pins.ts +9 -0
- package/src/types.ts +5 -2
- package/src/update-many-send.ts +66 -0
- package/src/update-many.ts +170 -0
- package/src/view-repo.ts +4 -0
- package/src/write-where.ts +161 -0
package/src/memory-repo.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { appendOnlyRepo } from './append-only';
|
|
|
12
12
|
import { keyOf } from './batch-read';
|
|
13
13
|
import { entityNow } from './clock';
|
|
14
14
|
import { narrowRow } from './columns';
|
|
15
|
+
import { copyColumns } from './copy-plan';
|
|
15
16
|
import { cursorFor, kindOf, valueAt } from './cursor';
|
|
16
17
|
import { projectRow } from './driver-rows';
|
|
17
18
|
import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
|
|
@@ -30,7 +31,8 @@ import { afterCursor } from './memory-seek';
|
|
|
30
31
|
import { StoredRows, uniqueIndex, uniqueViolation } from './memory-unique';
|
|
31
32
|
import { judgeUpdate, mergedRow } from './memory-update';
|
|
32
33
|
import { memoryUpsertAll } from './memory-upsert';
|
|
33
|
-
import {
|
|
34
|
+
import { assertPageBytes } from './page-bytes';
|
|
35
|
+
import { idPlan, readPlan, singleKeyOf } from './plan';
|
|
34
36
|
import type { FindManyArgs, MemoryRepo, RepoOptions } from './repo';
|
|
35
37
|
import { rowKey } from './row-key';
|
|
36
38
|
import { sealedFields } from './sealed';
|
|
@@ -39,7 +41,9 @@ import { deletionStamp } from './search-index-version';
|
|
|
39
41
|
import { writtenRowsSink } from './search-written-rows';
|
|
40
42
|
import type { QueryPlan } from './tenancy';
|
|
41
43
|
import { assertRowTenant } from './tenancy';
|
|
42
|
-
import type { RowWrite } from './types';
|
|
44
|
+
import type { RowPatch, RowWrite } from './types';
|
|
45
|
+
import { judgeUpdateMany, updateManyPlan } from './update-many';
|
|
46
|
+
import { updateWherePlan, writeWherePlan } from './write-where';
|
|
43
47
|
|
|
44
48
|
const field = (row: unknown, property: string): unknown =>
|
|
45
49
|
typeof row === 'object' && row !== null ? (row as Record<string, unknown>)[property] : undefined;
|
|
@@ -252,8 +256,15 @@ export const memoryRepo = <Row>(
|
|
|
252
256
|
const more = start + page.length < found.length;
|
|
253
257
|
// Projected as `pg-sql.ts` projects (`driver-rows.ts`): the asked columns, the key and the
|
|
254
258
|
// sort keys — the cursor is minted from the stored row, which holds all of them anyway.
|
|
259
|
+
// The PROJECTED page is weighed, as Postgres weighs the columns it was asked for.
|
|
260
|
+
const projected = page.map((row) => projectRow(entity, plan, row));
|
|
261
|
+
assertPageBytes(
|
|
262
|
+
entity,
|
|
263
|
+
'findMany',
|
|
264
|
+
projected as readonly Readonly<Record<string, unknown>>[],
|
|
265
|
+
);
|
|
255
266
|
return pageOf(
|
|
256
|
-
|
|
267
|
+
projected,
|
|
257
268
|
more && last !== undefined ? cursorFor(entity, plan, last, storeKey(last)) : null,
|
|
258
269
|
);
|
|
259
270
|
},
|
|
@@ -329,7 +340,7 @@ export const memoryRepo = <Row>(
|
|
|
329
340
|
// soft-delete visibility. A row already stamped is not matched, so a second call cannot
|
|
330
341
|
// move `deletedAt` forward — which is what the Postgres driver's `deleted_at is null`
|
|
331
342
|
// clause says there.
|
|
332
|
-
const doomed = rowsOf(
|
|
343
|
+
const doomed = rowsOf(writeWherePlan(entity, filter, options, 'deleteWhere'), {});
|
|
333
344
|
// A soft delete is an update, so an app-only rule judges it: bounded as `updateWhere` is, and
|
|
334
345
|
// one row refused takes the rows before it with it, as the statement does in Postgres.
|
|
335
346
|
if (entity.$softDelete && hasJsOnlyInvariant(entity.$invariants)) {
|
|
@@ -354,7 +365,7 @@ export const memoryRepo = <Row>(
|
|
|
354
365
|
|
|
355
366
|
updateWhere: writing(async (filter, given, options) => {
|
|
356
367
|
const patch = entity.$parsePatch(given);
|
|
357
|
-
const plan =
|
|
368
|
+
const plan = updateWherePlan(entity, filter, patch, options, 'updateWhere');
|
|
358
369
|
// The PATCH, judged whole and before the rows are read — the same call `postgresRepo` makes
|
|
359
370
|
// before its statement exists. Inside the loop below it is judged only where a row was
|
|
360
371
|
// matched, so a patch handing rows to another tenant was refused or accepted depending on
|
|
@@ -385,6 +396,33 @@ export const memoryRepo = <Row>(
|
|
|
385
396
|
return found.length;
|
|
386
397
|
}),
|
|
387
398
|
|
|
399
|
+
// Nothing is decoded in memory, so a count is the rows' length: the same judging, one answer.
|
|
400
|
+
insertAllCount: async (given, options) => (await repo.insertAll(given, options)).length,
|
|
401
|
+
upsertAllCount: async (given, args) => (await repo.upsertAll(given, args)).length,
|
|
402
|
+
copyAll: async (given, options) => {
|
|
403
|
+
copyColumns(entity, given as readonly RowPatch<Row>[]);
|
|
404
|
+
return (await repo.insertAll(given, options)).length;
|
|
405
|
+
},
|
|
406
|
+
|
|
407
|
+
// `updateWhere`'s path with a patch per row: matched by the read path, judged whole first.
|
|
408
|
+
updateMany: writing(async (given, options) => {
|
|
409
|
+
const plan = updateManyPlan(entity, given, options);
|
|
410
|
+
if (plan.patches.length === 0) return 0;
|
|
411
|
+
// By key, never `rowsOf(plan.match)`: an `in` of n ids over n stored rows is n² comparisons,
|
|
412
|
+
// and 40,000 of each never returned. Each row then passes the scope as a read would judge it.
|
|
413
|
+
const found = plan.patches.flatMap(({ id }) => {
|
|
414
|
+
const row = rows.get(idStoreKey(id, 'updateMany'));
|
|
415
|
+
return row !== undefined && visibleTo({})(row) && matchesPlan(plan.scope, row) ? [row] : [];
|
|
416
|
+
});
|
|
417
|
+
const merged = judgeUpdateMany(entity, plan, found, untouched(found), storeKey);
|
|
418
|
+
for (const row of merged) judgeReferences(row);
|
|
419
|
+
const written = merged.map((row, at) =>
|
|
420
|
+
write(row, options, 'updateMany', storeKey(found[at])),
|
|
421
|
+
);
|
|
422
|
+
if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
|
|
423
|
+
return written.length;
|
|
424
|
+
}),
|
|
425
|
+
|
|
388
426
|
async count(args = {}) {
|
|
389
427
|
return select(args, 'count').found.length;
|
|
390
428
|
},
|
package/src/memory-update.ts
CHANGED
|
@@ -49,24 +49,31 @@ export const mergedRow = <Row>(entity: EntityCore<Row>, row: Row, patch: object)
|
|
|
49
49
|
*
|
|
50
50
|
* The judgement is the whole batch's, so a refusal lands before anything is stored — the shape
|
|
51
51
|
* `insertAll` already has, and the shape Postgres gives the statement it refuses.
|
|
52
|
+
*
|
|
53
|
+
* `patch` is one patch for every row (`updateWhere`) or the patch for each row (`updateMany`), where
|
|
54
|
+
* `undefined` leaves that row out of the batch. `op` is the call a refusal names.
|
|
52
55
|
*/
|
|
53
56
|
export const judgeUpdate = <Row>(
|
|
54
57
|
entity: EntityCore<Row>,
|
|
55
58
|
matched: readonly Row[],
|
|
56
|
-
patch: object,
|
|
59
|
+
patch: object | ((row: Row) => object | undefined),
|
|
57
60
|
untouched: readonly Row[],
|
|
58
61
|
key: (row: unknown) => string,
|
|
62
|
+
op = 'updateWhere',
|
|
59
63
|
): readonly Row[] => {
|
|
64
|
+
const patchOf = typeof patch === 'function' ? patch : () => patch;
|
|
60
65
|
const judged: Row[] = [];
|
|
61
66
|
const judgedKeys = new Set<string>();
|
|
62
67
|
const untouchedKeys = new Set(untouched.map((row) => key(row)));
|
|
63
68
|
// Built once and grown by each result: rebuilt per matched row, a sweep cost matched x stored.
|
|
64
69
|
const taken = uniqueIndex(entity, untouched);
|
|
65
70
|
for (const row of matched) {
|
|
66
|
-
const
|
|
71
|
+
const given = patchOf(row);
|
|
72
|
+
if (given === undefined) continue;
|
|
73
|
+
const result = mergedRow(entity, row, given);
|
|
67
74
|
// The same four judgements `write` makes, in the same order — on the merged row rather than
|
|
68
75
|
// on the patch, and on the whole batch rather than on the row that happens to come first.
|
|
69
|
-
assertRowTenant(entity.$name, entity.$tenantColumn,
|
|
76
|
+
assertRowTenant(entity.$name, entity.$tenantColumn, op, result);
|
|
70
77
|
entity.$assert(result);
|
|
71
78
|
// The primary key: a result may not land on a key another row holds — neither one this write
|
|
72
79
|
// does not touch, nor one an earlier result of this same batch took. A row's OWN old version
|
|
@@ -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 {
|
|
40
|
-
import {
|
|
41
|
-
import type { FindManyArgs, 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
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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 =
|
|
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 =
|
|
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);
|