@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,146 @@
1
+ // Single responsibility: compile an `updateMany` batch into `update … from (…) as v` statements —
2
+ // a different value per row, one statement per bind-count chunk. Nothing is interpolated: every
3
+ // cell is bound and every identifier is the entity's or one of the closed aliases written here.
4
+ //
5
+ // Measured (Postgres 17, Bun's `sql`): a bound `values ($1, $2), …` list resolves its columns as
6
+ // `text`, so `uuid = text` refuses the join. A `select <columns> from <table> where false` head,
7
+ // `union all`-ed with one `select $…` per row, types every column from the TABLE instead: a leaf's
8
+ // unknown parameters take the union's common type. No type name is spelled here, so none can drift.
9
+
10
+ import { identifier, join, type SqlFragment, sql } from '@ultimat3/db';
11
+ import { MAX_BIND_PARAMETERS } from './bulk-write';
12
+ import { columnName } from './column';
13
+ import type { EntityCore } from './entity';
14
+ import { bindValues, physicalName } from './pg-row';
15
+ import { conditions } from './pg-sql';
16
+ import { VERSION_STEP_SQL } from './pg-write-sql';
17
+ import { advancingVersionColumn } from './search-index-version';
18
+ import type { UpdateManyPlan } from './update-many';
19
+ import { versionOf } from './version-lock';
20
+
21
+ /**
22
+ * The source's column names. Upper case, which no physical column can be (`seekAlias` relies on
23
+ * the same rule), so the scope's unqualified `"org_id" = $n` can never be ambiguous with them.
24
+ */
25
+ const KEY_ALIAS = 'K$UM';
26
+ const aliasOf = (position: number): string => `C${position}$UM`;
27
+ const SOURCE = identifier('v');
28
+
29
+ /** Physical `jsonb` columns, resolved once per batch. */
30
+ const jsonColumns = <Row>(entity: EntityCore<Row>): ReadonlySet<string> => {
31
+ const names = new Set<string>();
32
+ for (const [property, column] of Object.entries(entity.$columns)) {
33
+ if (column.$meta.kind === 'jsonb') names.add(columnName(property, column.$meta));
34
+ }
35
+ return names;
36
+ };
37
+
38
+ /** A searchable entity's version column, physical: advanced past the stored one, never set back. */
39
+ const versionColumn = <Row>(entity: EntityCore<Row>): string | undefined => {
40
+ const property = advancingVersionColumn(entity as EntityCore<unknown>);
41
+ return property === undefined ? undefined : physicalName(entity, property);
42
+ };
43
+
44
+ /** The declared lock's column, physical (`version-lock.ts`), or `undefined`. */
45
+ const lockColumn = <Row>(entity: EntityCore<Row>): string | undefined => {
46
+ const property = versionOf(entity);
47
+ return property === null ? undefined : physicalName(entity, property);
48
+ };
49
+
50
+ /** Rows per statement: what the bind budget left after the scope's own binds, over one row's width. */
51
+ const chunked = <T>(items: readonly T[], width: number, reserved: number): readonly T[][] => {
52
+ const size = Math.max(1, Math.floor((MAX_BIND_PARAMETERS - reserved) / width));
53
+ const chunks: T[][] = [];
54
+ for (let from = 0; from < items.length; from += size) chunks.push(items.slice(from, from + size));
55
+ return chunks;
56
+ };
57
+
58
+ /**
59
+ * One statement per chunk. `returning` is `"<table>".*`, never `*`: a bare star would add the
60
+ * source's columns to every row handed back. Without it the answer is a count.
61
+ */
62
+ export const updateManyStatements = <Row>(
63
+ entity: EntityCore<Row>,
64
+ plan: UpdateManyPlan<Row>,
65
+ returning: boolean,
66
+ ): readonly SqlFragment[] => {
67
+ if (plan.patches.length === 0) return [];
68
+ const table = identifier(entity.$table);
69
+ const keyColumn = physicalName(entity, plan.key);
70
+ const bound = plan.patches.map(({ id, patch }) => ({
71
+ key: bindValues(entity, { [plan.key]: id } as typeof patch).get(keyColumn),
72
+ values: bindValues(entity, patch),
73
+ }));
74
+ // Every patch names the same properties (`updateManyPlan`), so the first row's physical columns
75
+ // are every row's — money's two or three included.
76
+ const columns = [...(bound[0]?.values.keys() ?? [])];
77
+ const json = jsonColumns(entity);
78
+ const version = versionColumn(entity);
79
+ const where = conditions(entity, plan.scope, { includeDeleted: false });
80
+ const head = sql`select ${join([
81
+ sql`${identifier(keyColumn)} as ${identifier(KEY_ALIAS)}`,
82
+ ...columns.map((column, at) => sql`${identifier(column)} as ${identifier(aliasOf(at))}`),
83
+ ])} from ${table} where false`;
84
+ // A declared lock: every row names the version it read (`updateManyPlan`), so each is matched
85
+ // only at that version and stored one past it — a stale row is not written, and not counted.
86
+ const lock = lockColumn(entity);
87
+ const set = join(
88
+ columns.map((column, at) => {
89
+ const next = sql`${SOURCE}.${identifier(aliasOf(at))}`;
90
+ if (column === lock) return sql`${identifier(column)} = ${table}.${identifier(column)} + 1`;
91
+ return column === version
92
+ ? sql`${identifier(column)} = greatest(${next}, ${table}.${identifier(column)} + ${VERSION_STEP_SQL})`
93
+ : sql`${identifier(column)} = ${next}`;
94
+ }),
95
+ );
96
+ const at = lock === undefined ? -1 : columns.indexOf(lock);
97
+ const read =
98
+ at < 0 || lock === undefined
99
+ ? sql``
100
+ : sql` and ${table}.${identifier(lock)} = ${SOURCE}.${identifier(aliasOf(at))}`;
101
+ const tail = returning ? sql` returning ${table}.*` : sql``;
102
+ return chunked(bound, columns.length + 1, where.values.length).map((chunk) => {
103
+ const legs = chunk.map(
104
+ (row) =>
105
+ sql`select ${join([
106
+ sql`${row.key}`,
107
+ ...columns.map((column) =>
108
+ json.has(column)
109
+ ? sql`${row.values.get(column)}::text::jsonb`
110
+ : sql`${row.values.get(column)}`,
111
+ ),
112
+ ])}`,
113
+ );
114
+ const source = join([head, ...legs], ' union all ');
115
+ return sql`update ${table} set ${set} from (${source}) as ${SOURCE} where ${table}.${identifier(
116
+ keyColumn,
117
+ )} = ${SOURCE}.${identifier(KEY_ALIAS)} and ${where}${read}${tail}`;
118
+ });
119
+ };
120
+
121
+ /**
122
+ * How many of a batch's rows are live and in scope, chunked as the batch is: what a versioned
123
+ * `updateMany` compares its written count with, inside its transaction — present but not written
124
+ * is a row another write moved past the version the batch read (`X_ENTITY_STALE`).
125
+ */
126
+ export const updateManyPresence = <Row>(
127
+ entity: EntityCore<Row>,
128
+ plan: UpdateManyPlan<Row>,
129
+ ): readonly SqlFragment[] => {
130
+ const reserved = conditions(entity, plan.scope, { includeDeleted: false }).values.length;
131
+ return chunked(
132
+ plan.patches.map((each) => each.id),
133
+ 1,
134
+ reserved,
135
+ ).map((ids) => {
136
+ const match = {
137
+ ...plan.scope,
138
+ where: [...plan.scope.where, { column: plan.key, op: 'in' as const, value: ids }],
139
+ };
140
+ return sql`select count(*)::int as ${identifier('n')} from ${identifier(entity.$table)} where ${conditions(
141
+ entity,
142
+ match,
143
+ { includeDeleted: false },
144
+ )}`;
145
+ });
146
+ };
@@ -0,0 +1,55 @@
1
+ // Single responsibility: a many-row insert's `(…), (…)` list, compiled in ONE `sql` call. The
2
+ // obvious spelling — a fragment per cell, joined per row, joined per chunk — builds and renders
3
+ // four nested fragments per value, and at 100k rows that was the larger half of `insertAll`'s time
4
+ // spent in JavaScript (measured 2026-11-11: 180 ms vs 60-120 ms per 16k-row chunk).
5
+
6
+ import { type SqlFragment, sql } from '@ultimat3/db';
7
+
8
+ /**
9
+ * The text between two bound values. Every one is a constant of this file — punctuation, the
10
+ * `default` keyword and the `jsonb` cast — and never derived from a value or a name, so the
11
+ * template this builds is the template a hand-written `sql` call with that many holes would be.
12
+ * The `default` cell is what makes a row inside a many-row `insert` mean what the same row means
13
+ * on its own, where an unnamed column is simply left out.
14
+ */
15
+ const OPEN = '(';
16
+ const NEXT_CELL = ', ';
17
+ const NEXT_ROW = '), (';
18
+ const CLOSE = ')';
19
+ const DEFAULT_CELL = 'default';
20
+ /** Why `::text::jsonb` and never `::jsonb`: `pg-write-sql.ts`, above `jsonColumns`. */
21
+ const JSON_CAST = '::text::jsonb';
22
+
23
+ /** `strings` as the tagged-template argument `sql` reads: it reads `strings[i]` and nothing else. */
24
+ const template = (strings: string[]): TemplateStringsArray =>
25
+ Object.assign(strings, { raw: strings }) as unknown as TemplateStringsArray;
26
+
27
+ /**
28
+ * `(a, b), (c, default)` for `rows` over `columns`: a value bound where the row names the column, a
29
+ * `default` cell where it does not, and a `jsonb` column's value cast from its text.
30
+ */
31
+ export const valuesList = (
32
+ json: ReadonlySet<string>,
33
+ columns: readonly string[],
34
+ rows: readonly ReadonlyMap<string, unknown>[],
35
+ ): SqlFragment => {
36
+ const strings: string[] = [OPEN];
37
+ const values: unknown[] = [];
38
+ let tail = OPEN;
39
+ for (const [index, row] of rows.entries()) {
40
+ if (index > 0) tail += NEXT_ROW;
41
+ for (const [position, column] of columns.entries()) {
42
+ if (position > 0) tail += NEXT_CELL;
43
+ if (!row.has(column)) {
44
+ tail += DEFAULT_CELL;
45
+ continue;
46
+ }
47
+ strings[strings.length - 1] = tail;
48
+ values.push(row.get(column));
49
+ tail = json.has(column) ? JSON_CAST : '';
50
+ strings.push(tail);
51
+ }
52
+ }
53
+ strings[strings.length - 1] = tail + CLOSE;
54
+ return sql(template(strings), ...values);
55
+ };
@@ -5,16 +5,17 @@
5
5
  //
