@ultimat3/entity 31.9.0 → 31.11.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 (70) hide show
  1. package/CLAUDE.md +2 -0
  2. package/README.md +70 -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 +8 -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 +34 -0
  56. package/src/repo.ts +34 -1
  57. package/src/row-observer.ts +29 -4
  58. package/src/sealed-column.ts +20 -0
  59. package/src/sealed-repo.ts +30 -2
  60. package/src/search-repo.ts +20 -2
  61. package/src/table-locks.ts +16 -1
  62. package/src/tenant-index.ts +84 -9
  63. package/src/text-contains.ts +53 -0
  64. package/src/types.ts +9 -22
  65. package/src/unique-constraints.ts +3 -1
  66. package/src/update-many-send.ts +32 -1
  67. package/src/update-many.ts +6 -1
  68. package/src/version-lock-errors.ts +42 -0
  69. package/src/version-lock.ts +177 -0
  70. package/src/write-where.ts +3 -0
package/src/index-name.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // What an index is CALLED. Split out of `entity.ts` at the 500-line ceiling, and it is one job:
2
- // two indexes that differ only in their predicate, their direction or their access method must not
3
- // share a name, and no name may cross the 63 bytes Postgres silently truncates at.
2
+ // two indexes that differ only in their predicate, their direction, their access method or a key
3
+ // part must not share a name, and no name may cross the 63 bytes Postgres silently truncates at.
4
4
 
5
5
  import type { IndexMethod } from '@ultimat3/db';
6
6
  import { invariantViolated } from './errors';
@@ -21,15 +21,32 @@ const indexDiscriminator = (
21
21
  order: string | undefined,
22
22
  where: string | null,
23
23
  using: string | undefined,
24
+ keys: string,
24
25
  ): string =>
25
26
  new Bun.CryptoHasher('sha256')
26
27
  // The method is APPENDED only when one was declared, never as an empty field: every name this
27
28
  // function has ever minted for a partial or ordered index is therefore unchanged by the method
28
- // existing, and an index that declares no method is byte-identical to the one it was.
29
- .update(`${order ?? ''}|${where ?? ''}${using === undefined ? '' : `|${using}`}`)
29
+ // existing, and an index that declares no method is byte-identical to the one it was. The key
30
+ // parts follow the same rule (`keyPartsText`).
31
+ .update(`${order ?? ''}|${where ?? ''}${using === undefined ? '' : `|${using}`}${keys}`)
30
32
  .digest('hex')
31
33
  .slice(0, 8);
32
34
 
35
+ /** The four key parts past a column list (`IndexKeyParts` in `@ultimat3/db`), as named. */
36
+ export interface IndexNameKeys {
37
+ readonly expression?: string | undefined;
38
+ readonly orders?: readonly ('asc' | 'desc' | null)[] | undefined;
39
+ readonly include?: readonly string[] | undefined;
40
+ readonly operatorClass?: string | undefined;
41
+ }
42
+
43
+ /** `''` when none is declared — so every name minted before they existed is unchanged. */
44
+ const keyPartsText = (keys: IndexNameKeys): string => {
45
+ const { expression, orders, include, operatorClass } = keys;
46
+ if ([expression, orders, include, operatorClass].every((part) => part === undefined)) return '';
47
+ return `|${JSON.stringify([expression ?? null, orders ?? null, include ?? null, operatorClass ?? null])}`;
48
+ };
49
+
33
50
  /**
34
51
  * `<table>_<columns>_idx`, plus a discriminator when — and only when — the index carries a
35
52
  * predicate, a direction or a non-default access method.
@@ -65,13 +82,15 @@ export const indexName = (
65
82
  order?: string | undefined,
66
83
  where: string | null = null,
67
84
  using?: IndexMethod | undefined,
85
+ keys: IndexNameKeys = {},
68
86
  ): string => {
69
87
  const suffix = unique ? 'key' : 'idx';
70
88
  const base = `${table}_${columns.join('_')}`;
71
- const plain = order === undefined && where === null && using === undefined;
89
+ const parts = keyPartsText(keys);
90
+ const plain = order === undefined && where === null && using === undefined && parts === '';
72
91
  const name = plain
73
92
  ? `${base}_${suffix}`
74
- : `${base}_${indexDiscriminator(order, where, using)}_${suffix}`;
93
+ : `${base}_${indexDiscriminator(order, where, using, parts)}_${suffix}`;
75
94
  const bytes = identifierBytes(name);
76
95
  if (bytes <= MAX_IDENTIFIER_BYTES) return name;
77
96
  throw invariantViolated(
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ export type { Infer } from '@ultimat3/schema';
12
12
  export { t } from '@ultimat3/schema';
13
13
  export type { AggregateFn } from './aggregate';
14
14
  export { AVG_SCALE } from './aggregate';
15
+ export { ALL_TRUNCATED } from './all-truncated';
15
16
  // Append-only entities: the same kind of seam, wrapped OUTSIDE `sealedRepo` by both drivers — a
16
17
  // driver written outside this package returns through `appendOnlyRepo(entity, sealedRepo(…))`.
17
18
  export type { AppendOnlySource } from './append-only';
@@ -74,10 +75,17 @@ export { iff } from './expr';
74
75
  /** The two DECLARED capabilities' refusals — a third-party driver raises the same ones. */
