@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
package/src/database.ts CHANGED
@@ -105,8 +105,10 @@ export const database = <E extends EntitySet>(
105
105
  // Wrapped here rather than in a driver, so a committed row change is reported the same whether
106
106
  // rows live in memory or in Postgres — `entity.row` on the bus, and with no subscriber the
107
107
  // wrapper is one map read per write. `related` below stays unwrapped on purpose: a relation
108
- // preload is a READ, and a change feed has nothing to say about one.
109
- tables[key] = tableFor(entity, observedRepo(entity, driver.repo(entity)), related);
108
+ // preload is a READ, and a change feed has nothing to say about one. The driver's own
109
+ // repositories are how the observer reads back a parent a `countedIn` trigger moved.
110
+ const observed = observedRepo(entity, driver.repo(entity), (parent) => driver.repo(parent));
111
+ tables[key] = tableFor(entity, observed, related);
110
112
  }
111
113
  // Built key by key from `entities`, so each table is the one `Database<E>` names.
112
114
  return tables as Database<E>;
@@ -0,0 +1,65 @@
1
+ // The four key parts one `indexes:` entry may declare past a column list — an expression key, a
2
+ // direction per key, INCLUDE payload, an operator class — checked where the author wrote them and
3
+ // resolved to physical names. `@ultimat3/db` (`index-key-ddl.ts`) renders them and refuses again.
4
+
5
+ import type { IndexOperatorClass } from '@ultimat3/db';
6
+ import { invariantViolated } from './errors';
7
+ import type { Resolve } from './expr';
8
+ import type { IndexInit } from './index-init';
9
+ import type { ColumnMap } from './types';
10
+
11
+ /** The declared parts, physical, each absent unless written — the `IndexDef` fields they become. */
12
+ export interface DeclaredKeyParts {
13
+ readonly expression?: string;
14
+ readonly orders?: readonly ('asc' | 'desc' | null)[];
15
+ readonly include?: readonly string[];
16
+ readonly operatorClass?: IndexOperatorClass;
17
+ }
18
+
19
+ const DIRECTIONS: ReadonlySet<unknown> = new Set(['asc', 'desc', null]);
20
+
21
+ /**
22
+ * Every rule Postgres has for the four, refused at `entity()` with `X_INVARIANT_VIOLATED` — the
23
+ * code a bad `on:` or `where:` already raises — rather than at `x db gen` or as the server's own
24
+ * syntax error inside `ROLE=migrate`, which names none of the entity.
25
+ */
26
+ export const declaredKeyPartsOf = <C extends ColumnMap>(
27
+ entityName: string,
28
+ index: IndexInit<C>,
29
+ resolve: Resolve,
30
+ ): DeclaredKeyParts => {
31
+ const on = `the index on (${index.on.join(', ')})`;
32
+ const refuse = (detail: string): never => {
33
+ throw invariantViolated(entityName, 'index', `${on} ${detail}`);
34
+ };
35
+ const btree = index.using === undefined || index.using === 'btree';
36
+ const { expression, orders, include, operatorClass } = index;
37
+ if (expression !== undefined && expression.trim() === '') {
38
+ refuse("declares a blank expression — write the key, e.g. expression: 'lower(email)'");
39
+ }
40
+ if (orders !== undefined) {
41
+ if (index.order !== undefined)
42
+ refuse('declares both order and orders — orders states every key; drop order');
43
+ if (!btree) refuse(`declares orders on a ${index.using} index — only a btree orders its keys`);
44
+ const keys = expression === undefined ? index.on.length : 1;
45
+ if (orders.length !== keys) {
46
+ refuse(`declares ${orders.length} direction(s) for ${keys} key(s) — orders is one per key`);
47
+ }
48
+ if (!orders.every((direction) => DIRECTIONS.has(direction))) {
49
+ refuse("declares a direction other than 'asc', 'desc' or null");
50
+ }
51
+ }
52
+ if (include !== undefined) {
53
+ if (!btree) refuse(`declares include on a ${index.using} index — INCLUDE is btree only`);
54
+ if (include.length === 0) refuse('declares an empty include — name a column, or drop include');
55
+ }
56
+ if (operatorClass !== undefined && index.using !== 'gin') {
57
+ refuse(`declares ${operatorClass} without using: 'gin' — it is a gin operator class`);
58
+ }
59
+ return {
60
+ ...(expression === undefined ? {} : { expression }),
61
+ ...(orders === undefined ? {} : { orders }),
62
+ ...(include === undefined ? {} : { include: include.map((property) => resolve([property])) }),
63
+ ...(operatorClass === undefined ? {} : { operatorClass }),
64
+ };
65
+ };
@@ -1,6 +1,7 @@
1
1
  // One `indexes: [...]` entry of `entity(name, { indexes })` turned into the `IndexDef` it declares,
