@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.
- package/dist/adapters/adapter.d.ts +33 -0
- package/dist/adapters/postgres.d.ts +21 -16
- package/dist/adapters/postgres.js +199 -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 +40 -1
- package/dist/adapters/scoped/postgresScopeCatalog.js +417 -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 +28 -8
- package/dist/adapters/scoped/scopedTransaction.d.ts +95 -6
- package/dist/adapters/scoped/scopedTransaction.js +308 -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/http/router.d.ts +11 -22
- package/dist/server/http/router.js +0 -15
- 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/addressParams.d.ts +2 -0
- package/dist/shared/addressParams.js +2 -0
- package/dist/shared/aggregate.d.ts +49 -0
- package/dist/shared/aggregate.js +107 -0
- package/dist/shared/breakdown.js +19 -6
- 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 +39 -1
- package/dist/shared/filter.js +96 -15
- package/dist/shared/listPresentations.d.ts +2 -0
- package/dist/shared/listQuestion.d.ts +3 -1
- package/dist/shared/money.d.ts +9 -0
- package/dist/shared/money.js +17 -0
- package/dist/shared/moneyEntry.d.ts +6 -3
- package/dist/shared/moneyEntry.js +14 -7
- package/dist/shared/pageModel.d.ts +1 -1
- package/dist/shared/recordview.d.ts +1 -1
- package/dist/shared/refusal.d.ts +16 -0
- package/dist/shared/refusal.js +40 -0
- package/dist/shared/rowScope.js +12 -4
- package/dist/shared/schema.d.ts +6 -0
- package/dist/shared/schematext.d.ts +22 -6
- package/dist/shared/schematext.js +18 -2
- package/dist/shared/scopeCatalog.js +4 -0
- package/dist/shared/servedApp.d.ts +15 -4
- package/dist/shared/view.js +4 -4
- package/dist/shared/viewLabels.d.ts +1 -0
- package/dist/shared/viewLabels.js +8 -2
- package/dist/shared/viewPaths.d.ts +3 -0
- package/dist/shared/viewPaths.js +8 -0
- package/package.json +5 -2
- package/schema/model.d.ts +1 -1
- package/dist/shared/order.d.ts +0 -59
- package/dist/shared/order.js +0 -133
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { overlaid, storedText, withStoredText } from './storedText.js';
|
|
2
|
+
import { firedBy } from './scopeTriggers.js';
|
|
3
|
+
const UNKNOWN = Symbol('unknown');
|
|
4
|
+
/**
|
|
5
|
+
* A column whose value the database assigns when a write gives none: SQLite's rowid alias takes the next id for an
|
|
6
|
+
* explicit NULL too, so a NULL given there is not the row's key, and NEW holds the id the statement chose.
|
|
7
|
+
*/
|
|
8
|
+
const assigned = (table, column) => table.columns.find((candidate) => candidate.name === column)?.identity !== undefined;
|
|
9
|
+
/** A term that names a column of NEW or OLD: its value is the row's, known once the row is, never computed by the trigger. */
|
|
10
|
+
const refersToRow = (term) => term !== undefined && 'row' in term;
|
|
11
|
+
const comparable = (value) => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
|
|
12
|
+
/** A row without its generated columns: the database computes them, so a value read before the write may not hold after it. */
|
|
13
|
+
const writtenPart = (table, row) => Object.fromEntries(Object.entries(row).filter(([name]) => table.columns.find((column) => column.name === name)?.writable !== false));
|
|
14
|
+
export function createTriggerProof(acceptance, tools) {
|
|
15
|
+
const tableOf = (id) => tools.tables.find((table) => table.id === id) ??
|
|
16
|
+
tools.refuse(`A trigger's effect reaches "${id}", which is not in this write's footprint.`);
|
|
17
|
+
const hidden = (table, trigger, on) => `The trigger ${JSON.stringify(trigger.name)} on "${on}" reaches a row of "${table.id}" outside the principal's rows: the row policy (or tenant) does not admit it, or it does not exist.`;
|
|
18
|
+
/** Whether `trigger` on `table` is one the App accepts: named, keyed, judged sound by the catalog, and its digest the one approved. */
|
|
19
|
+
const accepts = (table, trigger) => {
|
|
20
|
+
const named = acceptance.named.get(table);
|
|
21
|
+
if (!named?.has(trigger.name) || !trigger.effects || trigger.unaccepted)
|
|
22
|
+
return false;
|
|
23
|
+
const approved = named.get(trigger.name);
|
|
24
|
+
return approved === undefined || approved === trigger.digest;
|
|
25
|
+
};
|
|
26
|
+
/** Why a fired trigger that blocks is not accepted, for the refusal. */
|
|
27
|
+
const unaccepted = (table, trigger) => {
|
|
28
|
+
const named = acceptance.named.get(table);
|
|
29
|
+
if (!named?.has(trigger.name))
|
|
30
|
+
return undefined;
|
|
31
|
+
if (!trigger.effects)
|
|
32
|
+
return `named by the App, but outside the keyed-effect grammar: ${trigger.why ?? 'it is not validation-only'}`;
|
|
33
|
+
if (trigger.unaccepted)
|
|
34
|
+
return `named by the App, but ${trigger.unaccepted}`;
|
|
35
|
+
return 'named by the App, but its definition is not the one authority.lock approved';
|
|
36
|
+
};
|
|
37
|
+
/** The accepted triggers a write fires; refuses where it fires one that blocks and is not accepted. */
|
|
38
|
+
const fired = (table, write) => {
|
|
39
|
+
const triggers = tools.triggered?.get(table.id);
|
|
40
|
+
if (!triggers)
|
|
41
|
+
return [];
|
|
42
|
+
const all = firedBy(triggers, write, tools.foldCase);
|
|
43
|
+
if (all.length)
|
|
44
|
+
tools.relied?.(table);
|
|
45
|
+
const keyed = all.filter((trigger) => !trigger.validates);
|
|
46
|
+
const refused = keyed.find((trigger) => !accepts(table.id, trigger));
|
|
47
|
+
if (refused)
|
|
48
|
+
tools.refuse(`"${table.id}" cannot be written by a trigger under a row policy: the write fires ${JSON.stringify(refused.name)}, ${unaccepted(table.id, refused) ?? "which the App does not name in its resource's triggers"}.`);
|
|
49
|
+
return keyed;
|
|
50
|
+
};
|
|
51
|
+
const valueOf = (images, ref) => {
|
|
52
|
+
const row = ref.row === 'new' ? images.new : images.old;
|
|
53
|
+
if (row === null)
|
|
54
|
+
return null;
|
|
55
|
+
return Object.hasOwn(row, ref.column) ? (row[ref.column] ?? null) : UNKNOWN;
|
|
56
|
+
};
|
|
57
|
+
const termOf = (images, term) => 'row' in term ? valueOf(images, term) : 'literal' in term ? term.literal : UNKNOWN;
|
|
58
|
+
/** The stored text a term carries from the image it names (storedText.ts): a stored column copied as it is. */
|
|
59
|
+
const textOf = (images, term) => {
|
|
60
|
+
if (!('row' in term))
|
|
61
|
+
return undefined;
|
|
62
|
+
const row = term.row === 'new' ? images.new : images.old;
|
|
63
|
+
const texts = storedText(row);
|
|
64
|
+
return texts && row && Object.hasOwn(texts, term.column) && Object.hasOwn(row, term.column) ? texts[term.column] : undefined;
|
|
65
|
+
};
|
|
66
|
+
/** `row`, carrying the stored texts of the columns `terms` copy from an image unchanged. */
|
|
67
|
+
const carried = (row, images, terms, base = {}) => {
|
|
68
|
+
const texts = { ...base };
|
|
69
|
+
for (const [column, term] of Object.entries(terms)) {
|
|
70
|
+
const text = textOf(images, term);
|
|
71
|
+
if (text === undefined)
|
|
72
|
+
delete texts[column];
|
|
73
|
+
else
|
|
74
|
+
texts[column] = text;
|
|
75
|
+
}
|
|
76
|
+
return withStoredText(row, texts);
|
|
77
|
+
};
|
|
78
|
+
/** The effect's key as values: null where it reaches no row (a NULL never equals), UNKNOWN where the statement must tell. */
|
|
79
|
+
const keyOf = (images, effect, table) => {
|
|
80
|
+
const key = {};
|
|
81
|
+
let unknown = false;
|
|
82
|
+
for (const [column, ref] of Object.entries(effect.key ?? {})) {
|
|
83
|
+
const value = valueOf(images, ref);
|
|
84
|
+
if (value === null)
|
|
85
|
+
return null;
|
|
86
|
+
if (value === UNKNOWN)
|
|
87
|
+
unknown = true;
|
|
88
|
+
else if (!comparable(value))
|
|
89
|
+
return tools.refuse(`A trigger's key for "${table.id}".${column} is not a text or a number.`);
|
|
90
|
+
else
|
|
91
|
+
key[column] = value;
|
|
92
|
+
}
|
|
93
|
+
return unknown ? UNKNOWN : key;
|
|
94
|
+
};
|
|
95
|
+
const filterOf = (key) => ({
|
|
96
|
+
groups: [Object.entries(key).map(([column, value]) => ({ column, op: '=', value: value }))],
|
|
97
|
+
});
|
|
98
|
+
const primaryKey = (table, row) => {
|
|
99
|
+
const columns = table.columns.filter((column) => column.primaryKey);
|
|
100
|
+
if (!columns.length || columns.some((column) => !comparable(row[column.name])))
|
|
101
|
+
return undefined;
|
|
102
|
+
return Object.fromEntries(columns.map((column) => [column.name, row[column.name]]));
|
|
103
|
+
};
|
|
104
|
+
/** The row an update leaves, as far as the images say: a column it sets by an expression is not known until it ran. */
|
|
105
|
+
const updated = (table, stored, images, effect) => {
|
|
106
|
+
const row = writtenPart(table, stored);
|
|
107
|
+
for (const [column, term] of Object.entries(effect.values ?? {})) {
|
|
108
|
+
const value = termOf(images, term);
|
|
109
|
+
if (value === UNKNOWN)
|
|
110
|
+
delete row[column];
|
|
111
|
+
else
|
|
112
|
+
row[column] = value;
|
|
113
|
+
}
|
|
114
|
+
return carried(row, images, effect.values ?? {}, storedText(stored));
|
|
115
|
+
};
|
|
116
|
+
/** Whether `value` stored in `column` equals `wanted` as the database would: only where JavaScript can say so for certain. */
|
|
117
|
+
const equal = (table, column, value, wanted) => {
|
|
118
|
+
if (value === null || wanted === null)
|
|
119
|
+
return false;
|
|
120
|
+
if (typeof value === typeof wanted && (typeof value === 'string' || typeof value === 'number'))
|
|
121
|
+
return value === wanted;
|
|
122
|
+
// An integer column compares a number and its canonical text alike on both engines (affinity, a cast of the parameter).
|
|
123
|
+
const type = table.columns.find((candidate) => candidate.name === column)?.type ?? '';
|
|
124
|
+
if (/int|serial/i.test(type) && comparable(value) && comparable(wanted))
|
|
125
|
+
return String(value) === String(wanted);
|
|
126
|
+
return UNKNOWN;
|
|
127
|
+
};
|
|
128
|
+
const holds = (table, condition, row) => {
|
|
129
|
+
if (condition.other !== undefined || condition.any !== undefined || condition.collation !== undefined)
|
|
130
|
+
return UNKNOWN;
|
|
131
|
+
if (!Object.hasOwn(row, condition.column))
|
|
132
|
+
return UNKNOWN;
|
|
133
|
+
const value = row[condition.column];
|
|
134
|
+
if (value === UNKNOWN)
|
|
135
|
+
return UNKNOWN;
|
|
136
|
+
if (condition.op === 'isNull')
|
|
137
|
+
return value === null;
|
|
138
|
+
if (condition.op === 'isNotNull')
|
|
139
|
+
return value !== null;
|
|
140
|
+
if (condition.op === '=')
|
|
141
|
+
return equal(table, condition.column, value, condition.value);
|
|
142
|
+
if (condition.op === 'in' && Array.isArray(condition.value)) {
|
|
143
|
+
let unknown = false;
|
|
144
|
+
for (const wanted of condition.value) {
|
|
145
|
+
const same = equal(table, condition.column, value, wanted);
|
|
146
|
+
if (same === true)
|
|
147
|
+
return true;
|
|
148
|
+
if (same === UNKNOWN)
|
|
149
|
+
unknown = true;
|
|
150
|
+
}
|
|
151
|
+
return unknown ? UNKNOWN : false;
|
|
152
|
+
}
|
|
153
|
+
// A comparison whose answer depends on collation or type rules this side does not hold.
|
|
154
|
+
return UNKNOWN;
|
|
155
|
+
};
|
|
156
|
+
/** Whether a row the trigger inserts lands inside the policy's rule for its table. */
|
|
157
|
+
const admitted = (table, row) => {
|
|
158
|
+
const rule = tools.scope[table.id];
|
|
159
|
+
if (rule === true)
|
|
160
|
+
return true;
|
|
161
|
+
if (!rule)
|
|
162
|
+
return false;
|
|
163
|
+
const filter = rule;
|
|
164
|
+
if (!filter.groups.length)
|
|
165
|
+
return true;
|
|
166
|
+
let unknown = false;
|
|
167
|
+
for (const group of filter.groups) {
|
|
168
|
+
let all = true;
|
|
169
|
+
for (const condition of group) {
|
|
170
|
+
const result = holds(table, condition, row);
|
|
171
|
+
if (result === false) {
|
|
172
|
+
all = false;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
if (result === UNKNOWN)
|
|
176
|
+
all = UNKNOWN;
|
|
177
|
+
}
|
|
178
|
+
if (all === true)
|
|
179
|
+
return true;
|
|
180
|
+
if (all === UNKNOWN)
|
|
181
|
+
unknown = true;
|
|
182
|
+
}
|
|
183
|
+
return unknown ? UNKNOWN : false;
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* Before the statement: every effect of every accepted trigger the write fires, proven where its images already
|
|
187
|
+
* say enough. Answers what runs right after the statement.
|
|
188
|
+
*/
|
|
189
|
+
/**
|
|
190
|
+
* The rows this statement's effects update or delete, by table and primary key, each with whether a write to it
|
|
191
|
+
* fires a keyed trigger; the statement's own row is one. A row two writes reach is seen by the second as the first
|
|
192
|
+
* left it, not as it was read and locked here: where either fires a keyed trigger, that trigger's keys would come
|
|
193
|
+
* from an image of the row this proof never had (a value one effect set, read as the key of the next).
|
|
194
|
+
*/
|
|
195
|
+
let reached = new Map();
|
|
196
|
+
const rowId = (table, row) => JSON.stringify([table.id, primaryKey(table, row) ?? row]);
|
|
197
|
+
const claim = (table, row, firing, trigger) => {
|
|
198
|
+
const id = rowId(table, row);
|
|
199
|
+
const prior = reached.get(id);
|
|
200
|
+
if (prior !== undefined && (prior || firing))
|
|
201
|
+
tools.refuse(`The trigger ${JSON.stringify(trigger.name)} reaches a row of "${table.id}" that this write already reaches, and a write to it fires a trigger that reads or writes another row: what that trigger sees depends on which write runs first, so it cannot be proven before the write.`);
|
|
202
|
+
reached.set(id, firing);
|
|
203
|
+
};
|
|
204
|
+
/** Whether a write to `table` fires a trigger there that reads or writes another row, accepted or not. */
|
|
205
|
+
const firesKeyed = (table, write) => (tools.triggered?.get(table.id) ?? []).some((next) => !next.validates && firedBy([next], write, tools.foldCase).length > 0);
|
|
206
|
+
const before = async (table, write, images) => {
|
|
207
|
+
const afterwards = [];
|
|
208
|
+
const firing = fired(table, write);
|
|
209
|
+
if (firing.length)
|
|
210
|
+
tools.watch?.();
|
|
211
|
+
for (const trigger of firing)
|
|
212
|
+
for (const effect of trigger.effects)
|
|
213
|
+
afterwards.push(await effectBefore(table, trigger, effect, images));
|
|
214
|
+
return afterwards;
|
|
215
|
+
};
|
|
216
|
+
const effectBefore = async (on, trigger, effect, images) => {
|
|
217
|
+
const table = tableOf(effect.table);
|
|
218
|
+
const said = async (kind, row) => {
|
|
219
|
+
await acceptance.changed?.({ table: table.id, kind, ...row, trigger: trigger.name, on: on.id });
|
|
220
|
+
};
|
|
221
|
+
if (effect.kind === 'read') {
|
|
222
|
+
const key = keyOf(images, effect, table);
|
|
223
|
+
// Whether the trigger raises is read before anything else can be: a key the statement alone knows is not proven.
|
|
224
|
+
if (key === UNKNOWN)
|
|
225
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} reads a "${table.id}" row by a value only the write assigns: it cannot be proven before the write.`);
|
|
226
|
+
if (key) {
|
|
227
|
+
const filter = filterOf(key);
|
|
228
|
+
await tools.holdParent?.(table, filter);
|
|
229
|
+
if ((await tools.guards().count(table.id, filter)) !== 1)
|
|
230
|
+
return tools.refuse(hidden(table, trigger, on.id));
|
|
231
|
+
}
|
|
232
|
+
return async () => { };
|
|
233
|
+
}
|
|
234
|
+
if (effect.kind === 'insert') {
|
|
235
|
+
/** The row it will insert, a column it gives by an expression or leaves to a default unknown. */
|
|
236
|
+
const rowOf = (images) => {
|
|
237
|
+
const row = {};
|
|
238
|
+
for (const column of table.columns) {
|
|
239
|
+
if (Object.hasOwn(effect.values ?? {}, column.name)) {
|
|
240
|
+
const value = termOf(images, effect.values[column.name]);
|
|
241
|
+
row[column.name] = value === null && column.identity !== undefined ? UNKNOWN : value;
|
|
242
|
+
}
|
|
243
|
+
else
|
|
244
|
+
row[column.name] = column.default !== undefined || column.identity !== undefined || column.writable === false ? UNKNOWN : null;
|
|
245
|
+
}
|
|
246
|
+
return carried(row, images, effect.values ?? {});
|
|
247
|
+
};
|
|
248
|
+
const references = new Set(tools.foreignKeys.filter((fk) => fk.from.table === table.id).flatMap((fk) => fk.from.columns));
|
|
249
|
+
const knownPart = (row) => withStoredText(Object.fromEntries(Object.entries(row).filter(([, value]) => value !== UNKNOWN)), storedText(row));
|
|
250
|
+
/* A reference no image will ever tell (an expression, a default): refused now, before the statement could fail on
|
|
251
|
+
its foreign key for a parent that does not exist and pass for one that is hidden. */
|
|
252
|
+
if ([...references].some((column) => rowOf({ new: null, old: null })[column] === UNKNOWN && !refersToRow(effect.values?.[column])))
|
|
253
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} inserts a "${table.id}" row whose place in the principal's rows cannot be proven: a value the policy or a reference depends on is computed by the trigger or left to a default.`);
|
|
254
|
+
/** Its proof. */
|
|
255
|
+
const prove = async (images, last) => {
|
|
256
|
+
const row = rowOf(images);
|
|
257
|
+
const verdict = admitted(table, row);
|
|
258
|
+
const unknownReference = [...references].some((column) => row[column] === UNKNOWN);
|
|
259
|
+
if ((verdict === UNKNOWN || unknownReference) && !last)
|
|
260
|
+
return undefined;
|
|
261
|
+
if (verdict === UNKNOWN || unknownReference)
|
|
262
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} inserts a "${table.id}" row whose place in the principal's rows cannot be proven: a value the policy or a reference depends on is computed by the trigger or left to a default.`);
|
|
263
|
+
if (!verdict)
|
|
264
|
+
return tools.refuse(hidden(table, trigger, on.id));
|
|
265
|
+
const known = knownPart(row);
|
|
266
|
+
await tools.parents(table, known, references);
|
|
267
|
+
const chained = await before(table, { kind: 'insert' }, { new: known, old: null });
|
|
268
|
+
return async () => {
|
|
269
|
+
const key = primaryKey(table, known);
|
|
270
|
+
for (const next of chained)
|
|
271
|
+
await next({ new: known, old: null });
|
|
272
|
+
await said('insert', { ...(key ? { key } : {}), after: known });
|
|
273
|
+
};
|
|
274
|
+
};
|
|
275
|
+
const early = await prove(images, false);
|
|
276
|
+
if (early)
|
|
277
|
+
return early;
|
|
278
|
+
// Proven after the statement, what its row fires on its table would be proven after that had run too.
|
|
279
|
+
if (firesKeyed(table, { kind: 'insert' }))
|
|
280
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} inserts a "${table.id}" row whose place in the principal's rows only the write can tell, and that insert fires a trigger that reads or writes another row: it cannot be proven before the write.`);
|
|
281
|
+
// Its row waits for the statement; the references it already names are checked before it.
|
|
282
|
+
await tools.parentsBefore(table, knownPart(rowOf(images)), references);
|
|
283
|
+
return async (after) => {
|
|
284
|
+
const late = await prove(after, true);
|
|
285
|
+
await late?.(after);
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
// An update or a delete: one row, by a key known before the statement.
|
|
289
|
+
const key = keyOf(images, effect, table);
|
|
290
|
+
if (key === UNKNOWN)
|
|
291
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} reaches a row of "${table.id}" by a value only the write assigns: it cannot be proven before the write.`);
|
|
292
|
+
const write = effect.kind === 'update' ? { kind: 'update', set: Object.keys(effect.values ?? {}) } : { kind: 'delete' };
|
|
293
|
+
let stored;
|
|
294
|
+
let chained = [];
|
|
295
|
+
if (key) {
|
|
296
|
+
const result = await tools.lockedRead(table, filterOf(key), tools.guards());
|
|
297
|
+
if (result.rows.length !== 1)
|
|
298
|
+
return tools.refuse(hidden(table, trigger, on.id));
|
|
299
|
+
stored = result.rows[0];
|
|
300
|
+
claim(table, stored, firesKeyed(table, write), trigger);
|
|
301
|
+
if (effect.kind === 'update') {
|
|
302
|
+
const set = new Set(Object.keys(effect.values ?? {}));
|
|
303
|
+
const sets = tools.foreignKeys
|
|
304
|
+
.filter((fk) => fk.from.table === table.id)
|
|
305
|
+
.flatMap((fk) => fk.from.columns.filter((column) => set.has(column)));
|
|
306
|
+
// A reference set by an expression only the statement computes: whether its parent exists cannot be asked first.
|
|
307
|
+
if (sets.some((column) => !refersToRow(effect.values?.[column]) && !('literal' in (effect.values?.[column] ?? {}))))
|
|
308
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} sets a reference of "${table.id}" to a value only the write computes: whether that row exists and is the principal's cannot be proven before the write.`);
|
|
309
|
+
await tools.parentsBefore(table, updated(table, stored, images, effect), set);
|
|
310
|
+
}
|
|
311
|
+
chained = await before(table, write, effect.kind === 'update' ? { new: updated(table, stored, images, effect), old: stored } : { new: null, old: stored });
|
|
312
|
+
}
|
|
313
|
+
return async () => {
|
|
314
|
+
if (!key || !stored)
|
|
315
|
+
return;
|
|
316
|
+
if (effect.kind === 'delete') {
|
|
317
|
+
for (const next of chained)
|
|
318
|
+
await next({ new: null, old: stored });
|
|
319
|
+
await said('delete', { ...(primaryKey(table, stored) ? { key: primaryKey(table, stored) } : {}), before: stored });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
// Still inside the principal's rows after the trigger wrote it, and every reference it set checked.
|
|
323
|
+
const result = await tools.read(table, filterOf(key));
|
|
324
|
+
if (result.rows.length !== 1)
|
|
325
|
+
return tools.refuse(hidden(table, trigger, on.id));
|
|
326
|
+
const now = result.rows[0];
|
|
327
|
+
const was = stored;
|
|
328
|
+
/* A key or a referenced column the database generates moves with what the trigger set, which the catalog's
|
|
329
|
+
judgment by name cannot see (triggerEffects.ts): one that moved is refused, as the person's own update is. */
|
|
330
|
+
const shifted = table.columns
|
|
331
|
+
.filter(({ name, writable, primaryKey }) => writable === false &&
|
|
332
|
+
(primaryKey || tools.foreignKeys.some((fk) => fk.to.table === table.id && fk.to.columns.includes(name))) &&
|
|
333
|
+
JSON.stringify(was[name]) !== JSON.stringify(now[name]))
|
|
334
|
+
.map((column) => column.name);
|
|
335
|
+
if (shifted.length)
|
|
336
|
+
return tools.refuse(`The trigger ${JSON.stringify(trigger.name)} changes "${table.id}".${shifted.join(', ')}: a key, or a column another table references, generated from the columns it sets.`);
|
|
337
|
+
// Every reference it set checked; one with a generated column with every update (scopedTransaction.ts parentChecks).
|
|
338
|
+
await tools.parents(table, now, new Set(Object.keys(effect.values ?? {})));
|
|
339
|
+
for (const next of chained)
|
|
340
|
+
await next({ new: now, old: stored });
|
|
341
|
+
await said('update', { ...(primaryKey(table, now) ? { key: primaryKey(table, now) } : {}), before: stored, after: now });
|
|
342
|
+
};
|
|
343
|
+
};
|
|
344
|
+
/** A statement's proof: its own row (an update's or a delete's) the first reached, and every effect's after it. */
|
|
345
|
+
const statement = async (table, write, images) => {
|
|
346
|
+
reached = new Map();
|
|
347
|
+
if (images.old)
|
|
348
|
+
reached.set(rowId(table, images.old), true);
|
|
349
|
+
return before(table, write, images);
|
|
350
|
+
};
|
|
351
|
+
return { accepts, unaccepted, before: statement, images: imagesBefore };
|
|
352
|
+
}
|
|
353
|
+
/** What a scoped write's own row looks like to its triggers before the statement, by write. */
|
|
354
|
+
const imagesBefore = {
|
|
355
|
+
/* A NULL given for a column the database assigns is not what NEW will hold: left unknown, like a value not given. */
|
|
356
|
+
insert: (table, values) => ({
|
|
357
|
+
new: Object.fromEntries(Object.entries(values ?? {}).filter(([column, value]) => value != null || !assigned(table, column))),
|
|
358
|
+
old: null,
|
|
359
|
+
}),
|
|
360
|
+
// NEW carries the stored texts of the columns the write leaves as they were (storedText.ts).
|
|
361
|
+
update: (table, stored, values) => ({
|
|
362
|
+
new: withStoredText({ ...writtenPart(table, stored), ...(values ?? {}) }, storedText(overlaid(stored, values))),
|
|
363
|
+
old: stored,
|
|
364
|
+
}),
|
|
365
|
+
delete: (stored) => ({ new: null, old: stored }),
|
|
366
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Run `work` with the next write transaction it opens reading one snapshot. */
|
|
2
|
+
export declare function withSnapshotRead<T>(snapshot: boolean, work: () => T): T;
|
|
3
|
+
/** Whether the transaction about to open here reads one snapshot. */
|
|
4
|
+
export declare function snapshotRead(): boolean;
|
|
5
|
+
/** Run `work` without it: a transaction's own work, so nothing it opens takes the snapshot for its own. */
|
|
6
|
+
export declare function withoutSnapshotRead<T>(work: () => T): T;
|
|
7
|
+
/** PostgreSQL's serialization failure: a REPEATABLE READ transaction wrote or locked a row that moved after its snapshot. */
|
|
8
|
+
export declare function isSnapshotConflict(error: unknown): boolean;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A command that asked for one snapshot (`snapshot: true` on its definition,
|
|
3
|
+
* docs/command-aggregates.md): every read it makes sees the database as of one
|
|
4
|
+
* moment, so a total and the rows behind it, or a count and the pages that
|
|
5
|
+
* follow, agree with each other while other writers carry on.
|
|
6
|
+
*
|
|
7
|
+
* PostgreSQL's write transaction is READ COMMITTED (postgres.ts
|
|
8
|
+
* journalTransaction says why), where each statement sees what committed
|
|
9
|
+
* before it began; asked for a snapshot it opens REPEATABLE READ instead. A
|
|
10
|
+
* row another transaction changed after the snapshot and this one then
|
|
11
|
+
* writes or locks fails with 40001, which the command host says as
|
|
12
|
+
* `stale_record` — the refusal a job or workflow already retries. SQLite's
|
|
13
|
+
* writer holds the file (`BEGIN IMMEDIATE`) from its first statement to its
|
|
14
|
+
* last, so its reads are one snapshot already and nothing here changes it.
|
|
15
|
+
*
|
|
16
|
+
* Carried as the write-ahead hint is (writeAhead.ts): told by the caller that
|
|
17
|
+
* knows the command, read once by the adapter for the transaction it is
|
|
18
|
+
* opening, and not passed to a transaction that work opens inside.
|
|
19
|
+
*/
|
|
20
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
21
|
+
const asked = new AsyncLocalStorage();
|
|
22
|
+
/** Run `work` with the next write transaction it opens reading one snapshot. */
|
|
23
|
+
export function withSnapshotRead(snapshot, work) {
|
|
24
|
+
return asked.run(snapshot, work);
|
|
25
|
+
}
|
|
26
|
+
/** Whether the transaction about to open here reads one snapshot. */
|
|
27
|
+
export function snapshotRead() {
|
|
28
|
+
return asked.getStore() === true;
|
|
29
|
+
}
|
|
30
|
+
/** Run `work` without it: a transaction's own work, so nothing it opens takes the snapshot for its own. */
|
|
31
|
+
export function withoutSnapshotRead(work) {
|
|
32
|
+
return asked.run(false, work);
|
|
33
|
+
}
|
|
34
|
+
/** PostgreSQL's serialization failure: a REPEATABLE READ transaction wrote or locked a row that moved after its snapshot. */
|
|
35
|
+
export function isSnapshotConflict(error) {
|
|
36
|
+
return !!error && typeof error === 'object' && error.code === '40001';
|
|
37
|
+
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
|
|
2
|
-
import { type Adapter, type ScopedReads, type Filter, type QueryRequest, type QueryResult, type SqlRequest, type SqlResult, type DeleteRequest, type DeleteResult, type UpdateRequest, type UpdateResult, type ViewResult, type BreakdownResult, TransactionOperations, type WriteTransaction, type InsertRequest, type InsertResult, type ExplainRequest, type ExplainResult, type ProfileLimits, type ProfileResult, type CountItem } from './adapter.js';
|
|
2
|
+
import { type Adapter, type ScopedReads, type Filter, type QueryRequest, type QueryResult, type SqlRequest, type SqlResult, type DeleteRequest, type DeleteResult, type UpdateRequest, type UpdateResult, type ViewResult, type BreakdownResult, TransactionOperations, type WriteTransaction, type InsertRequest, type InsertResult, type ExplainRequest, type ExplainResult, type ProfileLimits, type ProfileResult, type CountItem, type AggregateRequest, type AggregateResult } from './adapter.js';
|
|
3
|
+
import type { TriggerAcceptance } from './scoped/triggerProof.js';
|
|
3
4
|
import { type SqliteScopeCatalog } from './scoped/sqliteScopeCatalog.js';
|
|
5
|
+
import type { ScopeTrigger } from './scoped/scopeTriggers.js';
|
|
6
|
+
import type { TriggerKeyFacts } from './scoped/triggerEffects.js';
|
|
4
7
|
import { type RowScope } from '../shared/rowScope.js';
|
|
5
8
|
import { type ViewDef } from '../shared/view.js';
|
|
6
9
|
import { type BreakdownDef } from '../shared/breakdown.js';
|
|
@@ -29,6 +32,12 @@ export declare class SqliteAdapter implements Adapter {
|
|
|
29
32
|
* adapter's schema is accepted. Ordinary DDL invalidates it synchronously;
|
|
30
33
|
* malicious manual schema_version resets are outside this contract. */
|
|
31
34
|
captureSchemaLifetime(schema: DatabaseSchema): () => void;
|
|
35
|
+
/** Each table's triggers, read on the reader as a scoped write reads them on its writer (sqliteTriggers.ts). A TEMP
|
|
36
|
+
* trigger is its own connection's, which this reader cannot see; the writer reads those too. */
|
|
37
|
+
triggers(): Promise<ReadonlyMap<string, readonly ScopeTrigger[]>>;
|
|
38
|
+
/** What a write reads to judge a trigger's effects (sqliteScopeCatalog.ts): every table's keys, the conflict clauses
|
|
39
|
+
* its schema declares, and the tables a scoped write cannot target, on the reader. */
|
|
40
|
+
triggerKeys(): Promise<TriggerKeyFacts>;
|
|
32
41
|
introspect(): Promise<DatabaseSchema>;
|
|
33
42
|
private indexesOf;
|
|
34
43
|
/**
|
|
@@ -107,8 +116,10 @@ export declare class SqliteAdapter implements Adapter {
|
|
|
107
116
|
private cachedSchema;
|
|
108
117
|
private schema;
|
|
109
118
|
count(table: string, filter?: Filter, limit?: number): Promise<number>;
|
|
119
|
+
aggregate(request: AggregateRequest): Promise<AggregateResult>;
|
|
110
120
|
countEach(items: readonly CountItem[], limit?: number): Promise<number[]>;
|
|
111
121
|
private countOn;
|
|
122
|
+
private aggregateOn;
|
|
112
123
|
/**
|
|
113
124
|
* One compiled read's rows, BigInts and all. A read that could hold the
|
|
114
125
|
* server's one thread — a count, a filter or a sort over a large table —
|
|
@@ -222,7 +233,7 @@ export declare class SqliteAdapter implements Adapter {
|
|
|
222
233
|
* scope or bearer authority.
|
|
223
234
|
*/
|
|
224
235
|
private journalTransaction;
|
|
225
|
-
scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T
|
|
236
|
+
scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance): Promise<T>;
|
|
226
237
|
/** Private source-owner boundary, deliberately absent from Adapter. The
|
|
227
238
|
* verifier is trusted host code, never a business callback or wire value.
|
|
228
239
|
* It must be synchronous and may not retain the raw handle. */
|