@ultimat3/entity 31.8.0 → 31.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CLAUDE.md +2 -1
  2. package/README.md +78 -1
  3. package/package.json +5 -5
  4. package/src/adapter.ts +2 -2
  5. package/src/aggregate.ts +1 -1
  6. package/src/all-truncated.ts +33 -0
  7. package/src/append-only-errors.ts +2 -1
  8. package/src/append-only.ts +24 -2
  9. package/src/batch-bytes.ts +34 -0
  10. package/src/bulk-write-send.ts +38 -5
  11. package/src/bulk-write.ts +3 -0
  12. package/src/copy-plan.ts +40 -0
  13. package/src/counter-observed.ts +199 -0
  14. package/src/database.ts +4 -2
  15. package/src/declared-index-keys.ts +65 -0
  16. package/src/declared-index.ts +6 -1
  17. package/src/define-driver.ts +24 -2
  18. package/src/describe.ts +6 -0
  19. package/src/driver-counters.ts +21 -0
  20. package/src/driver-repo-reads.ts +76 -9
  21. package/src/driver-repo-writes.ts +104 -6
  22. package/src/driver-versioned-write.ts +99 -0
  23. package/src/entity-error.ts +6 -0
  24. package/src/entity-indexes.ts +118 -0
  25. package/src/entity.ts +20 -49
  26. package/src/history-purge.ts +15 -0
  27. package/src/index-def.ts +35 -0
  28. package/src/index-identity.ts +5 -0
  29. package/src/index-init.ts +13 -1
  30. package/src/index-name.ts +25 -6
  31. package/src/index.ts +19 -2
  32. package/src/latest-by-sql.ts +93 -0
  33. package/src/latest-by.ts +249 -0
  34. package/src/lock-key.ts +56 -3
  35. package/src/lock-unsupported.ts +5 -2
  36. package/src/measures.ts +157 -0
  37. package/src/memory-aggregates.ts +9 -16
  38. package/src/memory-latest-by.ts +34 -0
  39. package/src/memory-lock.ts +15 -1
  40. package/src/memory-match.ts +2 -0
  41. package/src/memory-measures.ts +75 -0
  42. package/src/memory-observed.ts +7 -1
  43. package/src/memory-repo.ts +60 -6
  44. package/src/memory-update.ts +17 -4
  45. package/src/page-bytes.ts +127 -0
  46. package/src/pg-aggregates.ts +9 -3
  47. package/src/pg-bulk-repo.ts +163 -0
  48. package/src/pg-copy.ts +87 -0
  49. package/src/pg-driver.ts +31 -72
  50. package/src/pg-latest-by.ts +57 -0
  51. package/src/pg-lock.ts +24 -4
  52. package/src/pg-measures.ts +64 -0
  53. package/src/pg-sql-aggregate.ts +9 -3
  54. package/src/pg-sql-measures.ts +102 -0
  55. package/src/pg-sql.ts +37 -6
  56. package/src/pg-update-many-sql.ts +146 -0
  57. package/src/pg-values-list.ts +55 -0
  58. package/src/pg-write-sql.ts +42 -26
  59. package/src/plan.ts +1 -56
  60. package/src/preload-ceiling.ts +73 -7
  61. package/src/preload.ts +17 -1
  62. package/src/query-write.ts +169 -0
  63. package/src/query.ts +38 -48
  64. package/src/read-aggregates.ts +87 -3
  65. package/src/registry.ts +29 -0
  66. package/src/repo.ts +74 -3
  67. package/src/row-observer.ts +68 -5
  68. package/src/sealed-repo.ts +78 -9
  69. package/src/search-mirrored-repo.ts +53 -0
  70. package/src/search-repo.ts +20 -2
  71. package/src/table-locks.ts +16 -1
  72. package/src/tenant-index.ts +84 -9
  73. package/src/text-contains.ts +53 -0
  74. package/src/type-pins.ts +9 -0
  75. package/src/types.ts +2 -22
  76. package/src/unique-constraints.ts +3 -1
  77. package/src/update-many-send.ts +97 -0
  78. package/src/update-many.ts +175 -0
  79. package/src/version-lock-errors.ts +42 -0
  80. package/src/version-lock.ts +177 -0
  81. package/src/view-repo.ts +4 -0
  82. package/src/write-where.ts +164 -0
