@ultimat3/entity 31.49.0 → 31.50.0
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/package.json +5 -5
- package/src/check-refusal.ts +38 -0
- package/src/expr-connectives.ts +117 -0
- package/src/expr.ts +3 -27
- package/src/index.ts +1 -0
- package/src/pg-driver.ts +7 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/entity",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.50.0",
|
|
4
4
|
"description": "A table + its domain type + invariants the database also enforces",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -45,9 +45,9 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@ultimat3/core": "31.
|
|
49
|
-
"@ultimat3/db": "31.
|
|
50
|
-
"@ultimat3/schema": "31.
|
|
51
|
-
"@ultimat3/time": "31.
|
|
48
|
+
"@ultimat3/core": "31.50.0",
|
|
49
|
+
"@ultimat3/db": "31.50.0",
|
|
50
|
+
"@ultimat3/schema": "31.50.0",
|
|
51
|
+
"@ultimat3/time": "31.50.0"
|
|
52
52
|
}
|
|
53
53
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Single responsibility: a CHECK the server enforced on an entity's own invariant answers as that
|
|
2
|
+
// invariant. `insert` judges the whole row before the statement; a patch (`update`, `updateWhere`)
|
|
3
|
+
// only becomes a row on the server, so there the CHECK is the first judge and its `23514` is the
|
|
4
|
+
// same refusal — `X_INVARIANT_VIOLATED`, a 422, never `X_DB_STATEMENT_FAILED`, a 500.
|
|
5
|
+
|
|
6
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
7
|
+
import { namesConstraint, sqlState } from '@ultimat3/db';
|
|
8
|
+
import type { EntityCore } from './entity';
|
|
9
|
+
import { invariantViolated } from './errors';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `check_violation`. Not a row of `@ultimat3/db`'s `SQLSTATE`: that table is the states the db
|
|
13
|
+
* layer classifies into its own codes, and this one it leaves to the entity that declared the CHECK.
|
|
14
|
+
*/
|
|
15
|
+
const CHECK_VIOLATION = '23514';
|
|
16
|
+
|
|
17
|
+
/** A table name without its schema: the server reports the relation's own name. */
|
|
18
|
+
const bareTable = (table: string): string => table.slice(table.lastIndexOf('.') + 1);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The invariant refusal `error` stands for, or `error` itself. Only a check this entity declares
|
|
22
|
+
* is rewritten: a hand-written constraint the declaration does not know stays the server's
|
|
23
|
+
* verdict, because no rule here can name what it means. And only on the entity's own table: a
|
|
24
|
+
* constraint name is unique per table, so a trigger's write to another table whose CHECK shares
|
|
25
|
+
* a rule's name is that table's failure, not this rule's. A driver that names no table is judged
|
|
26
|
+
* by the constraint alone, as before.
|
|
27
|
+
*/
|
|
28
|
+
export const asInvariantRefusal = (entity: EntityCore<unknown>, error: unknown): unknown => {
|
|
29
|
+
if (sqlState(error) !== CHECK_VIOLATION || !isUltimateError(error)) return error;
|
|
30
|
+
const constraint = error.meta?.['constraint'];
|
|
31
|
+
if (typeof constraint !== 'string') return error;
|
|
32
|
+
const table = error.meta?.['table'];
|
|
33
|
+
if (typeof table === 'string' && table !== bareTable(entity.$table)) return error;
|
|
34
|
+
const rule = entity.$invariants.find(
|
|
35
|
+
(inv) => inv.kind === 'check' && namesConstraint(entity.$table, inv, constraint),
|
|
36
|
+
);
|
|
37
|
+
return rule === undefined ? error : invariantViolated(entity.$name, rule.name, rule.message);
|
|
38
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Single responsibility: the connectives over invariant expressions — `allOf` (and), `anyOf` (or),
|
|
2
|
+
// and the operand rules `iff` shares with them. One declaration still compiles to both enforcement
|
|
3
|
+
// points: a three-valued verdict the app runs and the SQL predicate a CHECK or a partial index
|
|
4
|
+
// carries, so "both null" and "at most one set" are one rule, never a hand-written index.
|
|
5
|
+
|
|
6
|
+
import type { Expr } from './expr';
|
|
7
|
+
import { check, type Verdict, verdictOf } from './expr-verdict';
|
|
8
|
+
import { refuseInvariant } from './refuse';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Every operand of a combinator is a predicate: a `unique` is an `Expr` whose SQL is a COLUMN LIST,
|
|
12
|
+
* so combining one is refused where it was written, naming the rule the author meant to declare.
|
|
13
|
+
*/
|
|
14
|
+
export const assertPredicates = (combinator: string, sides: readonly Expr[]): void => {
|
|
15
|
+
for (const side of sides) {
|
|
16
|
+
if (side.kind !== 'unique') continue;
|
|
17
|
+
// The columns it names, so the pasted line is the rule the author already meant to declare —
|
|
18
|
+
// never a `<name>` for them to fill in, which is the placeholder `refuse.test.ts` refuses.
|
|
19
|
+
//
|
|
20
|
+
// `JSON.stringify` and never `'${column}'`: a column path is a VALUE reaching TypeScript
|
|
21
|
+
// SOURCE, which is this file's own hazard one layer up. `columns: { "o'brien": text() }` is a
|
|
22
|
+
// legal declaration and `unique()` is reached untyped besides, so a quote ends the literal and
|
|
23
|
+
// the fix stops parsing; a backslash is the half doubling the quote would still have missed.
|
|
24
|
+
// `errors.ts`'s `asLiteral` is the same rule for the same reason.
|
|
25
|
+
const columns = side.paths.map((path) => path.join('.'));
|
|
26
|
+
const list = columns.map((column) => JSON.stringify(column)).join(', ');
|
|
27
|
+
const name = JSON.stringify(`${columns.join('_')}_unique`);
|
|
28
|
+
refuseInvariant(
|
|
29
|
+
combinator,
|
|
30
|
+
`${side.message} is a unique constraint, whose SQL is a column list and not a predicate`,
|
|
31
|
+
`invariant(${name}, c.unique([${list}])) # uniqueness is its own invariant; ${combinator} takes predicates, e.g. iff(c.status.eq('published'), c.publishedAt.isNotNull())`,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The paths every operand reads, each once, in the order they were first named. */
|
|
37
|
+
export const operandPaths = (sides: readonly Expr[]): readonly (readonly string[])[] => {
|
|
38
|
+
const seen = new Set<string>();
|
|
39
|
+
const paths: (readonly string[])[] = [];
|
|
40
|
+
for (const path of sides.flatMap((side) => side.paths)) {
|
|
41
|
+
// The whole segment list, never `join('.')`: a property literally named `amount.minor` and the
|
|
42
|
+
// `minor` part of a money `amount` are two columns, and the dot would make them one.
|
|
43
|
+
const key = JSON.stringify(path);
|
|
44
|
+
if (seen.has(key)) continue;
|
|
45
|
+
seen.add(key);
|
|
46
|
+
paths.push(path);
|
|
47
|
+
}
|
|
48
|
+
return paths;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Two or more operands, or a combinator that combines nothing: `allOf(x)` is `x`, and writing it
|
|
53
|
+
* says the author meant a second condition they left out.
|
|
54
|
+
*/
|
|
55
|
+
const assertOperands = (combinator: string, sides: readonly Expr[]): void => {
|
|
56
|
+
if (sides.length >= 2) return;
|
|
57
|
+
// The fix names only what the author already wrote: their one operand's own columns, never a
|
|
58
|
+
// column this generator would be inventing for an entity it cannot see.
|
|
59
|
+
const column = sides[0]?.paths[0]?.join('.');
|
|
60
|
+
refuseInvariant(
|
|
61
|
+
combinator,
|
|
62
|
+
`takes two or more predicates, got ${sides.length}`,
|
|
63
|
+
column === undefined
|
|
64
|
+
? `${combinator}(first, second) # two predicates over this entity's columns, or none: drop the ${combinator}() call`
|
|
65
|
+
: `unwrap ${combinator}(…) and pass its one predicate on ${JSON.stringify(column)} directly # or add the second condition beside it inside ${combinator}(…)`,
|
|
66
|
+
);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* One connective over its operands: SQL as each operand parenthesised and joined by `keyword`, and
|
|
71
|
+
* the verdict in SQL's three values. One app-only operand makes the WHOLE rule app-only — emitting
|
|
72
|
+
* the rest would enforce a rule the author never wrote, and a partial index refuses it by name.
|
|
73
|
+
*/
|
|
74
|
+
const connective = (
|
|
75
|
+
combinator: string,
|
|
76
|
+
keyword: 'and' | 'or',
|
|
77
|
+
joiner: string,
|
|
78
|
+
sides: readonly Expr[],
|
|
79
|
+
verdict: (answers: readonly (boolean | null)[]) => boolean | null,
|
|
80
|
+
): Expr => {
|
|
81
|
+
assertOperands(combinator, sides);
|
|
82
|
+
assertPredicates(combinator, sides);
|
|
83
|
+
const verdicts: readonly Verdict[] = sides.map(verdictOf);
|
|
84
|
+
return check(
|
|
85
|
+
operandPaths(sides),
|
|
86
|
+
sides.map((side) => side.message).join(joiner),
|
|
87
|
+
(resolve) => {
|
|
88
|
+
const parts = sides.map((side) => side.toSql(resolve));
|
|
89
|
+
return parts.some((part) => part === null)
|
|
90
|
+
? null
|
|
91
|
+
: parts.map((part) => `(${part})`).join(` ${keyword} `);
|
|
92
|
+
},
|
|
93
|
+
(row) => verdict(verdicts.map((judge) => judge(row))),
|
|
94
|
+
);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Every operand holds: `allOf(c.a.isNull(), c.b.isNull())` — "both unset", rendered
|
|
99
|
+
* `(a is null) and (b is null)`. Three-valued as SQL's `and`: false when any operand is false,
|
|
100
|
+
* else unknown when any is unknown (which a CHECK passes), else true. For a rule, two invariants
|
|
101
|
+
* are the same conjunction; this is for where one predicate must say it — an index `where`, or
|
|
102
|
+
* inside `anyOf`/`iff`.
|
|
103
|
+
*/
|
|
104
|
+
export const allOf = (...sides: readonly Expr[]): Expr =>
|
|
105
|
+
connective('allOf', 'and', ', and ', sides, (answers) =>
|
|
106
|
+
answers.includes(false) ? false : answers.includes(null) ? null : true,
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* At least one operand holds: `anyOf(c.a.isNull(), c.b.isNull())` — "at most one of the two set",
|
|
111
|
+
* rendered `(a is null) or (b is null)`. Three-valued as SQL's `or`: true when any operand is
|
|
112
|
+
* true, else unknown when any is unknown, else false.
|
|
113
|
+
*/
|
|
114
|
+
export const anyOf = (...sides: readonly Expr[]): Expr =>
|
|
115
|
+
connective('anyOf', 'or', ', or ', sides, (answers) =>
|
|
116
|
+
answers.includes(true) ? true : answers.includes(null) ? null : false,
|
|
117
|
+
);
|
package/src/expr.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import { literal as sqlLiteral } from '@ultimat3/db';
|
|
16
16
|
import { invariantViolated } from './errors';
|
|
17
|
+
import { assertPredicates, operandPaths } from './expr-connectives';
|
|
17
18
|
import { check, unknownOnNull, verdictOf } from './expr-verdict';
|
|
18
19
|
import { isNullish } from './is-null';
|
|
19
20
|
import { DECIMAL_TEXT, numericOrder } from './numeric-compare';
|
|
@@ -398,33 +399,8 @@ const satisfies = (predicate: RowPredicate, columns: readonly string[]): Expr =>
|
|
|
398
399
|
* `isNull()`/`isNotNull()` are total, which is what makes a rule built from them decide a NULL.
|
|
399
400
|
*/
|
|
400
401
|
export const iff = (left: Expr, right: Expr): Expr => {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
// The columns it names, so the pasted line is the rule the author already meant to declare —
|
|
404
|
-
// never a `<name>` for them to fill in, which is the placeholder `refuse.test.ts` refuses.
|
|
405
|
-
//
|
|
406
|
-
// `JSON.stringify` and never `'${column}'`: a column path is a VALUE reaching TypeScript
|
|
407
|
-
// SOURCE, which is this file's own hazard one layer up. `columns: { "o'brien": text() }` is a
|
|
408
|
-
// legal declaration and `unique()` is reached untyped besides, so a quote ends the literal and
|
|
409
|
-
// the fix stops parsing; a backslash is the half doubling the quote would still have missed.
|
|
410
|
-
// `errors.ts`'s `asLiteral` is the same rule for the same reason.
|
|
411
|
-
const columns = side.paths.map((path) => path.join('.'));
|
|
412
|
-
const list = columns.map((column) => JSON.stringify(column)).join(', ');
|
|
413
|
-
const name = JSON.stringify(`${columns.join('_')}_unique`);
|
|
414
|
-
refuseInvariant(
|
|
415
|
-
'iff',
|
|
416
|
-
`${side.message} is a unique constraint, whose SQL is a column list and not a predicate`,
|
|
417
|
-
`invariant(${name}, c.unique([${list}])) # uniqueness is its own invariant; iff takes two predicates, e.g. iff(c.status.eq('published'), c.publishedAt.isNotNull())`,
|
|
418
|
-
);
|
|
419
|
-
}
|
|
420
|
-
const seen = new Set<string>();
|
|
421
|
-
const paths: (readonly string[])[] = [];
|
|
422
|
-
for (const path of [...left.paths, ...right.paths]) {
|
|
423
|
-
const key = path.join('.');
|
|
424
|
-
if (seen.has(key)) continue;
|
|
425
|
-
seen.add(key);
|
|
426
|
-
paths.push(path);
|
|
427
|
-
}
|
|
402
|
+
assertPredicates('iff', [left, right]);
|
|
403
|
+
const paths = operandPaths([left, right]);
|
|
428
404
|
return check(
|
|
429
405
|
paths,
|
|
430
406
|
`${left.message} exactly when ${right.message}`,
|
package/src/index.ts
CHANGED
|
@@ -72,6 +72,7 @@ export {
|
|
|
72
72
|
} from './errors';
|
|
73
73
|
export type { ColumnExpr, Expr, InvariantColumns, Resolve } from './expr';
|
|
74
74
|
export { iff } from './expr';
|
|
75
|
+
export { allOf, anyOf } from './expr-connectives';
|
|
75
76
|
/** The two DECLARED capabilities' refusals — a third-party driver raises the same ones. */
|
|
76
77
|
export type { HistoryColumns, HistoryEntity, HistoryInit } from './history';
|
|
77
78
|
export type { HistoryRecord, HistoryVersion } from './history-order';
|
package/src/pg-driver.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
withStatementAttribution,
|
|
18
18
|
} from '@ultimat3/db';
|
|
19
19
|
import { appendOnlyRepo } from './append-only';
|
|
20
|
+
import { asInvariantRefusal } from './check-refusal';
|
|
20
21
|
import { entityNow } from './clock';
|
|
21
22
|
import { coalesceFindById } from './coalesce';
|
|
22
23
|
import { cursorFor, seekFrom } from './cursor';
|
|
@@ -191,12 +192,17 @@ export const postgresRepo = <Row>(
|
|
|
191
192
|
* before the statement, not after), and where a keyed request's write names itself in the WAL
|
|
192
193
|
* (`write-tag.ts`). The one funnel for an autocommit repository write, so it is also where a scope
|
|
193
194
|
* whose caller was already answered stops: the pool does not refuse, and must not (`runOn`).
|
|
195
|
+
* A CHECK refusing the row is the entity's invariant answering, as `insert` answers it.
|
|
194
196
|
*/
|
|
195
197
|
const writing = async <T>(send: () => Promise<T>): Promise<T> => {
|
|
196
198
|
refuseAbandoned();
|
|
197
199
|
forgetPreloaded();
|
|
198
200
|
await stampHistoryActor(entity, config.client !== undefined);
|
|
199
|
-
|
|
201
|
+
try {
|
|
202
|
+
return await taggedWrite(config.client !== undefined, send);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
throw asInvariantRefusal(entity as EntityCore<unknown>, error);
|
|
205
|
+
}
|
|
200
206
|
};
|
|
201
207
|
|
|
202
208
|
/**
|