@ultimat3/entity 31.7.0 → 31.9.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.
@@ -0,0 +1,103 @@
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
+
20
+ /**
21
+ * The source's column names. Upper case, which no physical column can be (`seekAlias` relies on
22
+ * the same rule), so the scope's unqualified `"org_id" = $n` can never be ambiguous with them.
23
+ */
24
+ const KEY_ALIAS = 'K$UM';
25
+ const aliasOf = (position: number): string => `C${position}$UM`;
26
+ const SOURCE = identifier('v');
27
+
28
+ /** Physical `jsonb` columns, resolved once per batch. */
29
+ const jsonColumns = <Row>(entity: EntityCore<Row>): ReadonlySet<string> => {
30
+ const names = new Set<string>();
31
+ for (const [property, column] of Object.entries(entity.$columns)) {
32
+ if (column.$meta.kind === 'jsonb') names.add(columnName(property, column.$meta));
33
+ }
34
+ return names;
35
+ };
36
+
37
+ /** A searchable entity's version column, physical: advanced past the stored one, never set back. */
38
+ const versionColumn = <Row>(entity: EntityCore<Row>): string | undefined => {
39
+ const property = advancingVersionColumn(entity as EntityCore<unknown>);
40
+ return property === undefined ? undefined : physicalName(entity, property);
41
+ };
42
+
43
+ /** Rows per statement: what the bind budget left after the scope's own binds, over one row's width. */
44
+ const chunked = <T>(items: readonly T[], width: number, reserved: number): readonly T[][] => {
45
+ const size = Math.max(1, Math.floor((MAX_BIND_PARAMETERS - reserved) / width));
46
+ const chunks: T[][] = [];
47
+ for (let from = 0; from < items.length; from += size) chunks.push(items.slice(from, from + size));
48
+ return chunks;
49
+ };
50
+
51
+ /**
52
+ * One statement per chunk. `returning` is `"<table>".*`, never `*`: a bare star would add the
53
+ * source's columns to every row handed back. Without it the answer is a count.
54
+ */
55
+ export const updateManyStatements = <Row>(
56
+ entity: EntityCore<Row>,
57
+ plan: UpdateManyPlan<Row>,
58
+ returning: boolean,
59
+ ): readonly SqlFragment[] => {
60
+ if (plan.patches.length === 0) return [];
61
+ const table = identifier(entity.$table);
62
+ const keyColumn = physicalName(entity, plan.key);
63
+ const bound = plan.patches.map(({ id, patch }) => ({
64
+ key: bindValues(entity, { [plan.key]: id } as typeof patch).get(keyColumn),
65
+ values: bindValues(entity, patch),
66
+ }));
67
+ // Every patch names the same properties (`updateManyPlan`), so the first row's physical columns
68
+ // are every row's — money's two or three included.
69
+ const columns = [...(bound[0]?.values.keys() ?? [])];
70
+ const json = jsonColumns(entity);
71
+ const version = versionColumn(entity);
72
+ const where = conditions(entity, plan.scope, { includeDeleted: false });
73
+ const head = sql`select ${join([
74
+ sql`${identifier(keyColumn)} as ${identifier(KEY_ALIAS)}`,
75
+ ...columns.map((column, at) => sql`${identifier(column)} as ${identifier(aliasOf(at))}`),
76
+ ])} from ${table} where false`;
77
+ const set = join(
78
+ columns.map((column, at) => {
79
+ const next = sql`${SOURCE}.${identifier(aliasOf(at))}`;
80
+ return column === version
81
+ ? sql`${identifier(column)} = greatest(${next}, ${table}.${identifier(column)} + ${VERSION_STEP_SQL})`
82
+ : sql`${identifier(column)} = ${next}`;
83
+ }),
84
+ );
85
+ const tail = returning ? sql` returning ${table}.*` : sql``;
86
+ return chunked(bound, columns.length + 1, where.values.length).map((chunk) => {
87
+ const legs = chunk.map(
88
+ (row) =>
89
+ sql`select ${join([
90
+ sql`${row.key}`,
91
+ ...columns.map((column) =>
92
+ json.has(column)
93
+ ? sql`${row.values.get(column)}::text::jsonb`
94
+ : sql`${row.values.get(column)}`,
95
+ ),
96
+ ])}`,
97
+ );
98
+ const source = join([head, ...legs], ' union all ');
99
+ return sql`update ${table} set ${set} from (${source}) as ${SOURCE} where ${table}.${identifier(
100
+ keyColumn,
101
+ )} = ${SOURCE}.${identifier(KEY_ALIAS)} and ${where}${tail}`;
102
+ });
103
+ };
@@ -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,14 +5,14 @@
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
18
 