package/CLAUDE.md CHANGED
@@ -136,10 +136,11 @@ 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**: empty filter `X_WRITE_UNFILTERED`,
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`.
143
+ - **Sweep 5b seams** (`read-wrappers.test.ts`, `history-purge.test.ts`): `Repo.latestBy?`/`aggregates?`/`lockKeys?` optional, each forwarded by sealed (refuses sealed group/order/measure/filter columns, opens rows), search-repo and memory-observed; `countBy`'s 3rd arg `{ where }` forwarded everywhere. `defineDriver` composes filtered `countBy` and `aggregates` from existing capabilities; a versioned entity there takes the judged path, one CAS store write per row. `update(id)` calls `assertVersionedUpdate` in all three drivers. `purgingHistory` (`history-purge.ts`) is the only door out of a history table. `IndexDef` carries `expression`/`orders`/`include`/`operatorClass` (types.ts; checked in `declared-index-keys.ts`, rendered by db); one covering rule for implicit indexes (`coveringIndexOf`). Files: `latest-by*.ts`, `measures.ts`, `text-contains.ts`, `version-lock*.ts`, `lock-key.ts`, `counter-observed.ts`, `all-truncated.ts`.
143
144
  - **A write past a coded abort is refused on both drivers**: `refuseAbandoned()` in `writing()` and each `memoryRepo` write. `write-abandon.test.ts`.
144
145
  - **Every instant the write path stamps comes from `entityNow()`** (`clock.ts`, `ctx.clock`).
145
146
  **`touch()` in `touch.ts` is the ONE place `onUpdateNow()` columns are stamped.**
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
- `DEFAULT_PAGE_SIZE`, `MAX_PAGE_SIZE` and `MAX_ASSERTED_ROWS` are exported, beside
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
 
@@ -729,6 +733,54 @@ for (const id of ids) await db.posts.update(id, { likeCount: counts.get(id) ?? 0
729
733
  | More than 1000 groups | `X_INVARIANT_VIOLATED`, never a truncated map — the statement asks for one group past the bound, exactly as a page reads one row past its limit. The `fix` spells the `andWhere('<column>', 'in', <values>)` that bounds it |
730
734
  | Statement | `select "post_id" as group_value, count(*) as group_count … group by "post_id"`. Both names are fixed aliases, so an entity may still declare a column called `count`, and the grouped value is re-parsed by the column that declared it |
731
735
 
736
+ ## Newest per group, several measures, many locks, a version
737
+
738
+ ```ts
739
+ import { database, entity, integer, money, text, timestamp, uuid } from '@ultimat3/entity';
740
+
741
+ const messages = entity('messages', {
742
+ columns: { id: uuid().primaryKey(), conversationId: uuid(), body: text(), createdAt: timestamp() },
743
+ });
744
+ const posts = entity('posts', {
745
+ columns: { id: uuid().primaryKey(), orgId: uuid(), authorId: uuid(), status: text() },
746
+ });
747
+ const payments = entity('payments', {
748
+ columns: { id: uuid().primaryKey(), orgId: uuid(), amount: money(), status: text() },
749
+ });
750
+ const accounts = entity('accounts', { columns: { id: uuid().primaryKey(), balance: integer() } });
751
+ const db = database({ messages, posts, payments, accounts });
752
+ declare const ids: string[];
753
+ declare const orgId: string;
754
+ declare const from: string;
755
+ declare const to: string;
756
+
757
+ // One DISTINCT ON statement: the newest message of each conversation (memory mirrors it)
758
+ await db.messages.andWhere('conversationId', 'in', ids).latestBy('conversationId', { order: 'createdAt' });
759
+
760
+ // count(*) filter (where …): a group the filter empties answers 0, never absent
761
+ await db.posts.where({ orgId }).countBy('authorId', { where: [['status', 'eq', 'published']] });
762
+ // Several measures, one statement
763
+ await db.payments.where({ orgId }).aggregate({
764
+ total: { fn: 'count' },
765
+ paid: { fn: 'sum', column: 'amount', where: [['status', 'eq', 'paid']] },
766
+ });
767
+
768
+ // Every key held for fn, in ONE transaction, taken in sorted order: no deadlock between callers
769
+ await db.accounts.lockKeys(['acct:' + from, 'acct:' + to], async (tx) => { /* … */ });
770
+ ```
771
+
772
+ | | |
773
+ |---|---|
774
+ | `latestBy(group, { order, direction? })` | one row per group, ties to the primary key, groups ordered `null` last; past `MAX_LATEST_GROUPS` refused, never truncated; `orderBy()`/`limit()`/`after()` on the same chain refused. `Repo.latestBy?` is optional: without it (a hand-written repository, a custom store) paged `findMany` reads are folded — correct, never one statement. `preload(rel, { perParent: n })` reads n per parent in one `LATERAL` |
775
+ | `countBy(col, { where })` · `aggregate({ name: { fn, column?, where? } })` | one statement on Postgres and memory; at most `MAX_MEASURES`; `sum`/`avg` decimal text, money a `MoneyValue`, never a float. A `defineDriver` store composes them from the capabilities it declares (`aggregate:countBy`, `aggregate:<fn>`): several store calls, the same answer |
776
+ | `andWhere(col, 'contains', term)` on `text()`/`char()` | case-insensitive substring (`ilike`, the term bound and escaped). Served by a trigram index only — declare `indexes: [{ on: ['<col>'], using: 'gin', operatorClass: 'gin_trgm_ops' }]` (`trigramDeclaration(col)`); the plan sweep reports one without it |
777
+ | `indexes:` key parts | four optional fields beside `on`, each absent by default so no existing index name or schema hash moves (`declared-index-keys.ts`, refused at `entity()` with `X_INVARIANT_VIOLATED`): `expression: 'lower(email)'` — the ONE key is that SQL over physical columns, `on` names the columns it reads (a concurrent `refreshView` refuses it as its unique key); `orders: ['desc', null]` — a direction per key, btree only, never beside `order`; `include: ['title']` — INCLUDE payload, btree only; `operatorClass: 'gin_trgm_ops'` — needs `using: 'gin'`. A foreign-key index another index already leads with is still emitted — dropping it would make an existing app's next `x db gen` remove an index the database holds — and is listed on `RegistryEntry.coveredIndexes` (`CoveredIndex`: the index and the one that covers it; `coveredImplicitIndexes`, `tenant-index.ts`) |
778
+ | `lockKeys(keys, fn)` | `lockKey`'s tenancy and hashing per key, deduped, sorted, at most `MAX_LOCK_KEYS` (64), one transaction; `X_LOCK_UNSUPPORTED` for a repository without it |
779
+ | `entity({ version: 'lockVersion' })` | an optimistic lock on an `integer().default(0)` column: `update(id, { …patch, lockVersion: row.lockVersion })` conditions on it and increments it — moved since the read is `X_ENTITY_STALE` (409), omitted is `X_ENTITY_VERSION_INVALID`. `updateMany` checks every row (one stale row refuses the batch). `updateWhere`/`updateAll`/`transition`/soft delete increment it and may not set it (compare-and-set goes in the filter: `where({ id, lockVersion: 3 })`). `upsertAll` with `onMatch: 'update'` is refused, `'nothing'` allowed. A mutator carries the version as input |
780
+ | `.all()` | one page; when a next page existed and the chain named no `limit()`, dev and test log `ALL_TRUNCATED` (`'entity.all.truncated'`) with the fix (`inBatches()` or `.limit(n)`) |
781
+ | a `countedIn` child write | reports each parent whose count moved as an `entity.row` `update` (read back in the write's transaction, only while subscribed; `before` = the count moved back; a filter-pinned bulk write reports `before: null`, an unpinned one `entity.bulk` for the parent) — `counter-observed.ts` |
782
+ | a subject's history erase | a history table is append-only in both drivers; `purgingHistory(name, work)` lets a filtered delete of THAT table through — the in-process twin of `x.purge`, which the GDPR erase opens (memory parity) |
783
+
732
784
  ## Writing by filter
733
785
 
734
786
  `deleteWhere`/`updateWhere` are the bulk forms of `delete`/`update` — the same fix `insertAll` is
@@ -746,8 +798,33 @@ db.participants.updateWhere({ conversationId, userId }, { lastReadAt }); // ->
746
798
 
747
799
  db.likes.deleteWhere({}); // X_WRITE_UNFILTERED, never every row
748
800
  db.participants.updateWhere({ conversationId }, {}); // X_PATCH_EMPTY, never a silent no-op
801
+
802
+ // A chain's predicates, any operator: the same write, `updateWhere`'s guards and reports
803
+ db.likes.where({ postId }).andWhere('userId', 'in', ids).deleteAll(); // -> n
804
+ db.posts.where({ authorId }).andWhere('publishedAt', 'is-null').updateAll({ status: 'draft' });
805
+ db.posts.where({ authorId }).limit(10).deleteAll(); // X_INVARIANT_VIOLATED: a write has no page
806
+
807
+ // A different patch per row, one statement per bind-count chunk; the same columns in every patch
808
+ db.posts.updateMany(rows.map(({ id, rank }) => ({ id, patch: { rank } }))); // -> rows written
749
809
  ```