2
2
  // refusing what Postgres would refuse later. Split out of `entity.ts` at the 500-line ceiling.
3
3
 
4
+ import { declaredKeyPartsOf } from './declared-index-keys';
4
5
  import { invariantViolated } from './errors';
5
6
  import type { InvariantColumns, Resolve } from './expr';
6
7
  import type { IndexInit } from './index-init';
@@ -57,8 +58,9 @@ export const declaredIndexOf = <C extends ColumnMap>(
57
58
  );
58
59
  }
59
60
  }
61
+ const keys = declaredKeyPartsOf(name, index, resolve);
60
62
  return {
61
- name: indexName(name, table, columns, unique, index.order, where, index.using),
63
+ name: indexName(name, table, columns, unique, index.order, where, index.using, keys),
62
64
  columns,
63
65
  unique,
64
66
  ...(index.order === undefined ? {} : { order: index.order }),
@@ -69,5 +71,8 @@ export const declaredIndexOf = <C extends ColumnMap>(
69
71
  // How it is BUILT, so not part of the name. Absent stays absent — the default every existing
70
72
  // index already projects — and only an explicit ask, either way, rides along.
71
73
  ...(index.concurrently === undefined ? {} : { concurrently: index.concurrently }),
74
+ // The four key parts (E8), each absent unless declared — so no name, description or snapshot
75
+ // of an index that declares none moves.
76
+ ...keys,
72
77
  };
73
78
  };
@@ -6,6 +6,7 @@
6
6
  import { refuseAbandoned } from '@ultimat3/db';
7
7
  import { appendOnlyRepo } from './append-only';
8
8
  import type { Driver } from './database';
9
+ import { refuseCounters } from './driver-counters';
9
10
  import { driverCapabilityMissing, driverUnsupported } from './driver-errors';
10
11
  import type { DriverCapability, DriverDefinition, DriverRepo } from './driver-kit-types';
11
12
  import { noteDriverStore } from './driver-registry';
@@ -15,7 +16,7 @@ import { driverScope } from './driver-scope';
15
16
  import type { RawFor } from './driver-write-scope';
16
17
  import type { EntityCore } from './entity';
17
18
  import { notFound } from './errors';
18
- import { lockKeyInput } from './lock-key';
19
+ import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
19
20
  import { idPlan } from './plan';
20
21
  import type { Repo, RepoOptions, Tx } from './repo';
21
22
  import { sealedRepo } from './sealed-repo';
