@ultimat3/entity 31.9.0 → 31.11.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 (70) hide show
  1. package/CLAUDE.md +2 -0
  2. package/README.md +70 -0
  3. package/package.json +5 -5
  4. package/src/aggregate.ts +1 -1
  5. package/src/all-truncated.ts +33 -0
  6. package/src/append-only.ts +8 -1
  7. package/src/bulk-write.ts +3 -0
  8. package/src/counter-observed.ts +199 -0
  9. package/src/database.ts +4 -2
  10. package/src/declared-index-keys.ts +65 -0
  11. package/src/declared-index.ts +6 -1
  12. package/src/define-driver.ts +24 -2
  13. package/src/describe.ts +8 -0
  14. package/src/driver-counters.ts +21 -0
  15. package/src/driver-repo-reads.ts +71 -5
  16. package/src/driver-repo-writes.ts +23 -1
  17. package/src/driver-versioned-write.ts +99 -0
  18. package/src/entity-error.ts +4 -0
  19. package/src/entity-indexes.ts +118 -0
  20. package/src/entity.ts +20 -49
  21. package/src/history-purge.ts +15 -0
  22. package/src/index-def.ts +35 -0
  23. package/src/index-identity.ts +5 -0
  24. package/src/index-init.ts +13 -1
  25. package/src/index-name.ts +25 -6
  26. package/src/index.ts +13 -0
  27. package/src/latest-by-sql.ts +93 -0
  28. package/src/latest-by.ts +249 -0
  29. package/src/lock-key.ts +56 -3
  30. package/src/lock-unsupported.ts +5 -2
  31. package/src/measures.ts +157 -0
  32. package/src/memory-aggregates.ts +9 -16
  33. package/src/memory-latest-by.ts +34 -0
  34. package/src/memory-lock.ts +15 -1
  35. package/src/memory-match.ts +2 -0
  36. package/src/memory-measures.ts +75 -0
  37. package/src/memory-observed.ts +3 -1
  38. package/src/memory-repo.ts +17 -1
  39. package/src/memory-update.ts +7 -1
  40. package/src/pg-aggregates.ts +9 -3
  41. package/src/pg-bulk-repo.ts +1 -1
  42. package/src/pg-driver.ts +13 -1
  43. package/src/pg-latest-by.ts +57 -0
  44. package/src/pg-lock.ts +24 -4
  45. package/src/pg-measures.ts +64 -0
  46. package/src/pg-sql-aggregate.ts +9 -3
  47. package/src/pg-sql-measures.ts +102 -0
  48. package/src/pg-sql.ts +37 -6
  49. package/src/pg-update-many-sql.ts +44 -1
  50. package/src/pg-write-sql.ts +32 -4
  51. package/src/preload-ceiling.ts +73 -7
  52. package/src/preload.ts +17 -1
  53. package/src/query.ts +14 -1
  54. package/src/read-aggregates.ts +87 -3
  55. package/src/registry.ts +34 -0
  56. package/src/repo.ts +34 -1
  57. package/src/row-observer.ts +29 -4
  58. package/src/sealed-column.ts +20 -0
  59. package/src/sealed-repo.ts +30 -2
  60. package/src/search-repo.ts +20 -2
  61. package/src/table-locks.ts +16 -1
  62. package/src/tenant-index.ts +84 -9
  63. package/src/text-contains.ts +53 -0
  64. package/src/types.ts +9 -22
  65. package/src/unique-constraints.ts +3 -1
  66. package/src/update-many-send.ts +32 -1
  67. package/src/update-many.ts +6 -1
  68. package/src/version-lock-errors.ts +42 -0
  69. package/src/version-lock.ts +177 -0
  70. package/src/write-where.ts +3 -0
