@ultimat3/entity 31.23.0 → 31.24.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 CHANGED
@@ -83,6 +83,7 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
83
83
  `X_AGGREGATE_MIXED_CURRENCY`. Full rule: `docs/history/entity.md`. **`approximateCount()` is `reltuples`**; a filtered chain, a tenant-scoped or a soft-deleting entity is
84
84
  `X_APPROXIMATE_COUNT_FILTERED`; `null` for an unanalysed table.
85
85
  - **`series`, views**: `time-bucket.ts` (zone rules, measured), `view-repo.ts` (read-only); `time-bucket.test.ts`, `view-entity.test.ts`.
86
+ - **A predicate TREE rides in `plan.where` as one `Predicate`** whose op is no `Operator` (`'or' | 'and' | 'via'`, `predicate-node.ts`; `andWhereNode` the one door): every seam passes it along, an unaware executor refuses it. **A `via` is scoped through its TARGET's `scopedPlan` in `readPlan`** (`via-scope.ts`, marked; an unmarked hop is refused by both drivers); memory resolves it to an `in` (`memory-via.ts`). `TREE_CHECKS` in the suite.
86
87
  - **`json()` / `arrayOf()` are filterable** (`containment.ts`); no jsonpath operator. †
87
88
  - **A GIN index is declarable** (`using: 'gin'`); never unique or ordered. †
88
89
 
@@ -190,7 +191,7 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
190
191
  | `retain: { after, on }` | `retain.ts` | no default window; `on` a `timestamp()` some index STARTS with (`X_ENTITY_RETAIN_UNINDEXED`); refused beside `appendOnly` (`X_ENTITY_RETAIN_INVALID`). The sweep is `@ultimat3/jobs`' `retainTarget` |
191
192
  | `history: true` · `{ ignore }` | `history.ts`, `history-actor.ts` | `<table>_history` is a REAL registered entity (`$historyOf`), tenant column copied without its key. `ignore` (typed column names, refused otherwise) joins the counters in `$describe().history.ignore` — the trigger's, memory's (`historyIgnored`) and `history-order`'s one list. Written by `@ultimat3/db`'s trigger; `stampHistoryActor` sets `x.actor`/`x.request` once per transaction, never on a pinned repository — no transaction records `null`. `bigint`/`decimal`/`timestamp` columns ride `text`/`instants`: the image is the memory driver's strings (`history-values.test.ts`) |
192
193
  | `history(table, id)` | `history-read.ts`, `history-order.ts` | the history table's ordinary read (tenant scope, `inBatches`), then ONE ordering: the before→after walk (Hierholzer) across EVERY version — `at` is a transaction's start, so it only breaks ties — counted columns left out; no single walk: by `at`, the walk inside each instant. `{ limit }`: newest-first window, ties at its edge kept, numbered via `count`. `version` is a position, never stored — no schema change. `history-read.test.ts` (memory + PGlite), `.live.` |
