@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,249 @@
1
+ // Single responsibility: what a newest-row-per-group read means — the spec a driver answers, the
2
+ // plan both drivers build it from, the bound on how many groups one call may answer, and the
3
+ // answer for a repository that cannot send the one statement (`latestRows`). Postgres sends
4
+ // `DISTINCT ON` or `LATERAL` (`latest-by-sql.ts`); memory folds the same plan (`memory-latest-by.ts`).
5
+
6
+ import { keyOf } from './batch-read';
7
+ import { groupColumnOf, MAX_GROUPS } from './count-by';
8
+ import { valueAt } from './cursor';
9
+ import type { EntityCore } from './entity';
10
+ import { describeCommand, EntityError } from './errors';
11
+ import { MAX_PAGE_SIZE, readPlan } from './plan';
12
+ import type { FindManyArgs, Repo } from './repo';
13
+ import type { Predicate, QueryPlan, SortDirection, SortKey } from './tenancy';
14
+ import type { NoSealedKeys, SealedKeySet } from './types';
15
+
16
+ /** The groups one `latestBy` may answer: `countBy`'s bound, refused past it and never truncated. */
17
+ export const MAX_LATEST_GROUPS = MAX_GROUPS;
18
+
19
+ /**
20
+ * What a driver's `latestBy` is asked. `order` is the caller's, without the group and without the
21
+ * tiebreak — the plan adds both. `keys`, when present, are the only groups wanted (a preload's
22
+ * parents) and `perGroup` may then exceed one; without them it is the newest row of every group
23
+ * the predicate matches, one each.
24
+ */
25
+ export interface LatestBySpec {
26
+ readonly group: string;
27
+ readonly order: readonly SortKey[];
28
+ readonly perGroup: number;
29
+ readonly keys?: readonly unknown[];
30
+ }
31
+
32
+ /** `ReadBuilder.latestBy`'s options: the column that says which row is newest, descending unless stated. */
33
+ export interface LatestByOptions<K extends string = string> {
34
+ readonly order: K;
35
+ readonly direction?: SortDirection;
36
+ }
37
+
38
+ export interface ReadLatest<Row, S extends SealedKeySet = NoSealedKeys> {
39
+ /**
40
+ * The newest row of every group the chain matches, in ONE statement — "the last message of each
41
+ * conversation" is `messages.andWhere('conversationId', 'in', ids).latestBy('conversationId',
42
+ * { order: 'createdAt' })`, not one `.orderBy().one()` per conversation. Ties go to the primary
43
+ * key in the same direction. Rows come back ordered by the group, `null` last; a group with no
44
+ * row is absent. Past `MAX_LATEST_GROUPS` groups it is refused, never truncated, and the chain's
45
+ * own `orderBy()`, `limit()` and `after()` are refused: one row per group is the whole shape.
46
+ */
47
+ latestBy<
48
+ G extends Exclude<keyof Row & string, S['sealed']>,
49
+ K extends Exclude<keyof Row & string, S['sealed']>,
50
+ >(group: G, options: LatestByOptions<K>): Promise<readonly Row[]>;
51
+ }
52
+
53
+ const refused = (entityName: string, cause: string, fix: string): EntityError =>
54
+ new EntityError({
55
+ code: 'X_INVARIANT_VIOLATED',
56
+ cause,
57
+ fix: `${describeCommand(entityName)} # ${fix}`,
58
+ });
59
+
60
+ /** The per-group count a spec asks for: a whole number of rows, at least one, at most a page. */
61
+ const assertPerGroup = <Row>(entity: EntityCore<Row>, spec: LatestBySpec, op: string): void => {
62
+ const n = spec.perGroup;
63
+ if (!Number.isSafeInteger(n) || n < 1 || n > MAX_PAGE_SIZE) {
64
+ throw refused(
65
+ entity.$name,
66
+ `${entity.$name}.${op}('${spec.group}') asks for ${String(n)} rows per group — a whole number, at least 1 and at most ${MAX_PAGE_SIZE}`,
67
+ `{ perParent: 1 } # on that ${op}() call: a whole number of rows per group, 1 to ${MAX_PAGE_SIZE}`,
68
+ );
69
+ }
70
+ // `DISTINCT ON` keeps one row; more than one per group needs the groups named, which is the
71
+ // statement (`LATERAL`) that reads n rows per key off an index instead of every row of them.
72
+ if (n > 1 && spec.keys === undefined) {
73
+ throw refused(
74
+ entity.$name,
75
+ `${entity.$name}.${op}('${spec.group}') asks for ${n} rows per group without naming the groups — more than one row per group is a preload over known parents`,
76
+ `parents.preload('<relation>', { perParent: ${n} }) # a preload names the groups, its parents; latestBy names none`,
77
+ );
78
+ }
79
+ };
80
+
81
+ /**
82
+ * The read both drivers plan: the chain's scope, ordered by the group first, then the caller's
83
+ * order, then the primary key in the last key's direction — which is what `DISTINCT ON` needs
84
+ * leading its `order by`, and what makes "the first row of each group" one row in both drivers.
85
+ * With `keys`, an `in` predicate on the group joins the scope. No page and no cursor: not a page.
86
+ */
87
+ export const latestArgs = <Row>(
88
+ entity: EntityCore<Row>,
89
+ spec: LatestBySpec,
90
+ args: FindManyArgs,
91
+ ) => {
92
+ const keyed: readonly Predicate[] =
93
+ spec.keys === undefined ? [] : [{ column: spec.group, op: 'in', value: spec.keys }];
94
+ const { cursor: _cursor, limit: _limit, ...scope } = args;
95
+ return {
96
+ ...scope,
97
+ where: [...(args.where ?? []), ...keyed],
98
+ // The tiebreak follows the LAST key's direction (`totalOrder`), so an empty order is the
99
+ // primary key descending — "latest" by the uuid-v7 id every entity's default key mints.
100
+ orderBy: [
101
+ { column: spec.group, direction: 'asc' as const },
102
+ ...(spec.order.length === 0
103
+ ? entity.$primaryKey.map((column) => ({ column, direction: 'desc' as const }))
104
+ : spec.order),
105
+ ],
106
+ } satisfies FindManyArgs;
107
+ };
108
+
109
+ /** The plan, guarded as `readPlan` guards every read: tenancy, screening, a total order. */
110
+ export const latestPlanOf = <Row>(
111
+ entity: EntityCore<Row>,
112
+ spec: LatestBySpec,
113
+ args: FindManyArgs,
114
+ op = 'latestBy',
115
+ ): QueryPlan => {
116
+ groupColumnOf(entity, spec.group, op);
117
+ assertPerGroup(entity, spec, op);
118
+ return readPlan(entity, latestArgs(entity, spec, args), op);
119
+ };
120
+
121
+ /**
122
+ * The string a group is filed under, spelled as a batch spells a key (`keyOf`): a `uuid` handed in
123
+ * upper case is the group Postgres compares it into. `null` is its own bucket, apart from the text
124
+ * `'null'`, as `group by` keeps them.
125
+ */
126
+ const groupKey = (kind: string, value: unknown): string =>
127
+ value === null || value === undefined ? '\u0000null' : `v:${keyOf(kind, value)}`;
128
+
129
+ /**
130
+ * The first `perGroup` rows of each group, from rows already in the plan's order — the fold the
131
+ * memory driver and the paged fallback share, so the two cannot disagree about which row is first.
132
+ */
133
+ export const firstPerGroup = <Row>(
134
+ rows: readonly Row[],
135
+ group: { readonly column: string; readonly kind: string },
136
+ perGroup: number,
137
+ ): readonly Row[] => {
138
+ const taken = new Map<string, number>();
139
+ const kept: Row[] = [];
140
+ for (const row of rows) {
141
+ const key = groupKey(group.kind, valueAt(row, group.column));
142
+ const count = taken.get(key) ?? 0;
143
+ if (count >= perGroup) continue;
144
+ taken.set(key, count + 1);
145
+ kept.push(row);
146
+ }
147
+ return kept;
148
+ };
149
+
150
+ /** The group column as the fold reads it: its name and its declared kind. */
151
+ export const groupOf = <Row>(entity: EntityCore<Row>, spec: LatestBySpec) => ({
152
+ column: spec.group,
153
+ kind: entity.$columns[spec.group]?.$meta.kind ?? '',
154
+ });
155
+
156
+ /** How many distinct groups some rows span. */
157
+ export const groupsIn = (
158
+ rows: readonly unknown[],
159
+ group: { readonly column: string; readonly kind: string },
160
+ ): number => new Set(rows.map((row) => groupKey(group.kind, valueAt(row, group.column)))).size;
161
+
162
+ /**
163
+ * Refused past the bound, never truncated: a map of "the newest row per conversation" missing its
164
+ * tail reads exactly like a complete one. Only a read with no `keys` can reach it — a preload's
165
+ * groups are its parents, which the page already bounds.
166
+ */
167
+ export const assertGroupBound = <Row>(
168
+ entity: EntityCore<Row>,
169
+ spec: LatestBySpec,
170
+ groups: number,
171
+ ): void => {
172
+ if (spec.keys !== undefined || groups <= MAX_LATEST_GROUPS) return;
173
+ throw refused(
174
+ entity.$name,
175
+ `${entity.$name}.latestBy('${spec.group}') matched more than ${MAX_LATEST_GROUPS} groups — bound the chain first: ${entity.$name}.andWhere('${spec.group}', 'in', <values>).latestBy('${spec.group}', { order })`,
176
+ `andWhere('${spec.group}', 'in', <values>).latestBy('${spec.group}', { order }) # bound the groups first, or page them with inBatches()`,
177
+ );
178
+ };
179
+
180
+ /** Rows per `findMany` statement when a repository has no `latestBy` of its own. */
181
+ const FALLBACK_PAGE = 1000;
182
+
183
+ /**
184
+ * The answer for a repository without `latestBy` (a hand-written driver, a wrapper that does not
185
+ * forward it): every matched row in the plan's order, a page at a time, folded. Correct, never
186
+ * one statement — which is what the method exists to be, so a driver that can should implement it.
187
+ */
188
+ const pagedLatest = async <Row>(
189
+ entity: EntityCore<Row>,
190
+ repo: Repo<Row>,
191
+ spec: LatestBySpec,
192
+ args: FindManyArgs,
193
+ ): Promise<readonly Row[]> => {
194
+ latestPlanOf(entity, spec, args);
195
+ const read = latestArgs(entity, spec, args);
196
+ const group = groupOf(entity, spec);
197
+ const kept: Row[] = [];
198
+ let cursor: string | null = null;
199
+ do {
200
+ const page = await repo.findMany({
201
+ ...read,
202
+ limit: FALLBACK_PAGE,
203
+ cursor,
204
+ });
205
+ kept.push(...page.rows);
206
+ // Folded per page so memory holds the answer, never the table.
207
+ kept.splice(0, kept.length, ...firstPerGroup(kept, group, spec.perGroup));
208
+ assertGroupBound(entity, spec, groupsIn(kept, group));
209
+ cursor = page.nextCursor;
210
+ } while (cursor !== null);
211
+ return kept;
212
+ };
213
+
214
+ /** The one door: the driver's statement when it has one, the paged fold when it has not. */
215
+ export const latestRows = <Row>(
216
+ entity: EntityCore<Row>,
217
+ repo: Repo<Row>,
218
+ spec: LatestBySpec,
219
+ args: FindManyArgs = {},
220
+ ): Promise<readonly Row[]> =>
221
+ repo.latestBy === undefined ? pagedLatest(entity, repo, spec, args) : repo.latestBy(spec, args);
222
+
223
+ /**
224
+ * The chain's terminal, before the projection and the preloads (`query.ts` attaches those). A
225
+ * chain that also named an order, a page size or a cursor is refused: each is a second answer to
226
+ * "which rows", and silently dropping one is a read the author did not write.
227
+ */
228
+ export const latestByRows = <Row>(
229
+ entity: EntityCore<Row>,
230
+ repo: Repo<Row>,
231
+ group: string,
232
+ options: LatestByOptions,
233
+ args: FindManyArgs,
234
+ ): Promise<readonly Row[]> => {
235
+ const extra = [
236
+ (args.orderBy?.length ?? 0) > 0 ? 'orderBy()' : undefined,
237
+ args.limit === undefined ? undefined : 'limit()',
238
+ args.cursor === undefined || args.cursor === null ? undefined : 'after()',
239
+ ].filter((each) => each !== undefined);
240
+ if (extra.length > 0) {
241
+ throw refused(
242
+ entity.$name,
243
+ `${entity.$name}.latestBy('${group}') on a chain that also called ${extra.join(', ')} — latestBy answers one row per group, ordered by { order }, and takes no page`,
244
+ `latestBy('${group}', { order, direction }) # on a chain without ${extra.join(', ')}: { order, direction } picks the newest row`,
245
+ );
246
+ }
247
+ const order = [{ column: options.order, direction: options.direction ?? 'desc' }] as const;
248
+ return latestRows(entity, repo, { group, order, perGroup: 1 }, args);
249
+ };
package/src/lock-key.ts CHANGED
@@ -1,6 +1,6 @@
1
- // Single responsibility: what `lockKey` locks, in one place for both drivers. The tenant comes from
2
- // the read path's own plan, so an org's key never blocks another org's and an actor with none is
3
- // refused exactly as a read is, by the same guard and the same code.
1
+ // Single responsibility: what `lockKey` and `lockKeys` lock, in one place for every driver. The
2
+ // tenant comes from the read path's own plan, so an org's key never blocks another org's and an
3
+ // actor with none is refused exactly as a read is, by the same guard and the same code.
4
4
 
