@mistriwork/engine 1.0.0-rc.19 → 1.0.0-rc.20

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.
@@ -1,6 +1,5 @@
1
1
  import { type Adapter, type Filter, type QueryRequest, type QueryResult, type ScopedReads, type SqlRequest, type SqlResult, type ViewResult, type BreakdownResult, type ExplainRequest, type ExplainResult, type ProfileResult, TransactionOperations, type WriteTransaction, type DeleteRequest, type DeleteResult, type InsertRequest, type InsertResult, type UpdateRequest, type UpdateResult, type CountItem, type RolePrivileges, type SqlStyle, type AggregateRequest, type AggregateResult } from './adapter.js';
2
2
  import type { TriggerAcceptance } from './scoped/triggerProof.js';
3
- import { type PostgresScopeCatalog } from './scoped/postgresScopeCatalog.js';
4
3
  import type { ScopeTrigger } from './scoped/scopeTriggers.js';
5
4
  import type { TriggerKeyFacts } from './scoped/triggerEffects.js';
6
5
  import { type PinnedPostgresReadOwner, type PostgresReadDependency } from './postgresReadCatalog.js';
@@ -8,13 +7,14 @@ import type { DatabaseSchema } from '../shared/schema.js';
8
7
  import { type ViewDef } from '../shared/view.js';
9
8
  import { type BreakdownDef } from '../shared/breakdown.js';
10
9
  import { PgConnectionManager, type PgConnectionOptions, type PgQuery, type SharedPoolShape } from './postgresPool.js';
11
- import { type PipelinedStatement } from './postgresTransactionHandle.js';
10
+ import { type PostgresTransactionVerifier } from './postgresTransactionOpening.js';
12
11
  import type { PoolRoleStats } from './poolMetrics.js';
13
12
  import { type RowScope } from '../shared/rowScope.js';
14
13
  import { type PostgresReadSnapshot } from './postgresReadSnapshot.js';
15
14
  /** Constructor-issued source identity, checked without reading receiver data. */
16
15
  export declare const isPostgresVerifiedCommandSource: (value: unknown) => value is PostgresAdapter;
17
16
  export type { PostgresReadSnapshot } from './postgresReadSnapshot.js';
17
+ export type { PostgresTransactionVerifier } from './postgresTransactionOpening.js';
18
18
  /** For the budget tests: how many times this process described a PostgreSQL catalog, and how many were found kept. */
19
19
  export declare function postgresDescriptionCounts(): Readonly<{
20
20
  described: number;
@@ -194,6 +194,7 @@ export declare class PostgresAdapter implements Adapter {
194
194
  private attestJournal;
195
195
  query(request: QueryRequest): Promise<QueryResult>;
196
196
  scopeReads(input: RowScope): Promise<ScopedReads>;
197
+ private whereOf;
197
198
  private queryOn;
198
199
  /**
199
200
  * Run a compiled view.
@@ -415,27 +416,3 @@ export declare class PostgresAdapter implements Adapter {
415
416
  private epochOf;
416
417
  private assertTable;
417
418
  }
418
- /** Trusted host verification on the writer of a verified scoped transaction:
419
- * the scope catalog it was pinned and read with, and the adapter's own
420
- * introspection on the same writer. */
421
- export type PostgresTransactionVerifier = {
422
- (client: PgQuery, catalog: PostgresScopeCatalog, describe: () => Promise<DatabaseSchema>, epoch?: string): Promise<void>;
423
- /**
424
- * The verifier's own LOCK, without parameters, taken in the message that
425
- * begins the transaction, after the scope's pin and before the schema epoch
426
- * (or catalog digest) is read. The epoch then covers everything it pinned:
427
- * DDL committed before it is in the epoch, DDL after it waits for this
428
- * transaction. The verifier is handed that epoch as `epoch`, so a full
429
- * attestation it made under the same epoch stands without being read again
430
- * (tenantWriteSource.ts). A message that fails begins again plainly, and
431
- * the verifier is handed no epoch.
432
- */
433
- readonly pin?: string;
434
- /**
435
- * The statements the verifier's first pass sends, exactly, sent behind the
436
- * BEGIN with what else the transaction opens with (sendWriteAhead): each
437
- * answers the identical statement once when the verifier sends it. A
438
- * statement it does not send is left unread.
439
- */
440
- readonly ahead?: () => readonly PipelinedStatement[];
441
- };
@@ -8,6 +8,9 @@
8
8
  * connect, or the leased writer inside a scoped transaction.
9
9
  */
10
10
  import { isProxy } from 'node:util/types';
11
+ import { inlineRows } from '../shared/anyRows.js';
12
+ import { asksAboutRows } from '../shared/filter.js';
13
+ import { qualifiedTable } from '../shared/sqlRelation.js';
11
14
  import { POSTGRES_STYLE, buildWhere, clampLimit, boundStatement, dedupe, looksWrappable, refuseStacked, trimStatement, clampOffset, Refusal, WriteConflict, TransactionOperations, queueRecordLock, recordLockFilter, TransactionOutcomeUnknown, refuseAnalyze, countStatement, countEachStatement, countEachRows, countsTogether, orderClause, lanesStatement, withoutLaneRow, } from './adapter.js';
12
15
  import { compileAggregate } from '../shared/aggregate.js';
13
16
  import { coerceForColumn } from '../shared/schema.js';
@@ -25,6 +28,7 @@ import { compileBreakdown, compileBreakdownCount } from '../shared/breakdown.js'
25
28
  import { PgConnectionManager, sharedPgConnections } from './postgresPool.js';
26
29
  import { aheadReport, beforeCommit, behindWrite, generationOf, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
27
30
  import { snapshotRead, withoutSnapshotRead } from './snapshotRead.js';
31
+ import { SCOPED_SESSION, beginOf, snapshotHandles, verifierPin } from './postgresTransactionOpening.js';
28
32
  import { withoutWriteAhead, writeAhead } from './writeAhead.js';
29
33
  import { KeyRows } from './scoped/keyRows.js';
30
34
  import { PLAIN_SCOPE, catalogId, heldLocks, heldRows, lockKey, plainStatement, plainTable, reportWriteAhead, rowLockKey, rowLockStatement, scopedStatement, sendPlainAhead, sendWriteAhead, } from './postgresWriteAhead.js';
@@ -715,10 +719,23 @@ export class PostgresAdapter {
715
719
  };
716
720
  });
717
721
  }
