@mistriwork/engine 1.0.0-rc.10 → 1.0.0-rc.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/adapter.d.ts +33 -0
- package/dist/adapters/postgres.d.ts +21 -16
- package/dist/adapters/postgres.js +174 -223
- package/dist/adapters/postgresCatalog.d.ts +12 -1
- package/dist/adapters/postgresCatalog.js +57 -23
- package/dist/adapters/postgresCatalogDigest.js +40 -34
- package/dist/adapters/postgresCatalogRows.d.ts +2 -0
- package/dist/adapters/postgresWriteAhead.d.ts +47 -0
- package/dist/adapters/postgresWriteAhead.js +209 -0
- package/dist/adapters/scoped/keyRows.js +9 -3
- package/dist/adapters/scoped/keyTypes.d.ts +34 -0
- package/dist/adapters/scoped/keyTypes.js +66 -0
- package/dist/adapters/scoped/postgresScopeCatalog.d.ts +18 -0
- package/dist/adapters/scoped/postgresScopeCatalog.js +353 -13
- package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
- package/dist/adapters/scoped/postgresTriggers.js +1545 -0
- package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
- package/dist/adapters/scoped/scopeTriggers.js +131 -0
- package/dist/adapters/scoped/scopedReads.d.ts +3 -1
- package/dist/adapters/scoped/scopedReads.js +23 -5
- package/dist/adapters/scoped/scopedTransaction.d.ts +76 -6
- package/dist/adapters/scoped/scopedTransaction.js +278 -34
- package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +17 -1
- package/dist/adapters/scoped/sqliteScopeCatalog.js +197 -18
- package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
- package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
- package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
- package/dist/adapters/scoped/sqliteTriggers.js +822 -0
- package/dist/adapters/scoped/storedText.d.ts +45 -0
- package/dist/adapters/scoped/storedText.js +61 -0
- package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
- package/dist/adapters/scoped/triggerEffects.js +189 -0
- package/dist/adapters/scoped/triggerProof.d.ts +124 -0
- package/dist/adapters/scoped/triggerProof.js +366 -0
- package/dist/adapters/snapshotRead.d.ts +8 -0
- package/dist/adapters/snapshotRead.js +37 -0
- package/dist/adapters/sqlite.d.ts +13 -2
- package/dist/adapters/sqlite.js +139 -16
- package/dist/adapters/sqliteDecimals.d.ts +2 -2
- package/dist/adapters/sqliteDecimals.js +2 -8
- package/dist/adapters/storeHost.d.ts +4 -1
- package/dist/adapters/writeCapture.d.ts +7 -0
- package/dist/server/cli/args.d.ts +6 -0
- package/dist/server/cli/args.js +6 -0
- package/dist/server/columnGrants.d.ts +3 -0
- package/dist/server/columnGrants.js +12 -1
- package/dist/server/config/profile.d.ts +123 -0
- package/dist/server/config/profile.js +236 -0
- package/dist/server/connections.d.ts +5 -0
- package/dist/server/connections.js +11 -1
- package/dist/server/hiddenColumns.js +6 -0
- package/dist/server/http/refusalReport.js +16 -4
- package/dist/server/migrate/cli.d.ts +50 -3
- package/dist/server/migrate/cli.js +199 -14
- package/dist/server/migrate/runner.js +5 -1
- package/dist/server/shapeonly.js +5 -0
- package/dist/shared/aggregate.d.ts +49 -0
- package/dist/shared/aggregate.js +107 -0
- package/dist/shared/breakdown.js +17 -4
- package/dist/shared/decimals.d.ts +37 -0
- package/dist/shared/decimals.js +148 -0
- package/dist/shared/displayDefaults.js +15 -1
- package/dist/shared/filter.d.ts +22 -1
- package/dist/shared/filter.js +36 -9
- package/dist/shared/money.d.ts +9 -0
- package/dist/shared/money.js +17 -0
- package/dist/shared/pageModel.d.ts +1 -1
- package/dist/shared/refusal.d.ts +16 -0
- package/dist/shared/refusal.js +40 -0
- package/dist/shared/schema.d.ts +6 -0
- package/dist/shared/scopeCatalog.js +4 -0
- package/dist/shared/servedApp.d.ts +7 -2
- package/package.json +5 -1
|
@@ -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'))`;
|
|
@@ -2,6 +2,7 @@ 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
4
|
import { 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,24 @@ 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
|
+
* For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
|
|
27
|
+
* (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
|
|
28
|
+
* hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
|
|
29
|
+
*/
|
|
30
|
+
export declare function effectCatalogFacts(client: PgQuery, given: readonly string[]): Promise<TriggerKeyFacts>;
|
|
13
31
|
/** Call only on the leased writer inside its transaction, before any read of
|
|
14
32
|
* user data. The describe callback is the adapter's own introspection so the
|
|
15
33
|
* evidence has the same shape as the catalog the permissions were bound to. */
|
|
@@ -26,7 +26,11 @@
|
|
|
26
26
|
*/
|
|
27
27
|
import { POSTGRES_STYLE, Refusal } from '../adapter.js';
|
|
28
28
|
import { captureScopeCatalog } from '../../shared/scopeCatalog.js';
|
|
29
|
-
import {
|
|
29
|
+
import { writtenType } from '../postgresCatalog.js';
|
|
30
|
+
import { referenceKey, triggerNames } from './scopedTransaction.js';
|
|
31
|
+
import { baseType, CATALOG_OPERATORS, defaultBtreeClass, postgresTreeTriggerNames, postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, postgresTriggerVersions, readPostgresTableCode, } from './postgresTriggers.js';
|
|
32
|
+
import { keyTypeRefusal, postgresKeyType } from './keyTypes.js';
|
|
33
|
+
const { EQ, GT, LT, NE, PLUS } = CATALOG_OPERATORS;
|
|
30
34
|
const refuse = () => {
|
|
31
35
|
throw new Refusal('PostgreSQL scoped transactions require a complete catalog and an ordinary table the writer may update.');
|
|
32
36
|
};
|
|
@@ -36,6 +40,9 @@ function located(id) {
|
|
|
36
40
|
return dot === -1 ? { schema: 'public', name: id } : { schema: id.slice(0, dot), name: id.slice(dot + 1) };
|
|
37
41
|
}
|
|
38
42
|
const key = (at) => `${at.schema}.${at.name}`;
|
|
43
|
+
/** A column's type as a refusal names it: as declared, and a domain with the type it is over. */
|
|
44
|
+
const saidType = (type, typmod, base, basemod) => `pg_catalog.format_type(${type}, ${typmod}) OPERATOR(pg_catalog.||) CASE WHEN ${type} ${NE} ${base}
|
|
45
|
+
THEN ' (a domain over ' OPERATOR(pg_catalog.||) pg_catalog.format_type(${base}, ${basemod}) OPERATOR(pg_catalog.||) ')' ELSE '' END`;
|
|
39
46
|
/** Everything that decides whether a write to a relation means what the
|
|
40
47
|
* scope assumes: its kind, row security, and the presence of triggers,
|
|
41
48
|
* rules and policies — and whether this role may update it at all. */
|
|
@@ -43,22 +50,35 @@ async function facts(client, targets) {
|
|
|
43
50
|
const result = new Map();
|
|
44
51
|
if (!targets.length)
|
|
45
52
|
return result;
|
|
46
|
-
const rows = await client.query(
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
const rows = await client.query(
|
|
54
|
+
/* Every function and operator named in pg_catalog (postgresTriggers.ts CAT): with `cardinality` found through the
|
|
55
|
+
search_path, `public.cardinality(text[])` answered 0 for every table, which read as no triggers at all. */
|
|
56
|
+
`SELECT n.nspname::pg_catalog.text AS schema, c.relname::pg_catalog.text AS name, c.relkind::pg_catalog.text AS kind,
|
|
57
|
+
c.relrowsecurity AS rls, pg_catalog.cardinality(fired.names) ${GT} 0 AS triggers, fired.names AS trigger_names,
|
|
58
|
+
EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite r WHERE r.ev_class ${EQ} c.oid) AS rules,
|
|
59
|
+
EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid ${EQ} c.oid) AS policies,
|
|
60
|
+
pg_catalog.has_table_privilege(c.oid, 'UPDATE') AS updatable,
|
|
61
|
+
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
|
+
AS hierarchy,
|
|
63
|
+
unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type
|
|
64
|
+
FROM ${WANTED}
|
|
65
|
+
-- A key column whose type is not on the list (keyTypes.ts), its domains unwrapped: no scoped write targets the table.
|
|
66
|
+
LEFT JOIN LATERAL (SELECT a.attname::pg_catalog.text AS name, ${saidType('a.atttypid', 'a.atttypmod', 'b.type', 'b.typmod')} AS said
|
|
67
|
+
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)
|
|
68
|
+
CROSS JOIN LATERAL ${baseType('a.atttypid', 'a.atttypmod')} AS b
|
|
69
|
+
WHERE i.indrelid ${EQ} c.oid AND i.indisprimary AND NOT ${postgresKeyType('b.type')}
|
|
70
|
+
ORDER BY a.attnum LIMIT 1) AS unkeyed ON true
|
|
71
|
+
-- Its partitions' and inheritance children's too: a write through it reaches their rows and fires theirs.
|
|
72
|
+
CROSS JOIN LATERAL (SELECT ${postgresTreeTriggerNames('c.oid')} AS names) AS fired`, [targets.map((target) => target.schema), targets.map((target) => target.name)]);
|
|
55
73
|
for (const row of rows.rows) {
|
|
56
74
|
if (typeof row.schema !== 'string' ||
|
|
57
75
|
typeof row.name !== 'string' ||
|
|
58
76
|
typeof row.kind !== 'string' ||
|
|
59
|
-
[row.rls, row.triggers, row.rules, row.policies, row.updatable].some((value) => typeof value !== 'boolean') ||
|
|
77
|
+
[row.rls, row.triggers, row.rules, row.policies, row.updatable, row.hierarchy].some((value) => typeof value !== 'boolean') ||
|
|
60
78
|
!Array.isArray(row.trigger_names) ||
|
|
61
79
|
row.trigger_names.some((name) => typeof name !== 'string') ||
|
|
80
|
+
(row.unkeyed_column !== null && typeof row.unkeyed_column !== 'string') ||
|
|
81
|
+
(row.unkeyed_type !== null && typeof row.unkeyed_type !== 'string') ||
|
|
62
82
|
result.has(key(row)))
|
|
63
83
|
return refuse();
|
|
64
84
|
result.set(key(row), row);
|
|
@@ -67,6 +87,275 @@ async function facts(client, targets) {
|
|
|
67
87
|
}
|
|
68
88
|
const lockable = (fact) => fact !== undefined && ['r', 'p'].includes(fact.kind) && fact.updatable;
|
|
69
89
|
const clean = (fact) => !fact.rls && !fact.triggers && !fact.rules && !fact.policies;
|
|
90
|
+
/** Clean but for its triggers: each write is then judged by the triggers it fires (scopedTransaction.ts target). */
|
|
91
|
+
const cleanButTriggers = (fact) => fact.triggers && !fact.rls && !fact.rules && !fact.policies;
|
|
92
|
+
/** The rows of the triggers of `tables`, read on the writer. */
|
|
93
|
+
async function triggerRows(client, tables) {
|
|
94
|
+
const result = await client.query(postgresTriggerStatement(true), [
|
|
95
|
+
tables.map((table) => table.schema),
|
|
96
|
+
tables.map((table) => table.name),
|
|
97
|
+
]);
|
|
98
|
+
return result.rows;
|
|
99
|
+
}
|
|
100
|
+
/** 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. */
|
|
101
|
+
async function readTriggers(client, tables) {
|
|
102
|
+
const byKey = await postgresTriggersByTable(await triggerRows(client, tables), postgresTriggerAnalyzer(client));
|
|
103
|
+
const read = new Map();
|
|
104
|
+
for (const table of tables) {
|
|
105
|
+
const found = byKey.get(key(table));
|
|
106
|
+
// The facts said it has triggers, and the table is pinned against CREATE and DROP TRIGGER: none is a catalog this code misread.
|
|
107
|
+
if (!found)
|
|
108
|
+
return refuse();
|
|
109
|
+
read.set(table.id, found);
|
|
110
|
+
}
|
|
111
|
+
return read;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Before COMMIT, in a transaction that let a write fire a trigger the catalog proved validation-only: the proof's
|
|
115
|
+
* sources read again. A table's triggers cannot change under its pin, but the function a trigger runs, and the
|
|
116
|
+
* functions, operators and casts its conditions resolve to, can (CREATE OR REPLACE FUNCTION takes no lock on the table). Under
|
|
117
|
+
* READ COMMITTED this read sees every change committed before it, so every version a write that has already run
|
|
118
|
+
* could have used: a changed one refuses the transaction.
|
|
119
|
+
*/
|
|
120
|
+
export async function attestPostgresTriggers(client, catalog, tables) {
|
|
121
|
+
if (!tables.size)
|
|
122
|
+
return;
|
|
123
|
+
try {
|
|
124
|
+
const wanted = [...tables].map((id) => {
|
|
125
|
+
const table = catalog.schema.tables.find((candidate) => candidate.id === id);
|
|
126
|
+
const version = catalog.triggerVersions?.get(id);
|
|
127
|
+
if (!table || version === undefined)
|
|
128
|
+
return refuse();
|
|
129
|
+
return { id, schema: table.schema, name: table.name, version };
|
|
130
|
+
});
|
|
131
|
+
// The versions alone: what the proof was made from, not the proof made again.
|
|
132
|
+
const read = postgresTriggerVersions(await triggerRows(client, wanted));
|
|
133
|
+
for (const table of wanted)
|
|
134
|
+
if (read.get(key(table)) !== table.version)
|
|
135
|
+
return refuse();
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (error instanceof Refusal)
|
|
139
|
+
throw error;
|
|
140
|
+
return refuse();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** 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
|
+
const WANTED = `pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid ${EQ} c.relnamespace
|
|
145
|
+
JOIN ROWS FROM (pg_catalog.unnest($1::pg_catalog.text[]), pg_catalog.unnest($2::pg_catalog.text[])) AS wanted(schema, name)
|
|
146
|
+
ON n.nspname ${EQ} wanted.schema AND c.relname ${EQ} wanted.name`;
|
|
147
|
+
/**
|
|
148
|
+
* How a trigger's key equality compares on PostgreSQL, for `ids` (triggerEffects.ts): each column's base type and
|
|
149
|
+
* type modifier with its domains unwrapped, its collation and whether that collation is deterministic; and the
|
|
150
|
+
* column sets each table is unique on as such an equality compares. A unique index counts only where it is valid,
|
|
151
|
+
* immediate (a deferrable one holds duplicates until COMMIT), B-tree, over plain columns of the whole table, and
|
|
152
|
+
* each column is indexed under its own collation and its type's default operator class: an index under "C" on a
|
|
153
|
+
* column whose collation folds case, or under a pattern operator class, is unique by an equality the trigger does not
|
|
154
|
+
* make. `TableMeta.unique` (an App's address, a tenant's bound) is read by looser rules and is left as it is.
|
|
155
|
+
*/
|
|
156
|
+
async function effectKeyFacts(client, ids) {
|
|
157
|
+
// Each once: a table named twice would count each index column twice.
|
|
158
|
+
const at = [...new Set(ids)].map(located);
|
|
159
|
+
const params = [at.map((table) => table.schema), at.map((table) => table.name)];
|
|
160
|
+
const tables = `SELECT c.oid, n.nspname::pg_catalog.text OPERATOR(pg_catalog.||) '.' OPERATOR(pg_catalog.||) c.relname::pg_catalog.text AS id
|
|
161
|
+
FROM ${WANTED}`;
|
|
162
|
+
const columns = await client.query(`WITH t AS (${tables})
|
|
163
|
+
SELECT t.id, a.attname::pg_catalog.text AS name, b.type::pg_catalog.int4 AS type, b.typmod::pg_catalog.int4 AS typmod,
|
|
164
|
+
pg_catalog.format_type(b.type, b.typmod) AS said, a.attcollation::pg_catalog.int4 AS collation,
|
|
165
|
+
coalesce(ln.nspname::pg_catalog.text, '') AS collschema, coalesce(l.collname::pg_catalog.text, '') AS collname,
|
|
166
|
+
coalesce((pg_catalog.to_jsonb(l) OPERATOR(pg_catalog.->>) 'collisdeterministic')::pg_catalog.bool, true) AS exact,
|
|
167
|
+
${postgresKeyType('b.type')} AS keyable, ${saidType('a.atttypid', 'a.atttypmod', 'b.type', 'b.typmod')} AS declared
|
|
168
|
+
FROM t JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} t.oid AND a.attnum ${GT} 0 AND NOT a.attisdropped
|
|
169
|
+
CROSS JOIN LATERAL ${baseType('a.atttypid', 'a.atttypmod')} AS b
|
|
170
|
+
LEFT JOIN pg_catalog.pg_collation l ON l.oid ${EQ} a.attcollation
|
|
171
|
+
LEFT JOIN pg_catalog.pg_namespace ln ON ln.oid ${EQ} l.collnamespace`, params);
|
|
172
|
+
const keys = await client.query(`WITH t AS (${tables})
|
|
173
|
+
SELECT t.id, pg_catalog.array_agg(a.attname::pg_catalog.text ORDER BY k.ord) AS columns,
|
|
174
|
+
pg_catalog.bool_and(k.coll ${EQ} a.attcollation AND k.opclass ${EQ} ${defaultBtreeClass('b.type')}) AS own
|
|
175
|
+
FROM t
|
|
176
|
+
JOIN pg_catalog.pg_index i ON i.indrelid ${EQ} t.oid
|
|
177
|
+
JOIN pg_catalog.pg_class ic ON ic.oid ${EQ} i.indexrelid
|
|
178
|
+
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[]))
|
|
179
|
+
WITH ORDINALITY AS k(attnum, coll, opclass, ord)
|
|
180
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} t.oid AND a.attnum ${EQ} k.attnum
|
|
181
|
+
CROSS JOIN LATERAL ${baseType('a.atttypid', 'a.atttypmod')} AS b
|
|
182
|
+
WHERE i.indisunique AND i.indisvalid AND i.indimmediate AND i.indpred IS NULL AND i.indexprs IS NULL
|
|
183
|
+
AND i.indnatts ${EQ} i.indnkeyatts AND ic.relam ${EQ} 403::pg_catalog.oid
|
|
184
|
+
GROUP BY t.id, i.indexrelid
|
|
185
|
+
HAVING pg_catalog.count(*) ${EQ} pg_catalog.max(i.indnkeyatts)`, params);
|
|
186
|
+
const compared = new Map();
|
|
187
|
+
for (const row of columns.rows) {
|
|
188
|
+
if (typeof row.id !== 'string' ||
|
|
189
|
+
typeof row.name !== 'string' ||
|
|
190
|
+
typeof row.said !== 'string' ||
|
|
191
|
+
typeof row.exact !== 'boolean' ||
|
|
192
|
+
typeof row.keyable !== 'boolean' ||
|
|
193
|
+
typeof row.declared !== 'string')
|
|
194
|
+
return refuse();
|
|
195
|
+
compared.set(`${row.id}\u0000${row.name}`, {
|
|
196
|
+
type: `${String(row.type)}:${String(row.typmod)}`,
|
|
197
|
+
collation: String(row.collation),
|
|
198
|
+
exact: row.exact,
|
|
199
|
+
keyable: row.keyable,
|
|
200
|
+
declared: row.declared,
|
|
201
|
+
// Named with its schema: two collations of one name in two schemas are two collations (an ICU "sv" and a libc one).
|
|
202
|
+
said: `${row.said}${row.collname ? ` COLLATE ${POSTGRES_STYLE.quote(String(row.collschema))}.${POSTGRES_STYLE.quote(String(row.collname))}` : ''}`,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
const unique = new Map();
|
|
206
|
+
for (const row of keys.rows) {
|
|
207
|
+
if (typeof row.id !== 'string' || !Array.isArray(row.columns) || row.columns.some((name) => typeof name !== 'string'))
|
|
208
|
+
return refuse();
|
|
209
|
+
if (row.own === true)
|
|
210
|
+
unique.set(row.id, [...(unique.get(row.id) ?? []), row.columns]);
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
keys: (table) => unique.get(table.id) ?? [],
|
|
214
|
+
comparison: (table, column) => compared.get(`${table.id}\u0000${column}`),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/** A type as `ri_triggers.c` casts to it: its schema and name, each quoted where it needs it. */
|
|
218
|
+
const castType = (oid) => `(SELECT pg_catalog.quote_ident(tn.nspname::pg_catalog.text) OPERATOR(pg_catalog.||) '.'
|
|
219
|
+
OPERATOR(pg_catalog.||) pg_catalog.quote_ident(t.typname::pg_catalog.text)
|
|
220
|
+
FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace tn ON tn.oid ${EQ} t.typnamespace WHERE t.oid ${EQ} ${oid})`;
|
|
221
|
+
/* Whether a type is a pseudo-type: a polymorphic operator's input (an enum's `anyenum`), which a side is not cast to.
|
|
222
|
+
The operator resolves it from the side's own type. */
|
|
223
|
+
const pseudo = (oid) => `EXISTS (SELECT FROM pg_catalog.pg_type pt WHERE pt.oid ${EQ} ${oid} AND pt.typtype ${EQ} 'p')`;
|
|
224
|
+
const CONCAT = 'OPERATOR(pg_catalog.||)';
|
|
225
|
+
/**
|
|
226
|
+
* A column's type as a cast names it whatever the search_path: its schema and name from pg_type, each quoted where it
|
|
227
|
+
* needs it (castType), then its modifier as the digits the type's own input reads back — `pg_catalog."numeric"(10,2)`,
|
|
228
|
+
* `pg_catalog.bpchar(3)`. `format_type` said `text` and `character(3)`: a name found through the search_path when the
|
|
229
|
+
* statement runs, which a type made after the catalog was read (a domain `public.text` over `name`, with pg_catalog
|
|
230
|
+
* after public) answered, and a check that read 64 characters as 63 found another key than the foreign key. The
|
|
231
|
+
* modifier is what `format_type` adds to the type's bare name, a parenthesised list for every type a reference may be
|
|
232
|
+
* that has one (varchar, char, numeric: keyTypes.ts). NULL where it is not: a type a check cannot name.
|
|
233
|
+
*/
|
|
234
|
+
const sqlType = (oid, typmod) => `(SELECT CASE WHEN m.said IS NOT NULL THEN
|
|
235
|
+
pg_catalog.quote_ident(tn.nspname::pg_catalog.text) ${CONCAT} '.' ${CONCAT} pg_catalog.quote_ident(t.typname::pg_catalog.text) ${CONCAT} m.said END
|
|
236
|
+
FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace tn ON tn.oid ${EQ} t.typnamespace
|
|
237
|
+
CROSS JOIN LATERAL (SELECT CASE
|
|
238
|
+
WHEN ${typmod} ${LT} 0 THEN ''
|
|
239
|
+
WHEN pg_catalog.left(pg_catalog.format_type(t.oid, ${typmod}), pg_catalog.length(pg_catalog.format_type(t.oid, NULL)))
|
|
240
|
+
${EQ} pg_catalog.format_type(t.oid, NULL)
|
|
241
|
+
THEN pg_catalog.substr(pg_catalog.format_type(t.oid, ${typmod}), pg_catalog.length(pg_catalog.format_type(t.oid, NULL)) ${PLUS} 1)
|
|
242
|
+
END AS said) AS m
|
|
243
|
+
WHERE t.oid ${EQ} ${oid})`;
|
|
244
|
+
/**
|
|
245
|
+
* How each foreign key of `schema` compares a reference with its parent's key (ScopeCatalog.references), as the
|
|
246
|
+
* database's own check states it (ri_triggers.c RI_FKey_check, ruleutils.c generate_operator_clause): the parent
|
|
247
|
+
* column, cast to the operator's left type where its own is another, then `OPERATOR(schema.name)` of the constraint's
|
|
248
|
+
* own equality (`conpfeqop`), then the value read as the referencing column's type, typmod and all and named by its
|
|
249
|
+
* schema (sqlType), and cast to the operator's right type where that is another. Neither side is cast to a
|
|
250
|
+
* pseudo-type (`pseudo`): an enum's `anyenum` is resolved from the side's own type. A parent check written so finds the
|
|
251
|
+
* row the foreign key finds: by `=` and the value as given, a char(3) 'ab ' found the text key 'ab ', where the foreign
|
|
252
|
+
* key, comparing as text, finds 'ab'. A key whose columns or operators the catalog does not give whole, either side of
|
|
253
|
+
* 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
|
|
254
|
+
* through it.
|
|
255
|
+
*/
|
|
256
|
+
async function foreignKeyComparisons(client, schema) {
|
|
257
|
+
const at = schema.tables.map((table) => ({ schema: table.schema, name: table.name }));
|
|
258
|
+
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,
|
|
259
|
+
k.ord::pg_catalog.int4 AS ord, fa.attname::pg_catalog.text AS child, pa.attname::pg_catalog.text AS parent,
|
|
260
|
+
${sqlType('fa.atttypid', 'fa.atttypmod')} AS type, ${writtenType('fa.atttypid', 'fa.atttypmod')} AS written,
|
|
261
|
+
${postgresKeyType('fb.type')} AS child_keyable, ${saidType('fa.atttypid', 'fa.atttypmod', 'fb.type', 'fb.typmod')} AS child_said,
|
|
262
|
+
${postgresKeyType('pb.type')} AS parent_keyable, ${saidType('pa.atttypid', 'pa.atttypmod', 'pb.type', 'pb.typmod')} AS parent_said,
|
|
263
|
+
pg_catalog.quote_ident(opn.nspname::pg_catalog.text) OPERATOR(pg_catalog.||) '.' OPERATOR(pg_catalog.||) o.oprname::pg_catalog.text AS operator,
|
|
264
|
+
CASE WHEN pa.atttypid ${EQ} o.oprleft OR ${pseudo('o.oprleft')} THEN NULL ELSE ${castType('o.oprleft')} END AS "left",
|
|
265
|
+
CASE WHEN fa.atttypid ${EQ} o.oprright OR ${pseudo('o.oprright')} THEN NULL ELSE ${castType('o.oprright')} END AS "right"
|
|
266
|
+
FROM ${WANTED}
|
|
267
|
+
-- Never a clone that points at a partition, as the schema reads them (postgresCatalog.ts).
|
|
268
|
+
JOIN pg_catalog.pg_constraint con ON con.conrelid ${EQ} c.oid AND con.contype ${EQ} 'f'
|
|
269
|
+
AND NOT EXISTS (SELECT FROM pg_catalog.pg_constraint pc WHERE pc.oid ${EQ} con.conparentid AND pc.confrelid ${NE} con.confrelid)
|
|
270
|
+
CROSS JOIN LATERAL ROWS FROM (pg_catalog.unnest(con.conkey), pg_catalog.unnest(con.confkey), pg_catalog.unnest(con.conpfeqop))
|
|
271
|
+
WITH ORDINALITY AS k(child, parent, operator, ord)
|
|
272
|
+
LEFT JOIN pg_catalog.pg_attribute fa ON fa.attrelid ${EQ} con.conrelid AND fa.attnum ${EQ} k.child
|
|
273
|
+
LEFT JOIN pg_catalog.pg_attribute pa ON pa.attrelid ${EQ} con.confrelid AND pa.attnum ${EQ} k.parent
|
|
274
|
+
LEFT JOIN LATERAL ${baseType('fa.atttypid', 'fa.atttypmod')} AS fb ON true
|
|
275
|
+
LEFT JOIN LATERAL ${baseType('pa.atttypid', 'pa.atttypmod')} AS pb ON true
|
|
276
|
+
LEFT JOIN pg_catalog.pg_operator o ON o.oid ${EQ} k.operator
|
|
277
|
+
LEFT JOIN pg_catalog.pg_namespace opn ON opn.oid ${EQ} o.oprnamespace
|
|
278
|
+
ORDER BY 1, 2, 3, 4`, [at.map((table) => table.schema), at.map((table) => table.name)]);
|
|
279
|
+
const read = new Map();
|
|
280
|
+
for (const row of result.rows) {
|
|
281
|
+
const id = `${String(row.schema)}.${String(row.table)}\u0000${String(row.name)}`;
|
|
282
|
+
read.set(id, [...(read.get(id) ?? []), row]);
|
|
283
|
+
}
|
|
284
|
+
const comparisons = new Map();
|
|
285
|
+
for (const fk of schema.foreignKeys) {
|
|
286
|
+
const rows = read.get(`${fk.from.table}\u0000${fk.name}`) ?? [];
|
|
287
|
+
const whole = rows.length === fk.from.columns.length &&
|
|
288
|
+
rows.every((row, index) => row.ord === index + 1 &&
|
|
289
|
+
row.child === fk.from.columns[index] &&
|
|
290
|
+
row.parent === fk.to.columns[index] &&
|
|
291
|
+
(row.type === null || typeof row.type === 'string') &&
|
|
292
|
+
typeof row.written === 'string' &&
|
|
293
|
+
typeof row.child_keyable === 'boolean' &&
|
|
294
|
+
typeof row.parent_keyable === 'boolean' &&
|
|
295
|
+
typeof row.child_said === 'string' &&
|
|
296
|
+
typeof row.parent_said === 'string' &&
|
|
297
|
+
typeof row.operator === 'string' &&
|
|
298
|
+
(row.left === null || typeof row.left === 'string') &&
|
|
299
|
+
(row.right === null || typeof row.right === 'string'));
|
|
300
|
+
const unnamed = rows.findIndex((row) => row.type === null);
|
|
301
|
+
// Each side a row's identity (keyTypes.ts): the key pointed at, then the reference.
|
|
302
|
+
const parent = rows.findIndex((row) => row.parent_keyable !== true);
|
|
303
|
+
const child = rows.findIndex((row) => row.child_keyable !== true);
|
|
304
|
+
comparisons.set(referenceKey(fk), !whole
|
|
305
|
+
? {
|
|
306
|
+
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.`,
|
|
307
|
+
}
|
|
308
|
+
: parent !== -1
|
|
309
|
+
? { refused: `${keyTypeRefusal('postgres', fk.to.table, fk.to.columns[parent], rows[parent].parent_said)}.` }
|
|
310
|
+
: child !== -1
|
|
311
|
+
? { refused: `${keyTypeRefusal('postgres', fk.from.table, fk.from.columns[child], rows[child].child_said)}.` }
|
|
312
|
+
: unnamed !== -1
|
|
313
|
+
? {
|
|
314
|
+
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.`,
|
|
315
|
+
}
|
|
316
|
+
: {
|
|
317
|
+
columns: rows.map((row) => ({
|
|
318
|
+
// Coerced as the write coerces it (postgresCatalog.ts writtenType): a domain read as the type it is over.
|
|
319
|
+
type: row.written,
|
|
320
|
+
equality: {
|
|
321
|
+
operator: row.operator,
|
|
322
|
+
type: row.type,
|
|
323
|
+
...(typeof row.left === 'string' ? { left: row.left } : {}),
|
|
324
|
+
...(typeof row.right === 'string' ? { right: row.right } : {}),
|
|
325
|
+
},
|
|
326
|
+
})),
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
return comparisons;
|
|
330
|
+
}
|
|
331
|
+
/** What blocks a scoped write to a table beyond its triggers, as a refusal names it; undefined where nothing does. */
|
|
332
|
+
const blockerOf = (fact) => !['r', 'p'].includes(fact.kind)
|
|
333
|
+
? 'a kind a scoped write cannot target'
|
|
334
|
+
: !fact.updatable
|
|
335
|
+
? 'no UPDATE privilege for the role that writes'
|
|
336
|
+
: fact.rls || fact.rules || fact.policies
|
|
337
|
+
? [fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : ''].filter(Boolean).join(' and ')
|
|
338
|
+
: undefined;
|
|
339
|
+
/**
|
|
340
|
+
* For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
|
|
341
|
+
* (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
|
|
342
|
+
* hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
|
|
343
|
+
*/
|
|
344
|
+
export async function effectCatalogFacts(client, given) {
|
|
345
|
+
const ids = [...new Set(given)];
|
|
346
|
+
const read = await facts(client, ids.map(located));
|
|
347
|
+
const blocked = new Map();
|
|
348
|
+
const hierarchy = new Set();
|
|
349
|
+
for (const id of ids) {
|
|
350
|
+
const fact = read.get(key(located(id)));
|
|
351
|
+
if (fact?.hierarchy)
|
|
352
|
+
hierarchy.add(id);
|
|
353
|
+
const blocker = fact && blockerOf(fact);
|
|
354
|
+
if (blocker)
|
|
355
|
+
blocked.set(id, blocker);
|
|
356
|
+
}
|
|
357
|
+
return { ...(await effectKeyFacts(client, ids)), hierarchy, blocked };
|
|
358
|
+
}
|
|
70
359
|
/** What makes a table unclean, as a refusal names it. */
|
|
71
360
|
const unclean = (fact) => [fact.triggers ? triggerNames(fact.trigger_names) : '', fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : '']
|
|
72
361
|
.filter(Boolean)
|
|
@@ -88,24 +377,75 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
|
|
|
88
377
|
const held = new Set(pinned.map(key));
|
|
89
378
|
const writable = new Set();
|
|
90
379
|
const blockedBy = new Map();
|
|
380
|
+
const unkeyed = new Map();
|
|
381
|
+
const hierarchy = new Set();
|
|
91
382
|
const locks = new Set();
|
|
383
|
+
const withTriggers = [];
|
|
92
384
|
for (const table of schema.tables) {
|
|
93
385
|
const fact = (await after).get(key(table));
|
|
94
386
|
// A relation the catalog listed a moment ago and cannot describe now
|
|
95
387
|
// was dropped under this transaction; nothing here may rely on it.
|
|
96
388
|
if (!fact || table.id !== key(table))
|
|
97
389
|
return refuse();
|
|
390
|
+
if (fact.unkeyed_column !== null)
|
|
391
|
+
unkeyed.set(table.id, keyTypeRefusal('postgres', table.id, fact.unkeyed_column, fact.unkeyed_type ?? 'unknown'));
|
|
392
|
+
// Never a target, but still lockable: a reference to a partitioned table holds its parent row through it.
|
|
393
|
+
if (fact.hierarchy)
|
|
394
|
+
hierarchy.add(table.id);
|
|
98
395
|
if (!lockable(fact))
|
|
99
396
|
continue;
|
|
100
397
|
locks.add(table.id);
|
|
398
|
+
if (fact.hierarchy)
|
|
399
|
+
continue;
|
|
101
400
|
// Writable means pinned: a table that became clean after the pin
|
|
102
401
|
// decision could be dirtied again before COMMIT, so it stays read-only.
|
|
103
|
-
|
|
402
|
+
const ordinary = held.has(table.id) && !table.isView && table.columns.some((column) => column.primaryKey);
|
|
403
|
+
if (ordinary && clean(fact))
|
|
104
404
|
writable.add(table.id);
|
|
405
|
+
else if (ordinary && cleanButTriggers(fact))
|
|
406
|
+
withTriggers.push({ id: table.id, schema: table.schema, name: table.name });
|
|
105
407
|
else if (!clean(fact))
|
|
106
408
|
blockedBy.set(table.id, unclean(fact));
|
|
107
409
|
}
|
|
108
|
-
|
|
410
|
+
/* Read only where a table has triggers: a database without them asks nothing more than it did. */
|
|
411
|
+
const read = withTriggers.length ? await readTriggers(client, withTriggers) : undefined;
|
|
412
|
+
const readTriggered = new Map([...(read ?? [])].map(([id, entry]) => [id, entry.triggers]));
|
|
413
|
+
const triggerVersions = new Map([...(read ?? [])].map(([id, entry]) => [id, entry.version]));
|
|
414
|
+
/* What else a write to a writable table runs — a default, a CHECK, a domain — judged as a trigger that is not
|
|
415
|
+
validation-only where it calls a function of the database's: a table with such code is written only by the
|
|
416
|
+
writes that run none of it. Read before the effects are judged, so a trigger's write to such a table is
|
|
417
|
+
refused as the person's own would be. */
|
|
418
|
+
const written = schema.tables.filter((table) => writable.has(table.id) || readTriggered.has(table.id));
|
|
419
|
+
const code = await readPostgresTableCode(client, written);
|
|
420
|
+
for (const table of written) {
|
|
421
|
+
const own = code.get(key(table));
|
|
422
|
+
if (!own)
|
|
423
|
+
continue;
|
|
424
|
+
writable.delete(table.id);
|
|
425
|
+
readTriggered.set(table.id, [...(readTriggered.get(table.id) ?? []), ...own]);
|
|
426
|
+
}
|
|
427
|
+
// Keyed effects are judged against the catalog they run in (triggerEffects.ts); a database without them asks nothing more.
|
|
428
|
+
const triggered = [...readTriggered.values()].some((triggers) => triggers.some((trigger) => trigger.effects))
|
|
429
|
+
? (await import('./triggerEffects.js')).resolveTriggerEffects({
|
|
430
|
+
schema,
|
|
431
|
+
writable,
|
|
432
|
+
triggered: readTriggered,
|
|
433
|
+
foldCase: false,
|
|
434
|
+
hierarchy,
|
|
435
|
+
...(await effectKeyFacts(client, [...writable, ...readTriggered.keys()])),
|
|
436
|
+
})
|
|
437
|
+
: readTriggered;
|
|
438
|
+
return {
|
|
439
|
+
schema,
|
|
440
|
+
writable,
|
|
441
|
+
references: await foreignKeyComparisons(client, schema),
|
|
442
|
+
...(blockedBy.size ? { blockedBy } : {}),
|
|
443
|
+
...(unkeyed.size ? { unkeyed } : {}),
|
|
444
|
+
...(hierarchy.size ? { hierarchy } : {}),
|
|
445
|
+
...(triggered.size ? { triggered, triggerVersions } : {}),
|
|
446
|
+
lockable: locks,
|
|
447
|
+
pinned: relations,
|
|
448
|
+
};
|
|
109
449
|
}
|
|
110
450
|
catch (error) {
|
|
111
451
|
if (error instanceof Refusal)
|