@@ -29,17 +29,13 @@ export interface InsertShape {
29
29
  readonly columns: readonly string[];
30
30
  /** How a collision resolves. Absent, it is the caller's error, exactly as it is for one row. */
31
31
  readonly conflict?: ConflictTarget | undefined;
32
+ /**
33
+ * `false` sends no `returning *`: the command tag's count is the whole answer, and nothing
34
+ * stored crosses back to be decoded. Absent is `returning *`, what `insertAll` resolves with.
35
+ */
36
+ readonly returning?: boolean | undefined;
32
37
  }
33
38
 
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
39
  /**
44
40
  * A searchable entity's version column, physical — the one a write must ADVANCE past the stored
45
41
  * value (`search-index-version.ts`), so two writes inside one millisecond are two versions.
@@ -117,19 +113,11 @@ export const insertStatement = <Row>(
117
113
  rows: readonly ReadonlyMap<string, unknown>[],
118
114
  shape: InsertShape,
119
115
  ): 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
- );
116
+ const tuples = valuesList(jsonColumns(entity), shape.columns, rows);
129
117
  const conflict = shape.conflict === undefined ? sql`` : conflictSql(entity, shape.conflict);
130
118
  return sql`insert into ${identifier(entity.$table)} (${join(
131
119
  shape.columns.map(identifier),
132
- )}) values ${join(tuples)}${conflict} returning *`;
120
+ )}) values ${tuples}${conflict}${shape.returning === false ? sql`` : sql` returning *`}`;
133
121
  };
134
122
 
135
123
  /**
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
- };
@@ -0,0 +1,169 @@
1
+ // Single responsibility: the typed handle's writes past one row — a chain's `updateAll(patch)` and
2
+ // `deleteAll()`, `insertAll`/`upsertAll` with or without the rows back, `copyAll` and `updateMany` —
3
+ // each forwarded to the repository member that does it, or, for a hand-written repository that
4
+ // omits an optional one, to the counterpart every repository has. Split from `query.ts` at its ceiling.
5
+
6
+ import { overwrittenBy } from './bulk-write';
7
+ import { copyColumns } from './copy-plan';
8
+ import type { EntityCore } from './entity';
9
+ import type { Repo, RepoOptions, UpdateManyRow, UpsertArgs } from './repo';
10
+ import { stampedColumns, touch } from './touch';
11
+ import type { ColumnMap, Insertable, RowPatch } from './types';
12
+ import { updateManyPlan } from './update-many';
13
+ import { assertWritableChain, type WriteChain } from './write-where';
14
+
15
+ /** Asks for a count instead of the rows: no `returning *`, nothing decoded. */
16
+ export interface Unreturned {
17
+ readonly returning: false;
18
+ }
19
+
20
+ /** The default, spelled: the rows as stored. `boolean` is neither, so it does not typecheck. */
21
+ export interface Returned {
22
+ readonly returning?: true;
23
+ }
24
+
25
+ export interface ChainWrites<Row> {
26
+ /**
27
+ * Every row the chain matches, patched in ONE statement; resolves with how many. The chain's
28
+ * predicates are `updateWhere`'s filter: the same tenancy, soft-delete reach, invariant judging,
29
+ * `onUpdateNow()` stamp, search mirror and `entity.bulk` report. A chain with no predicate is
30
+ * `X_WRITE_UNFILTERED`; `limit()`, `after()` and `search()` are refused — a write has no page.
31
+ */
32
+ updateAll(patch: RowPatch<Row>, options?: RepoOptions): Promise<number>;
33
+ /** Every row the chain matches, removed (or soft-deleted) in one statement; `updateAll`'s guards. */
34
+ deleteAll(options?: RepoOptions): Promise<number>;
35
+ }
36
+
37
+ export const chainWrites = <Source, Row>(
38
+ entity: EntityCore<Source>,
39
+ repo: Repo<Source>,
40
+ chain: WriteChain,
41
+ ): ChainWrites<Row> => ({
42
+ updateAll: async (patch, options) => {
43
+ assertWritableChain(entity.$name, 'updateAll', chain);
44
+ return repo.updateWhere({}, touch(entity, patch as unknown as RowPatch<Source>), {
45
+ ...options,
46
+ where: chain.where,
47
+ });
48
+ },
49
+ deleteAll: async (options) => {
50
+ assertWritableChain(entity.$name, 'deleteAll', chain);
51
+ return repo.deleteWhere({}, { ...options, where: chain.where });
52
+ },
53
+ });
54
+
55
+ export interface TableBulkWrites<Row, C extends ColumnMap = ColumnMap> {
56
+ /**
57
+ * Many rows, one statement — the bulk write a per-row `insert` loop is the N+1 of, and the line
58
+ * an N+1 warning on a write loop names. Every row is parsed and asserted exactly as `insert`
59
+ * parses one, so declared defaults are filled here and not by the caller. Resolves with the rows
60
+ * as stored, in order; `insertAll([])` writes nothing. A collision is an error — `upsertAll` is
61
+ * the call that tolerates one. `{ returning: false }` resolves with the count instead.
62
+ */
63
+ insertAll(rows: readonly Insertable<C>[], options: RepoOptions & Unreturned): Promise<number>;
64
+ insertAll(
65
+ rows: readonly Insertable<C>[],
66
+ options?: RepoOptions & Returned,
67
+ ): Promise<readonly Row[]>;
68
+ /**
69
+ * `insertAll` that resolves a collision instead of failing on it: `on conflict (…) do update`,
70
+ * or `do nothing` with `onMatch: 'nothing'`. Resolves with the rows this call actually wrote, so
71
+ * a row left alone is absent from the result — which is how a caller counts what it inserted.
72
+ * The conflict target and the primary key are never overwritten: they are how the stored row was
73
+ * found and where it lives. `returning: false` resolves with how many rows it wrote.
74
+ */
75
+ upsertAll(rows: readonly Insertable<C>[], args: UpsertArgs<Row> & Unreturned): Promise<number>;
76
+ upsertAll(
77
+ rows: readonly Insertable<C>[],
78
+ args: UpsertArgs<Row> & Returned,
79
+ ): Promise<readonly Row[]>;
80
+ /**
81
+ * The bulk load: `COPY … FROM STDIN` on Postgres, the rows parsed, sealed, tenant-checked and
82
+ * judged exactly as `insertAll` judges them; resolves with the count. No conflict handling — a
83
+ * duplicate refuses the whole load. In memory and on a custom store it is `insertAll`.
84
+ */
85
+ copyAll(rows: readonly Insertable<C>[], options?: RepoOptions): Promise<number>;
86
+ /**
87
+ * A different patch per row, by id, in one statement per bind-count chunk; resolves with how many
88
+ * rows were written. Every patch names the same columns. An id that is absent, soft-deleted or
89
+ * another tenant's is not written and not counted, as `updateWhere` would not.
90
+ */
91
+ updateMany(rows: readonly UpdateManyRow<Row>[], options?: RepoOptions): Promise<number>;
92
+ }
93
+
94
+ /** `options` without `returning`, which no repository member takes. */
95
+ const withoutReturning = <O extends { readonly returning?: boolean }>(
96
+ options: O,
97
+ ): Omit<O, 'returning'> => {
98
+ const { returning: _returning, ...rest } = options;
99
+ return rest;
100
+ };
101
+
102
+ export const tableBulkWrites = <Row, C extends ColumnMap>(
103
+ entity: EntityCore<Row, C>,
104
+ repo: Repo<Row>,
105
+ ): TableBulkWrites<Row, C> => {
106
+ const parsed = (rows: readonly Insertable<C>[]): Row[] => rows.map((row) => entity.$parse(row));
107
+ const counted = async (rows: readonly Row[], options: RepoOptions | undefined) =>
108
+ repo.insertAllCount === undefined
109
+ ? (await repo.insertAll(rows, options)).length
110
+ : repo.insertAllCount(rows, options);
111
+
112
+ async function insertAll(
113
+ rows: readonly Insertable<C>[],
114
+ options?: RepoOptions & { readonly returning?: boolean },
115
+ ): Promise<number | readonly Row[]> {
116
+ const given = options === undefined ? undefined : withoutReturning(options);
117
+ return options?.returning === false
118
+ ? counted(parsed(rows), given)
119
+ : repo.insertAll(parsed(rows), given);
120
+ }
121
+
122
+ // `touch` and not `$parse` alone: an upsert that lands on a stored row IS an update, so an
123
+ // `onUpdateNow()` column has to move exactly as `update(id, patch)` moves it. Asked of the
124
+ // caller's rows BEFORE `$parse` makes every row name every column: otherwise a collision resets
125
+ // each column nobody mentioned to its default.
126
+ async function upsertAll(
127
+ rows: readonly Insertable<C>[],
128
+ args: UpsertArgs<Row> & { readonly returning?: boolean },
129
+ ): Promise<number | readonly Row[]> {
130
+ const plain = withoutReturning(args);
131
+ const overwrites =
132
+ plain.onMatch === 'nothing'
133
+ ? undefined
134
+ : ([
135
+ ...overwrittenBy(entity, rows as readonly RowPatch<Row>[]),
136
+ ...stampedColumns(entity),
137
+ ] as (keyof Row & string)[]);
138
+ const touched = rows.map((row) => touch(entity, entity.$parse(row)));
139
+ const sent = overwrites === undefined ? plain : { ...plain, overwrites };
140
+ if (args.returning !== false) return repo.upsertAll(touched, sent);
141
+ return repo.upsertAllCount === undefined
142
+ ? (await repo.upsertAll(touched, sent)).length
143
+ : repo.upsertAllCount(touched, sent);
144
+ }
145
+
146
+ return {
147
+ insertAll: insertAll as TableBulkWrites<Row, C>['insertAll'],
148
+ upsertAll: upsertAll as TableBulkWrites<Row, C>['upsertAll'],
149
+ copyAll: async (rows, options) => {
150
+ const given = parsed(rows);
151
+ if (repo.copyAll !== undefined) return repo.copyAll(given, options);
152
+ // COPY's refusal, kept by the fallback: a load is refused alike whatever the repository.
153
+ copyColumns(entity, given as readonly RowPatch<Row>[]);
154
+ return counted(given, options);
155
+ },
156
+ updateMany: async (rows, options) => {
157
+ const stamped = rows.map(({ id, patch }) => ({ id, patch: touch(entity, patch) }));
158
+ if (repo.updateMany !== undefined) return repo.updateMany(stamped, options);
159
+ // A hand-written repository: the batch judged as every driver judges it (a nullish or
160
+ // repeated id, an uneven column set, an empty patch), then one `updateWhere` per row.
161
+ const plan = updateManyPlan(entity, stamped, options);
162
+ let written = 0;
163
+ for (const { id, patch } of plan.patches) {
164
+ written += await repo.updateWhere({ [plan.key]: id } as RowPatch<Row>, patch, options);
165
+ }
166
+ return written;
167
+ },
168
+ };
169
+ };
package/src/query.ts CHANGED
@@ -7,21 +7,27 @@
7
7
  import type { Page } from '@ultimat3/core';
