@ultimat3/entity 31.23.0 → 31.25.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.
@@ -5,7 +5,7 @@
5
5
  import { tryUseContext } from '@ultimat3/core';
6
6
  import { entityNow } from './clock';
7
7
  import { columnName, moneyColumns } from './column';
8
- import { countersOf, countersTargeting } from './counter';
8
+ import { countersOf, countersTargeting, countsRow } from './counter';
9
9
  import type { EntityCore } from './entity';
10
10
  import { SOFT_DELETE_COLUMN } from './entity';
11
11
  import { historyIgnored } from './history';
@@ -56,7 +56,8 @@ export function memoryLifecycle(
56
56
  const key = counter.parent.$primaryKey[0] ?? '';
57
57
  const move = (row: unknown, delta: number): void => {
58
58
  const id = field(row, counter.references);
59
- if (row === undefined || id == null || !live(entity, row)) return;
59
+ if (row === undefined || id == null || !live(entity, row) || !countsRow(counter, row))
60
+ return;
60
61
  const stored = parent?.find(key, id);
61
62
  if (stored === undefined) return;
62
63
  const count = Number(field(stored, counter.column) ?? 0) + delta;
@@ -17,6 +17,7 @@ import { holdsJsonNull } from './json-null';
17
17
  import { likeMatches } from './like';
18
18
  import { DECIMAL_TEXT, numericOrder } from './numeric-compare';
19
19
  import { operatorUnknown } from './operator';
20
+ import { orMembers, predicateNodeInvalid } from './predicate-node';
20
21
  import type { Predicate } from './tenancy';
21
22
  import { isTextContains, textContainsMatches } from './text-contains';
22
23
  import type { ColumnKind } from './types';
@@ -140,6 +141,18 @@ export const matchesPredicate = <Row>(
140
141
  // `searchInMemory` — and `valueAt(row, '$search')` would answer `undefined`, which every
141
142
  // comparison below reads as NULL and silently turns into "no rows".
142
143
  if (predicate.op === 'matches') throw searchInMemory(entity.$name);
144
+ // A group holds when any member does; no member is no row, as Postgres' `1 = 0` answers.
145
+ if (predicate.op === 'or') {
146
+ return orMembers(predicate).some((member) => matchesPredicate(entity, row, member));
147
+ }
148
+ if (predicate.op === 'and') {
149
+ return orMembers(predicate).every((member) => matchesPredicate(entity, row, member));
150
+ }
151
+ // A hop needs the target's rows, which one row does not carry: the memory driver resolves it to
152
+ // an `in` list first (`memory-via.ts`), and a store held in process cannot answer one at all.
153
+ if (predicate.op === 'via') {
154
+ throw predicateNodeInvalid(entity.$name, 'a via hop cannot be judged row by row in process');
155
+ }
143
156
  // The column's declared kind, resolved once — `price.minor` included, which is the path a money
144
157
  // predicate and a money sort key both name.
145
158
  const kind = kindOf(entity, predicate.column);
@@ -32,6 +32,7 @@ import { afterCursor } from './memory-seek';
32
32
  import { StoredRows, uniqueIndex, uniqueViolation } from './memory-unique';
33
33
  import { judgeUpdate, mergedRow } from './memory-update';
34
34
  import { memoryUpsertAll } from './memory-upsert';
35
+ import { registerMemoryScan, resolveMemoryVias } from './memory-via';
35
36
  import { assertPageBytes } from './page-bytes';
36
37
  import { idPlan, readPlan, singleKeyOf } from './plan';
37
38
  import type { FindManyArgs, MemoryRepo, RepoOptions } from './repo';
@@ -78,6 +79,7 @@ export const memoryRepo = <Row>(
78
79
  // Every unique key kept as rows move, so a single write is judged by its own keys, never a scan.
79
80
  const rows = new StoredRows<Row>(entity);
80
81
  for (const row of seed) rows.set(storeKey(row), row);
82
+ registerMemoryScan(tables, entity.$name, () => rows.values());
81
83
  tables.set(entity.$name, {
82
84
  entity: entity as EntityCore,
83
85
  // By the primary key when that is what is asked, which is nearly every reference.
@@ -126,12 +128,16 @@ export const memoryRepo = <Row>(
126
128
  args.includeDeleted === true ||
127
129
  field(row, SOFT_DELETE_COLUMN) === null ||
128
130
  field(row, SOFT_DELETE_COLUMN) === undefined;
131
+ // A `via` hop is answered from the driver's other tables first (`memory-via.ts`), once per plan.
129
132
  const matchesPlan = (plan: QueryPlan, row: Row): boolean =>
130
- plan.where.every((predicate) => matchesPredicate(entity, row, predicate));
133
+ resolveMemoryVias(entity, plan, tables).where.every((predicate) =>
134
+ matchesPredicate(entity, row, predicate),
135
+ );
131
136
 
132
137
  const rowsOf = (plan: QueryPlan, args: FindManyArgs): Row[] => {
138
+ const resolved = resolveMemoryVias(entity, plan, tables);
133
139
  return [...rows.values()]
134
- .filter((row) => matchesPlan(plan, row))
140
+ .filter((row) => matchesPlan(resolved, row))
135
141
  .filter(visibleTo(args))
136
142
  .sort((left, right) => {
137
143
  for (const entry of plan.orderBy) {
@@ -219,11 +225,7 @@ export const memoryRepo = <Row>(
219
225
  entity.$softDelete &&
220
226
  field(current, SOFT_DELETE_COLUMN) !== null &&
221
227
  field(current, SOFT_DELETE_COLUMN) !== undefined;
222
- if (
223
- current === undefined ||
224
- hidden ||
225
- !plan.where.every((predicate) => matchesPredicate(entity, current, predicate))
226
- ) {
228
+ if (current === undefined || hidden || !matchesPlan(plan, current)) {
227
229
  throw notFound(entity.$name, id);
228
230
  }
229
231
  return current;
@@ -0,0 +1,78 @@
1
+ // Single responsibility: the memory driver's half of a `via` hop. Postgres runs the subselect; here
2
+ // the hop is resolved, before any row is judged, to an `in` list of the target column's values over
3
+ // the target's stored rows that match its (already tenant-scoped) where — its soft delete applied —
4
+ // so both drivers answer one question from one plan.
5
+
6
+ import { valueAt } from './cursor';
7
+ import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
8
+ import { matchesPredicate } from './memory-match';
9
+ import type { MemoryTables } from './memory-same-tenant';
10
+ import { isGroup, orMembers, predicateNodeInvalid, viaValue } from './predicate-node';
11
+ import { viaTarget } from './predicate-screen';
12
+ import type { Predicate, QueryPlan } from './tenancy';
13
+ import { isScopedVia } from './via-scope';
14
+
15
+ /** Every repository's stored rows, by entity name, per driver — what a hop reads its target from. */
16
+ const scans = new WeakMap<MemoryTables, Map<string, () => Iterable<unknown>>>();
17
+
18
+ /** `memoryRepo` registers its rows here beside its `tables` entry. */
19
+ export const registerMemoryScan = (
20
+ tables: MemoryTables,
21
+ name: string,
22
+ rows: () => Iterable<unknown>,
23
+ ): void => {
24
+ let byName = scans.get(tables);
25
+ if (byName === undefined) {
26
+ byName = new Map();
27
+ scans.set(tables, byName);
28
+ }
29
+ byName.set(name, rows);
30
+ };
31
+
32
+ const isDeleted = (target: EntityCore, row: unknown): boolean => {
33
+ if (!target.$softDelete) return false;
34
+ const stamp = valueAt(row, SOFT_DELETE_COLUMN);
35
+ return stamp !== null && stamp !== undefined;
36
+ };
37
+
38
+ const resolveLevel = (
39
+ source: EntityCore,
40
+ where: readonly Predicate[],
41
+ tables: MemoryTables,
42
+ ): readonly Predicate[] =>
43
+ where.map((predicate): Predicate => {
44
+ if (isGroup(predicate)) {
45
+ return { ...predicate, value: resolveLevel(source, orMembers(predicate), tables) };
46
+ }
47
+ if (predicate.op !== 'via') return predicate;
48
+ if (!isScopedVia(predicate.value)) {
49
+ throw predicateNodeInvalid(
50
+ source.$name,
51
+ 'a via hop reached the driver without readPlan scoping it',
52
+ );
53
+ }
54
+ const target = viaTarget(source, predicate);
55
+ const hop = viaValue(predicate);
56
+ const inner = resolveLevel(target, hop.where, tables);
57
+ // A target this driver holds no repository for has no rows — as an empty table answers.
58
+ const rows = scans.get(tables)?.get(target.$name)?.() ?? [];
59
+ const values: unknown[] = [];
60
+ for (const row of rows) {
61
+ if (isDeleted(target, row)) continue;
62
+ if (!inner.every((each) => matchesPredicate(target, row, each))) continue;
63
+ values.push(valueAt(row, hop.target));
64
+ }
65
+ // NULL never matches `in (select …)`; dropped so `in`'s own null rule cannot reintroduce it.
66
+ const present = values.filter((value) => value !== null && value !== undefined);
67
+ return { column: predicate.column, op: 'in', value: present };
68
+ });
69
+
70
+ /** `plan` with every hop answered from this driver's rows. A plan with no hop comes back as is. */
71
+ export const resolveMemoryVias = <Row>(
72
+ entity: EntityCore<Row>,
73
+ plan: QueryPlan,
74
+ tables: MemoryTables,
75
+ ): QueryPlan => {
76
+ const nodes = plan.where.some((predicate) => isGroup(predicate) || predicate.op === 'via');
77
+ return nodes ? { ...plan, where: resolveLevel(entity as EntityCore, plan.where, tables) } : plan;
78
+ };
package/src/pg-sql.ts CHANGED
@@ -12,9 +12,12 @@ import { searchUndeclared } from './feature-errors';
12
12
  import { microsToIso, seekAlias } from './instant';
13
13
  import { operatorUnknown } from './operator';
14
14
  import { allColumns, arrayLiteral, columnsOf, physicalName } from './pg-row';
15
+ import { orMembers, predicateNodeInvalid, viaValue } from './predicate-node';
16
+ import { viaTarget } from './predicate-screen';
15
17
  import type { Predicate, QueryPlan, SortKey } from './tenancy';
16
18
  import { isTextContains, textContainsSql } from './text-contains';
17
19
  import type { ColumnKind } from './types';
20
+ import { isScopedVia } from './via-scope';
18
21
 
19
22
  /** Nothing matches. `in ()` is a syntax error in Postgres, so an empty set needs a constant. */
20
23
  const NEVER = sql`1 = 0`;
@@ -74,9 +77,12 @@ const nullTestPath = <Row>(entity: EntityCore<Row>, predicate: Predicate): strin
74
77
  };
75
78
 
76
79
  const predicateSql = <Row>(entity: EntityCore<Row>, predicate: Predicate): SqlFragment => {
77
- // BEFORE the column is resolved: a `matches` predicate names `SEARCH_PROPERTY`, which is not a
78
- // column and must never be looked up as one.
80
+ // BEFORE the column is resolved: a `matches` predicate names `SEARCH_PROPERTY`, and an `or` group
81
+ // `OR_PROPERTY` — neither is a column, and neither must ever be looked up as one.
79
82
  if (predicate.op === 'matches') return searchSql(entity, predicate);
83
+ if (predicate.op === 'or') return orSql(entity, predicate);
84
+ if (predicate.op === 'and') return andSql(entity, predicate);
85
+ if (predicate.op === 'via') return viaSql(entity, predicate);
80
86
  const column = columnRef(entity, nullTestPath(entity, predicate));
81
87
  const value = predicate.value;
82
88
  switch (predicate.op) {
@@ -327,6 +333,41 @@ export const predicatesSql = <Row>(
327
333
  ' and ',
328
334
  );
329
335
 
336
+ /** `( a or b … )`, each member compiled as any predicate is. No member is no row, never every row. */
337
+ const orSql = <Row>(entity: EntityCore<Row>, predicate: Predicate): SqlFragment => {
338
+ const members = orMembers(predicate).map((member) => predicateSql(entity, member));
339
+ return members.length === 0 ? NEVER : sql`(${join(members, ' or ')})`;
340
+ };
341
+
342
+ /**
343
+ * `"col" in (select "target" from "table" where …)` — one statement, the hop inlined as a semi-join
344
+ * the planner can drive from either side. Only a hop `readPlan` scoped is compiled: its inner where
345
+ * already carries the target's tenant, and the target's soft delete is applied here as a top-level
346
+ * read of it would be. `null` in the target column never matches, as `in` already answers.
347
+ */
348
+ const viaSql = <Row>(entity: EntityCore<Row>, predicate: Predicate): SqlFragment => {
349
+ if (!isScopedVia(predicate.value)) {
350
+ throw predicateNodeInvalid(
351
+ entity.$name,
352
+ 'a via hop reached the driver without readPlan scoping it',
353
+ );
354
+ }
355
+ const target = viaTarget(entity as EntityCore, predicate);
356
+ const hop = viaValue(predicate);
357
+ const parts = hop.where.map((inner) => predicateSql(target, inner));
358
+ if (target.$softDelete) {
359
+ parts.push(sql`${identifier(physicalName(target, SOFT_DELETE_COLUMN))} is null`);
360
+ }
361
+ const where = parts.length === 0 ? sql`true` : join(parts, ' and ');
362
+ return sql`${columnRef(entity, predicate.column)} in (select ${columnRef(target, hop.target)} from ${identifier(target.$table)} where ${where})`;
363
+ };
364
+
365
+ /** `( a and b … )`; no member holds for every row, as an empty conjunction does. */
366
+ const andSql = <Row>(entity: EntityCore<Row>, predicate: Predicate): SqlFragment => {
367
+ const members = orMembers(predicate).map((member) => predicateSql(entity, member));
368
+ return members.length === 0 ? sql`true` : sql`(${join(members, ' and ')})`;
369
+ };
370
+
330
371
  export const conditions = <Row>(
331
372
  entity: EntityCore<Row>,
332
373
  plan: QueryPlan,
package/src/plan.ts CHANGED
@@ -10,6 +10,7 @@ import { screenPredicates } from './predicate-screen';
10
10
  import type { FindManyArgs, RepoOptions } from './repo';
11
11
  import type { Predicate, QueryPlan, SortKey } from './tenancy';
12
12
  import { scopedPlan } from './tenancy';
13
+ import { scopeVias } from './via-scope';
13
14
 
14
15
  /** A page is bounded by default; an unbounded read is a production incident waiting for traffic. */
15
16
  export const DEFAULT_PAGE_SIZE = 50;
@@ -145,7 +146,12 @@ export const readPlan = <Row>(
145
146
  // was declared and unusable — the defect class this repo keeps re-shipping. One refusal, and it
146
147
  // names which of the two situations the caller is in.
147
148
  if (operation === 'approximateCount') assertEstimable(entity, plan);
148
- return scopedPlan(entity.$name, entity.$tenantColumn, operation, plan);
149
+ // A `via` hop is scoped AFTER the source: its subselect gets its own target's tenant.
150
+ return scopeVias(
151
+ entity,
152
+ scopedPlan(entity.$name, entity.$tenantColumn, operation, plan),
153
+ operation,
154
+ );
149
155
  };
150
156
 
151
157
  /**
@@ -0,0 +1,148 @@
1
+ // Single responsibility: the predicate TREE (`or`/`and` groups, `via` hops) as an author writes it,
2
+ // compiled into ordinary plan predicates. A node rides in `plan.where` as one `Predicate` whose `op`
3
+ // is not an `Operator`, so an executor that does not know it refuses the op rather than silently
4
+ // dropping the filter.
5
+
6
+ import { EntityError } from './entity-error';
7
+ import { checkedPredicate, type Operator } from './operator';
8
+ import type { Predicate } from './tenancy';
9
+
10
+ /** The pseudo-columns a group is planned under — never a property, as `$search` is not. */
11
+ export const OR_PROPERTY = '$or';
12
+ export const AND_PROPERTY = '$and';
13
+
14
+ /**
15
+ * How deep a tree may nest, counting every `or` and `via`. A scope is a handful of conditions; a
16
+ * tree deeper than this is a generated one, and a statement whose planner time grows with it.
17
+ */
18
+ export const MAX_PREDICATE_DEPTH = 4;
19
+
20
+ /** A column of `Row`; any string for an untyped level (a hop's inner where), never `never`. */
21
+ export type NodeColumn<Row> = unknown extends Row ? string : Extract<keyof Row, string>;
22
+
23
+ /** One leaf, as `andWhere` takes it. */
24
+ export interface PredicateLeaf<Row = unknown> {
25
+ readonly column: NodeColumn<Row>;
26
+ readonly op: Operator;
27
+ readonly value?: unknown;
28
+ }
29
+
30
+ /** Any one of its members holds. `[]` holds for no row. */
31
+ export interface PredicateOr<Row = unknown> {
32
+ readonly or: readonly PredicateNode<Row>[];
33
+ }
34
+
35
+ /** Every member holds — the conjunction an `or` member needs (`friends AND a friend's`). `[]`: all. */
36
+ export interface PredicateAnd<Row = unknown> {
37
+ readonly and: readonly PredicateNode<Row>[];
38
+ }
39
+
40
+ /**
41
+ * `column in (select target from entity where …)`: the row's `column` names a row of `entity`
42
+ * matching `where`. `entity` is the target's NAME; its tenant and its soft delete apply inside.
43
+ */
44
+ export interface PredicateVia<Row = unknown> {
45
+ readonly via: {
46
+ readonly column: NodeColumn<Row>;
47
+ readonly entity: string;
48
+ readonly target: string;
49
+ };
50
+ readonly where: readonly PredicateNode[];
51
+ }
52
+
53
+ /** A tree over `Row`'s columns. A `via`'s inner `where` is over the target's, typed `unknown`. */
54
+ export type PredicateNode<Row = unknown> =
55
+ | PredicateLeaf<Row>
56
+ | PredicateOr<Row>
57
+ | PredicateAnd<Row>
58
+ | PredicateVia<Row>;
59
+
60
+ declare const scopedNode: unique symbol;
61
+
62
+ /**
63
+ * A node a `scoped()` policy produced, handed over on `@ultimat3/query`'s `RowWindow.nodes`. Typed
64
+ * against the policy's row where it was declared, so `andWhereNode` takes it as it takes a literal
65
+ * tree; the brand is what keeps a hand-written untyped node from passing for one.
66
+ */
67
+ export type ScopedNode = PredicateNode & { readonly [scopedNode]: true };
68
+
69
+ /** The planned form of a `via`, as `Predicate.value`. `where` is planned against the target. */
70
+ export interface ViaValue {
71
+ readonly entity: string;
72
+ readonly target: string;
73
+ readonly where: readonly Predicate[];
74
+ }
75
+
76
+ /** The ops a node plans to: never in `OPERATORS`, so `andWhere` cannot name one. */
77
+ export type NodeOperator = 'or' | 'and' | 'via';
78
+
79
+ export const isNodeOp = (op: unknown): op is NodeOperator =>
80
+ op === 'or' || op === 'and' || op === 'via';
81
+
82
+ /** Whether a planned predicate is an `or` or an `and` group — one walk serves both. */
83
+ export const isGroup = (predicate: Predicate): boolean =>
84
+ predicate.op === 'or' || predicate.op === 'and';
85
+
86
+ /** The refusal for a tree no driver can answer: its shape, its depth or what a `via` names. */
87
+ export const predicateNodeInvalid = (entityName: string, detail: string): EntityError =>
88
+ new EntityError({
89
+ code: 'X_ENTITY_PREDICATE_NODE_INVALID',
90
+ cause: `${entityName}: andWhereNode() was handed a tree no driver can answer — ${detail}`,
91
+ fix: `andWhereNode({ or: [{ column, op, value }, …] }) # or { via: { column, entity, target }, where: [ … ] }: entity is a registered entity name, column and target its declared properties, at most ${MAX_PREDICATE_DEPTH} levels deep`,
92
+ });
93
+
94
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
95
+ typeof value === 'object' && value !== null && !Array.isArray(value);
96
+
97
+ /**
98
+ * The tree as plan predicates, its shape checked on the line the author wrote. Columns are judged
99
+ * later, by `screenPredicates`, against the entity each level is about — a `via`'s inner level is
100
+ * the target's, which only the registry knows.
101
+ */
102
+ export const nodePredicate = (entityName: string, node: unknown, depth = 1): Predicate => {
103
+ if (!isRecord(node)) throw predicateNodeInvalid(entityName, 'a node is not an object');
104
+ const group = node['or'] !== undefined ? 'or' : node['and'] !== undefined ? 'and' : undefined;
105
+ const via = node['via'];
106
+ if ((group !== undefined || via !== undefined) && depth > MAX_PREDICATE_DEPTH) {
107
+ throw predicateNodeInvalid(entityName, `it nests deeper than ${MAX_PREDICATE_DEPTH} levels`);
108
+ }
109
+ if (group !== undefined) {
110
+ const members = node[group];
111
+ if (!Array.isArray(members))
112
+ throw predicateNodeInvalid(entityName, `\`${group}\` is not a list`);
113
+ const planned = members.map((each: unknown) => nodePredicate(entityName, each, depth + 1));
114
+ return { column: group === 'or' ? OR_PROPERTY : AND_PROPERTY, op: group, value: planned };
115
+ }
116
+ if (via !== undefined) return viaPredicate(entityName, via, node['where'], depth);
117
+ const column = node['column'];
118
+ if (typeof column !== 'string') throw predicateNodeInvalid(entityName, 'a leaf has no column');
119
+ return checkedPredicate(entityName, column, node['op'], node['value']);
120
+ };
121
+
122
+ const viaPredicate = (
123
+ entityName: string,
124
+ via: unknown,
125
+ where: unknown,
126
+ depth: number,
127
+ ): Predicate => {
128
+ const column = isRecord(via) ? via['column'] : undefined;
129
+ const entity = isRecord(via) ? via['entity'] : undefined;
130
+ const target = isRecord(via) ? via['target'] : undefined;
131
+ if (typeof column !== 'string' || typeof entity !== 'string' || typeof target !== 'string') {
132
+ throw predicateNodeInvalid(entityName, '`via` needs { column, entity, target }, each a string');
133
+ }
134
+ if (!Array.isArray(where)) throw predicateNodeInvalid(entityName, '`via.where` is not a list');
135
+ const value: ViaValue = {
136
+ entity,
137
+ target,
138
+ where: where.map((each: unknown) => nodePredicate(entity, each, depth + 1)),
139
+ };
140
+ return { column, op: 'via', value };
141
+ };
142
+
143
+ /** A group's members (`or` or `and`), as planned. */
144
+ export const orMembers = (predicate: Predicate): readonly Predicate[] =>
145
+ Array.isArray(predicate.value) ? (predicate.value as readonly Predicate[]) : [];
146
+
147
+ /** A `via` predicate's planned value. Only `nodePredicate` and `via-scope.ts` build one. */
148
+ export const viaValue = (predicate: Predicate): ViaValue => predicate.value as ViaValue;
@@ -1,12 +1,15 @@
1
- // Single responsibility: refuse, at plan time, a predicate no driver can answer — so the refusal
2
- // never depends on whether a table holds rows. Memory judged an operator only against a row, and
3
- // answered `[]` for an unknown one on an empty table where Postgres refused; a whole money value
4
- // compared as one column is the same shape: Postgres has no column to compare it with.
1
+ // Single responsibility: refuse, at plan time, a predicate no driver can answer, so the refusal
2
+ // never depends on whether a table holds rows (memory once answered `[]` where Postgres refused;
3
+ // a whole money value has no column to compare). A predicate TREE is screened level by level,
4
+ // each against the entity it is about.
5
5
 
6
6
  import { columnFor } from './column';
7
7
  import type { EntityCore } from './entity';
8
8
  import { invariantViolated } from './errors';
9
9
  import { isOperator, operatorUnknown } from './operator';
10
+ import { isGroup, orMembers, predicateNodeInvalid, viaValue } from './predicate-node';
11
+ import { getEntity } from './registry';
12
+ import { sealedFields } from './sealed';
10
13
  import type { Predicate } from './tenancy';
11
14
 
12
15
  /** A NULL test on a whole money property asks about its amount (`pg-sql.ts` `nullTestPath`). */
@@ -20,9 +23,28 @@ export const screenPredicates = <Row>(
20
23
  where: readonly Predicate[],
21
24
  ): void => {
22
25
  for (const predicate of where) {
26
+ if (isGroup(predicate)) {
27
+ screenPredicates(entity, orMembers(predicate));
28
+ continue;
29
+ }
30
+ if (predicate.op === 'via') {
31
+ screenVia(entity, predicate);
32
+ continue;
33
+ }
23
34
  if (!isOperator(predicate.op)) {
24
35
  throw operatorUnknown(entity.$name, predicate.column, predicate.op);
25
36
  }
37
+ // An undeclared column is refused HERE, for both drivers: Postgres could never resolve it
38
+ // (`physicalName`), and memory read it off the row as NULL — rows in one, a refusal in the other.
39
+ // `matches` names `SEARCH_PROPERTY`, which is not a column by design.
40
+ const [property = predicate.column] = predicate.column.split('.');
41
+ if (predicate.op !== 'matches' && columnFor(entity.$columns, property) === undefined) {
42
+ throw invariantViolated(
43
+ entity.$name,
44
+ 'column',
45
+ `no column "${predicate.column}" — pick from: ${Object.keys(entity.$columns).join(', ')}`,
46
+ );
47
+ }
26
48
  const column = columnFor(entity.$columns, predicate.column);
27
49
  if (column?.$meta.kind === 'money' && !isNullTest(predicate)) {
28
50
  const property = predicate.column;
@@ -34,3 +56,56 @@ export const screenPredicates = <Row>(
34
56
  }
35
57
  }
36
58
  };
59
+
60
+ /**
61
+ * The entity a `via` reads, resolved from the registry by NAME. Exported for the two places that
62
+ * compile one: the subselect is built against this entity's own table, columns and soft delete.
63
+ */
64
+ export const viaTarget = (source: EntityCore, predicate: Predicate): EntityCore => {
65
+ const { entity: name } = viaValue(predicate);
66
+ const target = getEntity(name)?.core;
67
+ if (target === undefined) {
68
+ throw predicateNodeInvalid(source.$name, `via names entity '${name}', which is not registered`);
69
+ }
70
+ return target;
71
+ };
72
+
73
+ /**
74
+ * A `via` names two declared columns, neither of them sealed — a sealed value is ciphertext and the
75
+ * hop would compare it to a plaintext the source never stores — and its inner level is screened as
76
+ * the target's. Sealed columns are refused INSIDE it too: the target's sealing seam is not on this
77
+ * read, so nothing would rewrite them.
78
+ */
79
+ const screenVia = <Row>(entity: EntityCore<Row>, predicate: Predicate): void => {
80
+ const source = entity as EntityCore;
81
+ const target = viaTarget(source, predicate);
82
+ const { target: targetColumn, where } = viaValue(predicate);
83
+ const named = (owner: EntityCore, column: string): void => {
84
+ if (columnFor(owner.$columns, column) === undefined) {
85
+ throw predicateNodeInvalid(
86
+ source.$name,
87
+ `via names ${owner.$name}.${column}, no declared column`,
88
+ );
89
+ }
90
+ if (sealedFields(owner).some((field) => field.property === column)) {
91
+ throw predicateNodeInvalid(
92
+ source.$name,
93
+ `via names ${owner.$name}.${column}, a sealed column`,
94
+ );
95
+ }
96
+ };
97
+ named(source, predicate.column);
98
+ named(target, targetColumn);
99
+ for (const column of leafColumns(where)) named(target, column);
100
+ screenPredicates(target, where);
101
+ };
102
+
103
+ /** Every real column a level names, through its `or` groups but not into a nested `via`. */
104
+ const leafColumns = (where: readonly Predicate[]): readonly string[] =>
105
+ where.flatMap((predicate) =>
106
+ isGroup(predicate)
107
+ ? leafColumns(orMembers(predicate))
108
+ : predicate.op === 'via'
109
+ ? [predicate.column]
110
+ : [predicate.column.split('.')[0] ?? predicate.column],
111
+ );
package/src/query.ts CHANGED
@@ -14,6 +14,7 @@ import { searchUndeclared } from './feature-errors';
14
14
  import { latestByRows, type ReadLatest } from './latest-by';
15
15
  import { checkedPredicate, type Operator } from './operator';
16
16
  import { assertFinitePageSize, DEFAULT_PAGE_SIZE } from './plan';
17
+ import { nodePredicate, type PredicateNode, type ScopedNode } from './predicate-node';
17
18
  import { preloaded, type RelatedTables } from './preload';
18
19
  import { type PreloadOptions, type PreloadRelation, preloadsWith } from './preload-ceiling';
19
20
  import {
@@ -70,6 +71,14 @@ export interface ReadBuilder<Row, S extends SealedKeySet = NoSealedKeys>
70
71
  op: Operator,
71
72
  value: unknown,
72
73
  ): ReadBuilder<Row, S>;
74
+ /**
75
+ * One predicate TREE, AND-ed with the rest of the chain: an `or` group, or a `via` hop —
76
+ * `{ via: { column: 'authorId', entity: 'friendships', target: 'friendId' }, where: [...] }` is
77
+ * `author_id in (select friend_id from friendships where …)`. One statement either way, and a
78
+ * hop's subselect runs under its target's tenant and soft delete as a read of it would. A leaf is
79
+ * `andWhere`'s three arguments as an object; at most `MAX_PREDICATE_DEPTH` levels deep.
80
+ */
81
+ andWhereNode(node: PredicateNode<Row> | ScopedNode): ReadBuilder<Row, S>;
73
82
  /**
74
83
  * Full-text search over the entity's generated `tsvector` — every `.searchable()` column at
75
84
  * once, one GIN index, one predicate. `posts.where({ orgId }).search(input.q).limit(20).page()`.
@@ -277,6 +286,8 @@ const builder = <Source, Row>(
277
286
  andWhere: (column: string, op: Operator, value?: unknown) =>
278
287
  next({ where: [...state.where, checkedPredicate(entity.$name, column, op, value)] }),
279
288
 
289
+ andWhereNode: (node) => next({ where: [...state.where, nodePredicate(entity.$name, node)] }),
290
+
280
291
  // Refused HERE as well as at the statement, because this is the line the author wrote: a chain
281
292
  // over an entity that declares nothing searchable can never produce a match, and the repair is
282
293
  // one edit to the schema rather than anything about this call.
package/src/registry.ts CHANGED
@@ -180,6 +180,8 @@ export interface EntityDescription {
180
180
  readonly retired?: readonly string[] | undefined;
181
181
  /** `entity({ shared: '<why>' })`: why a row referencing a tenant's belongs to no tenant. */
182
182
  readonly shared?: string | undefined;
183
+ /** `entity({ global: '<why>' })`: why a row referencing no tenant's is every tenant's alike. */
184
+ readonly global?: string | undefined;
183
185
  /** `entity({ scan: '<why>' })`: why the plan sweep may see this table scanned. */
184
186
  readonly scan?: string | undefined;
185
187
  /** `entity({ readOnly: '<why>' })`: why the app never writes the table; every write refused. */
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { pageOf } from '@ultimat3/core';
8
8
  import type { AggregateFn } from './aggregate';
9
+ import { isGroup, orMembers } from './predicate-node';
9
10
  import type { FilteredWriteOptions, FindManyArgs, Repo, UpsertArgs } from './repo';
10
11
  import type { SealedField, SealedSource, SealKeys } from './sealed';
11
12
  import {
@@ -94,6 +95,14 @@ const rewrite = async (
94
95
  predicate: Predicate,
95
96
  keys: SealKeys,
96
97
  ): Promise<Predicate> => {
98
+ // A group's members are this entity's predicates too, rewritten as top-level ones are. A
99
+ // `via` hop's inner level is the target's and names no sealed column (`predicate-screen.ts`).
100
+ if (isGroup(predicate)) {
101
+ const members = await Promise.all(
102
+ orMembers(predicate).map((member) => rewrite(entity, fields, member, keys)),
103
+ );
104
+ return { ...predicate, value: members };
105
+ }
97
106
  const field = fields.find((one) => one.property === predicate.column);
98
107
  if (field === undefined) return predicate;
99
108
  const { op, value } = predicate;
package/src/tenancy.ts CHANGED
@@ -12,14 +12,19 @@ import {
12
12
  tenancyUnscoped,
13
13
  } from './errors';
14
14
  import type { Operator } from './operator';
15
+ import type { NodeOperator } from './predicate-node';
15
16
  import type { ColumnMap } from './types';
16
17
 
17
18
  /** The vocabulary is `OPERATORS` (`operator.ts`) — one list, and this type is derived from it. */
18
19
  export type { Operator } from './operator';
19
20
 
21
+ /**
22
+ * One conjunct of a plan. `op` is an `Operator`, or a NODE (`predicate-node.ts`): an `or` group
23
+ * under the `$or` pseudo-column, or a `via` hop on a real column — built by `andWhereNode` only.
24
+ */
20
25
  export interface Predicate {
21
26
  readonly column: string;
22
- readonly op: Operator;
27
+ readonly op: Operator | NodeOperator;
23
28
  readonly value?: unknown;
24
29
  }
25
30
 
@@ -0,0 +1,31 @@
1
+ // Compile-time pins for `andWhereNode`'s column typing — split from `type-pins.ts`, which sits at
2
+ // the file ceiling. Source, not a test: `tsc -b` never reads a `.test.ts`, so a pin there cannot fail.
3
+
4
+ import type { ReadBuilder } from './query';
5
+
6
+ /** Fails to compile when `T` is anything but `true`. */
7
+ type Assert<T extends true> = T;
8
+
9
+ /**
10
+ * `andWhereNode` names the chain's own columns at the top and inside every `or`; a hop's inner level
11
+ * is the target's, which the type cannot see, so it takes any string there. A misspelt top-level
12
+ * column is a compile error, never a refusal at the first request.
13
+ */
14
+ type NodeOf<Row> = Parameters<ReadBuilder<Row>['andWhereNode']>[0];
15
+ type NodeRow = { readonly id: string; readonly kind: string };
16
+ export type _NodeLeafNamesTheRow = Assert<
17
+ { readonly column: 'nope'; readonly op: 'eq' } extends NodeOf<NodeRow> ? false : true
18
+ >;
19
+ export type _NodeOrNamesTheRow = Assert<
20
+ { readonly or: readonly [{ readonly column: 'nope'; readonly op: 'eq' }] } extends NodeOf<NodeRow>
21
+ ? false
22
+ : true
23
+ >;
24
+ export type _NodeViaInnerTakesTheTarget = Assert<
25
+ {
26
+ readonly via: { readonly column: 'id'; readonly entity: string; readonly target: string };
27
+ readonly where: readonly [{ readonly column: 'friendId'; readonly op: 'eq' }];
28
+ } extends NodeOf<NodeRow>
29
+ ? true
30
+ : false
31
+ >;