75
76
  export type { HistoryColumns, HistoryEntity, HistoryInit } from './history';
76
77
  export type { HistoryRecord, HistoryVersion } from './history-order';
78
+ export { purgingHistory } from './history-purge';
77
79
  export { history } from './history-read';
78
80
  export type { IndexInit } from './index-init';
79
81
  export type { Invariant, InvariantDef, InvariantKind } from './invariants';
80
82
  export { assertInvariants, invariant, MAX_ASSERTED_ROWS } from './invariants';
83
+ export type { LatestByOptions, LatestBySpec, ReadLatest } from './latest-by';
84
+ export { MAX_LATEST_GROUPS } from './latest-by';
85
+ // The lockKeys ceiling, exported for the same reason the page bounds are: one number, one place.
86
+ export { MAX_LOCK_KEYS } from './lock-key';
87
+ export type { CountByOptions, Measure, MeasureFn, MeasureMap } from './measures';
88
+ export { MAX_MEASURES } from './measures';
81
89
  export { memoryJournal } from './memory-journal';
82
90
  // How Postgres compares two values of one column, decided by the column's declared KIND. Exported
83
91
  // because `@ultimat3/query`'s matcher and in-memory source ask the same question — and a second
@@ -120,6 +128,9 @@ export type { Preloaded, ReadBuilder, Table } from './query';
120
128
  export { tableFor } from './query';
121
129
  export type { ChainWrites, Returned, TableBulkWrites, Unreturned } from './query-write';