@@ -0,0 +1,53 @@
1
+ // Single responsibility: what `contains` means on a `text()`/`char()` column — a case-insensitive
2
+ // substring, compiled to the bound `ilike` a `gin_trgm_ops` index serves and answered identically in
3
+ // memory. `contains` on `jsonb`/`arrayOf()` stays structural containment (`containment.ts`): the
4
+ // operator is decided by the column's declared kind, the rule `memory-match.ts` already reads.
5
+
6
+ import { type SqlFragment, sql } from '@ultimat3/db';
7
+ import type { ColumnKind } from './types';
8
+
9
+ /** The kinds whose `contains` is a substring. Every other kind keeps `@>`. */
10
+ const TEXT_KINDS: ReadonlySet<ColumnKind | undefined> = new Set<ColumnKind | undefined>([
11
+ 'text',
12
+ 'char',
13
+ ]);
14
+
15
+ export const isTextContains = (kind: ColumnKind | undefined): boolean => TEXT_KINDS.has(kind);
16
+
17
+ /**
18
+ * The term as an `ilike` pattern that finds it anywhere: the escape character first (so the
19
+ * escapes added after it are not doubled), then both wildcards — a `%` typed into a search box is a
20
+ * percent sign to find, never "anything". Postgres' default escape is the backslash, so no
21
+ * `escape` clause is written and the planner still matches the trigram operator class.
22
+ */
23
+ export const containsPattern = (term: string): string =>
24
+ `%${term.replaceAll('\\', '\\\\').replaceAll('%', '\\%').replaceAll('_', '\\_')}%`;
25
+
26
+ /** Nothing matches: a non-text operand bound as its `String()` would find `"5"` or `"null"`. */
27
+ const NEVER = sql`1 = 0`;
28
+
29
+ /**
30
+ * `col ilike $n`. `ilike` and not `lower(col) like lower($n)`: `gin_trgm_ops` serves `ilike` on the
31
+ * bare column, while `lower(col)` is an expression no column index can match.
32
+ */
33
+ export const textContainsSql = (column: SqlFragment, term: unknown): SqlFragment =>
34
+ typeof term === 'string' ? sql`${column} ilike ${containsPattern(term)}` : NEVER;
35
+
36
+ /**
37
+ * The memory driver's answer: both sides lower-cased, then a substring test — what the escaped
38
+ * `ilike` pattern matches. Case folding is JS's Unicode `toLowerCase`; Postgres folds through the
39
+ * database's collation, which agrees on every cased letter outside the locale-specific few
40
+ * (Turkish dotted I).
41
+ */
42
+ export const textContainsMatches = (actual: unknown, term: unknown): boolean =>
43
+ typeof actual === 'string' &&
44
+ typeof term === 'string' &&
45
+ actual.toLowerCase().includes(term.toLowerCase());
46
+
47
+ /**
48
+ * The `indexes:` entry that serves `contains` on `property` — `@ultimat3/db`'s spelling
49
+ * (`index-key-ddl.ts`), so the plan sweep's `X_QUERY_UNINDEXED` fix names a declaration that
50
+ * renders, and `x db gen` creates `pg_trgm` before it.
51
+ */
52
+ export const trigramDeclaration = (property: string): string =>
53
+ `indexes: [{ on: ['${property}'], using: 'gin', operatorClass: 'gin_trgm_ops' }]`;
package/src/types.ts CHANGED
@@ -6,7 +6,6 @@
6
6
  // A column carries its TypeScript type in `$parse`, which is what lets the row type be derived
7
7
  // from the column set instead of being written a second time as a hand-maintained schema.
8
8
 
9
- import type { IndexMethod } from '@ultimat3/db';
10
9
  import type { PersonalDataKind } from './personal-data-kind';
11
10
 
12
11
  /**
@@ -140,6 +139,8 @@ export interface ColumnMeta {
140
139
  */
141
140
  readonly name?: string;
142
141
  readonly length?: number;
142
+ /** `text().collate('C')`: absent is the database's default collation. `'C'` is code-point order. */
143
+ readonly collation?: 'C';
143
144
  /** `numeric(precision, scale)` — both, or neither. A bare `numeric` is unbounded on purpose. */
