@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
@@ -0,0 +1,169 @@
1
+ // Single responsibility: the typed handle's writes past one row — a chain's `updateAll(patch)` and
2
+ // `deleteAll()`, `insertAll`/`upsertAll` with or without the rows back, `copyAll` and `updateMany` —
3
+ // each forwarded to the repository member that does it, or, for a hand-written repository that
4
+ // omits an optional one, to the counterpart every repository has. Split from `query.ts` at its ceiling.
5
+
6
+ import { overwrittenBy } from './bulk-write';
7
+ import { copyColumns } from './copy-plan';
8
+ import type { EntityCore } from './entity';
9
+ import type { Repo, RepoOptions, UpdateManyRow, UpsertArgs } from './repo';
10
+ import { stampedColumns, touch } from './touch';
11
+ import type { ColumnMap, Insertable, RowPatch } from './types';
12
+ import { updateManyPlan } from './update-many';
13
+ import { assertWritableChain, type WriteChain } from './write-where';
14
+
15
+ /** Asks for a count instead of the rows: no `returning *`, nothing decoded. */
16
+ export interface Unreturned {
17
+ readonly returning: false;
18
+ }
19
+
20
+ /** The default, spelled: the rows as stored. `boolean` is neither, so it does not typecheck. */
21
+ export interface Returned {
22
+ readonly returning?: true;
23
+ }
24
+
25
+ export interface ChainWrites<Row> {
26
+ /**
27
+ * Every row the chain matches, patched in ONE statement; resolves with how many. The chain's
28
+ * predicates are `updateWhere`'s filter: the same tenancy, soft-delete reach, invariant judging,
29
+ * `onUpdateNow()` stamp, search mirror and `entity.bulk` report. A chain with no predicate is
30
+ * `X_WRITE_UNFILTERED`; `limit()`, `after()` and `search()` are refused — a write has no page.
31
+ */
32
+ updateAll(patch: RowPatch<Row>, options?: RepoOptions): Promise<number>;
33
+ /** Every row the chain matches, removed (or soft-deleted) in one statement; `updateAll`'s guards. */
34
+ deleteAll(options?: RepoOptions): Promise<number>;
35
+ }
36
+
37
+ export const chainWrites = <Source, Row>(
38
+ entity: EntityCore<Source>,
39
+ repo: Repo<Source>,
40
+ chain: WriteChain,
41
+ ): ChainWrites<Row> => ({
42
+ updateAll: async (patch, options) => {
43
+ assertWritableChain(entity.$name, 'updateAll', chain);
44
+ return repo.updateWhere({}, touch(entity, patch as unknown as RowPatch<Source>), {
45
+ ...options,
46
+ where: chain.where,
47
+ });
48
+ },
49
+ deleteAll: async (options) => {
50
+ assertWritableChain(entity.$name, 'deleteAll', chain);
51
+ return repo.deleteWhere({}, { ...options, where: chain.where });
52
+ },
53
+ });
54
+
55
+ export interface TableBulkWrites<Row, C extends ColumnMap = ColumnMap> {
56
+ /**
57
+ * Many rows, one statement — the bulk write a per-row `insert` loop is the N+1 of, and the line
58
+ * an N+1 warning on a write loop names. Every row is parsed and asserted exactly as `insert`
59
+ * parses one, so declared defaults are filled here and not by the caller. Resolves with the rows
60
+ * as stored, in order; `insertAll([])` writes nothing. A collision is an error — `upsertAll` is
61
+ * the call that tolerates one. `{ returning: false }` resolves with the count instead.
62
+ */
63
+ insertAll(rows: readonly Insertable<C>[], options: RepoOptions & Unreturned): Promise<number>;
64
+ insertAll(
65
+ rows: readonly Insertable<C>[],
66
+ options?: RepoOptions & Returned,
67
+ ): Promise<readonly Row[]>;
68
+ /**
69
+ * `insertAll` that resolves a collision instead of failing on it: `on conflict (…) do update`,
70
+ * or `do nothing` with `onMatch: 'nothing'`. Resolves with the rows this call actually wrote, so
71
+ * a row left alone is absent from the result — which is how a caller counts what it inserted.
72
+ * The conflict target and the primary key are never overwritten: they are how the stored row was
73
+ * found and where it lives. `returning: false` resolves with how many rows it wrote.
74
+ */
75
+ upsertAll(rows: readonly Insertable<C>[], args: UpsertArgs<Row> & Unreturned): Promise<number>;
76
+ upsertAll(
77
+ rows: readonly Insertable<C>[],
78
+ args: UpsertArgs<Row> & Returned,
79
+ ): Promise<readonly Row[]>;
80
+ /**
81
+ * The bulk load: `COPY … FROM STDIN` on Postgres, the rows parsed, sealed, tenant-checked and
82
+ * judged exactly as `insertAll` judges them; resolves with the count. No conflict handling — a
83
+ * duplicate refuses the whole load. In memory and on a custom store it is `insertAll`.
84
+ */
85
+ copyAll(rows: readonly Insertable<C>[], options?: RepoOptions): Promise<number>;
86
+ /**
87
+ * A different patch per row, by id, in one statement per bind-count chunk; resolves with how many
88
+ * rows were written. Every patch names the same columns. An id that is absent, soft-deleted or
89
+ * another tenant's is not written and not counted, as `updateWhere` would not.
90
+ */
91
+ updateMany(rows: readonly UpdateManyRow<Row>[], options?: RepoOptions): Promise<number>;
92
+ }
93
+
94
+ /** `options` without `returning`, which no repository member takes. */
95
+ const withoutReturning = <O extends { readonly returning?: boolean }>(
96
+ options: O,
97
+ ): Omit<O, 'returning'> => {
98
+ const { returning: _returning, ...rest } = options;
99
+ return rest;
100
+ };
101
+
102
+ export const tableBulkWrites = <Row, C extends ColumnMap>(
103
+ entity: EntityCore<Row, C>,
104
+ repo: Repo<Row>,
105
+ ): TableBulkWrites<Row, C> => {
106
+ const parsed = (rows: readonly Insertable<C>[]): Row[] => rows.map((row) => entity.$parse(row));
107
+ const counted = async (rows: readonly Row[], options: RepoOptions | undefined) =>
108
+ repo.insertAllCount === undefined
109
+ ? (await repo.insertAll(rows, options)).length
110
+ : repo.insertAllCount(rows, options);
111
+
112
+ async function insertAll(
113
+ rows: readonly Insertable<C>[],
114
+ options?: RepoOptions & { readonly returning?: boolean },
115
+ ): Promise<number | readonly Row[]> {
116
+ const given = options === undefined ? undefined : withoutReturning(options);
117
+ return options?.returning === false
118
+ ? counted(parsed(rows), given)
119
+ : repo.insertAll(parsed(rows), given);
120
+ }
121
+
122
+ // `touch` and not `$parse` alone: an upsert that lands on a stored row IS an update, so an
123
+ // `onUpdateNow()` column has to move exactly as `update(id, patch)` moves it. Asked of the
124
+ // caller's rows BEFORE `$parse` makes every row name every column: otherwise a collision resets
125
+ // each column nobody mentioned to its default.
126
+ async function upsertAll(
127
+ rows: readonly Insertable<C>[],
128
+ args: UpsertArgs<Row> & { readonly returning?: boolean },
129
+ ): Promise<number | readonly Row[]> {
130
+ const plain = withoutReturning(args);
131
+ const overwrites =
132
+ plain.onMatch === 'nothing'
133
+ ? undefined
134
+ : ([
135
+ ...overwrittenBy(entity, rows as readonly RowPatch<Row>[]),
136
+ ...stampedColumns(entity),
137
+ ] as (keyof Row & string)[]);
138
+ const touched = rows.map((row) => touch(entity, entity.$parse(row)));
139
+ const sent = overwrites === undefined ? plain : { ...plain, overwrites };
140
+ if (args.returning !== false) return repo.upsertAll(touched, sent);
141
+ return repo.upsertAllCount === undefined
142
+ ? (await repo.upsertAll(touched, sent)).length
143
+ : repo.upsertAllCount(touched, sent);
144
+ }
145
+
146
+ return {
147
+ insertAll: insertAll as TableBulkWrites<Row, C>['insertAll'],
148
+ upsertAll: upsertAll as TableBulkWrites<Row, C>['upsertAll'],
149
+ copyAll: async (rows, options) => {
150
+ const given = parsed(rows);
151
+ if (repo.copyAll !== undefined) return repo.copyAll(given, options);
152
+ // COPY's refusal, kept by the fallback: a load is refused alike whatever the repository.
153
+ copyColumns(entity, given as readonly RowPatch<Row>[]);
154
+ return counted(given, options);
155
+ },
156
+ updateMany: async (rows, options) => {
157
+ const stamped = rows.map(({ id, patch }) => ({ id, patch: touch(entity, patch) }));
158
+ if (repo.updateMany !== undefined) return repo.updateMany(stamped, options);
159
+ // A hand-written repository: the batch judged as every driver judges it (a nullish or
160
+ // repeated id, an uneven column set, an empty patch), then one `updateWhere` per row.
161
+ const plan = updateManyPlan(entity, stamped, options);
162
+ let written = 0;
163
+ for (const { id, patch } of plan.patches) {
164
+ written += await repo.updateWhere({ [plan.key]: id } as RowPatch<Row>, patch, options);
165
+ }
166
+ return written;
167
+ },
168
+ };
169
+ };
package/src/query.ts CHANGED
@@ -6,22 +6,30 @@
6
6
 
