@ultimat3/entity 31.8.0 → 31.10.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.
Files changed (82) hide show
  1. package/CLAUDE.md +2 -1
  2. package/README.md +78 -1
  3. package/package.json +5 -5
  4. package/src/adapter.ts +2 -2
  5. package/src/aggregate.ts +1 -1
  6. package/src/all-truncated.ts +33 -0
  7. package/src/append-only-errors.ts +2 -1
  8. package/src/append-only.ts +24 -2
  9. package/src/batch-bytes.ts +34 -0
  10. package/src/bulk-write-send.ts +38 -5
  11. package/src/bulk-write.ts +3 -0
  12. package/src/copy-plan.ts +40 -0
  13. package/src/counter-observed.ts +199 -0
  14. package/src/database.ts +4 -2
  15. package/src/declared-index-keys.ts +65 -0
  16. package/src/declared-index.ts +6 -1
  17. package/src/define-driver.ts +24 -2
  18. package/src/describe.ts +6 -0
  19. package/src/driver-counters.ts +21 -0
  20. package/src/driver-repo-reads.ts +76 -9
  21. package/src/driver-repo-writes.ts +104 -6
  22. package/src/driver-versioned-write.ts +99 -0
  23. package/src/entity-error.ts +6 -0
  24. package/src/entity-indexes.ts +118 -0
  25. package/src/entity.ts +20 -49
  26. package/src/history-purge.ts +15 -0
  27. package/src/index-def.ts +35 -0
  28. package/src/index-identity.ts +5 -0
  29. package/src/index-init.ts +13 -1
  30. package/src/index-name.ts +25 -6
  31. package/src/index.ts +19 -2
  32. package/src/latest-by-sql.ts +93 -0
  33. package/src/latest-by.ts +249 -0
  34. package/src/lock-key.ts +56 -3
  35. package/src/lock-unsupported.ts +5 -2
  36. package/src/measures.ts +157 -0
  37. package/src/memory-aggregates.ts +9 -16
  38. package/src/memory-latest-by.ts +34 -0
  39. package/src/memory-lock.ts +15 -1
  40. package/src/memory-match.ts +2 -0
  41. package/src/memory-measures.ts +75 -0
  42. package/src/memory-observed.ts +7 -1
  43. package/src/memory-repo.ts +60 -6
  44. package/src/memory-update.ts +17 -4
  45. package/src/page-bytes.ts +127 -0
  46. package/src/pg-aggregates.ts +9 -3
  47. package/src/pg-bulk-repo.ts +163 -0
  48. package/src/pg-copy.ts +87 -0
  49. package/src/pg-driver.ts +31 -72
  50. package/src/pg-latest-by.ts +57 -0
  51. package/src/pg-lock.ts +24 -4
  52. package/src/pg-measures.ts +64 -0
  53. package/src/pg-sql-aggregate.ts +9 -3
  54. package/src/pg-sql-measures.ts +102 -0
  55. package/src/pg-sql.ts +37 -6
  56. package/src/pg-update-many-sql.ts +146 -0
  57. package/src/pg-values-list.ts +55 -0
  58. package/src/pg-write-sql.ts +42 -26
  59. package/src/plan.ts +1 -56
  60. package/src/preload-ceiling.ts +73 -7
  61. package/src/preload.ts +17 -1
  62. package/src/query-write.ts +169 -0
  63. package/src/query.ts +38 -48
  64. package/src/read-aggregates.ts +87 -3
  65. package/src/registry.ts +29 -0
  66. package/src/repo.ts +74 -3
  67. package/src/row-observer.ts +68 -5
  68. package/src/sealed-repo.ts +78 -9
  69. package/src/search-mirrored-repo.ts +53 -0
  70. package/src/search-repo.ts +20 -2
  71. package/src/table-locks.ts +16 -1
  72. package/src/tenant-index.ts +84 -9
  73. package/src/text-contains.ts +53 -0
  74. package/src/type-pins.ts +9 -0
  75. package/src/types.ts +2 -22
  76. package/src/unique-constraints.ts +3 -1
  77. package/src/update-many-send.ts +97 -0
  78. package/src/update-many.ts +175 -0
  79. package/src/version-lock-errors.ts +42 -0
  80. package/src/version-lock.ts +177 -0
  81. package/src/view-repo.ts +4 -0
  82. package/src/write-where.ts +164 -0