5
5
  import { assert } from '@ultimat3/core';
6
6
  import type { EntityCore } from './entity';
@@ -25,3 +25,56 @@ export const lockKeyInput = <Row>(
25
25
  const named = plan.where.find((predicate) => predicate.column === entity.$tenantColumn)?.value;
26
26
  return `${entity.$table}:${typeof named === 'string' ? named : '-'}:${key}`;
27
27
  };
28
+
29
+ /**
30
+ * How many keys one `lockKeys` call may hold: Postgres sizes its shared lock table at
31
+ * `max_locks_per_transaction` (default 64) per connection, and a transaction past it is
32
+ * `out of shared memory` for every session on the server, not only this one.
33
+ */
34
+ export const MAX_LOCK_KEYS = 64;
35
+
36
+ /**
37
+ * `lockKeys`' inputs: each key exactly as `lockKey` spells it (same table, tenant and hashing
38
+ * input), duplicates dropped, SORTED — so two callers naming overlapping keys in any order take
39
+ * them in one global order, and neither can hold one the other waits on while waiting itself.
40
+ */
41
+ export const lockKeysInput = <Row>(
42
+ entity: EntityCore<Row>,
43
+ keys: readonly string[],
44
+ options: RepoOptions | undefined,
45
+ ): readonly string[] => {
46
+ assert(
47
+ keys.length > 0,
48
+ `${entity.$name}.lockKeys() was given no keys, so it would serialise nothing while reading as a lock`,
49
+ `db.${entity.$name}.lockKeys(['from:' + fromId, 'to:' + toId], fn) # name every key the work touches`,
50
+ );
51
+ const inputs = [...new Set(keys.map((key) => lockKeyInput(entity, key, options)))].sort();
52
+ assert(
53
+ inputs.length <= MAX_LOCK_KEYS,
54
+ `${entity.$name}.lockKeys() was given ${inputs.length} keys; past ${MAX_LOCK_KEYS} one transaction can exhaust the server's shared lock table`,
55
+ `db.${entity.$name}.lockKey('batch:' + batchId, fn) # one coarser key for the whole batch`,
56
+ );
57
+ return inputs;
58
+ };
59
+
60
+ /**
61
+ * Every input held, in the order given, for one `fn`: each lock taken inside the previous one's
62
+ * transaction, so the first opens it and the rest join it — the shape a store with only a
63
+ * one-key lock (`defineDriver`'s `lockKey`, the memory driver's queue) builds `lockKeys` from.
64
+ */
65
+ export const holdInOrder = <R, T>(
66
+ inputs: readonly string[],
67
+ lockOne: (input: string, outer: T | undefined, body: (tx: T) => Promise<R>) => Promise<R>,
68
+ fn: (tx: T) => Promise<R> | R,
69
+ outer?: T,
70
+ ): Promise<R> => {
71
+ const [first, ...rest] = inputs;
72
+ assert(
73
+ first !== undefined,
74
+ 'holdInOrder() was given no inputs, so it would hold nothing',
75
+ 'holdInOrder(lockKeysInput(entity, keys, options), lockOne, fn) # lockKeysInput refuses an empty list first',
76
+ );
77
+ return lockOne(first, outer, async (tx) =>
78
+ rest.length === 0 ? fn(tx) : holdInOrder(rest, lockOne, fn, tx),
79
+ );
80
+ };
@@ -3,9 +3,12 @@
3
3
 
