@mistriwork/engine 1.0.0-rc.10 → 1.0.0-rc.12

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 (93) hide show
  1. package/dist/adapters/adapter.d.ts +33 -0
  2. package/dist/adapters/postgres.d.ts +21 -16
  3. package/dist/adapters/postgres.js +199 -223
  4. package/dist/adapters/postgresCatalog.d.ts +12 -1
  5. package/dist/adapters/postgresCatalog.js +57 -23
  6. package/dist/adapters/postgresCatalogDigest.js +40 -34
  7. package/dist/adapters/postgresCatalogRows.d.ts +2 -0
  8. package/dist/adapters/postgresWriteAhead.d.ts +47 -0
  9. package/dist/adapters/postgresWriteAhead.js +209 -0
  10. package/dist/adapters/scoped/keyRows.js +9 -3
  11. package/dist/adapters/scoped/keyTypes.d.ts +34 -0
  12. package/dist/adapters/scoped/keyTypes.js +66 -0
  13. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +40 -1
  14. package/dist/adapters/scoped/postgresScopeCatalog.js +417 -13
  15. package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
  16. package/dist/adapters/scoped/postgresTriggers.js +1545 -0
  17. package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
  18. package/dist/adapters/scoped/scopeTriggers.js +131 -0
  19. package/dist/adapters/scoped/scopedReads.d.ts +3 -1
  20. package/dist/adapters/scoped/scopedReads.js +28 -8
  21. package/dist/adapters/scoped/scopedTransaction.d.ts +95 -6
  22. package/dist/adapters/scoped/scopedTransaction.js +308 -34
  23. package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +17 -1
  24. package/dist/adapters/scoped/sqliteScopeCatalog.js +197 -18
  25. package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
  26. package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
  27. package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
  28. package/dist/adapters/scoped/sqliteTriggers.js +822 -0
  29. package/dist/adapters/scoped/storedText.d.ts +45 -0
  30. package/dist/adapters/scoped/storedText.js +61 -0
  31. package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
  32. package/dist/adapters/scoped/triggerEffects.js +189 -0
  33. package/dist/adapters/scoped/triggerProof.d.ts +124 -0
  34. package/dist/adapters/scoped/triggerProof.js +366 -0
  35. package/dist/adapters/snapshotRead.d.ts +8 -0
  36. package/dist/adapters/snapshotRead.js +37 -0
  37. package/dist/adapters/sqlite.d.ts +13 -2
  38. package/dist/adapters/sqlite.js +139 -16
  39. package/dist/adapters/sqliteDecimals.d.ts +2 -2
  40. package/dist/adapters/sqliteDecimals.js +2 -8
  41. package/dist/adapters/storeHost.d.ts +4 -1
  42. package/dist/adapters/writeCapture.d.ts +7 -0
  43. package/dist/server/cli/args.d.ts +6 -0
  44. package/dist/server/cli/args.js +6 -0
  45. package/dist/server/columnGrants.d.ts +3 -0
  46. package/dist/server/columnGrants.js +12 -1
  47. package/dist/server/config/profile.d.ts +123 -0
  48. package/dist/server/config/profile.js +236 -0
  49. package/dist/server/connections.d.ts +5 -0
  50. package/dist/server/connections.js +11 -1
  51. package/dist/server/hiddenColumns.js +6 -0
  52. package/dist/server/http/refusalReport.js +16 -4
  53. package/dist/server/http/router.d.ts +11 -22
  54. package/dist/server/http/router.js +0 -15
  55. package/dist/server/migrate/cli.d.ts +50 -3
  56. package/dist/server/migrate/cli.js +199 -14
  57. package/dist/server/migrate/runner.js +5 -1
  58. package/dist/server/shapeonly.js +5 -0
  59. package/dist/shared/addressParams.d.ts +2 -0
  60. package/dist/shared/addressParams.js +2 -0
  61. package/dist/shared/aggregate.d.ts +49 -0
  62. package/dist/shared/aggregate.js +107 -0
  63. package/dist/shared/breakdown.js +19 -6
  64. package/dist/shared/decimals.d.ts +37 -0
  65. package/dist/shared/decimals.js +148 -0
  66. package/dist/shared/displayDefaults.js +15 -1
  67. package/dist/shared/filter.d.ts +39 -1
  68. package/dist/shared/filter.js +96 -15
  69. package/dist/shared/listPresentations.d.ts +2 -0
  70. package/dist/shared/listQuestion.d.ts +3 -1
  71. package/dist/shared/money.d.ts +9 -0
  72. package/dist/shared/money.js +17 -0
  73. package/dist/shared/moneyEntry.d.ts +6 -3
  74. package/dist/shared/moneyEntry.js +14 -7
  75. package/dist/shared/pageModel.d.ts +1 -1
  76. package/dist/shared/recordview.d.ts +1 -1
  77. package/dist/shared/refusal.d.ts +16 -0
  78. package/dist/shared/refusal.js +40 -0
  79. package/dist/shared/rowScope.js +12 -4
  80. package/dist/shared/schema.d.ts +6 -0
  81. package/dist/shared/schematext.d.ts +22 -6
  82. package/dist/shared/schematext.js +18 -2
  83. package/dist/shared/scopeCatalog.js +4 -0
  84. package/dist/shared/servedApp.d.ts +15 -4
  85. package/dist/shared/view.js +4 -4
  86. package/dist/shared/viewLabels.d.ts +1 -0
  87. package/dist/shared/viewLabels.js +8 -2
  88. package/dist/shared/viewPaths.d.ts +3 -0
  89. package/dist/shared/viewPaths.js +8 -0
  90. package/package.json +5 -2
  91. package/schema/model.d.ts +1 -1
  92. package/dist/shared/order.d.ts +0 -59
  93. package/dist/shared/order.js +0 -133
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The types a scoped write takes as a row's identity (docs/trigger-effects.md, "Key types").
3
+ *
4
+ * Under a row policy, every check names a row by a value: a write's own row by its primary key, a parent by the
5
+ * reference that points at it, a row a trigger reaches by its effect's key. The check is sound only where the value
6
+ * it binds is the value the database compares. Six reviews found the same defect in new places: the driver's
7
+ * JavaScript reading of a jsonb key (2^53 rounded, "123" read as 123), SQLite's numeric(p,s) said with its scale
8
+ * (19.987 read as "19.99"), a float or timestamp whose text depends on the session's settings. So a column that is a
9
+ * row's identity — a primary key, either side of a foreign key, either side of a trigger effect's key — must be of a
10
+ * type whose value reads back exactly, through the driver and through text, and any other is refused from the
11
+ * catalog, before a value is read:
12
+ *
13
+ * - PostgreSQL, a domain read as the type it is over: text, varchar, char, name, citext; int2, int4, int8; numeric
14
+ * (the driver reads it as its exact text); uuid; date (its text pinned to ISO for the transaction, postgres.ts);
15
+ * boolean; an enum. Never json or jsonb, a float, a time or timestamp, an interval, money, bytea, a network
16
+ * address, an array, a range or a composite.
17
+ * - SQLite, by the affinity its declared type gives: INTEGER or TEXT. Never REAL, NUMERIC (a decimal with a declared
18
+ * scale is said with it), BLOB or a column declared without a type; except that a typeless column may reference an
19
+ * allowed key, which its foreign key compares as the check does (sqliteScopeCatalog.ts affinitiesPart).
20
+ */
21
+ /** Why a column of `type` cannot be a row's identity in a scoped write, as a refusal says it (no full stop: it is said inside others). */
22
+ export const keyTypeRefusal = (dialect, table, column, type) => `"${table}".${column} is of type ${type}, which is not supported as a key for writes under a row policy ` +
23
+ "(a primary key, either side of a foreign key, or a trigger effect's key): " +
24
+ (dialect === 'sqlite'
25
+ ? 'on SQLite a key must have INTEGER or TEXT affinity'
26
+ : 'on PostgreSQL a key must be text, varchar, char, citext, name, an integer, numeric, uuid, date, boolean or an enum') +
27
+ ', whose value reads back exactly as the database compares it' +
28
+ (dialect === 'sqlite' && looksLikeText(type) ? '; declare it TEXT (or INTEGER) to use it as a key under a row policy' : '');
29
+ /* A SQLite type named as another engine's (UUID, STRING, DATETIME, BOOLEAN, GUID) is NUMERIC by SQLite's rules, which
30
+ its author rarely meant: the refusal says what to declare instead. `said` is sqliteTypeSaid's. */
31
+ const looksLikeText = (said) => said.endsWith(' (NUMERIC affinity)') && /UUID|GUID|STRING|DATE|TIME|BOOL/i.test(said.slice(0, -' (NUMERIC affinity)'.length));
32
+ /** SQLite's affinity for a declared type (datatype3.html, 3.1), and ANY as itself: a STRICT table's ANY converts nothing. */
33
+ export function sqliteAffinity(declared) {
34
+ const type = declared.toUpperCase();
35
+ if (type.trim() === 'ANY')
36
+ return 'ANY';
37
+ if (type.includes('INT'))
38
+ return 'INTEGER';
39
+ if (/CHAR|CLOB|TEXT/.test(type))
40
+ return 'TEXT';
41
+ if (type.includes('BLOB') || !type.trim())
42
+ return 'BLOB';
43
+ if (/REAL|FLOA|DOUB/.test(type))
44
+ return 'REAL';
45
+ return 'NUMERIC';
46
+ }
47
+ /** Whether a SQLite column declared `declared` may be a row's identity in a scoped write. */
48
+ export const sqliteKeyType = (declared) => ['INTEGER', 'TEXT'].includes(sqliteAffinity(declared));
49
+ /** A SQLite column's type as a refusal names it. */
50
+ export const sqliteTypeSaid = (declared) => declared.trim() ? `${declared.trim()} (${sqliteAffinity(declared)} affinity)` : 'none declared (BLOB affinity)';
51
+ /* PostgreSQL's built-in types on the list, by oid (pg_type.dat, fixed by the server's source): bool 16, name 19,
52
+ int8 20, int2 21, int4 23, text 25, bpchar 1042, varchar 1043, date 1082, numeric 1700, uuid 2950. */
53
+ const POSTGRES_KEY_OIDS = '{16,19,20,21,23,25,1042,1043,1082,1700,2950}';
54
+ /**
55
+ * Whether the base type `type` (an oid expression, its domains already unwrapped) may be a row's identity, as a SQL
56
+ * boolean: one of the built-in types above, an enum, or the citext extension's own type (an extension's member is
57
+ * recorded in pg_depend, so a type merely named citext is not it). Every operator named in pg_catalog.
58
+ */
59
+ export const postgresKeyType = (type) => `(${type} OPERATOR(pg_catalog.=) ANY ('${POSTGRES_KEY_OIDS}'::pg_catalog.oid[])
60
+ OR EXISTS (SELECT FROM pg_catalog.pg_type kt WHERE kt.oid OPERATOR(pg_catalog.=) ${type} AND kt.typtype OPERATOR(pg_catalog.=) 'e')
61
+ OR EXISTS (SELECT FROM pg_catalog.pg_type kt
62
+ JOIN pg_catalog.pg_depend kd ON kd.objid OPERATOR(pg_catalog.=) kt.oid AND kd.classid OPERATOR(pg_catalog.=) 1247::pg_catalog.oid
63
+ AND kd.refclassid OPERATOR(pg_catalog.=) 3079::pg_catalog.oid AND kd.deptype OPERATOR(pg_catalog.=) 'e'
64
+ JOIN pg_catalog.pg_extension kx ON kx.oid OPERATOR(pg_catalog.=) kd.refobjid
65
+ WHERE kt.oid OPERATOR(pg_catalog.=) ${type} AND kt.typname OPERATOR(pg_catalog.=) 'citext'
66
+ AND kx.extname OPERATOR(pg_catalog.=) 'citext'))`;
@@ -1,7 +1,8 @@
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
+ import type { TriggerKeyFacts } from './triggerEffects.js';
5
6
  export interface PostgresScopeCatalog extends ScopeCatalog {
6
7
  /** Ordinary tables the writer role may UPDATE, and so lock rows in. A
7
8
  * superset of `writable`: a lockable table with a trigger is still refused
@@ -9,7 +10,45 @@ export interface PostgresScopeCatalog extends ScopeCatalog {
9
10
  lockable: ReadonlySet<string>;
10
11
  /** The relations this read pinned, quoted, in order: what a later transaction under the same epoch pins before it reads the epoch. */
11
12
  pinned: readonly string[];
13
+ /** Each table in `triggered`, what its triggers' proof was read from (postgresTriggers.ts triggerVersion): read
14
+ * again before COMMIT by a transaction that relied on it (attestPostgresTriggers). */
15
+ triggerVersions?: ReadonlyMap<string, string>;
12
16
  }
