@mistriwork/engine 1.0.0-rc.11 → 1.0.0-rc.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/adapters/postgres.js +28 -3
  2. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +22 -1
  3. package/dist/adapters/scoped/postgresScopeCatalog.js +66 -2
  4. package/dist/adapters/scoped/scopedReads.js +6 -4
  5. package/dist/adapters/scoped/scopedTransaction.d.ts +21 -2
  6. package/dist/adapters/scoped/scopedTransaction.js +37 -7
  7. package/dist/adapters/sqlite.js +1 -1
  8. package/dist/server/cli/bin.js +2 -2
  9. package/dist/server/cli/startup.js +2 -2
  10. package/dist/server/cli/usage.d.ts +2 -2
  11. package/dist/server/cli/usage.js +2 -2
  12. package/dist/server/demo.js +2 -2
  13. package/dist/server/http/baselineHeaders.d.ts +2 -0
  14. package/dist/server/http/baselineHeaders.js +2 -0
  15. package/dist/server/http/crawlerText.d.ts +4 -1
  16. package/dist/server/http/crawlerText.js +4 -1
  17. package/dist/server/http/httpOperationRoutes.d.ts +4 -1
  18. package/dist/server/http/httpOperationRoutes.js +4 -1
  19. package/dist/server/http/reply.d.ts +1 -0
  20. package/dist/server/http/reply.js +1 -0
  21. package/dist/server/http/router.d.ts +11 -22
  22. package/dist/server/http/router.js +0 -15
  23. package/dist/server/http/trust.d.ts +1 -0
  24. package/dist/server/http/trust.js +1 -0
  25. package/dist/server/product.d.ts +1 -1
  26. package/dist/server/recordWriteOperations.d.ts +2 -1
  27. package/dist/server/recordWriteOperations.js +2 -1
  28. package/dist/server/resourceReadHttp.d.ts +1 -0
  29. package/dist/server/resourceReadHttp.js +1 -0
  30. package/dist/shared/addressParams.d.ts +2 -0
  31. package/dist/shared/addressParams.js +2 -0
  32. package/dist/shared/breakdown.js +2 -2
  33. package/dist/shared/filter.d.ts +18 -1
  34. package/dist/shared/filter.js +62 -8
  35. package/dist/shared/listPresentations.d.ts +2 -0
  36. package/dist/shared/listQuestion.d.ts +3 -1
  37. package/dist/shared/moneyEntry.d.ts +6 -3
  38. package/dist/shared/moneyEntry.js +14 -7
  39. package/dist/shared/recordview.d.ts +1 -1
  40. package/dist/shared/rowScope.js +12 -4
  41. package/dist/shared/schematext.d.ts +22 -6
  42. package/dist/shared/schematext.js +18 -2
  43. package/dist/shared/servedApp.d.ts +8 -2
  44. package/dist/shared/view.js +4 -4
  45. package/dist/shared/viewLabels.d.ts +1 -0
  46. package/dist/shared/viewLabels.js +8 -2
  47. package/dist/shared/viewPaths.d.ts +3 -0
  48. package/dist/shared/viewPaths.js +8 -0
  49. package/package.json +4 -2
  50. package/schema/model.d.ts +1 -1
  51. package/dist/shared/order.d.ts +0 -59
  52. package/dist/shared/order.js +0 -133
@@ -13,7 +13,7 @@ import { compileAggregate } from '../shared/aggregate.js';
13
13
  import { coerceForColumn } from '../shared/schema.js';
14
14
  import { buildUpdateGuard } from './scoped/updateGuard.js';
15
15
  import { createScopedTransaction, foreignKeyRefusal, isForeignKeyViolation, referencesStatement, wholeWithin, } from './scoped/scopedTransaction.js';
16
- import { attestPostgresTriggers, effectCatalogFacts, readPostgresScopeCatalog, } from './scoped/postgresScopeCatalog.js';
16
+ import { attestPostgresTriggers, effectCatalogFacts, hierarchyRecheck, joinedHierarchy, readPostgresScopeCatalog, } from './scoped/postgresScopeCatalog.js';
17
17
  import { postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, readPostgresTableCode, } from './scoped/postgresTriggers.js';
18
18
  import { captureScopeCatalog, mapScopeCatalog } from '../shared/scopeCatalog.js';
19
19
  import { createPinnedPostgresReadOwner } from './postgresReadCatalog.js';
@@ -23,7 +23,7 @@ import { lendStoreHost, } from './storeHost.js';
23
23
  import { compileView, compileViewCount } from '../shared/view.js';
24
24
  import { compileBreakdown, compileBreakdownCount } from '../shared/breakdown.js';
25
25
  import { PgConnectionManager, sharedPgConnections } from './postgresPool.js';