722
+ /* A read's filter. Rows that point at the one read (`any`/`no`) are asked as an EXISTS over the child's own table, read
723
+ as the parent is: no scope sits between, so the caller's declaration of what it may read is the only bound
724
+ (commandDb.ts). The catalog is read only when the filter asks, and a filter that asks of a catalog this handle
725
+ cannot read is refused, as one nothing resolves is. */
726
+ async whereOf(id, qualified, filter) {
727
+ if (!asksAboutRows(filter))
728
+ return buildWhere(filter, POSTGRES_STYLE);
729
+ const schema = await this.schema().catch(() => undefined);
730
+ const inline = schema && inlineRows(schema, id, qualified, POSTGRES_STYLE, (child) => qualifiedTable(schema, child.id, POSTGRES_STYLE));
731
+ return buildWhere(filter, POSTGRES_STYLE, 1, undefined, undefined, undefined, undefined, false, undefined, false, inline);
732
+ }
718
733
  async queryOn(request, db, read = false) {
719
734
  const { schema, name } = read ? await this.readTable(request.table) : await this.assertTable(request.table, db);
720
735
  const qualified = `${POSTGRES_STYLE.quote(schema)}.${POSTGRES_STYLE.quote(name)}`;
721
- const where = buildWhere(request.filter, POSTGRES_STYLE);
736
+ const where = asksAboutRows(request.filter)
737
+ ? await this.whereOf(request.table, qualified, request.filter)
738
+ : buildWhere(request.filter, POSTGRES_STYLE);
722
739
  const cols = request.columns?.length ? request.columns.map((c) => POSTGRES_STYLE.quote(c)).join(', ') : '*';
723
740
  const order = orderClause(request.orderBy, request.orderBy?.length ? (await this.schema()).tables.find((t) => t.id === request.table) : undefined, POSTGRES_STYLE, where.params.length + 1);
724
741
  /* Every read is bounded. There is no code path that reaches the database
@@ -844,8 +861,9 @@ export class PostgresAdapter {
844
861
  }
845
862
  async countOn(table, filter, db, limit, read = false) {
846
863
  const { schema, name } = read ? await this.readTable(table) : await this.assertTable(table, db);
847
- const where = buildWhere(filter, POSTGRES_STYLE);
848
- const text = countStatement(`${POSTGRES_STYLE.quote(schema)}.${POSTGRES_STYLE.quote(name)}${where.text}`, limit);
864
+ const qualified = `${POSTGRES_STYLE.quote(schema)}.${POSTGRES_STYLE.quote(name)}`;
865
+ const where = asksAboutRows(filter) ? await this.whereOf(table, qualified, filter) : buildWhere(filter, POSTGRES_STYLE);
866
+ const text = countStatement(`${qualified}${where.text}`, limit);
849
867
  const result = await db.query(text, where.params);
850
868
  return Number(result.rows[0]?.n ?? 0);
851
869
  }
@@ -1652,7 +1670,7 @@ export class PostgresAdapter {
1652
1670
  },
1653
1671
  scope,
1654
1672
  }
1655
- : undefined);
1673
+ : undefined, scope);
1656
1674
  if (journal?.fixedRecords)
1657
1675
  records = journal.fixedRecords(records);
1658
1676
  const invoke = scopedCommandInvoker(operations, true, journal !== undefined, isRuntimeRelation);
@@ -1852,19 +1870,3 @@ export class PostgresAdapter {
1852
1870
  return assertPostgresTable(id, db, this.epochOf(db), this.catalogCache, () => this.conn());
1853
1871
  }
1854
1872
  }
1855
- /** A verifier's pin, when it is only LOCK statements with no parameters (it rides in the simple-protocol message).
1856
- Anything else is not taken: the transaction then runs as it would without one, and its verifier attests in full. */
1857
- function verifierPin(verify) {
1858
- const pin = verify?.pin;
1859
- return typeof pin === 'string' && /^LOCK TABLE [^;$]+ IN [A-Z ]+ MODE(; LOCK TABLE [^;$]+ IN [A-Z ]+ MODE)*$/.test(pin) ? pin : undefined;
1860
- }
1861
- /* Handles whose transaction reads one snapshot (snapshotRead.ts): REPEATABLE READ from its BEGIN, so every statement
1862
- reads as of its first. Kept on the handle, as its epoch is, so a retry of the opening begins the same way. */
1863
- const snapshotHandles = new WeakSet();
1864
- const beginOf = (write) => (snapshotHandles.has(write) ? 'BEGIN ISOLATION LEVEL REPEATABLE READ' : 'BEGIN');
1865
- /* What a scoped transaction's BEGIN also says, in its one message: the text a date is read as, whatever the role or
1866
- database set. A check binds a key's stored text and the database reads it back (storedText.ts, keyTypes.ts); under
1867
- `DateStyle = 'SQL, YMD'` a date said as 01/02/2026 reads back as another day. Only the output style is set: the
1868
- field order, which decides how a person's own 01/02/2026 is read, stays the database's. The float and interval
1869
- text, which no key is (keyTypes.ts), is pinned as well, so a value a trigger's proof compares reads as stored. */
1870
- const SCOPED_SESSION = '; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3';
@@ -0,0 +1,39 @@
1
+ /**
2
+ * How a Postgres scoped transaction opens: the verifier a trusted host hands it, the pin that rides in its BEGIN, the
3
+ * isolation a snapshot read begins with, and the session text its BEGIN sets. Pure parts of the adapter's opening, kept
4
+ * apart from the connection and the writes that use them (postgres.ts).
5
+ */
6
+ import type { DatabaseSchema } from '../shared/schema.js';
7
+ import type { PgQuery } from './postgresPool.js';
8
+ import type { PostgresScopeCatalog } from './scoped/postgresScopeCatalog.js';
9
+ import type { PipelinedStatement } from './postgresTransactionHandle.js';
10
+ /** Trusted host verification on the writer of a verified scoped transaction:
11
+ * the scope catalog it was pinned and read with, and the adapter's own
12
+ * introspection on the same writer. */
13
+ export type PostgresTransactionVerifier = {
14
+ (client: PgQuery, catalog: PostgresScopeCatalog, describe: () => Promise<DatabaseSchema>, epoch?: string): Promise<void>;
15
+ /**
16
+ * The verifier's own LOCK, without parameters, taken in the message that
17
+ * begins the transaction, after the scope's pin and before the schema epoch
18
+ * (or catalog digest) is read. The epoch then covers everything it pinned:
19
+ * DDL committed before it is in the epoch, DDL after it waits for this
20
+ * transaction. The verifier is handed that epoch as `epoch`, so a full
21
+ * attestation it made under the same epoch stands without being read again
22
+ * (tenantWriteSource.ts). A message that fails begins again plainly, and
23
+ * the verifier is handed no epoch.
24
+ */
25
+ readonly pin?: string;
26
+ /**
27
+ * The statements the verifier's first pass sends, exactly, sent behind the
28
+ * BEGIN with what else the transaction opens with (sendWriteAhead): each
29
+ * answers the identical statement once when the verifier sends it. A
30
+ * statement it does not send is left unread.
31
+ */
32
+ readonly ahead?: () => readonly PipelinedStatement[];
33
+ };
34
+ /** A verifier's pin, when it is only LOCK statements with no parameters (it rides in the simple-protocol message).
35
+ Anything else is not taken: the transaction then runs as it would without one, and its verifier attests in full. */
36
+ export declare function verifierPin(verify: PostgresTransactionVerifier | undefined): string | undefined;
37
+ export declare const snapshotHandles: WeakSet<PgQuery>;
38
+ export declare const beginOf: (write: PgQuery) => "BEGIN" | "BEGIN ISOLATION LEVEL REPEATABLE READ";
39
+ export declare const SCOPED_SESSION = "; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3";
@@ -0,0 +1,16 @@
1
+ /** A verifier's pin, when it is only LOCK statements with no parameters (it rides in the simple-protocol message).
2
+ Anything else is not taken: the transaction then runs as it would without one, and its verifier attests in full. */
3
+ export function verifierPin(verify) {
4
+ const pin = verify?.pin;
5
+ return typeof pin === 'string' && /^LOCK TABLE [^;$]+ IN [A-Z ]+ MODE(; LOCK TABLE [^;$]+ IN [A-Z ]+ MODE)*$/.test(pin) ? pin : undefined;
6
+ }
7
+ /* Handles whose transaction reads one snapshot (snapshotRead.ts): REPEATABLE READ from its BEGIN, so every statement
8
+ reads as of its first. Kept on the handle, as its epoch is, so a retry of the opening begins the same way. */
9
+ export const snapshotHandles = new WeakSet();
10
+ export const beginOf = (write) => (snapshotHandles.has(write) ? 'BEGIN ISOLATION LEVEL REPEATABLE READ' : 'BEGIN');
11
+ /* What a scoped transaction's BEGIN also says, in its one message: the text a date is read as, whatever the role or
12
+ database set. A check binds a key's stored text and the database reads it back (storedText.ts, keyTypes.ts); under
13
+ `DateStyle = 'SQL, YMD'` a date said as 01/02/2026 reads back as another day. Only the output style is set: the
14
+ field order, which decides how a person's own 01/02/2026 is read, stays the database's. The float and interval
15
+ text, which no key is (keyTypes.ts), is pinned as well, so a value a trigger's proof compares reads as stored. */
16
+ export const SCOPED_SESSION = '; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3';
@@ -6,6 +6,7 @@ import { ScopedRelations, snapshotRowScope } from '../../shared/rowScope.js';
6
6
  import { compileView, compileViewCount } from '../../shared/view.js';
7
7
  import { compileBreakdown, compileBreakdownCount } from '../../shared/breakdown.js';
8
8
  import { compileAggregate } from '../../shared/aggregate.js';
9
+ import { childRows } from '../../shared/anyRows.js';
9
10
  import { readExactly, summed } from '../../shared/decimals.js';
10
11
  import { RequestFault } from '../../shared/refusal.js';
11
12
  import { storedTextOf, storedTextSelect } from './storedText.js';
@@ -105,10 +106,30 @@ references = false) {
105
106
  throw new RequestFault('Unknown column in scoped read.');
106
107
  return style.quote(name);
107
108
  };