17
+ /**
18
+ * Before COMMIT, in a transaction that let a write fire a trigger the catalog proved validation-only: the proof's
19
+ * sources read again. A table's triggers cannot change under its pin, but the function a trigger runs, and the
20
+ * functions, operators and casts its conditions resolve to, can (CREATE OR REPLACE FUNCTION takes no lock on the table). Under
21
+ * READ COMMITTED this read sees every change committed before it, so every version a write that has already run
22
+ * could have used: a changed one refuses the transaction.
23
+ */
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;
46
+ /**
47
+ * For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
48
+ * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
49
+ * hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
50
+ */
51
+ export declare function effectCatalogFacts(client: PgQuery, given: readonly string[]): Promise<TriggerKeyFacts>;
13
52
  /** Call only on the leased writer inside its transaction, before any read of
14
53
  * user data. The describe callback is the adapter's own introspection so the
15
54
  * evidence has the same shape as the catalog the permissions were bound to. */
@@ -26,7 +26,12 @@
26
26
  */
27
27
  import { POSTGRES_STYLE, Refusal } from '../adapter.js';
28
28
  import { captureScopeCatalog } from '../../shared/scopeCatalog.js';
29
- import { triggerNames } from './scopedTransaction.js';
29
+ import { writtenType } from '../postgresCatalog.js';
30
+ import { referenceKey, ScopeRefusal, triggerNames } from './scopedTransaction.js';
31
+ import { recordRefusalCause } from '../../shared/refusal.js';
32
+ import { baseType, CATALOG_OPERATORS, defaultBtreeClass, postgresTreeTriggerNames, postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, postgresTriggerVersions, readPostgresTableCode, } from './postgresTriggers.js';
33
+ import { keyTypeRefusal, postgresKeyType } from './keyTypes.js';
34
+ const { EQ, GT, LT, NE, PLUS } = CATALOG_OPERATORS;
30
35
  const refuse = () => {
31
36
  throw new Refusal('PostgreSQL scoped transactions require a complete catalog and an ordinary table the writer may update.');
32
37
  };
