@ultimat3/entity 31.7.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.
package/src/repo.ts CHANGED
@@ -59,6 +59,22 @@ export interface UpsertArgs<T = unknown> extends RepoOptions {
59
59
  readonly overwrites?: readonly (keyof T & string)[];
60
60
  }
61
61
 
62
+ /**
63
+ * A filtered write's options: `RepoOptions`, plus the predicates a CHAIN carries
64
+ * (`db.x.where(…).andWhere(…).update(patch)`). They AND with the equality filter, every guard
65
+ * applies to the union, and an empty union is `X_WRITE_UNFILTERED` — so a repository that ignores
66
+ * `where` refuses the chain's empty filter rather than reading it as every row.
67
+ */
68
+ export interface FilteredWriteOptions extends RepoOptions {
69
+ readonly where?: readonly Predicate[];
70
+ }
71
+
72
+ /** One row of `updateMany`: the row's id and what it becomes. */
73
+ export interface UpdateManyRow<T = unknown> {
74
+ readonly id: IdOf<T>;
75
+ readonly patch: RowPatch<T>;
76
+ }
77
+
62
78
  /**
63
79
  * `findById`'s options: `RepoOptions`, plus the one knob a point READ has and a write must not.
64
80
  *
@@ -125,14 +141,36 @@ export interface Repo<T = unknown> {
125
141
  * to be able to tell "nothing matched" from "it worked", and an empty filter is
126
142
  * `X_WRITE_UNFILTERED` rather than every row.
127
143
  */
128
- deleteWhere(filter: RowPatch<T>, options?: RepoOptions): Promise<number>;
144
+ deleteWhere(filter: RowPatch<T>, options?: FilteredWriteOptions): Promise<number>;
129
145
  /**
130
146
  * Update by filter, returning how many rows were written. The `update(id, patch)` a composite
131
147
  * primary key cannot express — `participants.lastReadAt` is the reference case. Same two guards
132
148
  * as `deleteWhere`, plus `X_PATCH_EMPTY` for a patch that names no columns, and soft-deleted
133
149
  * rows are not reachable, exactly as they are not by `update(id, patch)`.
134
150
  */
135
- updateWhere(filter: RowPatch<T>, patch: RowPatch<T>, options?: RepoOptions): Promise<number>;
151
+ updateWhere(
152
+ filter: RowPatch<T>,
153
+ patch: RowPatch<T>,
154
+ options?: FilteredWriteOptions,
155
+ ): Promise<number>;
156
+ /**
157
+ * A different patch per row, by id, resolving with how many rows were written — the bulk form of a
158
+ * loop of `update(id, patch)`. Every patch names the same columns. Optional: the typed handle
159
+ * runs a `updateWhere` per row for a repository without it.
160
+ */
161
+ updateMany?(rows: readonly UpdateManyRow<T>[], options?: RepoOptions): Promise<number>;
162
+ /**
163
+ * `insertAll` answering a count: no `returning *`, nothing decoded. Optional: the typed handle
164
+ * counts `insertAll`'s rows for a repository without it.
165
+ */
166
+ insertAllCount?(rows: readonly RowWrite<T>[], options?: RepoOptions): Promise<number>;
167
+ /** `upsertAll` answering how many rows it wrote, as `insertAllCount` is to `insertAll`. */
168
+ upsertAllCount?(rows: readonly RowWrite<T>[], args: UpsertArgs<T>): Promise<number>;
169
+ /**
170
+ * The bulk load: Postgres `COPY … FROM STDIN`, judged exactly as `insertAll` judges its rows.
171
+ * Optional: `insertAllCount` (else `insertAll`) for a repository without it.
172
+ */
173
+ copyAll?(rows: readonly RowWrite<T>[], options?: RepoOptions): Promise<number>;
136
174
  count(args?: FindManyArgs): Promise<number>;
137
175
  /**
138
176
  * The grouped count: one statement, one entry per distinct value of `column`, over exactly the
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { currentWriteOrigin, type EntityRowOp, instrument, subscribed } from '@ultimat3/core';
18
18
  import { expectedQueryLoop } from '@ultimat3/db';
19
+ import { copyColumns } from './copy-plan';
19
20
  import type { EntityCore } from './entity';
20
21
  import { MAX_PAGE_SIZE } from './plan';
21
22
  import { readRecorder } from './read-capture';
@@ -195,7 +196,7 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
195
196
  // The read half of failure capture (`read-capture.ts`): one check when no captured call is open.
196
197
  const read = readRecorder(name, sealed);
197
198
 
198
- return {
199
+ const observed: Repo<Row> = {
199
200
  ...repo,
200
201
 
201
202
  findById: async (id, options) => {
@@ -273,4 +274,41 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
273
274
  return rows;
274
275
  },
275
276
  };
277
+
278
+ /**
279
+ * The count-only writes report as their counterparts do. An insert's `entity.row` carries the
280
+ * stored row, so with a subscriber the call runs as its returning form and answers the length;
281
+ * with none it is the count path untouched. `updateMany` is `entity.bulk`, as `updateWhere` is.
282
+ * Each is present only where the repository has it, so the typed handle's fallback still sees
283
+ * an absence.
284
+ */
285
+ const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
286
+ if (insertAllCount !== undefined) {
287
+ observed.insertAllCount = async (rows, options) =>
288
+ subscribed(ROW)
289
+ ? (await observed.insertAll(rows, options)).length
290
+ : insertAllCount.call(repo, rows, options);
291
+ }
292
+ if (upsertAllCount !== undefined) {
293
+ observed.upsertAllCount = async (rows, args) =>
294
+ subscribed(ROW)
295
+ ? (await observed.upsertAll(rows, args)).length
296
+ : upsertAllCount.call(repo, rows, args);
297
+ }
298
+ if (copyAll !== undefined) {
299
+ observed.copyAll = async (rows, options) => {
300
+ if (!subscribed(ROW)) return copyAll.call(repo, rows, options);
301
+ // COPY's own refusal first, so a load is refused alike with or without a subscriber.
302
+ copyColumns(entity, rows as readonly RowPatch<Row>[]);
303
+ return (await observed.insertAll(rows, options)).length;
304
+ };
305
+ }
306
+ if (updateMany !== undefined) {
307
+ observed.updateMany = async (rows, options) => {
308
+ const written = await updateMany.call(repo, rows, options);
309
+ bulk('update', written, options);
310
+ return written;
311
+ };
312
+ }
313
+ return observed;
276
314
  }
@@ -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
+ >;
package/src/types.ts CHANGED
@@ -489,6 +489,9 @@ export interface IndexDef {
489
489
  * one fact that this release exists to stop.
490
490
  */
491
491
  readonly using?: IndexMethod;
492
- /** `indexes: [{ concurrently: true }]` — `true` or absent, never `false` (`IndexInit`). */
493
- readonly concurrently?: true;
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;
494
497
  }
@@ -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