750
810
 
811
+ `updateAll(patch)`/`deleteAll()` end any chain and run as `updateWhere`/`deleteWhere` with the
812
+ chain's predicates (`FilteredWriteOptions.where`): one plan builder (`write-where.ts`), so tenancy,
813
+ soft delete, invariant judging, `onUpdateNow()`, sealing (a lookup column matched as a read matches
814
+ it), the search mirror and the `entity.bulk` report cannot differ. No predicate is
815
+ `X_WRITE_UNFILTERED`; `limit()`, `after()` and `search()` are refused. `updateMany` is `Repo`-optional:
816
+ a hand-written repository without it gets one `updateWhere` per row from the typed handle.
817
+
818
+ | Bulk insert | Resolves | Statement |
819
+ |---|---|---|
820
+ | `insertAll(rows)` · `upsertAll(rows, args)` | the rows as stored | `insert … returning *` |
821
+ | `insertAll(rows, { returning: false })` · `upsertAll(rows, { …, returning: false })` | a count | no `returning`, nothing decoded |
822
+ | `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 |
823
+
824
+ All three judge rows identically (seal, tenant, invariants, defaults). The count forms still hand an
825
+ installed search index and an `entity.row` subscriber the rows: while either listens they run as
826
+ their returning counterpart.
827
+
751
828
  `delete(id)` and `update(id, patch)` both need a single-column primary key. A composite one —
752
829
  `likes`, `blocks`, `participants`, any join table — has no single id, so the filtered pair is the
753
830
  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.8.0",
3
+ "version": "31.10.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.8.0",
48
- "@ultimat3/db": "31.8.0",
49
- "@ultimat3/schema": "31.8.0",
50
- "@ultimat3/time": "31.8.0"
47
+ "@ultimat3/core": "31.10.0",
48
+ "@ultimat3/db": "31.10.0",
49
+ "@ultimat3/schema": "31.10.0",
50
+ "@ultimat3/time": "31.10.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';
package/src/aggregate.ts CHANGED
@@ -99,7 +99,7 @@ export const mixedCurrency = (
99
99
  return new EntityError({
100
100
  code: 'X_AGGREGATE_MIXED_CURRENCY',
101
101
  cause: `${entityName}.${fn}('${property}') covers ${scales.length} scales of ${only} (${scales.join(', ')}) — one minor unit is a different amount at each, so they have no common unit`,
102
- fix: `for await (const rows of ${entityName}.inBatches(1000)) { … } # fold row.${property} at ONE scale in the app: the scale is not a part a predicate can name`,
102
+ fix: `${entityName}.inBatches(1000) # for await (const rows of …): fold row.${property} at ONE scale in the app — the scale is not a part a predicate can name`,
103
103
  });