193
- | `countedIn` on a key | `counter.ts` | the target is a NOT NULL `integer()` of the entity the key points at (Postgres' `NULL + 1` stays NULL), by its single primary key (`X_ENTITY_COUNTS_INVALID`); resolved at describe time, memoised on `registryGeneration()` |
194
+ | `countedIn` on a key | `counter.ts` | the target is a NOT NULL `integer()` of the entity the key points at (Postgres' `NULL + 1` stays NULL), by its single primary key (`X_ENTITY_COUNTS_INVALID`); resolved at describe time, memoised on `registryGeneration()`. `{ to, where }`: `where` is a thunk over `whereColumns(child)`, compiled once to `CounterWhereLike` (SQL over the child aliased `c`) and a three-valued verdict (`countsRow`: only TRUE counts); app-only refused |
194
195
  | all three, described | `lifecycle.ts` | each `$describe()` key ABSENT unless declared, so no other entity's hash moves |
195
196
  | the memory driver | `memory-lifecycle.ts` | mirrors both triggers through the table's raw store |
196
197
  | `partitionBy` | `partition.ts` | Postgres' rules, at declaration (`X_ENTITY_PARTITION_INVALID`); SQL in db |
package/README.md CHANGED
@@ -486,6 +486,69 @@ never an empty result. The `fix` names the operator meant: `>`→`gt`, `>=`→`g
486
486
  `<=`→`lte`, `=`→`eq`, `!=`/`<>`→`neq`. `isOperator(value)` is the same test, for an op read off
487
487
  the wire.
488
488
 
489
+ ## A predicate tree: `andWhereNode`
490
+
491
+ `andWhereNode(node)` (`As of 2026-11`) adds one predicate TREE to a chain, AND-ed with the rest —
492
+ the one way to say `or`, an `and` inside it, or a relation hop. One statement either way.
493
+
494
+ | Node (`PredicateNode<Row>`) | Compiles to |
495
+ |---|---|
496
+ | `{ column, op, value? }` | a leaf, exactly `andWhere(column, op, value)` |
497
+ | `{ or: [...] }` | `( … or … )`; `[]` is `1 = 0` |
498
+ | `{ and: [...] }` | `( … and … )`; `[]` is `true` |
499
+ | `{ via: { column, entity, target }, where: [...] }` | `"column" in (select "target" from <entity's table> where …)` |
500
+
501
+ ```ts
502
+ import { database, entity, text, timestamp, uuid } from '@ultimat3/entity';
503
+
504
+ const posts = entity('posts', {
505
+ columns: {
506
+ id: uuid().primaryKey(),
507
+ authorId: uuid(),
508
+ audience: text({ max: 10 }),
509
+ publishedAt: timestamp().defaultNow(),
510
+ deletedAt: timestamp().nullable(),
511
+ },
512
+ });
513
+ entity('friendships', {
514
+ columns: { id: uuid().primaryKey(), userId: uuid(), friendId: uuid() },
515
+ });
516
+ const db = database({ posts });
517
+ declare const me: string;
518
+
519
+ await db.posts
520
+ .where({ deletedAt: null })
521
+ .andWhereNode({
522
+ or: [
523
+ { column: 'authorId', op: 'eq', value: me },
524
+ { column: 'audience', op: 'eq', value: 'public' },
525
+ {
526
+ via: { column: 'authorId', entity: 'friendships', target: 'friendId' },
527
+ where: [{ column: 'userId', op: 'eq', value: me }],
528
+ },
529
+ ],
530
+ })
531
+ .orderBy('publishedAt', 'desc')
532
+ .limit(20)
533
+ .all();
534
+ ```
535
+
536
+ - **A hop is planned through its TARGET's tenant guard** (`via-scope.ts`, in `readPlan`): the
537
+ acting actor's tenant and the target's soft delete apply inside the subselect; outside a request
538
+ its `where` must name the tenant (`X_TENANCY_UNSCOPED`). An untenanted target behind a tenanted
539
+ source must declare `shared:` or `global:`. A hop value no `readPlan` scoped is refused by both
540
+ drivers.
541
+ - `entity` is a registered entity NAME; `column`, `target` and every inner column must be declared
542
+ and not sealed; at most `MAX_PREDICATE_DEPTH` (4) levels. Each refusal is
543
+ `X_ENTITY_PREDICATE_NODE_INVALID`, on the chain line.
544
+ - Leaf columns are typed by the row at the top and inside every group; a hop's inner level is the
545
+ target's and takes any string. A `ScopedNode` — what `@ultimat3/query` hands a provider on
546
+ `RowWindow.nodes` — is accepted as is.
547
+ - Memory resolves a hop to an `in` list from its other tables (`memory-via.ts`); Postgres runs the
548
+ subselect. `entityDriverConformance`'s `TREE_CHECKS` hold both, tenancy included.
549
+ - A `defineDriver` store takes a tree only under `predicate:or` / `predicate:via`, else
550
+ `X_DRIVER_UNSUPPORTED` before the store is called; nothing in process can judge a hop row by row.
551
+
489
552
  ## Filtering inside a json() or arrayOf() column
490
553
 
491
554
  ```ts
@@ -913,6 +976,7 @@ Three declarations, each a trigger or a purge target `x db gen` and `purge()` co
913
976
  | `retain: { after: '90d', on: 'createdAt' }` | `purge({ entities: 'declared' })` (`@ultimat3/jobs`) deletes older rows in batches, across tenants. The window is required; `on` is an indexed `timestamp()` (`X_ENTITY_RETAIN_UNINDEXED`); never beside `appendOnly` (`X_ENTITY_RETAIN_INVALID`). `$retain` is the checked declaration. `x verify` refuses one no purge covers (`X_ENTITY_RETAIN_UNSWEPT`) |
914
977
  | `history: true` · `{ retain: { after }, ignore: ['likeCount', 'updatedAt'] }` | `<table>_history`, a registered entity (`$history`; it carries `$historyOf`), written by trigger with a before and after image of every change — `updateWhere`, cascades and raw SQL included. A change to `ignore`d columns alone (typed: the entity's own columns) records nothing, as a counter's does; a name that is no column is `X_INVARIANT_VIOLATED`. Its repository refuses every rewrite (`X_ENTITY_APPEND_ONLY`), the table too, except a retention sweep's delete |
915
978
  | `references(() => posts.id, { countedIn: () => posts.likeCount })` | the child's trigger keeps the parent's `integer()` equal to its row count, in the write's transaction; a soft-deleted child is not counted. Declared on the key because the child already names its parent: a thunk on the parent naming the child would make each declaration the other's type. `X_ENTITY_COUNTS_INVALID` when the target is no integer or the key points at no single primary key |
979
+ | `countedIn: { to: () => posts.upCount, where: (): Expr => whereColumns(likes).kind.eq('up') }` | the same counter, counting only the child rows the predicate holds over (a NULL operand is not counted, as a SQL `where`). The predicate is the invariant language over the CHILD, built from `whereColumns(<child>)` — typed by the child's columns; the `(): Expr` return type is required, since the child names itself in its own declaration (TS7022 without it) — and compiled once into the trigger's condition, its `update of` list and the recount's truth. A predicate with no SQL (a function) is `X_ENTITY_COUNTS_INVALID`. `countsRow(counter, row)` is the same verdict for a row in hand. The memory driver applies the same verdict |
916
980
 
917
981
  Memory parity: the memory driver records history and moves counters in its repository (`memory-lifecycle.ts`); `history.test.ts` and `counter.test.ts` are the parity tables.
918
982
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.23.0",
3
+ "version": "31.24.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.23.0",
48
- "@ultimat3/db": "31.23.0",
49
- "@ultimat3/schema": "31.23.0",
50
- "@ultimat3/time": "31.23.0"
47
+ "@ultimat3/core": "31.24.0",
48
+ "@ultimat3/db": "31.24.0",
49
+ "@ultimat3/schema": "31.24.0",
50
+ "@ultimat3/time": "31.24.0"
51
51
  }
52
52
  }
@@ -1,7 +1,7 @@
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.
1
+ // Single responsibility: say, in development and test, that `.all()` dropped a next page — with the
2
+ // caller's line, once per line. `.all()` answers one page (`DEFAULT_PAGE_SIZE` rows unless the chain
3
+ // says `.limit(n)`), and a caller that meant "every row" learns otherwise only from a missing row.
4
+ // Refusing is a break, so the throw waits for `next`; in 31.x this is a coded `log.record` warning.
5
5
 
6
6
  import { DEFAULT_ENVIRONMENT, logger, tryResolveEnvironment } from '@ultimat3/core';
7
7
  import { DEFAULT_PAGE_SIZE } from './plan';
@@ -9,10 +9,42 @@ import { DEFAULT_PAGE_SIZE } from './plan';
9
9
  /** The one log message this writes: a subscriber matches `log.record`'s `message` against it. */
10
10
  export const ALL_TRUNCATED = 'entity.all.truncated';
11
11
 
12
+ /** The warning's code, on `fields.code`. A refusal under the same code is `next`'s, not 31.x's. */
13
+ const CODE = 'X_ENTITY_ALL_TRUNCATED';
14
+
15
+ /** Sites already warned about. Bounded: past it a dev process has said enough, and stays quiet. */
16
+ const MAX_SITES = 1_000;
17
+ const warned = new Set<string>();
18
+
19
+ /** This package's own directory (`src/` or `dist/`): its frames are the chain, never the caller. */
20
+ const OWN = import.meta.dir;
21
+ const FRAME = /\(?((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/])[^()]*?):(\d+):(\d+)\)?\s*$/;
22
+
23
+ /**
24
+ * The first frame outside this package: the line that called `.all()`. Read after the page's
25
+ * `await`, so it rides Bun's async stack — a caller that awaited the chain is named; one that
26
+ * returned the promise un-awaited leaves no frame, and the site is `undefined`.
27
+ */
28
+ function callSite(): string | undefined {
29
+ const holder: { stack?: string } = {};
30
+ Error.captureStackTrace(holder, reportTruncatedAll);
31
+ for (const line of (holder.stack ?? '').split('\n').slice(1)) {
32
+ const match = FRAME.exec(line);
33
+ const file = match?.[1]?.replace(/^file:\/\//, '');
34
+ if (file === undefined || (file.startsWith(OWN) && !file.includes('.test.'))) continue;
35
+ const cwd = `${process.cwd()}/`;
36
+ const shown = file.startsWith(cwd) ? file.slice(cwd.length) : file;
37
+ return `${shown}:${match?.[2]}:${match?.[3]}`;
38
+ }
39
+ return undefined;
40
+ }
41
+
12
42
  /**
13
43
  * 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.
44
+ * `.limit(n)` (one page is what it asked for), in staging or production — the warning is for the
45
+ * author, and staging exists to behave as production does — and for a site already warned about.
46
+ * The stack is read only past those checks, so a production `.all()` pays nothing. `env` is the
47
+ * test seam.
16
48
  */
17
49
  export function reportTruncatedAll(
18
50
  entity: string,
@@ -24,10 +56,22 @@ export function reportTruncatedAll(
24
56
  const environment = tryResolveEnvironment(env === undefined ? undefined : { env });
25
57
  const at = environment ?? DEFAULT_ENVIRONMENT;
26
58
  if (at !== 'development' && at !== 'test') return;
59
+ const site = callSite();
60
+ const key = `${entity}@${site ?? '?'}`;
61
+ if (warned.has(key) || warned.size >= MAX_SITES) return;
62
+ warned.add(key);
63
+ const where = site === undefined ? '' : ` at ${site}`;
27
64
  logger.warn(ALL_TRUNCATED, {
65
+ code: CODE,
28
66
  entity,
29
67
  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`,
68
+ ...(site === undefined ? {} : { at: site }),
69
+ cause: `${entity}.….all()${where} answered its first ${DEFAULT_PAGE_SIZE} rows and dropped the cursor to the rest`,
70
+ 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; x g guard repo-unbounded finds every such read in a repo.ts`,
32
71
  });
33
72
  }
73
+
74
+ /** TEST SEAM: forget every warned site. */
75
+ export function resetTruncatedSites(): void {
76
+ warned.clear();
77
+ }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { currentWriteOrigin, instrument, subscribed } from '@ultimat3/core';
7
7
  import { expectedQueryLoop } from '@ultimat3/db';
8
- import { type Counter, countersTargeting } from './counter';
8
+ import { type Counter, countersTargeting, countsRow } from './counter';
9
9
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
10
10
  import { MAX_PAGE_SIZE } from './plan';
11
11
  import type { FilteredWriteOptions, Repo, RepoOptions } from './repo';
@@ -29,11 +29,15 @@ const BULK = 'entity.bulk';
29
29
  const asRow = (value: unknown): Row | null =>
30
30
  typeof value === 'object' && value !== null ? (value as Row) : null;
31
31
 
32
- /** The parent a child row counts into, or `undefined` when it counts nowhere (deleted, no key). */
32
+ /**
33
+ * The parent a child row counts into, or `undefined` when it counts nowhere (deleted, no key, or
34
+ * outside the counter's `where`).
35
+ */
33
36
  const countedParent = (counter: Counter, row: unknown): string | undefined => {
34
37
  const record = asRow(row);
35
38
  if (record === null) return undefined;
36
39
  if (counter.child.$softDelete && record[SOFT_DELETE_COLUMN] != null) return undefined;
40
+ if (!countsRow(counter, record)) return undefined;
37
41
  const id = record[counter.references];
38
42
  return typeof id === 'string' ? id : undefined;
39
43
  };
@@ -50,9 +54,11 @@ const pinnedTo = (
50
54
  filter?.[property] ??
51
55
  options?.where?.find((each) => each.column === property && each.op === 'eq')?.value;
52
56
 
53
- /** Whether a patch can move a counter: it sets the key, or the soft-delete stamp. */
57
+ /** Whether a patch can move a counter: it sets the key, the soft-delete stamp, or a `where` column. */
54
58
  const moves = (counter: Counter, patch: Row): boolean =>
55
- counter.references in patch || (counter.child.$softDelete && SOFT_DELETE_COLUMN in patch);
59
+ counter.references in patch ||
60
+ (counter.child.$softDelete && SOFT_DELETE_COLUMN in patch) ||
61
+ (counter.where?.properties.some((property) => property in patch) ?? false);
56
62
 
57
63
  export interface CounterEcho {
58
64
  /** Row writes: each change as `[before, after]`, `null` on the side that did not exist. */
package/src/counter.ts CHANGED
@@ -3,13 +3,17 @@
3
3
  // integer of the entity the key points at, and projected for `@ultimat3/db` (which emits the
4
4
  // trigger) and for the memory driver (which mirrors it).
5
5
 
6
- import type { CounterDescriptionLike } from '@ultimat3/db';
7
- import { bindingOf, columnName } from './column';
6
+ import type { CounterDescriptionLike, CounterWhereLike } from '@ultimat3/db';
7
+ import { identifier } from '@ultimat3/db';
8
+ import { bindingOf, columnName, moneyColumns } from './column';
8
9
  import type { EntityCore } from './entity';
9
10
  import { SOFT_DELETE_COLUMN } from './entity';
10
11
  import { EntityError } from './errors';
12
+ import { type Expr, type InvariantColumns, invariantColumns, type Row } from './expr';
13
+ import { type Verdict, verdictOf } from './expr-verdict';
11
14
  import { getEntity, registeredEntities, registryGeneration } from './registry';
12
- import type { AnyColumn } from './types';
15
+ import { sealedFields } from './sealed';
16
+ import type { AnyColumn, ColumnMap, CountedIn } from './types';
13
17
 
14
18
  /** One resolved counter: both entities, both properties. */
15
19
  export interface Counter {
@@ -19,20 +23,82 @@ export interface Counter {
19
23
  readonly child: EntityCore;
20
24
  /** The child's foreign-key property. */
21
25
  readonly references: string;
26
+ /** `countedIn: { where }`, compiled once: the memory driver's verdict and the trigger's SQL. */
27
+ readonly where: {
28
+ readonly verdict: Verdict;
29
+ readonly sql: CounterWhereLike;
30
+ /** The child properties it reads: a patch setting one can move the count. */
31
+ readonly properties: readonly string[];
32
+ } | null;
22
33
  }
23
34
 
35
+ /** The parent column a `countedIn` names, in either spelling, and its predicate thunk. */
36
+ const targetOf = (declared: CountedIn) =>
37
+ typeof declared === 'function'
38
+ ? { to: declared, where: undefined }
39
+ : { to: declared.to, where: declared.where };
40
+
24
41
  const countsInvalid = (entity: string, property: string, reason: string): EntityError =>
25
42
  new EntityError({
26
43
  code: 'X_ENTITY_COUNTS_INVALID',
27
44
  cause: `${entity}.${property} declares countedIn, and ${reason}`,
28
- fix: `x db gen "count" # after ${property}: uuid().references(() => <parent>.id, { countedIn: () => <parent>.<count> }) in entity('${entity}'), where <count> is integer().default(0)`,
45
+ fix: `${property}: uuid().references(() => <parent>.id, { countedIn: () => <parent>.<count> }) in entity('${entity}'), with <count> an integer().default(0) on the parent — then: x db gen "count"`,
29
46
  });
30
47
 
48
+ /**
49
+ * The `c` an invariant is written against, for an entity already declared — what a
50
+ * `countedIn: { where }` thunk builds its predicate from: `() => whereColumns(likes).kind.eq('up')`.
51
+ */
52
+ export const whereColumns = <C extends ColumnMap>(entity: {
53
+ readonly $name: string;
54
+ readonly $columns: C;
55
+ }): InvariantColumns<C> => invariantColumns(entity.$name, entity.$columns);
56
+
57
+ /**
58
+ * A `where` compiled once against the CHILD: SQL over the child aliased `c` (the trigger and the
59
+ * recount both give it that alias) and the physical columns it reads. A predicate with no SQL
60
+ * (a JS function) or a `unique` is refused: the trigger would count by a rule memory does not hold.
61
+ */
62
+ function compileWhere(child: EntityCore, property: string, rule: Expr): Counter['where'] {
63
+ const refuse = (reason: string): never => {
64
+ throw new EntityError({
65
+ code: 'X_ENTITY_COUNTS_INVALID',
66
+ cause: `${child.$name}.${property} declares countedIn, and ${reason}`,
67
+ fix: `${property}: uuid().references(() => <parent>.id, { countedIn: { to: () => <parent>.<count>, where: (): Expr => whereColumns(${child.$name}).<column>.eq(<value>) } }) in entity('${child.$name}'), a predicate in the invariant language and never a function — then: x db gen "count"`,
68
+ });
69
+ };
70
+ const sealed = new Set(sealedFields(child).map((field) => field.property));
71
+ const physical = (path: readonly string[]): string => {
72
+ const [name, part] = path;
73
+ const column = name === undefined ? undefined : child.$columns[name];
74
+ if (name === undefined || column === undefined) {
75
+ return refuse(`its where names ${path.join('.')}, no column of ${child.$name}`);
76
+ }
77
+ // The stored string is ciphertext: the trigger would compare it with the plaintext literal and
78
+ // memory would judge the sealed row — a counter that silently never counts (as a CHECK would).
79
+ if (sealed.has(name)) {
80
+ return refuse(
81
+ `its where reads ${name}, and ${name} is sealed: neither half ever sees the plaintext`,
82
+ );
83
+ }
84
+ if (part === undefined) return columnName(name, column.$meta);
85
+ const parts = moneyColumns(name, column.$meta);
86
+ return part === 'minor' ? parts.minor : parts.currency;
87
+ };
88
+ const sql =
89
+ rule.kind === 'unique' ? null : rule.toSql((path) => `c.${identifier(physical(path)).text}`);
90
+ if (sql === null) return refuse(`its where (${rule.message}) has no SQL the trigger can hold`);
91
+ const columns = [...new Set(rule.paths.map(physical))];
92
+ const properties = [...new Set(rule.paths.flatMap((path) => path.slice(0, 1)))];
93
+ return { verdict: verdictOf(rule), sql: { sql, columns }, properties };
94
+ }
95
+
31
96
  /** The counter one child key declares, resolved and checked. `null` when it declares none. */
32
97
  export function counterOf(child: EntityCore, property: string, column: AnyColumn): Counter | null {
33
- const target = column.$meta.countedIn;
34
- if (target === undefined) return null;
35
- const counting = target();
98
+ const declared = column.$meta.countedIn;
99
+ if (declared === undefined) return null;
100
+ const target = targetOf(declared);
101
+ const counting = target.to();
36
102
  const binding = bindingOf(counting);
37
103
  const parent = binding === undefined ? undefined : getEntity(binding.table)?.core;
38
104
  if (binding === undefined || parent === undefined) {
@@ -59,9 +125,19 @@ export function counterOf(child: EntityCore, property: string, column: AnyColumn
59
125
  `it is no foreign key to ${parent.$name}'s single primary key, so it cannot count into it`,
60
126
  );
61
127
  }
62
- return { parent, column: binding.property, child, references: property };
128
+ const where = target.where === undefined ? null : compileWhere(child, property, target.where());
129
+ return { parent, column: binding.property, child, references: property, where };
63
130
  }
64
131
 
132
+ /**
133
+ * Whether a child row (property-keyed, as a repository holds it) is counted by `counter`'s predicate:
134
+ * only a TRUE verdict counts — a NULL operand is unknown, and a SQL `where` drops it. The key and
135
+ * the soft-delete stamp are the caller's to check, as the trigger checks them first.
136
+ */
137
+ export const countsRow = (counter: Counter, row: unknown): boolean =>
138
+ counter.where === null ||
139
+ (typeof row === 'object' && row !== null && counter.where.verdict(row as Row) === true);
140
+
65
141
  let cached: { readonly generation: number; readonly counters: readonly Counter[] } | undefined;
66
142
 
67
143
  /**
@@ -105,5 +181,6 @@ export function describeCounter(counter: Counter): CounterDescriptionLike {
105
181
  table: counter.child.$table,
106
182
  references: physical(counter.child, counter.references),
107
183
  softDelete: counter.child.$softDelete ? physical(counter.child, SOFT_DELETE_COLUMN) : null,
184
+ ...(counter.where === null ? {} : { where: counter.where.sql }),
108
185
  };
109
186
  }
@@ -39,6 +39,8 @@ const MEMBER: Readonly<Record<DriverCapability, keyof DriverRepo<unknown> | 'tra
39
39
  series: 'series',
40
40
  upsert: 'upsert',
41
41
  matches: 'select',
42
+ 'predicate:or': 'select',
43
+ 'predicate:via': 'select',
42
44
  'aggregate:countBy': 'countBy',
43
45
  'aggregate:sum': 'aggregate',
44
46
  'aggregate:avg': 'aggregate',
package/src/describe.ts CHANGED
@@ -41,6 +41,8 @@ export interface DescribeInput<Row> {
41
41
  readonly retired?: readonly string[] | undefined;
42
42
  /** `entity({ shared: '<why>' })` — projected only when declared. */
43
43
  readonly shared?: string | undefined;
44
+ /** `entity({ global: '<why>' })` — projected only when declared. */
45
+ readonly global?: string | undefined;
44
46
  /** `entity({ scan: '<why>' })` — projected only when declared. */
45
47
  readonly scan?: string | undefined;
46
48
  /** `entity({ readOnly: '<why>' })` — projected only when declared. */
@@ -197,30 +199,46 @@ export const assertNotRetired = (
197
199
  }
198
200
  };