7
7
  import type { Page } from '@ultimat3/core';
8
8
  import { pageOf } from '@ultimat3/core';
9
+ import { reportTruncatedAll } from './all-truncated';
9
10
  import { assertBatchable, type BatchIterator, batchIterator } from './batch';
10
- import { overwrittenBy } from './bulk-write';
11
+ import { shrinkingPages } from './batch-bytes';
11
12
  import type { EntityCore } from './entity';
12
13
  import { searchUndeclared } from './feature-errors';
14
+ import { latestByRows, type ReadLatest } from './latest-by';
13
15
  import { checkedPredicate, type Operator } from './operator';
14
16
  import { assertFinitePageSize, DEFAULT_PAGE_SIZE } from './plan';
15
17
  import { preloaded, type RelatedTables } from './preload';
16
18
  import { type PreloadOptions, type PreloadRelation, preloadsWith } from './preload-ceiling';
19
+ import {
20
+ type ChainWrites,
21
+ chainWrites,
22
+ type TableBulkWrites,
23
+ tableBulkWrites,
24
+ } from './query-write';
17
25
  import { type ReadAggregates, readAggregates } from './read-aggregates';
18
- import type { Repo, RepoOptions, UpsertArgs } from './repo';
26
+ import type { Repo, RepoOptions } from './repo';
19
27
  import { pickRow } from './sealed';
