@ultimat3/entity 31.9.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 (69) hide show
  1. package/CLAUDE.md +1 -0
  2. package/README.md +48 -0
  3. package/package.json +5 -5
  4. package/src/aggregate.ts +1 -1
  5. package/src/all-truncated.ts +33 -0
  6. package/src/append-only.ts +8 -1
  7. package/src/bulk-write.ts +3 -0
  8. package/src/counter-observed.ts +199 -0
  9. package/src/database.ts +4 -2
  10. package/src/declared-index-keys.ts +65 -0
  11. package/src/declared-index.ts +6 -1
  12. package/src/define-driver.ts +24 -2
  13. package/src/describe.ts +6 -0
  14. package/src/driver-counters.ts +21 -0
  15. package/src/driver-repo-reads.ts +71 -5
  16. package/src/driver-repo-writes.ts +23 -1
  17. package/src/driver-versioned-write.ts +99 -0
  18. package/src/entity-error.ts +4 -0
  19. package/src/entity-indexes.ts +118 -0
  20. package/src/entity.ts +20 -49
  21. package/src/history-purge.ts +15 -0
  22. package/src/index-def.ts +35 -0
  23. package/src/index-identity.ts +5 -0
  24. package/src/index-init.ts +13 -1
  25. package/src/index-name.ts +25 -6
  26. package/src/index.ts +13 -0
  27. package/src/latest-by-sql.ts +93 -0
  28. package/src/latest-by.ts +249 -0
  29. package/src/lock-key.ts +56 -3
  30. package/src/lock-unsupported.ts +5 -2
  31. package/src/measures.ts +157 -0
  32. package/src/memory-aggregates.ts +9 -16
  33. package/src/memory-latest-by.ts +34 -0
  34. package/src/memory-lock.ts +15 -1
  35. package/src/memory-match.ts +2 -0
  36. package/src/memory-measures.ts +75 -0
  37. package/src/memory-observed.ts +3 -1
  38. package/src/memory-repo.ts +17 -1
  39. package/src/memory-update.ts +7 -1
  40. package/src/pg-aggregates.ts +9 -3
  41. package/src/pg-bulk-repo.ts +1 -1
  42. package/src/pg-driver.ts +13 -1
  43. package/src/pg-latest-by.ts +57 -0
  44. package/src/pg-lock.ts +24 -4
  45. package/src/pg-measures.ts +64 -0
  46. package/src/pg-sql-aggregate.ts +9 -3
  47. package/src/pg-sql-measures.ts +102 -0
  48. package/src/pg-sql.ts +37 -6
  49. package/src/pg-update-many-sql.ts +44 -1
  50. package/src/pg-write-sql.ts +32 -4
  51. package/src/preload-ceiling.ts +73 -7
  52. package/src/preload.ts +17 -1
  53. package/src/query.ts +14 -1
  54. package/src/read-aggregates.ts +87 -3
  55. package/src/registry.ts +29 -0
  56. package/src/repo.ts +34 -1
  57. package/src/row-observer.ts +29 -4
  58. package/src/sealed-repo.ts +30 -2
  59. package/src/search-repo.ts +20 -2
  60. package/src/table-locks.ts +16 -1
  61. package/src/tenant-index.ts +84 -9
  62. package/src/text-contains.ts +53 -0
  63. package/src/types.ts +2 -22
  64. package/src/unique-constraints.ts +3 -1
  65. package/src/update-many-send.ts +32 -1
  66. package/src/update-many.ts +6 -1
  67. package/src/version-lock-errors.ts +42 -0
  68. package/src/version-lock.ts +177 -0
  69. package/src/write-where.ts +3 -0
@@ -3,6 +3,9 @@
3
3
  // Split from `query.ts` at its line ceiling; the chain's arguments arrive as `args()`, so every
4
4
  // terminal here counts exactly the rows `count()` counts.
5
5
 