8
8
  import { pageOf } from '@ultimat3/core';
9
9
  import { assertBatchable, type BatchIterator, batchIterator } from './batch';
10
- import { overwrittenBy } from './bulk-write';
10
+ import { shrinkingPages } from './batch-bytes';
11
11
  import type { EntityCore } from './entity';
12
12
  import { searchUndeclared } from './feature-errors';
13
13
  import { checkedPredicate, type Operator } from './operator';
14
14
  import { assertFinitePageSize, DEFAULT_PAGE_SIZE } from './plan';
15
15
  import { preloaded, type RelatedTables } from './preload';
16
16
  import { type PreloadOptions, type PreloadRelation, preloadsWith } from './preload-ceiling';
17
+ import {
18
+ type ChainWrites,
19
+ chainWrites,
20
+ type TableBulkWrites,
21
+ tableBulkWrites,
22
+ } from './query-write';
17
23
  import { type ReadAggregates, readAggregates } from './read-aggregates';
18
- import type { Repo, RepoOptions, UpsertArgs } from './repo';
24
+ import type { Repo, RepoOptions } from './repo';
19
25
  import { pickRow } from './sealed';
20
26
  import { SEARCH_PROPERTY } from './search';
21
27
  import { searchedRepo } from './search-repo';
22
28
  import { type TableLocks, tableLocks } from './table-locks';
