@ultimat3/entity 31.9.0 → 31.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CLAUDE.md +1 -0
  2. package/README.md +48 -0
  3. package/package.json +5 -5
  4. package/src/aggregate.ts +1 -1
  5. package/src/all-truncated.ts +33 -0
  6. package/src/append-only.ts +8 -1
  7. package/src/bulk-write.ts +3 -0
  8. package/src/counter-observed.ts +199 -0
  9. package/src/database.ts +4 -2
  10. package/src/declared-index-keys.ts +65 -0
  11. package/src/declared-index.ts +6 -1
  12. package/src/define-driver.ts +24 -2
  13. package/src/describe.ts +6 -0
  14. package/src/driver-counters.ts +21 -0
  15. package/src/driver-repo-reads.ts +71 -5
  16. package/src/driver-repo-writes.ts +23 -1
  17. package/src/driver-versioned-write.ts +99 -0
  18. package/src/entity-error.ts +4 -0
  19. package/src/entity-indexes.ts +118 -0
  20. package/src/entity.ts +20 -49
  21. package/src/history-purge.ts +15 -0
  22. package/src/index-def.ts +35 -0
  23. package/src/index-identity.ts +5 -0
  24. package/src/index-init.ts +13 -1
  25. package/src/index-name.ts +25 -6
  26. package/src/index.ts +13 -0
  27. package/src/latest-by-sql.ts +93 -0
  28. package/src/latest-by.ts +249 -0
  29. package/src/lock-key.ts +56 -3
  30. package/src/lock-unsupported.ts +5 -2
  31. package/src/measures.ts +157 -0
  32. package/src/memory-aggregates.ts +9 -16
  33. package/src/memory-latest-by.ts +34 -0
  34. package/src/memory-lock.ts +15 -1
  35. package/src/memory-match.ts +2 -0
  36. package/src/memory-measures.ts +75 -0
  37. package/src/memory-observed.ts +3 -1
  38. package/src/memory-repo.ts +17 -1
  39. package/src/memory-update.ts +7 -1
  40. package/src/pg-aggregates.ts +9 -3
  41. package/src/pg-bulk-repo.ts +1 -1
  42. package/src/pg-driver.ts +13 -1
  43. package/src/pg-latest-by.ts +57 -0
  44. package/src/pg-lock.ts +24 -4
  45. package/src/pg-measures.ts +64 -0
  46. package/src/pg-sql-aggregate.ts +9 -3
  47. package/src/pg-sql-measures.ts +102 -0
  48. package/src/pg-sql.ts +37 -6
  49. package/src/pg-update-many-sql.ts +44 -1
  50. package/src/pg-write-sql.ts +32 -4
  51. package/src/preload-ceiling.ts +73 -7
  52. package/src/preload.ts +17 -1
  53. package/src/query.ts +14 -1
  54. package/src/read-aggregates.ts +87 -3
  55. package/src/registry.ts +29 -0
  56. package/src/repo.ts +34 -1
  57. package/src/row-observer.ts +29 -4
  58. package/src/sealed-repo.ts +30 -2
  59. package/src/search-repo.ts +20 -2
  60. package/src/table-locks.ts +16 -1
  61. package/src/tenant-index.ts +84 -9
  62. package/src/text-contains.ts +53 -0
  63. package/src/types.ts +2 -22
  64. package/src/unique-constraints.ts +3 -1
  65. package/src/update-many-send.ts +32 -1
  66. package/src/update-many.ts +6 -1
  67. package/src/version-lock-errors.ts +42 -0
  68. package/src/version-lock.ts +177 -0
  69. package/src/write-where.ts +3 -0