20
28
  import { SEARCH_PROPERTY } from './search';
21
29
  import { searchedRepo } from './search-repo';
22
30
  import { type TableLocks, tableLocks } from './table-locks';
23
31
  import type { Predicate, QueryPlan, SortDirection, SortKey } from './tenancy';
24
- import { stampedColumns, touch } from './touch';
32
+ import { touch } from './touch';
25
33
  import { type Move, transitionRow } from './transition';
26
34
  import type {
27
35
  ColumnMap,
@@ -46,7 +54,9 @@ export type Preloaded<Name extends string> = { readonly [K in Name]: unknown };
46
54
  * and not only `X_ENTITY_SEALED_PREDICATE` at runtime. It defaults to none.
47
55
  */
48
56
  export interface ReadBuilder<Row, S extends SealedKeySet = NoSealedKeys>
49
- extends ReadAggregates<Row, S> {
57
+ extends ReadAggregates<Row, S>,
58
+ ReadLatest<Row, S>,
59
+ ChainWrites<Row> {
50
60
  /** Equality on the columns given. `where({ orgId })` is what satisfies the tenancy guard. */
51
61
  where(filter: RowPatch<Filterable<Row, S>>): ReadBuilder<Row, S>;
52
62
  // NULL is never sealed, so its tests take ANY column. First: `Parameters<…>` reads the last.
@@ -135,9 +145,14 @@ export interface ReadBuilder<Row, S extends SealedKeySet = NoSealedKeys>
135
145
  plan(): QueryPlan;
136
146
  }
137
147
 
148
+ /**
149
+ * `update` and `delete` address one row by id; a chain's `updateAll(patch)`/`deleteAll()` write
150
+ * every row its predicates match (`query-write.ts`).
151
+ */
138
152
  export interface Table<Row, C extends ColumnMap = ColumnMap>
139
153
  extends ReadBuilder<Row, SealedKeysOf<C>>,
140
- TableLocks<Row> {
154
+ TableLocks<Row>,
155
+ TableBulkWrites<Row, C> {
141
156
  /**
142
157
  * Move one row through the state machine `column` declares, in ONE statement.
143
158
  *
@@ -165,22 +180,6 @@ export interface Table<Row, C extends ColumnMap = ColumnMap>
165
180
  options?: RepoOptions,
166
181
  ): Promise<Row>;
167
182
  insert(values: Insertable<C>, options?: RepoOptions): Promise<Row>;
168
- /**
169
- * Many rows, one statement — the bulk write a per-row `insert` loop is the N+1 of, and the line
170
- * an N+1 warning on a write loop names. Every row is parsed and asserted exactly as `insert`
171
- * parses one, so declared defaults are filled here and not by the caller. Resolves with the rows
172
- * as stored, in order; `insertAll([])` writes nothing. A collision is an error — `upsertAll` is
173
- * the call that tolerates one.
174
- */
175
- insertAll(rows: readonly Insertable<C>[], options?: RepoOptions): Promise<readonly Row[]>;
176
- /**
177
- * `insertAll` that resolves a collision instead of failing on it: `on conflict (…) do update`,
178
- * or `do nothing` with `onMatch: 'nothing'`. Resolves with the rows this call actually wrote, so
179
- * a row left alone is absent from the result — which is how a caller counts what it inserted.
180
- * The conflict target and the primary key are never overwritten: they are how the stored row was
181
- * found and where it lives.
182
- */
183
- upsertAll(rows: readonly Insertable<C>[], args: UpsertArgs<Row>): Promise<readonly Row[]>;
184
183
  /** `IdOf<Row>`: an entity that declared `uuid<PostId>()` is addressed by a `PostId` only. */
185
184
  update(id: IdOf<Row>, patch: RowPatch<Row>, options?: RepoOptions): Promise<Row>;
186
185
  delete(id: IdOf<Row>, options?: RepoOptions): Promise<void>;
@@ -336,10 +335,11 @@ const builder = <Source, Row>(
336
335
  from: state.cursor,
337
336
  // The chain's own arguments with the batch as the page size and the iteration's position
338
337
  // in place of the chain's: one statement per batch, and the same one `page()` sends.
339
- page: async (cursor) => {
340
- const result = await repo.findMany({ ...args(), limit: size, cursor });
338
+ // Past the page byte bound a batch re-reads its own cursor at half the size (`batch-bytes.ts`).
339
+ page: shrinkingPages(size, async (limit, cursor) => {
340
+ const result = await repo.findMany({ ...args(), limit, cursor });
341
341
  return pageOf(await attach(result.rows), result.nextCursor);
342
- },
342
+ }),
343
343
  });
344
344
  },
345
345
 
@@ -348,7 +348,13 @@ const builder = <Source, Row>(
348
348
  return pageOf(await attach(result.rows), result.nextCursor);
349
349
  },
350
350
 
351
- all: async () => attach((await repo.findMany(args())).rows),
351
+ // A page, never the table: when a next one existed and no `limit()` said so, dev and test hear
352
+ // about it (`all-truncated.ts`) — the refusal is a break and waits on `next`.
353
+ all: async () => {
354
+ const page = await repo.findMany(args());
355
+ reportTruncatedAll(entity.$name, page.nextCursor, state.limit !== undefined);
356
+ return attach(page.rows);
357
+ },
352
358
 
353
359
  one: async () => {
354
360
  const { rows } = await repo.findMany({ ...args(), limit: 1 });
@@ -358,6 +364,12 @@ const builder = <Source, Row>(
358
364
 
359
365
  count: () => repo.count(args()),
360
366
 
367
+ // The projection and every preload apply after the per-group pick, as a page's do.
368
+ latestBy: async (group, options) =>
369
+ attach(await latestByRows(entity, repo, group, options, args())),
370
+
371
+ ...chainWrites<Source, Row>(entity, repo, state),
372
+
361
373
  ...readAggregates(entity, repo, args),
362
374
 
363
375
  plan: (): QueryPlan => ({
@@ -393,29 +405,7 @@ export const tableFor = <Row, C extends ColumnMap>(
393
405
  related,
394
406
  ) as ReadBuilder<Row, SealedKeysOf<C>>),
395
407
  insert: async (values, options) => repo.insert(entity.$parse(values), options),
396
- insertAll: async (rows, options) =>
397
- repo.insertAll(
398
- rows.map((row) => entity.$parse(row)),
399
- options,
400
- ),
401
- // `touch` and not `$parse` alone: an upsert that lands on a stored row IS an update, so an
402
- // `onUpdateNow()` column has to move exactly as `update(id, patch)` moves it — and stamping it
403
- // in a second place is how one of the two ends up writing a stale `updatedAt`.
404
- // Asked of the caller's rows, BEFORE `$parse` makes every row name every column: otherwise a
405
- // collision resets each column nobody mentioned to its default.
406
- upsertAll: async (rows, args) => {
407
- const overwrites =
408
- args.onMatch === 'nothing'
409
- ? undefined
410
- : ([
411
- ...overwrittenBy(entity, rows as readonly RowPatch<Row>[]),
412
- ...stampedColumns(entity),
413
- ] as (keyof Row & string)[]);
414
- return repo.upsertAll(
415
- rows.map((row) => touch(entity, entity.$parse(row))),
416
- overwrites === undefined ? args : { ...args, overwrites },
417
- );
418
- },
408
+ ...tableBulkWrites(entity, repo),
419
409
  update: async (id, patch, options) => repo.update(id, touch(entity, patch), options),
420
410
  delete: async (id, options) => repo.delete(id, options),
421
411
  deleteWhere: async (filter, options) => repo.deleteWhere(filter, options),
@@ -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';
@@ -59,6 +61,22 @@ export interface UpsertArgs<T = unknown> extends RepoOptions {
59
61
  readonly overwrites?: readonly (keyof T & string)[];
60
62
  }
61
63
 
64
+ /**
65
+ * A filtered write's options: `RepoOptions`, plus the predicates a CHAIN carries
66
+ * (`db.x.where(…).andWhere(…).update(patch)`). They AND with the equality filter, every guard
67
+ * applies to the union, and an empty union is `X_WRITE_UNFILTERED` — so a repository that ignores
68
+ * `where` refuses the chain's empty filter rather than reading it as every row.
69
+ */
70
+ export interface FilteredWriteOptions extends RepoOptions {
71
+ readonly where?: readonly Predicate[];
72
+ }
73
+
74
+ /** One row of `updateMany`: the row's id and what it becomes. */
75
+ export interface UpdateManyRow<T = unknown> {
76
+ readonly id: IdOf<T>;
77
+ readonly patch: RowPatch<T>;
78
+ }
79
+
62
80
  /**
63
81
  * `findById`'s options: `RepoOptions`, plus the one knob a point READ has and a write must not.
64
82
  *
@@ -125,14 +143,36 @@ export interface Repo<T = unknown> {
125
143
  * to be able to tell "nothing matched" from "it worked", and an empty filter is
126
144
  * `X_WRITE_UNFILTERED` rather than every row.
127
145
  */
128
- deleteWhere(filter: RowPatch<T>, options?: RepoOptions): Promise<number>;
146
+ deleteWhere(filter: RowPatch<T>, options?: FilteredWriteOptions): Promise<number>;
129
147
  /**
130
148
  * Update by filter, returning how many rows were written. The `update(id, patch)` a composite
131
149
  * primary key cannot express — `participants.lastReadAt` is the reference case. Same two guards
132
150
  * as `deleteWhere`, plus `X_PATCH_EMPTY` for a patch that names no columns, and soft-deleted
133
151
  * rows are not reachable, exactly as they are not by `update(id, patch)`.
134
152
  */
135
- updateWhere(filter: RowPatch<T>, patch: RowPatch<T>, options?: RepoOptions): Promise<number>;
153
+ updateWhere(
154
+ filter: RowPatch<T>,
155
+ patch: RowPatch<T>,
156
+ options?: FilteredWriteOptions,
157
+ ): Promise<number>;
158
+ /**
159
+ * A different patch per row, by id, resolving with how many rows were written — the bulk form of a
160
+ * loop of `update(id, patch)`. Every patch names the same columns. Optional: the typed handle
161
+ * runs a `updateWhere` per row for a repository without it.
162
+ */
163
+ updateMany?(rows: readonly UpdateManyRow<T>[], options?: RepoOptions): Promise<number>;
164
+ /**
165
+ * `insertAll` answering a count: no `returning *`, nothing decoded. Optional: the typed handle
166
+ * counts `insertAll`'s rows for a repository without it.
167
+ */
168
+ insertAllCount?(rows: readonly RowWrite<T>[], options?: RepoOptions): Promise<number>;
169
+ /** `upsertAll` answering how many rows it wrote, as `insertAllCount` is to `insertAll`. */
170
+ upsertAllCount?(rows: readonly RowWrite<T>[], args: UpsertArgs<T>): Promise<number>;
171
+ /**
172
+ * The bulk load: Postgres `COPY … FROM STDIN`, judged exactly as `insertAll` judges its rows.
173
+ * Optional: `insertAllCount` (else `insertAll`) for a repository without it.
174
+ */
175
+ copyAll?(rows: readonly RowWrite<T>[], options?: RepoOptions): Promise<number>;
136
176
  count(args?: FindManyArgs): Promise<number>;
137
177
  /**
138
178
  * The grouped count: one statement, one entry per distinct value of `column`, over exactly the
@@ -143,7 +183,12 @@ export interface Repo<T = unknown> {
143
183
  * `column` is a property name, spelled as `select` spells one — the typed form is
144
184
  * `ReadBuilder.countBy`, which knows the row. Ordered by count, biggest group first.
145
185
  */
146
- 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>>;
147
192
  /**
148
193
  * One aggregate over exactly the rows `count(args)` counts. Row-agnostic here and typed on the
149
194
  * chain, the same seam `countBy` has: a column name is a runtime string at this contract.
@@ -153,6 +198,21 @@ export interface Repo<T = unknown> {
153
198
  * `MoneyValue`; neither is ever a float.
154
199
  */
155
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[]>;
156
216
  /**
157
217
  * One point per time bucket that holds rows, over exactly the rows `count(args)` counts with an
158
218
  * instant in `spec.on` — truncated in `spec.timeZone` as Postgres' `date_trunc(unit, col, zone)`
@@ -183,6 +243,17 @@ export interface Repo<T = unknown> {
183
243
  * On a tenant-scoped entity with no actor it is `X_TENANCY_UNSCOPED`, exactly as a read.
184
244
  */
185
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>;
186
257
  }
187
258
 
188
259
  /**