@ultimat3/entity 31.8.0 → 31.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CLAUDE.md +2 -1
  2. package/README.md +78 -1
  3. package/package.json +5 -5
  4. package/src/adapter.ts +2 -2
  5. package/src/aggregate.ts +1 -1
  6. package/src/all-truncated.ts +33 -0
  7. package/src/append-only-errors.ts +2 -1
  8. package/src/append-only.ts +24 -2
  9. package/src/batch-bytes.ts +34 -0
  10. package/src/bulk-write-send.ts +38 -5
  11. package/src/bulk-write.ts +3 -0
  12. package/src/copy-plan.ts +40 -0
  13. package/src/counter-observed.ts +199 -0
  14. package/src/database.ts +4 -2
  15. package/src/declared-index-keys.ts +65 -0
  16. package/src/declared-index.ts +6 -1
  17. package/src/define-driver.ts +24 -2
  18. package/src/describe.ts +6 -0
  19. package/src/driver-counters.ts +21 -0
  20. package/src/driver-repo-reads.ts +76 -9
  21. package/src/driver-repo-writes.ts +104 -6
  22. package/src/driver-versioned-write.ts +99 -0
  23. package/src/entity-error.ts +6 -0
  24. package/src/entity-indexes.ts +118 -0
  25. package/src/entity.ts +20 -49
  26. package/src/history-purge.ts +15 -0
  27. package/src/index-def.ts +35 -0
  28. package/src/index-identity.ts +5 -0
  29. package/src/index-init.ts +13 -1
  30. package/src/index-name.ts +25 -6
  31. package/src/index.ts +19 -2
  32. package/src/latest-by-sql.ts +93 -0
  33. package/src/latest-by.ts +249 -0
  34. package/src/lock-key.ts +56 -3
  35. package/src/lock-unsupported.ts +5 -2
  36. package/src/measures.ts +157 -0
  37. package/src/memory-aggregates.ts +9 -16
  38. package/src/memory-latest-by.ts +34 -0
  39. package/src/memory-lock.ts +15 -1
  40. package/src/memory-match.ts +2 -0
  41. package/src/memory-measures.ts +75 -0
  42. package/src/memory-observed.ts +7 -1
  43. package/src/memory-repo.ts +60 -6
  44. package/src/memory-update.ts +17 -4
  45. package/src/page-bytes.ts +127 -0
  46. package/src/pg-aggregates.ts +9 -3
  47. package/src/pg-bulk-repo.ts +163 -0
  48. package/src/pg-copy.ts +87 -0
  49. package/src/pg-driver.ts +31 -72
  50. package/src/pg-latest-by.ts +57 -0
  51. package/src/pg-lock.ts +24 -4
  52. package/src/pg-measures.ts +64 -0
  53. package/src/pg-sql-aggregate.ts +9 -3
  54. package/src/pg-sql-measures.ts +102 -0
  55. package/src/pg-sql.ts +37 -6
  56. package/src/pg-update-many-sql.ts +146 -0
  57. package/src/pg-values-list.ts +55 -0
  58. package/src/pg-write-sql.ts +42 -26
  59. package/src/plan.ts +1 -56
  60. package/src/preload-ceiling.ts +73 -7
  61. package/src/preload.ts +17 -1
  62. package/src/query-write.ts +169 -0
  63. package/src/query.ts +38 -48
  64. package/src/read-aggregates.ts +87 -3
  65. package/src/registry.ts +29 -0
  66. package/src/repo.ts +74 -3
  67. package/src/row-observer.ts +68 -5
  68. package/src/sealed-repo.ts +78 -9
  69. package/src/search-mirrored-repo.ts +53 -0
  70. package/src/search-repo.ts +20 -2
  71. package/src/table-locks.ts +16 -1
  72. package/src/tenant-index.ts +84 -9
  73. package/src/text-contains.ts +53 -0
  74. package/src/type-pins.ts +9 -0
  75. package/src/types.ts +2 -22
  76. package/src/unique-constraints.ts +3 -1
  77. package/src/update-many-send.ts +97 -0
  78. package/src/update-many.ts +175 -0
  79. package/src/version-lock-errors.ts +42 -0
  80. package/src/version-lock.ts +177 -0
  81. package/src/view-repo.ts +4 -0
  82. package/src/write-where.ts +164 -0