6
6
  // The same rule holds on both sides of the split and it is the reason either file exists: nothing
7
7
  // is interpolated. `sql` binds every scalar and every identifier is resolved through the entity,
8
- // so a column name can only ever be one the entity declared. `raw()` appears once here, for the
9
- // `default` cell of a many-row `values` list — a closed set of one word, written in this file and
10
- // never derived from a value.
8
+ // so a column name can only ever be one the entity declared. A many-row `values` list, with its
9
+ // `default` cells, is `pg-values-list.ts`'s, compiled in one `sql` call.
11
10
 
12
11
  import { identifier, join, raw, type SqlFragment, sql } from '@ultimat3/db';
13
12
  import { columnName } from './column';
14
13
  import type { EntityCore } from './entity';
15
14
  import { conditions, type ReadShape } from './pg-sql';
15
+ import { valuesList } from './pg-values-list';
16
16
  import { advancingVersionColumn } from './search-index-version';
17
17
  import type { QueryPlan } from './tenancy';
18
+ import { versionOf } from './version-lock';
18
19
 
19
20
  /** `on conflict (…) do update set …`, or `do nothing` when there is nothing to overwrite. */
20
21
  export interface ConflictTarget {
@@ -29,17 +30,13 @@ export interface InsertShape {
29
30
  readonly columns: readonly string[];
30
31
  /** How a collision resolves. Absent, it is the caller's error, exactly as it is for one row. */
31
32
  readonly conflict?: ConflictTarget | undefined;
33
+ /**
34
+ * `false` sends no `returning *`: the command tag's count is the whole answer, and nothing
35
+ * stored crosses back to be decoded. Absent is `returning *`, what `insertAll` resolves with.
36
+ */
37
+ readonly returning?: boolean | undefined;
32
38
  }
33
39
 
34
- /**
35
- * The cell of a row that did not name this column. `default` is the second and last `raw()` in
36
- * this file and, like `asc|desc` above it, a closed set of one word: it is what makes a row inside
37
- * a many-row `insert` mean what the same row means on its own, where an unnamed column is simply
38
- * left out. The seek operator used to be a third — it is chosen in TypeScript now
39
- * (`seekAfter`/`seekEqual`), because a timestamp seek is not one operator.
40
- */
41
- const DEFAULT_CELL = raw('default');
42
-
43
40
  /**
44
41
  * A searchable entity's version column, physical — the one a write must ADVANCE past the stored
45
42
  * value (`search-index-version.ts`), so two writes inside one millisecond are two versions.
@@ -117,19 +114,11 @@ export const insertStatement = <Row>(
117
114
  rows: readonly ReadonlyMap<string, unknown>[],
118
115
  shape: InsertShape,
119
116
  ): SqlFragment => {
120
- const json = jsonColumns(entity);
121
- const tuples = rows.map(
122
- (row) =>
123
- sql`(${join(
124
- shape.columns.map((column) =>
125
- row.has(column) ? cell(json, column, row.get(column)) : DEFAULT_CELL,
126
- ),
127
- )})`,
128
- );
117
+ const tuples = valuesList(jsonColumns(entity), shape.columns, rows);
129
118
  const conflict = shape.conflict === undefined ? sql`` : conflictSql(entity, shape.conflict);
130
119
  return sql`insert into ${identifier(entity.$table)} (${join(
131
120
  shape.columns.map(identifier),
132
- )}) values ${join(tuples)}${conflict} returning *`;
121
+ )}) values ${tuples}${conflict}${shape.returning === false ? sql`` : sql` returning *`}`;
133
122
  };
134
123
 
135
124
  /**
@@ -148,13 +137,40 @@ export const updateStatement = <Row>(
148
137
  ): SqlFragment => {
149
138
  const json = jsonColumns(entity);
150
139
  const version = advancingColumn(entity);
151
- return sql`update ${identifier(entity.$table)} set ${join(
152
- [...values].map(([column, value]) =>
140
+ const lock = lockOf(entity, plan, values);
141
+ const set = [...values]
142
+ .filter(([column]) => column !== lock?.column)
143
+ .map(([column, value]) =>
153
144
  column === version
154
145
  ? advanced(column, cell(json, column, value), identifier(column))
155
146
  : sql`${identifier(column)} = ${cell(json, column, value)}`,
156
- ),
157
- )} where ${conditions(entity, plan, shape)}${returning ? sql` returning *` : sql``}`;
147
+ );
148
+ if (lock !== undefined) set.push(lock.increment);
149
+ return sql`update ${identifier(entity.$table)} set ${join(set)} where ${conditions(
150
+ entity,
151
+ lock?.plan ?? plan,
152
+ shape,
153
+ )}${returning ? sql` returning *` : sql``}`;
154
+ };
155
+
156
+ /**
157
+ * A declared lock (`version-lock.ts`) in SQL: every UPDATE sets `"v" = "v" + 1`, and one whose
158
+ * values named the version is conditioned on it — `"v" = $read`, as one more predicate of the
159
+ * plan, so a row another write moved is simply not matched. `undefined` for an unversioned entity.
160
+ */
161
+ const lockOf = <Row>(
162
+ entity: EntityCore<Row>,
163
+ plan: QueryPlan,
164
+ values: ReadonlyMap<string, unknown>,
165
+ ): { column: string; increment: SqlFragment; plan: QueryPlan } | undefined => {
166
+ const property = versionOf(entity);
167
+ const meta = property === null ? undefined : entity.$columns[property]?.$meta;
168
+ if (property === null || meta === undefined) return undefined;
169
+ const column = columnName(property, meta);
170
+ const increment = sql`${identifier(column)} = ${identifier(column)} + 1`;
171
+ if (!values.has(column)) return { column, increment, plan };
172
+ const read = { column: property, op: 'eq' as const, value: values.get(column) };
173
+ return { column, increment, plan: { ...plan, where: [...plan.where, read] } };
158
174
  };
159
175
 
160
176
  /** Only reached when the entity has no soft-delete column, so there is no filter to apply. */
package/src/plan.ts CHANGED
@@ -5,18 +5,11 @@
5
5
 
6
6
  import { assertSeekable } from './cursor';
7
7
  import type { EntityCore } from './entity';
8
- import {
9
- describeCommand,
10
- EntityError,
11
- invariantViolated,
12
- patchEmpty,
13
- writeUnfiltered,
14
- } from './errors';
8
+ import { describeCommand, EntityError, invariantViolated } from './errors';
15
9
  import { screenPredicates } from './predicate-screen';
16
10
  import type { FindManyArgs, RepoOptions } from './repo';
17
11
  import type { Predicate, QueryPlan, SortKey } from './tenancy';
18
12
  import { scopedPlan } from './tenancy';
19
- import type { RowPatch } from './types';
20
13
 
21
14
  /** A page is bounded by default; an unbounded read is a production incident waiting for traffic. */
22
15
  export const DEFAULT_PAGE_SIZE = 50;
@@ -214,51 +207,3 @@ export const namedColumns = (values: unknown): readonly (readonly [string, unkno
214
207
  Object.entries(
215
208
  typeof values === 'object' && values !== null ? (values as Record<string, unknown>) : {},
216
209
  ).filter(([, value]) => value !== undefined);
217
-
218
- /** The filter a filtered write is allowed to run with: never the empty one. */
219
- const boundedWhere = <Row>(
220
- entity: EntityCore<Row>,
221
- filter: RowPatch<Row>,
222
- operation: string,
223
- ): Predicate[] => {
224
- const where = namedColumns(filter).map(
225
- ([column, value]): Predicate => ({ column, op: 'eq', value }),
226
- );
227
- if (where.length === 0) throw writeUnfiltered(entity.$name, operation, entity.$primaryKey);
228
- return where;
229
- };
230
-
231
- /**
232
- * The plan for a filtered delete. The guard order is the point: an empty filter is refused before
233
- * tenancy runs, so `deleteWhere({}, { orgId })` cannot pass by virtue of the org predicate the
234
- * framework added — that predicate bounds the blast radius to one tenant, which is still every
235
- * row that tenant has.
236
- *
237
- * `limit` is the read default and is not a bound on the delete: neither driver pages a delete.
238
- */
239
- export const deletePlan = <Row>(
240
- entity: EntityCore<Row>,
241
- filter: RowPatch<Row>,
242
- options: RepoOptions | undefined,
243
- operation: string,
244
- ): QueryPlan =>
245
- readPlan(entity, { ...options, where: boundedWhere(entity, filter, operation) }, operation);
246
-
247
- /**
248
- * The plan for a filtered update. Same filter guard as the delete, from the same function, plus
249
- * the patch: a write that names no columns is refused rather than counted, because "4 rows
250
- * updated" for a statement that set nothing is the answer nobody can act on.
251
- */
252
- export const updatePlan = <Row>(
253
- entity: EntityCore<Row>,
254
- filter: RowPatch<Row>,
255
- patch: RowPatch<Row>,
256
- options: RepoOptions | undefined,
257
- operation: string,
258
- ): QueryPlan => {
259
- const where = boundedWhere(entity, filter, operation);
260
- if (namedColumns(patch).length === 0) {
261
- throw patchEmpty(entity.$name, operation, Object.keys(entity.$columns));
262
- }
263
- return readPlan(entity, { ...options, where }, operation);
264
- };
@@ -1,11 +1,14 @@
1
1
  // Single responsibility: the bound on a preload — the ceiling a chain declares (or the default),
2
- // resolved where `preload()` is called, and the refusal past it. `preload.ts` reads under it.
2
+ // resolved where `preload()` is called, and the refusal past it — plus the per-parent bound a
3
+ // `hasMany` may declare (`perParent`), resolved and refused at the same place. `preload.ts` reads
4
+ // under both.
3
5
 
4
6
  import { describeValue } from '@ultimat3/schema';
5
7
  import { describeCommand, EntityError } from './errors';
6
8
  import { MAX_PAGE_SIZE } from './plan';
7
9
  import type { Relation } from './relations';
8
10
  import { relationNamed } from './relations';
11
+ import type { SortDirection, SortKey } from './tenancy';
9
12
 
10
13
  /**
11
14
  * How many related rows ONE relation may attach to one page when the chain declares no ceiling of
@@ -18,10 +21,71 @@ export const MAX_PRELOADED_ROWS = MAX_PAGE_SIZE;
18
21
  export interface PreloadOptions {
19
22
  /** The ceiling for this relation on this chain. Past it the read is refused, never truncated. */
20
23
  readonly max?: number;
24
+ /**
25
+ * A `hasMany` only: at most this many related rows per parent — "the last 3 messages of each
26
+ * conversation" — read for the whole page in ONE statement (`LATERAL`, `latest-by.ts`), not one
27
+ * `limit(n)` read per parent. Which n is `order` (a column of the related entity) in
28
+ * `direction` (default `desc`); unnamed, the related key descending — newest first by uuid v7.
29
+ */
30
+ readonly perParent?: number;
31
+ readonly order?: string;
32
+ readonly direction?: SortDirection;
21
33
  }
22
34
 
23
- /** A relation as a chain named it: the edge, and the ceiling it is read under. */
24
- export type PreloadRelation = Relation & { readonly max: number };
35
+ /** The per-parent bound a chain declared: how many, and which ones. */
36
+ export interface PerParent {
37
+ readonly rows: number;
38
+ readonly order: readonly SortKey[];
39
+ }
40
+
41
+ /** A relation as a chain named it: the edge, the ceiling it is read under, its per-parent bound. */
42
+ export type PreloadRelation = Relation & {
43
+ readonly max: number;
44
+ readonly perParent?: PerParent | undefined;
45
+ };
46
+
47
+ /** Whether a call stated anything a later call of the same relation replaces. */
48
+ const states = (options: PreloadOptions | undefined): boolean =>
49
+ options?.max !== undefined || options?.perParent !== undefined;
50
+
51
+ const perParentOf = (
52
+ entityName: string,
53
+ relation: Relation,
54
+ options: PreloadOptions | undefined,
55
+ ): PerParent | undefined => {
56
+ const rows = options?.perParent;
57
+ const call = `${entityName}.preload('${relation.name}', { perParent })`;
58
+ const refuse = (cause: string, fix: string): EntityError =>
59
+ new EntityError({
60
+ code: 'X_INVARIANT_VIOLATED',
61
+ cause: `${call} — ${cause}`,
62
+ fix: `${describeCommand(entityName)} # ${fix}`,
63
+ });
64
+ if (rows === undefined) {
65
+ if (options?.order === undefined && options?.direction === undefined) return undefined;
66
+ throw refuse(
67
+ 'an order without perParent names no "first n": a whole relation attaches in full',
68
+ `preload('${relation.name}', { perParent: <n>, order, direction }) # or drop { order, direction }: with no perParent the relation attaches in full`,
69
+ );
70
+ }
71
+ if (relation.kind !== 'hasMany') {
72
+ throw refuse(
73
+ `'${relation.name}' is a belongsTo, which attaches one row per parent already`,
74
+ `preload('${relation.name}') # no { perParent }: a belongsTo attaches one row per parent`,
75
+ );
76
+ }
77
+ if (!Number.isSafeInteger(rows) || rows < 1 || rows > MAX_PAGE_SIZE) {
78
+ throw refuse(
79
+ `perParent is a whole number of rows, at least 1 and at most ${MAX_PAGE_SIZE}; got ${describeValue(rows)}`,
80
+ `preload('${relation.name}', { perParent: 1 }) # a whole number of rows per parent, 1 to ${MAX_PAGE_SIZE}`,
81
+ );
82
+ }
83
+ const order =
84
+ options?.order === undefined
85
+ ? []
86
+ : [{ column: options.order, direction: options.direction ?? ('desc' as const) }];
87
+ return { rows, order };
88
+ };
25
89
 
26
90
  /**
27
91
  * The relation a `preload()` call names, resolved on the chain — an unknown name and a ceiling
@@ -41,13 +105,15 @@ export const preloadOf = (
41
105
  fix: `${describeCommand(entityName)} # the entity whose chain preloads '${relation.name}': correct the { max } on that call`,
42
106
  });
43
107
  }
44
- return { ...relation, max };
108
+ const perParent = perParentOf(entityName, relation, options);
109
+ return perParent === undefined ? { ...relation, max } : { ...relation, max, perParent };
45
110
  };
46
111
 
47
112
  /**
48
113
  * The chain's preloads after one more `preload()` call. A relation named twice is ONE statement,
49
- * and its ceiling is one setting: a later call that STATES `max` replaces the earlier one, exactly
50
- * as a second `.limit()` replaces the first; a later call that states none leaves it. Name-only
114
+ * and its bounds are one setting: a later call that STATES `max` or `perParent` replaces the
115
+ * earlier one whole, exactly as a second `.limit()` replaces the first; a later call that states
116
+ * neither leaves it. Name-only
51
117
  * dedup kept the first and silently dropped a stricter ceiling written after it.
52
118
  */
53
119
  export const preloadsWith = (
@@ -58,7 +124,7 @@ export const preloadsWith = (
58
124
  ): readonly PreloadRelation[] => {
59
125
  const resolved = preloadOf(entityName, name, options);
60
126
  if (!held.some((one) => one.name === resolved.name)) return [...held, resolved];
61
- if (options?.max === undefined) return held;
127
+ if (!states(options)) return held;
62
128
  return held.map((one) => (one.name === resolved.name ? resolved : one));
63
129
  };
64
130
 
package/src/preload.ts CHANGED
@@ -11,6 +11,7 @@ import { keyOf, MAX_IDS_PER_STATEMENT, statementChunks } from './batch-read';
11
11
  import { valueAt } from './cursor';
12
12
  import type { EntityCore } from './entity';
13
13
  import { EntityError } from './errors';
14
+ import { latestRows } from './latest-by';
14
15
  import { type PreloadRelation, preloadTooMany } from './preload-ceiling';
15
16
  import type { Relation } from './relations';
16
17
  import type { Repo } from './repo';
@@ -76,7 +77,8 @@ const tenantScope = (
76
77
  * The page loop is what keeps a `hasMany` honest: a relation with more rows than one page holds
77
78
  * costs another statement rather than silently returning the first page of them. And the ceiling
78
79
  * is what keeps the loop finite: it asks for at most ONE row past `relation.max`, which is the
79
- * row that proves the refusal, and reads nothing after it.
80
+ * row that proves the refusal, and reads nothing after it. A `perParent` bound is the one exception
81
+ * to the page loop: its rows are already bounded by keys × n, in one statement per chunk.
80
82
  */
81
83
  const relatedRows = async (
82
84
  source: string,
@@ -86,7 +88,21 @@ const relatedRows = async (
86
88
  scope: readonly Predicate[],
87
89
  ): Promise<readonly unknown[]> => {
88
90
  const rows: unknown[] = [];
91
+ const perParent = relation.perParent;
89
92
  for (const chunk of statementChunks(values)) {
93
+ // n per parent: ONE statement per chunk however many rows each parent has (`LATERAL` on
94
+ // Postgres), grouped by key in the order asked — never a page loop over every child.
95
+ if (perParent !== undefined) {
96
+ const spec = {
97
+ group: relation.remoteKey,
98
+ order: perParent.order,
99
+ perGroup: perParent.rows,
100
+ keys: chunk,
101
+ };
102
+ rows.push(...(await latestRows(target.entity, target.repo, spec, { where: scope })));
103
+ if (rows.length > relation.max) throw preloadTooMany(source, relation);
104
+ continue;
105
+ }
90
106
  let cursor: string | null = null;
91
107
  do {
92
108
  const page = await target.repo.findMany({