@@ -71,11 +72,12 @@ const driverRepo = <Row>(
71
72
  entity: EntityCore<Row>,
72
73
  rawFor: RawFor,
73
74
  ): Repo<Row> => {
75
+ refuseCounters(definition.name, entity as EntityCore);
74
76
  const scope = driverScope(definition, entity, rawFor);
75
77
  assertImplemented(definition, scope.raw as DriverRepo<unknown>);
76
78
  const { raw } = scope;
77
79
  // Absent unless declared, so the typed handle answers the shipped `X_LOCK_UNSUPPORTED`.
78
- const locks = (): Pick<Repo<Row>, 'lock' | 'lockKey'> => {
80
+ const locks = (): Pick<Repo<Row>, 'lock' | 'lockKey' | 'lockKeys'> => {
79
81
  const { lock, lockKey } = raw;
80
82
  if (lock === undefined || lockKey === undefined) return {};
81
83
  if (!definition.capabilities.includes('lock')) return {};
@@ -107,6 +109,26 @@ const driverRepo = <Row>(
107
109
  options?.tx,
108
110
  );
109
111
  },
112
+ // The store's one-key lock, sorted and nested: each key taken inside the last one's tx.
113
+ async lockKeys<R>(
114
+ keys: readonly string[],
115
+ fn: (tx: Tx) => Promise<R> | R,
116
+ options?: RepoOptions,
117
+ ) {
118
+ refuseAbandoned();
119
+ return holdInOrder<R, Tx>(
120
+ lockKeysInput(entity, keys, options),
121
+ (input, outer, body) =>
122
+ lockKey.call<DriverRepo<Row>, Parameters<typeof lockKey<R>>, Promise<R>>(
123
+ raw,
124
+ input,
125
+ body,
126
+ outer,
127
+ ),
128
+ fn,
129
+ options?.tx,
130
+ );
131
+ },
110
132
  };
111
133
  };
112
134
  const repo: Repo<Row> = { ...driverReads(scope), ...driverWrites(scope), ...locks() };
package/src/describe.ts CHANGED
@@ -366,6 +366,12 @@ export const describeEntity = <Row>(input: DescribeInput<Row>): EntityDescriptio
366
366
  // Absent stays absent for the same reason — `x verify` hashes this projection, and an index
367
367
  // that asks nothing must hash what it always did. An explicit ask, `true` or `false`, rides.
368
368
  ...(index.concurrently === undefined ? {} : { concurrently: index.concurrently }),
369
+ // The four key parts (E8), absent unless declared, for the same hash. `@ultimat3/db` renders
370
+ // them (`index-key-ddl.ts`) and records them in the snapshot (`declaredKeyParts`).
371
+ ...(index.expression === undefined ? {} : { expression: index.expression }),
372
+ ...(index.orders === undefined ? {} : { orders: index.orders }),
373
+ ...(index.include === undefined ? {} : { include: index.include }),
374
+ ...(index.operatorClass === undefined ? {} : { operatorClass: index.operatorClass }),
369
375
  })),
370
376
  tags: input.tags,
371
377
  cacheTag: input.cacheTag,
@@ -0,0 +1,21 @@
1
+ // Single responsibility: refuse a `countedIn` counter on a `defineDriver` store. Postgres keeps one
2
+ // by trigger and memory in its repository; a custom store has no lifecycle hook, so its parent's
3
+ // count would never move — refused when the child's repository is built, never a silent stale count.
4
+
5
+ import { DriverError } from './driver-errors';
6
+ import type { EntityCore } from './entity';
7
+
8
+ /** The child's first property declaring `countedIn`, refused; nothing when it declares none. */
9
+ export function refuseCounters(driverName: string, entity: EntityCore): void {
10
+ const counted = Object.entries(entity.$columns).find(
11
+ ([, column]) => column.$meta.countedIn !== undefined,
12
+ );
13
+ if (counted === undefined) return;
14
+ const [property] = counted;
15
+ throw new DriverError({
16
+ code: 'X_DRIVER_UNSUPPORTED',
17
+ cause: `${entity.$name}.${property} declares countedIn, and driver ${JSON.stringify(driverName)} keeps no counter: a defineDriver store has no trigger or repository hook to move the parent's count`,
18
+ fix: `database({ ${entity.$name}, … }, { driver: postgresDriver() }) # or memoryDriver(): both keep the counter — or drop countedIn from ${entity.$name}.${property} and count with db.${entity.$name}.countBy('${property}')`,
19
+ meta: { capability: 'countedIn', driver: driverName, entity: entity.$name, property },
20
+ });
21
+ }
@@ -8,14 +8,24 @@ import { countsFrom, groupColumnOf } from './count-by';
8
8
  import { cursorFor, seekFrom } from './cursor';
9
9
  import { projectRow } from './driver-rows';
10
10
  import type { DriverScope } from './driver-scope';
11
+ import { planMeasures, screenMeasureFilter } from './measures';
12
+ import { assertPageBytes } from './page-bytes';
11
13
  import { idPlan, readPlan, singleKeyOf } from './plan';