122
130
  export type {
131
+ ChainMeasure,
132
+ MeasureFilter,
133
+ MeasureValueOf,
123
134
  ReadAggregates,
124
135
  SeriesOptions,
125
136
  SeriesValueOf,
@@ -133,6 +144,7 @@ export { ENTITY_BRAND, recordProjection } from './record-projection';
133
144
  export { recordProjectionForTable, recordTypeForTable } from './record-table';
134
145
  export type {
135
146
  ColumnDescription,
147
+ CoveredIndex,
136
148
  EntityDescription,
137
149
  IndexDescription,
138
150
  InvariantDescription,
@@ -230,6 +242,7 @@ export {
230
242
  } from './tenancy';
231
243
  // The scaffolded handle's driver under test: memory until `setDbClient` installs a client.
232
244
  export { testDriver } from './test-driver';
245
+ export { trigramDeclaration } from './text-contains';
233
246
  export type { SeriesPoint, SeriesSpec, SeriesUnit, SeriesValue } from './time-bucket';
234
247
  export { bucketStart, SERIES_UNITS } from './time-bucket';
235
248
  export type { Move } from './transition';
@@ -0,0 +1,93 @@
1
+ // Single responsibility: compile a newest-row-per-group plan (`latest-by.ts`) into ONE statement.
2
+ // No keys: `select distinct on (group) … order by group, order…, key`. Keys (a preload's parents):
3
+ // the keys as a typed source, `cross join lateral` a `limit n` read per key — n rows per parent
4
+ // off an index, never every row of every parent. Every identifier is the entity's; values bind.
5
+
6
+ import { identifier, join, type SqlFragment, sql } from '@ultimat3/db';
7
+ import { columnFor } from './column';
8
+ import type { EntityCore } from './entity';
9
+ import { allColumns, columnsOf, physicalName } from './pg-row';
10
+ import { conditions, orderSql, type ReadShape } from './pg-sql';
11
+ import type { QueryPlan } from './tenancy';
12
+
13
+ /**
14
+ * The aliases written here. Upper case, which no physical column can be (`seekAlias` and
15
+ * `pg-update-many-sql.ts` rely on the same rule), so a scope's unqualified `"org_id" = $n` inside
16
+ * the lateral read can never resolve to one of them.
17
+ */
18
+ const KEYS = identifier('K$LB');
19
+ const KEY = identifier('V$LB');
20
+ const PICKED = identifier('L$LB');
21
+
22
+ /**
23
+ * The columns a row is read with: every one, or the projection plus what the read itself needs —
24
+ * the primary key, the group and the order keys, exactly as a page's projection carries its cursor
25
+ * keys. Physical names, one list, so the lateral's output and the outer `select` agree.
26
+ */
27
+ const projectionOf = <Row>(entity: EntityCore<Row>, plan: QueryPlan): readonly string[] => {
28
+ if (plan.select === undefined) return allColumns(entity);
29
+ const wanted = new Set([
30
+ ...plan.select,
31
+ ...entity.$primaryKey,
32
+ ...plan.orderBy.map((entry) => entry.column.split('.')[0] ?? entry.column),
33
+ ]);
34
+ return [...wanted].flatMap((property) => {
35
+ const column = columnFor(entity.$columns, property);
36
+ return column === undefined ? [] : columnsOf(property, column);
37
+ });
38
+ };
39
+
40
+ /**
41
+ * Every matched group's first row. `plan.orderBy` leads with the group (`latestPlanOf`), which is
42
+ * what `DISTINCT ON` requires of the `order by`; `limit` is one group past the bound, whose
43
+ * presence is the refusal (`assertGroupBound`).
44
+ */
45
+ export const distinctOnStatement = <Row>(
46
+ entity: EntityCore<Row>,
47
+ plan: QueryPlan,
48
+ shape: ReadShape,
49
+ limit: number,
50
+ ): SqlFragment => {
51
+ const [group] = plan.orderBy;
52
+ const groupColumn = identifier(physicalName(entity, group?.column ?? ''));
53
+ return sql`select distinct on (${groupColumn}) ${join(
54
+ projectionOf(entity, plan).map(identifier),
55
+ )} from ${identifier(entity.$table)} where ${conditions(entity, plan, shape)} order by ${orderSql(
56
+ entity,
57
+ plan.orderBy,
58
+ )} limit ${limit}`;
59
+ };
60
+
61
+ /**
62
+ * `perGroup` rows for each key. The keys are a source typed by the TABLE — a `where false` head on
63
+ * the group column, `union all` one bound `select $n` per key — because a bare bound list resolves
64
+ * as `text` and `uuid = text` refuses the join (measured in sweep 5a, `pg-update-many-sql.ts`).
65
+ * The lateral read is the plan minus its leading group key (constant inside it), under the plan's
66
+ * scope, which already carries the `in` over these keys. The outer order restates the plan's, so
67
+ * the rows arrive grouped and in order whatever join the planner picks.
68
+ */
69
+ export const lateralStatement = <Row>(
70
+ entity: EntityCore<Row>,
71
+ plan: QueryPlan,
72
+ shape: ReadShape,
73
+ keys: readonly unknown[],
74
+ perGroup: number,
75
+ ): SqlFragment => {
76
+ const [group, ...within] = plan.orderBy;
77
+ const groupName = physicalName(entity, group?.column ?? '');
78
+ const groupColumn = identifier(groupName);
79
+ const table = identifier(entity.$table);
80
+ const columns = projectionOf(entity, plan);
81
+ const head = sql`select ${groupColumn} as ${KEY} from ${table} where false`;
82
+ const source = join([head, ...keys.map((key) => sql`select ${key}`)], ' union all ');
83
+ const inner = sql`select ${join(columns.map(identifier))} from ${table} where ${groupColumn} = ${KEYS}.${KEY} and ${conditions(
84
+ entity,
85
+ plan,
86
+ shape,
87
+ )} order by ${orderSql(entity, within)} limit ${perGroup}`;
88
+ return sql`select ${join(columns.map((column) => sql`${PICKED}.${identifier(column)}`))} from (${source}) as ${KEYS} cross join lateral (${inner}) as ${PICKED} order by ${orderSql(
89
+ entity,
90
+ plan.orderBy,
91
+ PICKED,
92
+ )}`;
93
+ };
@@ -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
  });