104
104
  }
105
105
  return new EntityError({
@@ -0,0 +1,33 @@
1
+ // Single responsibility: say, in development and test, that `.all()` dropped a next page. `.all()`
2
+ // answers one page (`DEFAULT_PAGE_SIZE` rows unless the chain says `.limit(n)`), and a caller that
3
+ // meant "every row" learns otherwise only from a missing row. Refusing is a break, so it waits for
4
+ // `next`; until then the warning is a `log.record` the exercise step can surface as a finding.
5
+
6
+ import { DEFAULT_ENVIRONMENT, logger, tryResolveEnvironment } from '@ultimat3/core';
7
+ import { DEFAULT_PAGE_SIZE } from './plan';
8
+
9
+ /** The one log message this writes: a subscriber matches `log.record`'s `message` against it. */
10
+ export const ALL_TRUNCATED = 'entity.all.truncated';
11
+
12
+ /**
13
+ * Called by `.all()` with the page's `nextCursor`. Silent with no next page, when the chain said
14
+ * `.limit(n)` (one page is what it asked for), and in staging or production — the warning is for
15
+ * the author, and staging exists to behave as production does. `env` is the test seam.
16
+ */
17
+ export function reportTruncatedAll(
18
+ entity: string,
19
+ next: string | null,
20
+ explicitLimit: boolean,
21
+ env?: Readonly<Record<string, string | undefined>>,
22
+ ): void {
23
+ if (next === null || explicitLimit) return;
24
+ const environment = tryResolveEnvironment(env === undefined ? undefined : { env });
25
+ const at = environment ?? DEFAULT_ENVIRONMENT;
26
+ if (at !== 'development' && at !== 'test') return;
27
+ logger.warn(ALL_TRUNCATED, {
28
+ entity,
29
+ pageSize: DEFAULT_PAGE_SIZE,
30
+ cause: `${entity}.….all() answered its first ${DEFAULT_PAGE_SIZE} rows and dropped the cursor to the rest`,
31
+ fix: `${entity}.….inBatches(1000) to visit every row, one page per statement — or .limit(${DEFAULT_PAGE_SIZE}) on the chain to state that one page is meant`,
32
+ });
33
+ }
@@ -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 === 'update' || call === 'updateWhere' ? 'the correction' : 'the reversal';
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
 
@@ -4,6 +4,7 @@
4
4
  // alike — and before any statement exists, so memory and Postgres answer the same code.
5
5
 
6
6
  import { appendOnlyColumnRefused, appendOnlyRefused } from './append-only-errors';
7
+ import { purgeNames } from './history-purge';
7
8
  import { readOnlyRefused } from './read-only';
8
9
  import type { Repo, UpsertArgs } from './repo';
9
10
  import type { AnyColumn } from './types';
@@ -17,6 +18,8 @@ export interface AppendOnlySource {
17
18
  readonly $viewQuery?: unknown;
18
19
  /** `entity({ readOnly })`'s reason: every write refused. Optional, as `$viewQuery` is. */
19
20
  readonly $readOnly?: string | null;
21
+ /** A history table's parent. Optional, as `$viewQuery` is: only a history table can be purged. */
22
+ readonly $historyOf?: string | null;
20
23
  }
21
24
 
22
25
  /**
@@ -75,7 +78,7 @@ export const appendOnlyRepo = <Row, R extends Repo<Row>>(entity: AppendOnlySourc
75
78
  const name = entity.$name;
76
79
  const refusing: Pick<
77
80
  Repo<Row>,
78
- 'update' | 'delete' | 'updateWhere' | 'deleteWhere' | 'upsertAll'
81
+ 'update' | 'delete' | 'updateWhere' | 'deleteWhere' | 'upsertAll' | 'updateMany'
79
82
  > = {
80
83
  update: async () => {
81
84
  throw appendOnlyRefused(name, 'update');
@@ -86,13 +89,32 @@ export const appendOnlyRepo = <Row, R extends Repo<Row>>(entity: AppendOnlySourc
86
89
  updateWhere: async () => {
87
90
  throw appendOnlyRefused(name, 'updateWhere');
88
91
  },
89
- deleteWhere: async () => {
92
+ // The one door out of a history table: a subject's erase, inside `purgingHistory` naming it.
93
+ deleteWhere: async (filter, options) => {
94
+ const historyOf = entity.$historyOf;
95
+ if (typeof historyOf === 'string' && purgeNames(name))
96
+ return repo.deleteWhere(filter, options);
90
97
  throw appendOnlyRefused(name, 'deleteWhere');
91
98
  },
99
+ updateMany: async () => {
100
+ throw appendOnlyRefused(name, 'updateMany');
101
+ },
92
102
  async upsertAll(rows, args: UpsertArgs<Row>) {
93
103
  if (args.onMatch !== 'nothing') throw appendOnlyRefused(name, 'upsertAll');
94
104
  return repo.upsertAll(rows, args);
95
105
  },
96
106
  };
107
+ // The count-only upsert is the same append, or the same refusal; absent stays absent.
108
+ const upsertAllCount = repo.upsertAllCount;
109
+ if (upsertAllCount !== undefined) {
110
+ return {
111
+ ...repo,
112
+ ...refusing,
113
+ async upsertAllCount(rows: Parameters<typeof upsertAllCount>[0], args: UpsertArgs<Row>) {
114
+ if (args.onMatch !== 'nothing') throw appendOnlyRefused(name, 'upsertAll');
115
+ return upsertAllCount.call(repo, rows, args);
116
+ },
117
+ };
118
+ }
97
119
  return { ...repo, ...refusing };
98
120
  };
@@ -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
+ };
@@ -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>(insertStatement(entity, chunk, shape));
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/bulk-write.ts CHANGED
@@ -12,6 +12,7 @@ import { EntityError, invariantViolated } from './errors';
12
12
  import { allColumns, columnsOf } from './pg-row';
13
13
  import type { RowPatch } from './types';
14
14
  import { uniqueConstraints } from './unique-constraints';
15
+ import { assertVersionedUpsert } from './version-lock';
15
16
 
16
17
  /**
17
18
  * Postgres binds at most 65535 parameters in one statement and a multi-row insert spends
@@ -235,6 +236,8 @@ export const upsertPlan = <Row>(
235
236
  );
236
237
  }
237
238
  if (onMatch === 'nothing') return { on: onConflict, set: [] };
239
+ // A collision overwrite never read the stored row, so it cannot honour a declared lock.
240
+ assertVersionedUpsert(entity, onMatch);
238
241
  const tenant = entity.$tenantColumn;
239
242
  if (tenant !== null && !onConflict.includes(tenant)) {
240
243
  throw crossTenantUpsert(entity.$name, tenant, onConflict);
@@ -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
+ };
@@ -0,0 +1,199 @@
1
+ // Single responsibility: the parent change a `countedIn` counter makes, reported. The trigger (and
2
+ // the memory driver's mirror, `memory-lifecycle.ts`) rewrites the parent row inside the child's
3
+ // write, where no repository sees it — so a live query over `posts` never heard a like. This reads
4
+ // the rewritten parents back, only while `entity.row` has a subscriber, and reports them.
5
+
6
+ import { currentWriteOrigin, instrument, subscribed } from '@ultimat3/core';
7
+ import { expectedQueryLoop } from '@ultimat3/db';
8
+ import { type Counter, countersTargeting } from './counter';
9
+ import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
10
+ import { MAX_PAGE_SIZE } from './plan';
11
+ import type { FilteredWriteOptions, Repo, RepoOptions } from './repo';
12
+ import { sealedFields } from './sealed';
13
+ import { afterCommit } from './write-commit';
14
+
15
+ /** How `database()` hands the observer a parent's repository: the driver's own, unwrapped. */
16
+ export type RepoOf = (entity: EntityCore) => Repo<unknown>;
17
+
18
+ type Row = Readonly<Record<string, unknown>>;
19
+
20
+ /** One parent a write moved: by how much (`null`: a filter's write, unknown), in which tenant. */
21
+ interface Moved {
22
+ readonly delta: number | null;
23
+ readonly tenant: string | undefined;
24
+ }
25
+
26
+ const ROW = 'entity.row';
27
+ const BULK = 'entity.bulk';
28
+
29
+ const asRow = (value: unknown): Row | null =>
30
+ typeof value === 'object' && value !== null ? (value as Row) : null;
31
+
32
+ /** The parent a child row counts into, or `undefined` when it counts nowhere (deleted, no key). */
33
+ const countedParent = (counter: Counter, row: unknown): string | undefined => {
34
+ const record = asRow(row);
35
+ if (record === null) return undefined;
36
+ if (counter.child.$softDelete && record[SOFT_DELETE_COLUMN] != null) return undefined;
37
+ const id = record[counter.references];
38
+ return typeof id === 'string' ? id : undefined;
39
+ };
40
+
41
+ /**
42
+ * The one value a filtered write pins `property` to: the filter's own, else a chain's `eq` predicate
43
+ * (`where({ postId }).deleteAll()` names its filter as predicates, not as the equality map).
44
+ */
45
+ const pinnedTo = (
46
+ filter: Row | null,
47
+ options: FilteredWriteOptions | undefined,
48
+ property: string,
49
+ ): unknown =>
50
+ filter?.[property] ??
51
+ options?.where?.find((each) => each.column === property && each.op === 'eq')?.value;
52
+
53
+ /** Whether a patch can move a counter: it sets the key, or the soft-delete stamp. */
54
+ const moves = (counter: Counter, patch: Row): boolean =>
55
+ counter.references in patch || (counter.child.$softDelete && SOFT_DELETE_COLUMN in patch);
56
+
57
+ export interface CounterEcho {
58
+ /** Row writes: each change as `[before, after]`, `null` on the side that did not exist. */
59
+ rows(changes: readonly (readonly [unknown, unknown])[], options?: RepoOptions): Promise<void>;
60
+ /** A filtered write (`deleteWhere`, `updateWhere`, `updateMany`) that changed `rows` rows. */
61
+ filtered(
62
+ filter: Row | null,
63
+ patch: Row | null,
64
+ rows: number,
65
+ options?: FilteredWriteOptions,
66
+ ): Promise<void>;
67
+ }
68
+
69
+ /** The echo for one child entity. `undefined` without a parent repository to read back from. */
70
+ export function counterEcho(
71
+ child: EntityCore,
72
+ repoOf: RepoOf | undefined,
73
+ ): CounterEcho | undefined {
74
+ if (repoOf === undefined) return undefined;
75
+
76
+ const bulk = (parent: EntityCore, rows: number, options: RepoOptions | undefined): void => {
77
+ if (rows > 0 && subscribed(BULK)) {
78
+ afterCommit(options, () => instrument(BULK, { entity: parent.$name, op: 'update', rows }));
79
+ }
80
+ };
81
+
82
+ /**
83
+ * Read the parents back in the write's own transaction, one statement per tenant and page of ids,
84
+ * and report each. `delta` known: `before` is the row with the count moved back; unknown: `null`,
85
+ * which is what replication reports without `REPLICA IDENTITY FULL` — wider, never wrong. The
86
+ * tenant is the write's, else the child row's own (a counter's parent shares its child's tenant).
87
+ * A refused read still reports, as a count a subscriber re-reads on.
88
+ */
89
+ const report = async (
90
+ counter: Counter,
91
+ moved: ReadonlyMap<string, Moved>,
92
+ options: RepoOptions | undefined,
93
+ ): Promise<void> => {
94
+ const { parent } = counter;
95
+ if (moved.size === 0) return;
96
+ const key = parent.$primaryKey[0] ?? 'id';
97
+ const byTenant = new Map<string | undefined, string[]>();
98
+ for (const [id, { tenant }] of moved) {
99
+ const scope = parent.$tenantColumn === null ? undefined : (options?.orgId ?? tenant);
100
+ byTenant.set(scope, [...(byTenant.get(scope) ?? []), id]);
101
+ }
102
+ const read = new Map<string, Row>();
103
+ try {
104
+ for (const [orgId, ids] of byTenant) {
105
+ for (let at = 0; at < ids.length; at += MAX_PAGE_SIZE) {
106
+ const chunk = ids.slice(at, at + MAX_PAGE_SIZE);
107
+ const page = await expectedQueryLoop(
108
+ 'the entity.row event reads back the parents a countedIn trigger moved — one per write',
109
+ () =>
110
+ repoOf(parent).findMany({
111
+ where: [{ column: key, op: 'in', value: chunk }],
112
+ limit: chunk.length,
113
+ ...(options?.tx === undefined ? {} : { tx: options.tx }),
114
+ ...(orgId === undefined ? {} : { orgId }),
115
+ }),
116
+ );
117
+ for (const row of page.rows) {
118
+ const record = asRow(row);
119
+ if (record !== null) read.set(String(record[key]), record);
120
+ }
121
+ }
122
+ }
123
+ } catch {
124
+ bulk(parent, moved.size, options);
125
+ return;
126
+ }
127
+ const sealed = sealedFields(parent).map((field) => field.property);
128
+ const shown = (row: Row): Row =>
129
+ Object.fromEntries(Object.entries(row).filter(([property]) => !sealed.includes(property)));
130
+ const write = currentWriteOrigin();
131
+ for (const [id, { delta }] of moved) {
132
+ const after = read.get(id);
133
+ if (after === undefined) continue;
134
+ const before =
135
+ delta === null
136
+ ? null
137
+ : { ...after, [counter.column]: Number(after[counter.column]) - delta };
138
+ const change = {
139
+ entity: parent.$name,
140
+ op: 'update' as const,
141
+ before: before === null ? null : shown(before),
142
+ after: shown(after),
143
+ ...(write === undefined ? {} : { write }),
144
+ };
145
+ afterCommit(options, () => instrument(ROW, change));
146
+ }
147
+ };
148
+
149
+ /** The child row's tenant, which a counted parent shares. */
150
+ const tenantOf = (row: unknown): string | undefined => {
151
+ const column = child.$tenantColumn;
152
+ const value = column === null ? undefined : asRow(row)?.[column];
153
+ return typeof value === 'string' ? value : undefined;
154
+ };
155
+
156
+ return {
157
+ async rows(changes, options) {
158
+ if (!subscribed(ROW)) return;
159
+ for (const counter of countersTargeting(child.$name)) {
160
+ const moved = new Map<string, Moved>();
161
+ const move = (row: unknown, by: number): void => {
162
+ const id = countedParent(counter, row);
163
+ if (id === undefined) return;
164
+ const delta = (moved.get(id)?.delta ?? 0) + by;
165
+ moved.set(id, { delta, tenant: tenantOf(row) });
166
+ };
167
+ for (const [before, after] of changes) {
168
+ move(before, -1);
169
+ move(after, 1);
170
+ }
171
+ for (const [id, { delta }] of moved) if (delta === 0) moved.delete(id);
172
+ await report(counter, moved, options);
173
+ }
174
+ },
175
+
176
+ async filtered(filter, patch, rows, options) {
177
+ if (rows === 0 || !(subscribed(ROW) || subscribed(BULK))) return;
178
+ for (const counter of countersTargeting(child.$name)) {
179
+ if (patch !== null && !moves(counter, patch)) continue;
180
+ const from = pinnedTo(filter, options, counter.references);
181
+ const to = patch === null ? undefined : patch[counter.references];
182
+ // Pinned: the filter names one parent, and the patch names one or keeps it — so the
183
+ // parents that moved are known, though not by how much.
184
+ const pinned =
185
+ typeof from === 'string' && (to === undefined || to === null || typeof to === 'string');
186
+ if (!pinned || !subscribed(ROW)) {
187
+ bulk(counter.parent, rows, options);
188
+ continue;
189
+ }
190
+ const scope = child.$tenantColumn;
191
+ const pinnedTenant = scope === null ? undefined : pinnedTo(filter, options, scope);
192
+ const tenant = typeof pinnedTenant === 'string' ? pinnedTenant : undefined;
193
+ const moved = new Map<string, Moved>([[from, { delta: null, tenant }]]);
194
+ if (typeof to === 'string') moved.set(to, { delta: null, tenant });
195
+ await report(counter, moved, options);
196
+ }
197
+ },
198
+ };
199
+ }