6
+ import type { CountByOptions, Measure, MeasureFn, MeasureMap, MeasureReads } from './measures';
7
+ import { measuresUnsupported } from './measures';
8
+ import { checkedPredicate, type Operator } from './operator';
6
9
  import type { Repo } from './repo';
7
10
  import { seriesUnsupported } from './series-unsupported';
8
11
  import type { SeriesPoint, SeriesUnit, SeriesValue } from './time-bucket';
@@ -24,6 +27,36 @@ export type SeriesValueOf<Row, V> = V extends 'count'
24
27
  ? (Row[K] extends MoneyValue | null ? MoneyValue : string) | null
25
28
  : never;
26
29
 
30
+ /**
31
+ * One filter of a measure: `andWhere`'s three arguments, as a tuple. `S` is carried for the
32
+ * signature's sake only: excluding opaque columns inside `aggregate`'s generic constraint makes a
33
+ * sealed chain incomparable with an unsealed one (`tableFor`'s one cast), so a sealed column here is
34
+ * refused at RUNTIME, by `sealed-repo.ts`, as an `andWhere` built from a string is.
35
+ */
36
+ export type MeasureFilter<Row, _S extends SealedKeySet = NoSealedKeys> = readonly [
37
+ column: keyof Row & string,
38
+ op: Operator,
39
+ value?: unknown,
40
+ ];
41
+
42
+ /** One output of `aggregate({ name: measure })`, typed by the row. */
43
+ export interface ChainMeasure<Row, S extends SealedKeySet = NoSealedKeys> {
44
+ readonly fn: MeasureFn;
45
+ readonly column?: Exclude<keyof Row & string, S['sealed']>;
46
+ readonly where?: readonly MeasureFilter<Row, S>[];
47
+ }
48
+
49
+ /** What one measure answers: a count is a number, the rest what `sum`/`avg`/`min`/`max` answer. */
50
+ export type MeasureValueOf<Row, M> = M extends { readonly fn: 'count' }
51
+ ? number
52
+ : M extends { readonly fn: 'avg' }
53
+ ? string | null
54
+ : M extends { readonly fn: 'sum'; readonly column: infer K extends keyof Row }
55
+ ? (Row[K] extends MoneyValue | null ? MoneyValue : string) | null
56
+ : M extends { readonly fn: 'min' | 'max'; readonly column: infer K extends keyof Row }
57
+ ? Row[K] | null
58
+ : never;
59
+
27
60
  /** `ReadBuilder.series`'s argument. `timeZone` is required: there is no ambient zone. */