@@ -0,0 +1,75 @@
1
+ // Single responsibility: the in-memory driver's `aggregates(measures)` and the filtered `countBy` —
2
+ // each measure folded over the rows its own filter keeps, by the same `matchesPredicate` the read
3
+ // path filters with and the same `foldAggregate` `aggregate()` answers with.
4
+
5
+ import { foldAggregate } from './aggregate-fold';
6
+ import { countsFrom, groupColumnOf } from './count-by';
7
+ import { valueAt } from './cursor';
8
+ import type { EntityCore } from './entity';
9
+ import {
10
+ type CountByOptions,
11
+ type MeasureReads,
12
+ type PlannedMeasure,
13
+ planMeasures,
14
+ screenMeasureFilter,
15
+ } from './measures';
16
+ import { matchesPredicate } from './memory-match';
17
+ import type { FindManyArgs } from './repo';
18
+ import type { Predicate } from './tenancy';
19
+
20
+ /** `memoryRepo`'s own read: the plan built and guarded, the visible rows it matches. */
21
+ type MemorySelect<Row> = (args: FindManyArgs, operation: string) => { found: Row[] };
22
+
23
+ const keeps =
24
+ <Row>(entity: EntityCore<Row>, where: readonly Predicate[]) =>
25
+ (row: Row): boolean =>
26
+ where.every((predicate) => matchesPredicate(entity, row, predicate));
27
+
28
+ const measureOf = <Row>(entity: EntityCore<Row>, measure: PlannedMeasure, rows: readonly Row[]) => {
29
+ const kept = measure.where.length === 0 ? rows : rows.filter(keeps(entity, measure.where));
30
+ const { property, column } = measure;
31
+ if (measure.fn === 'count') {
32
+ if (property === undefined) return kept.length;
33
+ // `count(col)` counts non-null values; `?? null` reads an absent property as the NULL it is.
34
+ return kept.filter((row) => (valueAt(row, property) ?? null) !== null).length;
35
+ }
36
+ return foldAggregate(entity, measure.fn, property ?? '', column?.$meta.kind ?? 'integer', kept);
37
+ };
38
+
39
+ export const memoryMeasures = <Row>(
40
+ entity: EntityCore<Row>,
41
+ select: MemorySelect<Row>,
42
+ ): MeasureReads => ({
43
+ async aggregates(measures, args = {}) {
44
+ const planned = planMeasures(entity, measures);
45
+ const { found } = select(args, 'aggregate');
46
+ return Object.fromEntries(
47
+ planned.map((measure) => [measure.name, measureOf(entity, measure, found)]),
48
+ );
49
+ },
50
+ });
51
+
52
+ /**
53
+ * `countBy` with a filter: every group the chain matched, counting only the rows `where` keeps — so
54
+ * a group none of them satisfy is present with 0, as `count(*) filter (where …)` answers it. That
55
+ * is what makes it not `andWhere(…).countBy(…)`, which drops the group.
56
+ */
57
+ export const memoryCountBy = async <Row>(
58
+ entity: EntityCore<Row>,
59
+ select: MemorySelect<Row>,
60
+ column: string,
61
+ args: FindManyArgs = {},
62
+ options: CountByOptions = {},
63
+ ): Promise<ReadonlyMap<unknown, number>> => {
64
+ groupColumnOf(entity, column, 'countBy');
65
+ const where = screenMeasureFilter(entity, options.where ?? []);
66
+ const { found } = select(args, 'countBy');
67
+ const counted = keeps(entity, where);
68
+ const groups = new Map<unknown, number>();
69
+ for (const row of found) {
70
+ // `?? null`, so a property this row never carried lands in the group Postgres puts NULL in.
71
+ const value = valueAt(row, column) ?? null;
72
+ groups.set(value, (groups.get(value) ?? 0) + (counted(row) ? 1 : 0));
73
+ }
74
+ return countsFrom(entity, column, 'countBy', [...groups]);
75
+ };
@@ -27,11 +27,17 @@ const OPERATIONS = {
27
27
  count: { verb: 'select', rows: one },
28
28
  countBy: { verb: 'select', rows: none },
29
29
  aggregate: { verb: 'select', rows: one },
30
+ aggregates: { verb: 'select', rows: one },
31
+ latestBy: { verb: 'select', rows: listed },
30
32
  series: { verb: 'select', rows: listed },
31
33
  approximateCount: { verb: 'select', rows: one },
32
34
  insert: { verb: 'insert', rows: one },
33
35
  insertAll: { verb: 'insert', rows: listed },
34
36
  upsertAll: { verb: 'insert', rows: listed },
37
+ insertAllCount: { verb: 'insert', rows: counted },
38
+ upsertAllCount: { verb: 'insert', rows: counted },
39
+ copyAll: { verb: 'insert', rows: counted },
40
+ updateMany: { verb: 'update', rows: counted },
35
41
  update: { verb: 'update', rows: one },
36
42
  updateWhere: { verb: 'update', rows: counted },
37
43
  delete: { verb: 'delete', rows: () => 1 },
@@ -41,7 +47,7 @@ const OPERATIONS = {
41
47
  type Operation = keyof typeof OPERATIONS;
42
48
 
43
49
  /** Taken before the body runs, as Postgres answers the lock before the body it guards. */
44
- const LOCKS = ['lock', 'lockKey'] as const;
50
+ const LOCKS = ['lock', 'lockKey', 'lockKeys'] as const;
45
51
 
46
52
  const report = (
47
53
  entity: string,
@@ -12,15 +12,17 @@ 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';
18
19
  import { invariantViolated, notFound } from './errors';
19
20
  import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
20
- import { lockKeyInput } from './lock-key';
21
+ import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
21
22
  import { memoryAggregates } from './memory-aggregates';
22
23
  import { undoingBatch } from './memory-batch';
23
24
  import { memoryJournal } from './memory-journal';
25
+ import { memoryLatestBy } from './memory-latest-by';
24
26
  import { memoryLifecycle } from './memory-lifecycle';
25
27
  import { memoryLocks } from './memory-lock';
26
28
  import { compareByKind, matchesPredicate } from './memory-match';
@@ -30,7 +32,8 @@ import { afterCursor } from './memory-seek';
30
32
  import { StoredRows, uniqueIndex, uniqueViolation } from './memory-unique';
31
33
  import { judgeUpdate, mergedRow } from './memory-update';
32
34
  import { memoryUpsertAll } from './memory-upsert';
33
- import { deletePlan, idPlan, readPlan, singleKeyOf, updatePlan } from './plan';
35
+ import { assertPageBytes } from './page-bytes';
36
+ import { idPlan, readPlan, singleKeyOf } from './plan';
34
37
  import type { FindManyArgs, MemoryRepo, RepoOptions } from './repo';
35
38
  import { rowKey } from './row-key';
36
39
  import { sealedFields } from './sealed';
@@ -39,7 +42,10 @@ import { deletionStamp } from './search-index-version';
39
42
  import { writtenRowsSink } from './search-written-rows';
40
43
  import type { QueryPlan } from './tenancy';
41
44
  import { assertRowTenant } from './tenancy';
42
- import type { RowWrite } from './types';
45
+ import type { RowPatch, RowWrite } from './types';
46
+ import { judgeUpdateMany, updateManyPlan } from './update-many';
47
+ import { assertVersionedUpdate } from './version-lock';
48
+ import { updateWherePlan, writeWherePlan } from './write-where';
43
49
 
44
50
  const field = (row: unknown, property: string): unknown =>
45
51
  typeof row === 'object' && row !== null ? (row as Record<string, unknown>)[property] : undefined;
@@ -252,8 +258,15 @@ export const memoryRepo = <Row>(
252
258
  const more = start + page.length < found.length;
253
259
  // Projected as `pg-sql.ts` projects (`driver-rows.ts`): the asked columns, the key and the
254
260
  // sort keys — the cursor is minted from the stored row, which holds all of them anyway.
261
+ // The PROJECTED page is weighed, as Postgres weighs the columns it was asked for.
262
+ const projected = page.map((row) => projectRow(entity, plan, row));
263
+ assertPageBytes(
264
+ entity,
265
+ 'findMany',
266
+ projected as readonly Readonly<Record<string, unknown>>[],
267
+ );
255
268
  return pageOf(
256
- page.map((row) => projectRow(entity, plan, row)),
269
+ projected,
257
270
  more && last !== undefined ? cursorFor(entity, plan, last, storeKey(last)) : null,
258
271
  );
259
272
  },
@@ -299,6 +312,8 @@ export const memoryRepo = <Row>(
299
312
  update: writing(async (id, given, options) => {
300
313
  // Here and in `pg-driver.ts`, the one door: a value `insert` refuses, a fragment included.
301
314
  const patch = entity.$parsePatch(given);
315
+ // `mergedRow` does the compare-and-set and the increment (`version-lock.ts`).
316
+ assertVersionedUpdate(entity, patch);
302
317
  addressed(id, options, 'update');
303
318
  return locks.turn(`row:${idStoreKey(id, 'update')}`, options?.tx, () => {
304
319
  const current = addressed(id, options, 'update');
@@ -329,7 +344,7 @@ export const memoryRepo = <Row>(
329
344
  // soft-delete visibility. A row already stamped is not matched, so a second call cannot
330
345
  // move `deletedAt` forward — which is what the Postgres driver's `deleted_at is null`
331
346
  // clause says there.
332
- const doomed = rowsOf(deletePlan(entity, filter, options, 'deleteWhere'), {});
347
+ const doomed = rowsOf(writeWherePlan(entity, filter, options, 'deleteWhere'), {});
333
348
  // A soft delete is an update, so an app-only rule judges it: bounded as `updateWhere` is, and
334
349
  // one row refused takes the rows before it with it, as the statement does in Postgres.
335
350
  if (entity.$softDelete && hasJsOnlyInvariant(entity.$invariants)) {
@@ -354,7 +369,7 @@ export const memoryRepo = <Row>(
354
369
 
355
370
  updateWhere: writing(async (filter, given, options) => {
356
371
  const patch = entity.$parsePatch(given);
357
- const plan = updatePlan(entity, filter, patch, options, 'updateWhere');
372
+ const plan = updateWherePlan(entity, filter, patch, options, 'updateWhere');
358
373
  // The PATCH, judged whole and before the rows are read — the same call `postgresRepo` makes
359
374
  // before its statement exists. Inside the loop below it is judged only where a row was
360
375
  // matched, so a patch handing rows to another tenant was refused or accepted depending on
@@ -385,11 +400,39 @@ export const memoryRepo = <Row>(
385
400
  return found.length;
386
401
  }),
387
402
 
403
+ // Nothing is decoded in memory, so a count is the rows' length: the same judging, one answer.
404
+ insertAllCount: async (given, options) => (await repo.insertAll(given, options)).length,
405
+ upsertAllCount: async (given, args) => (await repo.upsertAll(given, args)).length,
406
+ copyAll: async (given, options) => {
407
+ copyColumns(entity, given as readonly RowPatch<Row>[]);
408
+ return (await repo.insertAll(given, options)).length;
409
+ },
410
+
411
+ // `updateWhere`'s path with a patch per row: matched by the read path, judged whole first.
412
+ updateMany: writing(async (given, options) => {
413
+ const plan = updateManyPlan(entity, given, options);
414
+ if (plan.patches.length === 0) return 0;
415
+ // By key, never `rowsOf(plan.match)`: an `in` of n ids over n stored rows is n² comparisons,
416
+ // and 40,000 of each never returned. Each row then passes the scope as a read would judge it.
417
+ const found = plan.patches.flatMap(({ id }) => {
418
+ const row = rows.get(idStoreKey(id, 'updateMany'));
419
+ return row !== undefined && visibleTo({})(row) && matchesPlan(plan.scope, row) ? [row] : [];
420
+ });
421
+ const merged = judgeUpdateMany(entity, plan, found, untouched(found), storeKey);
422
+ for (const row of merged) judgeReferences(row);
423
+ const written = merged.map((row, at) =>
424
+ write(row, options, 'updateMany', storeKey(found[at])),
425
+ );
426
+ if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
427
+ return written.length;
428
+ }),
429
+
388
430
  async count(args = {}) {
389
431
  return select(args, 'count').found.length;
390
432
  },
391
433
 
392
434
  ...memoryAggregates(entity, select),
435
+ ...memoryLatestBy(entity, select),
393
436
 
394
437
  // Asked before the wait, so another tenant's id never queues behind that tenant's holder, and
395
438
  // again after it, because the row may be gone by then: Postgres re-reads a row it waited for.
@@ -401,6 +444,17 @@ export const memoryRepo = <Row>(
401
444
  );
402
445
  })(),
403
446
 
447
+ // Every key through the one-key queue, sorted, each inside the last: `lockKey`'s spelling.
448
+ lockKeys: (keys, fn, options) =>
449
+ writing(async () =>
450
+ holdInOrder(
451
+ lockKeysInput(entity, keys, options),
452
+ (input, outer, body) => locks.run(`key:${input}`, outer, body),
453
+ fn,
454
+ options?.tx,
455
+ ),
456
+ )(),
457
+
404
458
  lockKey: (key, fn, options) =>
405
459
  writing(async () =>
406
460
  locks.run(`key:${lockKeyInput(entity, key, options)}`, options?.tx, fn),
@@ -10,8 +10,10 @@
10
10
  import { narrowRow } from './columns';
11
11
  import type { EntityCore } from './entity';
12
12
  import { uniqueIndex, uniqueViolation } from './memory-unique';
13
+ import { rowKey } from './row-key';
13
14
  import { advanceVersion } from './search-index-version';
14
15
  import { assertRowTenant } from './tenancy';
16
+ import { versionedMerge } from './version-lock';
15
17
 
16
18
  /**
17
19
  * The patch with every `undefined` property dropped — `bindValues` skips them in Postgres, so a
@@ -34,7 +36,11 @@ export const mergedRow = <Row>(entity: EntityCore<Row>, row: Row, patch: object)
34
36
  const given = defined(patch);
35
37
  const merged = narrowRow<Row>(entity.$columns, Object.assign({}, row, given));
36
38
  // A searchable entity's version moves past the stored one even inside one millisecond.
37
- return advanceVersion(entity, row, merged, (property) => Object.hasOwn(given, property));
39
+ const advanced = advanceVersion(entity, row, merged, (property) =>
40
+ Object.hasOwn(given, property),
41
+ );
42
+ // A declared lock: a patch naming a version the row has left is stale, and every merge counts.
43
+ return versionedMerge(entity, row, given, advanced, (stored) => rowKey(entity, stored));
38
44
  };
39
45
 
40
46
  /**
@@ -49,24 +55,31 @@ export const mergedRow = <Row>(entity: EntityCore<Row>, row: Row, patch: object)
49
55
  *
50
56
  * The judgement is the whole batch's, so a refusal lands before anything is stored — the shape
51
57
  * `insertAll` already has, and the shape Postgres gives the statement it refuses.
58
+ *
59
+ * `patch` is one patch for every row (`updateWhere`) or the patch for each row (`updateMany`), where
60
+ * `undefined` leaves that row out of the batch. `op` is the call a refusal names.
52
61
  */
53
62
  export const judgeUpdate = <Row>(
54
63
  entity: EntityCore<Row>,
55
64
  matched: readonly Row[],
56
- patch: object,
65
+ patch: object | ((row: Row) => object | undefined),
57
66
  untouched: readonly Row[],
58
67
  key: (row: unknown) => string,
68
+ op = 'updateWhere',
59
69
  ): readonly Row[] => {
70
+ const patchOf = typeof patch === 'function' ? patch : () => patch;
60
71
  const judged: Row[] = [];
61
72
  const judgedKeys = new Set<string>();
62
73
  const untouchedKeys = new Set(untouched.map((row) => key(row)));
63
74
  // Built once and grown by each result: rebuilt per matched row, a sweep cost matched x stored.
64
75
  const taken = uniqueIndex(entity, untouched);
65
76
  for (const row of matched) {
66
- const result = mergedRow(entity, row, patch);
77
+ const given = patchOf(row);
78
+ if (given === undefined) continue;
79
+ const result = mergedRow(entity, row, given);
67
80
  // The same four judgements `write` makes, in the same order — on the merged row rather than
68
81
  // on the patch, and on the whole batch rather than on the row that happens to come first.
69
- assertRowTenant(entity.$name, entity.$tenantColumn, 'updateWhere', result);
82
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, result);
70
83
  entity.$assert(result);
71
84
  // The primary key: a result may not land on a key another row holds — neither one this write
72
85
  // 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
+ };
@@ -9,6 +9,8 @@ import { decodeAggregate } from './aggregate-decode';
9
9
  import { moneyColumns } from './column';
10
10
  import { countsFrom, groupColumnOf, groupValue, MAX_GROUPS } from './count-by';
11
11
  import type { EntityCore } from './entity';
12
+ import { type CountByOptions, type MeasureReads, screenMeasureFilter } from './measures';
13
+ import { postgresMeasures } from './pg-measures';
12
14
  import type { ReadShape } from './pg-sql';
13
15
  import {
14
16
  type AggregateRow,
@@ -30,7 +32,8 @@ import type { MoneyValue } from './types';
30
32
  type AggregateReads<Row> = Pick<
31
33
  Required<Repo<Row>>,
32
34
  'aggregate' | 'approximateCount' | 'countBy' | 'series'
33
- >;
35
+ > &
36
+ MeasureReads;
34
37
 
35
38
  const shapeOf = (args: FindManyArgs): ReadShape => ({
36
39
  includeDeleted: args.includeDeleted === true,
@@ -90,16 +93,19 @@ export const postgresAggregates = <Row>(
90
93
  };
91
94
 
92
95
  return {
93
- async countBy(column, args = {}) {
96
+ ...postgresMeasures(entity, client),
97
+
98
+ async countBy(column, args = {}, options: CountByOptions = {}) {
94
99
  const op = 'countBy';
95
100
  const grouped = groupColumnOf(entity, column, op);
101
+ const where = screenMeasureFilter(entity, options.where ?? []);
96
102
  const plan = readPlan(entity, args, op);
97
103
  // One group past the bound, for the same reason a page reads one row past its limit: the
98
104
  // presence of that group is what says the answer was never going to fit, and `countsFrom`
99
105
  // refuses it rather than hand back a breakdown missing its tail.
100
106
  const rows = await attributed(op, () =>
101
107
  client().query<GroupRow>(
102
- countByStatement(entity, plan, shapeOf(args), column, MAX_GROUPS + 1),
108
+ countByStatement(entity, plan, shapeOf(args), column, MAX_GROUPS + 1, where),
103
109
  ),
104
110
  );
105
111
  return countsFrom(
@@ -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, plan)),
158
+ );
159
+ if (sink !== undefined && returning) sink(written);
160
+ return count;
161
+ },
162
+ };
163
+ };