@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.
- 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/declared-index.ts +3 -2
- package/src/describe.ts +3 -2
- 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-identity.ts +13 -8
- package/src/index-init.ts +3 -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/registry.ts +4 -3
- 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/types.ts +5 -2
- 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
package/CLAUDE.md
CHANGED
|
@@ -136,7 +136,7 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
|
|
|
136
136
|
- **`crossTenant(reason, fn)` is the ONE way to read across tenants** — an `asyncContext` scope from
|
|
137
137
|
core (`scripts/async-context-guard.ts`), `CROSS_TENANT_SCOPE` (`tenancy:cross`) proven at the call
|
|
138
138
|
and at every plan (`X_TENANCY_CROSS_DENIED`), refused outside a request, blank reason `X_INVARIANT`.
|
|
139
|
-
- **`deleteWhere` / `updateWhere` are the only filtered writes
|
|
139
|
+
- **`deleteWhere` / `updateWhere` are the only filtered writes** — a chain's `updateAll`/`deleteAll` (`query-write.ts`) IS one, its predicates in `FilteredWriteOptions.where`, one plan (`write-where.ts`). `updateMany`/`insertAllCount`/`upsertAllCount`/`copyAll` are `Repo`-optional with typed-handle fallbacks; every wrapper (sealed, append-only, view, mirror, observer, memory-observed) handles each (`query-write-wrappers.test.ts`). Empty filter `X_WRITE_UNFILTERED`,
|
|
140
140
|
empty patch `X_PATCH_EMPTY` (undefined values dropped first); soft delete respected; both return a
|
|
141
141
|
count; a JS-only invariant is judged
|
|
142
142
|
in the statement's transaction (`judged-write.ts`), refused past `MAX_ASSERTED_ROWS`. Full rule: `docs/history/entity.md`.
|
package/README.md
CHANGED
|
@@ -397,7 +397,11 @@ and again inside the plan both drivers build, so `findMany({ limit })` straight
|
|
|
397
397
|
cannot route around it. `inBatches(size)` is the call that means "every row" — one page per
|
|
398
398
|
statement, never a table in memory.
|
|
399
399
|
|
|
400
|
-
|
|
400
|
+
A page is bounded in bytes too: `MAX_PAGE_BYTES` (64 MiB), weighed on the raw rows before decode
|
|
401
|
+
(the projected page in memory and on a custom store) — past it `X_ENTITY_PAGE_TOO_LARGE`, naming a
|
|
402
|
+
`select(…)` and a `limit(n)` that fits.
|
|
403
|
+
|
|
404
|
+
`DEFAULT_PAGE_SIZE`, `MAX_PAGE_SIZE`, `MAX_PAGE_BYTES` and `MAX_ASSERTED_ROWS` are exported, beside
|
|
401
405
|
`N_PLUS_ONE_THRESHOLD` and for the same reason: an action validating its own `pageSize` input
|
|
402
406
|
against a hardcoded `10_000` is a second declaration of one number, and the second one goes stale.
|
|
403
407
|
|
|
@@ -746,8 +750,33 @@ db.participants.updateWhere({ conversationId, userId }, { lastReadAt }); // ->
|
|
|
746
750
|
|
|
747
751
|
db.likes.deleteWhere({}); // X_WRITE_UNFILTERED, never every row
|
|
748
752
|
db.participants.updateWhere({ conversationId }, {}); // X_PATCH_EMPTY, never a silent no-op
|
|
753
|
+
|
|
754
|
+
// A chain's predicates, any operator: the same write, `updateWhere`'s guards and reports
|
|
755
|
+
db.likes.where({ postId }).andWhere('userId', 'in', ids).deleteAll(); // -> n
|
|
756
|
+
db.posts.where({ authorId }).andWhere('publishedAt', 'is-null').updateAll({ status: 'draft' });
|
|
757
|
+
db.posts.where({ authorId }).limit(10).deleteAll(); // X_INVARIANT_VIOLATED: a write has no page
|
|
758
|
+
|
|
759
|
+
// A different patch per row, one statement per bind-count chunk; the same columns in every patch
|
|
760
|
+
db.posts.updateMany(rows.map(({ id, rank }) => ({ id, patch: { rank } }))); // -> rows written
|
|
749
761
|
```
|
|
750
762
|
|
|
763
|
+
`updateAll(patch)`/`deleteAll()` end any chain and run as `updateWhere`/`deleteWhere` with the
|
|
764
|
+
chain's predicates (`FilteredWriteOptions.where`): one plan builder (`write-where.ts`), so tenancy,
|
|
765
|
+
soft delete, invariant judging, `onUpdateNow()`, sealing (a lookup column matched as a read matches
|
|
766
|
+
it), the search mirror and the `entity.bulk` report cannot differ. No predicate is
|
|
767
|
+
`X_WRITE_UNFILTERED`; `limit()`, `after()` and `search()` are refused. `updateMany` is `Repo`-optional:
|
|
768
|
+
a hand-written repository without it gets one `updateWhere` per row from the typed handle.
|
|
769
|
+
|
|
770
|
+
| Bulk insert | Resolves | Statement |
|
|
771
|
+
|---|---|---|
|
|
772
|
+
| `insertAll(rows)` · `upsertAll(rows, args)` | the rows as stored | `insert … returning *` |
|
|
773
|
+
| `insertAll(rows, { returning: false })` · `upsertAll(rows, { …, returning: false })` | a count | no `returning`, nothing decoded |
|
|
774
|
+
| `copyAll(rows)` | a count | Postgres `COPY … FROM STDIN`, at most 50,000 rows per COPY (`MAX_ROWS_PER_COPY`) — a larger load is several COPYs in one transaction, all or nothing; every row names the same columns; elsewhere `insertAll`. With row security installed it is `insertAll`, since Postgres refuses COPY on a row-secured table. While an external search index or an `entity.row` subscriber listens it is a multi-row `INSERT … returning *` (same judging, same refusals), so the rows can be mirrored and reported |
|
|
775
|
+
|
|
776
|
+
All three judge rows identically (seal, tenant, invariants, defaults). The count forms still hand an
|
|
777
|
+
installed search index and an `entity.row` subscriber the rows: while either listens they run as
|
|
778
|
+
their returning counterpart.
|
|
779
|
+
|
|
751
780
|
`delete(id)` and `update(id, patch)` both need a single-column primary key. A composite one —
|
|
752
781
|
`likes`, `blocks`, `participants`, any join table — has no single id, so the filtered pair is the
|
|
753
782
|
only write path there: without them such an entity is **create-only**, and a row could be written
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/entity",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.9.0",
|
|
4
4
|
"description": "A table + its domain type + invariants the database also enforces",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -44,9 +44,9 @@
|
|
|
44
44
|
"test": "bun test"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@ultimat3/core": "31.
|
|
48
|
-
"@ultimat3/db": "31.
|
|
49
|
-
"@ultimat3/schema": "31.
|
|
50
|
-
"@ultimat3/time": "31.
|
|
47
|
+
"@ultimat3/core": "31.9.0",
|
|
48
|
+
"@ultimat3/db": "31.9.0",
|
|
49
|
+
"@ultimat3/schema": "31.9.0",
|
|
50
|
+
"@ultimat3/time": "31.9.0"
|
|
51
51
|
}
|
|
52
52
|
}
|
package/src/adapter.ts
CHANGED
|
@@ -34,13 +34,11 @@ export { compareByKind, matchesPredicate, sameValueOfKind } from './memory-match
|
|
|
34
34
|
export type { PostgresDriverOptions } from './pg-driver';
|
|
35
35
|
export {
|
|
36
36
|
DEFAULT_PAGE_SIZE,
|
|
37
|
-
deletePlan,
|
|
38
37
|
idPlan,
|
|
39
38
|
MAX_PAGE_SIZE,
|
|
40
39
|
planFor,
|
|
41
40
|
readPlan,
|
|
42
41
|
singleKeyOf,
|
|
43
|
-
updatePlan,
|
|
44
42
|
} from './plan';
|
|
45
43
|
export { rowKey } from './row-key';
|
|
46
44
|
// The searchIndex port: what an app's Meilisearch/Typesense index implements, and its installer.
|
|
@@ -64,3 +62,5 @@ export type { Predicate, QueryPlan, SortKey } from './tenancy';
|
|
|
64
62
|
export { assertRowTenant, scopedPlan } from './tenancy';
|
|
65
63
|
export type { UniqueConstraint } from './unique-constraints';
|
|
66
64
|
export { uniqueConstraints } from './unique-constraints';
|
|
65
|
+
// The shipped names of the one filtered-write plan (`write-where.ts`), kept for the kit's callers.
|
|
66
|
+
export { updateWherePlan as updatePlan, writeWherePlan as deletePlan } from './write-where';
|
|
@@ -12,6 +12,7 @@ export type AppendOnlyRefusedCall =
|
|
|
12
12
|
| 'delete'
|
|
13
13
|
| 'updateWhere'
|
|
14
14
|
| 'deleteWhere'
|
|
15
|
+
| 'updateMany'
|
|
15
16
|
| 'upsertAll';
|
|
16
17
|
|
|
17
18
|
/** How to lift the rule, said once: the trigger goes with the flag, in a migration. */
|
|
@@ -22,7 +23,7 @@ const fixFor = (entityName: string, call: AppendOnlyRefusedCall): string => {
|
|
|
22
23
|
if (call === 'upsertAll') {
|
|
23
24
|
return `${entityName}.upsertAll(rows, { onConflict, onMatch: 'nothing' }) # a row already stored is skipped, never overwritten — ${LIFT}`;
|
|
24
25
|
}
|
|
25
|
-
const what = call
|
|
26
|
+
const what = call.startsWith('update') ? 'the correction' : 'the reversal';
|
|
26
27
|
return `${entityName}.insert({ … }) # append ${what} as a new row that names the one it supersedes — ${LIFT}`;
|
|
27
28
|
};
|
|
28
29
|
|
package/src/append-only.ts
CHANGED
|
@@ -75,7 +75,7 @@ export const appendOnlyRepo = <Row, R extends Repo<Row>>(entity: AppendOnlySourc
|
|
|
75
75
|
const name = entity.$name;
|
|
76
76
|
const refusing: Pick<
|
|
77
77
|
Repo<Row>,
|
|
78
|
-
'update' | 'delete' | 'updateWhere' | 'deleteWhere' | 'upsertAll'
|
|
78
|
+
'update' | 'delete' | 'updateWhere' | 'deleteWhere' | 'upsertAll' | 'updateMany'
|
|
79
79
|
> = {
|
|
80
80
|
update: async () => {
|
|
81
81
|
throw appendOnlyRefused(name, 'update');
|
|
@@ -89,10 +89,25 @@ export const appendOnlyRepo = <Row, R extends Repo<Row>>(entity: AppendOnlySourc
|
|
|
89
89
|
deleteWhere: async () => {
|
|
90
90
|
throw appendOnlyRefused(name, 'deleteWhere');
|
|
91
91
|
},
|
|
92
|
+
updateMany: async () => {
|
|
93
|
+
throw appendOnlyRefused(name, 'updateMany');
|
|
94
|
+
},
|
|
92
95
|
async upsertAll(rows, args: UpsertArgs<Row>) {
|
|
93
96
|
if (args.onMatch !== 'nothing') throw appendOnlyRefused(name, 'upsertAll');
|
|
94
97
|
return repo.upsertAll(rows, args);
|
|
95
98
|
},
|
|
96
99
|
};
|
|
100
|
+
// The count-only upsert is the same append, or the same refusal; absent stays absent.
|
|
101
|
+
const upsertAllCount = repo.upsertAllCount;
|
|
102
|
+
if (upsertAllCount !== undefined) {
|
|
103
|
+
return {
|
|
104
|
+
...repo,
|
|
105
|
+
...refusing,
|
|
106
|
+
async upsertAllCount(rows: Parameters<typeof upsertAllCount>[0], args: UpsertArgs<Row>) {
|
|
107
|
+
if (args.onMatch !== 'nothing') throw appendOnlyRefused(name, 'upsertAll');
|
|
108
|
+
return upsertAllCount.call(repo, rows, args);
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
97
112
|
return { ...repo, ...refusing };
|
|
98
113
|
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Single responsibility: keep `inBatches(size)` under the page byte bound by shrinking the batch.
|
|
2
|
+
// A batch IS a page, so a sweep over heavy rows would hit `X_ENTITY_PAGE_TOO_LARGE` on a size that
|
|
3
|
+
// was right for light ones; halving and re-reading the same cursor finishes the sweep instead, and
|
|
4
|
+
// every caller — the framework's reindex and history reads, an app's own loop — needs no edit.
|
|
5
|
+
|
|
6
|
+
import type { Page } from '@ultimat3/core';
|
|
7
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
8
|
+
|
|
9
|
+
const tooLarge = (error: unknown): boolean =>
|
|
10
|
+
isUltimateError(error) && error.code === 'X_ENTITY_PAGE_TOO_LARGE';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The batch reader `inBatches` hands `batchIterator`: `read` at `size` rows, and on a page refused
|
|
14
|
+
* for its bytes the same cursor again at half the rows — down to one, where a row heavier than the
|
|
15
|
+
* bound on its own is refused as it should be. The smaller size is kept for the batches after it:
|
|
16
|
+
* the rows that were heavy are usually the table's shape, and starting over at `size` would pay
|
|
17
|
+
* the refused reads once per batch. At most `⌈log2(size)⌉` statements are refused per iteration.
|
|
18
|
+
*/
|
|
19
|
+
export const shrinkingPages = <Row>(
|
|
20
|
+
size: number,
|
|
21
|
+
read: (limit: number, cursor: string | null) => Promise<Page<Row>>,
|
|
22
|
+
): ((cursor: string | null) => Promise<Page<Row>>) => {
|
|
23
|
+
let limit = size;
|
|
24
|
+
return async (cursor) => {
|
|
25
|
+
for (;;) {
|
|
26
|
+
try {
|
|
27
|
+
return await read(limit, cursor);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (limit <= 1 || !tooLarge(error)) throw error;
|
|
30
|
+
limit = Math.floor(limit / 2);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
};
|
package/src/bulk-write-send.ts
CHANGED
|
@@ -23,6 +23,12 @@ import { type InsertShape, insertStatement } from './pg-write-sql';
|
|
|
23
23
|
* stored is the incoming row merged into the stored one, and only `returning *` shows that row. The
|
|
24
24
|
* memory driver judges the same merge in `write`, so without this the rule held only there.
|
|
25
25
|
*/
|
|
26
|
+
/** An updating upsert whose stored rows only the app can judge — the one write that must read back. */
|
|
27
|
+
const judgesMerge = <Row>(entity: EntityCore<Row>, shape: InsertShape): boolean =>
|
|
28
|
+
shape.conflict !== undefined &&
|
|
29
|
+
shape.conflict.set.length > 0 &&
|
|
30
|
+
hasJsOnlyInvariant(entity.$invariants);
|
|
31
|
+
|
|
26
32
|
export const writeChunks = async <Row>(
|
|
27
33
|
entity: EntityCore<Row>,
|
|
28
34
|
bound: readonly ReadonlyMap<string, unknown>[],
|
|
@@ -31,14 +37,13 @@ export const writeChunks = async <Row>(
|
|
|
31
37
|
pinned: DbClient | undefined,
|
|
32
38
|
): Promise<readonly Row[]> => {
|
|
33
39
|
const chunks = insertChunks(bound, shape.columns.length);
|
|
34
|
-
const judges =
|
|
35
|
-
shape.conflict !== undefined &&
|
|
36
|
-
shape.conflict.set.length > 0 &&
|
|
37
|
-
hasJsOnlyInvariant(entity.$invariants);
|
|
40
|
+
const judges = judgesMerge(entity, shape);
|
|
38
41
|
const send = async (on: DbClient): Promise<readonly Row[]> => {
|
|
39
42
|
const written: Row[] = [];
|
|
40
43
|
for (const chunk of chunks) {
|
|
41
|
-
const stored = await on.query<PhysicalRow>(
|
|
44
|
+
const stored = await on.query<PhysicalRow>(
|
|
45
|
+
insertStatement(entity, chunk, { ...shape, returning: true }),
|
|
46
|
+
);
|
|
42
47
|
for (const row of stored) written.push(decodeRow(entity, row));
|
|
43
48
|
}
|
|
44
49
|
if (judges) for (const row of written) entity.$assert(row);
|
|
@@ -47,3 +52,31 @@ export const writeChunks = async <Row>(
|
|
|
47
52
|
if (chunks.length === 1 && !judges) return send(direct);
|
|
48
53
|
return withTransaction(send, pinned === undefined ? {} : { client: pinned });
|
|
49
54
|
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* `writeChunks` answering a count: the same chunks under the same one-transaction rule, each sent
|
|
58
|
+
* with no `returning`, so nothing stored crosses back. The exception is the one write that must
|
|
59
|
+
* read back to be judged — an updating upsert under an app-only rule — which takes `writeChunks`
|
|
60
|
+
* whole and counts what it judged, so `returning: false` never skips a rule.
|
|
61
|
+
*/
|
|
62
|
+
export const countChunks = async <Row>(
|
|
63
|
+
entity: EntityCore<Row>,
|
|
64
|
+
bound: readonly ReadonlyMap<string, unknown>[],
|
|
65
|
+
shape: InsertShape,
|
|
66
|
+
direct: DbClient,
|
|
67
|
+
pinned: DbClient | undefined,
|
|
68
|
+
): Promise<number> => {
|
|
69
|
+
if (judgesMerge(entity, shape)) {
|
|
70
|
+
return (await writeChunks(entity, bound, shape, direct, pinned)).length;
|
|
71
|
+
}
|
|
72
|
+
const chunks = insertChunks(bound, shape.columns.length);
|
|
73
|
+
const send = async (on: DbClient): Promise<number> => {
|
|
74
|
+
let count = 0;
|
|
75
|
+
for (const chunk of chunks) {
|
|
76
|
+
count += await on.execute(insertStatement(entity, chunk, { ...shape, returning: false }));
|
|
77
|
+
}
|
|
78
|
+
return count;
|
|
79
|
+
};
|
|
80
|
+
if (chunks.length <= 1) return send(direct);
|
|
81
|
+
return withTransaction(send, pinned === undefined ? {} : { client: pinned });
|
|
82
|
+
};
|
package/src/copy-plan.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Single responsibility: what a `copyAll` batch may be, decided in PROPERTY space so every driver
|
|
2
|
+
// refuses the same batch. `COPY … FROM STDIN` has one column list and no per-row `default` cell,
|
|
3
|
+
// so a column one row writes and another leaves out has no honest spelling — refused here, in
|
|
4
|
+
// memory and behind `defineDriver` too, rather than accepted where it happens to work.
|
|
5
|
+
|
|
6
|
+
import type { EntityCore } from './entity';
|
|
7
|
+
import { EntityError } from './errors';
|
|
8
|
+
import type { RowPatch } from './types';
|
|
9
|
+
|
|
10
|
+
/** Present and not `undefined` — the two tests `bindValues` makes before it binds a value. */
|
|
11
|
+
const writes = (row: unknown, property: string): boolean =>
|
|
12
|
+
typeof row === 'object' &&
|
|
13
|
+
row !== null &&
|
|
14
|
+
Object.hasOwn(row, property) &&
|
|
15
|
+
(row as Readonly<Record<string, unknown>>)[property] !== undefined;
|
|
16
|
+
|
|
17
|
+
const unevenCopy = (entityName: string, position: number, missing: string): EntityError =>
|
|
18
|
+
new EntityError({
|
|
19
|
+
code: 'X_INVARIANT_VIOLATED',
|
|
20
|
+
cause: `${entityName}.copyAll() row ${position + 1} does not name "${missing}", which other rows of the batch do — COPY writes one column list for every row and has no per-row default`,
|
|
21
|
+
fix: `${entityName}.copyAll(rows.map((row) => ({ ...row, ${missing}: <value> }))) # or ${entityName}.insertAll(rows, { returning: false }), which writes default per cell`,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The properties every row of the batch writes, in declaration order. Empty when no row writes
|
|
26
|
+
* anything: every column then takes its default, which a COPY spells by naming none of them.
|
|
27
|
+
*/
|
|
28
|
+
export const copyColumns = <Row>(
|
|
29
|
+
entity: EntityCore<Row>,
|
|
30
|
+
rows: readonly RowPatch<Row>[],
|
|
31
|
+
): readonly string[] => {
|
|
32
|
+
const properties = Object.keys(entity.$columns).filter((property) =>
|
|
33
|
+
rows.some((row) => writes(row, property)),
|
|
34
|
+
);
|
|
35
|
+
for (const [position, row] of rows.entries()) {
|
|
36
|
+
const missing = properties.find((property) => !writes(row, property));
|
|
37
|
+
if (missing !== undefined) throw unevenCopy(entity.$name, position, missing);
|
|
38
|
+
}
|
|
39
|
+
return properties;
|
|
40
|
+
};
|
package/src/declared-index.ts
CHANGED
|
@@ -66,7 +66,8 @@ export const declaredIndexOf = <C extends ColumnMap>(
|
|
|
66
66
|
// Absent stays absent: `btree` written out would be a field every existing snapshot lacks,
|
|
67
67
|
// and `indexMethodOf` reads the two the same way precisely so nothing regenerates.
|
|
68
68
|
...(index.using === undefined || index.using === 'btree' ? {} : { using: index.using }),
|
|
69
|
-
// How it is BUILT, so not part of the name
|
|
70
|
-
|
|
69
|
+
// How it is BUILT, so not part of the name. Absent stays absent — the default every existing
|
|
70
|
+
// index already projects — and only an explicit ask, either way, rides along.
|
|
71
|
+
...(index.concurrently === undefined ? {} : { concurrently: index.concurrently }),
|
|
71
72
|
};
|
|
72
73
|
};
|
package/src/describe.ts
CHANGED
|
@@ -363,8 +363,9 @@ export const describeEntity = <Row>(input: DescribeInput<Row>): EntityDescriptio
|
|
|
363
363
|
// Spread, never `?? null`: absent is what `@ultimat3/db` reads as the btree it always was,
|
|
364
364
|
// and a written-out `null` would be a field no existing snapshot carries.
|
|
365
365
|
...(index.using === undefined ? {} : { using: index.using }),
|
|
366
|
-
//
|
|
367
|
-
|
|
366
|
+
// Absent stays absent for the same reason — `x verify` hashes this projection, and an index
|
|
367
|
+
// that asks nothing must hash what it always did. An explicit ask, `true` or `false`, rides.
|
|
368
|
+
...(index.concurrently === undefined ? {} : { concurrently: index.concurrently }),
|
|
368
369
|
})),
|
|
369
370
|
tags: input.tags,
|
|
370
371
|
cacheTag: input.cacheTag,
|
package/src/driver-repo-reads.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { countsFrom, groupColumnOf } from './count-by';
|
|
|
8
8
|
import { cursorFor, seekFrom } from './cursor';
|
|
9
9
|
import { projectRow } from './driver-rows';
|
|
10
10
|
import type { DriverScope } from './driver-scope';
|
|
11
|
+
import { assertPageBytes } from './page-bytes';
|
|
11
12
|
import { idPlan, readPlan, singleKeyOf } from './plan';
|
|
12
13
|
import type { Repo } from './repo';
|
|
13
14
|
import { rowKey } from './row-key';
|
|
@@ -50,10 +51,10 @@ export const driverReads = <Row>(scope: DriverScope<Row>): DriverReads<Row> => {
|
|
|
50
51
|
found.length > plan.limit && last !== undefined
|
|
51
52
|
? cursorFor(entity, plan, last, rowKey(entity, last))
|
|
52
53
|
: null;
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
);
|
|
54
|
+
// Weighed projected, as memory weighs it: a store's page is bounded like the other two.
|
|
55
|
+
const projected = page.map((row) => projectRow(entity, plan, row));
|
|
56
|
+
assertPageBytes(entity, op, projected as readonly Readonly<Record<string, unknown>>[]);
|
|
57
|
+
return pageOf(projected, next);
|
|
57
58
|
},
|
|
58
59
|
|
|
59
60
|
async count(args = {}) {
|
|
@@ -3,9 +3,12 @@
|
|
|
3
3
|
// tenant, before the store is called — and the store is handed only scoped plans and judged rows.
|
|
4
4
|
|
|
5
5
|
import { refuseAbandoned } from '@ultimat3/db';
|
|
6
|
+
import { keyOf } from './batch-read';
|
|
6
7
|
import { conflictKeys, upsertPlan } from './bulk-write';
|
|
7
8
|
import { entityNow } from './clock';
|
|
8
9
|
import { narrowRow } from './columns';
|
|
10
|
+
import { copyColumns } from './copy-plan';
|
|
11
|
+
import { kindOf, valueAt } from './cursor';
|
|
9
12
|
import { byKeys, checkedDelete } from './driver-delete';
|
|
10
13
|
import type { DriverScope } from './driver-scope';
|
|
11
14
|
import {
|
|
@@ -17,16 +20,29 @@ import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
|
|
|
17
20
|
import { notFound } from './errors';
|
|
18
21
|
import { assertedRowsTooMany, MAX_ASSERTED_ROWS } from './invariants';
|
|
19
22
|
import { mergedRow } from './memory-update';
|
|
20
|
-
import {
|
|
23
|
+
import { idPlan, namedColumns, singleKeyOf } from './plan';
|
|
21
24
|
import type { Repo, RepoOptions, Tx } from './repo';
|
|
25
|
+
import { rowKey } from './row-key';
|
|
22
26
|
import { advancingVersionColumn, deletionStamp, VERSION_STEP_MS } from './search-index-version';
|
|
23
27
|
import { writtenRowsSink } from './search-written-rows';
|
|
24
28
|
import { assertRowTenant, type QueryPlan } from './tenancy';
|
|
25
29
|
import type { RowPatch, RowWrite } from './types';
|
|
30
|
+
import { judgeUpdateMany, updateManyPlan } from './update-many';
|
|
31
|
+
import { updateWherePlan, writeWherePlan } from './write-where';
|
|
26
32
|
|
|
27
33
|
export type DriverWrites<Row> = Pick<
|
|
28
34
|
Repo<Row>,
|
|
29
|
-
|
|
35
|
+
| 'insert'
|
|
36
|
+
| 'insertAll'
|
|
37
|
+
| 'upsertAll'
|
|
38
|
+
| 'update'
|
|
39
|
+
| 'delete'
|
|
40
|
+
| 'deleteWhere'
|
|
41
|
+
| 'updateWhere'
|
|
42
|
+
| 'insertAllCount'
|
|
43
|
+
| 'upsertAllCount'
|
|
44
|
+
| 'copyAll'
|
|
45
|
+
| 'updateMany'
|
|
30
46
|
>;
|
|
31
47
|
|
|
32
48
|
export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> => {
|
|
@@ -148,7 +164,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
|
|
|
148
164
|
)
|
|
149
165
|
: checkedDelete(scope, op, plan, options);
|
|
150
166
|
|
|
151
|
-
|
|
167
|
+
const writes: DriverWrites<Row> = {
|
|
152
168
|
async insert(values, options) {
|
|
153
169
|
refuseAbandoned();
|
|
154
170
|
const [row] = judged('insert', [values]);
|
|
@@ -221,16 +237,76 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
|
|
|
221
237
|
async deleteWhere(filter, options) {
|
|
222
238
|
refuseAbandoned();
|
|
223
239
|
const op = 'deleteWhere';
|
|
224
|
-
return removed(op, scope.storePlan(op,
|
|
240
|
+
return removed(op, scope.storePlan(op, writeWherePlan(entity, filter, options, op)), options);
|
|
225
241
|
},
|
|
226
242
|
|
|
227
243
|
async updateWhere(filter, given, options) {
|
|
228
244
|
refuseAbandoned();
|
|
229
245
|
const op = 'updateWhere';
|
|
230
246
|
const patch = entity.$parsePatch(given) as RowPatch<Row>;
|
|
231
|
-
const plan = scope.storePlan(op,
|
|
247
|
+
const plan = scope.storePlan(op, updateWherePlan(entity, filter, patch, options, op));
|
|
232
248
|
assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
|
|
233
249
|
return patched(op, plan, patch, options);
|
|
234
250
|
},
|
|
251
|
+
|
|
252
|
+
// A store answers rows from every insert, so the count is their length: one judging path.
|
|
253
|
+
insertAllCount: async (given, options) => (await writes.insertAll(given, options)).length,
|
|
254
|
+
upsertAllCount: async (given, args) => (await writes.upsertAll(given, args)).length,
|
|
255
|
+
copyAll: async (given, options) => {
|
|
256
|
+
copyColumns(entity, given as readonly RowPatch<Row>[]);
|
|
257
|
+
return (await writes.insertAll(given, options)).length;
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Judged as ONE batch first — tenant, invariants, keys, same-tenant references, the shape
|
|
262
|
+
* `memoryRepo` judges — then one `patched` write per row, since a store's `update` sets one
|
|
263
|
+
* patch on every row it matches. That is n store calls, so a refusal part way (a unique the
|
|
264
|
+
* store judges against a row outside the batch) writes the rows already moved BACK before it
|
|
265
|
+
* rethrows: all or nothing, as `updateWhere`'s single call is. Missing, soft-deleted and other
|
|
266
|
+
* tenants' ids are not counted.
|
|
267
|
+
*/
|
|
268
|
+
async updateMany(given, options) {
|
|
269
|
+
refuseAbandoned();
|
|
270
|
+
const op = 'updateMany';
|
|
271
|
+
const plan = updateManyPlan(entity, given, options);
|
|
272
|
+
if (plan.patches.length === 0) return 0;
|
|
273
|
+
const tx = scope.txOf(op, options);
|
|
274
|
+
const match = scope.storePlan(op, plan.match);
|
|
275
|
+
const found = scope.checked(
|
|
276
|
+
op,
|
|
277
|
+
match,
|
|
278
|
+
await raw.select({ plan: match, after: undefined, limit: plan.patches.length, tx }),
|
|
279
|
+
);
|
|
280
|
+
const merged = judgeUpdateMany(entity, plan, found, [], (row) => rowKey(entity, row));
|
|
281
|
+
await references(merged);
|
|
282
|
+
const kind = kindOf(entity, plan.key) ?? '';
|
|
283
|
+
const cell = (row: unknown) => keyOf(kind, valueAt(row, plan.key));
|
|
284
|
+
const before = new Map(found.map((row) => [cell(row), row]));
|
|
285
|
+
const after = new Map(merged.map((row, at) => [cell(found[at]), row]));
|
|
286
|
+
const moved: (readonly [Row, Row])[] = [];
|
|
287
|
+
let written = 0;
|
|
288
|
+
try {
|
|
289
|
+
for (const { id, patch } of plan.patches) {
|
|
290
|
+
const stored = before.get(keyOf(kind, id));
|
|
291
|
+
const result = after.get(keyOf(kind, id));
|
|
292
|
+
if (stored === undefined || result === undefined) continue;
|
|
293
|
+
const one = scope.storePlan(op, idPlan(entity, id, options, op));
|
|
294
|
+
const count = await patched(op, one, patch, options);
|
|
295
|
+
if (count > 0) moved.push([stored, result]);
|
|
296
|
+
written += count;
|
|
297
|
+
}
|
|
298
|
+
} catch (error) {
|
|
299
|
+
for (const [stored, result] of moved.reverse()) {
|
|
300
|
+
const where = idPlan(entity, String(valueAt(result, plan.key)), options, op);
|
|
301
|
+
const values = Object.fromEntries(
|
|
302
|
+
[...plan.properties, plan.key].map((property) => [property, valueAt(stored, property)]),
|
|
303
|
+
);
|
|
304
|
+
await raw.update({ plan: scope.storePlan(op, where, true), tx }, values);
|
|
305
|
+
}
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
return written;
|
|
309
|
+
},
|
|
235
310
|
};
|
|
311
|
+
return writes;
|
|
236
312
|
};
|
package/src/entity-error.ts
CHANGED
|
@@ -53,6 +53,7 @@ export const ENTITY_ERROR_CODES = [
|
|
|
53
53
|
'X_DRIVER_CAPABILITY_MISSING',
|
|
54
54
|
'X_DRIVER_ROW_OUT_OF_SCOPE',
|
|
55
55
|
'X_ENTITY_PARTITION_INVALID',
|
|
56
|
+
'X_ENTITY_PAGE_TOO_LARGE',
|
|
56
57
|
] as const;
|
|
57
58
|
|
|
58
59
|
export type EntityErrorCode = (typeof ENTITY_ERROR_CODES)[number];
|
|
@@ -103,6 +104,7 @@ export const ENTITY_ERROR_TITLES: Readonly<Record<EntityErrorCode, string>> = {
|
|
|
103
104
|
X_DRIVER_ROW_OUT_OF_SCOPE: 'a custom driver returned a row outside the plan it was given',
|
|
104
105
|
X_ENTITY_PARTITION_INVALID:
|
|
105
106
|
'entity({ partitionBy }) declares a partitioning Postgres cannot build',
|
|
107
|
+
X_ENTITY_PAGE_TOO_LARGE: 'a page weighed more than the page byte bound before it was decoded',
|
|
106
108
|
};
|
|
107
109
|
|
|
108
110
|
// Registered at module load, unconditionally, in one call. Without this the registry humanises the
|
package/src/index-identity.ts
CHANGED
|
@@ -28,8 +28,9 @@ const identity = (index: IndexDef): string =>
|
|
|
28
28
|
* definition keeps both, and two `create index` statements sharing a name is `42P07` on the next
|
|
29
29
|
* migration.
|
|
30
30
|
*
|
|
31
|
-
* A duplicate
|
|
32
|
-
*
|
|
31
|
+
* A duplicate's ask about how to build is handed to the one kept: `true` over everything, since
|
|
32
|
+
* dropping it would build a hot table's index inside a transaction after all, then an explicit
|
|
33
|
+
* `false` over the default it opted out of.
|
|
33
34
|
*/
|
|
34
35
|
export function distinctIndexes(declared: readonly IndexDef[]): readonly IndexDef[] {
|
|
35
36
|
return declared
|
|
@@ -37,10 +38,14 @@ export function distinctIndexes(declared: readonly IndexDef[]): readonly IndexDe
|
|
|
37
38
|
(index, position) =>
|
|
38
39
|
declared.findIndex((other) => identity(other) === identity(index)) === position,
|
|
39
40
|
)
|
|
40
|
-
.map((index) =>
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
41
|
+
.map((index) => {
|
|
42
|
+
const asks = declared
|
|
43
|
+
.filter((other) => identity(other) === identity(index))
|
|
44
|
+
.map((other) => other.concurrently);
|
|
45
|
+
const ask = asks.includes(true) ? true : asks.includes(false) ? false : undefined;
|
|
46
|
+
// `undefined` means no duplicate asked, so `index` itself asked nothing either.
|
|
47
|
+
return ask === undefined || ask === index.concurrently
|
|
48
|
+
? index
|
|
49
|
+
: { ...index, concurrently: ask };
|
|
50
|
+
});
|
|
46
51
|
}
|
package/src/index-init.ts
CHANGED
|
@@ -36,6 +36,9 @@ export interface IndexInit<C extends ColumnMap> {
|
|
|
36
36
|
* `<id>_concurrently.sql` beside the migration (or as the migration, when it is the only change),
|
|
37
37
|
* marked `-- transaction: false`; an index on a table the same migration creates is still built
|
|
38
38
|
* inside that migration's transaction — the table is empty and nobody else can see it.
|
|
39
|
+
*
|
|
40
|
+
* Absent is the default: concurrent on a table that already exists; `false` is the plain build
|
|
41
|
+
* `x db gen` marks `-- lock-heavy: true`.
|
|
39
42
|
*/
|
|
40
43
|
readonly concurrently?: boolean;
|
|
41
44
|
}
|
package/src/index.ts
CHANGED
|
@@ -87,6 +87,9 @@ export { memoryRepo, memoryTransactor } from './memory-repo';
|
|
|
87
87
|
export type { StatementLoop } from './n-plus-one';
|
|
88
88
|
export { N_PLUS_ONE_THRESHOLD, nPlusOne, preloadsFor } from './n-plus-one';
|
|
89
89
|
export { isOperator, OPERATORS } from './operator';
|
|
90
|
+
// The two page bounds, beside `N_PLUS_ONE_THRESHOLD` and for the same reason: an app validating
|
|
91
|
+
// its own `pageSize` input against a hardcoded 10_000 is a second declaration of one number.
|
|
92
|
+
export { MAX_PAGE_BYTES } from './page-bytes';
|
|
90
93
|
// `entity({ partitionBy })`, checked at declaration (`partition.ts`); the SQL is `@ultimat3/db`'s.
|
|
91
94
|
export type {
|
|
92
95
|
PartitionContext,
|
|
@@ -109,14 +112,13 @@ export type { PostgresDriverOptions } from './pg-driver';
|
|
|
109
112
|
export { postgresDriver, postgresRepo } from './pg-driver';
|
|
110
113
|
export { decodeRow } from './pg-row';
|
|
111
114
|
export { postgresTransactor } from './pg-transactor';
|
|
112
|
-
// The two page bounds, beside `N_PLUS_ONE_THRESHOLD` and for the same reason: an app validating
|
|
113
|
-
// its own `pageSize` input against a hardcoded 10_000 is a second declaration of one number.
|
|
114
115
|
export { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from './plan';
|
|
115
116
|
export type { RelatedTable, RelatedTables } from './preload';
|
|
116
117
|
export type { PreloadOptions } from './preload-ceiling';
|
|
117
118
|
export { MAX_PRELOADED_ROWS } from './preload-ceiling';
|
|
118
119
|
export type { Preloaded, ReadBuilder, Table } from './query';
|
|
119
120
|
export { tableFor } from './query';
|
|
121
|
+
export type { ChainWrites, Returned, TableBulkWrites, Unreturned } from './query-write';
|
|
120
122
|
export type {
|
|
121
123
|
ReadAggregates,
|
|
122
124
|
SeriesOptions,
|
|
@@ -150,6 +152,7 @@ export {
|
|
|
150
152
|
export type { EntityRelations, Relation, RelationKind, RelationMap } from './relations';
|
|
151
153
|
export { relationMap, relationNamed, relationsFor, relationsOf } from './relations';
|
|
152
154
|
export type {
|
|
155
|
+
FilteredWriteOptions,
|
|
153
156
|
FindByIdOptions,
|
|
154
157
|
FindManyArgs,
|
|
155
158
|
MemoryRepo,
|
|
@@ -157,6 +160,7 @@ export type {
|
|
|
157
160
|
RepoOptions,
|
|
158
161
|
Transactor,
|
|
159
162
|
Tx,
|
|
163
|
+
UpdateManyRow,
|
|
160
164
|
UpsertArgs,
|
|
161
165
|
} from './repo';
|
|
162
166
|
export type { Retain, RetainInit } from './retain';
|
package/src/memory-observed.ts
CHANGED
|
@@ -32,6 +32,10 @@ const OPERATIONS = {
|
|
|
32
32
|
insert: { verb: 'insert', rows: one },
|
|
33
33
|
insertAll: { verb: 'insert', rows: listed },
|
|
34
34
|
upsertAll: { verb: 'insert', rows: listed },
|
|
35
|
+
insertAllCount: { verb: 'insert', rows: counted },
|
|
36
|
+
upsertAllCount: { verb: 'insert', rows: counted },
|
|
37
|
+
copyAll: { verb: 'insert', rows: counted },
|
|
38
|
+
updateMany: { verb: 'update', rows: counted },
|
|
35
39
|
update: { verb: 'update', rows: one },
|
|
36
40
|
updateWhere: { verb: 'update', rows: counted },
|
|
37
41
|
delete: { verb: 'delete', rows: () => 1 },
|