28
61
  export interface SeriesOptions<On, V> {
29
62
  readonly on: On;
@@ -49,7 +82,24 @@ export interface ReadAggregates<Row, S extends SealedKeySet = NoSealedKeys> {
49
82
  */
50
83
  countBy<K extends Exclude<keyof Row & string, S['sealed']>>(
51
84
  column: K,
85
+ options?: { readonly where?: readonly MeasureFilter<Row, S>[] },
52
86
  ): Promise<ReadonlyMap<Row[K], number>>;
87
+ /**
88
+ * Several measures over the chain's rows in ONE statement, each with its own filter — the
89
+ * dashboard tile a `count()` per status is the N+1 of:
90
+ * `orders.where({ orgId }).aggregate({ all: { fn: 'count' }, paid: { fn: 'count', where:
91
+ * [['status', 'eq', 'paid']] }, revenue: { fn: 'sum', column: 'total' } })`.
92
+ *
93
+ * Each `where` is `count(*) filter (where …)`: it narrows that measure only, inside the rows
94
+ * `count()` would count (filters, tenancy, soft delete). A `count` answers a number (0 over no
95
+ * rows); every other measure answers exactly what `sum`/`avg`/`min`/`max` answer, `null` over
96
+ * none. Refused as they are: a kind with no aggregate, avg over money, a mixed currency.
97
+ * `countBy(col, { where })` is the grouped form: a group none of whose rows satisfy `where` is
98
+ * present with 0, which is what tells it from `andWhere(…).countBy(col)`.
99
+ */
100
+ aggregate<M extends Readonly<Record<string, ChainMeasure<Row, S>>>>(
101
+ measures: M,
102
+ ): Promise<{ readonly [N in keyof M]: MeasureValueOf<Row, M[N]> }>;
53
103
  /**
54
104
  * The four SQL aggregates, over exactly the rows `count()` counts — the chain's filters, its
55
105
  * tenancy and its soft-delete visibility, never its page. "Total spend this month" is
@@ -104,7 +154,20 @@ export interface ReadAggregates<Row, S extends SealedKeySet = NoSealedKeys> {
104
154
  }
105
155
 
106
156
  /** The members of `Repo` these read, none of which names the row — so any repository fits. */
107
- type AggregateRepo = Pick<Repo<unknown>, 'aggregate' | 'approximateCount' | 'countBy' | 'series'>;
157
+ type AggregateRepo = Pick<Repo<unknown>, 'aggregate' | 'approximateCount' | 'series'> & {
158
+ countBy(
159
+ column: string,
160
+ args?: Parameters<Repo['count']>[0],
161
+ options?: CountByOptions,
162
+ ): Promise<ReadonlyMap<unknown, number>>;
163
+ readonly aggregates?: MeasureReads['aggregates'];
164
+ };
165
+
166
+ /** A chain's tuples as the repository's predicates, each refused on the line that wrote it. */
167
+ const predicatesOf = (
168
+ entityName: string,
169
+ where: readonly (readonly [string, Operator, unknown?])[] | undefined,
170
+ ) => (where ?? []).map(([column, op, value]) => checkedPredicate(entityName, column, op, value));
108
171
 
109
172
  export const readAggregates = <Row, S extends SealedKeySet>(
110
173
  entity: { readonly $name: string },
@@ -127,8 +190,29 @@ export const readAggregates = <Row, S extends SealedKeySet>(
127
190
 
128
191
  approximateCount: () => repo.approximateCount(args()),
129
192
 
130
- countBy: async <K extends keyof Row & string>(column: K) =>
131
- (await repo.countBy(column, args())) as ReadonlyMap<Row[K], number>,
193
+ countBy: async <K extends keyof Row & string>(
194
+ column: K,
195
+ options?: { readonly where?: readonly MeasureFilter<Row, S>[] },
196
+ ) =>
197
+ (await repo.countBy(
198
+ column,
199
+ args(),
200
+ options?.where === undefined ? {} : { where: predicatesOf(entity.$name, options.where) },
201
+ )) as ReadonlyMap<Row[K], number>,
202
+
203
+ aggregate: async <M extends Readonly<Record<string, ChainMeasure<Row, S>>>>(measures: M) => {
204
+ if (repo.aggregates === undefined) throw measuresUnsupported(entity.$name);
205
+ const plain: Record<string, Measure> = {};
206
+ for (const [name, measure] of Object.entries(measures)) {
207
+ const { where, ...rest } = measure;
208
+ plain[name] =
209
+ where === undefined ? rest : { ...rest, where: predicatesOf(entity.$name, where) };
210
+ }
211
+ // The same seam `sum` has: the repository is row-agnostic, the chain knows the measures.
212
+ return (await repo.aggregates(plain as MeasureMap, args())) as {
213
+ readonly [N in keyof M]: MeasureValueOf<Row, M[N]>;
214
+ };
215
+ },
132
216
 
133
217
  series: async <On extends TimestampKeys<Row, S>, V>(spec: SeriesOptions<On, V>) => {
134
218
  if (repo.series === undefined) throw seriesUnsupported(entity.$name);
package/src/registry.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  CounterDescriptionLike,
8
8
  HistoryDescriptionLike,
9
9
  IndexMethod,
10
+ IndexOperatorClass,
10
11
  RetainDescriptionLike,
11
12
  } from '@ultimat3/db';
12
13
  import type { EntityCore } from './entity';
@@ -143,6 +144,18 @@ export interface IndexDescription {
143
144
  * default (concurrently on an existing table), so an entity that never asked hashes as before.
144
145
  */
145
146
  readonly concurrently?: boolean | undefined;
147
+ /**
148
+ * The four key parts (E8), each absent unless the entity declared it, for `using`'s reason: a
149
+ * description written before them hashes and records as it did. `IndexDescriptionLike` in
150
+ * `@ultimat3/db` is the reader. `expression` is the ONE key; `columns` names what it reads.
151
+ */
152
+ readonly expression?: string | undefined;
153
+ /** A direction per key, in key order; `null` writes none. Never beside `order`. */
154
+ readonly orders?: readonly ('asc' | 'desc' | null)[] | undefined;
155
+ /** INCLUDE payload columns, physical. */
156
+ readonly include?: readonly string[] | undefined;
157
+ /** An operator class on every key — `gin_trgm_ops`, on a gin index. */
158
+ readonly operatorClass?: IndexOperatorClass | undefined;
146
159
  }
147
160
 
148
161
  export interface EntityDescription {
@@ -183,9 +196,25 @@ export interface EntityDescription {
183
196
  readonly partition?: PartitionDescription;
184
197
  }
185
198
 
199
+ /**
200
+ * An index the framework adds unasked (a column's own, from `.references()` or `.index()`) that
201
+ * another index already leads with (`coveringIndexOf`, `tenant-index.ts`): every write pays for it
202
+ * twice. On `RegistryEntry` and NOT in `EntityDescription`: the description is what `x verify`
203
+ * hashes and what `x db gen` diffs, and removing the index there drops it from every existing app.
204
+ */
205
+ export interface CoveredIndex {
206
+ readonly name: string;
207
+ /** Physical columns, in index order. */
208
+ readonly columns: readonly string[];
209
+ /** The index (or `<table>_pkey`, or the unique invariant's name) that already leads with them. */
210
+ readonly coveredBy: string;
211
+ }
212
+
186
213
  export interface RegistryEntry {
187
214
  readonly name: string;
188
215
  readonly tableName: string;
216
+ /** Implicit indexes another one already serves; absent or empty when there are none. */
217
+ readonly coveredIndexes?: readonly CoveredIndex[];
189
218
  /** `entity(name, { persist: true })` — the client keeps this type on disk. Absent = `false`. */
190
219
  readonly persist?: boolean;
191
220
  /** The entity's client projection — what a changefeed's table maps to on the client. */
package/src/repo.ts CHANGED
@@ -9,6 +9,8 @@
9
9
 
10
10
  import type { Page } from '@ultimat3/core';
11
11
  import type { AggregateFn } from './aggregate';
12
+ import type { LatestBySpec } from './latest-by';
13
+ import type { CountByOptions, MeasureMap } from './measures';
12
14
  import type { Predicate, SortKey } from './tenancy';
13
15
  import type { SeriesPoint, SeriesSpec } from './time-bucket';
14
16
  import type { IdOf, RowPatch, RowWrite } from './types';
@@ -181,7 +183,12 @@ export interface Repo<T = unknown> {
181
183
  * `column` is a property name, spelled as `select` spells one — the typed form is
182
184
  * `ReadBuilder.countBy`, which knows the row. Ordered by count, biggest group first.
183
185
  */
184
- countBy(column: string, args?: FindManyArgs): Promise<ReadonlyMap<unknown, number>>;
186
+ countBy(
187
+ column: string,
188
+ args?: FindManyArgs,
189
+ /** `where`: counted with `count(*) filter (where …)` — a group none satisfy answers `0`. */
190
+ options?: CountByOptions,
191
+ ): Promise<ReadonlyMap<unknown, number>>;
185
192
  /**
186
193
  * One aggregate over exactly the rows `count(args)` counts. Row-agnostic here and typed on the
187
194
  * chain, the same seam `countBy` has: a column name is a runtime string at this contract.
@@ -191,6 +198,21 @@ export interface Repo<T = unknown> {
191
198
  * `MoneyValue`; neither is ever a float.
192
199
  */
193
200
  aggregate(fn: AggregateFn, column: string, args?: FindManyArgs): Promise<unknown>;
201
+ /**
202
+ * Several measures over exactly the rows `count(args)` counts, each with its own optional
203
+ * `filter (where …)`, in ONE statement; keyed by the caller's names. Optional: the typed handle
204
+ * answers `X_AGGREGATE_UNSUPPORTED` for a repository without it.
205
+ */
206
+ aggregates?(
207
+ measures: MeasureMap,
208
+ args?: FindManyArgs,
209
+ ): Promise<Readonly<Record<string, unknown>>>;
210
+ /**
211
+ * The newest `spec.perGroup` rows of each group, in ONE statement (`DISTINCT ON`, or `LATERAL`
212
+ * over `spec.keys`). Optional: `latest-by.ts` folds paged `findMany` reads for a repository
213
+ * without it — correct, never one statement.
214
+ */
215
+ latestBy?(spec: LatestBySpec, args?: FindManyArgs): Promise<readonly T[]>;
194
216
  /**
195
217
  * One point per time bucket that holds rows, over exactly the rows `count(args)` counts with an
196
218
  * instant in `spec.on` — truncated in `spec.timeZone` as Postgres' `date_trunc(unit, col, zone)`
@@ -221,6 +243,17 @@ export interface Repo<T = unknown> {
221
243
  * On a tenant-scoped entity with no actor it is `X_TENANCY_UNSCOPED`, exactly as a read.
222
244
  */
223
245
  lockKey?<R>(key: string, fn: (tx: Tx) => Promise<R> | R, options?: RepoOptions): Promise<R>;
246
+ /**
247
+ * `lockKey` over several keys: every key held, for as long as `fn` runs, in ONE transaction —
248
+ * acquired in sorted order so two callers naming the same keys in any order cannot deadlock.
249
+ * Same hashing and tenancy as `lockKey`. Optional, like it: the typed handle answers
250
+ * `X_LOCK_UNSUPPORTED` for a repository without it.
251
+ */
252
+ lockKeys?<R>(
253
+ keys: readonly string[],
254
+ fn: (tx: Tx) => Promise<R> | R,
255
+ options?: RepoOptions,
256
+ ): Promise<R>;
224
257
  }
225
258
 
226
259
  /**
@@ -17,10 +17,11 @@
17
17
  import { currentWriteOrigin, type EntityRowOp, instrument, subscribed } from '@ultimat3/core';
18
18
  import { expectedQueryLoop } from '@ultimat3/db';
19
19
  import { copyColumns } from './copy-plan';
20
+ import { counterEcho, type RepoOf } from './counter-observed';
20
21
  import type { EntityCore } from './entity';
21
22
  import { MAX_PAGE_SIZE } from './plan';
22
23
  import { readRecorder } from './read-capture';
23
- import type { Repo, RepoOptions, UpsertArgs } from './repo';
24
+ import type { FilteredWriteOptions, Repo, RepoOptions, UpsertArgs } from './repo';
24
25
  import { sealedFields } from './sealed';
25
26
  import { searchMirroredRepo } from './search-mirrored-repo';
26
27
  import type { IdOf, RowPatch } from './types';
@@ -140,9 +141,17 @@ const beforeAllOf = async <Row>(
140
141
  * so an app opts in by subscribing to `entity.row` and never by choosing a different repository — the
141
142
  * rows under test are the rows the app reads, which is the whole reason `defaultDriver()` is
142
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.
143
147
  */
144
- 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> {
145
153
  const name = entity.$name;
154
+ const counted = counterEcho(entity as EntityCore, repoOf);
146
155
  // Beneath the observer, so a searchable entity's writes reach an external index whether or not
147
156
  // anything hears `entity.row` (`search-mirrored-repo.ts`).
148
157
  const repo = searchMirroredRepo(entity, driven);
@@ -214,12 +223,17 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
214
223
  insert: async (values: Row, options?: RepoOptions): Promise<Row> => {
215
224
  const stored = await repo.insert(values, options);
216
225
  emit('insert', null, stored, options);
226
+ await counted?.rows([[null, stored]], options);
217
227
  return stored;
218
228
  },
219
229
 
220
230
  insertAll: async (rows: readonly Row[], options?: RepoOptions): Promise<readonly Row[]> => {
221
231
  const stored = await repo.insertAll(rows, options);
222
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
+ );
223
237
  return stored;
224
238
  },
225
239
 
@@ -235,11 +249,14 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
235
249
  const ids = [...new Set(rows.flatMap((row) => idOf(row) ?? []))];
236
250
  const before = await beforeAllOf(entity, repo, ids);
237
251
  const stored = await repo.upsertAll(rows, args);
252
+ const changes: (readonly [unknown, unknown])[] = [];
238
253
  for (const row of stored) {
239
254
  const id = idOf(row);
240
255
  const previous = id === undefined ? null : (before.get(id) ?? null);
241
256
  emit(previous === null ? 'insert' : 'update', previous, row, args);
257
+ changes.push([previous, row]);
242
258
  }
259
+ await counted?.rows(changes, args);
243
260
  return stored;
244
261
  },
245
262
 
@@ -248,6 +265,7 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
248
265
  const before = await beforeOf(entity, repo, id);
249
266
  const after = await repo.update(id, patch, options);
250
267
  emit('update', before, after, options);
268
+ await counted?.rows([[before, after]], options);
251
269
  return after;
252
270
  },
253
271
 
@@ -256,21 +274,24 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
256
274
  const before = await beforeOf(entity, repo, id);
257
275
  await repo.delete(id, options);
258
276
  emit('delete', before, null, options);
277
+ await counted?.rows([[before, null]], options);
259
278
  },
260
279
 
261
- deleteWhere: async (filter: RowPatch<Row>, options?: RepoOptions): Promise<number> => {
280
+ deleteWhere: async (filter: RowPatch<Row>, options?: FilteredWriteOptions): Promise<number> => {
262
281
  const rows = await repo.deleteWhere(filter, options);
263
282
  bulk('delete', rows, options);
283
+ await counted?.filtered(asRecord(filter), null, rows, options);
264
284
  return rows;
265
285
  },
266
286
 
267
287
  updateWhere: async (
268
288
  filter: RowPatch<Row>,
269
289
  patch: RowPatch<Row>,
270
- options?: RepoOptions,
290
+ options?: FilteredWriteOptions,
271
291
  ): Promise<number> => {
272
292
  const rows = await repo.updateWhere(filter, patch, options);
273
293
  bulk('update', rows, options);
294
+ await counted?.filtered(asRecord(filter), asRecord(patch) ?? {}, rows, options);
274
295
  return rows;
275
296
  },
276
297
  };
@@ -307,6 +328,10 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
307
328
  observed.updateMany = async (rows, options) => {
308
329
  const written = await updateMany.call(repo, rows, options);
309
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);
310
335
  return written;
311
336
  };
312
337
  }
@@ -230,9 +230,12 @@ export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo:
230
230
  async count(args) {
231
231
  return repo.count(await readArgs(entity, fields, args, sealKeysOnce()));
232
232
  },
233
- async countBy(column, args) {
233
+ async countBy(column, args, options) {
234
234
  refuseNamed(entity, fields, [column], 'a grouped count');
235
- 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);
236
239
  },
237
240
  async aggregate(fn: AggregateFn, column, args) {
238
241
  refuseNamed(entity, fields, [column], 'an aggregate');
@@ -273,6 +276,31 @@ export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo:
273
276
  return updateMany.call(repo, sealed, options);
274
277
  };
275
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
+ }
276
304
  // A bucket is an instant and a sum is arithmetic: neither has a meaning over ciphertext.
277
305
  const series = repo.series?.bind(repo);
278
306
  if (series !== undefined) {
@@ -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' }]`;