@@ -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);
@@ -0,0 +1,75 @@
1
+ // Single responsibility: the in-memory driver's `aggregates(measures)` and the filtered `countBy` —
2
+ // each measure folded over the rows its own filter keeps, by the same `matchesPredicate` the read
3
+ // path filters with and the same `foldAggregate` `aggregate()` answers with.
4
+
5
+ import { foldAggregate } from './aggregate-fold';
6
+ import { countsFrom, groupColumnOf } from './count-by';
7
+ import { valueAt } from './cursor';
8
+ import type { EntityCore } from './entity';
9
+ import {
10
+ type CountByOptions,
11
+ type MeasureReads,
12
+ type PlannedMeasure,
13
+ planMeasures,
14
+ screenMeasureFilter,
15
+ } from './measures';
16
+ import { matchesPredicate } from './memory-match';
17
+ import type { FindManyArgs } from './repo';
18
+ import type { Predicate } from './tenancy';
19
+
20
+ /** `memoryRepo`'s own read: the plan built and guarded, the visible rows it matches. */
21
+ type MemorySelect<Row> = (args: FindManyArgs, operation: string) => { found: Row[] };
22
+
23
+ const keeps =
24
+ <Row>(entity: EntityCore<Row>, where: readonly Predicate[]) =>
25
+ (row: Row): boolean =>
26
+ where.every((predicate) => matchesPredicate(entity, row, predicate));
27
+
28
+ const measureOf = <Row>(entity: EntityCore<Row>, measure: PlannedMeasure, rows: readonly Row[]) => {
29
+ const kept = measure.where.length === 0 ? rows : rows.filter(keeps(entity, measure.where));
30
+ const { property, column } = measure;
31
+ if (measure.fn === 'count') {
32
+ if (property === undefined) return kept.length;
33
+ // `count(col)` counts non-null values; `?? null` reads an absent property as the NULL it is.
34
+ return kept.filter((row) => (valueAt(row, property) ?? null) !== null).length;
35
+ }
36
+ return foldAggregate(entity, measure.fn, property ?? '', column?.$meta.kind ?? 'integer', kept);
37
+ };
38
+
39
+ export const memoryMeasures = <Row>(
40
+ entity: EntityCore<Row>,
41
+ select: MemorySelect<Row>,
42
+ ): MeasureReads => ({
43
+ async aggregates(measures, args = {}) {
44
+ const planned = planMeasures(entity, measures);
45
+ const { found } = select(args, 'aggregate');
46
+ return Object.fromEntries(
47
+ planned.map((measure) => [measure.name, measureOf(entity, measure, found)]),
48
+ );
49
+ },
50
+ });
51
+
52
+ /**
53
+ * `countBy` with a filter: every group the chain matched, counting only the rows `where` keeps — so
54
+ * a group none of them satisfy is present with 0, as `count(*) filter (where …)` answers it. That
55
+ * is what makes it not `andWhere(…).countBy(…)`, which drops the group.
56
+ */
57
+ export const memoryCountBy = async <Row>(
58
+ entity: EntityCore<Row>,
59
+ select: MemorySelect<Row>,
60
+ column: string,
61
+ args: FindManyArgs = {},
62
+ options: CountByOptions = {},
63
+ ): Promise<ReadonlyMap<unknown, number>> => {
64
+ groupColumnOf(entity, column, 'countBy');
65
+ const where = screenMeasureFilter(entity, options.where ?? []);
66
+ const { found } = select(args, 'countBy');
67
+ const counted = keeps(entity, where);
68
+ const groups = new Map<unknown, number>();
69
+ for (const row of found) {
70
+ // `?? null`, so a property this row never carried lands in the group Postgres puts NULL in.
71
+ const value = valueAt(row, column) ?? null;
72
+ groups.set(value, (groups.get(value) ?? 0) + (counted(row) ? 1 : 0));
73
+ }
74
+ return countsFrom(entity, column, 'countBy', [...groups]);
75
+ };
@@ -27,6 +27,8 @@ const OPERATIONS = {
27
27
  count: { verb: 'select', rows: one },
28
28
  countBy: { verb: 'select', rows: none },
29
29
  aggregate: { verb: 'select', rows: one },
30
+ aggregates: { verb: 'select', rows: one },
31
+ latestBy: { verb: 'select', rows: listed },
30
32
  series: { verb: 'select', rows: listed },
31
33
  approximateCount: { verb: 'select', rows: one },
32
34
  insert: { verb: 'insert', rows: one },
@@ -45,7 +47,7 @@ const OPERATIONS = {
45
47
  type Operation = keyof typeof OPERATIONS;
46
48
 
47
49
  /** Taken before the body runs, as Postgres answers the lock before the body it guards. */
48
- const LOCKS = ['lock', 'lockKey'] as const;
50
+ const LOCKS = ['lock', 'lockKey', 'lockKeys'] as const;
49
51
 
50
52
  const report = (
51
53
  entity: string,
@@ -18,10 +18,11 @@ import { projectRow } from './driver-rows';
18
18
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
19
19
  import { invariantViolated, notFound } from './errors';
20
20
  import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
21
- import { lockKeyInput } from './lock-key';
21
+ import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
22
22
  import { memoryAggregates } from './memory-aggregates';
23
23
  import { undoingBatch } from './memory-batch';
24
24
  import { memoryJournal } from './memory-journal';
25
+ import { memoryLatestBy } from './memory-latest-by';
25
26
  import { memoryLifecycle } from './memory-lifecycle';
26
27
  import { memoryLocks } from './memory-lock';
27
28
  import { compareByKind, matchesPredicate } from './memory-match';
@@ -43,6 +44,7 @@ import type { QueryPlan } from './tenancy';
43
44
  import { assertRowTenant } from './tenancy';
44
45
  import type { RowPatch, RowWrite } from './types';
45
46
  import { judgeUpdateMany, updateManyPlan } from './update-many';
47
+ import { assertVersionedUpdate } from './version-lock';
46
48
  import { updateWherePlan, writeWherePlan } from './write-where';
47
49
 
48
50
  const field = (row: unknown, property: string): unknown =>
@@ -310,6 +312,8 @@ export const memoryRepo = <Row>(
310
312
  update: writing(async (id, given, options) => {
311
313
  // Here and in `pg-driver.ts`, the one door: a value `insert` refuses, a fragment included.
312
314
  const patch = entity.$parsePatch(given);
315
+ // `mergedRow` does the compare-and-set and the increment (`version-lock.ts`).
316
+ assertVersionedUpdate(entity, patch);
313
317
  addressed(id, options, 'update');
314
318
  return locks.turn(`row:${idStoreKey(id, 'update')}`, options?.tx, () => {
315
319
  const current = addressed(id, options, 'update');
@@ -428,6 +432,7 @@ export const memoryRepo = <Row>(
428
432
  },
429
433
 
430
434
  ...memoryAggregates(entity, select),
435
+ ...memoryLatestBy(entity, select),
431
436
 
432
437
  // Asked before the wait, so another tenant's id never queues behind that tenant's holder, and
433
438
  // again after it, because the row may be gone by then: Postgres re-reads a row it waited for.
@@ -439,6 +444,17 @@ export const memoryRepo = <Row>(
439
444
  );
440
445
  })(),
441
446
 
447
+ // Every key through the one-key queue, sorted, each inside the last: `lockKey`'s spelling.
448
+ lockKeys: (keys, fn, options) =>
449
+ writing(async () =>
450
+ holdInOrder(
451
+ lockKeysInput(entity, keys, options),
452
+ (input, outer, body) => locks.run(`key:${input}`, outer, body),
453
+ fn,
454
+ options?.tx,
455
+ ),
456
+ )(),
457
+
442
458
  lockKey: (key, fn, options) =>
443
459
  writing(async () =>
444
460
  locks.run(`key:${lockKeyInput(entity, key, options)}`, options?.tx, fn),
@@ -10,8 +10,10 @@
10
10
  import { narrowRow } from './columns';
11
11
  import type { EntityCore } from './entity';
12
12
  import { uniqueIndex, uniqueViolation } from './memory-unique';
13
+ import { rowKey } from './row-key';
13
14
  import { advanceVersion } from './search-index-version';
14
15
  import { assertRowTenant } from './tenancy';
16
+ import { versionedMerge } from './version-lock';
15
17
 
16
18
  /**
17
19
  * The patch with every `undefined` property dropped — `bindValues` skips them in Postgres, so a
@@ -34,7 +36,11 @@ export const mergedRow = <Row>(entity: EntityCore<Row>, row: Row, patch: object)
34
36
  const given = defined(patch);
35
37
  const merged = narrowRow<Row>(entity.$columns, Object.assign({}, row, given));
36
38
  // A searchable entity's version moves past the stored one even inside one millisecond.
37
- return advanceVersion(entity, row, merged, (property) => Object.hasOwn(given, property));
39
+ const advanced = advanceVersion(entity, row, merged, (property) =>
40
+ Object.hasOwn(given, property),
41
+ );
42
+ // A declared lock: a patch naming a version the row has left is stale, and every merge counts.
43
+ return versionedMerge(entity, row, given, advanced, (stored) => rowKey(entity, stored));
38
44
  };
39
45
 
40
46
  /**
@@ -9,6 +9,8 @@ import { decodeAggregate } from './aggregate-decode';
9
9
  import { moneyColumns } from './column';
10
10
  import { countsFrom, groupColumnOf, groupValue, MAX_GROUPS } from './count-by';
11
11
  import type { EntityCore } from './entity';
12
+ import { type CountByOptions, type MeasureReads, screenMeasureFilter } from './measures';
13
+ import { postgresMeasures } from './pg-measures';
12
14
  import type { ReadShape } from './pg-sql';
13
15
  import {
14
16
  type AggregateRow,
@@ -30,7 +32,8 @@ import type { MoneyValue } from './types';
30
32
  type AggregateReads<Row> = Pick<
31
33
  Required<Repo<Row>>,
32
34
  'aggregate' | 'approximateCount' | 'countBy' | 'series'
33
- >;
35
+ > &
36
+ MeasureReads;
34
37
 
35
38
  const shapeOf = (args: FindManyArgs): ReadShape => ({
36
39
  includeDeleted: args.includeDeleted === true,
@@ -90,16 +93,19 @@ export const postgresAggregates = <Row>(
90
93
  };
91
94
 
92
95
  return {
93
- async countBy(column, args = {}) {
96
+ ...postgresMeasures(entity, client),
97
+
98
+ async countBy(column, args = {}, options: CountByOptions = {}) {
94
99
  const op = 'countBy';
95
100
  const grouped = groupColumnOf(entity, column, op);
101
+ const where = screenMeasureFilter(entity, options.where ?? []);
96
102
  const plan = readPlan(entity, args, op);
97
103
  // One group past the bound, for the same reason a page reads one row past its limit: the
98
104
  // presence of that group is what says the answer was never going to fit, and `countsFrom`
99
105
  // refuses it rather than hand back a breakdown missing its tail.
100
106
  const rows = await attributed(op, () =>
101
107
  client().query<GroupRow>(
102
- countByStatement(entity, plan, shapeOf(args), column, MAX_GROUPS + 1),
108
+ countByStatement(entity, plan, shapeOf(args), column, MAX_GROUPS + 1, where),
103
109
  ),
104
110
  );
105
111
  return countsFrom(
@@ -154,7 +154,7 @@ export const postgresBulkWrites = <Row>(context: PgWriteContext<Row>): PgBulkWri
154
154
  const returning = updateManyReturns(entity, plan, sink !== undefined);
155
155
  const statements = updateManyStatements(entity, plan, returning);
156
156
  const { count, rows: written } = await attributed('updateMany', () =>
157
- writing(() => sendUpdateMany(entity, statements, returning, client(), pinned)),
157
+ writing(() => sendUpdateMany(entity, statements, returning, client(), pinned, plan)),
158
158
  );
159
159
  if (sink !== undefined && returning) sink(written);
160
160
  return count;
package/src/pg-driver.ts CHANGED
@@ -31,6 +31,7 @@ import { judgedWrite } from './judged-write';
31
31
  import { assertPageBytes } from './page-bytes';
32
32
  import { postgresAggregates } from './pg-aggregates';
33
33
  import { postgresBulkWrites } from './pg-bulk-repo';
34
+ import { postgresLatestBy } from './pg-latest-by';
34
35
  import { postgresLocks } from './pg-lock';
35
36
  import { bindValues, decodeRow, type PhysicalRow, physicalName, sortPrecision } from './pg-row';
36
37
  import { countStatement, type ReadShape, selectStatement } from './pg-sql';
@@ -44,6 +45,7 @@ import { deletionStamp } from './search-index-version';
44
45
  import { writtenRowsSink } from './search-written-rows';
45
46
  import type { QueryPlan } from './tenancy';
46
47
  import { assertRowTenant } from './tenancy';
48
+ import { assertVersionedUpdate, staleOrNotFound, versionOf } from './version-lock';
47
49
  import { taggedWrite } from './write-tag';
48
50
  import { updateWherePlan, writeWherePlan } from './write-where';
49
51
 
@@ -299,6 +301,9 @@ export const postgresRepo = <Row>(
299
301
  // Here and in `memory-repo.ts`, the one door: a value `insert` refuses, a fragment included.
300
302
  const patch = entity.$parsePatch(given);
301
303
  const op = 'update';
304
+ // A declared version lock: the patch carries the version it read (`version-lock.ts`), and
305
+ // `updateStatement` conditions on it and increments it.
306
+ assertVersionedUpdate(entity, patch);
302
307
  const plan = idPlan(entity, id, options, op);
303
308
  // The plan bounds WHICH row is written; the patch decides what it becomes, and a patch
304
309
  // naming another tenant would hand this row away — a leak out of the actor's tenant that no
@@ -318,7 +323,13 @@ export const postgresRepo = <Row>(
318
323
  // the statement inside a transaction the refusal rolls back.
319
324
  return judged(async (send) => {
320
325
  const written = await attributed(op, () => writing(() => send.one<PhysicalRow>(statement)));
321
- if (written === null) throw notFound(entity.$name, id);
326
+ if (written === null) {
327
+ // No row matched: absent, another tenant's, or (versioned) moved past the read version.
328
+ if (versionOf(entity) === null) throw notFound(entity.$name, id);
329
+ throw await staleOrNotFound(entity, id, patch, () =>
330
+ attributed(op, () => one(idPlan(entity, id, options, op), options ?? {})),
331
+ );
332
+ }
322
333
  const after = decodeRow(entity, written);
323
334
  entity.$assert(after);
324
335
  return after;
@@ -383,6 +394,7 @@ export const postgresRepo = <Row>(
383
394
  },
384
395
 
385
396
  ...postgresAggregates(entity, client),
397
+ ...postgresLatestBy(entity, client),
386
398
  ...postgresLocks(entity, config.client, client),
387
399
  };
388
400
  // The one sealing seam, shared with `memoryRepo()`: sealed on the way in, opened on the way out.
@@ -0,0 +1,57 @@
1
+ // Single responsibility: the Postgres driver's `latestBy` — one statement per call (per 500 keys
2
+ // for a preload's parents), weighed and decoded as a page is. What the statement means is
3
+ // `latest-by.ts`'s; how it is spelled is `latest-by-sql.ts`'s. `pg-driver.ts` spreads this in.
4
+
5
+ import { type DbClient, withStatementAttribution } from '@ultimat3/db';
6
+ import { statementChunks } from './batch-read';
7
+ import type { EntityCore } from './entity';
8
+ import { assertGroupBound, type LatestBySpec, latestPlanOf, MAX_LATEST_GROUPS } from './latest-by';
9
+ import { distinctOnStatement, lateralStatement } from './latest-by-sql';
10
+ import { assertPageBytes } from './page-bytes';
11
+ import { decodeRow, type PhysicalRow } from './pg-row';
12
+ import type { FindManyArgs } from './repo';
13
+
14
+ export interface LatestByRead<Row> {
15
+ latestBy(spec: LatestBySpec, args?: FindManyArgs): Promise<readonly Row[]>;
16
+ }
17
+
18
+ export const postgresLatestBy = <Row>(
19
+ entity: EntityCore<Row>,
20
+ client: () => DbClient,
21
+ ): LatestByRead<Row> => ({
22
+ async latestBy(spec, args = {}) {
23
+ const op = 'latestBy';
24
+ const shape = { includeDeleted: args.includeDeleted === true };
25
+ const send = (statement: ReturnType<typeof distinctOnStatement>) =>
26
+ withStatementAttribution(entity.$name, op, () => client().query<PhysicalRow>(statement));
27
+ const keys = spec.keys;
28
+ let found: readonly PhysicalRow[];
29
+ if (keys === undefined) {
30
+ const plan = latestPlanOf(entity, spec, args, op);
31
+ found = await send(distinctOnStatement(entity, plan, shape, MAX_LATEST_GROUPS + 1));
32
+ // One group per row here, so the row count IS the group count.
33
+ assertGroupBound(entity, spec, found.length);
34
+ } else {
35
+ // Null is no parent (`preload.ts` drops it); an empty list sends nothing.
36
+ const present = keys.filter((key) => key !== null && key !== undefined);
37
+ // Judged even with nothing to send, so a refusal does not depend on the page being empty.
38
+ if (present.length === 0) {
39
+ latestPlanOf(entity, spec, args, op);
40
+ return [];
41
+ }
42
+ // Planned per chunk: the plan's `in` carries the chunk's keys, never the whole list.
43
+ const plans = statementChunks(present).map((chunk) => ({
44
+ chunk,
45
+ plan: latestPlanOf(entity, { ...spec, keys: chunk }, args, op),
46
+ }));
47
+ const pages: PhysicalRow[] = [];
48
+ for (const { chunk, plan } of plans) {
49
+ pages.push(...(await send(lateralStatement(entity, plan, shape, chunk, spec.perGroup))));
50
+ }
51
+ found = pages;
52
+ }
53
+ // Weighed raw, before a row is decoded, as `findMany` weighs its page.
54
+ assertPageBytes(entity, op, found);
55
+ return found.map((row) => decodeRow(entity, row));
56
+ },
57
+ });