@ultimat3/entity 31.8.0 → 31.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,8 +6,7 @@
6
6
 
7
7
  import { pageOf } from '@ultimat3/core';
8
8
  import type { AggregateFn } from './aggregate';
9
- import { namedColumns } from './plan';
10
- import type { FindManyArgs, Repo, UpsertArgs } from './repo';
9
+ import type { FilteredWriteOptions, FindManyArgs, Repo, UpsertArgs } from './repo';
11
10
  import type { SealedField, SealedSource, SealKeys } from './sealed';
12
11
  import {
13
12
  lookupCandidates,
@@ -20,6 +19,7 @@ import {
20
19
  import type { SealedUse } from './sealed-errors';
21
20
  import { sealedLookupValue, sealedMissing, sealedPredicate } from './sealed-errors';
22
21
  import type { Predicate } from './tenancy';
22
+ import { predicateColumns } from './write-where';
23
23
 
24
24
  type Loose = Readonly<Record<string, unknown>>;
25
25
 
@@ -166,8 +166,15 @@ const readArgs = async <A extends FindManyArgs>(
166
166
  export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo: R): R => {
167
167
  const fields = sealedFields(entity);
168
168
  if (fields.length === 0) return repo;
169
- const filterOf = (filter: unknown): readonly string[] =>
170
- namedColumns(filter).map(([property]) => property);
169
+
170
+ const filterOf = (filter: unknown): readonly string[] => predicateColumns(filter, undefined);
171
+ const chainArgs = async (options: FilteredWriteOptions | undefined, keys: SealKeys) =>
172
+ options?.where === undefined
173
+ ? options
174
+ : {
175
+ ...options,
176
+ where: await Promise.all(options.where.map((one) => rewrite(entity, fields, one, keys))),
177
+ };
171
178
 
172
179
  // Every method takes its own ring: one resolution per repository call, however many values.
173
180
  const sealing: Repo<Row> = {
@@ -205,16 +212,19 @@ export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo:
205
212
  delete: (id, options) => repo.delete(id, options),
206
213
  // A filtered write's filter is refused for every sealed column, lookup included: its shape is
207
214
  // one value per column, and during a rotation a lookup value has one stored form PER KEY.
215
+ // A chain's predicates (`options.where`) are a READ's, rewritten as a read rewrites them — a
216
+ // lookup column matched by every stored form, so a rotation in progress still finds its rows.
208
217
  async deleteWhere(filter, options) {
209
218
  refuseNamed(entity, fields, filterOf(filter), "a filtered write's filter");
210
- return repo.deleteWhere(filter, options);
219
+ return repo.deleteWhere(filter, await chainArgs(options, sealKeysOnce()));
211
220
  },
212
221
  async updateWhere(filter, patch, options) {
213
222
  refuseNamed(entity, fields, filterOf(filter), "a filtered write's filter");
223
+ const keys = sealKeysOnce();
214
224
  return repo.updateWhere(
215
225
  filter,
216
- await sealRow(entity, fields, patch, sealKeysOnce()),
217
- options,
226
+ await sealRow(entity, fields, patch, keys),
227
+ await chainArgs(options, keys),
218
228
  );
219
229
  },
220
230
  async count(args) {
@@ -232,6 +242,37 @@ export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo:
232
242
  return repo.approximateCount(await readArgs(entity, fields, args, sealKeysOnce()));
233
243
  },
234
244
  };
245
+ // The count-only and bulk writes: sealed exactly as their counterparts above, and present only
246
+ // where the inner repository has them, so the typed handle's fallback still sees an absence.
247
+ const sealAll = <T>(rows: readonly T[], keys: SealKeys): Promise<T[]> =>
248
+ Promise.all(rows.map((row) => sealRow(entity, fields, row, keys, true)));
249
+ const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
250
+ if (insertAllCount !== undefined) {
251
+ sealing.insertAllCount = async (rows, options) =>
252
+ insertAllCount.call(repo, await sealAll(rows, sealKeysOnce()), options);
253
+ }
254
+ if (upsertAllCount !== undefined) {
255
+ sealing.upsertAllCount = async (rows, args) => {
256
+ refuseNamed(entity, fields, args.onConflict, 'an upsert conflict target', true);
257
+ return upsertAllCount.call(repo, await sealAll(rows, sealKeysOnce()), args);
258
+ };
259
+ }
260
+ if (copyAll !== undefined) {
261
+ sealing.copyAll = async (rows, options) =>
262
+ copyAll.call(repo, await sealAll(rows, sealKeysOnce()), options);
263
+ }
264
+ if (updateMany !== undefined) {
265
+ sealing.updateMany = async (rows, options) => {
266
+ const keys = sealKeysOnce();
267
+ const sealed = await Promise.all(
268
+ rows.map(async ({ id, patch }) => ({
269
+ id,
270
+ patch: await sealRow(entity, fields, patch, keys),
271
+ })),
272
+ );
273
+ return updateMany.call(repo, sealed, options);
274
+ };
275
+ }
235
276
  // A bucket is an instant and a sum is arithmetic: neither has a meaning over ciphertext.
236
277
  const series = repo.series?.bind(repo);
237
278
  if (series !== undefined) {
@@ -3,11 +3,13 @@
3
3
  // (`returning *`) — for a composite or non-`id` key too. Not searchable, or the built-in index
4
4
  // installed: the repository is handed back, or the write delegates with no extra statement.
5
5
 
6
+ import { copyColumns } from './copy-plan';
6
7
  import type { EntityCore } from './entity';
7
8
  import type { Repo, RepoOptions } from './repo';
8
9
  import type { SearchMirror } from './search-index-sync';
9
10
  import { mirrorFor, mirrors } from './search-index-sync';
10
11
  import { collectWrittenRows } from './search-written-rows';
12
+ import type { RowPatch } from './types';
11
13
 
12
14
  type Told = (mirror: SearchMirror, rows: readonly unknown[]) => void;
13
15
 
@@ -58,8 +60,59 @@ export function searchMirroredRepo<Row>(entity: EntityCore<Row>, repo: Repo<Row>
58
60
  (mirror, rows) =>
59
61
  mirror.deleted(op, rows);
60
62
 
63
+ /**
64
+ * A count-only write names no rows, and the mirror needs them: while an external index is
65
+ * installed it runs as its returning counterpart — the same judging, the rows mirrored, their
66
+ * length answered. With none installed it is the count path, untouched.
67
+ */
68
+ const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
69
+ const counts: Partial<Repo<Row>> = {
70
+ ...(insertAllCount === undefined
71
+ ? {}
72
+ : {
73
+ insertAllCount: async (rows, options) =>
74
+ mirrors(core)
75
+ ? (await stored(core, 'insertAll', options, () => repo.insertAll(rows, options)))
76
+ .length
77
+ : insertAllCount.call(repo, rows, options),
78
+ }),
79
+ ...(upsertAllCount === undefined
80
+ ? {}
81
+ : {
82
+ upsertAllCount: async (rows, args) =>
83
+ mirrors(core)
84
+ ? (await stored(core, 'upsertAll', args, () => repo.upsertAll(rows, args))).length
85
+ : upsertAllCount.call(repo, rows, args),
86
+ }),
87
+ ...(copyAll === undefined
88
+ ? {}
89
+ : {
90
+ copyAll: async (rows, options) => {
91
+ if (!mirrors(core)) return copyAll.call(repo, rows, options);
92
+ // COPY's own refusal first, so a load is refused alike with or without an index.
93
+ copyColumns(entity, rows as readonly RowPatch<Row>[]);
94
+ return (await stored(core, 'copyAll', options, () => repo.insertAll(rows, options)))
95
+ .length;
96
+ },
97
+ }),
98
+ ...(updateMany === undefined
99
+ ? {}
100
+ : {
101
+ updateMany: (rows, options) =>
102
+ collected(
103
+ core,
104
+ 'updateMany',
105
+ options,
106
+ () => updateMany.call(repo, rows, options),
107
+ changed('updateMany'),
108
+ (count) => count,
109
+ ),
110
+ }),
111
+ };
112
+
61
113
  return {
62
114
  ...repo,
115
+ ...counts,
63
116
  insert: async (values, options) =>
64
117
  (await stored(core, 'insert', options, () => single(repo.insert(values, options))))[0],
65
118
  insertAll: (rows, options) =>
package/src/type-pins.ts CHANGED
@@ -476,3 +476,12 @@ export type _FindManyAnswersCorePage = Assert<
476
476
  : false
477
477
  : false
478
478
  >;
479
+
480
+ /**
481
+ * `select` takes the chain's own spelling — `{ id: true }` — never a list of names. The page byte
482
+ * refusal's fix is rendered in this spelling (`page-bytes.ts`); a string argument would be split
483
+ * into its characters by `Object.keys` and select nothing.
484
+ */
485
+ export type _SelectTakesAnObjectNotNames = Assert<
486
+ 'id' extends Parameters<ReadBuilder<{ readonly id: string }>['select']>[0] ? false : true
487
+ >;
@@ -0,0 +1,66 @@
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 type { UpdateManyPlan } from './update-many';
11
+
12
+ /** What the batch did: how many rows it updated, and those rows when `returning` asked for them. */
13
+ export interface UpdateManyResult<Row> {
14
+ readonly count: number;
15
+ readonly rows: readonly Row[];
16
+ }
17
+
18
+ /**
19
+ * `returning "<table>".*` or a count. The rows are read back when an app-only rule must judge
20
+ * them (the plan already refused a batch past `MAX_ASSERTED_ROWS`), or when the search mirror's
21
+ * sink is open and the batch fits that same bound — each id matches at most one row, so the batch
22
+ * width bounds the rows without the `count(*)` `updateWhere` spends on it. Otherwise a count:
23
+ * nobody reads the rows, and a backfill must not stream its table back into the process.
24
+ */
25
+ export const updateManyReturns = <Row>(
26
+ entity: EntityCore<Row>,
27
+ plan: UpdateManyPlan<Row>,
28
+ sinkOpen: boolean,
29
+ ): boolean =>
30
+ hasJsOnlyInvariant(entity.$invariants) || (sinkOpen && plan.patches.length <= MAX_ASSERTED_ROWS);
31
+
32
+ /**
33
+ * One statement and no rule to judge is one autocommit statement. Several are one transaction — a
34
+ * SAVEPOINT inside an open one — so a batch failing in its last chunk leaves no earlier chunk
35
+ * stored, as `writeChunks` holds `insertAll`. An app-only rule takes the transaction at any width:
36
+ * the rows are judged after the server stored them, and the refusal has to take them back.
37
+ *
38
+ * `direct` is resolved by the caller first (`X_REPO_CLIENT_PINNED` before anything opens); `pinned`
39
+ * is where the transaction opens when the repository has one.
40
+ */
41
+ export const sendUpdateMany = async <Row>(
42
+ entity: EntityCore<Row>,
43
+ statements: readonly SqlFragment[],
44
+ returning: boolean,
45
+ direct: DbClient,
46
+ pinned: DbClient | undefined,
47
+ ): Promise<UpdateManyResult<Row>> => {
48
+ const judges = hasJsOnlyInvariant(entity.$invariants);
49
+ const send = async (on: DbClient): Promise<UpdateManyResult<Row>> => {
50
+ let count = 0;
51
+ const rows: Row[] = [];
52
+ for (const statement of statements) {
53
+ if (!returning) {
54
+ count += await on.execute(statement);
55
+ continue;
56
+ }
57
+ const stored = await on.query<PhysicalRow>(statement);
58
+ for (const row of stored) rows.push(decodeRow(entity, row));
59
+ count += stored.length;
60
+ }
61
+ if (judges) for (const row of rows) entity.$assert(row);
62
+ return { count, rows };
63
+ };
64
+ if (statements.length <= 1 && !judges) return send(direct);
65
+ return withTransaction(send, pinned === undefined ? {} : { client: pinned });
66
+ };
@@ -0,0 +1,170 @@
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
+
19
+ /** A batch, judged and resolved. Property names, so every driver reads one answer. */
20
+ export interface UpdateManyPlan<Row> {
21
+ readonly op: 'updateMany';
22
+ /** The primary key property each `id` addresses. */
23
+ readonly key: string;
24
+ /** Every property the patches write — the same set in every one, in declaration order. */
25
+ readonly properties: readonly string[];
26
+ /** The patches, parsed. Empty means there is nothing to send. */
27
+ readonly patches: readonly { readonly id: string; readonly patch: RowPatch<Row> }[];
28
+ /** The rows any write may touch: the tenant's, as every read is. No id predicate. */
29
+ readonly scope: QueryPlan;
30
+ /** `scope` plus `key in ids` — for a driver that selects the rows by plan before writing. */
31
+ readonly match: QueryPlan;
32
+ }
33
+
34
+ const OP = 'updateMany';
35
+
36
+ /**
37
+ * A row with no id addresses nothing, and `String(undefined)` would address a row keyed
38
+ * "undefined". Refused as the empty filter is (`X_WRITE_UNFILTERED`): the id IS this write's filter.
39
+ */
40
+ const unaddressed = (entityName: string, position: number): EntityError =>
41
+ new EntityError({
42
+ code: 'X_WRITE_UNFILTERED',
43
+ 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"`,
44
+ fix: `${entityName}.updateMany(rows.filter((row) => row.id != null)) # or patch by filter: ${entityName}.where({ … }).updateAll(patch)`,
45
+ });
46
+
47
+ /** Present and not `undefined`: `bindValues` binds nothing for an `undefined`, nor does memory. */
48
+ const writes = (patch: unknown, property: string): boolean =>
49
+ typeof patch === 'object' &&
50
+ patch !== null &&
51
+ Object.hasOwn(patch, property) &&
52
+ (patch as Readonly<Record<string, unknown>>)[property] !== undefined;
53
+
54
+ /**
55
+ * One statement sets one column list, so a row that omits a column another row names would have
56
+ * it set to something — and nothing the row said. Refused, as `upsertAll` refuses the same batch.
57
+ */
58
+ const unevenBatch = (entityName: string, position: number, missing: string): EntityError =>
59
+ new EntityError({
60
+ code: 'X_INVARIANT_VIOLATED',
61
+ 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`,
62
+ fix: `${entityName}.updateMany(rows.map(({ id, patch }) => ({ id, patch: { ...patch, ${missing}: <value> } }))) # or one updateMany() per column set`,
63
+ });
64
+
65
+ /** `update … from` meets a target row twice and keeps one of the two, unsaid which. */
66
+ const repeatedId = (entityName: string, position: number): EntityError =>
67
+ new EntityError({
68
+ code: 'X_INVARIANT_VIOLATED',
69
+ cause: `${entityName}.updateMany() row ${position + 1} addresses an id already in the batch — one statement cannot update the same row twice`,
70
+ fix: `${entityName}.updateMany([...new Map(rows.map((row) => [row.id, row])).values()]) # dedupe on id: the last patch per id wins`,
71
+ });
72
+
73
+ /** The batch's column set, refusing a row that names a different one. */
74
+ const sharedProperties = <Row>(
75
+ entity: EntityCore<Row>,
76
+ patches: readonly RowPatch<Row>[],
77
+ ): readonly string[] => {
78
+ const properties = Object.keys(entity.$columns).filter((property) =>
79
+ patches.some((patch) => writes(patch, property)),
80
+ );
81
+ for (const [position, patch] of patches.entries()) {
82
+ const missing = properties.find((property) => !writes(patch, property));
83
+ if (missing !== undefined) throw unevenBatch(entity.$name, position, missing);
84
+ }
85
+ return properties;
86
+ };
87
+
88
+ /**
89
+ * The batch, judged before any driver sees it. Each patch goes through `$parsePatch` (the door
90
+ * `update(id, patch)` uses) and the tenant check a patch gets (a patch naming another tenant
91
+ * would hand its row away). An app-only rule reads every row back to be judged, so a batch
92
+ * wider than `MAX_ASSERTED_ROWS` is refused here, before a statement exists — as `updateWhere`.
93
+ */
94
+ export const updateManyPlan = <Row>(
95
+ entity: EntityCore<Row>,
96
+ rows: readonly UpdateManyRow<Row>[],
97
+ options: RepoOptions | undefined,
98
+ ): UpdateManyPlan<Row> => {
99
+ const key = singleKeyOf(entity, OP);
100
+ const kind = columnFor(entity.$columns, key)?.$meta.kind ?? '';
101
+ for (const [position, row] of rows.entries()) {
102
+ if (row.id === undefined || row.id === null) throw unaddressed(entity.$name, position);
103
+ }
104
+ 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
+ const properties = sharedProperties(
107
+ entity,
108
+ patches.map((each) => each.patch),
109
+ );
110
+ if (patches.length > 0 && properties.length === 0) {
111
+ throw patchEmpty(entity.$name, OP, Object.keys(entity.$columns));
112
+ }
113
+ const seen = new Set<string>();
114
+ for (const [position, { id }] of patches.entries()) {
115
+ const spelled = keyOf(kind, id);
116
+ if (seen.has(spelled)) throw repeatedId(entity.$name, position);
117
+ seen.add(spelled);
118
+ }
119
+ if (hasJsOnlyInvariant(entity.$invariants) && patches.length > MAX_ASSERTED_ROWS) {
120
+ throw assertedRowsTooMany(entity.$name, OP, patches.length);
121
+ }
122
+ const ids = patches.map((each) => each.id);
123
+ return {
124
+ op: OP,
125
+ key,
126
+ properties,
127
+ patches,
128
+ scope: readPlan(entity, { ...options, where: [] }, OP),
129
+ match: readPlan(entity, { ...options, where: [{ column: key, op: 'in', value: ids }] }, OP),
130
+ };
131
+ };
132
+
133
+ /**
134
+ * The rows a batch makes of the stored rows it matched, judged as ONE batch before any lands —
135
+ * `judgeUpdate`'s four judgements (tenant, invariants, primary key, unique constraints), with one
136
+ * patch per row instead of one for all. `matched` are the live rows `plan.match` selects;
137
+ * `untouched` every other stored row, another tenant's and the soft-deleted ones included, because
138
+ * a Postgres unique index covers those too. `key` is the store's own row key.
139
+ */
140
+ export const judgeUpdateMany = <Row>(
141
+ entity: EntityCore<Row>,
142
+ plan: UpdateManyPlan<Row>,
143
+ matched: readonly Row[],
144
+ untouched: readonly Row[],
145
+ key: (row: unknown) => string,
146
+ ): readonly Row[] => {
147
+ const kind = columnFor(entity.$columns, plan.key)?.$meta.kind ?? '';
148
+ const patchFor = new Map(plan.patches.map((each) => [keyOf(kind, each.id), each.patch]));
149
+ const untouchedKeys = new Set(untouched.map((row) => key(row)));
150
+ const judgedKeys = new Set<string>();
151
+ const taken = uniqueIndex(entity, untouched);
152
+ const judged: Row[] = [];
153
+ for (const row of matched) {
154
+ const patch = patchFor.get(keyOf(kind, valueAt(row, plan.key)));
155
+ if (patch === undefined) continue;
156
+ const result = mergedRow(entity, row, patch);
157
+ assertRowTenant(entity.$name, entity.$tenantColumn, OP, result);
158
+ entity.$assert(result);
159
+ const resultKey = key(result);
160
+ if (untouchedKeys.has(resultKey) || judgedKeys.has(resultKey)) {
161
+ throw uniqueViolation(entity, `${entity.$table}_pkey`);
162
+ }
163
+ const clash = taken.clash(result);
164
+ if (clash !== undefined) throw uniqueViolation(entity, clash);
165
+ taken.add(result);
166
+ judged.push(result);
167
+ judgedKeys.add(resultKey);
168
+ }
169
+ return judged;
170
+ };
package/src/view-repo.ts CHANGED
@@ -14,6 +14,10 @@ const WRITES = [
14
14
  'delete',
15
15
  'deleteWhere',
16
16
  'updateWhere',
17
+ 'insertAllCount',
18
+ 'upsertAllCount',
19
+ 'copyAll',
20
+ 'updateMany',
17
21
  'lock',
18
22
  ] as const;
19
23
 
@@ -0,0 +1,161 @@
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
+
14
+ /** What a chain carries into a write terminal. */
15
+ export interface WriteChain {
16
+ readonly where: readonly Predicate[];
17
+ readonly limit: number | undefined;
18
+ readonly cursor: string | null;
19
+ }
20
+
21
+ /** A NULL test names its column and no value; every other predicate is only a filter with one. */
22
+ const named = (predicate: Predicate): boolean =>
23
+ predicate.op === 'is-null' || predicate.op === 'is-not-null' || predicate.value !== undefined;
24
+
25
+ /**
26
+ * The filter's equalities, then the chain's predicates. In the FILTER an `undefined` value is
27
+ * dropped, never bound — the rule `updateWhere` has always had, kept. On a CHAIN it is refused
28
+ * (`chainUndefined`), so it never reaches here.
29
+ */
30
+ const boundedBy = <Row>(
31
+ filter: RowPatch<Row>,
32
+ options: FilteredWriteOptions | undefined,
33
+ ): Predicate[] => [
34
+ ...namedColumns(filter).map(([column, value]): Predicate => ({ column, op: 'eq', value })),
35
+ ...(options?.where ?? []),
36
+ ];
37
+
38
+ const verbOf = (op: string): 'updateAll' | 'deleteAll' =>
39
+ op.startsWith('update') ? 'updateAll' : 'deleteAll';
40
+
41
+ /**
42
+ * A chain predicate written with `undefined` is refused, not dropped. Dropped, `.where({ orgId,
43
+ * postId }).deleteAll()` on a `postId` that came back undefined deletes every row the org has —
44
+ * the remaining predicate still bounds it, so the empty-filter refusal never fires. A chain is
45
+ * written predicate by predicate; one with no value is a bug at that line, never an intent.
46
+ */
47
+ const chainUndefined = <Row>(
48
+ entity: EntityCore<Row>,
49
+ op: string,
50
+ where: readonly Predicate[],
51
+ ): EntityError | undefined => {
52
+ const missing = where.find((predicate) => !named(predicate));
53
+ if (missing === undefined) return undefined;
54
+ const verb = verbOf(op);
55
+ return new EntityError({
56
+ code: 'X_WRITE_UNFILTERED',
57
+ 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`,
58
+ 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')`,
59
+ });
60
+ };
61
+
62
+ /**
63
+ * The fix spelled as the call the author wrote. `X_WRITE_UNFILTERED` is one situation whichever
64
+ * spelling hit it, so it stays one code; only the line to paste differs.
65
+ */
66
+ const unfiltered = <Row>(entity: EntityCore<Row>, op: string, chained: boolean): EntityError => {
67
+ if (!chained) return writeUnfiltered(entity.$name, op, entity.$primaryKey);
68
+ const verb = verbOf(op);
69
+ return new EntityError({
70
+ code: 'X_WRITE_UNFILTERED',
71
+ cause: `${entity.$name}.where(…).${verb}() named no filter — an empty chain would reach every row`,
72
+ 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>"`,
73
+ });
74
+ };
75
+
76
+ /**
77
+ * The plan for a filtered delete. The empty filter is refused BEFORE tenancy runs: the org
78
+ * predicate the framework adds bounds the blast radius to one tenant, which is still every row
79
+ * that tenant has. Then the read's own plan — tenancy, operator screening — so a chain's
80
+ * `.deleteAll()` reaches exactly the rows the same chain's `.all()` would read, and no other.
81
+ */
82
+ export const writeWherePlan = <Row>(
83
+ entity: EntityCore<Row>,
84
+ filter: RowPatch<Row>,
85
+ options: FilteredWriteOptions | undefined,
86
+ op: string,
87
+ ): QueryPlan => {
88
+ const refused = chainUndefined(entity, op, options?.where ?? []);
89
+ if (refused !== undefined) throw refused;
90
+ const where = boundedBy(filter, options);
91
+ if (where.length === 0) throw unfiltered(entity, op, options?.where !== undefined);
92
+ const { where: _chain, ...rest } = options ?? {};
93
+ return readPlan(entity, { ...rest, where }, op);
94
+ };
95
+
96
+ /**
97
+ * The plan for a filtered update: the delete's, after the patch is judged non-empty — "4 rows
98
+ * updated" for a statement that set nothing is the answer nobody can act on. Filter first, so the
99
+ * order of the two refusals is the order of the arguments.
100
+ */
101
+ export const updateWherePlan = <Row>(
102
+ entity: EntityCore<Row>,
103
+ filter: RowPatch<Row>,
104
+ patch: RowPatch<Row>,
105
+ options: FilteredWriteOptions | undefined,
106
+ op: string,
107
+ ): QueryPlan => {
108
+ const plan = writeWherePlan(entity, filter, options, op);
109
+ if (namedColumns(patch).length > 0) return plan;
110
+ const columns = Object.keys(entity.$columns);
111
+ if (options?.where === undefined) throw patchEmpty(entity.$name, op, columns);
112
+ throw new EntityError({
113
+ code: 'X_PATCH_EMPTY',
114
+ cause: `${entity.$name}.where(…).updateAll() named no columns to write`,
115
+ fix: `${entity.$name}.where(filter).updateAll({ <column>: <value> }) # pick a column from: ${columns.join(', ')}`,
116
+ });
117
+ };
118
+
119
+ const unwritable = (entityName: string, verb: string, what: string, instead: string) =>
120
+ new EntityError({
121
+ code: 'X_INVARIANT_VIOLATED',
122
+ cause: `${entityName}.where(…).${what}.${verb}() — ${instead}`,
123
+ 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`,
124
+ });
125
+
126
+ /**
127
+ * A write has no page. `limit(n)` would read as "the first n" and `after(cursor)` as "past this
128
+ * row", and neither Postgres's UPDATE/DELETE nor any other driver's honours either — so a chain
129
+ * carrying one is refused rather than written in full. A `.search()` is refused too: an external
130
+ * index answers at most `MAX_PAGE_SIZE` ids, and a write over a sample of the matches is a write
131
+ * nobody asked for. The order, the projection and preloads change no row, and are ignored.
132
+ */
133
+ export const assertWritableChain = (
134
+ entityName: string,
135
+ verb: 'updateAll' | 'deleteAll',
136
+ chain: WriteChain,
137
+ ): void => {
138
+ if (chain.limit !== undefined) {
139
+ throw unwritable(entityName, verb, 'limit()', 'a write has no page and reaches every match');
140
+ }
141
+ if (chain.cursor !== null) {
142
+ throw unwritable(entityName, verb, 'after()', 'a write has no page and reaches every match');
143
+ }
144
+ if (chain.where.some((each) => each.column === SEARCH_PROPERTY)) {
145
+ throw unwritable(
146
+ entityName,
147
+ verb,
148
+ 'search()',
149
+ 'an external search index answers a bounded sample of ids, never every match',
150
+ );
151
+ }
152
+ };
153
+
154
+ /** Every column a filtered write is bounded by — what `sealed-repo.ts` refuses a sealed one from. */
155
+ export const predicateColumns = (
156
+ filter: unknown,
157
+ where: readonly Predicate[] | undefined,
158
+ ): readonly string[] => [
159
+ ...namedColumns(filter).map(([column]) => column),
160
+ ...(where ?? []).map((each) => each.column),
161
+ ];