12
14
  import type { Repo } from './repo';
13
15
  import { rowKey } from './row-key';
16
+ import type { Predicate } from './tenancy';
14
17
  import { seriesPlanOf } from './time-bucket';
15
18
 
16
19
  export type DriverReads<Row> = Pick<
17
20
  Repo<Row>,
18
- 'findById' | 'findMany' | 'count' | 'countBy' | 'aggregate' | 'approximateCount' | 'series'
21
+ | 'findById'
22
+ | 'findMany'
23
+ | 'count'
24
+ | 'countBy'
25
+ | 'aggregate'
26
+ | 'aggregates'
27
+ | 'approximateCount'
28
+ | 'series'
19
29
  >;
20
30
 
21
31
  export const driverReads = <Row>(scope: DriverScope<Row>): DriverReads<Row> => {
@@ -50,10 +60,10 @@ export const driverReads = <Row>(scope: DriverScope<Row>): DriverReads<Row> => {
50
60
  found.length > plan.limit && last !== undefined
51
61
  ? cursorFor(entity, plan, last, rowKey(entity, last))
52
62
  : null;
53
- return pageOf(
54
- page.map((row) => projectRow(entity, plan, row)),
55
- next,
56
- );
63
+ // Weighed projected, as memory weighs it: a store's page is bounded like the other two.
64
+ const projected = page.map((row) => projectRow(entity, plan, row));
65
+ assertPageBytes(entity, op, projected as readonly Readonly<Record<string, unknown>>[]);
66
+ return pageOf(projected, next);
57
67
  },
58
68
 
59
69
  async count(args = {}) {
@@ -62,13 +72,70 @@ export const driverReads = <Row>(scope: DriverScope<Row>): DriverReads<Row> => {
62
72
  return raw.count({ plan, tx: scope.txOf(op, args) });
63
73
  },
64
74
 
65
- async countBy(column, args = {}) {
75
+ /**
76
+ * With `where`, two store calls over the one capability a store already declares: every group
77
+ * the chain matches, then the groups' counts with the filter ANDed in — a group the filter
78
+ * empties answers `0`, as `count(*) filter (where …)` does. No new store contract to forget.
79
+ */
80
+ async countBy(column, args = {}, options) {
66
81
  const op = 'countBy';
67
82
  groupColumnOf(entity, column, op);
68
83
  scope.need(op, 'aggregate:countBy');
69
- const plan = scope.storePlan(op, readPlan(entity, args, op), args.includeDeleted);
70
- const groups = await raw.countBy?.(column, { plan, tx: scope.txOf(op, args) });
71
- return countsFrom(entity, column, op, groups ?? []);
84
+ const tx = scope.txOf(op, args);
85
+ const planOf = (where: readonly Predicate[]) =>
86
+ scope.storePlan(op, readPlan(entity, { ...args, where }, op), args.includeDeleted);
87
+ const groups = await raw.countBy?.(column, { plan: planOf(args.where ?? []), tx });
88
+ const all = countsFrom(entity, column, op, groups ?? []);
89
+ const filter = options?.where;
90
+ if (filter === undefined || filter.length === 0) return all;
91
+ const where = [...(args.where ?? []), ...screenMeasureFilter(entity, filter)];
92
+ const hit = countsFrom(
93
+ entity,
94
+ column,
95
+ op,
96
+ (await raw.countBy?.(column, { plan: planOf(where), tx })) ?? [],
97
+ );
98
+ // Re-ordered by the FILTERED count, as memory's `countsFrom` pass orders its pairs.
99
+ return countsFrom(
100
+ entity,
101
+ column,
102
+ op,
103
+ [...all.keys()].map((key) => [key, hit.get(key) ?? 0] as const),
104
+ );
105
+ },
106
+
107
+ /**
108
+ * Every measure as the store call its function already is — `count` through `count`, the rest
109
+ * through `aggregate` under its own `aggregate:<fn>` capability — each with its filter ANDed
110
+ * into the plan. Several store calls, never one statement: a store has no select list.
111
+ */
112
+ async aggregates(measures, args = {}) {
113
+ const op = 'aggregates';
114
+ const planned = planMeasures(entity, measures);
115
+ const tx = scope.txOf(op, args);
116
+ const answer: Record<string, unknown> = {};
117
+ for (const measure of planned) {
118
+ const where = [
119
+ ...(args.where ?? []),
120
+ ...measure.where,
121
+ ...(measure.fn === 'count' && measure.property !== undefined
122
+ ? [{ column: measure.property, op: 'is-not-null' as const }]
123
+ : []),
124
+ ];
125
+ const plan = scope.storePlan(
126
+ op,
127
+ readPlan(entity, { ...args, where }, op),
128
+ args.includeDeleted,
129
+ );
130
+ if (measure.fn === 'count') {
131
+ answer[measure.name] = await raw.count({ plan, tx });
132
+ continue;
133
+ }
134
+ scope.need(measure.fn, `aggregate:${measure.fn}`);
135
+ answer[measure.name] =
136
+ (await raw.aggregate?.(measure.fn, measure.property ?? '', { plan, tx })) ?? null;
137
+ }
138
+ return answer;
72
139
  },
73
140
 
74
141
  async aggregate(fn, column, args = {}) {
@@ -3,11 +3,15 @@
3
3
  // tenant, before the store is called — and the store is handed only scoped plans and judged rows.
4
4
 
5
5
  import { refuseAbandoned } from '@ultimat3/db';
6
+ import { keyOf } from './batch-read';
6
7
  import { conflictKeys, upsertPlan } from './bulk-write';
7
8
  import { entityNow } from './clock';
8
9
  import { narrowRow } from './columns';
10
+ import { copyColumns } from './copy-plan';
11
+ import { kindOf, valueAt } from './cursor';
9
12
  import { byKeys, checkedDelete } from './driver-delete';
10
13
  import type { DriverScope } from './driver-scope';
14
+ import { versionedWrites } from './driver-versioned-write';
11
15
  import {
12
16
  assertWrittenInScope,
13
17
  sameTenantProperties,
@@ -17,16 +21,30 @@ import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
17
21
  import { notFound } from './errors';
18
22
  import { assertedRowsTooMany, MAX_ASSERTED_ROWS } from './invariants';
19
23
  import { mergedRow } from './memory-update';
20
- import { deletePlan, idPlan, namedColumns, singleKeyOf, updatePlan } from './plan';
24
+ import { idPlan, namedColumns, singleKeyOf } from './plan';
21
25
  import type { Repo, RepoOptions, Tx } from './repo';
26
+ import { rowKey } from './row-key';
22
27
  import { advancingVersionColumn, deletionStamp, VERSION_STEP_MS } from './search-index-version';
23
28
  import { writtenRowsSink } from './search-written-rows';
24
29
  import { assertRowTenant, type QueryPlan } from './tenancy';
25
30
  import type { RowPatch, RowWrite } from './types';
31
+ import { judgeUpdateMany, updateManyPlan } from './update-many';
32
+ import { assertVersionedUpdate, versionOf } from './version-lock';
33
+ import { updateWherePlan, writeWherePlan } from './write-where';
26
34
 
27
35
  export type DriverWrites<Row> = Pick<
28
36
  Repo<Row>,
29
- 'insert' | 'insertAll' | 'upsertAll' | 'update' | 'delete' | 'deleteWhere' | 'updateWhere'
37
+ | 'insert'
38
+ | 'insertAll'
39
+ | 'upsertAll'
40
+ | 'update'
41
+ | 'delete'
42
+ | 'deleteWhere'
43
+ | 'updateWhere'
44
+ | 'insertAllCount'
45
+ | 'upsertAllCount'
46
+ | 'copyAll'
47
+ | 'updateMany'
30
48
  >;
31
49
 
32
50
  export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> => {
@@ -94,7 +112,10 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
94
112
  entity.$columns,
95
113
  Object.fromEntries(namedColumns(patch)),
96
114
  );
97
- if (entity.$invariants.length === 0 && !movesReference) {
115
+ // A declared version lock is per row (`v = stored + 1`), which one store patch cannot say: the
116
+ // judged path below, one write per row (`driver-versioned-write.ts`).
117
+ const lock = versionOf(entity);
118
+ if (entity.$invariants.length === 0 && !movesReference && lock === null) {
98
119
  // The search mirror asked for the rows: read them first, as the judged path does. Past the
99
120
  // judged bound they are not handed over — the mirror logs the write it could not name.
100
121
  const before =
@@ -126,6 +147,22 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
126
147
  entity.$assert(merged);
127
148
  }
128
149
  await references(results);
150
+ if (lock !== null) {
151
+ const written = await versionedWrites(scope, {
152
+ op,
153
+ plan,
154
+ patch,
155
+ lock,
156
+ found,
157
+ results,
158
+ advance,
159
+ narrowed,
160
+ tx,
161
+ references,
162
+ });
163
+ if (sink !== undefined) sink(await writtenBack(op, plan, found, tx));
164
+ return written;
165
+ }
129
166
  // The narrowed values the merge produced — the same for every row — so the store holds what
130
167
  // was judged rather than a money `bigint` the row type never carries. The version is the
131
168
  // patch's instant: the store advances it per row.
@@ -148,7 +185,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
148
185
  )
149
186
  : checkedDelete(scope, op, plan, options);
150
187
 
151
- return {
188
+ const writes: DriverWrites<Row> = {
152
189
  async insert(values, options) {
153
190
  refuseAbandoned();
154
191
  const [row] = judged('insert', [values]);
@@ -188,6 +225,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
188
225
  refuseAbandoned();
189
226
  const op = 'update';
190
227
  const patch = entity.$parsePatch(given);
228
+ assertVersionedUpdate(entity, patch);
191
229
  const plan = scope.storePlan(op, idPlan(entity, id, options, op));
192
230
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
193
231
  if (namedColumns(patch).length > 0 && (await patched(op, plan, patch, options)) === 0) {
@@ -221,16 +259,76 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
221
259
  async deleteWhere(filter, options) {
222
260
  refuseAbandoned();
223
261
  const op = 'deleteWhere';
224
- return removed(op, scope.storePlan(op, deletePlan(entity, filter, options, op)), options);
262
+ return removed(op, scope.storePlan(op, writeWherePlan(entity, filter, options, op)), options);
225
263
  },
226
264
 
227
265
  async updateWhere(filter, given, options) {
228
266
  refuseAbandoned();
229
267
  const op = 'updateWhere';
230
268
  const patch = entity.$parsePatch(given) as RowPatch<Row>;
231
- const plan = scope.storePlan(op, updatePlan(entity, filter, patch, options, op));
269
+ const plan = scope.storePlan(op, updateWherePlan(entity, filter, patch, options, op));
232
270
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
233
271
  return patched(op, plan, patch, options);
234
272
  },
273
+
274
+ // A store answers rows from every insert, so the count is their length: one judging path.
275
+ insertAllCount: async (given, options) => (await writes.insertAll(given, options)).length,
276
+ upsertAllCount: async (given, args) => (await writes.upsertAll(given, args)).length,
277
+ copyAll: async (given, options) => {
278
+ copyColumns(entity, given as readonly RowPatch<Row>[]);
279
+ return (await writes.insertAll(given, options)).length;
280
+ },
281
+
282
+ /**
283
+ * Judged as ONE batch first — tenant, invariants, keys, same-tenant references, the shape
284
+ * `memoryRepo` judges — then one `patched` write per row, since a store's `update` sets one
285
+ * patch on every row it matches. That is n store calls, so a refusal part way (a unique the
286
+ * store judges against a row outside the batch) writes the rows already moved BACK before it
287
+ * rethrows: all or nothing, as `updateWhere`'s single call is. Missing, soft-deleted and other
288
+ * tenants' ids are not counted.
289
+ */
290
+ async updateMany(given, options) {
291
+ refuseAbandoned();
292
+ const op = 'updateMany';
293
+ const plan = updateManyPlan(entity, given, options);
294
+ if (plan.patches.length === 0) return 0;
295
+ const tx = scope.txOf(op, options);
296
+ const match = scope.storePlan(op, plan.match);
297
+ const found = scope.checked(
298
+ op,
299
+ match,
300
+ await raw.select({ plan: match, after: undefined, limit: plan.patches.length, tx }),
301
+ );
302
+ const merged = judgeUpdateMany(entity, plan, found, [], (row) => rowKey(entity, row));
303
+ await references(merged);
304
+ const kind = kindOf(entity, plan.key) ?? '';
305
+ const cell = (row: unknown) => keyOf(kind, valueAt(row, plan.key));
306
+ const before = new Map(found.map((row) => [cell(row), row]));
307
+ const after = new Map(merged.map((row, at) => [cell(found[at]), row]));
308
+ const moved: (readonly [Row, Row])[] = [];
309
+ let written = 0;
310
+ try {
311
+ for (const { id, patch } of plan.patches) {
312
+ const stored = before.get(keyOf(kind, id));
313
+ const result = after.get(keyOf(kind, id));
314
+ if (stored === undefined || result === undefined) continue;
315
+ const one = scope.storePlan(op, idPlan(entity, id, options, op));
316
+ const count = await patched(op, one, patch, options);
317
+ if (count > 0) moved.push([stored, result]);
318
+ written += count;
319
+ }
320
+ } catch (error) {
321
+ for (const [stored, result] of moved.reverse()) {
322
+ const where = idPlan(entity, String(valueAt(result, plan.key)), options, op);
323
+ const values = Object.fromEntries(
324
+ [...plan.properties, plan.key].map((property) => [property, valueAt(stored, property)]),
325
+ );
326
+ await raw.update({ plan: scope.storePlan(op, where, true), tx }, values);
327
+ }
328
+ throw error;
329
+ }
330
+ return written;
331
+ },
235
332
  };
333
+ return writes;
236
334
  };
@@ -0,0 +1,99 @@
1
+ // Single responsibility: a `defineDriver` write of a versioned entity, one store call per row since
2
+ // `v = stored + 1` is per row. `update(id)`/`updateMany` name the version and compare-and-set on
3
+ // it; a filtered write names none and, like Postgres's `set v = v + 1`, never answers stale.
4
+
5
+ import { valueAt } from './cursor';
6
+ import type { DriverAdvance } from './driver-kit-types';
7
+ import type { DriverScope } from './driver-scope';
8
+ import { mergedRow } from './memory-update';
9
+ import { namedColumns } from './plan';
10
+ import type { Tx } from './repo';
11
+ import { rowKey } from './row-key';
12
+ import { assertRowTenant, type QueryPlan } from './tenancy';
13
+ import { entityStale } from './version-lock-errors';
14
+
15
+ /**
16
+ * How many times a filtered write re-reads one row a concurrent writer keeps moving. Each miss is
17
+ * another writer's progress; the bound only stops a store whose conditioned update never matches.
18
+ */
19
+ export const MAX_VERSION_RETRIES = 16;
20
+
21
+ export interface VersionedWrite<Row> {
22
+ readonly op: string;
23
+ readonly plan: QueryPlan;
24
+ readonly patch: object;
25
+ /** The version property (`versionOf(entity)`). */
26
+ readonly lock: string;
27
+ /** The rows the plan matched, as read, each with the row the patch made of it. */
28
+ readonly found: readonly Row[];
29
+ readonly results: readonly Row[];
30
+ readonly advance: DriverAdvance | undefined;
31
+ readonly narrowed: Readonly<Record<string, unknown>>;
32
+ readonly tx: Tx | undefined;
33
+ /** Same-tenant references of a re-merged row, judged as the batch was. */
34
+ readonly references: (rows: readonly Row[]) => Promise<void>;
35
+ }
36
+
37
+ /**
38
+ * Writes every row conditioned on the version it was READ at. A miss is `X_ENTITY_STALE` when the
39
+ * patch named the version; otherwise the row is re-read under the same plan — gone or out of the
40
+ * filter is skipped, as Postgres re-checks the WHERE on the newer row — re-merged, re-judged and
41
+ * written again at ITS version, so neither increment is lost. Answers how many rows were written.
42
+ */
43
+ export const versionedWrites = async <Row>(
44
+ scope: DriverScope<Row>,
45
+ write: VersionedWrite<Row>,
46
+ ): Promise<number> => {
47
+ const { entity, raw } = scope;
48
+ const { op, plan, patch, lock, advance, narrowed, tx } = write;
49
+ const checks = namedColumns(patch).some(([key]) => key === lock);
50
+ const keyed = (row: Row, withVersion: boolean): QueryPlan => ({
51
+ ...plan,
52
+ where: [
53
+ ...plan.where,
54
+ ...entity.$primaryKey.map((key) => ({
55
+ column: key,
56
+ op: 'eq' as const,
57
+ value: valueAt(row, key),
58
+ })),
59
+ ...(withVersion ? [{ column: lock, op: 'eq' as const, value: valueAt(row, lock) }] : []),
60
+ ],
61
+ });
62
+ // The narrowed values the merge produced, so the store holds what was judged; the version is
63
+ // one past the read row's, and a searchable version the patch's instant the store advances.
64
+ const valuesOf = (result: Row): Record<string, unknown> => {
65
+ const merged = result as Readonly<Record<string, unknown>>;
66
+ const values = Object.fromEntries(namedColumns(patch).map(([key]) => [key, merged[key]]));
67
+ values[lock] = merged[lock];
68
+ if (advance !== undefined) values[advance.property] = narrowed[advance.property];
69
+ return values;
70
+ };
71
+ const stale = (row: Row) =>
72
+ entityStale(entity.$name, lock, rowKey(entity, row), valueAt(row, lock), undefined);
73
+ let written = 0;
74
+ for (const [at, first] of write.found.entries()) {
75
+ let read = first;
76
+ let result = write.results[at] as Row;
77
+ for (let attempt = 0; ; attempt += 1) {
78
+ const count = await raw.update({ plan: keyed(read, true), tx }, valuesOf(result), advance);
79
+ if (count > 0) {
80
+ written += count;
81
+ break;
82
+ }
83
+ if (checks || attempt >= MAX_VERSION_RETRIES) throw stale(read);
84
+ const again = keyed(read, false);
85
+ const [fresh] = scope.checked(
86
+ op,
87
+ again,
88
+ await raw.select({ plan: again, after: undefined, limit: 1, tx }),
89
+ );
90
+ if (fresh === undefined) break;
91
+ read = fresh;
92
+ result = mergedRow(entity, fresh, patch);
93
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, result);
94
+ entity.$assert(result);
95
+ await write.references([result]);
96
+ }
97
+ }
98
+ return written;
99
+ };
@@ -53,6 +53,9 @@ export const ENTITY_ERROR_CODES = [
53
53
  'X_DRIVER_CAPABILITY_MISSING',
54
54
  'X_DRIVER_ROW_OUT_OF_SCOPE',
55
55
  'X_ENTITY_PARTITION_INVALID',
56
+ 'X_ENTITY_PAGE_TOO_LARGE',
57
+ 'X_ENTITY_STALE',
58
+ 'X_ENTITY_VERSION_INVALID',
56
59
  ] as const;
57
60
 
58
61
  export type EntityErrorCode = (typeof ENTITY_ERROR_CODES)[number];
@@ -103,6 +106,9 @@ export const ENTITY_ERROR_TITLES: Readonly<Record<EntityErrorCode, string>> = {
103
106
  X_DRIVER_ROW_OUT_OF_SCOPE: 'a custom driver returned a row outside the plan it was given',
104
107
  X_ENTITY_PARTITION_INVALID:
105
108
  'entity({ partitionBy }) declares a partitioning Postgres cannot build',
109
+ X_ENTITY_PAGE_TOO_LARGE: 'a page weighed more than the page byte bound before it was decoded',
110
+ X_ENTITY_STALE: "the row's version moved since this write read it",
111
+ X_ENTITY_VERSION_INVALID: 'a write or declaration breaks the declared version lock',
106
112
  };
107
113
 
108
114
  // Registered at module load, unconditionally, in one call. Without this the registry humanises the