@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.
- package/CLAUDE.md +2 -1
- package/README.md +78 -1
- package/package.json +5 -5
- package/src/adapter.ts +2 -2
- package/src/aggregate.ts +1 -1
- package/src/all-truncated.ts +33 -0
- package/src/append-only-errors.ts +2 -1
- package/src/append-only.ts +24 -2
- package/src/batch-bytes.ts +34 -0
- package/src/bulk-write-send.ts +38 -5
- package/src/bulk-write.ts +3 -0
- package/src/copy-plan.ts +40 -0
- package/src/counter-observed.ts +199 -0
- package/src/database.ts +4 -2
- package/src/declared-index-keys.ts +65 -0
- package/src/declared-index.ts +6 -1
- package/src/define-driver.ts +24 -2
- package/src/describe.ts +6 -0
- package/src/driver-counters.ts +21 -0
- package/src/driver-repo-reads.ts +76 -9
- package/src/driver-repo-writes.ts +104 -6
- package/src/driver-versioned-write.ts +99 -0
- package/src/entity-error.ts +6 -0
- package/src/entity-indexes.ts +118 -0
- package/src/entity.ts +20 -49
- package/src/history-purge.ts +15 -0
- package/src/index-def.ts +35 -0
- package/src/index-identity.ts +5 -0
- package/src/index-init.ts +13 -1
- package/src/index-name.ts +25 -6
- package/src/index.ts +19 -2
- package/src/latest-by-sql.ts +93 -0
- package/src/latest-by.ts +249 -0
- package/src/lock-key.ts +56 -3
- package/src/lock-unsupported.ts +5 -2
- package/src/measures.ts +157 -0
- package/src/memory-aggregates.ts +9 -16
- package/src/memory-latest-by.ts +34 -0
- package/src/memory-lock.ts +15 -1
- package/src/memory-match.ts +2 -0
- package/src/memory-measures.ts +75 -0
- package/src/memory-observed.ts +7 -1
- package/src/memory-repo.ts +60 -6
- package/src/memory-update.ts +17 -4
- package/src/page-bytes.ts +127 -0
- package/src/pg-aggregates.ts +9 -3
- package/src/pg-bulk-repo.ts +163 -0
- package/src/pg-copy.ts +87 -0
- package/src/pg-driver.ts +31 -72
- package/src/pg-latest-by.ts +57 -0
- package/src/pg-lock.ts +24 -4
- package/src/pg-measures.ts +64 -0
- package/src/pg-sql-aggregate.ts +9 -3
- package/src/pg-sql-measures.ts +102 -0
- package/src/pg-sql.ts +37 -6
- package/src/pg-update-many-sql.ts +146 -0
- package/src/pg-values-list.ts +55 -0
- package/src/pg-write-sql.ts +42 -26
- package/src/plan.ts +1 -56
- package/src/preload-ceiling.ts +73 -7
- package/src/preload.ts +17 -1
- package/src/query-write.ts +169 -0
- package/src/query.ts +38 -48
- package/src/read-aggregates.ts +87 -3
- package/src/registry.ts +29 -0
- package/src/repo.ts +74 -3
- package/src/row-observer.ts +68 -5
- package/src/sealed-repo.ts +78 -9
- package/src/search-mirrored-repo.ts +53 -0
- package/src/search-repo.ts +20 -2
- package/src/table-locks.ts +16 -1
- package/src/tenant-index.ts +84 -9
- package/src/text-contains.ts +53 -0
- package/src/type-pins.ts +9 -0
- package/src/types.ts +2 -22
- package/src/unique-constraints.ts +3 -1
- package/src/update-many-send.ts +97 -0
- package/src/update-many.ts +175 -0
- package/src/version-lock-errors.ts +42 -0
- package/src/version-lock.ts +177 -0
- package/src/view-repo.ts +4 -0
- package/src/write-where.ts +164 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Single responsibility: sending an `updateMany`'s statements so the batch is one write, and
|
|
2
|
+
// deciding whether its rows come back at all. `pg-update-many-sql.ts` compiles the statements;
|
|
3
|
+
// `pg-driver.ts` resolves the connection, attributes the call and hands both over.
|
|
4
|
+
|
|
5
|
+
import type { SqlFragment } from '@ultimat3/db';
|
|
6
|
+
import { type DbClient, withTransaction } from '@ultimat3/db';
|
|
7
|
+
import type { EntityCore } from './entity';
|
|
8
|
+
import { hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
|
|
9
|
+
import { decodeRow, type PhysicalRow } from './pg-row';
|
|
10
|
+
import { updateManyPresence } from './pg-update-many-sql';
|
|
11
|
+
import type { UpdateManyPlan } from './update-many';
|
|
12
|
+
import { versionOf } from './version-lock';
|
|
13
|
+
import { entityStaleBatch } from './version-lock-errors';
|
|
14
|
+
|
|
15
|
+
/** What the batch did: how many rows it updated, and those rows when `returning` asked for them. */
|
|
16
|
+
export interface UpdateManyResult<Row> {
|
|
17
|
+
readonly count: number;
|
|
18
|
+
readonly rows: readonly Row[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `returning "<table>".*` or a count. The rows are read back when an app-only rule must judge
|
|
23
|
+
* them (the plan already refused a batch past `MAX_ASSERTED_ROWS`), or when the search mirror's
|
|
24
|
+
* sink is open and the batch fits that same bound — each id matches at most one row, so the batch
|
|
25
|
+
* width bounds the rows without the `count(*)` `updateWhere` spends on it. Otherwise a count:
|
|
26
|
+
* nobody reads the rows, and a backfill must not stream its table back into the process.
|
|
27
|
+
*/
|
|
28
|
+
export const updateManyReturns = <Row>(
|
|
29
|
+
entity: EntityCore<Row>,
|
|
30
|
+
plan: UpdateManyPlan<Row>,
|
|
31
|
+
sinkOpen: boolean,
|
|
32
|
+
): boolean =>
|
|
33
|
+
hasJsOnlyInvariant(entity.$invariants) || (sinkOpen && plan.patches.length <= MAX_ASSERTED_ROWS);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* One statement and no rule to judge is one autocommit statement. Several are one transaction — a
|
|
37
|
+
* SAVEPOINT inside an open one — so a batch failing in its last chunk leaves no earlier chunk
|
|
38
|
+
* stored, as `writeChunks` holds `insertAll`. An app-only rule takes the transaction at any width:
|
|
39
|
+
* the rows are judged after the server stored them, and the refusal has to take them back.
|
|
40
|
+
*
|
|
41
|
+
* `direct` is resolved by the caller first (`X_REPO_CLIENT_PINNED` before anything opens); `pinned`
|
|
42
|
+
* is where the transaction opens when the repository has one.
|
|
43
|
+
*/
|
|
44
|
+
export const sendUpdateMany = async <Row>(
|
|
45
|
+
entity: EntityCore<Row>,
|
|
46
|
+
statements: readonly SqlFragment[],
|
|
47
|
+
returning: boolean,
|
|
48
|
+
direct: DbClient,
|
|
49
|
+
pinned: DbClient | undefined,
|
|
50
|
+
/** The batch, for a declared lock's stale check (`version-lock.ts`). Unversioned: unused. */
|
|
51
|
+
plan?: UpdateManyPlan<Row>,
|
|
52
|
+
): Promise<UpdateManyResult<Row>> => {
|
|
53
|
+
const judges = hasJsOnlyInvariant(entity.$invariants);
|
|
54
|
+
const lock = plan === undefined ? null : versionOf(entity);
|
|
55
|
+
const send = async (on: DbClient): Promise<UpdateManyResult<Row>> => {
|
|
56
|
+
let count = 0;
|
|
57
|
+
const rows: Row[] = [];
|
|
58
|
+
for (const statement of statements) {
|
|
59
|
+
if (!returning) {
|
|
60
|
+
count += await on.execute(statement);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const stored = await on.query<PhysicalRow>(statement);
|
|
64
|
+
for (const row of stored) rows.push(decodeRow(entity, row));
|
|
65
|
+
count += stored.length;
|
|
66
|
+
}
|
|
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
|
+
}
|
|
71
|
+
return { count, rows };
|
|
72
|
+
};
|
|
73
|
+
if (statements.length <= 1 && !judges && lock === null) return send(direct);
|
|
74
|
+
return withTransaction(send, pinned === undefined ? {} : { client: pinned });
|
|
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
|
+
};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Single responsibility: what an `updateMany([{ id, patch }])` batch is allowed to be, decided once
|
|
2
|
+
// in PROPERTY space so every driver writes the same thing — the patches through the one door, the
|
|
3
|
+
// column set they share, the scope they run under — and the in-memory judgement of the whole batch.
|
|
4
|
+
// The SQL is `pg-update-many-sql.ts`'s; sending it is `update-many-send.ts`'s.
|
|
5
|
+
|
|
6
|
+
import { keyOf } from './batch-read';
|
|
7
|
+
import { columnFor } from './column';
|
|
8
|
+
import { valueAt } from './cursor';
|
|
9
|
+
import type { EntityCore } from './entity';
|
|
10
|
+
import { EntityError, patchEmpty } from './errors';
|
|
11
|
+
import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
|
|
12
|
+
import { uniqueIndex, uniqueViolation } from './memory-unique';
|
|
13
|
+
import { mergedRow } from './memory-update';
|
|
14
|
+
import { readPlan, singleKeyOf } from './plan';
|
|
15
|
+
import type { RepoOptions, UpdateManyRow } from './repo';
|
|
16
|
+
import { assertRowTenant, type QueryPlan } from './tenancy';
|
|
17
|
+
import type { RowPatch } from './types';
|
|
18
|
+
import { assertVersionedUpdate } from './version-lock';
|
|
19
|
+
|
|
20
|
+
/** A batch, judged and resolved. Property names, so every driver reads one answer. */
|
|
21
|
+
export interface UpdateManyPlan<Row> {
|
|
22
|
+
readonly op: 'updateMany';
|
|
23
|
+
/** The primary key property each `id` addresses. */
|
|
24
|
+
readonly key: string;
|
|
25
|
+
/** Every property the patches write — the same set in every one, in declaration order. */
|
|
26
|
+
readonly properties: readonly string[];
|
|
27
|
+
/** The patches, parsed. Empty means there is nothing to send. */
|
|
28
|
+
readonly patches: readonly { readonly id: string; readonly patch: RowPatch<Row> }[];
|
|
29
|
+
/** The rows any write may touch: the tenant's, as every read is. No id predicate. */
|
|
30
|
+
readonly scope: QueryPlan;
|
|
31
|
+
/** `scope` plus `key in ids` — for a driver that selects the rows by plan before writing. */
|
|
32
|
+
readonly match: QueryPlan;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const OP = 'updateMany';
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A row with no id addresses nothing, and `String(undefined)` would address a row keyed
|
|
39
|
+
* "undefined". Refused as the empty filter is (`X_WRITE_UNFILTERED`): the id IS this write's filter.
|
|
40
|
+
*/
|
|
41
|
+
const unaddressed = (entityName: string, position: number): EntityError =>
|
|
42
|
+
new EntityError({
|
|
43
|
+
code: 'X_WRITE_UNFILTERED',
|
|
44
|
+
cause: `${entityName}.updateMany() row ${position + 1} names no id — a nullish id addresses no row, and is never written as the text "undefined" or "null"`,
|
|
45
|
+
fix: `${entityName}.updateMany(rows.filter((row) => row.id != null)) # or patch by filter: ${entityName}.where({ … }).updateAll(patch)`,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** Present and not `undefined`: `bindValues` binds nothing for an `undefined`, nor does memory. */
|
|
49
|
+
const writes = (patch: unknown, property: string): boolean =>
|
|
50
|
+
typeof patch === 'object' &&
|
|
51
|
+
patch !== null &&
|
|
52
|
+
Object.hasOwn(patch, property) &&
|
|
53
|
+
(patch as Readonly<Record<string, unknown>>)[property] !== undefined;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* One statement sets one column list, so a row that omits a column another row names would have
|
|
57
|
+
* it set to something — and nothing the row said. Refused, as `upsertAll` refuses the same batch.
|
|
58
|
+
*/
|
|
59
|
+
const unevenBatch = (entityName: string, position: number, missing: string): EntityError =>
|
|
60
|
+
new EntityError({
|
|
61
|
+
code: 'X_INVARIANT_VIOLATED',
|
|
62
|
+
cause: `${entityName}.updateMany() row ${position + 1} does not name "${missing}", which other rows of the batch do — one statement writes one column list to every row it updates`,
|
|
63
|
+
fix: `${entityName}.updateMany(rows.map(({ id, patch }) => ({ id, patch: { ...patch, ${missing}: <value> } }))) # or one updateMany() per column set`,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/** `update … from` meets a target row twice and keeps one of the two, unsaid which. */
|
|
67
|
+
const repeatedId = (entityName: string, position: number): EntityError =>
|
|
68
|
+
new EntityError({
|
|
69
|
+
code: 'X_INVARIANT_VIOLATED',
|
|
70
|
+
cause: `${entityName}.updateMany() row ${position + 1} addresses an id already in the batch — one statement cannot update the same row twice`,
|
|
71
|
+
fix: `${entityName}.updateMany([...new Map(rows.map((row) => [row.id, row])).values()]) # dedupe on id: the last patch per id wins`,
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/** The batch's column set, refusing a row that names a different one. */
|
|
75
|
+
const sharedProperties = <Row>(
|
|
76
|
+
entity: EntityCore<Row>,
|
|
77
|
+
patches: readonly RowPatch<Row>[],
|
|
78
|
+
): readonly string[] => {
|
|
79
|
+
const properties = Object.keys(entity.$columns).filter((property) =>
|
|
80
|
+
patches.some((patch) => writes(patch, property)),
|
|
81
|
+
);
|
|
82
|
+
for (const [position, patch] of patches.entries()) {
|
|
83
|
+
const missing = properties.find((property) => !writes(patch, property));
|
|
84
|
+
if (missing !== undefined) throw unevenBatch(entity.$name, position, missing);
|
|
85
|
+
}
|
|
86
|
+
return properties;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The batch, judged before any driver sees it. Each patch goes through `$parsePatch` (the door
|
|
91
|
+
* `update(id, patch)` uses) and the tenant check a patch gets (a patch naming another tenant
|
|
92
|
+
* would hand its row away). An app-only rule reads every row back to be judged, so a batch
|
|
93
|
+
* wider than `MAX_ASSERTED_ROWS` is refused here, before a statement exists — as `updateWhere`.
|
|
94
|
+
*/
|
|
95
|
+
export const updateManyPlan = <Row>(
|
|
96
|
+
entity: EntityCore<Row>,
|
|
97
|
+
rows: readonly UpdateManyRow<Row>[],
|
|
98
|
+
options: RepoOptions | undefined,
|
|
99
|
+
): UpdateManyPlan<Row> => {
|
|
100
|
+
const key = singleKeyOf(entity, OP);
|
|
101
|
+
const kind = columnFor(entity.$columns, key)?.$meta.kind ?? '';
|
|
102
|
+
for (const [position, row] of rows.entries()) {
|
|
103
|
+
if (row.id === undefined || row.id === null) throw unaddressed(entity.$name, position);
|
|
104
|
+
}
|
|
105
|
+
const patches = rows.map((row) => ({ id: String(row.id), patch: entity.$parsePatch(row.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
|
+
}
|
|
111
|
+
const properties = sharedProperties(
|
|
112
|
+
entity,
|
|
113
|
+
patches.map((each) => each.patch),
|
|
114
|
+
);
|
|
115
|
+
if (patches.length > 0 && properties.length === 0) {
|
|
116
|
+
throw patchEmpty(entity.$name, OP, Object.keys(entity.$columns));
|
|
117
|
+
}
|
|
118
|
+
const seen = new Set<string>();
|
|
119
|
+
for (const [position, { id }] of patches.entries()) {
|
|
120
|
+
const spelled = keyOf(kind, id);
|
|
121
|
+
if (seen.has(spelled)) throw repeatedId(entity.$name, position);
|
|
122
|
+
seen.add(spelled);
|
|
123
|
+
}
|
|
124
|
+
if (hasJsOnlyInvariant(entity.$invariants) && patches.length > MAX_ASSERTED_ROWS) {
|
|
125
|
+
throw assertedRowsTooMany(entity.$name, OP, patches.length);
|
|
126
|
+
}
|
|
127
|
+
const ids = patches.map((each) => each.id);
|
|
128
|
+
return {
|
|
129
|
+
op: OP,
|
|
130
|
+
key,
|
|
131
|
+
properties,
|
|
132
|
+
patches,
|
|
133
|
+
scope: readPlan(entity, { ...options, where: [] }, OP),
|
|
134
|
+
match: readPlan(entity, { ...options, where: [{ column: key, op: 'in', value: ids }] }, OP),
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The rows a batch makes of the stored rows it matched, judged as ONE batch before any lands —
|
|
140
|
+
* `judgeUpdate`'s four judgements (tenant, invariants, primary key, unique constraints), with one
|
|
141
|
+
* patch per row instead of one for all. `matched` are the live rows `plan.match` selects;
|
|
142
|
+
* `untouched` every other stored row, another tenant's and the soft-deleted ones included, because
|
|
143
|
+
* a Postgres unique index covers those too. `key` is the store's own row key.
|
|
144
|
+
*/
|
|
145
|
+
export const judgeUpdateMany = <Row>(
|
|
146
|
+
entity: EntityCore<Row>,
|
|
147
|
+
plan: UpdateManyPlan<Row>,
|
|
148
|
+
matched: readonly Row[],
|
|
149
|
+
untouched: readonly Row[],
|
|
150
|
+
key: (row: unknown) => string,
|
|
151
|
+
): readonly Row[] => {
|
|
152
|
+
const kind = columnFor(entity.$columns, plan.key)?.$meta.kind ?? '';
|
|
153
|
+
const patchFor = new Map(plan.patches.map((each) => [keyOf(kind, each.id), each.patch]));
|
|
154
|
+
const untouchedKeys = new Set(untouched.map((row) => key(row)));
|
|
155
|
+
const judgedKeys = new Set<string>();
|
|
156
|
+
const taken = uniqueIndex(entity, untouched);
|
|
157
|
+
const judged: Row[] = [];
|
|
158
|
+
for (const row of matched) {
|
|
159
|
+
const patch = patchFor.get(keyOf(kind, valueAt(row, plan.key)));
|
|
160
|
+
if (patch === undefined) continue;
|
|
161
|
+
const result = mergedRow(entity, row, patch);
|
|
162
|
+
assertRowTenant(entity.$name, entity.$tenantColumn, OP, result);
|
|
163
|
+
entity.$assert(result);
|
|
164
|
+
const resultKey = key(result);
|
|
165
|
+
if (untouchedKeys.has(resultKey) || judgedKeys.has(resultKey)) {
|
|
166
|
+
throw uniqueViolation(entity, `${entity.$table}_pkey`);
|
|
167
|
+
}
|
|
168
|
+
const clash = taken.clash(result);
|
|
169
|
+
if (clash !== undefined) throw uniqueViolation(entity, clash);
|
|
170
|
+
taken.add(result);
|
|
171
|
+
judged.push(result);
|
|
172
|
+
judgedKeys.add(resultKey);
|
|
173
|
+
}
|
|
174
|
+
return judged;
|
|
175
|
+
};
|
|
@@ -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
|
+
};
|
package/src/view-repo.ts
CHANGED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Single responsibility: the plan a FILTERED write runs — `updateWhere(filter, …)`, `deleteWhere(
|
|
2
|
+
// filter)` and a chain's `.updateAll(patch)`/`.deleteAll()` — built once, so the two spellings are one
|
|
3
|
+
// write. Every driver already executes any predicate a read plan holds; what a write adds is the
|
|
4
|
+
// refusal of the empty filter and of chain state (a page, a cursor, a search) it cannot honour.
|
|
5
|
+
|
|
6
|
+
import type { EntityCore } from './entity';
|
|
7
|
+
import { describeCommand, EntityError, patchEmpty, writeUnfiltered } from './errors';
|
|
8
|
+
import { namedColumns, readPlan } from './plan';
|
|
9
|
+
import type { FilteredWriteOptions } from './repo';
|
|
10
|
+
import { SEARCH_PROPERTY } from './search';
|
|
11
|
+
import type { Predicate, QueryPlan } from './tenancy';
|
|
12
|
+
import type { RowPatch } from './types';
|
|
13
|
+
import { assertUnversionedPatch } from './version-lock';
|
|
14
|
+
|
|
15
|
+
/** What a chain carries into a write terminal. */
|
|
16
|
+
export interface WriteChain {
|
|
17
|
+
readonly where: readonly Predicate[];
|
|
18
|
+
readonly limit: number | undefined;
|
|
19
|
+
readonly cursor: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A NULL test names its column and no value; every other predicate is only a filter with one. */
|
|
23
|
+
const named = (predicate: Predicate): boolean =>
|
|
24
|
+
predicate.op === 'is-null' || predicate.op === 'is-not-null' || predicate.value !== undefined;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The filter's equalities, then the chain's predicates. In the FILTER an `undefined` value is
|
|
28
|
+
* dropped, never bound — the rule `updateWhere` has always had, kept. On a CHAIN it is refused
|
|
29
|
+
* (`chainUndefined`), so it never reaches here.
|
|
30
|
+
*/
|
|
31
|
+
const boundedBy = <Row>(
|
|
32
|
+
filter: RowPatch<Row>,
|
|
33
|
+
options: FilteredWriteOptions | undefined,
|
|
34
|
+
): Predicate[] => [
|
|
35
|
+
...namedColumns(filter).map(([column, value]): Predicate => ({ column, op: 'eq', value })),
|
|
36
|
+
...(options?.where ?? []),
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const verbOf = (op: string): 'updateAll' | 'deleteAll' =>
|
|
40
|
+
op.startsWith('update') ? 'updateAll' : 'deleteAll';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A chain predicate written with `undefined` is refused, not dropped. Dropped, `.where({ orgId,
|
|
44
|
+
* postId }).deleteAll()` on a `postId` that came back undefined deletes every row the org has —
|
|
45
|
+
* the remaining predicate still bounds it, so the empty-filter refusal never fires. A chain is
|
|
46
|
+
* written predicate by predicate; one with no value is a bug at that line, never an intent.
|
|
47
|
+
*/
|
|
48
|
+
const chainUndefined = <Row>(
|
|
49
|
+
entity: EntityCore<Row>,
|
|
50
|
+
op: string,
|
|
51
|
+
where: readonly Predicate[],
|
|
52
|
+
): EntityError | undefined => {
|
|
53
|
+
const missing = where.find((predicate) => !named(predicate));
|
|
54
|
+
if (missing === undefined) return undefined;
|
|
55
|
+
const verb = verbOf(op);
|
|
56
|
+
return new EntityError({
|
|
57
|
+
code: 'X_WRITE_UNFILTERED',
|
|
58
|
+
cause: `${entity.$name}.where(…).${verb}() — the predicate on ${missing.column} has an undefined value, and dropping it would widen the write to every row the rest of the chain matches`,
|
|
59
|
+
fix: `${entity.$name}.where({ ${missing.column} }).${verb}(${verb === 'updateAll' ? '…' : ''}) # guard ${missing.column} so it is defined before the write; for SQL NULL write .andWhere('${missing.column}', 'is-null')`,
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The fix spelled as the call the author wrote. `X_WRITE_UNFILTERED` is one situation whichever
|
|
65
|
+
* spelling hit it, so it stays one code; only the line to paste differs.
|
|
66
|
+
*/
|
|
67
|
+
const unfiltered = <Row>(entity: EntityCore<Row>, op: string, chained: boolean): EntityError => {
|
|
68
|
+
if (!chained) return writeUnfiltered(entity.$name, op, entity.$primaryKey);
|
|
69
|
+
const verb = verbOf(op);
|
|
70
|
+
return new EntityError({
|
|
71
|
+
code: 'X_WRITE_UNFILTERED',
|
|
72
|
+
cause: `${entity.$name}.where(…).${verb}() named no filter — an empty chain would reach every row`,
|
|
73
|
+
fix: `${entity.$name}.where({ ${entity.$primaryKey.join(', ')} }).${verb}(${verb === 'updateAll' ? '…' : ''}) # name the columns that bound it. A deliberate whole-table write is a migration: x db gen "<name>"`,
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The plan for a filtered delete. The empty filter is refused BEFORE tenancy runs: the org
|
|
79
|
+
* predicate the framework adds bounds the blast radius to one tenant, which is still every row
|
|
80
|
+
* that tenant has. Then the read's own plan — tenancy, operator screening — so a chain's
|
|
81
|
+
* `.deleteAll()` reaches exactly the rows the same chain's `.all()` would read, and no other.
|
|
82
|
+
*/
|
|
83
|
+
export const writeWherePlan = <Row>(
|
|
84
|
+
entity: EntityCore<Row>,
|
|
85
|
+
filter: RowPatch<Row>,
|
|
86
|
+
options: FilteredWriteOptions | undefined,
|
|
87
|
+
op: string,
|
|
88
|
+
): QueryPlan => {
|
|
89
|
+
const refused = chainUndefined(entity, op, options?.where ?? []);
|
|
90
|
+
if (refused !== undefined) throw refused;
|
|
91
|
+
const where = boundedBy(filter, options);
|
|
92
|
+
if (where.length === 0) throw unfiltered(entity, op, options?.where !== undefined);
|
|
93
|
+
const { where: _chain, ...rest } = options ?? {};
|
|
94
|
+
return readPlan(entity, { ...rest, where }, op);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The plan for a filtered update: the delete's, after the patch is judged non-empty — "4 rows
|
|
99
|
+
* updated" for a statement that set nothing is the answer nobody can act on. Filter first, so the
|
|
100
|
+
* order of the two refusals is the order of the arguments.
|
|
101
|
+
*/
|
|
102
|
+
export const updateWherePlan = <Row>(
|
|
103
|
+
entity: EntityCore<Row>,
|
|
104
|
+
filter: RowPatch<Row>,
|
|
105
|
+
patch: RowPatch<Row>,
|
|
106
|
+
options: FilteredWriteOptions | undefined,
|
|
107
|
+
op: string,
|
|
108
|
+
): QueryPlan => {
|
|
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);
|
|
112
|
+
if (namedColumns(patch).length > 0) return plan;
|
|
113
|
+
const columns = Object.keys(entity.$columns);
|
|
114
|
+
if (options?.where === undefined) throw patchEmpty(entity.$name, op, columns);
|
|
115
|
+
throw new EntityError({
|
|
116
|
+
code: 'X_PATCH_EMPTY',
|
|
117
|
+
cause: `${entity.$name}.where(…).updateAll() named no columns to write`,
|
|
118
|
+
fix: `${entity.$name}.where(filter).updateAll({ <column>: <value> }) # pick a column from: ${columns.join(', ')}`,
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const unwritable = (entityName: string, verb: string, what: string, instead: string) =>
|
|
123
|
+
new EntityError({
|
|
124
|
+
code: 'X_INVARIANT_VIOLATED',
|
|
125
|
+
cause: `${entityName}.where(…).${what}.${verb}() — ${instead}`,
|
|
126
|
+
fix: `${describeCommand(entityName)} # the entity whose write chain carries ${what}: drop it, or sweep with .where(filter).inBatches(1000) and write each batch by its keys`,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A write has no page. `limit(n)` would read as "the first n" and `after(cursor)` as "past this
|
|
131
|
+
* row", and neither Postgres's UPDATE/DELETE nor any other driver's honours either — so a chain
|
|
132
|
+
* carrying one is refused rather than written in full. A `.search()` is refused too: an external
|
|
133
|
+
* index answers at most `MAX_PAGE_SIZE` ids, and a write over a sample of the matches is a write
|
|
134
|
+
* nobody asked for. The order, the projection and preloads change no row, and are ignored.
|
|
135
|
+
*/
|
|
136
|
+
export const assertWritableChain = (
|
|
137
|
+
entityName: string,
|
|
138
|
+
verb: 'updateAll' | 'deleteAll',
|
|
139
|
+
chain: WriteChain,
|
|
140
|
+
): void => {
|
|
141
|
+
if (chain.limit !== undefined) {
|
|
142
|
+
throw unwritable(entityName, verb, 'limit()', 'a write has no page and reaches every match');
|
|
143
|
+
}
|
|
144
|
+
if (chain.cursor !== null) {
|
|
145
|
+
throw unwritable(entityName, verb, 'after()', 'a write has no page and reaches every match');
|
|
146
|
+
}
|
|
147
|
+
if (chain.where.some((each) => each.column === SEARCH_PROPERTY)) {
|
|
148
|
+
throw unwritable(
|
|
149
|
+
entityName,
|
|
150
|
+
verb,
|
|
151
|
+
'search()',
|
|
152
|
+
'an external search index answers a bounded sample of ids, never every match',
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** Every column a filtered write is bounded by — what `sealed-repo.ts` refuses a sealed one from. */
|
|
158
|
+
export const predicateColumns = (
|
|
159
|
+
filter: unknown,
|
|
160
|
+
where: readonly Predicate[] | undefined,
|
|
161
|
+
): readonly string[] => [
|
|
162
|
+
...namedColumns(filter).map(([column]) => column),
|
|
163
|
+
...(where ?? []).map((each) => each.column),
|
|
164
|
+
];
|