26
- import { aheadReport, behindWrite, generationOf, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
26
+ import { aheadReport, beforeCommit, behindWrite, generationOf, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
27
27
  import { snapshotRead, withoutSnapshotRead } from './snapshotRead.js';
28
28
  import { withoutWriteAhead, writeAhead } from './writeAhead.js';
29
29
  import { KeyRows } from './scoped/keyRows.js';
@@ -1605,6 +1605,8 @@ export class PostgresAdapter {
1605
1605
  });
1606
1606
  // The tables whose validation-only triggers a write of this transaction fired: their proof is read again before COMMIT.
1607
1607
  const relied = new Set();
1608
+ // The tables this transaction's writes targeted: whether one joined a hierarchy is read again with the COMMIT.
1609
+ const written = new Set();
1608
1610
  attest = () => attestPostgresTriggers(write, catalog, relied);
1609
1611
  let records = createScopedTransaction(catalog, {
1610
1612
  query: (r) => this.queryOn(r, write),
@@ -1621,11 +1623,12 @@ export class PostgresAdapter {
1621
1623
  },
1622
1624
  together: sendsAhead(write),
1623
1625
  relied: (table) => void relied.add(table.id),
1626
+ written: (table) => void written.add(table.id),
1624
1627
  }, bound && {
1625
1628
  reads: scopedReads(true, bound),
1626
1629
  whole: wholeWithin(scope, bound),
1627
1630
  references: async (fk, key) => {
1628
- const statement = referencesStatement(catalog.schema, fk, key, POSTGRES_STYLE);
1631
+ const statement = referencesStatement(catalog, fk, key, POSTGRES_STYLE);
1629
1632
  return Number((await write.query(statement.text, statement.params)).rows[0]?.n ?? 0);
1630
1633
  },
1631
1634
  },
@@ -1666,11 +1669,33 @@ export class PostgresAdapter {
1666
1669
  if (verify)
1667
1670
  await verify(write, catalog, described);
1668
1671
  await attestPostgresTriggers(write, catalog, relied);
1672
+ /* A target's triggers may write any table the scope can write (triggerEffects.ts): where one ran, each of
1673
+ those is read again too. */
1674
+ const reached = [...written].some((id) => catalog.triggered?.has(id))
1675
+ ? [...written, ...catalog.writable, ...(catalog.triggered?.keys() ?? [])]
1676
+ : written;
1677
+ /* And what they reference, for a parent that gained an inheritance child (ScopeCatalog.inheritanceParents):
1678
+ one that was a parent when the catalog was read was judged by the parent checks, which refused a
1679
+ reference to it. A table that became one is refused whether or not a reference to it was checked. */
1680
+ const wrote = new Set(reached);
1681
+ const recheck = hierarchyRecheck(reached, catalog.schema.foreignKeys
1682
+ .filter((fk) => wrote.has(fk.from.table) && !catalog.inheritanceParents?.has(fk.to.table))
1683
+ .map((fk) => fk.to.table));
1684
+ if (recheck && !beforeCommit(write, [recheck]))
1685
+ await write.query(recheck.text, recheck.values).catch((error) => {
1686
+ throw joinedHierarchy(error) ?? error;
1687
+ });
1669
1688
  commitAttempted = true;
1670
1689
  try {
1671
1690
  await write.query('COMMIT');
1672
1691
  }
1673
1692
  catch (error) {
1693
+ // The recheck sent with the COMMIT found a hierarchy: the server answered the COMMIT as a ROLLBACK.
1694
+ const joined = error instanceof RolledBackAtCommit ? joinedHierarchy(error.cause) : undefined;
1695
+ if (joined) {
1696
+ commitAttempted = false;
1697
+ throw joined;
1698
+ }
1674
1699
  /* A deferred foreign key the COMMIT found broken: the server answered, so nothing committed, and the
1675
1700
  refusal is a hidden parent's (foreignKeyRefusal). */
1676
1701
  if (!isForeignKeyViolation(error))
@@ -1,7 +1,7 @@
1
1
  import type { DatabaseSchema } from '../../shared/schema.js';
2
2
  import type { RowScope } from '../../shared/rowScope.js';
3
3
  import type { PgQuery } from '../postgresPool.js';
4
- import { type ScopeCatalog } from './scopedTransaction.js';
4
+ import { ScopeRefusal, type ScopeCatalog } from './scopedTransaction.js';
5
5
  import type { TriggerKeyFacts } from './triggerEffects.js';
6
6
  export interface PostgresScopeCatalog extends ScopeCatalog {
7
7
  /** Ordinary tables the writer role may UPDATE, and so lock rows in. A
@@ -22,6 +22,27 @@ export interface PostgresScopeCatalog extends ScopeCatalog {
22
22
  * could have used: a changed one refuses the transaction.
23
23
  */
24
24
  export declare function attestPostgresTriggers(client: PgQuery, catalog: PostgresScopeCatalog, tables: ReadonlySet<string>): Promise<void>;
25
+ /**
26
+ * The tables a scoped write wrote, read again for a hierarchy just before COMMIT, as a statement that fails where one
27
+ * is in one: sent with the COMMIT (beforeCommit), its failure answers the COMMIT as a ROLLBACK, so it costs no round
28
+ * trip. The pin's ROW EXCLUSIVE holds a target against becoming a partition or a child (ATTACH PARTITION and ALTER
29
+ * TABLE … INHERIT take ACCESS EXCLUSIVE on it), but not against becoming a parent: ALTER TABLE c INHERIT t and CREATE
30
+ * TABLE c () INHERITS (t) take SHARE UPDATE EXCLUSIVE on t, and every mode that conflicts with that conflicts with an
31
+ * ordinary write's ROW EXCLUSIVE or with itself, which would line up every scoped write of the table behind one
32
+ * another. Under READ COMMITTED a statement after the transaction's last write sees every inheritance committed before
33
+ * that write was planned, and one committed after it no write of the transaction expanded into: so a target that
34
+ * passed the catalog's check (ScopeCatalog.hierarchy) and gained a child while the write ran refuses the transaction.
35
+ * The tables those reference are read in the same statement for the same reason: one that gained an inheritance child
36
+ * while the write ran (CREATE TABLE … INHERITS takes the same SHARE UPDATE EXCLUSIVE) may have let a parent check
37
+ * find the child's visible row where the foreign key, which reads the parent alone, found a hidden one
38
+ * (ScopeCatalog.inheritanceParents). Undefined where nothing was written.
39
+ */
40
+ export declare function hierarchyRecheck(ids: Iterable<string>, referenced?: Iterable<string>): {
41
+ text: string;
42
+ values: unknown[];
43
+ } | undefined;
44
+ /** The refusal a hierarchyRecheck failure says, or undefined for any other failure. */
45
+ export declare function joinedHierarchy(error: unknown): ScopeRefusal | undefined;
25
46
  /**
26
47
  * For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
27
48
  * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
@@ -27,7 +27,8 @@
27
27
  import { POSTGRES_STYLE, Refusal } from '../adapter.js';
28
28
  import { captureScopeCatalog } from '../../shared/scopeCatalog.js';
29
29
  import { writtenType } from '../postgresCatalog.js';
30
- import { referenceKey, triggerNames } from './scopedTransaction.js';
30
+ import { referenceKey, ScopeRefusal, triggerNames } from './scopedTransaction.js';
31
+ import { recordRefusalCause } from '../../shared/refusal.js';
31
32
  import { baseType, CATALOG_OPERATORS, defaultBtreeClass, postgresTreeTriggerNames, postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, postgresTriggerVersions, readPostgresTableCode, } from './postgresTriggers.js';
32
33
  import { keyTypeRefusal, postgresKeyType } from './keyTypes.js';
33
34
  const { EQ, GT, LT, NE, PLUS } = CATALOG_OPERATORS;
@@ -60,6 +61,7 @@ async function facts(client, targets) {
60
61
  pg_catalog.has_table_privilege(c.oid, 'UPDATE') AS updatable,
61
62
  c.relkind ${EQ} 'p' OR EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid ${EQ} c.oid OR i.inhparent ${EQ} c.oid)
62
63
  AS hierarchy,
64
+ c.relkind ${EQ} 'r' AND EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhparent ${EQ} c.oid) AS inherited,
63
65
  unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type
64
66
  FROM ${WANTED}
65
67
  -- A key column whose type is not on the list (keyTypes.ts), its domains unwrapped: no scoped write targets the table.
@@ -74,7 +76,7 @@ async function facts(client, targets) {
74
76
  if (typeof row.schema !== 'string' ||
75
77
  typeof row.name !== 'string' ||
76
78
  typeof row.kind !== 'string' ||
77
- [row.rls, row.triggers, row.rules, row.policies, row.updatable, row.hierarchy].some((value) => typeof value !== 'boolean') ||
79
+ [row.rls, row.triggers, row.rules, row.policies, row.updatable, row.hierarchy, row.inherited].some((value) => typeof value !== 'boolean') ||
78
80
  !Array.isArray(row.trigger_names) ||
79
81
  row.trigger_names.some((name) => typeof name !== 'string') ||
80
82
  (row.unkeyed_column !== null && typeof row.unkeyed_column !== 'string') ||
@@ -140,6 +142,64 @@ export async function attestPostgresTriggers(client, catalog, tables) {
140
142
  return refuse();
141
143
  }
142
144
  }
145
+ /* The value a hierarchy found again is said in (hierarchyRecheck), between these, so its failure names the table. */
146
+ const JOINED = 'mistri: a scoped write target is in a hierarchy: ';
147
+ const INHERITED = 'mistri: a scoped write references an inheritance parent: ';
148
+ const JOINED_END = ' (end)';
149
+ /**
150
+ * The tables a scoped write wrote, read again for a hierarchy just before COMMIT, as a statement that fails where one
151
+ * is in one: sent with the COMMIT (beforeCommit), its failure answers the COMMIT as a ROLLBACK, so it costs no round
152
+ * trip. The pin's ROW EXCLUSIVE holds a target against becoming a partition or a child (ATTACH PARTITION and ALTER
153
+ * TABLE … INHERIT take ACCESS EXCLUSIVE on it), but not against becoming a parent: ALTER TABLE c INHERIT t and CREATE
154
+ * TABLE c () INHERITS (t) take SHARE UPDATE EXCLUSIVE on t, and every mode that conflicts with that conflicts with an
155
+ * ordinary write's ROW EXCLUSIVE or with itself, which would line up every scoped write of the table behind one
156
+ * another. Under READ COMMITTED a statement after the transaction's last write sees every inheritance committed before
157
+ * that write was planned, and one committed after it no write of the transaction expanded into: so a target that
158
+ * passed the catalog's check (ScopeCatalog.hierarchy) and gained a child while the write ran refuses the transaction.
159
+ * The tables those reference are read in the same statement for the same reason: one that gained an inheritance child
160
+ * while the write ran (CREATE TABLE … INHERITS takes the same SHARE UPDATE EXCLUSIVE) may have let a parent check
161
+ * find the child's visible row where the foreign key, which reads the parent alone, found a hidden one
162
+ * (ScopeCatalog.inheritanceParents). Undefined where nothing was written.
163
+ */
164
+ export function hierarchyRecheck(ids, referenced = []) {
165
+ const at = [...new Set(ids)].map(located);
166
+ if (!at.length)
167
+ return undefined;
168
+ const parents = [...new Set(referenced)].map(located);
169
+ const said = (prefix) => `('${prefix}' ${CONCAT} n.nspname::pg_catalog.text ${CONCAT} '.' ${CONCAT} c.relname::pg_catalog.text ${CONCAT} '${JOINED_END}')::pg_catalog.int4`;
170
+ return {
171
+ text: `SELECT ${said(JOINED)}
172
+ FROM ${WANTED}
173
+ WHERE c.relkind ${EQ} 'p' OR EXISTS (SELECT FROM pg_catalog.pg_inherits i WHERE i.inhrelid ${EQ} c.oid OR i.inhparent ${EQ} c.oid)${parents.length
174
+ ? `
175
+ UNION ALL
176
+ SELECT ${said(INHERITED)}
177
+ FROM ${WANTED.replace('$1::', '$3::').replace('$2::', '$4::')}
178
+ WHERE c.relkind ${EQ} 'r' AND EXISTS (SELECT FROM pg_catalog.pg_inherits i WHERE i.inhparent ${EQ} c.oid)`
179
+ : ''}`,
180
+ values: [
181
+ at.map((table) => table.schema),
182
+ at.map((table) => table.name),
183
+ ...(parents.length ? [parents.map((table) => table.schema), parents.map((table) => table.name)] : []),
184
+ ],
185
+ };
186
+ }
187
+ /** The refusal a hierarchyRecheck failure says, or undefined for any other failure. */
188
+ export function joinedHierarchy(error) {
189
+ const { code, message } = (error ?? {});
190
+ if (code !== '22P02' || typeof message !== 'string')
191
+ return undefined;
192
+ const reference = message.includes(INHERITED);
193
+ const prefix = reference ? INHERITED : JOINED;
194
+ const start = message.indexOf(prefix);
195
+ const end = message.indexOf(JOINED_END, start);
196
+ if (start === -1 || end === -1)
197
+ return undefined;
198
+ const table = message.slice(start + prefix.length, end);
199
+ return recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), reference
200
+ ? `"${table}" became an inheritance parent while the write ran, and a reference to it is not checked under a row policy: the foreign key reads its own rows, a parent check its children's too.`
201
+ : `"${table}" became part of a partition or inheritance hierarchy while the write ran, which writes under a row policy do not support yet.`);
202
+ }
143
203
  /** The relations of `$1` (schemas) and `$2` (names), as `c` and `n`: the proof's own catalog read, its operators named in pg_catalog (postgresTriggers.ts). */
144
204
  const WANTED = `pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid ${EQ} c.relnamespace
145
205
  JOIN ROWS FROM (pg_catalog.unnest($1::pg_catalog.text[]), pg_catalog.unnest($2::pg_catalog.text[])) AS wanted(schema, name)
@@ -379,6 +439,7 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
379
439
  const blockedBy = new Map();
380
440
  const unkeyed = new Map();
381
441
  const hierarchy = new Set();
442
+ const inheritanceParents = new Set();
382
443
  const locks = new Set();
383
444
  const withTriggers = [];
384
445
  for (const table of schema.tables) {
@@ -392,6 +453,8 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
392
453
  // Never a target, but still lockable: a reference to a partitioned table holds its parent row through it.
393
454
  if (fact.hierarchy)
394
455
  hierarchy.add(table.id);
456
+ if (fact.inherited)
457
+ inheritanceParents.add(table.id);
395
458
  if (!lockable(fact))
396
459
  continue;
397
460
  locks.add(table.id);
@@ -442,6 +505,7 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
442
505
  ...(blockedBy.size ? { blockedBy } : {}),
443
506
  ...(unkeyed.size ? { unkeyed } : {}),
444
507
  ...(hierarchy.size ? { hierarchy } : {}),
508
+ ...(inheritanceParents.size ? { inheritanceParents } : {}),
445
509
  ...(triggered.size ? { triggered, triggerVersions } : {}),
446
510
  lockable: locks,
447
511
  pinned: relations,
@@ -96,6 +96,8 @@ references = false) {
96
96
  throw new Refusal('Unknown resource in scoped read.');
97
97
  return table;
98
98
  };
99
+ /* Each column's type, so a comparison names the database's own operator for it (SqlStyle.builtin). */
100
+ const typeIn = (table) => (name) => table.columns.find((column) => column.name === name)?.type;
99
101
  const from = (id, filter) => {
100
102
  const table = tableFor(id);
101
103
  const column = (name) => {
@@ -106,7 +108,7 @@ references = false) {
106
108
  const relations = new ScopedRelations(schema, style, scope);
107
109
  const relation = relations.table(id);
108
110
  const prefix = relations.finish();
109
- const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, undefined, references);
111
+ const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, undefined, references, typeIn(table));
110
112
  return { table, column, relation, prefix, where, params: [...prefix.params, ...where.params] };
111
113
  };
112
114
  /* A SQLite sum that cannot be exact says so in its cell (decimals.ts); PostgreSQL's numeric always is. */
@@ -153,12 +155,12 @@ references = false) {
153
155
  throw new RequestFault('Unknown column in scoped read.');
154
156
  return style.quote(name);
155
157
  };
156
- return { relation: relations.table(item.table), column, filter: item.filter };
158
+ return { relation: relations.table(item.table), column, filter: item.filter, types: typeIn(table) };
157
159
  });
158
160
  const prefix = relations.finish();
159
161
  const params = [...prefix.params];
160
- const branches = planned.map(({ relation, column, filter }, i) => {
161
- const where = buildWhere(filter, style, params.length + 1, column);
162
+ const branches = planned.map(({ relation, column, filter, types }, i) => {
163
+ const where = buildWhere(filter, style, params.length + 1, column, undefined, undefined, undefined, false, types);
162
164
  params.push(...where.params);
163
165
  const counted = countStatement(`${relation}${where.text}`, limit);
164
166
  return counted.replace(/^SELECT COUNT\(\*\) AS n/, `SELECT ${i} AS i, COUNT(*) AS n`);
@@ -33,6 +33,13 @@ export interface ScopeCatalog {
33
33
  * reference to a partitioned table from an ordinary one is still checked, through the partitioned table.
34
34
  */
35
35
  hierarchy?: ReadonlySet<string>;
36
+ /**
37
+ * PostgreSQL: ordinary tables with inheritance children. A reference to one is refused: its foreign key checks the
38
+ * parent's own rows (`ONLY`), while a parent check reads the parent with its children, so a child's visible row
39
+ * could pass for a hidden one of the parent's under the same key. A partitioned table is not here: its key and its
40
+ * check both read every partition.
41
+ */
42
+ inheritanceParents?: ReadonlySet<string>;
36
43
  }
37
44
  /** One foreign key's comparison, column by column in its order (ScopeCatalog.references); or the reason it has none. */
38
45
  export type ReferenceComparison = {
@@ -68,6 +75,12 @@ export declare const loadTriggerEffects: () => Promise<typeof import("./triggerE
68
75
  interface ScopeRowLocks {
69
76
  target(table: TableMeta, filter: Filter): Promise<void>;
70
77
  parent(table: TableMeta, filter: Filter): Promise<void>;
78
+ /**
79
+ * Told of each table a write of this transaction targets, once it is judged a target, before the write is sent:
80
+ * where a table can join a hierarchy under the lock the write's pin holds (PostgreSQL, ALTER TABLE … INHERIT), what
81
+ * it wrote is read again before COMMIT (postgresScopeCatalog.ts hierarchyRecheck).
82
+ */
83
+ written?(table: TableMeta): void;
71
84
  /**
72
85
  * Run `ride` the moment the update of `table` is sent, so the read that
73
86
  * proves the row still in scope leaves behind it in the same round trip
@@ -127,9 +140,15 @@ export interface ScopeBound {
127
140
  * does, and missed such a reference, which the delete's cascade then reached.
128
141
  * Here each parent column is the left side of a join, where both engines take
129
142
  * its affinity and collation as the foreign key does; where two collations
130
- * conflict, PostgreSQL refuses the count, and the delete with it.
143
+ * conflict, PostgreSQL refuses the count, and the delete with it. On
144
+ * PostgreSQL the join compares by the constraint's own operator
145
+ * (`conpfeqop`), each side cast as ri_triggers.c casts it: the comparison the
146
+ * catalog read for the parent check (ScopeCatalog.references,
147
+ * Condition.equality), so a `char(3)` key reaches the `text` reference 'ab '
148
+ * the cascade reaches, and no `=` on the search_path decides what is counted.
149
+ * A key whose comparison the catalog refused refuses the count.
131
150
  */
132
- export declare function referencesStatement(schema: DatabaseSchema, fk: ForeignKey, key: Filter, style: SqlStyle): SqlFragment;
151
+ export declare function referencesStatement(catalog: Pick<ScopeCatalog, 'schema' | 'references'>, fk: ForeignKey, key: Filter, style: SqlStyle): SqlFragment;
133
152
  /** The tables where `scope` is exactly `bound`, and the bound admits rows at all: nothing in it is hidden there. */
134
153
  export declare function wholeWithin(scope: Readonly<Record<string, unknown>>, bound: Readonly<Record<string, unknown>>): ReadonlySet<string>;
135
154
  /** A bound names exactly the scope's tables: it bounds that scope, never another. */
@@ -40,21 +40,44 @@ export const loadTriggerEffects = () => import('./triggerEffects.js');
40
40
  * does, and missed such a reference, which the delete's cascade then reached.
41
41
  * Here each parent column is the left side of a join, where both engines take
42
42
  * its affinity and collation as the foreign key does; where two collations
43
- * conflict, PostgreSQL refuses the count, and the delete with it.
43
+ * conflict, PostgreSQL refuses the count, and the delete with it. On
44
+ * PostgreSQL the join compares by the constraint's own operator
45
+ * (`conpfeqop`), each side cast as ri_triggers.c casts it: the comparison the
46
+ * catalog read for the parent check (ScopeCatalog.references,
47
+ * Condition.equality), so a `char(3)` key reaches the `text` reference 'ab '
48
+ * the cascade reaches, and no `=` on the search_path decides what is counted.
49
+ * A key whose comparison the catalog refused refuses the count.
44
50
  */
45
- export function referencesStatement(schema, fk, key, style) {
46
- const relation = (id) => {
51
+ export function referencesStatement(catalog, fk, key, style) {
52
+ const { schema } = catalog;
53
+ const tableOf = (id) => {
47
54
  const table = schema.tables.find((table) => table.id === id);
48
55
  if (!table)
49
56
  throw new Refusal('This operation is not available in the current row scope.');
50
- return `${style.quote(table.schema)}.${style.quote(table.name)}`;
57
+ return table;
51
58
  };
52
- const on = fk.to.columns.map((column, index) => `p.${style.quote(column)} = c.${style.quote(fk.from.columns[index])}`).join(' AND ');
53
- const where = buildWhere(key, style, 1, (name) => `p.${style.quote(name)}`);
59
+ const relation = (table) => `${style.quote(table.schema)}.${style.quote(table.name)}`;
60
+ const compared = catalog.references?.get(referenceKey(fk));
61
+ if (catalog.references && !compared)
62
+ refuse(`"${fk.from.table}" has a foreign key whose comparison was not read with the catalog.`);
63
+ if (compared && 'refused' in compared)
64
+ refuse(compared.refused);
65
+ const columns = compared && 'columns' in compared ? compared.columns : undefined;
66
+ const parent = tableOf(fk.to.table);
67
+ const on = buildWhere({
68
+ groups: [
69
+ fk.to.columns.map((column, index) => {
70
+ const equality = columns?.[index]?.equality;
71
+ return { column, op: '=', other: fk.from.columns[index], ...(equality ? { equality } : {}) };
72
+ }),
73
+ ],
74
+ }, style, 1, (name) => `p.${style.quote(name)}`, (name) => `c.${style.quote(name)}`, undefined, undefined, true);
75
+ const typeOf = (name) => parent.columns.find((column) => column.name === name)?.type;
76
+ const where = buildWhere(key, style, 1, (name) => `p.${style.quote(name)}`, undefined, undefined, undefined, false, typeOf);
54
77
  if (!where.text)
55
78
  throw new Refusal('This operation is not available in the current row scope.');
56
79
  return {
57
- text: `SELECT COUNT(*) AS n FROM ${relation(fk.from.table)} AS c JOIN ${relation(fk.to.table)} AS p ON ${on}${where.text}`,
80
+ text: `SELECT COUNT(*) AS n FROM ${relation(tableOf(fk.from.table))} AS c JOIN ${relation(parent)} AS p ON ${on.text.replace(/^ WHERE /, '')}${where.text}`,
58
81
  params: where.params,
59
82
  };
60
83
  }
@@ -182,6 +205,7 @@ export function createScopedTransaction(catalog, records, reads, guards, locks,
182
205
  const unkeyed = catalog.unkeyed?.get(id);
183
206
  if (unkeyed)
184
207
  return refuse(`${unkeyed}.`);
208
+ locks?.written?.(table);
185
209
  return table;
186
210
  };
187
211
  const keyFilter = (table, key) => {
@@ -290,6 +314,12 @@ export function createScopedTransaction(catalog, records, reads, guards, locks,
290
314
  });
291
315
  if (values.some((value) => value === null))
292
316
  continue;
317
+ if (catalog.inheritanceParents?.has(fk.to.table)) {
318
+ checks.push({
319
+ refused: `"${table.id}" references "${fk.to.table}", an inheritance parent: its foreign key reads the parent's own rows and a parent check its children's too, which writes under a row policy do not support yet.`,
320
+ });
321
+ break;
322
+ }
293
323
  if ('refused' in compared) {
294
324
  checks.push({ refused: compared.refused });
295
325
  break;
@@ -1328,7 +1328,7 @@ export class SqliteAdapter {
1328
1328
  reads: scopedReads(true, bound),
1329
1329
  whole: wholeWithin(scope, bound),
1330
1330
  references: async (fk, key) => {
1331
- const statement = referencesStatement(catalog.schema, fk, key, ANSI_STYLE);
1331
+ const statement = referencesStatement(catalog, fk, key, ANSI_STYLE);
1332
1332
  const [row] = await this.readRows(statement.text, statement.params, true, handle);
1333
1333
  return Number(row?.n ?? 0);
1334
1334
  },
@@ -1,6 +1,6 @@
1
1
  /**
2
- * What each binary's entry does before its main, the one way: `tablewalk` (packages/tablewalk/src/server/index.ts)
3
- * and `mistri` (packages/mistri/src/server/index.ts) each call `runBin` with their own main, and nothing else.
2
+ * What each binary's entry does before its main, the one way: `mistri` (packages/mistri/src/server/index.ts) and
3
+ * `tablewalk` (the database browser's, in its own repository) each call `runBin` with their own main, and nothing else.
4
4
  *
5
5
  * Two binaries, not one bin that hands a start across: a person types `npx tablewalk <db>` for the database browser
6
6
  * and `npx @mistriwork/mistri dev` for an App, and each refuses the other's start by the other's name. Neither entry imports the
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * What every start does before its mode, whichever binary runs it: the questions answered without starting
3
3
  * anything (`--help`, `--version`, a typo), and the process's settings the flags make (the proxies it believes,
4
- * its pools). Both mains call these (packages/tablewalk/src/server/cli/browserMain.ts,
5
- * packages/mistri/src/server/cli/mistriMain.ts), each with its own words (`Product`), and each binary runs its own
4
+ * its pools). Both mains call these (packages/mistri/src/server/cli/mistriMain.ts here, the database browser's in
5
+ * its own repository), each with its own words (`Product`), and each binary runs its own
6
6
  * main (bin.ts).
7
7
  */
8
8
  import { parseClientAddressPolicy, parseTrustedProxies } from '../http/trust.js';
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * What both command lines share about their words: the near miss a typo is told, the version, and how a usage text
3
- * is read for its command and flag words. Each binary keeps its own `USAGE` (packages/tablewalk/src/server/cli/usage.ts,
4
- * packages/mistri/src/server/cli/usage.ts), and test/prose.test.ts holds each one to its own README.
3
+ * is read for its command and flag words. Each binary keeps its own `USAGE` (packages/mistri/src/server/cli/usage.ts
4
+ * here, the database browser's in its own repository), and each is held to its own README.
5
5
  */
6
6
  /** The command words a usage names (`tablewalk migrate`, `mistri check`, …), for a near miss's suggestion. */
7
7
  export declare function commandWordsOf(usage: string, bin: string): string[];
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * What both command lines share about their words: the near miss a typo is told, the version, and how a usage text
3
- * is read for its command and flag words. Each binary keeps its own `USAGE` (packages/tablewalk/src/server/cli/usage.ts,
4
- * packages/mistri/src/server/cli/usage.ts), and test/prose.test.ts holds each one to its own README.
3
+ * is read for its command and flag words. Each binary keeps its own `USAGE` (packages/mistri/src/server/cli/usage.ts
4
+ * here, the database browser's in its own repository), and each is held to its own README.
5
5
  */
6
6
  /** The command words a usage names (`tablewalk migrate`, `mistri check`, …), for a near miss's suggestion. */
7
7
  export function commandWordsOf(usage, bin) {
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * Build the demo database.
3
3
  *
4
- * Lives in `src/` (not `test/`) because it ships: `tablewalk --demo` builds
4
+ * Lives in `src/` (not `test/`) because it ships: `--demo` builds
5
5
  * one of these at runtime so a new install has something to walk without
6
6
  * hunting for a database first. `test/make-demo-db.ts` re-exports it, so the
7
- * suite and `npm run demo` keep the path they have always used.
7
+ * suite keeps the path it has always used.
8
8
  *
9
9
  * A demo that ships as a binary file is a demo nobody can review, so this
10
10
  * writes one from source instead. The shape is chosen to exercise the parts
@@ -17,7 +17,9 @@
17
17
  */
18
18
  import type { IncomingMessage, ServerResponse } from 'node:http';
19
19
  import { type ProxyRange } from './trust.js';
20
+ /** @public the database browser's (scripts/boundary/entries.json, "host") */
20
21
  export declare const REFERRER_POLICY = "strict-origin-when-cross-origin";
22
+ /** @public the database browser's (scripts/boundary/entries.json, "host") */
21
23
  export declare const PERMISSIONS_POLICY: string;
22
24
  /** A year, and the names under this one: the time browsers ask of a name kept on https. */
23
25
  export declare const STRICT_TRANSPORT = "max-age=31536000; includeSubDomains";
@@ -1,5 +1,7 @@
1
1
  import { arrivedOverHttps } from './trust.js';
2
+ /** @public the database browser's (scripts/boundary/entries.json, "host") */
2
3
  export const REFERRER_POLICY = 'strict-origin-when-cross-origin';
4
+ /** @public the database browser's (scripts/boundary/entries.json, "host") */
3
5
  export const PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=(), bluetooth=(), hid=(), midi=(), ' +
4
6
  'magnetometer=(), gyroscope=(), accelerometer=(), display-capture=(), browsing-topics=()';
5
7
  /** A year, and the names under this one: the time browsers ask of a name kept on https. */
@@ -11,5 +11,8 @@ export declare const ROBOTS_PATH = "/robots.txt";
11
11
  export declare function sendText(req: IncomingMessage, res: ServerResponse, status: number, type: string, body: string): true;
12
12
  /** True when `path` is a crawler's question: answered as a GET or HEAD only. */
13
13
  export declare function crawlerAsks(req: IncomingMessage, res: ServerResponse, path: string): boolean;
14
- /** The answer of a server with nothing public: crawl nothing, list nothing. False for any other address. */
14
+ /**
15
+ * The answer of a server with nothing public: crawl nothing, list nothing. False for any other address.
16
+ * @public the database browser's (scripts/boundary/entries.json, "host")
17
+ */
15
18
  export declare function closedToCrawlers(req: IncomingMessage, res: ServerResponse, path: string): boolean;
@@ -20,7 +20,10 @@ export function crawlerAsks(req, res, path) {
20
20
  }
21
21
  return false;
22
22
  }
23
- /** The answer of a server with nothing public: crawl nothing, list nothing. False for any other address. */
23
+ /**
24
+ * The answer of a server with nothing public: crawl nothing, list nothing. False for any other address.
25
+ * @public the database browser's (scripts/boundary/entries.json, "host")
26
+ */
24
27
  export function closedToCrawlers(req, res, path) {
25
28
  if (path !== ROBOTS_PATH && path !== SITEMAP_PATH)
26
29
  return false;
@@ -1,5 +1,8 @@
1
1
  import type { PostContext } from './context.js';
2
- /** Why this request cannot try an API, or undefined when it can. */
2
+ /**
3
+ * Why this request cannot try an API, or undefined when it can.
4
+ * @public the database browser's (scripts/boundary/entries.json, "host")
5
+ */
3
6
  export declare function operationRefusal(request: {
4
7
  appConfigured: boolean;
5
8
  dialect: string;
@@ -1,7 +1,10 @@
1
1
  import { send } from './reply.js';
2
2
  const DESCRIBE = '/api/http/operations';
3
3
  const TRY = '/api/http/operation';
4
- /** Why this request cannot try an API, or undefined when it can. */
4
+ /**
5
+ * Why this request cannot try an API, or undefined when it can.
6
+ * @public the database browser's (scripts/boundary/entries.json, "host")
7
+ */
5
8
  export function operationRefusal(request) {
6
9
  if (request.appConfigured)
7
10
  return { status: 403, error: 'Trying an API is part of the database browser; an application does not offer it.' };
@@ -116,6 +116,7 @@ export declare class HttpError extends Error {
116
116
  * reads `.error` showed a blank message on exactly the endpoints where the
117
117
  * message mattered most. Both are sent — the list stays the shape the view
118
118
  * editor reads, and `error` is the first of them.
119
+ * @public the database browser's (scripts/boundary/entries.json, "host")
119
120
  */
120
121
  export declare function refuse(res: ServerResponse, status: number, messages: string[]): void;
121
122
  /**
@@ -330,6 +330,7 @@ export class HttpError extends Error {
330
330
  * reads `.error` showed a blank message on exactly the endpoints where the
331
331
  * message mattered most. Both are sent — the list stays the shape the view
332
332
  * editor reads, and `error` is the first of them.
333
+ * @public the database browser's (scripts/boundary/entries.json, "host")
333
334
  */
334
335
  export function refuse(res, status, messages) {
335
336
  send(res, status, {
@@ -18,28 +18,17 @@ export type Route<C extends RequestContext> = (ctx: C) => boolean | Promise<bool
18
18
  /** Try `routes` in order; true when one answered. */
19
19
  export declare function route<C extends RequestContext>(ctx: C, routes: readonly Route<C>[]): Promise<boolean>;
20
20
  /**
21
- * Every dispatcher: a module that takes a request from a socket (or a host's
21
+ * A dispatcher: a module that takes a request from a socket (or a host's
22
22
  * server) and holds it to the door before any route reads it, in the door's
23
23
  * order — the Host, the proxy's identity, the product's session, then a
24
- * write's Origin and body. test/door.test.ts stands each up and sends it the
25
- * same refusals; a new one is named here, and given a row there.
24
+ * write's Origin and body. Each product names its own in a table of these
25
+ * (its server/http/dispatchers.ts), so the engine names no product's path;
26
+ * test/door.test.ts stands each up and sends it the same refusals, and a new
27
+ * one is named in its product's table and given a row there.
26
28
  */
27
- export declare const DISPATCHERS: readonly [{
28
- readonly module: 'packages/tablewalk/src/server/http/browserHandler.ts';
29
- readonly serves: 'the database browser';
30
- }, {
31
- readonly module: 'packages/mistri/src/server/http/handler.ts';
32
- readonly serves: 'the Apps of a deployment that serves them';
33
- }, {
34
- readonly module: 'packages/mistri/src/server/embed/handler.ts';
35
- readonly serves: 'an App mounted inside somebody else’s server';
36
- }, {
37
- readonly module: 'packages/mistri/src/server/http/suite.ts';
38
- readonly serves: 'several deployments under one origin, each behind its own dispatcher';
39
- }, {
40
- readonly module: 'packages/mistri/src/server/tenant/tenantAuthenticatedHttp.ts';
41
- readonly serves: 'a tenant App’s browser host and its native sign-in';
42
- }, {
43
- readonly module: 'packages/mistri/src/server/tenant/tenantHttp.ts';
44
- readonly serves: 'a tenant App’s data, inside its browser host';
45
- }];
29
+ export interface Dispatcher {
30
+ /** The module, by its path in the repository. */
31
+ readonly module: string;
32
+ /** What it serves. */
33
+ readonly serves: string;
34
+ }
@@ -5,18 +5,3 @@ export async function route(ctx, routes) {
5
5
  return true;
6
6
  return false;
7
7
  }
8
- /**
9
- * Every dispatcher: a module that takes a request from a socket (or a host's
10
- * server) and holds it to the door before any route reads it, in the door's
11
- * order — the Host, the proxy's identity, the product's session, then a
12
- * write's Origin and body. test/door.test.ts stands each up and sends it the
13
- * same refusals; a new one is named here, and given a row there.
14
- */
15
- export const DISPATCHERS = [
16
- { module: 'packages/tablewalk/src/server/http/browserHandler.ts', serves: 'the database browser' },
17
- { module: 'packages/mistri/src/server/http/handler.ts', serves: 'the Apps of a deployment that serves them' },
18
- { module: 'packages/mistri/src/server/embed/handler.ts', serves: 'an App mounted inside somebody else’s server' },
19
- { module: 'packages/mistri/src/server/http/suite.ts', serves: 'several deployments under one origin, each behind its own dispatcher' },
20
- { module: 'packages/mistri/src/server/tenant/tenantAuthenticatedHttp.ts', serves: 'a tenant App’s browser host and its native sign-in' },
21
- { module: 'packages/mistri/src/server/tenant/tenantHttp.ts', serves: 'a tenant App’s data, inside its browser host' },
22
- ];
@@ -60,6 +60,7 @@ export declare function parseTrustedProxies(values: readonly string[]): {
60
60
  * it is a peer whose `X-Forwarded-For` the limiter may read; with the `--auth-proxy-from` list (`Bound.identityProxies`)
61
61
  * it is a peer whose `--auth-proxy-header` value `identityFor` believes. The two lists are never swapped: one
62
62
  * grants a client address, the other a person.
63
+ * @public the database browser's (scripts/boundary/entries.json, "host")
63
64
  */
64
65
  export declare function trustedProxyPeer(address: string | undefined, trusted?: readonly ProxyRange[]): boolean;
65
66
  /** Whether a public address (MISTRI_PUBLIC_URL) is an https one: what `ServerSettings.httpsFront` is set from. */
@@ -136,6 +136,7 @@ function inRange(groups, range) {
136
136
  * it is a peer whose `X-Forwarded-For` the limiter may read; with the `--auth-proxy-from` list (`Bound.identityProxies`)
137
137
  * it is a peer whose `--auth-proxy-header` value `identityFor` believes. The two lists are never swapped: one
138
138
  * grants a client address, the other a person.
139
+ * @public the database browser's (scripts/boundary/entries.json, "host")
139
140
  */
140
141
  export function trustedProxyPeer(address, trusted = []) {
141
142
  if (loopbackPeer(address))