@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,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The triggers on a table a scoped write may target, and which of them a given
|
|
3
|
+
* write can fire.
|
|
4
|
+
*
|
|
5
|
+
* A row policy bounds the rows a write reaches; a trigger runs inside that
|
|
6
|
+
* write and reaches whatever its body says, which the policy cannot see. So a
|
|
7
|
+
* table with a trigger used to be refused as a target outright, for every
|
|
8
|
+
* write — and a field report's ledger lost its integrity triggers to get past
|
|
9
|
+
* it: a validation-only `BEFORE UPDATE OF posted_minor` refused an update of
|
|
10
|
+
* `status` that could never fire it.
|
|
11
|
+
*
|
|
12
|
+
* Two facts now decide it per write, not per table, and each fails closed:
|
|
13
|
+
*
|
|
14
|
+
* - Whether the write can fire the trigger at all. An INSERT fires the INSERT
|
|
15
|
+
* triggers, a DELETE the DELETE triggers, and an UPDATE every UPDATE trigger
|
|
16
|
+
* without a column list and those whose `UPDATE OF` list meets the columns it
|
|
17
|
+
* sets. Both engines fire on the SET list, not on whether a value changed.
|
|
18
|
+
* A definition the engine cannot read is taken to fire on every write.
|
|
19
|
+
* - Whether the trigger is validation-only: it reads only the row being
|
|
20
|
+
* written (NEW and OLD) and literals, raises or does nothing, and writes
|
|
21
|
+
* nothing — not even NEW. Such a trigger is a CHECK constraint written as
|
|
22
|
+
* code: what it reads the policy already admitted (the row is in scope), and
|
|
23
|
+
* what it does is refuse the statement. One that reads another table could
|
|
24
|
+
* say, by whether it raises, that a row the policy hides exists, so it is not
|
|
25
|
+
* validation-only, however little it writes. The grammar each engine
|
|
26
|
+
* accepts is narrow on purpose (sqliteTriggers.ts, postgresTriggers.ts):
|
|
27
|
+
* anything else is not proven, and blocks the writes that fire it.
|
|
28
|
+
*/
|
|
29
|
+
export type TriggerEvent = 'insert' | 'update' | 'delete';
|
|
30
|
+
/** A column of the row being written, as a trigger names it: `NEW.account_id`, `OLD.id`. */
|
|
31
|
+
export interface EffectRef {
|
|
32
|
+
readonly row: 'new' | 'old';
|
|
33
|
+
readonly column: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A value a keyed effect writes: a column of the row being written, a literal, or an expression in the grammar
|
|
37
|
+
* whose value only the trigger computes (`posted_minor + NEW.amount`, `CURRENT_TIMESTAMP`). Only the first two are
|
|
38
|
+
* known before the write.
|
|
39
|
+
*/
|
|
40
|
+
export type EffectTerm = EffectRef | {
|
|
41
|
+
readonly literal: string | number | null;
|
|
42
|
+
} | {
|
|
43
|
+
readonly expression: true;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* One thing a trigger does beyond checking its own row, in the keyed-effect grammar (docs/trigger-effects.md): it
|
|
47
|
+
* writes, inserts or deletes one row of a table it names by a key equal to columns of NEW or OLD, or reads one
|
|
48
|
+
* column of such a row in a condition. `table` is the name the body gives it (PostgreSQL `schema.name`), until the
|
|
49
|
+
* catalog resolves it to a table id (triggerEffects.ts).
|
|
50
|
+
*/
|
|
51
|
+
export interface TriggerEffect {
|
|
52
|
+
readonly kind: 'update' | 'insert' | 'delete' | 'read';
|
|
53
|
+
readonly table: string;
|
|
54
|
+
/** update, delete and read: the row it reaches, each key column equal to a column of NEW or OLD. */
|
|
55
|
+
readonly key?: Readonly<Record<string, EffectRef>>;
|
|
56
|
+
/** update: the columns it sets; insert: the columns it gives; read: the column it reads (a null literal). */
|
|
57
|
+
readonly values?: Readonly<Record<string, EffectTerm>>;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* One trigger on a table, as the writer's catalog read it — or other code a write runs that the policy cannot bound,
|
|
61
|
+
* judged the same way: a CHECK constraint, a default or a domain calling a function of the database's
|
|
62
|
+
* (postgresTriggers.ts readPostgresTableCode). Such code is never validation-only.
|
|
63
|
+
*/
|
|
64
|
+
export interface ScopeTrigger {
|
|
65
|
+
readonly name: string;
|
|
66
|
+
/** What it is, as a refusal names it, when not a trigger: `CHECK constraint`, `default of column`, `domain`. */
|
|
67
|
+
readonly kind?: string;
|
|
68
|
+
/** The writes that may fire it. */
|
|
69
|
+
readonly events: readonly TriggerEvent[];
|
|
70
|
+
/** An update fires it only when it sets one of these columns (`UPDATE OF`). Absent: every update fires it. */
|
|
71
|
+
readonly columns?: readonly string[];
|
|
72
|
+
/** Proven validation-only (above): it does not block the writes that fire it. */
|
|
73
|
+
readonly validates: boolean;
|
|
74
|
+
/** Why it is not, as a refusal and `mistri check` say it: `it writes rows`, `it reads another table`. */
|
|
75
|
+
readonly why?: string;
|
|
76
|
+
/**
|
|
77
|
+
* What it does, where its body is in the keyed-effect grammar and does more than validate: the effects an App
|
|
78
|
+
* accepts by naming the trigger (`resources.<table>.triggers`). Absent where the body leaves the grammar.
|
|
79
|
+
*/
|
|
80
|
+
readonly effects?: readonly TriggerEffect[];
|
|
81
|
+
/** Why the effects cannot be accepted even when named, once the catalog has judged them (triggerEffects.ts). */
|
|
82
|
+
readonly unaccepted?: string;
|
|
83
|
+
/** `sha256:<hex>` of the normalized definition: what authority.lock approves, so a changed body is a stale lock. */
|
|
84
|
+
readonly digest?: string;
|
|
85
|
+
/** The longest chain of accepted-kind triggers its effects start, itself included (triggerEffects.ts). */
|
|
86
|
+
readonly depth?: number;
|
|
87
|
+
}
|
|
88
|
+
/** Why a trigger's effects are not accepted where its definition is not plain (plainDefinition). */
|
|
89
|
+
export declare const PLAIN = "its definition holds characters outside plain SQL, or an IN without a list";
|
|
90
|
+
/**
|
|
91
|
+
* Whether a definition is plain enough for its effects to be accepted: outside its literals, quoted names and
|
|
92
|
+
* comments, only ASCII and the engines' common whitespace (no U+00A0, which JavaScript's `\s` takes for space and
|
|
93
|
+
* SQLite for part of a name; no vertical tab), no `$`, and every IN followed by a parenthesized list. Effects widen
|
|
94
|
+
* what a write reaches, so they are held to the strictest reading even where validation is not.
|
|
95
|
+
*/
|
|
96
|
+
export declare function plainDefinition(sql: string, tokens: readonly {
|
|
97
|
+
kind: string;
|
|
98
|
+
text?: string;
|
|
99
|
+
upper?: string;
|
|
100
|
+
}[], dialect: 'sqlite' | 'postgres'): boolean;
|
|
101
|
+
/** A write as the triggers see it: its kind, and for an update the columns it sets. */
|
|
102
|
+
export interface TriggeringWrite {
|
|
103
|
+
readonly kind: TriggerEvent;
|
|
104
|
+
readonly set?: readonly string[];
|
|
105
|
+
}
|
|
106
|
+
/** The triggers `write` can fire. */
|
|
107
|
+
export declare function firedBy(triggers: readonly ScopeTrigger[], write: TriggeringWrite, foldCase: boolean): ScopeTrigger[];
|
|
108
|
+
/** The triggers that keep `write` from running under a row policy: those it fires that are not validation-only. */
|
|
109
|
+
export declare function blockingTriggers(triggers: readonly ScopeTrigger[], write: TriggeringWrite, foldCase: boolean): ScopeTrigger[];
|
|
110
|
+
/** A write as a sentence names it: `an insert`, `an update of status, note`, `a delete`. */
|
|
111
|
+
export declare function sayWrite(write: TriggeringWrite): string;
|
|
112
|
+
/**
|
|
113
|
+
* Triggers as a refusal and `mistri check` name them: `the trigger "post" (it writes rows)`; other code by what it is,
|
|
114
|
+
* `the CHECK constraint "seen" (it calls public.peek(text))`.
|
|
115
|
+
*/
|
|
116
|
+
export declare const sayTriggers: (triggers: readonly ScopeTrigger[]) => string;
|
|
117
|
+
/** What a write does to the code it runs, as a refusal says it: `fires` a trigger, `runs` a constraint or a default. */
|
|
118
|
+
export declare const sayRuns: (triggers: readonly ScopeTrigger[]) => string;
|
|
119
|
+
/** The writes a set of triggers blocks, as `mistri check` names them: `inserts`, `updates of posted_minor`, `deletes`. */
|
|
120
|
+
export declare function sayBlocked(triggers: readonly ScopeTrigger[]): string[];
|
|
121
|
+
/** Whether the triggers refuse every insert, every update and every delete: no write to the table can run. */
|
|
122
|
+
export declare function blocksEveryWrite(triggers: readonly ScopeTrigger[]): boolean;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The triggers on a table a scoped write may target, and which of them a given
|
|
3
|
+
* write can fire.
|
|
4
|
+
*
|
|
5
|
+
* A row policy bounds the rows a write reaches; a trigger runs inside that
|
|
6
|
+
* write and reaches whatever its body says, which the policy cannot see. So a
|
|
7
|
+
* table with a trigger used to be refused as a target outright, for every
|
|
8
|
+
* write — and a field report's ledger lost its integrity triggers to get past
|
|
9
|
+
* it: a validation-only `BEFORE UPDATE OF posted_minor` refused an update of
|
|
10
|
+
* `status` that could never fire it.
|
|
11
|
+
*
|
|
12
|
+
* Two facts now decide it per write, not per table, and each fails closed:
|
|
13
|
+
*
|
|
14
|
+
* - Whether the write can fire the trigger at all. An INSERT fires the INSERT
|
|
15
|
+
* triggers, a DELETE the DELETE triggers, and an UPDATE every UPDATE trigger
|
|
16
|
+
* without a column list and those whose `UPDATE OF` list meets the columns it
|
|
17
|
+
* sets. Both engines fire on the SET list, not on whether a value changed.
|
|
18
|
+
* A definition the engine cannot read is taken to fire on every write.
|
|
19
|
+
* - Whether the trigger is validation-only: it reads only the row being
|
|
20
|
+
* written (NEW and OLD) and literals, raises or does nothing, and writes
|
|
21
|
+
* nothing — not even NEW. Such a trigger is a CHECK constraint written as
|
|
22
|
+
* code: what it reads the policy already admitted (the row is in scope), and
|
|
23
|
+
* what it does is refuse the statement. One that reads another table could
|
|
24
|
+
* say, by whether it raises, that a row the policy hides exists, so it is not
|
|
25
|
+
* validation-only, however little it writes. The grammar each engine
|
|
26
|
+
* accepts is narrow on purpose (sqliteTriggers.ts, postgresTriggers.ts):
|
|
27
|
+
* anything else is not proven, and blocks the writes that fire it.
|
|
28
|
+
*/
|
|
29
|
+
/** Why a trigger's effects are not accepted where its definition is not plain (plainDefinition). */
|
|
30
|
+
export const PLAIN = 'its definition holds characters outside plain SQL, or an IN without a list';
|
|
31
|
+
/**
|
|
32
|
+
* Whether a definition is plain enough for its effects to be accepted: outside its literals, quoted names and
|
|
33
|
+
* comments, only ASCII and the engines' common whitespace (no U+00A0, which JavaScript's `\s` takes for space and
|
|
34
|
+
* SQLite for part of a name; no vertical tab), no `$`, and every IN followed by a parenthesized list. Effects widen
|
|
35
|
+
* what a write reaches, so they are held to the strictest reading even where validation is not.
|
|
36
|
+
*/
|
|
37
|
+
export function plainDefinition(sql, tokens, dialect) {
|
|
38
|
+
let i = 0;
|
|
39
|
+
while (i < sql.length) {
|
|
40
|
+
const char = sql[i];
|
|
41
|
+
const close = char === "'"
|
|
42
|
+
? "'"
|
|
43
|
+
: char === '"'
|
|
44
|
+
? '"'
|
|
45
|
+
: dialect === 'sqlite' && char === '`'
|
|
46
|
+
? '`'
|
|
47
|
+
: dialect === 'sqlite' && char === '['
|
|
48
|
+
? ']'
|
|
49
|
+
: undefined;
|
|
50
|
+
if (close) {
|
|
51
|
+
const end = sql.indexOf(close, i + 1);
|
|
52
|
+
if (end === -1)
|
|
53
|
+
return false;
|
|
54
|
+
i = end + 1;
|
|
55
|
+
}
|
|
56
|
+
else if (sql.startsWith('--', i)) {
|
|
57
|
+
const end = sql.indexOf('\n', i);
|
|
58
|
+
i = end === -1 ? sql.length : end + 1;
|
|
59
|
+
}
|
|
60
|
+
else if (sql.startsWith('/*', i)) {
|
|
61
|
+
const end = sql.indexOf('*/', i + 2);
|
|
62
|
+
if (end === -1)
|
|
63
|
+
return false;
|
|
64
|
+
i = end + 2;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
const code = char.charCodeAt(0);
|
|
68
|
+
if (code >= 0x7f || char === '$' || (code < 0x20 && !'\t\n\f\r'.includes(char)))
|
|
69
|
+
return false;
|
|
70
|
+
i += 1;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return tokens.every((token, index) => token.upper !== 'IN' || (tokens[index + 1]?.kind === 'op' && tokens[index + 1]?.text === '('));
|
|
74
|
+
}
|
|
75
|
+
/* SQLite matches a column name in `UPDATE OF` as it matches every identifier, folding ASCII case; PostgreSQL names
|
|
76
|
+
an attribute exactly. */
|
|
77
|
+
const foldedName = (name) => name.replace(/[A-Z]/g, (char) => char.toLowerCase());
|
|
78
|
+
/** The triggers `write` can fire. */
|
|
79
|
+
export function firedBy(triggers, write, foldCase) {
|
|
80
|
+
const same = foldCase ? foldedName : (name) => name;
|
|
81
|
+
const set = new Set((write.set ?? []).map(same));
|
|
82
|
+
return triggers.filter((trigger) => trigger.events.includes(write.kind) &&
|
|
83
|
+
(write.kind !== 'update' ||
|
|
84
|
+
trigger.columns === undefined ||
|
|
85
|
+
write.set === undefined ||
|
|
86
|
+
trigger.columns.some((column) => set.has(same(column)))));
|
|
87
|
+
}
|
|
88
|
+
/** The triggers that keep `write` from running under a row policy: those it fires that are not validation-only. */
|
|
89
|
+
export function blockingTriggers(triggers, write, foldCase) {
|
|
90
|
+
return firedBy(triggers, write, foldCase).filter((trigger) => !trigger.validates);
|
|
91
|
+
}
|
|
92
|
+
/** A write as a sentence names it: `an insert`, `an update of status, note`, `a delete`. */
|
|
93
|
+
export function sayWrite(write) {
|
|
94
|
+
if (write.kind === 'insert')
|
|
95
|
+
return 'an insert';
|
|
96
|
+
if (write.kind === 'delete')
|
|
97
|
+
return 'a delete';
|
|
98
|
+
return write.set?.length ? `an update of ${write.set.join(', ')}` : 'an update';
|
|
99
|
+
}
|
|
100
|
+
const said = (trigger) => `${JSON.stringify(trigger.name)} (${trigger.why ?? 'it is not validation-only'})`;
|
|
101
|
+
/**
|
|
102
|
+
* Triggers as a refusal and `mistri check` name them: `the trigger "post" (it writes rows)`; other code by what it is,
|
|
103
|
+
* `the CHECK constraint "seen" (it calls public.peek(text))`.
|
|
104
|
+
*/
|
|
105
|
+
export const sayTriggers = (triggers) => triggers.every((trigger) => trigger.kind === undefined)
|
|
106
|
+
? `the trigger${triggers.length === 1 ? '' : 's'} ${triggers.map(said).join(', ')}`
|
|
107
|
+
: triggers.map((trigger) => `the ${trigger.kind ?? 'trigger'} ${said(trigger)}`).join(', ');
|
|
108
|
+
/** What a write does to the code it runs, as a refusal says it: `fires` a trigger, `runs` a constraint or a default. */
|
|
109
|
+
export const sayRuns = (triggers) => triggers.every((trigger) => trigger.kind === undefined) ? 'fires' : 'runs';
|
|
110
|
+
/** The writes a set of triggers blocks, as `mistri check` names them: `inserts`, `updates of posted_minor`, `deletes`. */
|
|
111
|
+
export function sayBlocked(triggers) {
|
|
112
|
+
const blocking = triggers.filter((trigger) => !trigger.validates);
|
|
113
|
+
const said = [];
|
|
114
|
+
if (blocking.some((trigger) => trigger.events.includes('insert')))
|
|
115
|
+
said.push('inserts');
|
|
116
|
+
const updates = blocking.filter((trigger) => trigger.events.includes('update'));
|
|
117
|
+
if (updates.some((trigger) => trigger.columns === undefined))
|
|
118
|
+
said.push('every update');
|
|
119
|
+
else if (updates.length)
|
|
120
|
+
said.push(`updates of ${[...new Set(updates.flatMap((trigger) => trigger.columns))].join(', ')}`);
|
|
121
|
+
if (blocking.some((trigger) => trigger.events.includes('delete')))
|
|
122
|
+
said.push('deletes');
|
|
123
|
+
return said;
|
|
124
|
+
}
|
|
125
|
+
/** Whether the triggers refuse every insert, every update and every delete: no write to the table can run. */
|
|
126
|
+
export function blocksEveryWrite(triggers) {
|
|
127
|
+
const blocking = triggers.filter((trigger) => !trigger.validates);
|
|
128
|
+
return (blocking.some((trigger) => trigger.events.includes('insert')) &&
|
|
129
|
+
blocking.some((trigger) => trigger.events.includes('update') && trigger.columns === undefined) &&
|
|
130
|
+
blocking.some((trigger) => trigger.events.includes('delete')));
|
|
131
|
+
}
|
|
@@ -17,4 +17,6 @@ export declare function createScopedReads(catalog: DatabaseSchema, input: RowSco
|
|
|
17
17
|
/** Execution formatting only: it never changes the compiled statement or scope. */
|
|
18
18
|
execute: (statement: SqlFragment, hint?: {
|
|
19
19
|
binary?: true;
|
|
20
|
-
}) => Promise<QueryResult
|
|
20
|
+
}) => Promise<QueryResult>,
|
|
21
|
+
/** A scoped write's own guards: a condition may compare as a foreign key does (`Condition.equality`). Never an App's reads. */
|
|
22
|
+
references?: boolean): ScopedReads;
|
|
@@ -5,6 +5,10 @@ import { isCapturedScopeCatalog } from '../../shared/scopeCatalog.js';
|
|
|
5
5
|
import { ScopedRelations, snapshotRowScope } from '../../shared/rowScope.js';
|
|
6
6
|
import { compileView, compileViewCount } from '../../shared/view.js';
|
|
7
7
|
import { compileBreakdown, compileBreakdownCount } from '../../shared/breakdown.js';
|
|
8
|
+
import { compileAggregate } from '../../shared/aggregate.js';
|
|
9
|
+
import { readExactly, summed } from '../../shared/decimals.js';
|
|
10
|
+
import { RequestFault } from '../../shared/refusal.js';
|
|
11
|
+
import { storedTextOf, storedTextSelect } from './storedText.js';
|
|
8
12
|
/** Structured read arguments must not retain mutable values across driver
|
|
9
13
|
* waits. This is deliberately separate from stricter nonempty policy filters:
|
|
10
14
|
* an empty user filter is fine, because it never replaces the bound policy. */
|
|
@@ -81,7 +85,9 @@ export function snapshotScopedData(input) {
|
|
|
81
85
|
*/
|
|
82
86
|
export function createScopedReads(catalog, input, style,
|
|
83
87
|
/** Execution formatting only: it never changes the compiled statement or scope. */
|
|
84
|
-
execute
|
|
88
|
+
execute,
|
|
89
|
+
/** A scoped write's own guards: a condition may compare as a foreign key does (`Condition.equality`). Never an App's reads. */
|
|
90
|
+
references = false) {
|
|
85
91
|
const schema = isCapturedScopeCatalog(catalog) ? catalog : structuredClone(catalog);
|
|
86
92
|
const scope = snapshotRowScope(schema, input);
|
|
87
93
|
const tableFor = (id) => {
|
|
@@ -94,15 +100,17 @@ execute) {
|
|
|
94
100
|
const table = tableFor(id);
|
|
95
101
|
const column = (name) => {
|
|
96
102
|
if (!table.columns.some((column) => column.name === name))
|
|
97
|
-
throw new
|
|
103
|
+
throw new RequestFault('Unknown column in scoped read.');
|
|
98
104
|
return style.quote(name);
|
|
99
105
|
};
|
|
100
106
|
const relations = new ScopedRelations(schema, style, scope);
|
|
101
107
|
const relation = relations.table(id);
|
|
102
108
|
const prefix = relations.finish();
|
|
103
|
-
const where = buildWhere(filter, style, prefix.params.length + 1, column);
|
|
109
|
+
const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, undefined, references);
|
|
104
110
|
return { table, column, relation, prefix, where, params: [...prefix.params, ...where.params] };
|
|
105
111
|
};
|
|
112
|
+
/* A SQLite sum that cannot be exact says so in its cell (decimals.ts); PostgreSQL's numeric always is. */
|
|
113
|
+
const exact = (run, measures) => (style.dialect === 'sqlite' ? readExactly(run, summed(measures)) : run());
|
|
106
114
|
const counted = async (statement) => {
|
|
107
115
|
const result = await execute(statement);
|
|
108
116
|
return Number(result.rows[0]?.n ?? 0);
|
|
@@ -113,6 +121,10 @@ execute) {
|
|
|
113
121
|
const plan = from(request.table, request.filter);
|
|
114
122
|
const names = request.columns?.length ? request.columns : plan.table.columns.map((column) => column.name);
|
|
115
123
|
const columns = names.map(plan.column);
|
|
124
|
+
// A scoped write's own read: its reference columns' stored text too, as one more column (storedText.ts).
|
|
125
|
+
const texts = request.storedText ? storedTextOf(schema, plan.table) : undefined;
|
|
126
|
+
if (texts)
|
|
127
|
+
columns.push(`${storedTextSelect(texts.columns, (name) => style.quote(name))} AS ${style.quote(texts.alias)}`);
|
|
116
128
|
const order = orderClause(request.orderBy, plan.table, style, plan.params.length + 1, plan.column);
|
|
117
129
|
const n = plan.params.length + order.params.length;
|
|
118
130
|
const text = `${plan.prefix.text}SELECT ${columns.join(', ')} FROM ${plan.relation}${plan.where.text}${order.text}` +
|
|
@@ -138,7 +150,7 @@ execute) {
|
|
|
138
150
|
const table = tableFor(item.table);
|
|
139
151
|
const column = (name) => {
|
|
140
152
|
if (!table.columns.some((column) => column.name === name))
|
|
141
|
-
throw new
|
|
153
|
+
throw new RequestFault('Unknown column in scoped read.');
|
|
142
154
|
return style.quote(name);
|
|
143
155
|
};
|
|
144
156
|
return { relation: relations.table(item.table), column, filter: item.filter };
|
|
@@ -164,11 +176,17 @@ execute) {
|
|
|
164
176
|
},
|
|
165
177
|
async runBreakdown(breakdown, offset = 0) {
|
|
166
178
|
const compiled = compileBreakdown(schema, snapshotScopedData(breakdown), style, offset, scope);
|
|
167
|
-
const result = await execute(compiled);
|
|
179
|
+
const result = await exact(() => execute(compiled), breakdown.measures);
|
|
168
180
|
return { ...result, columns: compiled.columns.map((column) => column.name), resolved: compiled.columns };
|
|
169
181
|
},
|
|
170
182
|
async countBreakdown(breakdown, limit) {
|
|
171
183
|
return counted(compileBreakdownCount(schema, snapshotScopedData(breakdown), style, scope, limit));
|
|
172
184
|
},
|
|
185
|
+
/* The base table read through the scope's relation, as `count` reads it, and nothing else: an aggregate names
|
|
186
|
+
only its table's own columns (aggregate.ts), so no other table's relation is planned at all. */
|
|
187
|
+
async aggregate(request) {
|
|
188
|
+
const compiled = compileAggregate(schema, snapshotScopedData(request), style, 0, scope);
|
|
189
|
+
return { rows: (await exact(() => execute(compiled), request.measures)).rows };
|
|
190
|
+
},
|
|
173
191
|
});
|
|
174
192
|
}
|
|
@@ -1,18 +1,66 @@
|
|
|
1
1
|
import { Refusal, type Filter, type ScopedReads, type WriteTransaction } from '../adapter.js';
|
|
2
|
+
import { type ConditionEquality, type SqlFragment, type SqlStyle } from '../../shared/filter.js';
|
|
2
3
|
import type { RowScope } from '../../shared/rowScope.js';
|
|
3
|
-
import type
|
|
4
|
+
import { type DatabaseSchema, type ForeignKey, type TableMeta } from '../../shared/schema.js';
|
|
5
|
+
import { type ScopeTrigger } from './scopeTriggers.js';
|
|
6
|
+
import type { ScopedTriggers } from './triggerProof.js';
|
|
4
7
|
/** Physical metadata read on the writer inside its own transaction. `writable`
|
|
5
8
|
* names the tables this scope may mutate; everything else stays in the graph
|
|
6
9
|
* so a hidden dependent cannot vanish from the FK checks. */
|
|
7
10
|
export interface ScopeCatalog {
|
|
8
11
|
schema: DatabaseSchema;
|
|
9
12
|
writable: ReadonlySet<string>;
|
|
10
|
-
/** What in the database keeps a table out of `writable`, named where it can be:
|
|
11
|
-
*
|
|
13
|
+
/** What in the database keeps a table out of `writable`, named where it can be: on PostgreSQL its rules, policies
|
|
14
|
+
* or row security. A refusal says it, so the owner knows what to drop or move. */
|
|
12
15
|
blockedBy?: ReadonlyMap<string, string>;
|
|
16
|
+
/** Tables kept out of `writable` only by their triggers, with those triggers: a write that fires none of them but
|
|
17
|
+
* validation-only ones runs (scopeTriggers.ts); any other is refused, naming the trigger. */
|
|
18
|
+
triggered?: ReadonlyMap<string, readonly ScopeTrigger[]>;
|
|
19
|
+
/**
|
|
20
|
+
* How the database's own foreign key compares each reference with its parent's key, by {@link referenceKey}: what a
|
|
21
|
+
* parent check compares by (parentChecks below), or why a write through it cannot be checked. Absent, a reference is
|
|
22
|
+
* compared by `=`, its value coerced by the referencing column's type; present, a key it does not name is refused.
|
|
23
|
+
*/
|
|
24
|
+
references?: ReadonlyMap<string, ReferenceComparison>;
|
|
25
|
+
/** Tables whose primary key has a column of a type a scoped write does not take as a row's identity (keyTypes.ts),
|
|
26
|
+
* with why: no write targets one, whose key would name a row by a value the database may not compare. */
|
|
27
|
+
unkeyed?: ReadonlyMap<string, string>;
|
|
28
|
+
/**
|
|
29
|
+
* PostgreSQL: the tables in a partition or inheritance hierarchy, on either side of pg_inherits (a partitioned table,
|
|
30
|
+
* a partition at any level, an inheritance parent or child). No scoped write or trigger effect targets one: a foreign
|
|
31
|
+
* key may be declared on a partition alone, or point at one, and a write through the table above it reaches rows
|
|
32
|
+
* under keys and cascades that the table written does not have, which no parent or child check here reads. A
|
|
33
|
+
* reference to a partitioned table from an ordinary one is still checked, through the partitioned table.
|
|
34
|
+
*/
|
|
35
|
+
hierarchy?: ReadonlySet<string>;
|
|
13
36
|
}
|
|
37
|
+
/** One foreign key's comparison, column by column in its order (ScopeCatalog.references); or the reason it has none. */
|
|
38
|
+
export type ReferenceComparison = {
|
|
39
|
+
readonly refused: string;
|
|
40
|
+
} | {
|
|
41
|
+
readonly columns: ReadonlyArray<{
|
|
42
|
+
/** The referencing column's declared type, as the write coerces a value for it (shared/schema.ts coerceForColumn). */
|
|
43
|
+
readonly type: string;
|
|
44
|
+
/** PostgreSQL: the foreign key's own equality (Condition.equality). */
|
|
45
|
+
readonly equality?: ConditionEquality;
|
|
46
|
+
}>;
|
|
47
|
+
};
|
|
48
|
+
/** A foreign key's name in ScopeCatalog.references: its table, name and columns, each side. */
|
|
49
|
+
export declare const referenceKey: (fk: ForeignKey) => string;
|
|
50
|
+
/** Whether a failure is the database's foreign key refusing a write: SQLite's SQLITE_CONSTRAINT_FOREIGNKEY, PostgreSQL's 23503. */
|
|
51
|
+
export declare const isForeignKeyViolation: (error: unknown) => boolean;
|
|
52
|
+
/**
|
|
53
|
+
* A foreign key's refusal of a scoped write, said as a hidden parent's is: the database's own error says whether the
|
|
54
|
+
* row it points at exists (and, on PostgreSQL, its key, a default's part of it included), which the principal's rows
|
|
55
|
+
* may hide. Whichever statement it came from, at the statement or at COMMIT for a deferred one, it is the one
|
|
56
|
+
* refusal; what the operator reads names the constraint and nothing of the row.
|
|
57
|
+
*/
|
|
58
|
+
export declare const foreignKeyRefusal: (error: unknown) => ScopeRefusal;
|
|
14
59
|
/** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
|
|
15
60
|
export declare const triggerNames: (names: readonly string[]) => string;
|
|
61
|
+
export { blocksEveryWrite, sayBlocked, sayRuns, sayTriggers, type ScopeTrigger } from './scopeTriggers.js';
|
|
62
|
+
/** The keyed-effect judge (triggerEffects.ts), loaded where it is used: a process that never meets a named trigger never loads it. */
|
|
63
|
+
export declare const loadTriggerEffects: () => Promise<typeof import("./triggerEffects.js")>;
|
|
16
64
|
/** Row locks taken on the writer before a guard read, for engines whose
|
|
17
65
|
* transaction does not already exclude every other writer. SQLite passes
|
|
18
66
|
* none: `BEGIN IMMEDIATE` is the lock. Each receives the physical table and
|
|
@@ -37,6 +85,11 @@ interface ScopeRowLocks {
|
|
|
37
85
|
* Elsewhere each is asked once the one before it is answered.
|
|
38
86
|
*/
|
|
39
87
|
readonly together?: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* Told of each write that fired a trigger the catalog proved validation-only, before it is sent: where a trigger's
|
|
90
|
+
* function can change without a lock on the table (PostgreSQL), the proof is read again before COMMIT.
|
|
91
|
+
*/
|
|
92
|
+
relied?(table: TableMeta): void;
|
|
40
93
|
}
|
|
41
94
|
/**
|
|
42
95
|
* The outer bound a command's scope sits inside, when its host has one: a
|
|
@@ -58,7 +111,25 @@ interface ScopeRowLocks {
|
|
|
58
111
|
export interface ScopeBound {
|
|
59
112
|
readonly reads: Pick<ScopedReads, 'query' | 'count'>;
|
|
60
113
|
readonly whole: ReadonlySet<string>;
|
|
114
|
+
/** How many rows reference the row `key` names through `fk`, counted on the writer: {@link referencesStatement}. */
|
|
115
|
+
readonly references: (fk: ForeignKey, key: Filter) => Promise<number>;
|
|
61
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* The count of rows of `fk.from.table` that reference the `fk.to.table` row
|
|
119
|
+
* `key` names, as the database's own foreign key matches them, and so as its
|
|
120
|
+
* cascade would reach them.
|
|
121
|
+
*
|
|
122
|
+
* A foreign key compares a reference as the parent key compares: SQLite
|
|
123
|
+
* applies the parent column's affinity and collation to the child's value
|
|
124
|
+
* (an untyped child column holding the number 7 references the text key
|
|
125
|
+
* '7'), PostgreSQL the parent's collation where the child's is the default.
|
|
126
|
+
* The child counted by its own column (`child.col = ?`) compares as the child
|
|
127
|
+
* does, and missed such a reference, which the delete's cascade then reached.
|
|
128
|
+
* Here each parent column is the left side of a join, where both engines take
|
|
129
|
+
* its affinity and collation as the foreign key does; where two collations
|
|
130
|
+
* conflict, PostgreSQL refuses the count, and the delete with it.
|
|
131
|
+
*/
|
|
132
|
+
export declare function referencesStatement(schema: DatabaseSchema, fk: ForeignKey, key: Filter, style: SqlStyle): SqlFragment;
|
|
62
133
|
/** The tables where `scope` is exactly `bound`, and the bound admits rows at all: nothing in it is hidden there. */
|
|
63
134
|
export declare function wholeWithin(scope: Readonly<Record<string, unknown>>, bound: Readonly<Record<string, unknown>>): ReadonlySet<string>;
|
|
64
135
|
/** A bound names exactly the scope's tables: it bounds that scope, never another. */
|
|
@@ -80,10 +151,9 @@ export declare class ScopeRefusal extends Refusal {
|
|
|
80
151
|
*/
|
|
81
152
|
export interface ScopeOwnRows {
|
|
82
153
|
readonly scope: RowScope;
|
|
83
|
-
readonly reads: (scope: RowScope, guard: boolean) => Pick<ScopedReads, 'query' | 'count'>;
|
|
154
|
+
readonly reads: (scope: RowScope, guard: boolean) => Pick<ScopedReads, 'query' | 'count' | 'aggregate'>;
|
|
84
155
|
}
|
|
85
156
|
/** Runs INSIDE a single queued operation. The supplied guards retain actual
|
|
86
157
|
* stored scalar types, not display conversions (a blob label is not a key).
|
|
87
158
|
* This capability deliberately refuses side effects it cannot bound. */
|
|
88
|
-
export declare function createScopedTransaction(catalog: ScopeCatalog, records: WriteTransaction, reads: Pick<ScopedReads, 'query' | 'count'>, guards: Pick<ScopedReads, 'query' | 'count'>, locks?: ScopeRowLocks, bound?: ScopeBound, own?: ScopeOwnRows): WriteTransaction;
|
|
89
|
-
export {};
|
|
159
|
+
export declare function createScopedTransaction(catalog: ScopeCatalog, records: WriteTransaction, reads: Pick<ScopedReads, 'query' | 'count' | 'aggregate'>, guards: Pick<ScopedReads, 'query' | 'count'>, locks?: ScopeRowLocks, bound?: ScopeBound, own?: ScopeOwnRows, triggers?: ScopedTriggers): WriteTransaction;
|