@ultimat3/entity 31.9.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 (69) hide show
  1. package/CLAUDE.md +1 -0
  2. package/README.md +48 -0
  3. package/package.json +5 -5
  4. package/src/aggregate.ts +1 -1
  5. package/src/all-truncated.ts +33 -0
  6. package/src/append-only.ts +8 -1
  7. package/src/bulk-write.ts +3 -0
  8. package/src/counter-observed.ts +199 -0
  9. package/src/database.ts +4 -2
  10. package/src/declared-index-keys.ts +65 -0
  11. package/src/declared-index.ts +6 -1
  12. package/src/define-driver.ts +24 -2
  13. package/src/describe.ts +6 -0
  14. package/src/driver-counters.ts +21 -0
  15. package/src/driver-repo-reads.ts +71 -5
  16. package/src/driver-repo-writes.ts +23 -1
  17. package/src/driver-versioned-write.ts +99 -0
  18. package/src/entity-error.ts +4 -0
  19. package/src/entity-indexes.ts +118 -0
  20. package/src/entity.ts +20 -49
  21. package/src/history-purge.ts +15 -0
  22. package/src/index-def.ts +35 -0
  23. package/src/index-identity.ts +5 -0
  24. package/src/index-init.ts +13 -1
  25. package/src/index-name.ts +25 -6
  26. package/src/index.ts +13 -0
  27. package/src/latest-by-sql.ts +93 -0
  28. package/src/latest-by.ts +249 -0
  29. package/src/lock-key.ts +56 -3
  30. package/src/lock-unsupported.ts +5 -2
  31. package/src/measures.ts +157 -0
  32. package/src/memory-aggregates.ts +9 -16
  33. package/src/memory-latest-by.ts +34 -0
  34. package/src/memory-lock.ts +15 -1
  35. package/src/memory-match.ts +2 -0
  36. package/src/memory-measures.ts +75 -0
  37. package/src/memory-observed.ts +3 -1
  38. package/src/memory-repo.ts +17 -1
  39. package/src/memory-update.ts +7 -1
  40. package/src/pg-aggregates.ts +9 -3
  41. package/src/pg-bulk-repo.ts +1 -1
  42. package/src/pg-driver.ts +13 -1
  43. package/src/pg-latest-by.ts +57 -0
  44. package/src/pg-lock.ts +24 -4
  45. package/src/pg-measures.ts +64 -0
  46. package/src/pg-sql-aggregate.ts +9 -3
  47. package/src/pg-sql-measures.ts +102 -0
  48. package/src/pg-sql.ts +37 -6
  49. package/src/pg-update-many-sql.ts +44 -1
  50. package/src/pg-write-sql.ts +32 -4
  51. package/src/preload-ceiling.ts +73 -7
  52. package/src/preload.ts +17 -1
  53. package/src/query.ts +14 -1
  54. package/src/read-aggregates.ts +87 -3
  55. package/src/registry.ts +29 -0
  56. package/src/repo.ts +34 -1
  57. package/src/row-observer.ts +29 -4
  58. package/src/sealed-repo.ts +30 -2
  59. package/src/search-repo.ts +20 -2
  60. package/src/table-locks.ts +16 -1
  61. package/src/tenant-index.ts +84 -9
  62. package/src/text-contains.ts +53 -0
  63. package/src/types.ts +2 -22
  64. package/src/unique-constraints.ts +3 -1
  65. package/src/update-many-send.ts +32 -1
  66. package/src/update-many.ts +6 -1
  67. package/src/version-lock-errors.ts +42 -0
  68. package/src/version-lock.ts +177 -0
  69. package/src/write-where.ts +3 -0