4
4
  import { EntityError } from './entity-error';
5
5
 
6
- export const lockUnsupported = (entityName: string, method: 'lock' | 'lockKey'): EntityError =>
6
+ export const lockUnsupported = (
7
+ entityName: string,
8
+ method: 'lock' | 'lockKey' | 'lockKeys',
9
+ ): EntityError =>
7
10
  new EntityError({
8
11
  code: 'X_LOCK_UNSUPPORTED',
9
12
  cause: `${entityName}.${method}() reached a repository that does not implement it: a hand-written driver, which the contract lets omit both`,
10
- fix: 'database(entities, { driver: postgresDriver() }) # the shipped driver has both; a hand-written Repo implements lock and lockKey',
13
+ fix: 'database(entities, { driver: postgresDriver() }) # the shipped driver has both; a hand-written Repo implements lock, lockKey and lockKeys',
11
14
  });
@@ -0,0 +1,157 @@
1
+ // Single responsibility: what a multi-measure aggregate MEANS — the measure shape, which ones a call
2
+ // may ask for, and how each is judged before either driver builds anything. Both drivers plan from
3
+ // here, so `aggregate({ … })` is the same refusal and the same answer against memory and Postgres.
4
+
5
+ import { type AggregateFn, aggregateColumnOf } from './aggregate';
6
+ import { columnFor } from './column';
7
+ import type { EntityCore } from './entity';
8
+ import { EntityError } from './errors';
9
+ import { screenPredicates } from './predicate-screen';
10
+ import type { FindManyArgs } from './repo';
11
+ import type { Predicate } from './tenancy';
12
+ import type { AnyColumn } from './types';
13
+
14
+ /** `count`, then the four `aggregate.ts` already defines. A sixth is a member there first. */
15
+ export type MeasureFn = 'count' | AggregateFn;
16
+
17
+ /**
18
+ * One output of `aggregate({ name: measure })`. `count` without a column is `count(*)`; with one it
19
+ * counts that column's non-null values. `where` narrows THIS measure only — `count(*) filter (where
20
+ * …)` — inside the rows the chain already matched, so tenancy and soft delete still bound it.
21
+ */
22
+ export interface Measure {
23
+ readonly fn: MeasureFn;
24
+ readonly column?: string;
25
+ readonly where?: readonly Predicate[];
26
+ }
27
+
28
+ export type MeasureMap = Readonly<Record<string, Measure>>;
29
+
30
+ /** `countBy(column, args, { where })`: each group's count of the rows that satisfy `where`. */
31
+ export interface CountByOptions {
32
+ readonly where?: readonly Predicate[];
33
+ }
34
+
35
+ /** The repository member both drivers add — optional on `Repo`, so a hand-written driver compiles. */
36
+ export interface MeasureReads {
37
+ aggregates(measures: MeasureMap, args?: FindManyArgs): Promise<Readonly<Record<string, unknown>>>;
38
+ }
39
+
40
+ /**
41
+ * How many measures one statement carries. A dashboard tile asks for a handful; past this it is a
42
+ * report, and the select list of one statement is not where a report is built.
43
+ */
44
+ export const MAX_MEASURES = 32;
45
+
46
+ const FNS: ReadonlySet<unknown> = new Set<MeasureFn>(['count', 'sum', 'avg', 'min', 'max']);
47
+
48
+ /** A measure judged: its name, its function, the column it reads (absent for `count(*)`). */
49
+ export interface PlannedMeasure {
50
+ readonly name: string;
51
+ readonly fn: MeasureFn;
52
+ readonly property: string | undefined;
53
+ readonly column: AnyColumn | undefined;
54
+ readonly where: readonly Predicate[];
55
+ }
56
+
57
+ const EXAMPLE = "aggregate({ total: { fn: 'count' }, paid: { fn: 'sum', column: '<column>' } })";
58
+
59
+ const refused = <Row>(entity: EntityCore<Row>, cause: string, fix?: string): EntityError =>
60
+ new EntityError({
61
+ code: 'X_AGGREGATE_UNSUPPORTED',
62
+ cause: `${entity.$name}.aggregate(…): ${cause}`,
63
+ fix: fix ?? `${entity.$name}.${EXAMPLE}`,
64
+ });
65
+
66
+ /** A value from an app, rendered so building the message cannot throw instead of refusing. */
67
+ const shown = (value: unknown): string =>
68
+ typeof value === 'string' ? `'${value}'` : value === null ? 'null' : `a ${typeof value}`;
69
+
70
+ /**
71
+ * Filters judged as the chain's own are: an operator outside the vocabulary, a whole money value.
72
+ * A column the entity never declared is refused too — `physicalName` would refuse it in Postgres
73
+ * and memory would read `undefined` as NULL and answer zero.
74
+ */
75
+ export const screenMeasureFilter = <Row>(
76
+ entity: EntityCore<Row>,
77
+ where: readonly Predicate[],
78
+ ): readonly Predicate[] => {
79
+ if (!Array.isArray(where)) {
80
+ throw refused(entity, `a measure's where is ${shown(where)}, not a list of predicates`);
81
+ }
82
+ screenPredicates(entity, where);
83
+ for (const predicate of where) {
84
+ const [property = predicate.column] = predicate.column.split('.');
85
+ if (predicate.op !== 'matches' && columnFor(entity.$columns, property) === undefined) {
86
+ throw refused(
87
+ entity,
88
+ `a measure filters on "${predicate.column}", which ${entity.$name} does not declare`,
89
+ `x entities show ${entity.$name} --json # the columns a filter can name`,
90
+ );
91
+ }
92
+ }
93
+ return where;
94
+ };
95
+
96
+ const planOne = <Row>(entity: EntityCore<Row>, name: string, measure: unknown): PlannedMeasure => {
97
+ if (typeof measure !== 'object' || measure === null) {
98
+ throw refused(entity, `measure '${name}' is ${shown(measure)}, not { fn, column?, where? }`);
99
+ }
100
+ const { fn, column, where = [] } = measure as Partial<Measure>;
101
+ if (!FNS.has(fn)) {
102
+ throw refused(
103
+ entity,
104
+ `measure '${name}' names fn ${shown(fn)} — one of: ${[...FNS].join(', ')}`,
105
+ );
106
+ }
107
+ const filter = screenMeasureFilter(entity, where);
108
+ if (fn === 'count') {
109
+ if (column === undefined)
110
+ return { name, fn, property: undefined, column: undefined, where: filter };
111
+ const declared = columnFor(entity.$columns, column);
112
+ if (declared === undefined) {
113
+ throw refused(
114
+ entity,
115
+ `measure '${name}' counts "${column}", which ${entity.$name} does not declare`,
116
+ );
117
+ }
118
+ return { name, fn, property: column, column: declared, where: filter };
119
+ }
120
+ if (typeof column !== 'string') {
121
+ throw refused(entity, `measure '${name}' is ${String(fn)} with no column`);
122
+ }
123
+ // The same judgement `sum('title')` gets, so a kind with no aggregate is one refusal everywhere.
124
+ const declared = aggregateColumnOf(entity, fn as AggregateFn, column);
125
+ return { name, fn: fn as AggregateFn, property: column, column: declared, where: filter };
126
+ };
127
+
128
+ /** Every measure judged, in the order the caller wrote them — refused before any row is read. */
129
+ export const planMeasures = <Row>(
130
+ entity: EntityCore<Row>,
131
+ measures: MeasureMap,
132
+ ): readonly PlannedMeasure[] => {
133
+ if (typeof measures !== 'object' || measures === null || Array.isArray(measures)) {
134
+ throw refused(entity, `the measures are ${shown(measures)}, not { name: measure }`);
135
+ }
136
+ const names = Object.keys(measures);
137
+ if (names.length === 0) throw refused(entity, 'no measures — there is nothing to compute');
138
+ if (names.length > MAX_MEASURES) {
139
+ throw refused(
140
+ entity,
141
+ `${names.length} measures in one statement, past ${MAX_MEASURES}`,
142
+ `${entity.$name}.aggregate({ … }) # split into calls of at most ${MAX_MEASURES} measures`,
143
+ );
144
+ }
145
+ return names.map((name) => planOne(entity, name, measures[name]));
146
+ };
147
+
148
+ /**
149
+ * A repository with no `aggregates` — a hand-written driver, which the contract lets omit it. The
150
+ * fix is the equivalent the contract does guarantee: one aggregate per call.
151
+ */
152
+ export const measuresUnsupported = (entityName: string): EntityError =>
153
+ new EntityError({
154
+ code: 'X_AGGREGATE_UNSUPPORTED',
155
+ cause: `${entityName}.aggregate({ … }) reached a repository that does not implement aggregates(measures, args): a hand-written driver, which the contract lets omit it`,
156
+ fix: `${entityName}.count() / .sum('<column>') # one aggregate per call; or a driver that implements aggregates (postgresDriver(), memoryDriver())`,
157
+ });
@@ -5,9 +5,10 @@
5
5
 