108
- const relations = new ScopedRelations(schema, style, scope);
109
+ const relations = new ScopedRelations(schema, style, scope, schema);
109
110
  const relation = relations.table(id);
111
+ /* Rows that point at this one (`any`/`no`) are read through the reader's own scope, as this table's rows are: the
112
+ child is a relation of this statement, planned here with its values bound ahead of the outer filter's, so the
113
+ EXISTS carries none. A child the reader's catalog does not hold is refused (ScopedRelations.table). */
114
+ const planned = new Map();
115
+ for (const group of filter?.groups ?? []) {
116
+ for (const c of group) {
117
+ if (c.any === undefined || planned.has(c.any))
118
+ continue;
119
+ const { child, join } = childRows(schema, id, c.any, style);
120
+ const source = c.any.filter?.groups.length ? relations.filtered(child.id, c.any.filter) : relations.table(child.id);
121
+ const alias = style.quote('_tw_any');
122
+ planned.set(c.any, `EXISTS (SELECT 1 FROM ${source} ${alias} WHERE ${join(alias, relation)})`);
123
+ }
124
+ }
110
125
  const prefix = relations.finish();
111
- const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, undefined, references, typeIn(table));
126
+ const exists = planned.size
127
+ ? (rows) => planned.get(rows) ??
128
+ (() => {
129
+ throw new RequestFault('This read cannot ask about the rows that point at it.');
130
+ })()
131
+ : undefined;
132
+ const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, exists, references, typeIn(table));
112
133
  return { table, column, relation, prefix, where, params: [...prefix.params, ...where.params] };