package/CLAUDE.md CHANGED
@@ -140,6 +140,7 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
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
@@ -733,6 +733,54 @@ for (const id of ids) await db.posts.update(id, { likeCount: counts.get(id) ?? 0
733
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 |
734
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 |
735
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
+
736
784
  ## Writing by filter
737
785
 
738
786
  `deleteWhere`/`updateWhere` are the bulk forms of `delete`/`update` — the same fix `insertAll` is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.9.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.9.0",
48
- "@ultimat3/db": "31.9.0",
49
- "@ultimat3/schema": "31.9.0",
50
- "@ultimat3/time": "31.9.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/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
+ }
@@ -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
  /**
@@ -86,7 +89,11 @@ 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
  },
92
99
  updateMany: async () => {
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,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
+ }
package/src/database.ts CHANGED
@@ -105,8 +105,10 @@ export const database = <E extends EntitySet>(
105
105
  // Wrapped here rather than in a driver, so a committed row change is reported the same whether
106
106
  // rows live in memory or in Postgres — `entity.row` on the bus, and with no subscriber the
107
107
  // wrapper is one map read per write. `related` below stays unwrapped on purpose: a relation
108
- // preload is a READ, and a change feed has nothing to say about one.
109
- tables[key] = tableFor(entity, observedRepo(entity, driver.repo(entity)), related);
108
+ // preload is a READ, and a change feed has nothing to say about one. The driver's own
109
+ // repositories are how the observer reads back a parent a `countedIn` trigger moved.
110
+ const observed = observedRepo(entity, driver.repo(entity), (parent) => driver.repo(parent));
111
+ tables[key] = tableFor(entity, observed, related);
110
112
  }
111
113
  // Built key by key from `entities`, so each table is the one `Database<E>` names.
112
114
  return tables as Database<E>;
@@ -0,0 +1,65 @@
1
+ // The four key parts one `indexes:` entry may declare past a column list — an expression key, a
2
+ // direction per key, INCLUDE payload, an operator class — checked where the author wrote them and
3
+ // resolved to physical names. `@ultimat3/db` (`index-key-ddl.ts`) renders them and refuses again.
4
+
5
+ import type { IndexOperatorClass } from '@ultimat3/db';
6
+ import { invariantViolated } from './errors';
7
+ import type { Resolve } from './expr';
8
+ import type { IndexInit } from './index-init';
9
+ import type { ColumnMap } from './types';
10
+
11
+ /** The declared parts, physical, each absent unless written — the `IndexDef` fields they become. */
12
+ export interface DeclaredKeyParts {
13
+ readonly expression?: string;
14
+ readonly orders?: readonly ('asc' | 'desc' | null)[];
15
+ readonly include?: readonly string[];
16
+ readonly operatorClass?: IndexOperatorClass;
17
+ }
18
+
19
+ const DIRECTIONS: ReadonlySet<unknown> = new Set(['asc', 'desc', null]);
20
+
21
+ /**
22
+ * Every rule Postgres has for the four, refused at `entity()` with `X_INVARIANT_VIOLATED` — the
23
+ * code a bad `on:` or `where:` already raises — rather than at `x db gen` or as the server's own
24
+ * syntax error inside `ROLE=migrate`, which names none of the entity.
25
+ */
26
+ export const declaredKeyPartsOf = <C extends ColumnMap>(
27
+ entityName: string,
28
+ index: IndexInit<C>,
29
+ resolve: Resolve,
30
+ ): DeclaredKeyParts => {
31
+ const on = `the index on (${index.on.join(', ')})`;
32
+ const refuse = (detail: string): never => {
33
+ throw invariantViolated(entityName, 'index', `${on} ${detail}`);
34
+ };
35
+ const btree = index.using === undefined || index.using === 'btree';
36
+ const { expression, orders, include, operatorClass } = index;
37
+ if (expression !== undefined && expression.trim() === '') {
38
+ refuse("declares a blank expression — write the key, e.g. expression: 'lower(email)'");
39
+ }
40
+ if (orders !== undefined) {
41
+ if (index.order !== undefined)
42
+ refuse('declares both order and orders — orders states every key; drop order');
43
+ if (!btree) refuse(`declares orders on a ${index.using} index — only a btree orders its keys`);
44
+ const keys = expression === undefined ? index.on.length : 1;
45
+ if (orders.length !== keys) {
46
+ refuse(`declares ${orders.length} direction(s) for ${keys} key(s) — orders is one per key`);
47
+ }
48
+ if (!orders.every((direction) => DIRECTIONS.has(direction))) {
49
+ refuse("declares a direction other than 'asc', 'desc' or null");
50
+ }
51
+ }
52
+ if (include !== undefined) {
53
+ if (!btree) refuse(`declares include on a ${index.using} index — INCLUDE is btree only`);
54
+ if (include.length === 0) refuse('declares an empty include — name a column, or drop include');
55
+ }
56
+ if (operatorClass !== undefined && index.using !== 'gin') {
57
+ refuse(`declares ${operatorClass} without using: 'gin' — it is a gin operator class`);
58
+ }
59
+ return {
60
+ ...(expression === undefined ? {} : { expression }),
61
+ ...(orders === undefined ? {} : { orders }),
62
+ ...(include === undefined ? {} : { include: include.map((property) => resolve([property])) }),
63
+ ...(operatorClass === undefined ? {} : { operatorClass }),
64
+ };
65
+ };
@@ -1,6 +1,7 @@
1
1
  // One `indexes: [...]` entry of `entity(name, { indexes })` turned into the `IndexDef` it declares,
2
2
  // refusing what Postgres would refuse later. Split out of `entity.ts` at the 500-line ceiling.
3
3
 
4
+ import { declaredKeyPartsOf } from './declared-index-keys';
4
5
  import { invariantViolated } from './errors';
5
6
  import type { InvariantColumns, Resolve } from './expr';
6
7
  import type { IndexInit } from './index-init';
@@ -57,8 +58,9 @@ export const declaredIndexOf = <C extends ColumnMap>(
57
58
  );
58
59
  }