199
201
 
202
+ /** The two tenantless reasons, each a stance: `shared` hangs off a tenant's row, `global` off none. */
203
+ export interface TenantlessReasons {
204
+ readonly shared: string | undefined;
205
+ readonly global: string | undefined;
206
+ }
207
+
200
208
  /**
201
- * `shared` is a reason, so a blank one is no reason: refused where it was written, never read as a
202
- * declaration someone took. On an entity WITH a tenant column it states a reason for nothing — the
203
- * stance `sameTenantOf` takes on a `crossTenant` reason for an edge that cannot be same-tenant.
209
+ * `shared` and `global` are reasons, so a blank one is no reason: refused where it was written,
210
+ * never read as a declaration someone took. On an entity WITH a tenant column either states a
211
+ * reason for nothing — the stance `sameTenantOf` takes on a `crossTenant` reason for an edge that
212
+ * cannot be same-tenant — and both on one entity are two meanings for one row.
204
213
  */
205
214
  export const assertShared = (
206
215
  entityName: string,
207
216
  table: string,
208
- shared: string | undefined,
217
+ reasons: TenantlessReasons,
209
218
  tenantColumn: string | null,
210
219
  ): void => {
211
- if (shared === undefined) return;
212
- if (shared.trim() === '') {
220
+ if (reasons.shared !== undefined && reasons.global !== undefined) {
221
+ throw new EntityError({
222
+ code: 'X_INVARIANT_VIOLATED',
223
+ cause: `${entityName} declares both shared and global: a row that hangs off a tenant's row (shared) is not a row every tenant reads alike (global)`,
224
+ fix: `entity('${entityName}', { … }) — keep shared if it references a tenant-owned table, global if it references none; remove the other`,
225
+ });
226
+ }
227
+ const option = reasons.shared === undefined ? 'global' : 'shared';
228
+ const reason = reasons.shared ?? reasons.global;
229
+ if (reason === undefined) return;
230
+ if (reason.trim() === '') {
213
231
  throw new EntityError({
214
232
  code: 'X_ENTITY_TENANT_UNDECLARED',
215
- cause: `${entityName} declares shared with no reason: a blank reason says nothing about why its rows belong to no tenant`,
216
- fix: `entity('${entityName}', { shared: '<why it belongs to no tenant>' }) — or drop shared, add orgId: uuid().tenant() to its columns, then x db gen "${table} tenant"`,
233
+ cause: `${entityName} declares ${option} with no reason: a blank reason says nothing about why its rows belong to no tenant`,
234
+ fix: `entity('${entityName}', { ${option}: '<why it belongs to no tenant>' }) — or drop ${option}, add orgId: uuid().tenant() to its columns, then x db gen "${table} tenant"`,
217
235
  });
218
236
  }
219
237
  if (tenantColumn !== null) {
220
238
  throw new EntityError({
221
239
  code: 'X_INVARIANT_VIOLATED',
222
- cause: `${entityName} declares shared and has the tenant column ${tenantColumn}: its rows belong to a tenant, so the reason explains nothing`,
223
- fix: `entity('${entityName}', { … }) — with the shared option removed`,
240
+ cause: `${entityName} declares ${option} and has the tenant column ${tenantColumn}: its rows belong to a tenant, so the reason explains nothing`,
241
+ fix: `entity('${entityName}', { … }) — with the ${option} option removed`,
224
242
  });
225
243
  }
226
244
  };
@@ -385,6 +403,7 @@ export const describeEntity = <Row>(input: DescribeInput<Row>): EntityDescriptio
385
403
  ...((input.retired ?? []).length === 0 ? {} : { retired: input.retired }),
386
404
  // Absent unless declared, like `appendOnly`: no entity that never said it moves the hash.
387
405
  ...(input.shared === undefined ? {} : { shared: input.shared }),
406
+ ...(input.global === undefined ? {} : { global: input.global }),
388
407
  ...(input.scan === undefined ? {} : { scan: input.scan }),
389
408
  ...(input.readOnly === undefined ? {} : { readOnly: input.readOnly }),
390
409
  // Absent on every table, so no entity that never said `view` moves the hash.
@@ -21,6 +21,11 @@ export const DRIVER_CAPABILITIES = [
21
21
  'series',
22
22
  'upsert',
23
23
  'matches',
24
+ // A predicate TREE (`predicate-node.ts`) in `plan.where`: an `or` group, a `via` hop. A store
25
+ // that declares `via` answers `col in (select … )` natively — the hop's inner where already
26
+ // carries the target's tenant; nothing in process can judge one row by row.
27
+ 'predicate:or',
28
+ 'predicate:via',
24
29
  'aggregate:countBy',
25
30
  'aggregate:sum',
26
31
  'aggregate:avg',
@@ -7,8 +7,9 @@ import type { DriverCapability, DriverDefinition, DriverRepo } from './driver-ki
7
7
  import { outOfScope, structuralPredicates } from './driver-rows';
8
8
  import type { RawFor } from './driver-write-scope';
9
9
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
10
+ import { isGroup, orMembers, viaValue } from './predicate-node';
10
11
  import type { Tx } from './repo';
11
- import type { QueryPlan } from './tenancy';
12
+ import type { Predicate, QueryPlan } from './tenancy';
12
13
 
13
14
  export interface DriverScope<Row> {
14
15
  readonly definition: DriverDefinition;
@@ -26,6 +27,22 @@ export interface DriverScope<Row> {
26
27
  checked(operation: string, plan: QueryPlan, rows: readonly Row[]): readonly Row[];
27
28
  }
28
29
 
30
+ /** The node ops a level holds, through every `or` group and into every `via`. */
31
+ const treeOps = (where: readonly Predicate[], found = new Set<string>()): ReadonlySet<string> => {
32
+ for (const predicate of where) {
33
+ if (isGroup(predicate)) {
34
+ // An `and` group is no capability of its own — the plan is a conjunction already — but an
35
+ // `or` or a `via` under it is.
36
+ if (predicate.op === 'or') found.add('or');
37
+ treeOps(orMembers(predicate), found);
38
+ } else if (predicate.op === 'via') {
39
+ found.add('via');
40
+ treeOps(viaValue(predicate).where, found);
41
+ }
42
+ }
43
+ return found;
44
+ };
45
+
29
46
  export const driverScope = <Row>(
30
47
  definition: DriverDefinition,
31
48
  entity: EntityCore<Row>,
@@ -52,6 +69,11 @@ export const driverScope = <Row>(
52
69
  },
53
70
  storePlan(operation, plan, includeDeleted = false) {
54
71
  if (plan.where.some((predicate) => predicate.op === 'matches')) need(operation, 'matches');
72
+ // Every node at any depth, refused before the store sees it: a store handed a tree it then
73
+ // ignores while honouring the page bound serves the short page the tree exists to end.
74
+ const nodes = treeOps(plan.where);
75
+ if (nodes.has('or')) need(operation, 'predicate:or');
76
+ if (nodes.has('via')) need(operation, 'predicate:via');
55
77
  const hidden =
56
78
  entity.$softDelete && !includeDeleted
57
79
  ? [{ column: SOFT_DELETE_COLUMN, op: 'is-null' as const }]
@@ -56,6 +56,8 @@ export const ENTITY_ERROR_CODES = [
56
56
  'X_ENTITY_PAGE_TOO_LARGE',
57
57
  'X_ENTITY_STALE',
58
58
  'X_ENTITY_VERSION_INVALID',
59
+ 'X_ENTITY_ALL_TRUNCATED',
60
+ 'X_ENTITY_PREDICATE_NODE_INVALID',
59
61
  ] as const;
60
62
 
61
63
  export type EntityErrorCode = (typeof ENTITY_ERROR_CODES)[number];
@@ -109,6 +111,9 @@ export const ENTITY_ERROR_TITLES: Readonly<Record<EntityErrorCode, string>> = {
109
111
  X_ENTITY_PAGE_TOO_LARGE: 'a page weighed more than the page byte bound before it was decoded',
110
112
  X_ENTITY_STALE: "the row's version moved since this write read it",
111
113
  X_ENTITY_VERSION_INVALID: 'a write or declaration breaks the declared version lock',
114
+ X_ENTITY_ALL_TRUNCATED: '.all() answered one page and dropped the cursor to the rest',
115
+ X_ENTITY_PREDICATE_NODE_INVALID:
116
+ 'a predicate tree (andWhereNode, a policy scope) no driver can answer',
112
117
  };
113
118
 
114
119
  // Registered at module load, unconditionally, in one call. Without this the registry humanises the
package/src/entity.ts CHANGED
@@ -73,6 +73,12 @@ export interface EntityInit<C extends ColumnMap> {
73
73
  * Without it `x verify`'s exercise step reports `X_ENTITY_TENANT_UNDECLARED`; blank is refused.
74
74
  */
75
75
  readonly shared?: string;
76
+ /**
77
+ * Why an entity with no tenant column, referencing no tenant-owned one, is the same for every
78
+ * tenant — a plan catalog, a stream cursor. A read touching only global entities is the exercise's
79
+ * `global` verdict, not `unproven`. Never beside `shared`; blank is refused.
80
+ */
81
+ readonly global?: string;
76
82
  /**
77
83
  * Why this table may be read by a sequential scan: a closed catalog that stays a handful of rows.
78
84
  * Without it `x verify`'s exercise step reports a statement no index serves (`X_QUERY_UNINDEXED`)
@@ -245,7 +251,7 @@ export const entity = <const C extends ColumnMap>(
245
251
  // does not rename its table — was not, so an entity NAME closed the identifier in the same way a
246
252
  // column name could: `entity('t" (x int); drop table u; --')` emitted that `drop table` verbatim.
247
253
  const table = assertTableName(name, init.table ?? name);
248
- assertShared(name, table, init.shared, tenantColumn);
254
+ assertShared(name, table, { shared: init.shared, global: init.global }, tenantColumn);
249
255
  assertScan(name, init.scan);
250
256
  for (const [property, column] of entries) bindColumn(column, name, property, tenant, table);
251
257
  const cacheTag = `entity:${name}`;
@@ -374,6 +380,7 @@ export const entity = <const C extends ColumnMap>(
374
380
  appendOnly,
375
381
  retired: init.retired,
376
382
  shared: init.shared,
383
+ global: init.global,
377
384
  scan: init.scan,
378
385
  readOnly: init.readOnly,
379
386
  view: viewQuery,
package/src/index.ts CHANGED
@@ -37,7 +37,7 @@ export {
37
37
  export type { DecimalOptions } from './columns-data';
38
38
  export { arrayOf, bigint, bytes, date, decimal, json } from './columns-data';
39
39
  export type { Counter } from './counter';
40
- export { countersOf, describeCounter } from './counter';
40
+ export { countersOf, countsRow, describeCounter, whereColumns } from './counter';
41
41
  // `crossTenantReason` stays internal: an app that could read the flag would have a second way to
42
42
  // reason about tenant scope — branch on it — next to the one way, which is entering the scope.
43
43
  export { CROSS_TENANT_SCOPE, crossTenant } from './cross-tenant';
@@ -121,6 +121,16 @@ export { postgresDriver, postgresRepo } from './pg-driver';
121
121
  export { decodeRow } from './pg-row';
122
122
  export { postgresTransactor } from './pg-transactor';
123
123
  export { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from './plan';
124
+ export type {
125
+ NodeColumn,
126
+ PredicateAnd,
127
+ PredicateLeaf,
128
+ PredicateNode,
129
+ PredicateOr,
130
+ PredicateVia,
131
+ ScopedNode,
132
+ } from './predicate-node';
133
+ export { MAX_PREDICATE_DEPTH } from './predicate-node';
124
134
  export type { RelatedTable, RelatedTables } from './preload';
125
135
  export type { PreloadOptions } from './preload-ceiling';
126
136
  export { MAX_PRELOADED_ROWS } from './preload-ceiling';
@@ -254,6 +264,7 @@ export type {
254
264
  ColumnKind,
255
265
  ColumnMap,
256
266
  ColumnMeta,
267
+ CountedIn,
257
268
  EnumeratedColumn,
258
269
  IdOf,
259
270
  IndexDef,
package/src/measures.ts CHANGED
@@ -79,7 +79,8 @@ export const screenMeasureFilter = <Row>(
79
79
  if (!Array.isArray(where)) {
80
80
  throw refused(entity, `a measure's where is ${shown(where)}, not a list of predicates`);
81
81
  }
82
- screenPredicates(entity, where);
82
+ // The measure's own refusal first: `screenPredicates` refuses an undeclared column too, under the
83
+ // read path's code, and a measure's caller is owed the aggregate's.
83
84
  for (const predicate of where) {
84
85
  const [property = predicate.column] = predicate.column.split('.');
85
86
  if (predicate.op !== 'matches' && columnFor(entity.$columns, property) === undefined) {
@@ -90,6 +91,7 @@ export const screenMeasureFilter = <Row>(
90
91
  );
91
92
  }
92
93
  }
94
+ screenPredicates(entity, where);
93
95
  return where;
94
96
  };
95
97