@ultimat3/entity 31.8.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.
- package/CLAUDE.md +1 -1
- package/README.md +30 -1
- package/package.json +5 -5
- package/src/adapter.ts +2 -2
- package/src/append-only-errors.ts +2 -1
- package/src/append-only.ts +16 -1
- package/src/batch-bytes.ts +34 -0
- package/src/bulk-write-send.ts +38 -5
- package/src/copy-plan.ts +40 -0
- package/src/driver-repo-reads.ts +5 -4
- package/src/driver-repo-writes.ts +81 -5
- package/src/entity-error.ts +2 -0
- package/src/index.ts +6 -2
- package/src/memory-observed.ts +4 -0
- package/src/memory-repo.ts +43 -5
- package/src/memory-update.ts +10 -3
- package/src/page-bytes.ts +127 -0
- package/src/pg-bulk-repo.ts +163 -0
- package/src/pg-copy.ts +87 -0
- package/src/pg-driver.ts +18 -71
- package/src/pg-update-many-sql.ts +103 -0
- package/src/pg-values-list.ts +55 -0
- package/src/pg-write-sql.ts +10 -22
- package/src/plan.ts +1 -56
- package/src/query-write.ts +169 -0
- package/src/query.ts +24 -47
- package/src/repo.ts +40 -2
- package/src/row-observer.ts +39 -1
- package/src/sealed-repo.ts +48 -7
- package/src/search-mirrored-repo.ts +53 -0
- package/src/type-pins.ts +9 -0
- package/src/update-many-send.ts +66 -0
- package/src/update-many.ts +170 -0
- package/src/view-repo.ts +4 -0
- package/src/write-where.ts +161 -0
|
@@ -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
|
+
};
|
package/src/pg-write-sql.ts
CHANGED
|
@@ -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. `
|
|
9
|
-
// `default`
|
|
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
|
|
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 ${
|
|
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 {
|
|
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
|
|
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 {
|
|
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
|
|
340
|
-
|
|
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
|
-
|
|
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/repo.ts
CHANGED
|
@@ -59,6 +59,22 @@ export interface UpsertArgs<T = unknown> extends RepoOptions {
|
|
|
59
59
|
readonly overwrites?: readonly (keyof T & string)[];
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/**
|
|
63
|
+
* A filtered write's options: `RepoOptions`, plus the predicates a CHAIN carries
|
|
64
|
+
* (`db.x.where(…).andWhere(…).update(patch)`). They AND with the equality filter, every guard
|
|
65
|
+
* applies to the union, and an empty union is `X_WRITE_UNFILTERED` — so a repository that ignores
|
|
66
|
+
* `where` refuses the chain's empty filter rather than reading it as every row.
|
|
67
|
+
*/
|
|
68
|
+
export interface FilteredWriteOptions extends RepoOptions {
|
|
69
|
+
readonly where?: readonly Predicate[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** One row of `updateMany`: the row's id and what it becomes. */
|
|
73
|
+
export interface UpdateManyRow<T = unknown> {
|
|
74
|
+
readonly id: IdOf<T>;
|
|
75
|
+
readonly patch: RowPatch<T>;
|
|
76
|
+
}
|
|
77
|
+
|
|
62
78
|
/**
|
|
63
79
|
* `findById`'s options: `RepoOptions`, plus the one knob a point READ has and a write must not.
|
|
64
80
|
*
|
|
@@ -125,14 +141,36 @@ export interface Repo<T = unknown> {
|
|
|
125
141
|
* to be able to tell "nothing matched" from "it worked", and an empty filter is
|
|
126
142
|
* `X_WRITE_UNFILTERED` rather than every row.
|
|
127
143
|
*/
|
|
128
|
-
deleteWhere(filter: RowPatch<T>, options?:
|
|
144
|
+
deleteWhere(filter: RowPatch<T>, options?: FilteredWriteOptions): Promise<number>;
|
|
129
145
|
/**
|
|
130
146
|
* Update by filter, returning how many rows were written. The `update(id, patch)` a composite
|
|
131
147
|
* primary key cannot express — `participants.lastReadAt` is the reference case. Same two guards
|
|
132
148
|
* as `deleteWhere`, plus `X_PATCH_EMPTY` for a patch that names no columns, and soft-deleted
|
|
133
149
|
* rows are not reachable, exactly as they are not by `update(id, patch)`.
|
|
134
150
|
*/
|
|
135
|
-
updateWhere(
|
|
151
|
+
updateWhere(
|
|
152
|
+
filter: RowPatch<T>,
|
|
153
|
+
patch: RowPatch<T>,
|
|
154
|
+
options?: FilteredWriteOptions,
|
|
155
|
+
): Promise<number>;
|
|
156
|
+
/**
|
|
157
|
+
* A different patch per row, by id, resolving with how many rows were written — the bulk form of a
|
|
158
|
+
* loop of `update(id, patch)`. Every patch names the same columns. Optional: the typed handle
|
|
159
|
+
* runs a `updateWhere` per row for a repository without it.
|
|
160
|
+
*/
|
|
161
|
+
updateMany?(rows: readonly UpdateManyRow<T>[], options?: RepoOptions): Promise<number>;
|
|
162
|
+
/**
|
|
163
|
+
* `insertAll` answering a count: no `returning *`, nothing decoded. Optional: the typed handle
|
|
164
|
+
* counts `insertAll`'s rows for a repository without it.
|
|
165
|
+
*/
|
|
166
|
+
insertAllCount?(rows: readonly RowWrite<T>[], options?: RepoOptions): Promise<number>;
|
|
167
|
+
/** `upsertAll` answering how many rows it wrote, as `insertAllCount` is to `insertAll`. */
|
|
168
|
+
upsertAllCount?(rows: readonly RowWrite<T>[], args: UpsertArgs<T>): Promise<number>;
|
|
169
|
+
/**
|
|
170
|
+
* The bulk load: Postgres `COPY … FROM STDIN`, judged exactly as `insertAll` judges its rows.
|
|
171
|
+
* Optional: `insertAllCount` (else `insertAll`) for a repository without it.
|
|
172
|
+
*/
|
|
173
|
+
copyAll?(rows: readonly RowWrite<T>[], options?: RepoOptions): Promise<number>;
|
|
136
174
|
count(args?: FindManyArgs): Promise<number>;
|
|
137
175
|
/**
|
|
138
176
|
* The grouped count: one statement, one entry per distinct value of `column`, over exactly the
|
package/src/row-observer.ts
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { currentWriteOrigin, type EntityRowOp, instrument, subscribed } from '@ultimat3/core';
|
|
18
18
|
import { expectedQueryLoop } from '@ultimat3/db';
|
|
19
|
+
import { copyColumns } from './copy-plan';
|
|
19
20
|
import type { EntityCore } from './entity';
|
|
20
21
|
import { MAX_PAGE_SIZE } from './plan';
|
|
21
22
|
import { readRecorder } from './read-capture';
|
|
@@ -195,7 +196,7 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
|
|
|
195
196
|
// The read half of failure capture (`read-capture.ts`): one check when no captured call is open.
|
|
196
197
|
const read = readRecorder(name, sealed);
|
|
197
198
|
|
|
198
|
-
|
|
199
|
+
const observed: Repo<Row> = {
|
|
199
200
|
...repo,
|
|
200
201
|
|
|
201
202
|
findById: async (id, options) => {
|
|
@@ -273,4 +274,41 @@ export function observedRepo<Row>(entity: EntityCore<Row>, driven: Repo<Row>): R
|
|
|
273
274
|
return rows;
|
|
274
275
|
},
|
|
275
276
|
};
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* The count-only writes report as their counterparts do. An insert's `entity.row` carries the
|
|
280
|
+
* stored row, so with a subscriber the call runs as its returning form and answers the length;
|
|
281
|
+
* with none it is the count path untouched. `updateMany` is `entity.bulk`, as `updateWhere` is.
|
|
282
|
+
* Each is present only where the repository has it, so the typed handle's fallback still sees
|
|
283
|
+
* an absence.
|
|
284
|
+
*/
|
|
285
|
+
const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
|
|
286
|
+
if (insertAllCount !== undefined) {
|
|
287
|
+
observed.insertAllCount = async (rows, options) =>
|
|
288
|
+
subscribed(ROW)
|
|
289
|
+
? (await observed.insertAll(rows, options)).length
|
|
290
|
+
: insertAllCount.call(repo, rows, options);
|
|
291
|
+
}
|
|
292
|
+
if (upsertAllCount !== undefined) {
|
|
293
|
+
observed.upsertAllCount = async (rows, args) =>
|
|
294
|
+
subscribed(ROW)
|
|
295
|
+
? (await observed.upsertAll(rows, args)).length
|
|
296
|
+
: upsertAllCount.call(repo, rows, args);
|
|
297
|
+
}
|
|
298
|
+
if (copyAll !== undefined) {
|
|
299
|
+
observed.copyAll = async (rows, options) => {
|
|
300
|
+
if (!subscribed(ROW)) return copyAll.call(repo, rows, options);
|
|
301
|
+
// COPY's own refusal first, so a load is refused alike with or without a subscriber.
|
|
302
|
+
copyColumns(entity, rows as readonly RowPatch<Row>[]);
|
|
303
|
+
return (await observed.insertAll(rows, options)).length;
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
if (updateMany !== undefined) {
|
|
307
|
+
observed.updateMany = async (rows, options) => {
|
|
308
|
+
const written = await updateMany.call(repo, rows, options);
|
|
309
|
+
bulk('update', written, options);
|
|
310
|
+
return written;
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
return observed;
|
|
276
314
|
}
|