@@ -16,10 +16,12 @@
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';
20
+ import { counterEcho, type RepoOf } from './counter-observed';
19
21
  import type { EntityCore } from './entity';
20
22
  import { MAX_PAGE_SIZE } from './plan';
21
23
  import { readRecorder } from './read-capture';
22
- import type { Repo, RepoOptions, UpsertArgs } from './repo';
24
+ import type { FilteredWriteOptions, Repo, RepoOptions, UpsertArgs } from './repo';
23
25
  import { sealedFields } from './sealed';
24
26
  import { searchMirroredRepo } from './search-mirrored-repo';
25
27
  import type { IdOf, RowPatch } from './types';
@@ -139,9 +141,17 @@ const beforeAllOf = async <Row>(
139
141
  * so an app opts in by subscribing to `entity.row` and never by choosing a different repository — the
140
142
  * rows under test are the rows the app reads, which is the whole reason `defaultDriver()` is
141
143
  * exported at all.
144
+ *
145
+ * `repoOf` reaches the parents a `countedIn` counter moves (`counter-observed.ts`): without it a
146
+ * trigger's parent write stays unreported, as before.
142
147
  */
143
- export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): Repo<Row> {
148
+ export function observedRepo<Row>(
149
+ entity: EntityCore<Row>,
150
+ driven: Repo<Row>,
151
+ repoOf?: RepoOf,
152
+ ): Repo<Row> {
144
153
  const name = entity.$name;
154
+ const counted = counterEcho(entity as EntityCore, repoOf);
145
155
  // Beneath the observer, so a searchable entity's writes reach an external index whether or not
146
156
  // anything hears `entity.row` (`search-mirrored-repo.ts`).
147
157
  const repo = searchMirroredRepo(entity, driven);
@@ -195,7 +205,7 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
195
205
  // The read half of failure capture (`read-capture.ts`): one check when no captured call is open.
196
206
  const read = readRecorder(name, sealed);
197
207
 
198
- return {
208
+ const observed: Repo<Row> = {
199
209
  ...repo,
200
210
 
201
211
  findById: async (id, options) => {
@@ -213,12 +223,17 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
213
223
  insert: async (values: Row, options?: RepoOptions): Promise<Row> => {
214
224
  const stored = await repo.insert(values, options);
215
225
  emit('insert', null, stored, options);
226
+ await counted?.rows([[null, stored]], options);
216
227
  return stored;
217
228
  },
218
229
 
219
230
  insertAll: async (rows: readonly Row[], options?: RepoOptions): Promise<readonly Row[]> => {
220
231
  const stored = await repo.insertAll(rows, options);
221
232
  for (const row of stored) emit('insert', null, row, options);
233
+ await counted?.rows(
234
+ stored.map((row) => [null, row] as const),
235
+ options,
236
+ );
222
237
  return stored;
223
238
  },
224
239
 
@@ -234,11 +249,14 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
234
249
  const ids = [...new Set(rows.flatMap((row) => idOf(row) ?? []))];
235
250
  const before = await beforeAllOf(entity, repo, ids);
236
251
  const stored = await repo.upsertAll(rows, args);
252
+ const changes: (readonly [unknown, unknown])[] = [];
237
253
  for (const row of stored) {
238
254
  const id = idOf(row);
239
255
  const previous = id === undefined ? null : (before.get(id) ?? null);
240
256
  emit(previous === null ? 'insert' : 'update', previous, row, args);
257
+ changes.push([previous, row]);
241
258
  }
259
+ await counted?.rows(changes, args);
242
260
  return stored;
243
261
  },
244
262
 
@@ -247,6 +265,7 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
247
265
  const before = await beforeOf(entity, repo, id);
248
266
  const after = await repo.update(id, patch, options);
249
267
  emit('update', before, after, options);
268
+ await counted?.rows([[before, after]], options);
250
269
  return after;
251
270
  },
252
271
 
@@ -255,22 +274,66 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
255
274
  const before = await beforeOf(entity, repo, id);
256
275
  await repo.delete(id, options);
257
276
  emit('delete', before, null, options);
277
+ await counted?.rows([[before, null]], options);
258
278
  },
259
279
 
260
- deleteWhere: async (filter: RowPatch<Row>, options?: RepoOptions): Promise<number> => {
280
+ deleteWhere: async (filter: RowPatch<Row>, options?: FilteredWriteOptions): Promise<number> => {
261
281
  const rows = await repo.deleteWhere(filter, options);
262
282
  bulk('delete', rows, options);
283
+ await counted?.filtered(asRecord(filter), null, rows, options);
263
284
  return rows;
264
285
  },
265
286
 
266
287
  updateWhere: async (
267
288
  filter: RowPatch<Row>,
268
289
  patch: RowPatch<Row>,
269
- options?: RepoOptions,
290
+ options?: FilteredWriteOptions,
270
291
  ): Promise<number> => {
271
292
  const rows = await repo.updateWhere(filter, patch, options);
272
293
  bulk('update', rows, options);
294
+ await counted?.filtered(asRecord(filter), asRecord(patch) ?? {}, rows, options);
273
295
  return rows;
274
296
  },
275
297
  };
298
+
299
+ /**
300
+ * The count-only writes report as their counterparts do. An insert's `entity.row` carries the
301
+ * stored row, so with a subscriber the call runs as its returning form and answers the length;
302
+ * with none it is the count path untouched. `updateMany` is `entity.bulk`, as `updateWhere` is.
303
+ * Each is present only where the repository has it, so the typed handle's fallback still sees
304
+ * an absence.
305
+ */
306
+ const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
307
+ if (insertAllCount !== undefined) {
308
+ observed.insertAllCount = async (rows, options) =>
309
+ subscribed(ROW)
310
+ ? (await observed.insertAll(rows, options)).length
311
+ : insertAllCount.call(repo, rows, options);
312
+ }
313
+ if (upsertAllCount !== undefined) {
314
+ observed.upsertAllCount = async (rows, args) =>
315
+ subscribed(ROW)
316
+ ? (await observed.upsertAll(rows, args)).length
317
+ : upsertAllCount.call(repo, rows, args);
318
+ }
319
+ if (copyAll !== undefined) {
320
+ observed.copyAll = async (rows, options) => {
321
+ if (!subscribed(ROW)) return copyAll.call(repo, rows, options);
322
+ // COPY's own refusal first, so a load is refused alike with or without a subscriber.
323
+ copyColumns(entity, rows as readonly RowPatch<Row>[]);
324
+ return (await observed.insertAll(rows, options)).length;
325
+ };
326
+ }
327
+ if (updateMany !== undefined) {
328
+ observed.updateMany = async (rows, options) => {
329
+ const written = await updateMany.call(repo, rows, options);
330
+ bulk('update', written, options);
331
+ // Each patch names the same columns, so the first says whether a counter moved; which
332
+ // parents it moved, no filter says — a count.
333
+ const patch = asRecord(rows[0]?.patch);
334
+ if (patch !== null) await counted?.filtered(null, patch, written, options);
335
+ return written;
336
+ };
337
+ }
338
+ return observed;
276
339
  }
@@ -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,24 +212,30 @@ 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) {
221
231
  return repo.count(await readArgs(entity, fields, args, sealKeysOnce()));
222
232
  },