144
145
  readonly precision?: number;
145
146
  readonly numericScale?: number;
@@ -306,6 +307,11 @@ export interface TextColumn<T extends string | null = string, Optional extends b
306
307
  unique(): TextColumn<T, Optional>;
307
308
  default(value: T): TextColumn<T, true>;
308
309
  column(name: string): TextColumn<T, Optional>;
310
+ /**
311
+ * Order and compare this column by code point (`collate "C"`), the order a live window's matcher
312
+ * keeps — so a live query may order by it. `'C'` only; changing it is `x db gen`.
313
+ */
314
+ collate(collation: 'C'): TextColumn<T, Optional>;
309
315
  /**
310
316
  * Seal this column under the app's master key: the row still reads `string`, the database holds
311
317
  * `x1.<keyId>.<iv>.<ciphertext>`, and no view, `$schema`, record or predicate carries it.
@@ -474,24 +480,5 @@ export type RowPatch<Row> = {
474
480
  readonly [K in keyof Row]?: Row[K] | InputOf<Row[K]> | undefined;
475
481
  };
476
482
 
477
- export interface IndexDef {
478
- readonly name: string;
479
- readonly columns: readonly string[];
480
- readonly unique: boolean;
481
- readonly order?: 'asc' | 'desc';
482
- /** Partial index predicate — a soft-deleted row is excluded with this. */
483
- readonly where?: string;
484
- /**
485
- * The access method. Absent is `btree`, which is Postgres' own default and what every index
486
- * declared before this field existed is — so an entity that names none emits the statement it
487
- * always emitted, byte for byte, and no app's sidecar regenerates. `@ultimat3/db` owns the
488
- * closed set (`INDEX_METHODS`); redeclaring the union here would be the second declaration of
489
- * one fact that this release exists to stop.
490
- */
491
- readonly using?: IndexMethod;
492
- /**
493
- * How it is built (`IndexInit`). Absent is the default: concurrently on a table that already
494
- * exists. `false` is the opt-out, a plain build `x db gen` marks `-- lock-heavy: true`.
495
- */
496
- readonly concurrently?: boolean;
497
- }
483
+ // A declared index is its own vocabulary (`index-def.ts`); re-exported so a column import stays one.
484
+ export type { IndexDef } from './index-def';
@@ -25,7 +25,9 @@ export interface UniqueConstraint {
25
25
  */
26
26
  export const uniqueConstraints = <Row>(entity: EntityCore<Row>): readonly UniqueConstraint[] => [
27
27
  ...entity.$indexes
28
- .filter((index) => index.unique && index.where === undefined)
28
+ // An expression key is excluded too: `on conflict (email)` cannot infer `unique(lower(email))`
29
+ // (42P10), and the memory driver cannot evaluate the expression — the partial index's reason.
30
+ .filter((index) => index.unique && index.where === undefined && index.expression === undefined)
29
31
  .map((index) => ({ columns: index.columns, name: () => index.name })),
30
32
  ...entity.$invariants
31
33
  .filter((rule) => rule.kind === 'unique' && rule.where === undefined)
@@ -7,7 +7,10 @@ import { type DbClient, withTransaction } from '@ultimat3/db';
7
7
  import type { EntityCore } from './entity';
8
8
  import { hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
9
9
  import { decodeRow, type PhysicalRow } from './pg-row';
10
+ import { updateManyPresence } from './pg-update-many-sql';
10
11
  import type { UpdateManyPlan } from './update-many';
12
+ import { versionOf } from './version-lock';
13
+ import { entityStaleBatch } from './version-lock-errors';
11
14
 
12
15
  /** What the batch did: how many rows it updated, and those rows when `returning` asked for them. */
13
16
  export interface UpdateManyResult<Row> {
@@ -44,8 +47,11 @@ export const sendUpdateMany = async <Row>(
44
47
  returning: boolean,
45
48
  direct: DbClient,
46
49
  pinned: DbClient | undefined,
50
+ /** The batch, for a declared lock's stale check (`version-lock.ts`). Unversioned: unused. */
51
+ plan?: UpdateManyPlan<Row>,
47
52
  ): Promise<UpdateManyResult<Row>> => {
48
53
  const judges = hasJsOnlyInvariant(entity.$invariants);
54
+ const lock = plan === undefined ? null : versionOf(entity);
49
55
  const send = async (on: DbClient): Promise<UpdateManyResult<Row>> => {
50
56
  let count = 0;
51
57
  const rows: Row[] = [];
@@ -59,8 +65,33 @@ export const sendUpdateMany = async <Row>(
59
65
  count += stored.length;
60
66
  }
61
67
  if (judges) for (const row of rows) entity.$assert(row);
68
+ if (lock !== null && plan !== undefined && count < plan.patches.length) {
69
+ await refuseStale(entity, plan, lock, count, on);
70
+ }
62
71
  return { count, rows };
63
72
  };
64
- if (statements.length <= 1 && !judges) return send(direct);
73
+ if (statements.length <= 1 && !judges && lock === null) return send(direct);
65
74
  return withTransaction(send, pinned === undefined ? {} : { client: pinned });
66
75
  };
76
+
77
+ /**
78
+ * Fewer rows written than the batch named: either rows that are gone or out of scope — not written
79
+ * and not counted, as without a lock — or rows present at another version. The second refuses the
80
+ * batch, and the transaction it runs in takes back the rows already written.
81
+ */
82
+ const refuseStale = async <Row>(
83
+ entity: EntityCore<Row>,
84
+ plan: UpdateManyPlan<Row>,
85
+ lock: string,
86
+ written: number,
87
+ on: DbClient,
88
+ ): Promise<void> => {
89
+ let present = 0;
90
+ for (const statement of updateManyPresence(entity, plan)) {
91
+ const [row] = await on.query<{ readonly n: number }>(statement);
92
+ present += Number(row?.n ?? 0);
93
+ }
94
+ if (present > written) {
95
+ throw entityStaleBatch(entity.$name, lock, present - written, plan.patches.length);
96
+ }
97
+ };
@@ -15,6 +15,7 @@ import { readPlan, singleKeyOf } from './plan';
15
15
  import type { RepoOptions, UpdateManyRow } from './repo';
16
16
  import { assertRowTenant, type QueryPlan } from './tenancy';
17
17
  import type { RowPatch } from './types';
18
+ import { assertVersionedUpdate } from './version-lock';
18
19
 
19
20
  /** A batch, judged and resolved. Property names, so every driver reads one answer. */
20
21
  export interface UpdateManyPlan<Row> {
@@ -102,7 +103,11 @@ export const updateManyPlan = <Row>(
102
103
  if (row.id === undefined || row.id === null) throw unaddressed(entity.$name, position);
103
104
  }
104
105
  const patches = rows.map((row) => ({ id: String(row.id), patch: entity.$parsePatch(row.patch) }));
105
- for (const { patch } of patches) assertRowTenant(entity.$name, entity.$tenantColumn, OP, patch);
106
+ for (const { patch } of patches) {
107
+ assertRowTenant(entity.$name, entity.$tenantColumn, OP, patch);
108
+ // A declared lock: every row names the version it was read at, as `update(id, patch)` does.
109
+ assertVersionedUpdate(entity, patch, OP);
110
+ }
106
111
  const properties = sharedProperties(
107
112
  entity,
108
113
  patches.map((each) => each.patch),
@@ -0,0 +1,42 @@
1
+ // The refusals of the declared optimistic lock (`entity({ version })`): a write that read a row
2
+ // another write has since moved, and a write or declaration that would leave the lock with a hole.
3
+ // Codes and titles live in `entity-error.ts`'s registry; this file only builds the instances.
4
+
5
+ import { renderCauseValue } from '@ultimat3/core';
6
+ import { EntityError } from './entity-error';
7
+
8
+ /**
9
+ * The lost update, caught: the write named the version it read, and the stored row is past it.
10
+ * 409, as `X_STATE_CONFLICT`: the identical request succeeds after a re-read, which is exactly what
11
+ * a 409 tells a client to do. `stored` is read back AFTER the statement refused, so it is the
12
+ * diagnosis, never the decision.
13
+ */
14
+ export const entityStale = (
15
+ entityName: string,
16
+ property: string,
17
+ id: string,
18
+ expected: unknown,
19
+ stored: unknown,
20
+ ): EntityError =>
21
+ new EntityError({
22
+ code: 'X_ENTITY_STALE',
23
+ cause: `${entityName} ${id} was written with ${property} ${renderCauseValue(expected)}, and the stored row is at ${renderCauseValue(stored)} — another write landed after this one read the row`,
24
+ fix: `const fresh = await db.${entityName}.findById(id) # re-read, re-apply the change, and send fresh.${property} back with the patch`,
25
+ });
26
+
27
+ /** `updateMany`'s form: one statement, so the rows it skipped are counted rather than named. */
28
+ export const entityStaleBatch = (
29
+ entityName: string,
30
+ property: string,
31
+ stale: number,
32
+ of: number,
33
+ ): EntityError =>
34
+ new EntityError({
35
+ code: 'X_ENTITY_STALE',
36
+ cause: `${entityName}.updateMany() named a ${property} for ${of} rows, and ${stale} of them are stored past it — another write landed after the batch was read; nothing was written`,
37
+ fix: `const fresh = await db.${entityName}.where({ id: ids }).all() # re-read the batch, rebuild each patch with its row's ${property}, then updateMany again`,
38
+ });
39
+
40
+ /** The entity declared a lock, and this write's shape cannot honour it. */
41
+ export const versionMisused = (entityName: string, detail: string, fix: string): EntityError =>
42
+ new EntityError({ code: 'X_ENTITY_VERSION_INVALID', cause: `${entityName}: ${detail}`, fix });
@@ -0,0 +1,177 @@
1
+ // Single responsibility: the declared optimistic lock, `entity({ version: 'lockVersion' })`, in
2
+ // property space — what a valid declaration is, which write shapes may carry the version, and the
3
+ // compare-and-increment a store merging in code applies. Postgres says the same thing in SQL
4
+ // (`pg-write-sql.ts`, `pg-update-many-sql.ts`); the per-write rule table is in the entity README.
5
+
6
+ import type { EntityCore } from './entity';
7
+ import { notFound } from './errors';
8
+ import { namedColumns } from './plan';
9
+ import type { ColumnMap } from './types';
10
+ import { entityStale, versionMisused } from './version-lock-errors';
11
+
12
+ /** The fix every declaration refusal shares: the one spelling of a lock column. */
13
+ const declare = (entityName: string, version: string): string =>
14
+ `${version}: integer().default(0) # in entity('${entityName}', { columns, version: '${version}' }), then: x db gen "lock ${entityName}"`;
15
+
16
+ /**
17
+ * The declared version property, or `null` for an entity with none. Validated where it is
18
+ * written: a lock over a nullable or defaultless column has a row with no version, and a write
19
+ * conditioned on `null = null` matches nothing, so every update of that row would read as stale.
20
+ */
21
+ export const versionColumnOf = (
22
+ entityName: string,
23
+ columns: ColumnMap,
24
+ version: string | undefined,
25
+ ): string | null => {
26
+ if (version === undefined) return null;
27
+ const meta = Object.hasOwn(columns, version) ? columns[version]?.$meta : undefined;
28
+ const refuse = (detail: string): never => {
29
+ throw versionMisused(
30
+ entityName,
31
+ `version: '${version}' ${detail}`,
32
+ declare(entityName, version),
33
+ );
34
+ };
35
+ if (meta === undefined)
36
+ return refuse(`names no column — pick from: ${Object.keys(columns).join(', ')}`);
37
+ if (meta.kind !== 'integer')
38
+ return refuse(`is a ${meta.kind} column; a version counts writes, so it is an integer()`);
39
+ if (!meta.notNull)
40
+ return refuse('is nullable; a row with no version could never be written again');
41
+ if (meta.default?.kind !== 'value' || typeof meta.default.value !== 'number') {
42
+ return refuse('has no .default(n); an insert that names no version would store none');
43
+ }
44
+ if (meta.primaryKey || meta.tenant)
45
+ return refuse('is a key column; a version moves on every write');
46
+ return version;
47
+ };
48
+
49
+ /**
50
+ * The version property of `entity`, read structurally so a hand-built `EntityCore` (a view, a
51
+ * test double) with no `$version` reads as unversioned rather than as a crash.
52
+ */
53
+ export const versionOf = (entity: object): string | null => {
54
+ const declared = (entity as { readonly $version?: string | null }).$version;
55
+ return typeof declared === 'string' ? declared : null;
56
+ };
57
+
58
+ const named = (patch: unknown, property: string): unknown =>
59
+ namedColumns(patch).find(([key]) => key === property)?.[1];
60
+
61
+ const expectedOf = (entityName: string, property: string, value: unknown, op: string): number => {
62
+ if (typeof value === 'number' && Number.isSafeInteger(value)) return value;
63
+ throw versionMisused(
64
+ entityName,
65
+ `${op}() named ${property} as ${value === null ? 'null' : typeof value}, and a version is the integer the row was read with`,
66
+ `${entityName}.${op}(id, { …patch, ${property}: row.${property} }) # the integer from the row this change was decided on`,
67
+ );
68
+ };
69
+
70
+ /**
71
+ * `update(id, patch)` on a versioned entity: the patch names the version it read, or the write is
72
+ * refused — an update that omits it is the lost update the declaration exists to stop. Answers the
73
+ * expected version (`undefined` for an unversioned entity).
74
+ */
75
+ export const assertVersionedUpdate = (
76
+ entity: { readonly $name: string },
77
+ patch: unknown,
78
+ op: 'update' | 'updateMany' = 'update',
79
+ ): number | undefined => {
80
+ const property = versionOf(entity);
81
+ if (property === null) return undefined;
82
+ const value = named(patch, property);
83
+ if (value === undefined) {
84
+ throw versionMisused(
85
+ entity.$name,
86
+ `${op}() names no ${property}, and ${entity.$name} declares version: '${property}' — the write cannot tell whether the row moved since it was read`,
87
+ `${entity.$name}.update(id, { …patch, ${property}: row.${property} }) # carry the version from the read; a mutator takes it as input`,
88
+ );
89
+ }
90
+ return expectedOf(entity.$name, property, value, op);
91
+ };
92
+
93
+ /**
94
+ * A filtered write (`updateWhere`, a chain's `updateAll`, a transition) may not SET the version:
95
+ * the statement increments it on every matched row. A compare-and-set over a filter is spelled in
96
+ * the filter, `where({ id, lockVersion: 3 })`, where a stale row is simply not matched.
97
+ */
98
+ export const assertUnversionedPatch = (
99
+ entity: { readonly $name: string },
100
+ patch: unknown,
101
+ op: string,
102
+ ): void => {
103
+ const property = versionOf(entity);
104
+ if (property === null || named(patch, property) === undefined) return;
105
+ throw versionMisused(
106
+ entity.$name,
107
+ `${op}() sets ${property}, which every write of ${entity.$name} increments itself`,
108
+ `${entity.$name}.where({ id, ${property}: row.${property} }).updateAll(patchWithout${capital(property)}) # the version goes in the filter`,
109
+ );
110
+ };
111
+
112
+ const capital = (word: string): string => word.charAt(0).toUpperCase() + word.slice(1);
113
+
114
+ /**
115
+ * `upsertAll` with `onMatch: 'update'` overwrites a stored row it never read, so it would bypass
116
+ * the lock wholesale. Refused; `onMatch: 'nothing'` writes only new rows and stays allowed.
117
+ */
118
+ export const assertVersionedUpsert = (
119
+ entity: { readonly $name: string },
120
+ onMatch: 'update' | 'nothing',
121
+ ): void => {
122
+ const property = versionOf(entity);
123
+ if (property === null || onMatch === 'nothing') return;
124
+ throw versionMisused(
125
+ entity.$name,
126
+ `upsertAll() would overwrite stored rows without reading their ${property}, and ${entity.$name} declares version: '${property}'`,
127
+ `${entity.$name}.upsertAll(rows, { onConflict, onMatch: 'nothing' }) # then update(id, { …patch, ${property} }) each row that already existed`,
128
+ );
129
+ };
130
+
131
+ /**
132
+ * The memory driver's (and a code-merging store's) half of the lock: `merged` with the version
133
+ * one past `stored`'s, after refusing a patch that named a version the stored row is no longer at.
134
+ * The Postgres statement says the same with `where "v" = $n` and `set "v" = "v" + 1`.
135
+ */
136
+ export const versionedMerge = <Row>(
137
+ entity: EntityCore<Row>,
138
+ stored: Row,
139
+ patch: object,
140
+ merged: Row,
141
+ idOf: (row: Row) => string,
142
+ ): Row => {
143
+ const property = versionOf(entity);
144
+ if (property === null) return merged;
145
+ const current = (stored as Readonly<Record<string, unknown>>)[property];
146
+ const expected = named(patch, property);
147
+ if (expected !== undefined && expected !== current) {
148
+ throw entityStale(entity.$name, property, idOf(stored), expected, current);
149
+ }
150
+ const next = typeof current === 'number' ? current + 1 : 1;
151
+ return Object.assign({}, merged, { [property]: next }) as Row;
152
+ };
153
+
154
+ /** What a store's patch writes as the version when it can only set a value: the expected + 1. */
155
+ export const nextVersion = (entity: object, patch: unknown): number | undefined => {
156
+ const property = versionOf(entity);
157
+ if (property === null) return undefined;
158
+ const value = named(patch, property);
159
+ return typeof value === 'number' ? value + 1 : undefined;
160
+ };
161
+
162
+ /**
163
+ * Why a conditioned `update(id)` matched no row, asked only after it did: re-read (tenant scoped,
164
+ * so another org's row is absent) and name the stored version, or `X_NOT_FOUND`.
165
+ */
166
+ export const staleOrNotFound = async <Row>(
167
+ entity: EntityCore<Row>,
168
+ id: unknown,
169
+ patch: unknown,
170
+ reread: () => Promise<Row | null>,
171
+ ): Promise<Error> => {
172
+ const property = versionOf(entity);
173
+ const row = await reread();
174
+ if (row === null || property === null) return notFound(entity.$name, String(id));
175
+ const stored = (row as Readonly<Record<string, unknown>>)[property];
176
+ return entityStale(entity.$name, property, String(id), named(patch, property), stored);
177
+ };
@@ -10,6 +10,7 @@ import type { FilteredWriteOptions } from './repo';
10
10
  import { SEARCH_PROPERTY } from './search';
11
11
  import type { Predicate, QueryPlan } from './tenancy';
12
12
  import type { RowPatch } from './types';
13
+ import { assertUnversionedPatch } from './version-lock';
13
14
 
14
15
  /** What a chain carries into a write terminal. */
15
16
  export interface WriteChain {
@@ -106,6 +107,8 @@ export const updateWherePlan = <Row>(
106
107
  op: string,
107
108
  ): QueryPlan => {
108
109
  const plan = writeWherePlan(entity, filter, options, op);
110
+ // The statement increments a declared version itself; a patch setting it is refused.
111
+ assertUnversionedPatch(entity, patch, op);
109
112
  if (namedColumns(patch).length > 0) return plan;
110
113
  const columns = Object.keys(entity.$columns);
111
114
  if (options?.where === undefined) throw patchEmpty(entity.$name, op, columns);