113
134
  };
114
135
  /* A SQLite sum that cannot be exact says so in its cell (decimals.ts); PostgreSQL's numeric always is. */
@@ -165,7 +186,7 @@ references = false) {
165
186
  const given = snapshotScopedData(items);
166
187
  if (!given.length || given.length > COUNT_EACH_MAX)
167
188
  throw new Refusal(`One statement counts 1 to ${COUNT_EACH_MAX} things.`);
168
- const relations = new ScopedRelations(schema, style, scope);
189
+ const relations = new ScopedRelations(schema, style, scope, schema);
169
190
  const planned = given.map((item) => {
170
191
  const table = tableFor(item.table);
171
192
  const column = (name) => {
@@ -187,25 +208,25 @@ references = false) {
187
208
  return countEachRows(result.rows, given.length);
188
209
  },
189
210
  async runView(view, offset = 0) {
190
- const compiled = compileView(schema, snapshotScopedData(view), style, offset, scope);
211
+ const compiled = compileView(schema, snapshotScopedData(view), style, offset, scope, schema);
191
212
  const result = await execute(compiled);
192
213
  return { ...result, columns: compiled.columns.map((column) => column.name), resolved: compiled.columns, joins: compiled.joins };
193
214
  },
194
215
  async countView(view, limit) {
195
- return counted(compileViewCount(schema, snapshotScopedData(view), style, scope, limit));
216
+ return counted(compileViewCount(schema, snapshotScopedData(view), style, scope, limit, schema));
196
217
  },
197
218
  async runBreakdown(breakdown, offset = 0) {
198
- const compiled = compileBreakdown(schema, snapshotScopedData(breakdown), style, offset, scope);
219
+ const compiled = compileBreakdown(schema, snapshotScopedData(breakdown), style, offset, scope, schema);
199
220
  const result = await exact(() => execute(compiled), breakdown.measures);
200
221
  return { ...result, columns: compiled.columns.map((column) => column.name), resolved: compiled.columns };
201
222
  },
202
223
  async countBreakdown(breakdown, limit) {
203
- return counted(compileBreakdownCount(schema, snapshotScopedData(breakdown), style, scope, limit));
224
+ return counted(compileBreakdownCount(schema, snapshotScopedData(breakdown), style, scope, limit, schema));
204
225
  },
205
226
  /* The base table read through the scope's relation, as `count` reads it, and nothing else: an aggregate names
206
227
  only its table's own columns (aggregate.ts), so no other table's relation is planned at all. */
207
228
  async aggregate(request) {
208
- const compiled = compileAggregate(schema, snapshotScopedData(request), style, 0, scope);
229
+ const compiled = compileAggregate(schema, snapshotScopedData(request), style, 0, scope, schema);
209
230
  return { rows: (await exact(() => execute(compiled), request.measures)).rows };
210
231
  },
211
232
  });
@@ -175,4 +175,6 @@ export interface ScopeOwnRows {
175
175
  /** Runs INSIDE a single queued operation. The supplied guards retain actual
176
176
  * stored scalar types, not display conversions (a blob label is not a key).
177
177
  * This capability deliberately refuses side effects it cannot bound. */
178
- export declare function createScopedTransaction(catalog: ScopeCatalog, records: WriteTransaction, reads: Pick<ScopedReads, 'query' | 'count' | 'aggregate'>, guards: Pick<ScopedReads, 'query' | 'count'>, locks?: ScopeRowLocks, bound?: ScopeBound, own?: ScopeOwnRows, triggers?: ScopedTriggers): WriteTransaction;
178
+ export declare function createScopedTransaction(catalog: ScopeCatalog, records: WriteTransaction, reads: Pick<ScopedReads, 'query' | 'count' | 'aggregate'>, guards: Pick<ScopedReads, 'query' | 'count'>, locks?: ScopeRowLocks, bound?: ScopeBound, own?: ScopeOwnRows, triggers?: ScopedTriggers,
179
+ /** The principal's rows, for the `via` conditions a write's parents are checked against (viaChecks). */
180
+ scope?: RowScope): WriteTransaction;
@@ -83,7 +83,19 @@ export function referencesStatement(catalog, fk, key, style) {
83
83
  }
84
84
  /** The tables where `scope` is exactly `bound`, and the bound admits rows at all: nothing in it is hidden there. */
85
85
  export function wholeWithin(scope, bound) {
86
- return new Set(Object.keys(bound).filter((table) => bound[table] !== false && Object.hasOwn(scope, table) && JSON.stringify(scope[table]) === JSON.stringify(bound[table])));
86
+ return new Set(Object.keys(bound).filter((table) => bound[table] !== false && Object.hasOwn(scope, table) && scopeText(scope[table]) === scopeText(bound[table])));
87
+ }
88
+ /* A rule as text, each AND group saying a condition once. A tenant request's rows already carry the tenant's predicate,
89
+ and its writer composes the tenant's predicate over them again (tenantRequestRuntime.ts, tenantWriteKindMember.ts), so
90
+ a table the member reads whole is `tenant AND tenant` beside a bound of `tenant`: the same rows, never judged so,
91
+ and no command over HTTP could delete a row its own tenant's rows reference. A condition repeated within one
92
+ conjunction narrows nothing, so dropping the repeat is exact; nothing else is rewritten, and a rule that differs in
93
+ anything else is still not whole. */
94
+ function scopeText(rule) {
95
+ if (!rule || typeof rule !== 'object' || !Array.isArray(rule.groups))
96
+ return JSON.stringify(rule);
97
+ const groups = rule.groups.map((group) => Array.isArray(group) ? [...new Map(group.map((condition) => [JSON.stringify(condition), condition])).values()] : group);
98
+ return JSON.stringify({ ...rule, groups });
87
99
  }
88
100
  /** A bound names exactly the scope's tables: it bounds that scope, never another. */
89
101
  export function sameTables(scope, bound) {
@@ -102,6 +114,7 @@ export class ScopeRefusal extends Refusal {
102
114
  const refuse = (reason) => {
103
115
  throw recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), reason);
104
116
  };
117
+ const isViaCondition = (condition) => typeof condition.via?.resource === 'string';
105
118
  const keyText = (key) => Object.entries(key)
106
119
  .map(([column, value]) => `${column} ${JSON.stringify(value)}`)
107
120
  .join(', ');
@@ -143,7 +156,12 @@ function withOwnRows(schema, scope, made) {
143
156
  continue;
144
157
  out[table] = {
145
158
  ...rule,
146
- groups: rule.groups.map((group) => group.map((condition) => {
159
+ groups: rule.groups.map((group) => group.map((given) => {
160
+ /* A relationship test needs no extension: it reads the live target relation inside the transaction, so a row
161
+ inserted a statement earlier is already there. */
162
+ if (given.via !== undefined || typeof given.column !== 'string')
163
+ return given;
164
+ const condition = given;
147
165
  const added = extra.get(condition.column);
148
166
  if (!added || condition.other !== undefined || condition.any !== undefined)
149
167
  return condition;
@@ -160,7 +178,9 @@ function withOwnRows(schema, scope, made) {
160
178
  /** Runs INSIDE a single queued operation. The supplied guards retain actual
161
179
  * stored scalar types, not display conversions (a blob label is not a key).
162
180
  * This capability deliberately refuses side effects it cannot bound. */
163
- export function createScopedTransaction(catalog, records, reads, guards, locks, bound, own, triggers) {
181
+ export function createScopedTransaction(catalog, records, reads, guards, locks, bound, own, triggers,
182
+ /** The principal's rows, for the `via` conditions a write's parents are checked against (viaChecks). */
183
+ scope) {
164
184
  /* The rows this transaction inserted inside the principal's rows, by table, and the reads that count them in
165
185
  (ScopeOwnRows). Rebuilt on each such insert; until the first, the reads are the ones resolved for the request. */
166
186
  const made = new Map();
@@ -297,6 +317,50 @@ export function createScopedTransaction(catalog, records, reads, guards, locks,
297
317
  known (what the row held is not what the update leaves), so a check of what a write gives leaves it out. */
298
318
  const generated = (table, name) => table.columns.find((column) => column.name === name)?.writable === false;
299
319
  const generatedIn = (table, fk) => fk.from.columns.some((name) => generated(table, name));
320
+ /* A row scope's `via` is checked as a reference is: the parent it names must be among the rows the principal may see
321
+ (and held to COMMIT), and a hidden parent answers as a missing one. Only where the policy is one group: of several,
322
+ a row need satisfy only one, which the read after the statement judges whole (a tree's roots name no visible
323
+ parent). A command whose rows may land outside the principal's (a bound) is judged there as well. The parent's
324
+ own scope applies, so the target's filter (`where`) and any chain behind it are part of the count. */
325
+ const synthetic = new WeakMap();
326
+ const viaChecks = (table, row, set, given = false) => {
327
+ const rule = bound ? undefined : scope?.[table.id];
328
+ if (!rule || typeof rule !== 'object' || rule.groups.length !== 1)
329
+ return [];
330
+ const checks = [];
331
+ for (const condition of rule.groups[0]) {
332
+ if (!isViaCondition(condition) || condition.via.resource === table.id)
333
+ continue;
334
+ const columns = typeof condition.column === 'string' ? [condition.column] : [...condition.column];
335
+ const keys = typeof condition.via.column === 'string' ? [condition.via.column] : [...condition.via.column];
336
+ if (set && !columns.some((column) => set.has(column)))
337
+ continue;
338
+ if (given && !columns.every((column) => Object.hasOwn(row, column) && row[column] !== undefined))
339
+ continue;
340
+ const values = columns.map((column) => asWritten(table.columns.find((candidate) => candidate.name === column)?.type, row[column]));
341
+ const parent = catalog.schema.tables.find((candidate) => candidate.id === condition.via.resource);
342
+ if (!parent) {
343
+ checks.push({
344
+ refused: `"${table.id}" is scoped through "${condition.via.resource}", which is not in this write's footprint: declare it read by the command.`,
345
+ });
346
+ break;
347
+ }
348
+ if (values.some((value) => value === null) || !values.every(comparable)) {
349
+ checks.push({
350
+ refused: `"${table.id}".${columns.join('+')} holds no value the principal's rows could include, so the row cannot be in scope.`,
351
+ });
352
+ break;
353
+ }
354
+ let fk = synthetic.get(condition);
355
+ if (!fk)
356
+ synthetic.set(condition, (fk = { name: 'via', from: { table: table.id, columns }, to: { table: parent.id, columns: keys } }));
357
+ const match = keys.map((column, index) => ({ column, op: '=', value: values[index] }));
358
+ // The target's filter narrows the count: each alternative holds the key too.
359
+ const filter = { groups: condition.via.where ? condition.via.where.map((group) => [...match, ...group]) : [match] };
360
+ checks.push({ fk, values, filter, parent, exists: true });
361
+ }
362
+ return checks;
363
+ };
300
364
  const parentChecks = (table, row, set, given = false) => {
301
365
  const checks = [];
302
366
  for (const fk of catalog.schema.foreignKeys.filter((fk) => fk.from.table === table.id &&
@@ -355,11 +419,15 @@ export function createScopedTransaction(catalog, records, reads, guards, locks,
355
419
  }
356
420
  checks.push({ fk, values, filter, parent });
357
421
  }
422
+ if (!checks.some((check) => 'refused' in check))
423
+ checks.push(...viaChecks(table, row, set, given));
358
424
  return checks;
359
425
  };
360
426
  /** Whether a check binds every value as text read by its column's type (Condition.equality): PostgreSQL's. */
361
427
  const bindsText = (check) => check.filter.groups[0].every((condition) => condition.equality);
362
428
  const unseen = (check) => `"${check.fk.from.table}".${check.fk.from.columns.join('+')} points at the "${check.fk.to.table}" row ${keyText(Object.fromEntries(check.fk.to.columns.map((column, index) => [column, check.values[index]])))}, which the principal's rows do not include (or the command does not declare "${check.fk.to.table}" read).`;
429
+ /** Whether the count of a parent's rows does not prove the reference: a foreign key names one row, a `via` any number of them. */
430
+ const missing = (check, counted) => (check.exists ? counted < 1 : counted !== 1);
363
431
  /** The checks sent at once (locks.together): each parent's lock, then its count, every answer heard. */
364
432
  const ask = (checks) => checks.map((check) => {
365
433
  if ('refused' in check)
@@ -392,7 +460,7 @@ export function createScopedTransaction(catalog, records, reads, guards, locks,
392
460
  return refuse(check.refused);
393
461
  // A parent's visibility must hold until commit, not just at this read.
394
462
  await locks?.parent(check.parent, check.filter);
395
- if ((await guards.count(check.fk.to.table, check.filter)) !== 1)
463
+ if (missing(check, await guards.count(check.fk.to.table, check.filter)))
396
464
  return refuse(unseen(check));
397
465
  proven.push(check);
398
466
  }
@@ -405,7 +473,7 @@ export function createScopedTransaction(catalog, records, reads, guards, locks,
405
473
  if ('refused' in check)
406
474
  return refuse(check.refused);
407
475
  await check.locked;
408
- if ((await check.counted) !== 1)
476
+ if (missing(check, await check.counted))
409
477
  return refuse(unseen(check));
410
478
  proven.push(check);
411
479
  }
@@ -125,7 +125,11 @@ export function createTriggerProof(acceptance, tools) {
125
125
  return String(value) === String(wanted);
126
126
  return UNKNOWN;
127
127
  };
128
- const holds = (table, condition, row) => {
128
+ const holds = (table, given, row) => {
129
+ // A relationship test reads another table's rows, which a trigger's inserted row cannot say.
130
+ if (given.via !== undefined)
131
+ return UNKNOWN;
132
+ const condition = given;
129
133
  if (condition.other !== undefined || condition.any !== undefined || condition.collation !== undefined)
130
134
  return UNKNOWN;
131
135
  if (!Object.hasOwn(row, condition.column))
@@ -65,6 +65,7 @@ export declare class SqliteAdapter implements Adapter {
65
65
  private leadingIndexColumns;
66
66
  query(request: QueryRequest): Promise<QueryResult>;
67
67
  scopeReads(input: RowScope): Promise<ScopedReads>;
68
+ private whereOf;
68
69
  private queryOn;
69
70
  /**
70
71
  * Run a compiled view.
@@ -10,6 +10,9 @@
10
10
  import { statSync } from 'node:fs';
11
11
  import { waitForLocks, assertIndependentWrite, writeToFile, prepareGuarded, transactionEpoch, storeEpoch } from './sqliteHandles.js';
12
12
  import { captureScopeCatalog, mapScopeCatalog } from '../shared/scopeCatalog.js';
13
+ import { inlineRows } from '../shared/anyRows.js';
14
+ import { asksAboutRows } from '../shared/filter.js';
15
+ import { qualifiedTable } from '../shared/sqlRelation.js';
13
16
  import { DatabaseSync } from 'node:sqlite';
14
17
  import { isPromise, isProxy } from 'node:util/types';
15
18
  import { ANSI_STYLE, buildWhere, clampLimit, clampOffset, boundStatement, looksWrappable, dedupe, refuseStacked, trimStatement, Refusal, WriteConflict, TransactionOutcomeUnknown, Serial, TransactionOperations, queueRecordLock, recordLockFilter, refuseAnalyze, countStatement, countEachStatement, countEachRows, countsTogether, orderClause, lanesStatement, withoutLaneRow, } from './adapter.js';
@@ -436,9 +439,19 @@ export class SqliteAdapter {
436
439
  };
437
440
  });
438
441
  }
442
+ /* A read's filter. Rows that point at the one read (`any`/`no`) are asked as an EXISTS over the child's own table, read
443
+ as the parent is: no scope sits between, so the caller's declaration of what it may read is the only bound
444
+ (commandDb.ts). The catalog is read only when the filter asks, and a filter that asks of a catalog this handle
445
+ cannot read is refused, as one nothing resolves is. */
446
+ async whereOf(id, relation, filter) {
447
+ if (!asksAboutRows(filter))
448
+ return buildWhere(filter, ANSI_STYLE);
449
+ const schema = await this.schema().catch(() => undefined);
450
+ const inline = schema && inlineRows(schema, id, ANSI_STYLE.quote(relation), ANSI_STYLE, (child) => qualifiedTable(schema, child.id, ANSI_STYLE));
451
+ return buildWhere(filter, ANSI_STYLE, 1, undefined, undefined, undefined, undefined, false, undefined, false, inline);
452
+ }
439
453
  async queryOn(request, db, read = false) {
440
454
  const table = read ? this.readTable(request.table) : this.assertTable(request.table, db);
441
- const where = buildWhere(request.filter, ANSI_STYLE);
442
455
  const cols = request.columns?.length ? request.columns.map((c) => ANSI_STYLE.quote(c)).join(', ') : '*';
443
456
  /* Every read is bounded. There is no code path that reaches the database
444
457
  without a LIMIT, including one that forgot to ask for one. Limit and
@@ -446,6 +459,9 @@ export class SqliteAdapter {
446
459
  its operation input, and the schema wait below must not outlive it. */
447
460
  const limit = clampLimit(request.limit);
448
461
  const offset = clampOffset(request.offset);
462
+ const where = asksAboutRows(request.filter)
463
+ ? await this.whereOf(request.table, table, request.filter)
464
+ : buildWhere(request.filter, ANSI_STYLE);
449
465
  /* A sort by declared vocabulary needs the catalog, but an ordinary read must
450
466
  not depend on the whole catalog introspecting on this handle (a view over
451
467
  a function only the writer registered cannot be prepared here). Without
@@ -685,7 +701,7 @@ export class SqliteAdapter {
685
701
  }
686
702
  async countOn(table, filter, db, limit, read = false) {
687
703
  const name = read ? this.readTable(table) : this.assertTable(table, db);
688
- const where = buildWhere(filter, ANSI_STYLE);
704
+ const where = asksAboutRows(filter) ? await this.whereOf(table, name, filter) : buildWhere(filter, ANSI_STYLE);
689
705
  const text = countStatement(`${ANSI_STYLE.quote(name)}${where.text}`, limit);
690
706
  const [row] = await this.readRows(text, where.params, true, db);
691
707
  return Number(row?.n ?? 0);
@@ -1340,7 +1356,7 @@ export class SqliteAdapter {
1340
1356
  // A public intake writes exactly its fixed rows; only a principal's own transaction counts its new parents in.
1341
1357
  journal?.fixedRecords ? undefined : { scope, reads: (within, guard) => scopedReads(guard, within) },
1342
1358
  // Triggers the App names, on a principal's own transaction: their effects proven per write (triggerProof.ts).
1343
- accepted);
1359
+ accepted, scope);
1344
1360
  /* Each row the transaction's own statements write, told to the session after the statement and after the
1345
1361
  proof has said what its triggers reached: a trigger the proof did not reach that writes it again later is
1346
1362
  a change SQLite still calls direct. */
@@ -137,6 +137,7 @@ interface ShellTitle {
137
137
  interface HeadBranding {
138
138
  readonly value: {
139
139
  readonly theme: unknown;
140
+ readonly icon?: unknown;
140
141
  };
141
142
  readonly private: boolean;
142
143
  }
@@ -139,7 +139,7 @@ const writesHead = (head) => Boolean(head?.title ||
139
139
  head?.pwa);
140
140
  /** Generate only registered token names and validated theme values. Row text
141
141
  * exists only in escaped JSON; it can never close a style/script element. */
142
- function brandingHead(html, presentation) {
142
+ function brandingHead(html, presentation, base) {
143
143
  const theme = parseThemes([presentation.value.theme], 'Request branding')[0];
144
144
  const declarations = (mode) => {
145
145
  const pairs = [];
@@ -178,7 +178,27 @@ function brandingHead(html, presentation) {
178
178
  : /<head>/i.test(out)
179
179
  ? out.replace(/<head>/i, (match) => `${match}${block}`)
180
180
  : `${block}${out}`;
181
- return out;
181
+ return tenantIcon(out, presentation.value.icon, base);
182
+ }
183
+ /** An address a tenant's tab icon may have: the App's own branding-image route, by content hash (server tenantBranding.ts). */
184
+ const BRAND_ICON_ADDRESS = /^\/api\/branding\/logo\/[0-9a-f]{64}$/;
185
+ /**
186
+ * A tenant's own tab icon, in the page's `<link rel="icon">` from the first byte, so the tab never shows another icon first.
187
+ * It replaces the shell's default icon; `data-brand-icon` tells the client not to draw its own over it (appBrand.tsx).
188
+ * Anything but the App's own image address is ignored: the App's icon, then the platform's, stands.
189
+ */
190
+ function tenantIcon(html, icon, base) {
191
+ if (typeof icon !== 'string' || !BRAND_ICON_ADDRESS.test(icon))
192
+ return html;
193
+ const link = `<link rel="icon" data-brand-icon href="${base ?? ''}${icon}" />`;
194
+ let replaced = false;
195
+ const out = html.replace(/<link\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => {
196
+ if (replaced || !/\brel=["']icon["']/i.test(tag))
197
+ return tag;
198
+ replaced = true;
199
+ return link;
200
+ });
201
+ return replaced ? out : out.replace(/<\/head>/i, `${link}</head>`);
182
202
  }
183
203
  /**
184
204
  * The shell with a page's own head written in. Under a base path the page's
@@ -192,7 +212,7 @@ export function withHead(html, head) {
192
212
  return html;
193
213
  let out = html;
194
214
  if (head?.branding)
195
- out = brandingHead(out, head.branding);
215
+ out = brandingHead(out, head.branding, head.mount?.base);
196
216
  const base = head.mount?.base;
197
217
  if (base) {
198
218
  out = out.replace(/(\s(?:src|href)=")\/(?=assets\/)/g, (_, attribute) => `${attribute}${base}/`);
@@ -398,10 +398,15 @@ export function resourceChecks(full, access) {
398
398
  const filterFor = (table, input, server = false) => {
399
399
  assertRead(table);
400
400
  const filter = requestData(input);
401
+ /* An `any`/`no` condition names the rows that point here, not a column of this table: its child, reference and
402
+ conditions are held to the reader as a view's are (assertAnyRows), and its own `column` is never read. */
401
403
  if (filter)
402
404
  for (const group of filter.groups)
403
405
  for (const condition of group)
404
- assertFields(table, [condition.column], 'read', server);
406
+ if (condition.any)
407
+ assertAnyRows({ groups: [[{ ...condition, path: condition.column }]] });
408
+ else
409
+ assertFields(table, [condition.column], 'read', server);
405
410
  return filter;
406
411
  };
407
412
  const queryFor = (input) => {
@@ -139,6 +139,11 @@ export interface ResolvedSource {
139
139
  readonly publicDefinition: <T extends {
140
140
  connection?: string;
141
141
  }>(definition: T) => T;
142
+ /** The App's own reader of its declared resources, before any grant or row narrows it: for the server's own questions about rows this reader may not see (a draft's owner), never for what it is sent. */
143
+ readonly appReader?: {
144
+ readonly schema: DatabaseSchema;
145
+ readonly reader: Pick<Adapter, 'query'>;
146
+ };
142
147
  /** Who `me` is for this request, through the reader it is given (server/app/appMe.ts). */
143
148
  readonly person?: (reader: Adapter) => Promise<QueryPerson>;
144
149
  /** This reader's zone, where `ui.timezone` reads one (readerZone.ts); read through `appZone`. */
@@ -45,5 +45,5 @@ export declare const FORBIDDEN_ANSWER_NAMES: ReadonlySet<string>;
45
45
  * The statement an aggregate compiles to. A path the compiler refuses (a period cut of a column that is no date) is
46
46
  * the request's fault as written, said as one (RequestFault), never as a read that may succeed on a retry.
47
47
  */
48
- export declare function compileAggregate(schema: DatabaseSchema, request: AggregateRequest, style: SqlStyle, offset?: number | unknown, scope?: RowScope): ReturnType<typeof compileBreakdown>;
48
+ export declare function compileAggregate(schema: DatabaseSchema, request: AggregateRequest, style: SqlStyle, offset?: number | unknown, scope?: RowScope, policy?: DatabaseSchema): ReturnType<typeof compileBreakdown>;
49
49
  export {};
@@ -94,10 +94,10 @@ function aggregateBreakdown(schema, request) {
94
94
  * The statement an aggregate compiles to. A path the compiler refuses (a period cut of a column that is no date) is
95
95
  * the request's fault as written, said as one (RequestFault), never as a read that may succeed on a retry.
96
96
  */
97
- export function compileAggregate(schema, request, style, offset = 0, scope) {
97
+ export function compileAggregate(schema, request, style, offset = 0, scope, policy = schema) {
98
98
  const def = aggregateBreakdown(schema, request);
99
99
  try {
100
- return compileBreakdown(schema, def, style, offset, scope);
100
+ return compileBreakdown(schema, def, style, offset, scope, policy);
101
101
  }
102
102
  catch (error) {
103
103
  if (error instanceof PathError)