@@ -36,6 +41,9 @@ function located(id) {
36
41
  return dot === -1 ? { schema: 'public', name: id } : { schema: id.slice(0, dot), name: id.slice(dot + 1) };
37
42
  }
38
43
  const key = (at) => `${at.schema}.${at.name}`;
44
+ /** A column's type as a refusal names it: as declared, and a domain with the type it is over. */
45
+ const saidType = (type, typmod, base, basemod) => `pg_catalog.format_type(${type}, ${typmod}) OPERATOR(pg_catalog.||) CASE WHEN ${type} ${NE} ${base}
46
+ THEN ' (a domain over ' OPERATOR(pg_catalog.||) pg_catalog.format_type(${base}, ${basemod}) OPERATOR(pg_catalog.||) ')' ELSE '' END`;
39
47
  /** Everything that decides whether a write to a relation means what the
40
48
  * scope assumes: its kind, row security, and the presence of triggers,
41
49
  * rules and policies — and whether this role may update it at all. */
@@ -43,22 +51,36 @@ async function facts(client, targets) {
43
51
  const result = new Map();
44
52
  if (!targets.length)
45
53
  return result;
46
- const rows = await client.query(`SELECT n.nspname AS schema, c.relname AS name, c.relkind::text AS kind, c.relrowsecurity AS rls,
47
- EXISTS (SELECT 1 FROM pg_trigger t WHERE t.tgrelid = c.oid AND NOT t.tgisinternal) AS triggers,
48
- ARRAY(SELECT t.tgname::text FROM pg_trigger t WHERE t.tgrelid = c.oid AND NOT t.tgisinternal ORDER BY 1) AS trigger_names,
49
- EXISTS (SELECT 1 FROM pg_rewrite r WHERE r.ev_class = c.oid) AS rules,
50
- EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid) AS policies,
51
- has_table_privilege(c.oid, 'UPDATE') AS updatable
52
- FROM pg_class c
53
- JOIN pg_namespace n ON n.oid = c.relnamespace
54
- JOIN unnest($1::text[], $2::text[]) AS wanted(schema, name) ON wanted.schema = n.nspname AND wanted.name = c.relname`, [targets.map((target) => target.schema), targets.map((target) => target.name)]);
54
+ const rows = await client.query(
55
+ /* Every function and operator named in pg_catalog (postgresTriggers.ts CAT): with `cardinality` found through the
56
+ search_path, `public.cardinality(text[])` answered 0 for every table, which read as no triggers at all. */
57
+ `SELECT n.nspname::pg_catalog.text AS schema, c.relname::pg_catalog.text AS name, c.relkind::pg_catalog.text AS kind,
58
+ c.relrowsecurity AS rls, pg_catalog.cardinality(fired.names) ${GT} 0 AS triggers, fired.names AS trigger_names,
59
+ EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite r WHERE r.ev_class ${EQ} c.oid) AS rules,
60
+ EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid ${EQ} c.oid) AS policies,
61
+ pg_catalog.has_table_privilege(c.oid, 'UPDATE') AS updatable,
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)
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,
65
+ unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type
66
+ FROM ${WANTED}
67
+ -- A key column whose type is not on the list (keyTypes.ts), its domains unwrapped: no scoped write targets the table.
68
+ LEFT JOIN LATERAL (SELECT a.attname::pg_catalog.text AS name, ${saidType('a.atttypid', 'a.atttypmod', 'b.type', 'b.typmod')} AS said
69
+ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} c.oid AND a.attnum OPERATOR(pg_catalog.=) ANY (i.indkey)
70
+ CROSS JOIN LATERAL ${baseType('a.atttypid', 'a.atttypmod')} AS b
71
+ WHERE i.indrelid ${EQ} c.oid AND i.indisprimary AND NOT ${postgresKeyType('b.type')}
72
+ ORDER BY a.attnum LIMIT 1) AS unkeyed ON true
73
+ -- Its partitions' and inheritance children's too: a write through it reaches their rows and fires theirs.
74
+ CROSS JOIN LATERAL (SELECT ${postgresTreeTriggerNames('c.oid')} AS names) AS fired`, [targets.map((target) => target.schema), targets.map((target) => target.name)]);
55
75
  for (const row of rows.rows) {
56
76
  if (typeof row.schema !== 'string' ||
57
77
  typeof row.name !== 'string' ||
58
78
  typeof row.kind !== 'string' ||
59
- [row.rls, row.triggers, row.rules, row.policies, row.updatable].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') ||
60
80
  !Array.isArray(row.trigger_names) ||
61
81
  row.trigger_names.some((name) => typeof name !== 'string') ||
82
+ (row.unkeyed_column !== null && typeof row.unkeyed_column !== 'string') ||
83
+ (row.unkeyed_type !== null && typeof row.unkeyed_type !== 'string') ||
62
84
  result.has(key(row)))
63
85
  return refuse();
64
86
  result.set(key(row), row);
@@ -67,6 +89,333 @@ async function facts(client, targets) {
67
89
  }
68
90
  const lockable = (fact) => fact !== undefined && ['r', 'p'].includes(fact.kind) && fact.updatable;
69
91
  const clean = (fact) => !fact.rls && !fact.triggers && !fact.rules && !fact.policies;
92
+ /** Clean but for its triggers: each write is then judged by the triggers it fires (scopedTransaction.ts target). */
93
+ const cleanButTriggers = (fact) => fact.triggers && !fact.rls && !fact.rules && !fact.policies;
94
+ /** The rows of the triggers of `tables`, read on the writer. */
95
+ async function triggerRows(client, tables) {
96
+ const result = await client.query(postgresTriggerStatement(true), [
97
+ tables.map((table) => table.schema),
98
+ tables.map((table) => table.name),
99
+ ]);
100
+ return result.rows;
101
+ }
102
+ /** The triggers of `tables` (adapter ids), read and proven on the writer: what fires each, whether it only validates, and what that was proven from. */
103
+ async function readTriggers(client, tables) {
104
+ const byKey = await postgresTriggersByTable(await triggerRows(client, tables), postgresTriggerAnalyzer(client));
105
+ const read = new Map();
106
+ for (const table of tables) {
107
+ const found = byKey.get(key(table));
108
+ // The facts said it has triggers, and the table is pinned against CREATE and DROP TRIGGER: none is a catalog this code misread.
109
+ if (!found)
110
+ return refuse();
111
+ read.set(table.id, found);
112
+ }
113
+ return read;
114
+ }
115
+ /**
116
+ * Before COMMIT, in a transaction that let a write fire a trigger the catalog proved validation-only: the proof's
117
+ * sources read again. A table's triggers cannot change under its pin, but the function a trigger runs, and the
118
+ * functions, operators and casts its conditions resolve to, can (CREATE OR REPLACE FUNCTION takes no lock on the table). Under
119
+ * READ COMMITTED this read sees every change committed before it, so every version a write that has already run
120
+ * could have used: a changed one refuses the transaction.
121
+ */
122
+ export async function attestPostgresTriggers(client, catalog, tables) {
123
+ if (!tables.size)
124
+ return;
125
+ try {
126
+ const wanted = [...tables].map((id) => {
127
+ const table = catalog.schema.tables.find((candidate) => candidate.id === id);
128
+ const version = catalog.triggerVersions?.get(id);
129
+ if (!table || version === undefined)
130
+ return refuse();
131
+ return { id, schema: table.schema, name: table.name, version };
132
+ });
133
+ // The versions alone: what the proof was made from, not the proof made again.
134
+ const read = postgresTriggerVersions(await triggerRows(client, wanted));
135
+ for (const table of wanted)
136
+ if (read.get(key(table)) !== table.version)
137
+ return refuse();
138
+ }
139
+ catch (error) {
140
+ if (error instanceof Refusal)
141
+ throw error;
142
+ return refuse();
143
+ }
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
+ }
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). */
204
+ const WANTED = `pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid ${EQ} c.relnamespace
205
+ JOIN ROWS FROM (pg_catalog.unnest($1::pg_catalog.text[]), pg_catalog.unnest($2::pg_catalog.text[])) AS wanted(schema, name)
206
+ ON n.nspname ${EQ} wanted.schema AND c.relname ${EQ} wanted.name`;
207
+ /**
208
+ * How a trigger's key equality compares on PostgreSQL, for `ids` (triggerEffects.ts): each column's base type and
209
+ * type modifier with its domains unwrapped, its collation and whether that collation is deterministic; and the
210
+ * column sets each table is unique on as such an equality compares. A unique index counts only where it is valid,
211
+ * immediate (a deferrable one holds duplicates until COMMIT), B-tree, over plain columns of the whole table, and
212
+ * each column is indexed under its own collation and its type's default operator class: an index under "C" on a
213
+ * column whose collation folds case, or under a pattern operator class, is unique by an equality the trigger does not
214
+ * make. `TableMeta.unique` (an App's address, a tenant's bound) is read by looser rules and is left as it is.
215
+ */
216
+ async function effectKeyFacts(client, ids) {
217
+ // Each once: a table named twice would count each index column twice.
218
+ const at = [...new Set(ids)].map(located);
219
+ const params = [at.map((table) => table.schema), at.map((table) => table.name)];
220
+ const tables = `SELECT c.oid, n.nspname::pg_catalog.text OPERATOR(pg_catalog.||) '.' OPERATOR(pg_catalog.||) c.relname::pg_catalog.text AS id
221
+ FROM ${WANTED}`;
222
+ const columns = await client.query(`WITH t AS (${tables})
223
+ SELECT t.id, a.attname::pg_catalog.text AS name, b.type::pg_catalog.int4 AS type, b.typmod::pg_catalog.int4 AS typmod,
224
+ pg_catalog.format_type(b.type, b.typmod) AS said, a.attcollation::pg_catalog.int4 AS collation,
225
+ coalesce(ln.nspname::pg_catalog.text, '') AS collschema, coalesce(l.collname::pg_catalog.text, '') AS collname,
226
+ coalesce((pg_catalog.to_jsonb(l) OPERATOR(pg_catalog.->>) 'collisdeterministic')::pg_catalog.bool, true) AS exact,
227
+ ${postgresKeyType('b.type')} AS keyable, ${saidType('a.atttypid', 'a.atttypmod', 'b.type', 'b.typmod')} AS declared
228
+ FROM t JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} t.oid AND a.attnum ${GT} 0 AND NOT a.attisdropped
229
+ CROSS JOIN LATERAL ${baseType('a.atttypid', 'a.atttypmod')} AS b
230
+ LEFT JOIN pg_catalog.pg_collation l ON l.oid ${EQ} a.attcollation
231
+ LEFT JOIN pg_catalog.pg_namespace ln ON ln.oid ${EQ} l.collnamespace`, params);
232
+ const keys = await client.query(`WITH t AS (${tables})
233
+ SELECT t.id, pg_catalog.array_agg(a.attname::pg_catalog.text ORDER BY k.ord) AS columns,
234
+ pg_catalog.bool_and(k.coll ${EQ} a.attcollation AND k.opclass ${EQ} ${defaultBtreeClass('b.type')}) AS own
235
+ FROM t
236
+ JOIN pg_catalog.pg_index i ON i.indrelid ${EQ} t.oid
237
+ JOIN pg_catalog.pg_class ic ON ic.oid ${EQ} i.indexrelid
238
+ CROSS JOIN LATERAL ROWS FROM (pg_catalog.unnest(i.indkey::pg_catalog.int2[]), pg_catalog.unnest(i.indcollation::pg_catalog.oid[]), pg_catalog.unnest(i.indclass::pg_catalog.oid[]))
239
+ WITH ORDINALITY AS k(attnum, coll, opclass, ord)
240
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} t.oid AND a.attnum ${EQ} k.attnum
241
+ CROSS JOIN LATERAL ${baseType('a.atttypid', 'a.atttypmod')} AS b
242
+ WHERE i.indisunique AND i.indisvalid AND i.indimmediate AND i.indpred IS NULL AND i.indexprs IS NULL
243
+ AND i.indnatts ${EQ} i.indnkeyatts AND ic.relam ${EQ} 403::pg_catalog.oid
244
+ GROUP BY t.id, i.indexrelid
245
+ HAVING pg_catalog.count(*) ${EQ} pg_catalog.max(i.indnkeyatts)`, params);
246
+ const compared = new Map();
247
+ for (const row of columns.rows) {
248
+ if (typeof row.id !== 'string' ||
249
+ typeof row.name !== 'string' ||
250
+ typeof row.said !== 'string' ||
251
+ typeof row.exact !== 'boolean' ||
252
+ typeof row.keyable !== 'boolean' ||
253
+ typeof row.declared !== 'string')
254
+ return refuse();
255
+ compared.set(`${row.id}\u0000${row.name}`, {
256
+ type: `${String(row.type)}:${String(row.typmod)}`,
257
+ collation: String(row.collation),
258
+ exact: row.exact,
259
+ keyable: row.keyable,
260
+ declared: row.declared,
261
+ // Named with its schema: two collations of one name in two schemas are two collations (an ICU "sv" and a libc one).
262
+ said: `${row.said}${row.collname ? ` COLLATE ${POSTGRES_STYLE.quote(String(row.collschema))}.${POSTGRES_STYLE.quote(String(row.collname))}` : ''}`,
263
+ });
264
+ }
265
+ const unique = new Map();
266
+ for (const row of keys.rows) {
267
+ if (typeof row.id !== 'string' || !Array.isArray(row.columns) || row.columns.some((name) => typeof name !== 'string'))
268
+ return refuse();
269
+ if (row.own === true)
270
+ unique.set(row.id, [...(unique.get(row.id) ?? []), row.columns]);
271
+ }
272
+ return {
273
+ keys: (table) => unique.get(table.id) ?? [],
274
+ comparison: (table, column) => compared.get(`${table.id}\u0000${column}`),
275
+ };
276
+ }
277
+ /** A type as `ri_triggers.c` casts to it: its schema and name, each quoted where it needs it. */
278
+ const castType = (oid) => `(SELECT pg_catalog.quote_ident(tn.nspname::pg_catalog.text) OPERATOR(pg_catalog.||) '.'
279
+ OPERATOR(pg_catalog.||) pg_catalog.quote_ident(t.typname::pg_catalog.text)
280
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace tn ON tn.oid ${EQ} t.typnamespace WHERE t.oid ${EQ} ${oid})`;
281
+ /* Whether a type is a pseudo-type: a polymorphic operator's input (an enum's `anyenum`), which a side is not cast to.
282
+ The operator resolves it from the side's own type. */
283
+ const pseudo = (oid) => `EXISTS (SELECT FROM pg_catalog.pg_type pt WHERE pt.oid ${EQ} ${oid} AND pt.typtype ${EQ} 'p')`;
284
+ const CONCAT = 'OPERATOR(pg_catalog.||)';
285
+ /**
286
+ * A column's type as a cast names it whatever the search_path: its schema and name from pg_type, each quoted where it
287
+ * needs it (castType), then its modifier as the digits the type's own input reads back — `pg_catalog."numeric"(10,2)`,
288
+ * `pg_catalog.bpchar(3)`. `format_type` said `text` and `character(3)`: a name found through the search_path when the
289
+ * statement runs, which a type made after the catalog was read (a domain `public.text` over `name`, with pg_catalog
290
+ * after public) answered, and a check that read 64 characters as 63 found another key than the foreign key. The
291
+ * modifier is what `format_type` adds to the type's bare name, a parenthesised list for every type a reference may be
292
+ * that has one (varchar, char, numeric: keyTypes.ts). NULL where it is not: a type a check cannot name.
293
+ */
294
+ const sqlType = (oid, typmod) => `(SELECT CASE WHEN m.said IS NOT NULL THEN
295
+ pg_catalog.quote_ident(tn.nspname::pg_catalog.text) ${CONCAT} '.' ${CONCAT} pg_catalog.quote_ident(t.typname::pg_catalog.text) ${CONCAT} m.said END
296
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace tn ON tn.oid ${EQ} t.typnamespace
297
+ CROSS JOIN LATERAL (SELECT CASE
298
+ WHEN ${typmod} ${LT} 0 THEN ''
299
+ WHEN pg_catalog.left(pg_catalog.format_type(t.oid, ${typmod}), pg_catalog.length(pg_catalog.format_type(t.oid, NULL)))
300
+ ${EQ} pg_catalog.format_type(t.oid, NULL)
301
+ THEN pg_catalog.substr(pg_catalog.format_type(t.oid, ${typmod}), pg_catalog.length(pg_catalog.format_type(t.oid, NULL)) ${PLUS} 1)
302
+ END AS said) AS m
303
+ WHERE t.oid ${EQ} ${oid})`;
304
+ /**
305
+ * How each foreign key of `schema` compares a reference with its parent's key (ScopeCatalog.references), as the
306
+ * database's own check states it (ri_triggers.c RI_FKey_check, ruleutils.c generate_operator_clause): the parent
307
+ * column, cast to the operator's left type where its own is another, then `OPERATOR(schema.name)` of the constraint's
308
+ * own equality (`conpfeqop`), then the value read as the referencing column's type, typmod and all and named by its
309
+ * schema (sqlType), and cast to the operator's right type where that is another. Neither side is cast to a
310
+ * pseudo-type (`pseudo`): an enum's `anyenum` is resolved from the side's own type. A parent check written so finds the
311
+ * row the foreign key finds: by `=` and the value as given, a char(3) 'ab ' found the text key 'ab ', where the foreign
312
+ * key, comparing as text, finds 'ab'. A key whose columns or operators the catalog does not give whole, either side of
313
+ * which is of a type a key may not be (keyTypes.ts), or whose type a cast cannot name, is refused to a scoped write
314
+ * through it.
315
+ */
316
+ async function foreignKeyComparisons(client, schema) {
317
+ const at = schema.tables.map((table) => ({ schema: table.schema, name: table.name }));
318
+ const result = await client.query(`SELECT n.nspname::pg_catalog.text AS schema, c.relname::pg_catalog.text AS "table", con.conname::pg_catalog.text AS name,
319
+ k.ord::pg_catalog.int4 AS ord, fa.attname::pg_catalog.text AS child, pa.attname::pg_catalog.text AS parent,
320
+ ${sqlType('fa.atttypid', 'fa.atttypmod')} AS type, ${writtenType('fa.atttypid', 'fa.atttypmod')} AS written,
321
+ ${postgresKeyType('fb.type')} AS child_keyable, ${saidType('fa.atttypid', 'fa.atttypmod', 'fb.type', 'fb.typmod')} AS child_said,
322
+ ${postgresKeyType('pb.type')} AS parent_keyable, ${saidType('pa.atttypid', 'pa.atttypmod', 'pb.type', 'pb.typmod')} AS parent_said,
323
+ pg_catalog.quote_ident(opn.nspname::pg_catalog.text) OPERATOR(pg_catalog.||) '.' OPERATOR(pg_catalog.||) o.oprname::pg_catalog.text AS operator,
324
+ CASE WHEN pa.atttypid ${EQ} o.oprleft OR ${pseudo('o.oprleft')} THEN NULL ELSE ${castType('o.oprleft')} END AS "left",
325
+ CASE WHEN fa.atttypid ${EQ} o.oprright OR ${pseudo('o.oprright')} THEN NULL ELSE ${castType('o.oprright')} END AS "right"
326
+ FROM ${WANTED}
327
+ -- Never a clone that points at a partition, as the schema reads them (postgresCatalog.ts).
328
+ JOIN pg_catalog.pg_constraint con ON con.conrelid ${EQ} c.oid AND con.contype ${EQ} 'f'
329
+ AND NOT EXISTS (SELECT FROM pg_catalog.pg_constraint pc WHERE pc.oid ${EQ} con.conparentid AND pc.confrelid ${NE} con.confrelid)
330
+ CROSS JOIN LATERAL ROWS FROM (pg_catalog.unnest(con.conkey), pg_catalog.unnest(con.confkey), pg_catalog.unnest(con.conpfeqop))
331
+ WITH ORDINALITY AS k(child, parent, operator, ord)
332
+ LEFT JOIN pg_catalog.pg_attribute fa ON fa.attrelid ${EQ} con.conrelid AND fa.attnum ${EQ} k.child
333
+ LEFT JOIN pg_catalog.pg_attribute pa ON pa.attrelid ${EQ} con.confrelid AND pa.attnum ${EQ} k.parent
334
+ LEFT JOIN LATERAL ${baseType('fa.atttypid', 'fa.atttypmod')} AS fb ON true
335
+ LEFT JOIN LATERAL ${baseType('pa.atttypid', 'pa.atttypmod')} AS pb ON true
336
+ LEFT JOIN pg_catalog.pg_operator o ON o.oid ${EQ} k.operator
337
+ LEFT JOIN pg_catalog.pg_namespace opn ON opn.oid ${EQ} o.oprnamespace
338
+ ORDER BY 1, 2, 3, 4`, [at.map((table) => table.schema), at.map((table) => table.name)]);
339
+ const read = new Map();
340
+ for (const row of result.rows) {
341
+ const id = `${String(row.schema)}.${String(row.table)}\u0000${String(row.name)}`;
342
+ read.set(id, [...(read.get(id) ?? []), row]);
343
+ }
344
+ const comparisons = new Map();
345
+ for (const fk of schema.foreignKeys) {
346
+ const rows = read.get(`${fk.from.table}\u0000${fk.name}`) ?? [];
347
+ const whole = rows.length === fk.from.columns.length &&
348
+ rows.every((row, index) => row.ord === index + 1 &&
349
+ row.child === fk.from.columns[index] &&
350
+ row.parent === fk.to.columns[index] &&
351
+ (row.type === null || typeof row.type === 'string') &&
352
+ typeof row.written === 'string' &&
353
+ typeof row.child_keyable === 'boolean' &&
354
+ typeof row.parent_keyable === 'boolean' &&
355
+ typeof row.child_said === 'string' &&
356
+ typeof row.parent_said === 'string' &&
357
+ typeof row.operator === 'string' &&
358
+ (row.left === null || typeof row.left === 'string') &&
359
+ (row.right === null || typeof row.right === 'string'));
360
+ const unnamed = rows.findIndex((row) => row.type === null);
361
+ // Each side a row's identity (keyTypes.ts): the key pointed at, then the reference.
362
+ const parent = rows.findIndex((row) => row.parent_keyable !== true);
363
+ const child = rows.findIndex((row) => row.child_keyable !== true);
364
+ comparisons.set(referenceKey(fk), !whole
365
+ ? {
366
+ refused: `"${fk.from.table}".${fk.from.columns.join('+')} has a foreign key ("${fk.name}") whose comparison the catalog does not give whole, so a parent it points at cannot be checked as it compares.`,
367
+ }
368
+ : parent !== -1
369
+ ? { refused: `${keyTypeRefusal('postgres', fk.to.table, fk.to.columns[parent], rows[parent].parent_said)}.` }
370
+ : child !== -1
371
+ ? { refused: `${keyTypeRefusal('postgres', fk.from.table, fk.from.columns[child], rows[child].child_said)}.` }
372
+ : unnamed !== -1
373
+ ? {
374
+ refused: `"${fk.from.table}".${fk.from.columns[unnamed]} is of a type whose modifier a check cannot write, which a scoped write does not support for a reference.`,
375
+ }
376
+ : {
377
+ columns: rows.map((row) => ({
378
+ // Coerced as the write coerces it (postgresCatalog.ts writtenType): a domain read as the type it is over.
379
+ type: row.written,
380
+ equality: {
381
+ operator: row.operator,
382
+ type: row.type,
383
+ ...(typeof row.left === 'string' ? { left: row.left } : {}),
384
+ ...(typeof row.right === 'string' ? { right: row.right } : {}),
385
+ },
386
+ })),
387
+ });
388
+ }
389
+ return comparisons;
390
+ }
391
+ /** What blocks a scoped write to a table beyond its triggers, as a refusal names it; undefined where nothing does. */
392
+ const blockerOf = (fact) => !['r', 'p'].includes(fact.kind)
393
+ ? 'a kind a scoped write cannot target'
394
+ : !fact.updatable
395
+ ? 'no UPDATE privilege for the role that writes'
396
+ : fact.rls || fact.rules || fact.policies
397
+ ? [fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : ''].filter(Boolean).join(' and ')
398
+ : undefined;
399
+ /**
400
+ * For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
401
+ * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
402
+ * hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
403
+ */
404
+ export async function effectCatalogFacts(client, given) {
405
+ const ids = [...new Set(given)];
406
+ const read = await facts(client, ids.map(located));
407
+ const blocked = new Map();
408
+ const hierarchy = new Set();
409
+ for (const id of ids) {
410
+ const fact = read.get(key(located(id)));
411
+ if (fact?.hierarchy)
412
+ hierarchy.add(id);
413
+ const blocker = fact && blockerOf(fact);
414
+ if (blocker)
415
+ blocked.set(id, blocker);
416
+ }
417
+ return { ...(await effectKeyFacts(client, ids)), hierarchy, blocked };
418
+ }
70
419
  /** What makes a table unclean, as a refusal names it. */
71
420
  const unclean = (fact) => [fact.triggers ? triggerNames(fact.trigger_names) : '', fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : '']
72
421
  .filter(Boolean)
@@ -88,24 +437,79 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
88
437
  const held = new Set(pinned.map(key));
89
438
  const writable = new Set();
90
439
  const blockedBy = new Map();
440
+ const unkeyed = new Map();
441
+ const hierarchy = new Set();
442
+ const inheritanceParents = new Set();
91
443
  const locks = new Set();
444
+ const withTriggers = [];
92
445
  for (const table of schema.tables) {
93
446
  const fact = (await after).get(key(table));
94
447
  // A relation the catalog listed a moment ago and cannot describe now
95
448
  // was dropped under this transaction; nothing here may rely on it.
96
449
  if (!fact || table.id !== key(table))
97
450
  return refuse();
451
+ if (fact.unkeyed_column !== null)
452
+ unkeyed.set(table.id, keyTypeRefusal('postgres', table.id, fact.unkeyed_column, fact.unkeyed_type ?? 'unknown'));
453
+ // Never a target, but still lockable: a reference to a partitioned table holds its parent row through it.
454
+ if (fact.hierarchy)
455
+ hierarchy.add(table.id);
456
+ if (fact.inherited)
457
+ inheritanceParents.add(table.id);
98
458
  if (!lockable(fact))
99
459
  continue;
100
460
  locks.add(table.id);
461
+ if (fact.hierarchy)
462
+ continue;
101
463
  // Writable means pinned: a table that became clean after the pin
102
464
  // decision could be dirtied again before COMMIT, so it stays read-only.
103
- if (held.has(table.id) && clean(fact) && !table.isView && table.columns.some((column) => column.primaryKey))
465
+ const ordinary = held.has(table.id) && !table.isView && table.columns.some((column) => column.primaryKey);
466
+ if (ordinary && clean(fact))
104
467
  writable.add(table.id);
468
+ else if (ordinary && cleanButTriggers(fact))
469
+ withTriggers.push({ id: table.id, schema: table.schema, name: table.name });
105
470
  else if (!clean(fact))
106
471
  blockedBy.set(table.id, unclean(fact));
107
472
  }
108
- return { schema, writable, ...(blockedBy.size ? { blockedBy } : {}), lockable: locks, pinned: relations };
473
+ /* Read only where a table has triggers: a database without them asks nothing more than it did. */
474
+ const read = withTriggers.length ? await readTriggers(client, withTriggers) : undefined;
475
+ const readTriggered = new Map([...(read ?? [])].map(([id, entry]) => [id, entry.triggers]));
476
+ const triggerVersions = new Map([...(read ?? [])].map(([id, entry]) => [id, entry.version]));
477
+ /* What else a write to a writable table runs — a default, a CHECK, a domain — judged as a trigger that is not
478
+ validation-only where it calls a function of the database's: a table with such code is written only by the
479
+ writes that run none of it. Read before the effects are judged, so a trigger's write to such a table is
480
+ refused as the person's own would be. */
481
+ const written = schema.tables.filter((table) => writable.has(table.id) || readTriggered.has(table.id));
482
+ const code = await readPostgresTableCode(client, written);
483
+ for (const table of written) {
484
+ const own = code.get(key(table));
485
+ if (!own)
486
+ continue;
487
+ writable.delete(table.id);
488
+ readTriggered.set(table.id, [...(readTriggered.get(table.id) ?? []), ...own]);
489
+ }
490
+ // Keyed effects are judged against the catalog they run in (triggerEffects.ts); a database without them asks nothing more.
491
+ const triggered = [...readTriggered.values()].some((triggers) => triggers.some((trigger) => trigger.effects))
492
+ ? (await import('./triggerEffects.js')).resolveTriggerEffects({
493
+ schema,
494
+ writable,
495
+ triggered: readTriggered,
496
+ foldCase: false,
497
+ hierarchy,
498
+ ...(await effectKeyFacts(client, [...writable, ...readTriggered.keys()])),
499
+ })
500
+ : readTriggered;
501
+ return {
502
+ schema,
503
+ writable,
504
+ references: await foreignKeyComparisons(client, schema),
505
+ ...(blockedBy.size ? { blockedBy } : {}),
506
+ ...(unkeyed.size ? { unkeyed } : {}),
507
+ ...(hierarchy.size ? { hierarchy } : {}),
508
+ ...(inheritanceParents.size ? { inheritanceParents } : {}),
509
+ ...(triggered.size ? { triggered, triggerVersions } : {}),
510
+ lockable: locks,
511
+ pinned: relations,
512
+ };
109
513
  }
110
514
  catch (error) {
111
515
  if (error instanceof Refusal)