23
29
  import type { Predicate, QueryPlan, SortDirection, SortKey } from './tenancy';
24
- import { stampedColumns, touch } from './touch';
30
+ import { touch } from './touch';
25
31
  import { type Move, transitionRow } from './transition';
26
32
  import type {
27
33
  ColumnMap,
@@ -46,7 +52,8 @@ export type Preloaded<Name extends string> = { readonly [K in Name]: unknown };
46
52
  * and not only `X_ENTITY_SEALED_PREDICATE` at runtime. It defaults to none.
47
53
  */
48
54
  export interface ReadBuilder<Row, S extends SealedKeySet = NoSealedKeys>
49
- extends ReadAggregates<Row, S> {
55
+ extends ReadAggregates<Row, S>,
56
+ ChainWrites<Row> {
50
57
  /** Equality on the columns given. `where({ orgId })` is what satisfies the tenancy guard. */
51
58
  where(filter: RowPatch<Filterable<Row, S>>): ReadBuilder<Row, S>;
52
59
  // NULL is never sealed, so its tests take ANY column. First: `Parameters<…>` reads the last.
@@ -135,9 +142,14 @@ export interface ReadBuilder<Row, S extends SealedKeySet = NoSealedKeys>
135
142
  plan(): QueryPlan;
136
143
  }
137
144
 
145
+ /**
146
+ * `update` and `delete` address one row by id; a chain's `updateAll(patch)`/`deleteAll()` write
147
+ * every row its predicates match (`query-write.ts`).
148
+ */
138
149
  export interface Table<Row, C extends ColumnMap = ColumnMap>
139
150
  extends ReadBuilder<Row, SealedKeysOf<C>>,
140
- TableLocks<Row> {
151
+ TableLocks<Row>,
152
+ TableBulkWrites<Row, C> {
141
153
  /**
142
154
  * Move one row through the state machine `column` declares, in ONE statement.
143
155
  *
@@ -165,22 +177,6 @@ export interface Table<Row, C extends ColumnMap = ColumnMap>
165
177
  options?: RepoOptions,
166
178
  ): Promise<Row>;
167
179
  insert(values: Insertable<C>, options?: RepoOptions): Promise<Row>;
168
- /**
169
- * Many rows, one statement — the bulk write a per-row `insert` loop is the N+1 of, and the line
170
- * an N+1 warning on a write loop names. Every row is parsed and asserted exactly as `insert`
171
- * parses one, so declared defaults are filled here and not by the caller. Resolves with the rows
172
- * as stored, in order; `insertAll([])` writes nothing. A collision is an error — `upsertAll` is
173
- * the call that tolerates one.
174
- */
175
- insertAll(rows: readonly Insertable<C>[], options?: RepoOptions): Promise<readonly Row[]>;
176
- /**
177
- * `insertAll` that resolves a collision instead of failing on it: `on conflict (…) do update`,
178
- * or `do nothing` with `onMatch: 'nothing'`. Resolves with the rows this call actually wrote, so
179
- * a row left alone is absent from the result — which is how a caller counts what it inserted.
180
- * The conflict target and the primary key are never overwritten: they are how the stored row was
181
- * found and where it lives.
182
- */
183
- upsertAll(rows: readonly Insertable<C>[], args: UpsertArgs<Row>): Promise<readonly Row[]>;
184
180
  /** `IdOf<Row>`: an entity that declared `uuid<PostId>()` is addressed by a `PostId` only. */
185
181
  update(id: IdOf<Row>, patch: RowPatch<Row>, options?: RepoOptions): Promise<Row>;
186
182
  delete(id: IdOf<Row>, options?: RepoOptions): Promise<void>;
@@ -336,10 +332,11 @@ const builder = <Source, Row>(
336
332
  from: state.cursor,
337
333
  // The chain's own arguments with the batch as the page size and the iteration's position
338
334
  // in place of the chain's: one statement per batch, and the same one `page()` sends.
339
- page: async (cursor) => {
340
- const result = await repo.findMany({ ...args(), limit: size, cursor });
335
+ // Past the page byte bound a batch re-reads its own cursor at half the size (`batch-bytes.ts`).
336
+ page: shrinkingPages(size, async (limit, cursor) => {
337
+ const result = await repo.findMany({ ...args(), limit, cursor });
341
338
  return pageOf(await attach(result.rows), result.nextCursor);
342
- },
339
+ }),
343
340
  });
344
341
  },
345
342
 
@@ -358,6 +355,8 @@ const builder = <Source, Row>(
358
355
 
359
356
  count: () => repo.count(args()),
360
357
 
358
+ ...chainWrites<Source, Row>(entity, repo, state),
359
+
361
360
  ...readAggregates(entity, repo, args),
362
361
 
363
362
  plan: (): QueryPlan => ({
@@ -393,29 +392,7 @@ export const tableFor = <Row, C extends ColumnMap>(
393
392
  related,
394
393
  ) as ReadBuilder<Row, SealedKeysOf<C>>),
395
394
  insert: async (values, options) => repo.insert(entity.$parse(values), options),
396
- insertAll: async (rows, options) =>
397
- repo.insertAll(
398
- rows.map((row) => entity.$parse(row)),
399
- options,
400
- ),
401
- // `touch` and not `$parse` alone: an upsert that lands on a stored row IS an update, so an
402
- // `onUpdateNow()` column has to move exactly as `update(id, patch)` moves it — and stamping it
403
- // in a second place is how one of the two ends up writing a stale `updatedAt`.
404
- // Asked of the caller's rows, BEFORE `$parse` makes every row name every column: otherwise a
405
- // collision resets each column nobody mentioned to its default.
406
- upsertAll: async (rows, args) => {
407
- const overwrites =
408
- args.onMatch === 'nothing'
409
- ? undefined
410
- : ([
411
- ...overwrittenBy(entity, rows as readonly RowPatch<Row>[]),
412
- ...stampedColumns(entity),
413
- ] as (keyof Row & string)[]);
414
- return repo.upsertAll(
415
- rows.map((row) => touch(entity, entity.$parse(row))),
416
- overwrites === undefined ? args : { ...args, overwrites },
417
- );
418
- },
395
+ ...tableBulkWrites(entity, repo),
419
396
  update: async (id, patch, options) => repo.update(id, touch(entity, patch), options),
420
397
  delete: async (id, options) => repo.delete(id, options),
421
398
  deleteWhere: async (filter, options) => repo.deleteWhere(filter, options),
package/src/registry.ts CHANGED
@@ -138,10 +138,11 @@ export interface IndexDescription {
138
138
  */
139
139
  readonly using?: IndexMethod | undefined;
140
140
  /**
141
- * `true` when the index is built with `create index concurrently`, outside a transaction; absent
142
- * otherwise, so an entity that never asked hashes exactly what it hashed before.
141
+ * How the index is built, when the entity asked: `true` for `create index concurrently` outside a
142
+ * transaction, `false` for the plain build `x db gen` marks `-- lock-heavy: true`. Absent is the
143
+ * default (concurrently on an existing table), so an entity that never asked hashes as before.
143
144
  */
144
- readonly concurrently?: true | undefined;
145
+ readonly concurrently?: boolean | undefined;
145
146
  }
146
147
 
147
148
  export interface EntityDescription {