59
60
  }
61
+ const keys = declaredKeyPartsOf(name, index, resolve);
60
62
  return {
61
- name: indexName(name, table, columns, unique, index.order, where, index.using),
63
+ name: indexName(name, table, columns, unique, index.order, where, index.using, keys),
62
64
  columns,
63
65
  unique,
64
66
  ...(index.order === undefined ? {} : { order: index.order }),
@@ -69,5 +71,8 @@ export const declaredIndexOf = <C extends ColumnMap>(
69
71
  // How it is BUILT, so not part of the name. Absent stays absent — the default every existing
70
72
  // index already projects — and only an explicit ask, either way, rides along.
71
73
  ...(index.concurrently === undefined ? {} : { concurrently: index.concurrently }),
74
+ // The four key parts (E8), each absent unless declared — so no name, description or snapshot
75
+ // of an index that declares none moves.
76
+ ...keys,
72
77
  };
73
78
  };
@@ -6,6 +6,7 @@
6
6
  import { refuseAbandoned } from '@ultimat3/db';
7
7
  import { appendOnlyRepo } from './append-only';
8
8
  import type { Driver } from './database';
9
+ import { refuseCounters } from './driver-counters';
9
10
  import { driverCapabilityMissing, driverUnsupported } from './driver-errors';
10
11
  import type { DriverCapability, DriverDefinition, DriverRepo } from './driver-kit-types';
11
12
  import { noteDriverStore } from './driver-registry';
@@ -15,7 +16,7 @@ import { driverScope } from './driver-scope';
15
16
  import type { RawFor } from './driver-write-scope';
16
17
  import type { EntityCore } from './entity';
17
18
  import { notFound } from './errors';
18
- import { lockKeyInput } from './lock-key';
19
+ import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
19
20
  import { idPlan } from './plan';
20
21
  import type { Repo, RepoOptions, Tx } from './repo';
21
22
  import { sealedRepo } from './sealed-repo';