223
- async countBy(column, args) {
233
+ async countBy(column, args, options) {
224
234
  refuseNamed(entity, fields, [column], 'a grouped count');
225
- return repo.countBy(column, await readArgs(entity, fields, args, sealKeysOnce()));
235
+ // A filter inside the aggregate is evaluated by the database too: no sealed column in it.
236
+ const filtered = (options?.where ?? []).map((one) => one.column);
237
+ refuseNamed(entity, fields, filtered, 'a grouped count');
238
+ return repo.countBy(column, await readArgs(entity, fields, args, sealKeysOnce()), options);
226
239
  },
227
240
  async aggregate(fn: AggregateFn, column, args) {
228
241
  refuseNamed(entity, fields, [column], 'an aggregate');
@@ -232,6 +245,62 @@ export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo:
232
245
  return repo.approximateCount(await readArgs(entity, fields, args, sealKeysOnce()));
233
246
  },
234
247
  };
248
+ // The count-only and bulk writes: sealed exactly as their counterparts above, and present only
249
+ // where the inner repository has them, so the typed handle's fallback still sees an absence.
250
+ const sealAll = <T>(rows: readonly T[], keys: SealKeys): Promise<T[]> =>
251
+ Promise.all(rows.map((row) => sealRow(entity, fields, row, keys, true)));
252
+ const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
253
+ if (insertAllCount !== undefined) {
254
+ sealing.insertAllCount = async (rows, options) =>
255
+ insertAllCount.call(repo, await sealAll(rows, sealKeysOnce()), options);
256
+ }
257
+ if (upsertAllCount !== undefined) {
258
+ sealing.upsertAllCount = async (rows, args) => {
259
+ refuseNamed(entity, fields, args.onConflict, 'an upsert conflict target', true);
260
+ return upsertAllCount.call(repo, await sealAll(rows, sealKeysOnce()), args);
261
+ };
262
+ }
263
+ if (copyAll !== undefined) {
264
+ sealing.copyAll = async (rows, options) =>
265
+ copyAll.call(repo, await sealAll(rows, sealKeysOnce()), options);
266
+ }
267
+ if (updateMany !== undefined) {
268
+ sealing.updateMany = async (rows, options) => {
269
+ const keys = sealKeysOnce();
270
+ const sealed = await Promise.all(
271
+ rows.map(async ({ id, patch }) => ({
272
+ id,
273
+ patch: await sealRow(entity, fields, patch, keys),
274
+ })),
275
+ );
276
+ return updateMany.call(repo, sealed, options);
277
+ };
278
+ }
279
+ // Every measure's column and every column its filter names is evaluated over ciphertext.
280
+ const aggregates = repo.aggregates?.bind(repo);
281
+ if (aggregates !== undefined) {
282
+ sealing.aggregates = async (measures, args) => {
283
+ const named = Object.values(measures).flatMap((measure) => [
284
+ ...(measure.column === undefined ? [] : [measure.column]),
285
+ ...(measure.where ?? []).map((one) => one.column),
286
+ ]);
287
+ refuseNamed(entity, fields, named, 'an aggregate');
288
+ return aggregates(measures, await readArgs(entity, fields, args, sealKeysOnce()));
289
+ };
290
+ }
291
+ // A read: its rows open exactly as `findMany`'s, and a group or an order is never sealed.
292
+ const latestBy = repo.latestBy?.bind(repo);
293
+ if (latestBy !== undefined) {
294
+ sealing.latestBy = async (spec, args) => {
295
+ refuseNamed(entity, fields, [spec.group, ...spec.order.map((key) => key.column)], 'an order');
296
+ const keys = sealKeysOnce();
297
+ return openRows(
298
+ fields,
299
+ await latestBy(spec, await readArgs(entity, fields, args, keys)),
300
+ keys,
301
+ );
302
+ };
303
+ }
235
304
  // A bucket is an instant and a sum is arithmetic: neither has a meaning over ciphertext.