6
6
  import { aggregateColumnOf, assertOneUnit, type MoneyUnit } from './aggregate';
7
7
  import { foldAggregate } from './aggregate-fold';
8
- import { countsFrom, groupColumnOf } from './count-by';
9
8
  import { valueAt } from './cursor';
10
9
  import type { EntityCore } from './entity';
10
+ import type { CountByOptions, MeasureReads } from './measures';
11
+ import { memoryCountBy, memoryMeasures } from './memory-measures';
11
12
  import type { FindManyArgs, Repo } from './repo';
12
13
  import type { QueryPlan } from './tenancy';
13
14
  import { bucketStart, type SeriesPoint, seriesFrom, seriesPlanOf } from './time-bucket';
@@ -21,7 +22,8 @@ export type MemorySelect<Row> = (
21
22
  type AggregateReads<Row> = Pick<
22
23
  Required<Repo<Row>>,
23
24
  'aggregate' | 'approximateCount' | 'countBy' | 'series'
24
- >;
25
+ > &
26
+ MeasureReads;
25
27
 
26
28
  const moneyUnitOf = (value: unknown): MoneyUnit | undefined => {
27
29
  if (typeof value !== 'object' || value === null) return undefined;
@@ -52,20 +54,11 @@ export const memoryAggregates = <Row>(
52
54
  return select(args, 'approximateCount').found.length;
53
55
  },
54
56
 
55
- async countBy(column, args = {}) {
56
- // Refused before a row is read, and by the same function the Postgres driver calls: a column
57
- // a map cannot be keyed by is that mistake in both drivers or in neither.
58
- groupColumnOf(entity, column, 'countBy');
59
- const { found } = select(args, 'countBy');
60
- const groups = new Map<unknown, number>();
61
- for (const row of found) {
62
- // `?? null`, so a property this row never carried lands in the same group Postgres puts a
63
- // NULL row in — and `0`, `''` and `false` stay the values they are.
64
- const value = valueAt(row, column) ?? null;
65
- groups.set(value, (groups.get(value) ?? 0) + 1);
66
- }
67
- return countsFrom(entity, column, 'countBy', [...groups]);
68
- },
57
+ // The filtered form is the general one: no `where` counts every row, as before.
58
+ countBy: (column, args = {}, options: CountByOptions = {}) =>
59
+ memoryCountBy(entity, select, column, args, options),
60
+
61
+ ...memoryMeasures(entity, select),
69
62
 
70
63
  async series(spec, args = {}) {
71
64
  const plan = seriesPlanOf(entity, spec);
@@ -0,0 +1,34 @@
1
+ // Single responsibility: the in-memory driver's `latestBy` — the plan `latest-by.ts` builds, read
2
+ // through the driver's own `select` (scope, tenancy, soft delete, the plan's order) and folded to
3
+ // the first rows of each group by the same function the paged fallback uses. Never a second meaning.
4
+
5
+ import { projectRow } from './driver-rows';
6
+ import type { EntityCore } from './entity';
7
+ import {
8
+ assertGroupBound,
9
+ firstPerGroup,
10
+ groupOf,
11
+ groupsIn,
12
+ type LatestBySpec,
13
+ latestArgs,
14
+ latestPlanOf,
15
+ } from './latest-by';
16
+ import type { MemorySelect } from './memory-aggregates';
17
+ import type { LatestByRead } from './pg-latest-by';
18
+
19
+ export const memoryLatestBy = <Row>(
20
+ entity: EntityCore<Row>,
21
+ select: MemorySelect<Row>,
22
+ ): LatestByRead<Row> => ({
23
+ async latestBy(spec: LatestBySpec, args = {}) {
24
+ const op = 'latestBy';
25
+ // Judged by the function the Postgres driver calls, before a row is read: a refusal there is
26
+ // the same refusal here.
27
+ const plan = latestPlanOf(entity, spec, args, op);
28
+ const { found } = select(latestArgs(entity, spec, args), op);
29
+ const group = groupOf(entity, spec);
30
+ const kept = firstPerGroup(found, group, spec.perGroup);
31
+ assertGroupBound(entity, spec, groupsIn(kept, group));
32
+ return kept.map((row) => projectRow(entity, plan, row));
33
+ },
34
+ });
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { asyncContext } from '@ultimat3/core';
6
6
  import { driverError } from '@ultimat3/db';
7
+ import { holdInOrder } from './lock-key';
7
8
  import { undoingBatch } from './memory-batch';
8
9
  import { memoryJournal, memoryRoot, refuseIfMemoryTxClosed } from './memory-journal';
9
10
  import { memoryTransactor } from './memory-transactor';
@@ -24,6 +25,15 @@ export interface MemoryLocks {
24
25
  * holder, runs `work`, holds nothing after it. No wait when this chain or `outer` holds the key.
25
26
  */
26
27
  turn<R>(key: string, outer: Tx | undefined, work: () => R): Promise<R>;
28
+ /**
29
+ * `work` under every key, in the order given (`lockKeysInput` sorts them), in ONE transaction:
30
+ * the first key's `run` opens it and each later one joins it, so all are held to its end.
31
+ */
32
+ runAll<R>(
33
+ keys: readonly string[],
34
+ outer: Tx | undefined,
35
+ work: (tx: Tx) => Promise<R> | R,
36
+ ): Promise<R>;
27
37
  }
28
38
 
29
39
  /** What this async chain holds, and the transaction its innermost lock runs in. */
@@ -100,7 +110,7 @@ export const memoryLocks = (waitMs: number = MEMORY_LOCK_WAIT_MS): MemoryLocks =
100
110
  chain?.names.has(name) === true ||
101
111
  (outer !== undefined && heldByTx.get(memoryRoot(outer))?.has(name)) === true;
102
112
 
103
- return {
113
+ const locks: MemoryLocks = {
104
114
  async run(key, given, work) {
105
115
  const name = `${instance}:${key}`;
106
116
  const chain = heldByChain.get();
@@ -152,5 +162,9 @@ export const memoryLocks = (waitMs: number = MEMORY_LOCK_WAIT_MS): MemoryLocks =
152
162
  release();
153
163
  }
154
164
  },
165
+
166
+ runAll: (keys, outer, work) =>
167
+ holdInOrder(keys, (key, tx, body) => locks.run(key, tx, body), work, outer),
155
168
  };
169
+ return locks;
156
170
  };
@@ -18,6 +18,7 @@ import { likeMatches } from './like';
18
18
  import { DECIMAL_TEXT, numericOrder } from './numeric-compare';
19
19
  import { operatorUnknown } from './operator';
20
20
  import type { Predicate } from './tenancy';
21
+ import { isTextContains, textContainsMatches } from './text-contains';
21
22
  import type { ColumnKind } from './types';
22
23
 
23
24
  const sign = <T extends number | bigint | string>(left: T, right: T): number =>
@@ -208,6 +209,7 @@ export const matchesPredicate = <Row>(
208
209
  // element containment, and those are two different operators that happen to share a symbol.
209
210
  // A NULL column value matches nothing, which is what the SQL answers too.
210
211
  case 'contains':
212
+ if (isTextContains(kind)) return textContainsMatches(actual, predicate.value);
211
213
  return !rowIsNull && containsBy(kind, actual, predicate.value);
212
214
  case 'contained-by':
213
215
  return !rowIsNull && containsBy(kind, predicate.value, actual);