@mistriwork/engine 1.0.0-rc.50 → 1.0.0-rc.51
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.
|
@@ -63,6 +63,31 @@ export declare const isForeignKeyViolation: (error: unknown) => boolean;
|
|
|
63
63
|
* refusal; what the operator reads names the constraint and nothing of the row.
|
|
64
64
|
*/
|
|
65
65
|
export declare const foreignKeyRefusal: (error: unknown) => ScopeRefusal;
|
|
66
|
+
/** The columns of `table` whose unique rule refused a write, or undefined where the error names another table, an
|
|
67
|
+
* expression, an exclusion, or nothing it can read. */
|
|
68
|
+
export declare function uniqueColumns(error: unknown, table: Pick<TableMeta, 'name' | 'schema'>): string[] | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* Whether a unique refusal on `columns` names a row the principal reads: some group of its rule fixes every one of
|
|
71
|
+
* those columns' values (`=` and nothing else), and the row written holds exactly those values. Any row the unique rule
|
|
72
|
+
* compared equal to it then holds them too, and is inside the same group, so long as the index compares those columns
|
|
73
|
+
* no more loosely than the scope does. That is what the engine cannot read off the error, so only a comparison that is
|
|
74
|
+
* attested counts:
|
|
75
|
+
* - on SQLite (`sqlite`), a column the scope compares by its bytes (`binary`): a tenant's owner column, which every
|
|
76
|
+
* unique index of a tenant table must compare BINARY (the tenant write source's assertUniqueKeys). Any other
|
|
77
|
+
* condition is compared under the column's collation, where `UNIQUE (email COLLATE NOCASE)` finds 'X' equal to an
|
|
78
|
+
* 'x' the scope tells apart, so the refusal stays generic;
|
|
79
|
+
* - on PostgreSQL, a condition under the column's own collation: an index compares by it unless it names another, and
|
|
80
|
+
* a tenant's owner column must be deterministic in every unique index (tenantPostgresCatalog.ts).
|
|
81
|
+
* A tenant's own table answers so, by the owner column its unique indexes include: the conflicting row is the tenant's
|
|
82
|
+
* own. A rule that reads the whole table answers so whatever the index compares.
|
|
83
|
+
*/
|
|
84
|
+
export declare function uniqueConflictSeen(rule: RowScope[string], columns: readonly string[], row: Readonly<Record<string, unknown>>, sqlite: boolean): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* A unique rule's refusal of a scoped write, where the row it conflicts with may be one the principal cannot read:
|
|
87
|
+
* said as the scope's own refusal, so neither the column nor the fact that the value is taken outside its rows is
|
|
88
|
+
* named. The operator reads the table and the columns, never the value.
|
|
89
|
+
*/
|
|
90
|
+
export declare const uniqueRefusal: (table: Pick<TableMeta, 'id'>, columns: readonly string[] | undefined) => ScopeRefusal;
|
|
66
91
|
/** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
|
|
67
92
|
export declare const triggerNames: (names: readonly string[]) => string;
|
|
68
93
|
export { blocksEveryWrite, sayBlocked, sayRuns, sayTriggers, type ScopeTrigger } from './scopeTriggers.js';
|
|
@@ -158,6 +183,31 @@ export declare function sameTables(scope: Readonly<Record<string, unknown>>, bou
|
|
|
158
183
|
* words stay value-free, the reason recorded beneath them for the owner. */
|
|
159
184
|
export declare class ScopeRefusal extends Refusal {
|
|
160
185
|
}
|
|
186
|
+
/** The sentence a delete hears when every row still referencing it is one its principal cannot read. */
|
|
187
|
+
export declare const IN_USE = "This record is in use and can't be deleted.";
|
|
188
|
+
/**
|
|
189
|
+
* A delete refused because rows still reference the row, said as the record's state rather than as the scope: the
|
|
190
|
+
* person can act on it. Its words name only what the principal reads — the referencing table and how many of its
|
|
191
|
+
* rows point here, counted under the principal's own rows — and, where every remaining reference is one the scope
|
|
192
|
+
* hides (another tenant's row on a shared parent, a row the policy keeps from them), name nothing: {@link IN_USE}.
|
|
193
|
+
* That the delete is refused at all is the one thing such a row still says, and it cannot be otherwise: deleting it
|
|
194
|
+
* would reach that row. The total across every row is recorded for the operator only.
|
|
195
|
+
*/
|
|
196
|
+
export declare class ReferencedRefusal extends ScopeRefusal {
|
|
197
|
+
/** What the principal reads of the references: the table and its count, or nothing when it reads none. */
|
|
198
|
+
readonly seen?: {
|
|
199
|
+
readonly table: string;
|
|
200
|
+
readonly count: number;
|
|
201
|
+
} | undefined;
|
|
202
|
+
constructor(
|
|
203
|
+
/** What the principal reads of the references: the table and its count, or nothing when it reads none. */
|
|
204
|
+
seen?: {
|
|
205
|
+
readonly table: string;
|
|
206
|
+
readonly count: number;
|
|
207
|
+
} | undefined);
|
|
208
|
+
}
|
|
209
|
+
/** The ReferencedRefusal a failure was rebuilt over, however many value-free wrappers lie between. */
|
|
210
|
+
export declare function referencedBeneath(error: unknown): ReferencedRefusal | undefined;
|
|
161
211
|
/**
|
|
162
212
|
* The principal's scope and the reads it compiles to, for a transaction that
|
|
163
213
|
* may create a parent and then its children. A scope is resolved before the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Refusal } from '../adapter.js';
|
|
2
2
|
import { buildWhere } from '../../shared/filter.js';
|
|
3
|
-
import { authorFault, recordRefusalCause } from '../../shared/refusal.js';
|
|
3
|
+
import { authorFault, recordRefusalCause, refusalCause, sayRefusal } from '../../shared/refusal.js';
|
|
4
4
|
import { coerceForColumn, columnKind } from '../../shared/schema.js';
|
|
5
5
|
import { blockingTriggers, firedBy, sayRuns, sayTriggers, sayWrite } from './scopeTriggers.js';
|
|
6
6
|
import { detachStoredText, overlaid, storedText, storedTextOf } from './storedText.js';
|
|
@@ -21,6 +21,74 @@ export const foreignKeyRefusal = (error) => {
|
|
|
21
21
|
const constraint = error?.constraint;
|
|
22
22
|
return recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), `The database's foreign key${typeof constraint === 'string' ? ` ${JSON.stringify(constraint)}` : ''} refused the write: a row it points at is not in the principal's rows, or does not exist.`);
|
|
23
23
|
};
|
|
24
|
+
/** Whether a failure is a unique rule refusing a write: SQLite's PRIMARY KEY and UNIQUE, PostgreSQL's 23505 and 23P01. */
|
|
25
|
+
const isUniqueViolation = (error) => {
|
|
26
|
+
const { code, errcode } = (error ?? {});
|
|
27
|
+
return errcode === 1555 || errcode === 2067 || code === '23505' || code === '23P01';
|
|
28
|
+
};
|
|
29
|
+
/* A column as each engine names it in a unique refusal, and nothing else: the names only, never the values
|
|
30
|
+
(engine/src/server/constraints.ts reads the same, for a form's field, where the adapters cannot import it). */
|
|
31
|
+
const COLUMN_NAME = /^[A-Za-z_][\w$]{0,127}$/;
|
|
32
|
+
/** The columns of `table` whose unique rule refused a write, or undefined where the error names another table, an
|
|
33
|
+
* expression, an exclusion, or nothing it can read. */
|
|
34
|
+
export function uniqueColumns(error, table) {
|
|
35
|
+
const e = (error ?? {});
|
|
36
|
+
let names;
|
|
37
|
+
if (e.code === '23505') {
|
|
38
|
+
// A trigger or a cascade can break another table's rule: only the table written is judged.
|
|
39
|
+
if (e.table !== table.name || (typeof e.schema === 'string' && table.schema && e.schema !== table.schema))
|
|
40
|
+
return undefined;
|
|
41
|
+
const head = typeof e.detail === 'string' ? /^Key \(([^()]*)\)=\(/.exec(e.detail) : null;
|
|
42
|
+
names = head?.[1].split(',').map((name) => name.trim());
|
|
43
|
+
}
|
|
44
|
+
else if (typeof e.message === 'string') {
|
|
45
|
+
const said = /^UNIQUE constraint failed: (.+)$/.exec(e.message);
|
|
46
|
+
names = said?.[1].split(',').map((part) => {
|
|
47
|
+
const at = part.trim();
|
|
48
|
+
return at.startsWith(`${table.name}.`) ? at.slice(table.name.length + 1) : '';
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return names?.length && names.every((name) => COLUMN_NAME.test(name)) ? [...new Set(names)] : undefined;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Whether a unique refusal on `columns` names a row the principal reads: some group of its rule fixes every one of
|
|
55
|
+
* those columns' values (`=` and nothing else), and the row written holds exactly those values. Any row the unique rule
|
|
56
|
+
* compared equal to it then holds them too, and is inside the same group, so long as the index compares those columns
|
|
57
|
+
* no more loosely than the scope does. That is what the engine cannot read off the error, so only a comparison that is
|
|
58
|
+
* attested counts:
|
|
59
|
+
* - on SQLite (`sqlite`), a column the scope compares by its bytes (`binary`): a tenant's owner column, which every
|
|
60
|
+
* unique index of a tenant table must compare BINARY (the tenant write source's assertUniqueKeys). Any other
|
|
61
|
+
* condition is compared under the column's collation, where `UNIQUE (email COLLATE NOCASE)` finds 'X' equal to an
|
|
62
|
+
* 'x' the scope tells apart, so the refusal stays generic;
|
|
63
|
+
* - on PostgreSQL, a condition under the column's own collation: an index compares by it unless it names another, and
|
|
64
|
+
* a tenant's owner column must be deterministic in every unique index (tenantPostgresCatalog.ts).
|
|
65
|
+
* A tenant's own table answers so, by the owner column its unique indexes include: the conflicting row is the tenant's
|
|
66
|
+
* own. A rule that reads the whole table answers so whatever the index compares.
|
|
67
|
+
*/
|
|
68
|
+
export function uniqueConflictSeen(rule, columns, row, sqlite) {
|
|
69
|
+
if (rule === true)
|
|
70
|
+
return true;
|
|
71
|
+
if (rule === false)
|
|
72
|
+
return false;
|
|
73
|
+
return rule.groups.some((group) => group.length > 0 &&
|
|
74
|
+
group.every((condition) => !isViaCondition(condition) &&
|
|
75
|
+
condition.op === '=' &&
|
|
76
|
+
condition.other === undefined &&
|
|
77
|
+
condition.collation === undefined &&
|
|
78
|
+
condition.equality === undefined &&
|
|
79
|
+
(!sqlite || rule.binary?.includes(condition.column) === true) &&
|
|
80
|
+
columns.includes(condition.column) &&
|
|
81
|
+
condition.value !== undefined &&
|
|
82
|
+
!Array.isArray(condition.value) &&
|
|
83
|
+
Object.hasOwn(row, condition.column) &&
|
|
84
|
+
row[condition.column] === condition.value));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A unique rule's refusal of a scoped write, where the row it conflicts with may be one the principal cannot read:
|
|
88
|
+
* said as the scope's own refusal, so neither the column nor the fact that the value is taken outside its rows is
|
|
89
|
+
* named. The operator reads the table and the columns, never the value.
|
|
90
|
+
*/
|
|
91
|
+
export const uniqueRefusal = (table, columns) => recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), `A unique rule on "${table.id}"${columns ? ` (${columns.map((column) => JSON.stringify(column)).join(', ')})` : ''} refused the write, and the row it conflicts with may be outside the principal's rows.`);
|
|
24
92
|
/** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
|
|
25
93
|
export const triggerNames = (names) => `the trigger${names.length === 1 ? '' : 's'} ${names.map((name) => JSON.stringify(name)).join(', ')}`;
|
|
26
94
|
/* The trigger vocabulary, for `mistri check` (commandTriggerChecks.ts), which says the same refusal ahead of time. */
|
|
@@ -114,6 +182,39 @@ export class ScopeRefusal extends Refusal {
|
|
|
114
182
|
const refuse = (reason) => {
|
|
115
183
|
throw recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), reason);
|
|
116
184
|
};
|
|
185
|
+
/** The sentence a delete hears when every row still referencing it is one its principal cannot read. */
|
|
186
|
+
export const IN_USE = "This record is in use and can't be deleted.";
|
|
187
|
+
/**
|
|
188
|
+
* A delete refused because rows still reference the row, said as the record's state rather than as the scope: the
|
|
189
|
+
* person can act on it. Its words name only what the principal reads — the referencing table and how many of its
|
|
190
|
+
* rows point here, counted under the principal's own rows — and, where every remaining reference is one the scope
|
|
191
|
+
* hides (another tenant's row on a shared parent, a row the policy keeps from them), name nothing: {@link IN_USE}.
|
|
192
|
+
* That the delete is refused at all is the one thing such a row still says, and it cannot be otherwise: deleting it
|
|
193
|
+
* would reach that row. The total across every row is recorded for the operator only.
|
|
194
|
+
*/
|
|
195
|
+
export class ReferencedRefusal extends ScopeRefusal {
|
|
196
|
+
seen;
|
|
197
|
+
constructor(
|
|
198
|
+
/** What the principal reads of the references: the table and its count, or nothing when it reads none. */
|
|
199
|
+
seen) {
|
|
200
|
+
super(seen
|
|
201
|
+
? `${seen.count === 1 ? 'A record' : `${seen.count} records`} in "${seen.table}" still ${seen.count === 1 ? 'points' : 'point'} at this one. Change or remove ${seen.count === 1 ? 'it' : 'them'} first, then try again.`
|
|
202
|
+
: IN_USE);
|
|
203
|
+
this.seen = seen;
|
|
204
|
+
this.name = 'ReferencedRefusal';
|
|
205
|
+
sayRefusal(this, this.message);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** The ReferencedRefusal a failure was rebuilt over, however many value-free wrappers lie between. */
|
|
209
|
+
export function referencedBeneath(error) {
|
|
210
|
+
let at = error;
|
|
211
|
+
for (let depth = 0; at !== null && typeof at === 'object' && depth < 16; depth++) {
|
|
212
|
+
if (at instanceof ReferencedRefusal)
|
|
213
|
+
return at;
|
|
214
|
+
at = refusalCause(at) ?? (at instanceof Error ? at.cause : undefined);
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
117
218
|
const isViaCondition = (condition) => typeof condition.via?.resource === 'string';
|
|
118
219
|
const keyText = (key) => Object.entries(key)
|
|
119
220
|
.map(([column, value]) => `${column} ${JSON.stringify(value)}`)
|
|
@@ -199,6 +300,28 @@ referencesOf) {
|
|
|
199
300
|
reads = own.reads(scope, false);
|
|
200
301
|
guards = own.reads(scope, true);
|
|
201
302
|
};
|
|
303
|
+
/* A row still referenced, said in what the principal reads of it. The total above counts every row on the writer, as
|
|
304
|
+
the cascade would reach them; how many of those the principal reads is counted again under its own rows, by each
|
|
305
|
+
referencing column as the child compares — where the foreign key matches more than that (a parent collation the
|
|
306
|
+
child lacks), fewer are named, never more, and none named is the sentence that names nothing. */
|
|
307
|
+
const referencedRefusal = async (table, key, referenced) => {
|
|
308
|
+
const cause = `A scoped command may not delete the "${table.id}" row ${keyText(key)}: ${referenced
|
|
309
|
+
.map(({ fk, total }) => `"${fk.from.table}" still references it (${total} ${total === 1 ? 'row' : 'rows'} in all)`)
|
|
310
|
+
.join(', ')}.`;
|
|
311
|
+
for (const { fk, values } of referenced) {
|
|
312
|
+
const seen = await reads
|
|
313
|
+
.count(fk.from.table, { groups: [fk.from.columns.map((column, index) => ({ column, op: '=', value: values[index] }))] })
|
|
314
|
+
.catch((error) => {
|
|
315
|
+
// A table the principal does not read at all reads none of the references: refused as the one that names nothing.
|
|
316
|
+
if (error instanceof Refusal)
|
|
317
|
+
return 0;
|
|
318
|
+
throw error;
|
|
319
|
+
});
|
|
320
|
+
if (seen > 0)
|
|
321
|
+
return recordRefusalCause(new ReferencedRefusal({ table: fk.from.table, count: seen }), cause);
|
|
322
|
+
}
|
|
323
|
+
return recordRefusalCause(new ReferencedRefusal(), cause);
|
|
324
|
+
};
|
|
202
325
|
const target = (id, write) => {
|
|
203
326
|
const table = catalog.schema.tables.find((table) => table.id === id);
|
|
204
327
|
if (!table)
|
|
@@ -527,11 +650,23 @@ referencesOf) {
|
|
|
527
650
|
/* The statements themselves. A foreign key that refuses one answers as a hidden parent does (foreignKeyRefusal):
|
|
528
651
|
the checks before a write compare what it names, and this is everything they cannot see — a default's part of a
|
|
529
652
|
reference, a value a trigger writes, a deferred check. */
|
|
530
|
-
|
|
531
|
-
|
|
653
|
+
/* A unique rule that refuses one names its column, and on PostgreSQL the value, of a row that may be outside the
|
|
654
|
+
principal's rows: that the value is taken there is what the scope keeps. It is let through only where the
|
|
655
|
+
conflicting row is one the principal reads (uniqueConflictSeen); otherwise it is the scope's own refusal. */
|
|
656
|
+
const statement = (sent, table, row) => sent.catch((error) => {
|
|
657
|
+
if (isForeignKeyViolation(error))
|
|
658
|
+
throw foreignKeyRefusal(error);
|
|
659
|
+
if (isUniqueViolation(error) && table) {
|
|
660
|
+
const columns = uniqueColumns(error, table);
|
|
661
|
+
// With a scope present, a table it does not name has no rows the principal reads (shared/rowScope.ts).
|
|
662
|
+
const rule = scope === undefined ? true : Object.hasOwn(scope, table.id) ? scope[table.id] : false;
|
|
663
|
+
if (!columns || !uniqueConflictSeen(rule, columns, row ?? {}, typeof error.errcode === 'number'))
|
|
664
|
+
throw uniqueRefusal(table, columns);
|
|
665
|
+
}
|
|
666
|
+
throw error;
|
|
532
667
|
});
|
|
533
|
-
const insertRow = (request) => statement(records.insert(request));
|
|
534
|
-
const updateRow = (request) => statement(records.update(request));
|
|
668
|
+
const insertRow = (table, request) => statement(records.insert(request), table, request.values ?? {});
|
|
669
|
+
const updateRow = (table, request, row) => statement(records.update(request), table, row);
|
|
535
670
|
const afterward = async (afterwards, images) => {
|
|
536
671
|
for (const next of afterwards ?? [])
|
|
537
672
|
await next(images);
|
|
@@ -551,7 +686,7 @@ referencesOf) {
|
|
|
551
686
|
const given = unproven(parentChecks(table, request.values ?? {}, undefined, true));
|
|
552
687
|
if (!locks?.together)
|
|
553
688
|
await verify(given);
|
|
554
|
-
const result = locks?.together ? await parentsFirst(given, () => insertRow(request)) : await insertRow(request);
|
|
689
|
+
const result = locks?.together ? await parentsFirst(given, () => insertRow(table, request)) : await insertRow(table, request);
|
|
555
690
|
const filter = keyFilter(table, result.key);
|
|
556
691
|
/* The new row locked and read back, and where the writer sends together
|
|
557
692
|
its references checked in the same flight, from the row the INSERT
|
|
@@ -588,7 +723,8 @@ referencesOf) {
|
|
|
588
723
|
const set = new Set(Object.keys(request.values ?? {}));
|
|
589
724
|
const afterwards = proof && (await proof.before(table, { kind: 'update', set: [...set] }, proof.images.update(table, before, request.values)));
|
|
590
725
|
// What the update sets is given; every other column of a reference it sets in part is as stored, bound as its text.
|
|
591
|
-
const
|
|
726
|
+
const written = overlaid(before, request.values);
|
|
727
|
+
const given = unproven(parentChecks(table, written, set, true));
|
|
592
728
|
if (!locks?.together)
|
|
593
729
|
await verify(given);
|
|
594
730
|
/* The row read again after the write, sent the moment the write is: it
|
|
@@ -605,7 +741,9 @@ referencesOf) {
|
|
|
605
741
|
let result;
|
|
606
742
|
try {
|
|
607
743
|
// The references it sets leave ahead of it, in its flight (parentsFirst).
|
|
608
|
-
result = locks?.together
|
|
744
|
+
result = locks?.together
|
|
745
|
+
? await parentsFirst(given, () => updateRow(table, request, written))
|
|
746
|
+
: await updateRow(table, request, written);
|
|
609
747
|
}
|
|
610
748
|
finally {
|
|
611
749
|
withdraw?.();
|
|
@@ -637,6 +775,7 @@ referencesOf) {
|
|
|
637
775
|
are counted: across every row of each table, on the writer itself,
|
|
638
776
|
since the principal sees every row the bound holds there and a row
|
|
639
777
|
outside the bound pointing in is the one a cascade must never reach. */
|
|
778
|
+
const referenced = [];
|
|
640
779
|
for (const fk of children) {
|
|
641
780
|
const values = fk.to.columns.map((column) => row[column]);
|
|
642
781
|
if (values.some((value) => value === null))
|
|
@@ -644,9 +783,14 @@ referencesOf) {
|
|
|
644
783
|
if (!values.every(comparable))
|
|
645
784
|
return refuse(`"${table.id}".${fk.to.columns.join('+')} holds a value that is not a text or a number.`);
|
|
646
785
|
const key = { groups: [Object.entries(request.key).map(([column, value]) => ({ column, op: '=', value }))] };
|
|
647
|
-
|
|
648
|
-
|
|
786
|
+
const total = await counted?.(fk, key);
|
|
787
|
+
if (total === undefined)
|
|
788
|
+
return refuse(`A scoped command may not delete the "${table.id}" row ${keyText(request.key)}: its references were not counted.`);
|
|
789
|
+
if (total !== 0)
|
|
790
|
+
referenced.push({ fk, values, total });
|
|
649
791
|
}
|
|
792
|
+
if (referenced.length)
|
|
793
|
+
throw await referencedRefusal(table, request.key, referenced);
|
|
650
794
|
const afterwards = proof && (await proof.before(table, { kind: 'delete' }, proof.images.delete(row)));
|
|
651
795
|
const result = await statement(records.remove(request));
|
|
652
796
|
if (result.affected !== 1)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mistriwork/engine",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.51",
|
|
4
4
|
"description": "The engine both products stand on: the adapters (SQLite, Postgres), the catalog, the query language, keyset pages, the HTTP kit and the shared rules. No React.",
|
|
5
5
|
"homepage": "https://mistriwork.dev",
|
|
6
6
|
"bugs": {
|