@@ -71,11 +72,12 @@ const driverRepo = <Row>(
71
72
  entity: EntityCore<Row>,
72
73
  rawFor: RawFor,
73
74
  ): Repo<Row> => {
75
+ refuseCounters(definition.name, entity as EntityCore);
74
76
  const scope = driverScope(definition, entity, rawFor);
75
77
  assertImplemented(definition, scope.raw as DriverRepo<unknown>);
76
78
  const { raw } = scope;
77
79
  // Absent unless declared, so the typed handle answers the shipped `X_LOCK_UNSUPPORTED`.
78
- const locks = (): Pick<Repo<Row>, 'lock' | 'lockKey'> => {
80
+ const locks = (): Pick<Repo<Row>, 'lock' | 'lockKey' | 'lockKeys'> => {
79
81
  const { lock, lockKey } = raw;
80
82
  if (lock === undefined || lockKey === undefined) return {};
81
83
  if (!definition.capabilities.includes('lock')) return {};
@@ -107,6 +109,26 @@ const driverRepo = <Row>(
107
109
  options?.tx,
108
110
  );
109
111
  },
112
+ // The store's one-key lock, sorted and nested: each key taken inside the last one's tx.
113
+ async lockKeys<R>(
114
+ keys: readonly string[],
115
+ fn: (tx: Tx) => Promise<R> | R,
116
+ options?: RepoOptions,
117
+ ) {
118
+ refuseAbandoned();
119
+ return holdInOrder<R, Tx>(
120
+ lockKeysInput(entity, keys, options),
121
+ (input, outer, body) =>
122
+ lockKey.call<DriverRepo<Row>, Parameters<typeof lockKey<R>>, Promise<R>>(
123
+ raw,
124
+ input,
125
+ body,
126
+ outer,
127
+ ),
128
+ fn,
129
+ options?.tx,
130
+ );
131
+ },
110
132
  };
111
133
  };
112
134
  const repo: Repo<Row> = { ...driverReads(scope), ...driverWrites(scope), ...locks() };
package/src/describe.ts CHANGED
@@ -366,6 +366,12 @@ export const describeEntity = <Row>(input: DescribeInput<Row>): EntityDescriptio
366
366
  // Absent stays absent for the same reason — `x verify` hashes this projection, and an index
367
367
  // that asks nothing must hash what it always did. An explicit ask, `true` or `false`, rides.
368
368
  ...(index.concurrently === undefined ? {} : { concurrently: index.concurrently }),
369
+ // The four key parts (E8), absent unless declared, for the same hash. `@ultimat3/db` renders
370
+ // them (`index-key-ddl.ts`) and records them in the snapshot (`declaredKeyParts`).
371
+ ...(index.expression === undefined ? {} : { expression: index.expression }),
372
+ ...(index.orders === undefined ? {} : { orders: index.orders }),
373
+ ...(index.include === undefined ? {} : { include: index.include }),
374
+ ...(index.operatorClass === undefined ? {} : { operatorClass: index.operatorClass }),
369
375
  })),
370
376
  tags: input.tags,
371
377
  cacheTag: input.cacheTag,
@@ -0,0 +1,21 @@
1
+ // Single responsibility: refuse a `countedIn` counter on a `defineDriver` store. Postgres keeps one
2
+ // by trigger and memory in its repository; a custom store has no lifecycle hook, so its parent's
3
+ // count would never move — refused when the child's repository is built, never a silent stale count.
4
+
5
+ import { DriverError } from './driver-errors';
6
+ import type { EntityCore } from './entity';
7
+
8
+ /** The child's first property declaring `countedIn`, refused; nothing when it declares none. */
9
+ export function refuseCounters(driverName: string, entity: EntityCore): void {
10
+ const counted = Object.entries(entity.$columns).find(
11
+ ([, column]) => column.$meta.countedIn !== undefined,
12
+ );
13
+ if (counted === undefined) return;
14
+ const [property] = counted;
15
+ throw new DriverError({
16
+ code: 'X_DRIVER_UNSUPPORTED',
17
+ cause: `${entity.$name}.${property} declares countedIn, and driver ${JSON.stringify(driverName)} keeps no counter: a defineDriver store has no trigger or repository hook to move the parent's count`,
18
+ fix: `database({ ${entity.$name}, … }, { driver: postgresDriver() }) # or memoryDriver(): both keep the counter — or drop countedIn from ${entity.$name}.${property} and count with db.${entity.$name}.countBy('${property}')`,
19
+ meta: { capability: 'countedIn', driver: driverName, entity: entity.$name, property },
20
+ });
21
+ }