236
305
  const series = repo.series?.bind(repo);
237
306
  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) =>
@@ -86,17 +86,35 @@ const searching = (args: FindManyArgs | undefined): boolean => args?.where?.some
86
86
  export const searchedRepo = <Row>(entity: EntityCore<Row>, repo: Repo<Row>): Repo<Row> => {
87
87
  const core = entity as EntityCore<unknown>;
88
88
  const series = repo.series;
89
+ const aggregates = repo.aggregates;
90
+ const latestBy = repo.latestBy;
89
91
  return {
90
92
  ...repo,
91
93
  findMany: async (args) =>
92
94
  repo.findMany(searching(args) ? await resolved(core, args ?? {}) : args),
93
95
  count: async (args) => repo.count(searching(args) ? await resolved(core, args ?? {}) : args),
94
- countBy: async (column, args) =>
95
- repo.countBy(column, searching(args) ? await resolved(core, args ?? {}) : args),
96
+ countBy: async (column, args, options) =>
97
+ repo.countBy(column, searching(args) ? await resolved(core, args ?? {}) : args, options),
96
98
  aggregate: async (fn, column, args) =>
97
99
  repo.aggregate(fn, column, searching(args) ? await resolved(core, args ?? {}) : args),
98
100
  approximateCount: async (args) =>
99
101
  repo.approximateCount(searching(args) ? await resolved(core, args ?? {}) : args),
102
+ ...(aggregates === undefined
103
+ ? {}
104
+ : {
105
+ aggregates: async (measures, args) =>
106
+ aggregates.call(
107
+ repo,
108
+ measures,
109
+ searching(args) ? await resolved(core, args ?? {}) : args,
110
+ ),
111
+ }),
112
+ ...(latestBy === undefined
113
+ ? {}
114
+ : {
115
+ latestBy: async (spec, args) =>
116
+ latestBy.call(repo, spec, searching(args) ? await resolved(core, args ?? {}) : args),
117
+ }),
100
118
  ...(series === undefined
101
119
  ? {}
102
120
  : {
@@ -1,4 +1,4 @@
1
- // Single responsibility: `lock` and `lockKey` on the typed handle. The refusal lives here because
1
+ // Single responsibility: `lock`, `lockKey` and `lockKeys` on the typed handle. The refusal lives here because
2
2
  // the repository contract lets a hand-written driver omit both, so only this layer can say so.
3
3
 
4
4
  import { lockUnsupported } from './lock-unsupported';
@@ -23,6 +23,17 @@ export interface TableLocks<Row> {
23
23
  * A's key never blocks org B. On a tenant-scoped entity with no actor it is `X_TENANCY_UNSCOPED`.
24
24
  */
25
25
  lockKey<R>(key: string, fn: (tx: Tx) => Promise<R> | R, options?: RepoOptions): Promise<R>;
26
+ /**
27
+ * `lockKey` over several keys, for work that spans them — a transfer between two accounts:
28
+ * `db.accounts.lockKeys(['acct:' + from, 'acct:' + to], (tx) => …)`. Every key held for `fn`, in
29
+ * ONE transaction, taken in sorted order so two callers naming them in any order never deadlock.
30
+ * Same table, tenant and hashing as `lockKey`; an empty list and more than 64 keys are refused.
31
+ */
32
+ lockKeys<R>(
33
+ keys: readonly string[],
34
+ fn: (tx: Tx) => Promise<R> | R,
35
+ options?: RepoOptions,
36
+ ): Promise<R>;
26
37
  }
27
38
 
28
39
  /** Called as methods and refused in an `async` body, so a class-shaped driver keeps its `this`. */
@@ -38,4 +49,8 @@ export const tableLocks = <Row>(
38
49
  if (repo.lockKey === undefined) throw lockUnsupported(entity.$name, 'lockKey');
39
50
  return repo.lockKey(key, fn, options);
40
51
  },
52
+ lockKeys: async (keys, fn, options) => {
53
+ if (repo.lockKeys === undefined) throw lockUnsupported(entity.$name, 'lockKeys');
54
+ return repo.lockKeys(keys, fn, options);
55
+ },
41
56
  });
@@ -1,9 +1,10 @@
1
- // The one index every tenant table needs and nobody declares: `(tenant, primary key)`, the exact
2
- // shape of every scoped read — `where org_id = $1 order by id` — whether the tenant column was
3
- // marked `.tenant()`, named by `tenant:` or inferred from `orgId`.
1
+ // The indexes nobody declares, and the ONE rule for when one is already served: `(tenant, primary
2
+ // key)` — the shape of every scoped read, `where org_id = $1 order by id` — and each column's own
3
+ // index (`.references()`, `.index()`), which another index leading with that column makes a second
4
+ // copy every write pays for (`coveringIndexOf`, E9).
4
5
 
5
6
  import { indexName } from './index-name';
6
- import type { ReferenceDescription, RegistryEntry } from './registry';
7
+ import type { CoveredIndex, ReferenceDescription, RegistryEntry } from './registry';
7
8
  import { registeredEntities, registryGeneration } from './registry';
8
9
  import type { IndexDef } from './types';
9
10
 
@@ -17,14 +18,88 @@ export interface TenantIndexInput {
17
18
  /** A plain (non-materialized) view holds no index at all. */
18
19
  readonly plainView: boolean;
19
20
  /**
20
- * The column lists of every non-partial btree index and unique constraint the table already
21
- * declares. One that STARTS with `(tenant, pk…)` serves the scoped read already.
21
+ * Every index the table already has that can serve a prefix (`coverersOf`). One that STARTS
22
+ * with `(tenant, pk…)` serves the scoped read already.
22
23
  */
23
- readonly covering: readonly (readonly string[])[];
24
+ readonly covering: readonly IndexCoverer[];
25
+ }
26
+
27
+ /** An index whose leading key columns can serve a lookup: a name to report, physical columns. */
28
+ export interface IndexCoverer {
29
+ readonly name: string;
30
+ readonly columns: readonly string[];
31
+ }
32
+
33
+ /** What `coverersOf` reads off a declared index — structural, so every index shape fits. */
34
+ interface PrefixCandidate {
35
+ readonly name: string;
36
+ readonly columns: readonly string[];
37
+ readonly where?: string | undefined;
38
+ readonly using?: string | undefined;
39
+ readonly expression?: string | undefined;
40
+ readonly operatorClass?: string | undefined;
24
41
  }
25
42
 
26
43
  const startsWith = (list: readonly string[], prefix: readonly string[]): boolean =>
27
- prefix.length <= list.length && prefix.every((column, at) => list[at] === column);
44
+ prefix.length > 0 &&
45
+ prefix.length <= list.length &&
46
+ prefix.every((column, at) => list[at] === column);
47
+
48
+ /**
49
+ * THE covering rule, the one every implicit index is judged by: the first coverer whose key
50
+ * columns START with `columns`. A btree serves an equality on any leading prefix of its keys, so
51
+ * `(a)` beside `(a, b)` is the same lookup kept twice. Direction is irrelevant to that equality.
52
+ */
53
+ export const coveringIndexOf = (
54
+ columns: readonly string[],
55
+ coverers: readonly IndexCoverer[],
56
+ ): IndexCoverer | undefined => coverers.find((coverer) => startsWith(coverer.columns, columns));
57
+
58
+ /**
59
+ * The indexes that can serve a prefix: the primary key (Postgres names it `<table>_pkey`), every
60
+ * total btree keyed on plain columns, and every total unique invariant. A partial index misses
61
+ * the rows its predicate excludes; a gin, an expression key or an operator class answers other
62
+ * questions than `col = $1`.
63
+ */
64
+ export const coverersOf = (
65
+ table: string,
66
+ primaryKey: readonly string[],
67
+ indexes: readonly PrefixCandidate[],
68
+ uniques: readonly {
69
+ readonly name: string;
70
+ readonly columns: readonly string[];
71
+ readonly where?: string | undefined;
72
+ }[],
73
+ ): readonly IndexCoverer[] => [
74
+ { name: `${table}_pkey`, columns: primaryKey },
75
+ ...indexes.filter(
76
+ (index) =>
77
+ index.where == null &&
78
+ (index.using === undefined || index.using === 'btree') &&
79
+ index.expression === undefined &&
80
+ index.operatorClass === undefined,
81
+ ),
82
+ ...uniques.filter((unique) => unique.where == null),
83
+ ];
84
+
85
+ /**
86
+ * Each implicit index another index already leads with, and which one. LISTED, never removed: on
87
+ * `main` an existing app's description must keep it, or its next `x db gen` drops an index the
88
+ * database holds (`index-plan.ts` `removeUndeclared`). The consumers report and drop on request.
89
+ */
90
+ export const coveredImplicitIndexes = (
91
+ implicit: readonly IndexCoverer[],
92
+ coverers: readonly IndexCoverer[],
93
+ ): readonly CoveredIndex[] =>
94
+ implicit.flatMap((index) => {
95
+ const by = coveringIndexOf(
96
+ index.columns,
97
+ coverers.filter((coverer) => coverer.name !== index.name),
98
+ );
99
+ return by === undefined
100
+ ? []
101
+ : [{ name: index.name, columns: index.columns, coveredBy: by.name }];
102
+ });
28
103
 
29
104
  /**
30
105
  * Zero or one index. Measured at 500k rows / 1,000 tenants: a tenant page took 43.7 ms with no
@@ -42,7 +117,7 @@ export const tenantIndexOf = (input: TenantIndexInput): readonly IndexDef[] => {
42
117
  const [leadingColumn] = primaryKey;
43
118
  if (tenant === null || input.plainView || leadingColumn === tenant) return [];
44
119
  const columns = [tenant, ...primaryKey.filter((column) => column !== tenant)];
45
- if (input.covering.some((list) => startsWith(list, columns))) return [];
120
+ if (coveringIndexOf(columns, input.covering) !== undefined) return [];
46
121
  return [
47
122
  {
48
123
  name: indexName(input.entityName, input.table, columns, false),
@@ -0,0 +1,53 @@
1
+ // Single responsibility: what `contains` means on a `text()`/`char()` column — a case-insensitive
2
+ // substring, compiled to the bound `ilike` a `gin_trgm_ops` index serves and answered identically in
3
+ // memory. `contains` on `jsonb`/`arrayOf()` stays structural containment (`containment.ts`): the
4
+ // operator is decided by the column's declared kind, the rule `memory-match.ts` already reads.
5
+
6
+ import { type SqlFragment, sql } from '@ultimat3/db';
7
+ import type { ColumnKind } from './types';
8
+
9
+ /** The kinds whose `contains` is a substring. Every other kind keeps `@>`. */
10
+ const TEXT_KINDS: ReadonlySet<ColumnKind | undefined> = new Set<ColumnKind | undefined>([
11
+ 'text',
12
+ 'char',
13
+ ]);
14
+
15
+ export const isTextContains = (kind: ColumnKind | undefined): boolean => TEXT_KINDS.has(kind);
16
+
17
+ /**
18
+ * The term as an `ilike` pattern that finds it anywhere: the escape character first (so the
19
+ * escapes added after it are not doubled), then both wildcards — a `%` typed into a search box is a
20
+ * percent sign to find, never "anything". Postgres' default escape is the backslash, so no
21
+ * `escape` clause is written and the planner still matches the trigram operator class.
22
+ */
23
+ export const containsPattern = (term: string): string =>
24
+ `%${term.replaceAll('\\', '\\\\').replaceAll('%', '\\%').replaceAll('_', '\\_')}%`;
25
+
26
+ /** Nothing matches: a non-text operand bound as its `String()` would find `"5"` or `"null"`. */
27
+ const NEVER = sql`1 = 0`;
28
+
29
+ /**
30
+ * `col ilike $n`. `ilike` and not `lower(col) like lower($n)`: `gin_trgm_ops` serves `ilike` on the
31
+ * bare column, while `lower(col)` is an expression no column index can match.
32
+ */
33
+ export const textContainsSql = (column: SqlFragment, term: unknown): SqlFragment =>
34
+ typeof term === 'string' ? sql`${column} ilike ${containsPattern(term)}` : NEVER;
35
+
36
+ /**
37
+ * The memory driver's answer: both sides lower-cased, then a substring test — what the escaped
38
+ * `ilike` pattern matches. Case folding is JS's Unicode `toLowerCase`; Postgres folds through the
39
+ * database's collation, which agrees on every cased letter outside the locale-specific few
40
+ * (Turkish dotted I).
41
+ */
42
+ export const textContainsMatches = (actual: unknown, term: unknown): boolean =>
43
+ typeof actual === 'string' &&
44
+ typeof term === 'string' &&
45
+ actual.toLowerCase().includes(term.toLowerCase());
46
+
47
+ /**
48
+ * The `indexes:` entry that serves `contains` on `property` — `@ultimat3/db`'s spelling
49
+ * (`index-key-ddl.ts`), so the plan sweep's `X_QUERY_UNINDEXED` fix names a declaration that
50
+ * renders, and `x db gen` creates `pg_trgm` before it.
51
+ */
52
+ export const trigramDeclaration = (property: string): string =>
53
+ `indexes: [{ on: ['${property}'], using: 'gin', operatorClass: 'gin_trgm_ops' }]`;
package/src/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
@@ -6,7 +6,6 @@
6
6
  // A column carries its TypeScript type in `$parse`, which is what lets the row type be derived
7
7
  // from the column set instead of being written a second time as a hand-maintained schema.
8
8
 
9
- import type { IndexMethod } from '@ultimat3/db';
10
9
  import type { PersonalDataKind } from './personal-data-kind';
11
10
 
12
11
  /**
@@ -474,24 +473,5 @@ export type RowPatch<Row> = {
474
473
  readonly [K in keyof Row]?: Row[K] | InputOf<Row[K]> | undefined;
475
474
  };
476
475
 
477
- export interface IndexDef {
478
- readonly name: string;
479
- readonly columns: readonly string[];
480
- readonly unique: boolean;
481
- readonly order?: 'asc' | 'desc';
482
- /** Partial index predicate — a soft-deleted row is excluded with this. */
483
- readonly where?: string;
484
- /**
485
- * The access method. Absent is `btree`, which is Postgres' own default and what every index
486
- * declared before this field existed is — so an entity that names none emits the statement it
487
- * always emitted, byte for byte, and no app's sidecar regenerates. `@ultimat3/db` owns the
488
- * closed set (`INDEX_METHODS`); redeclaring the union here would be the second declaration of
489
- * one fact that this release exists to stop.
490
- */
491
- readonly using?: IndexMethod;
492
- /**
493
- * How it is built (`IndexInit`). Absent is the default: concurrently on a table that already
494
- * exists. `false` is the opt-out, a plain build `x db gen` marks `-- lock-heavy: true`.
495
- */
496
- readonly concurrently?: boolean;
497
- }
476
+ // A declared index is its own vocabulary (`index-def.ts`); re-exported so a column import stays one.
477
+ export type { IndexDef } from './index-def';
@@ -25,7 +25,9 @@ export interface UniqueConstraint {
25
25
  */
26
26
  export const uniqueConstraints = <Row>(entity: EntityCore<Row>): readonly UniqueConstraint[] => [
27
27
  ...entity.$indexes
28
- .filter((index) => index.unique && index.where === undefined)
28
+ // An expression key is excluded too: `on conflict (email)` cannot infer `unique(lower(email))`
29
+ // (42P10), and the memory driver cannot evaluate the expression — the partial index's reason.
30
+ .filter((index) => index.unique && index.where === undefined && index.expression === undefined)
29
31
  .map((index) => ({ columns: index.columns, name: () => index.name })),
30
32
  ...entity.$invariants
31
33
  .filter((rule) => rule.kind === 'unique' && rule.where === undefined)