ezship 0.1.16 → 0.1.18
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/README.md +60 -56
- package/access.d.mts +4 -4
- package/access.mjs +13 -13
- package/account.mjs +9 -8
- package/bindings.mjs +9 -27
- package/commands.d.mts +65 -67
- package/commands.mjs +1274 -535
- package/connections.d.mts +2 -3
- package/connections.mjs +10 -22
- package/cron.d.mts +1 -1
- package/cron.mjs +1 -1
- package/documents.d.mts +1 -1
- package/documents.mjs +1 -1
- package/editor-types.json.gz +0 -0
- package/editor.mjs +22 -56
- package/ez.mjs +48 -133
- package/package.json +7 -1
- package/paths.d.mts +24 -0
- package/paths.mjs +103 -0
- package/schema.d.mts +45 -49
- package/schema.mjs +364 -219
- package/session.d.mts +2 -3
- package/session.mjs +3 -5
- package/shape.d.mts +2 -2
- package/shape.mjs +1 -1
- package/signup.mjs +2 -2
- package/types.d.mts +73 -73
- package/update-check.mjs +1 -1
- package/workflow.d.mts +8 -2
- package/workflow.mjs +88 -21
package/schema.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The App Database rules (docs/adr/
|
|
1
|
+
// The App Database rules (docs/adr/0217): what a Site
|
|
2
2
|
// may declare in db/schema.sql, how a declaration becomes DDL, and what a Builder may run with `ez db sql`.
|
|
3
3
|
// Zero dependencies, plain JavaScript, Node 20+ and the browser. RULES is the single source: the parser, the
|
|
4
4
|
// planner, `ez help db` and every error message read it, so documentation cannot drift from behaviour.
|
|
@@ -22,9 +22,9 @@ export const TABLE_PREFIX = "data_";
|
|
|
22
22
|
export const PLATFORM_PREFIX = "data_ez_";
|
|
23
23
|
/**
|
|
24
24
|
* The App Database operations a server function's or job's `db` sends to the Host, each with the argument
|
|
25
|
-
* counts the Host accepts (docs/adr/
|
|
25
|
+
* counts the Host accepts (docs/adr/0228). The guest's `db` is built from these keys and the Host validates
|
|
26
26
|
* against them; the page `db` has the same methods plus `upload`, and both derive `count` from `aggregate`.
|
|
27
|
-
* A Global lib module's `Database` type is exactly these and `count` (docs/adr/
|
|
27
|
+
* A Global lib module's `Database` type is exactly these and `count` (docs/adr/0210).
|
|
28
28
|
* @type {typeof import("./schema.d.mts").DATABASE_OPERATIONS}
|
|
29
29
|
*/
|
|
30
30
|
export const DATABASE_OPERATIONS = Object.freeze({
|
|
@@ -32,15 +32,15 @@ export const DATABASE_OPERATIONS = Object.freeze({
|
|
|
32
32
|
query: Object.freeze([1, 2]),
|
|
33
33
|
aggregate: Object.freeze([1, 2]),
|
|
34
34
|
get: Object.freeze([2]),
|
|
35
|
-
// A write's optional last argument is its options, `{ why }` (docs/adr/
|
|
35
|
+
// A write's optional last argument is its options, `{ why }` (docs/adr/0211).
|
|
36
36
|
insert: Object.freeze([2, 3]),
|
|
37
37
|
update: Object.freeze([3, 4]),
|
|
38
38
|
delete: Object.freeze([2, 3]),
|
|
39
|
-
// A workflow action on a row (docs/adr/
|
|
39
|
+
// A workflow action on a row (docs/adr/0227): table, id, action, then an optional patch and options.
|
|
40
40
|
transition: Object.freeze([3, 4, 5]),
|
|
41
41
|
});
|
|
42
42
|
/**
|
|
43
|
-
* What server code's `db` has beyond `DATABASE_OPERATIONS` (docs/adr/
|
|
43
|
+
* What server code's `db` has beyond `DATABASE_OPERATIONS` (docs/adr/0249), with the argument counts the Host
|
|
44
44
|
* accepts: many rows in one database operation. Never a page's, a Table rule's or the `Database` a lib module takes.
|
|
45
45
|
* @type {typeof import("./schema.d.mts").SERVER_DATABASE_OPERATIONS}
|
|
46
46
|
*/
|
|
@@ -53,17 +53,17 @@ export const SERVER_DATABASE_OPERATIONS = Object.freeze({
|
|
|
53
53
|
deleteMany: Object.freeze([2, 3]),
|
|
54
54
|
});
|
|
55
55
|
/**
|
|
56
|
-
* The most rows one many-row operation writes (docs/adr/
|
|
56
|
+
* The most rows one many-row operation writes (docs/adr/0228).
|
|
57
57
|
* @type {typeof import("./schema.d.mts").MANY_ROWS}
|
|
58
58
|
*/
|
|
59
59
|
export const MANY_ROWS = 1000;
|
|
60
60
|
/**
|
|
61
|
-
* The longest Push message and write reason (docs/adr/
|
|
61
|
+
* The longest Push message and write reason (docs/adr/0211), in characters.
|
|
62
62
|
* @type {typeof import("./schema.d.mts").MAX_MESSAGE_CHARS}
|
|
63
63
|
*/
|
|
64
64
|
export const MAX_MESSAGE_CHARS = 500;
|
|
65
65
|
/**
|
|
66
|
-
* A Push message or write reason as stored (docs/adr/
|
|
66
|
+
* A Push message or write reason as stored (docs/adr/0211): trimmed, null when absent or blank, an error
|
|
67
67
|
* when it is not a string or too long.
|
|
68
68
|
* @type {typeof import("./schema.d.mts").messageText}
|
|
69
69
|
*/
|
|
@@ -87,7 +87,7 @@ export const SYSTEM_COLUMNS = Object.freeze([
|
|
|
87
87
|
"updated_by",
|
|
88
88
|
]);
|
|
89
89
|
/**
|
|
90
|
-
* Table History (docs/adr/
|
|
90
|
+
* Table History (docs/adr/0218): every Table `t` has a read-only `t_history` the platform writes.
|
|
91
91
|
* @type {typeof import("./schema.d.mts").HISTORY_SUFFIX}
|
|
92
92
|
*/
|
|
93
93
|
export const HISTORY_SUFFIX = "_history";
|
|
@@ -131,24 +131,24 @@ export const NAME_RE = /^[a-z][a-z0-9_]{0,62}$/;
|
|
|
131
131
|
*/
|
|
132
132
|
export const VALUE_RE = /^[A-Za-z0-9_ .-]{1,64}$/;
|
|
133
133
|
/**
|
|
134
|
-
* What a FILE column holds (docs/adr/
|
|
134
|
+
* What a FILE column holds (docs/adr/0221): an Attachment id, the platform's random id, URL-safe.
|
|
135
135
|
* @type {typeof import("./schema.d.mts").ATTACHMENT_ID_RE}
|
|
136
136
|
*/
|
|
137
137
|
export const ATTACHMENT_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
138
138
|
/**
|
|
139
|
-
* What a MEMBER column holds (docs/adr/
|
|
139
|
+
* What a MEMBER column holds (docs/adr/0225): a Member's actor id, the form of `created_by` and `actors.id`.
|
|
140
140
|
* @type {typeof import("./schema.d.mts").MEMBER_ID_RE}
|
|
141
141
|
*/
|
|
142
142
|
export const MEMBER_ID_RE = /^user:[A-Za-z0-9_-]{1,128}$/;
|
|
143
143
|
/**
|
|
144
|
-
* A Member group's name (docs/adr/
|
|
144
|
+
* A Member group's name (docs/adr/0225): on the Instance's roster, named by `group(<name>)` in access rules.
|
|
145
145
|
* @type {typeof import("./schema.d.mts").GROUP_RE}
|
|
146
146
|
*/
|
|
147
147
|
export const GROUP_RE = /^[a-z][a-z0-9-]{0,39}$/;
|
|
148
148
|
/** @type {typeof import("./schema.d.mts").MAX_GROUPS} */
|
|
149
149
|
export const MAX_GROUPS = 50;
|
|
150
150
|
/**
|
|
151
|
-
* The Host's own groups (docs/adr/
|
|
151
|
+
* The Host's own groups (docs/adr/0225): `ez-admin` is held by the Instance's Admins, `ez-builder` by every
|
|
152
152
|
* Builder, each through the Member identity with their email. Tested like any group, never assigned or
|
|
153
153
|
* declared; every other `ez-` name is reserved and held by no one.
|
|
154
154
|
* @type {typeof import("./schema.d.mts").RESERVED_GROUPS}
|
|
@@ -175,13 +175,11 @@ export const RULES = Object.freeze({
|
|
|
175
175
|
policies: Object.freeze(/** @type {const} */ (["member", "none"])),
|
|
176
176
|
/** Constructs the parser refuses, with the reason an agent needs. Keys are matched as whole words, in order. */
|
|
177
177
|
refused: Object.freeze({
|
|
178
|
-
"
|
|
179
|
-
"
|
|
180
|
-
|
|
181
|
-
UNIQUE:
|
|
182
|
-
"declare CREATE UNIQUE INDEX ON <table> (<columns>) below the table instead (docs/adr/0046)",
|
|
178
|
+
"NOT NULL": "all user-defined columns are nullable; require values in the app's workflow",
|
|
179
|
+
"PRIMARY KEY":
|
|
180
|
+
"every Table's key is the platform's `id`; a business key is UNIQUE on its column (docs/adr/0204)",
|
|
183
181
|
AUTOINCREMENT:
|
|
184
|
-
"write <name> INTEGER SEQUENCE: the platform numbers rows per Table (docs/adr/
|
|
182
|
+
"write <name> INTEGER SEQUENCE: the platform numbers rows per Table (docs/adr/0217)",
|
|
185
183
|
COLLATE: "collations are not supported",
|
|
186
184
|
"WITHOUT ROWID": "not supported",
|
|
187
185
|
STRICT: "every table is strict already",
|
|
@@ -215,6 +213,19 @@ export const RULES = Object.freeze({
|
|
|
215
213
|
"ratelimit",
|
|
216
214
|
"app_members",
|
|
217
215
|
]),
|
|
216
|
+
/**
|
|
217
|
+
* Standard SQL the parser reads as the Declaration's own form (docs/adr/0204): what an author writes first,
|
|
218
|
+
* and what it means here. `ez help db` prints the list.
|
|
219
|
+
*/
|
|
220
|
+
accepted: Object.freeze({
|
|
221
|
+
"<column> ... UNIQUE": "CREATE UNIQUE INDEX ON <table> (<column>)",
|
|
222
|
+
"UNIQUE (<columns>)": "CREATE UNIQUE INDEX ON <table> (<columns>)",
|
|
223
|
+
"FOREIGN KEY (<column>) REFERENCES <table>": "REFERENCES <table> on that column",
|
|
224
|
+
"REFERENCES <table> (id)": "REFERENCES <table>: a reference always holds the row's id",
|
|
225
|
+
"id ... PRIMARY KEY [AUTOINCREMENT], PRIMARY KEY (id)":
|
|
226
|
+
"nothing: every Table has the platform's `id`, a string",
|
|
227
|
+
"CONSTRAINT <name>": "nothing: the name is ignored",
|
|
228
|
+
}),
|
|
218
229
|
limits: Object.freeze({ tablesPerInstance: 500, columnsPerTable: 200, valuesPerCheck: 50 }),
|
|
219
230
|
});
|
|
220
231
|
|
|
@@ -278,7 +289,7 @@ function tokenize(sql) {
|
|
|
278
289
|
i++;
|
|
279
290
|
continue;
|
|
280
291
|
}
|
|
281
|
-
// A number (a DEFAULT, docs/adr/
|
|
292
|
+
// A number (a DEFAULT, docs/adr/0224) may carry a sign and a fraction; a name never starts with a digit.
|
|
282
293
|
const m = /^-?[0-9]+\.[0-9]+(?![A-Za-z0-9_])|^-[0-9]+(?![A-Za-z0-9_.])|^[A-Za-z0-9_]+/.exec(
|
|
283
294
|
sql.slice(i),
|
|
284
295
|
);
|
|
@@ -326,7 +337,7 @@ function checkName(name, what, line) {
|
|
|
326
337
|
};
|
|
327
338
|
if (what === "table" && name.endsWith(HISTORY_SUFFIX))
|
|
328
339
|
return {
|
|
329
|
-
error: `${what} "${name}": the ${HISTORY_SUFFIX} suffix is reserved for History (docs/adr/
|
|
340
|
+
error: `${what} "${name}": the ${HISTORY_SUFFIX} suffix is reserved for History (docs/adr/0218)`,
|
|
330
341
|
line,
|
|
331
342
|
};
|
|
332
343
|
if (name in HISTORY_COLUMNS)
|
|
@@ -345,7 +356,7 @@ function checkName(name, what, line) {
|
|
|
345
356
|
function splitStatements(tokens) {
|
|
346
357
|
const statements = [];
|
|
347
358
|
let comments = [];
|
|
348
|
-
/** The comments inside a statement: a column's doc is the one on its line (docs/adr/
|
|
359
|
+
/** The comments inside a statement: a column's doc is the one on its line (docs/adr/0222). */
|
|
349
360
|
let inner = [];
|
|
350
361
|
let current = [];
|
|
351
362
|
let lastLine = 0;
|
|
@@ -386,7 +397,7 @@ function parsePolicies(comments) {
|
|
|
386
397
|
const value = RULES.policies.find((policy) => policy === m[2].toLowerCase());
|
|
387
398
|
if (!value)
|
|
388
399
|
return {
|
|
389
|
-
error: `${m[1].toLowerCase()} policy "${m[2]}" must be member or none
|
|
400
|
+
error: `${m[1].toLowerCase()} policy "${m[2]}" must be member or none.`,
|
|
390
401
|
line: c.line,
|
|
391
402
|
};
|
|
392
403
|
out[/** @type {"read" | "write"} */ (m[1].toLowerCase())] = value;
|
|
@@ -398,7 +409,7 @@ function parsePolicies(comments) {
|
|
|
398
409
|
const DEFAULT_MAX_CHARS = 256;
|
|
399
410
|
|
|
400
411
|
/**
|
|
401
|
-
* The token after DEFAULT (docs/adr/
|
|
412
|
+
* The token after DEFAULT (docs/adr/0224): a quoted string, a number, true/false, now or me. Checked against
|
|
402
413
|
* the column's type once the whole definition is read.
|
|
403
414
|
* @param {Token | undefined} t @param {string} column @param {number} line
|
|
404
415
|
* @returns {{value: import("./schema.d.mts").ColumnDefault, quoted: boolean} | ParseError}
|
|
@@ -443,7 +454,7 @@ function defaultError(col, d, column, line) {
|
|
|
443
454
|
if (v.kind === "me")
|
|
444
455
|
return col.type === "MEMBER"
|
|
445
456
|
? null
|
|
446
|
-
: { error: `column "${column}": DEFAULT me needs a MEMBER column (docs/adr/
|
|
457
|
+
: { error: `column "${column}": DEFAULT me needs a MEMBER column (docs/adr/0225)`, line };
|
|
447
458
|
if (col.type === "MEMBER")
|
|
448
459
|
return { error: `column "${column}": a MEMBER column's DEFAULT is me`, line };
|
|
449
460
|
if (v.kind === "now")
|
|
@@ -480,8 +491,8 @@ function defaultError(col, d, column, line) {
|
|
|
480
491
|
}
|
|
481
492
|
|
|
482
493
|
/**
|
|
483
|
-
* One column definition: `<name> [<type>] [
|
|
484
|
-
* @param {Token[]} tokens @param {number} line @returns {{name: string, column: Column} | ParseError}
|
|
494
|
+
* One column definition: `<name> [<type>] [REFERENCES <table>] [CHECK (<name> IN (...))] [DEFAULT <value>] [SEQUENCE] [UNIQUE]`.
|
|
495
|
+
* @param {Token[]} tokens @param {number} line @returns {{name: string, unique: boolean, column: Column} | ParseError}
|
|
485
496
|
*/
|
|
486
497
|
function parseColumn(tokens, line) {
|
|
487
498
|
const [nameTok, ...rest] = tokens;
|
|
@@ -490,13 +501,17 @@ function parseColumn(tokens, line) {
|
|
|
490
501
|
if (bad) return refuse(bad, line);
|
|
491
502
|
const nameErr = checkName(nameTok.text, "column", line);
|
|
492
503
|
if (nameErr) return nameErr;
|
|
493
|
-
if (isWord(nameTok, "DEFAULT"))
|
|
494
|
-
return {
|
|
504
|
+
if (isWord(nameTok, "DEFAULT") || isWord(nameTok, "UNIQUE") || isWord(nameTok, "FOREIGN"))
|
|
505
|
+
return {
|
|
506
|
+
error: `column "${nameTok.text}": ${nameTok.text.toUpperCase()} is a keyword; pick another name`,
|
|
507
|
+
line,
|
|
508
|
+
};
|
|
495
509
|
/** @type {{value: import("./schema.d.mts").ColumnDefault, quoted: boolean} | null} */
|
|
496
510
|
let fallback = null;
|
|
497
511
|
/** @type {Omit<Column, "type"> & {type: Column["type"] | null}} */
|
|
498
512
|
const col = { type: null, required: false, ref: null, values: null };
|
|
499
513
|
let sequence = false;
|
|
514
|
+
let unique = false;
|
|
500
515
|
/** @type {string | undefined} */
|
|
501
516
|
let label;
|
|
502
517
|
/** @type {"restrict" | undefined} */
|
|
@@ -508,7 +523,7 @@ function parseColumn(tokens, line) {
|
|
|
508
523
|
}
|
|
509
524
|
/** @type {string | undefined} */
|
|
510
525
|
let shape;
|
|
511
|
-
// `JSON TYPE '<shape>'` (docs/adr/
|
|
526
|
+
// `JSON TYPE '<shape>'` (docs/adr/0236): the column's TypeScript type and what every write must match.
|
|
512
527
|
if (isWord(rest[i], "TYPE")) {
|
|
513
528
|
const text = rest[i + 1];
|
|
514
529
|
if (col.type !== "JSON")
|
|
@@ -526,20 +541,30 @@ function parseColumn(tokens, line) {
|
|
|
526
541
|
while (i < rest.length) {
|
|
527
542
|
const key = refusedAt(rest, i);
|
|
528
543
|
if (key) return refuse(key, line);
|
|
529
|
-
if (isWord(rest[i], "NOT") && isWord(rest[i + 1], "NULL")) {
|
|
530
|
-
col.required = true;
|
|
531
|
-
i += 2;
|
|
532
|
-
continue;
|
|
533
|
-
}
|
|
534
544
|
const referenced = rest[i + 1];
|
|
535
545
|
if (isWord(rest[i], "REFERENCES") && referenced?.kind === "word") {
|
|
536
546
|
const refErr = checkName(referenced.text, "referenced table", line);
|
|
537
547
|
if (refErr) return refErr;
|
|
538
548
|
col.ref = referenced.text;
|
|
539
549
|
i += 2;
|
|
550
|
+
// `REFERENCES <table> (id)` (docs/adr/0204): a reference always holds the row's id, so naming it adds nothing.
|
|
551
|
+
if (rest[i]?.kind === "(") {
|
|
552
|
+
if (!isWord(rest[i + 1], "ID") || rest[i + 2]?.kind !== ")")
|
|
553
|
+
return {
|
|
554
|
+
error: `column "${nameTok.text}": a reference holds the referenced row's id; write REFERENCES ${referenced.text} or REFERENCES ${referenced.text} (id)`,
|
|
555
|
+
line,
|
|
556
|
+
};
|
|
557
|
+
i += 3;
|
|
558
|
+
}
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
// `<column> ... UNIQUE` (docs/adr/0204): the Table's unique index over this one column.
|
|
562
|
+
if (isWord(rest[i], "UNIQUE")) {
|
|
563
|
+
unique = true;
|
|
564
|
+
i++;
|
|
540
565
|
continue;
|
|
541
566
|
}
|
|
542
|
-
// `REFERENCES <table> ON DELETE RESTRICT` (docs/adr/
|
|
567
|
+
// `REFERENCES <table> ON DELETE RESTRICT` (docs/adr/0222): the referenced row cannot be deleted while
|
|
543
568
|
// this column holds its id. DELETE is otherwise a refused word, so the clause is read whole here.
|
|
544
569
|
if (isWord(rest[i], "ON") && isWord(rest[i + 1], "DELETE")) {
|
|
545
570
|
if (col.ref === null)
|
|
@@ -549,7 +574,7 @@ function parseColumn(tokens, line) {
|
|
|
549
574
|
};
|
|
550
575
|
if (!isWord(rest[i + 2], "RESTRICT"))
|
|
551
576
|
return {
|
|
552
|
-
error: `column "${nameTok.text}": ON DELETE takes RESTRICT only (CASCADE and SET NULL are not supported, docs/adr/
|
|
577
|
+
error: `column "${nameTok.text}": ON DELETE takes RESTRICT only (CASCADE and SET NULL are not supported, docs/adr/0222)`,
|
|
553
578
|
line,
|
|
554
579
|
};
|
|
555
580
|
onDelete = "restrict";
|
|
@@ -583,7 +608,7 @@ function parseColumn(tokens, line) {
|
|
|
583
608
|
continue;
|
|
584
609
|
}
|
|
585
610
|
return {
|
|
586
|
-
error: `unexpected ${upper(rest[i])} in column "${nameTok.text}": a column is <name> <type> [TYPE '<shape>'] [
|
|
611
|
+
error: `unexpected ${upper(rest[i])} in column "${nameTok.text}": a column is <name> <type> [TYPE '<shape>'] [REFERENCES <table> [ON DELETE RESTRICT]] [CHECK (<name> IN ('a', 'b'))] [DEFAULT <value>] [SEQUENCE] [UNIQUE] [LABEL '<label>']`,
|
|
587
612
|
line,
|
|
588
613
|
};
|
|
589
614
|
}
|
|
@@ -597,7 +622,7 @@ function parseColumn(tokens, line) {
|
|
|
597
622
|
}
|
|
598
623
|
if (col.values && col.type !== "TEXT")
|
|
599
624
|
return { error: `column "${nameTok.text}": CHECK (... IN (...)) needs a TEXT column`, line };
|
|
600
|
-
// `<name> JSON REFERENCES <table>` (docs/adr/
|
|
625
|
+
// `<name> JSON REFERENCES <table>` (docs/adr/0219): a list of ids, stored as JSON TYPE 'string[]'.
|
|
601
626
|
if (col.type === "JSON" && col.ref !== null) {
|
|
602
627
|
if (shape !== undefined && shape !== "string[]")
|
|
603
628
|
return {
|
|
@@ -608,22 +633,22 @@ function parseColumn(tokens, line) {
|
|
|
608
633
|
}
|
|
609
634
|
if (col.type === "FILE" && col.ref !== null)
|
|
610
635
|
return {
|
|
611
|
-
error: `column "${nameTok.text}": a FILE column holds an Attachment id and cannot REFERENCES a table (docs/adr/
|
|
636
|
+
error: `column "${nameTok.text}": a FILE column holds an Attachment id and cannot REFERENCES a table (docs/adr/0221)`,
|
|
612
637
|
line,
|
|
613
638
|
};
|
|
614
639
|
if (onDelete && col.type === "JSON")
|
|
615
640
|
return {
|
|
616
|
-
error: `column "${nameTok.text}": an id list takes no ON DELETE; only a single reference can restrict deletes (docs/adr/
|
|
641
|
+
error: `column "${nameTok.text}": an id list takes no ON DELETE; only a single reference can restrict deletes (docs/adr/0222)`,
|
|
617
642
|
line,
|
|
618
643
|
};
|
|
619
644
|
if (col.type === "MEMBER" && col.ref !== null)
|
|
620
645
|
return {
|
|
621
|
-
error: `column "${nameTok.text}": a MEMBER column holds a Member and cannot REFERENCES a table (docs/adr/
|
|
646
|
+
error: `column "${nameTok.text}": a MEMBER column holds a Member and cannot REFERENCES a table (docs/adr/0225)`,
|
|
622
647
|
line,
|
|
623
648
|
};
|
|
624
649
|
if (sequence && (col.type !== "INTEGER" || col.ref !== null))
|
|
625
650
|
return {
|
|
626
|
-
error: `column "${nameTok.text}": SEQUENCE needs a plain INTEGER column (the platform numbers rows per Table, docs/adr/
|
|
651
|
+
error: `column "${nameTok.text}": SEQUENCE needs a plain INTEGER column (the platform numbers rows per Table, docs/adr/0217)`,
|
|
627
652
|
line,
|
|
628
653
|
};
|
|
629
654
|
const typed = {
|
|
@@ -635,8 +660,10 @@ function parseColumn(tokens, line) {
|
|
|
635
660
|
const bad = defaultError(typed, fallback, nameTok.text, line);
|
|
636
661
|
if (bad) return bad;
|
|
637
662
|
}
|
|
663
|
+
// A column's UNIQUE is the unique index CREATE UNIQUE INDEX declares, on any type, as SQLite holds it.
|
|
638
664
|
return {
|
|
639
665
|
name: nameTok.text,
|
|
666
|
+
unique,
|
|
640
667
|
column: {
|
|
641
668
|
...typed,
|
|
642
669
|
...(shape ? { shape } : {}),
|
|
@@ -647,13 +674,13 @@ function parseColumn(tokens, line) {
|
|
|
647
674
|
};
|
|
648
675
|
}
|
|
649
676
|
|
|
650
|
-
/** The longest LABEL, in characters (docs/adr/
|
|
677
|
+
/** The longest LABEL, in characters (docs/adr/0222). */
|
|
651
678
|
const LABEL_MAX_CHARS = 80;
|
|
652
|
-
/** The longest column doc, in characters (docs/adr/
|
|
679
|
+
/** The longest column doc, in characters (docs/adr/0222). */
|
|
653
680
|
const DOC_MAX_CHARS = 500;
|
|
654
681
|
|
|
655
682
|
/**
|
|
656
|
-
* The quoted text after LABEL (docs/adr/
|
|
683
|
+
* The quoted text after LABEL (docs/adr/0222): one line, at most LABEL_MAX_CHARS.
|
|
657
684
|
* @param {Token | undefined} t @param {string} what @param {number} line @returns {string | ParseError}
|
|
658
685
|
*/
|
|
659
686
|
function labelText(t, what, line) {
|
|
@@ -737,6 +764,121 @@ function parseList(tokens, i, line) {
|
|
|
737
764
|
return { groups, next: j + 1 };
|
|
738
765
|
}
|
|
739
766
|
|
|
767
|
+
/**
|
|
768
|
+
* The column definitions of a Table's list, with the standard table constraints read into them
|
|
769
|
+
* (docs/adr/0204): `UNIQUE (<columns>)` is a unique index, `FOREIGN KEY (<column>) REFERENCES <table>` joins
|
|
770
|
+
* that column's own definition, and `PRIMARY KEY (id)` and an `id ... PRIMARY KEY` column say what every Table
|
|
771
|
+
* has already. A leading `CONSTRAINT <name>` is dropped.
|
|
772
|
+
* @param {Token[][]} groups @param {string} table @param {number} line
|
|
773
|
+
* @returns {{columns: Token[][], unique: string[][], ends: number[]} | ParseError}
|
|
774
|
+
*/
|
|
775
|
+
function tableConstraints(groups, table, line) {
|
|
776
|
+
/** @type {Token[][]} */
|
|
777
|
+
const columns = [];
|
|
778
|
+
/** @type {string[][]} */
|
|
779
|
+
const unique = [];
|
|
780
|
+
/** @type {{column: string, rest: Token[], line: number}[]} */
|
|
781
|
+
const foreign = [];
|
|
782
|
+
/** The last line of a column's own definition, where a FOREIGN KEY's words joined it. @type {Record<number, number>} */
|
|
783
|
+
const ends = {};
|
|
784
|
+
/**
|
|
785
|
+
* The bare names in the parentheses at `at`.
|
|
786
|
+
* @param {Token[]} g @param {number} at @param {string} what
|
|
787
|
+
* @returns {{names: string[], next: number} | ParseError}
|
|
788
|
+
*/
|
|
789
|
+
const names = (g, at, what) => {
|
|
790
|
+
const followed = {
|
|
791
|
+
error: `table "${table}": ${what} is followed by (<columns>)`,
|
|
792
|
+
line: g[0].line,
|
|
793
|
+
};
|
|
794
|
+
if (g[at]?.kind !== "(") return followed;
|
|
795
|
+
const list = parseList(g, at, g[0].line);
|
|
796
|
+
if ("error" in list || list.groups.length === 0) return followed;
|
|
797
|
+
/** @type {string[]} */
|
|
798
|
+
const out = [];
|
|
799
|
+
// As CREATE INDEX reads them: `(a b)`, a comma missing, is no list of two.
|
|
800
|
+
for (const group of list.groups) {
|
|
801
|
+
if (group.length !== 1 || group[0].kind !== "word")
|
|
802
|
+
return {
|
|
803
|
+
error: `table "${table}": ${what} lists bare column names, separated by commas`,
|
|
804
|
+
line: g[0].line,
|
|
805
|
+
};
|
|
806
|
+
out.push(group[0].text);
|
|
807
|
+
}
|
|
808
|
+
return { names: out, next: list.next };
|
|
809
|
+
};
|
|
810
|
+
for (const whole of groups) {
|
|
811
|
+
if (whole.length === 0) return { error: `table "${table}": empty column definition`, line };
|
|
812
|
+
const g =
|
|
813
|
+
isWord(whole[0], "CONSTRAINT") && whole[1]?.kind === "word" && whole.length > 2
|
|
814
|
+
? whole.slice(2)
|
|
815
|
+
: whole;
|
|
816
|
+
if (isWord(g[0], "UNIQUE") && g[1]?.kind === "(") {
|
|
817
|
+
const r = names(g, 1, "UNIQUE");
|
|
818
|
+
if ("error" in r) return r;
|
|
819
|
+
if (r.next < g.length)
|
|
820
|
+
return {
|
|
821
|
+
error: `table "${table}": unexpected ${upper(g[r.next])} after UNIQUE (...)`,
|
|
822
|
+
line: g[0].line,
|
|
823
|
+
};
|
|
824
|
+
unique.push(r.names);
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
if (isWord(g[0], "PRIMARY") && isWord(g[1], "KEY")) {
|
|
828
|
+
const r = names(g, 2, "PRIMARY KEY");
|
|
829
|
+
if ("error" in r) return r;
|
|
830
|
+
if (r.names.length !== 1 || r.names[0].toLowerCase() !== "id" || r.next < g.length)
|
|
831
|
+
return refuse("PRIMARY KEY", g[0].line);
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
if (isWord(g[0], "FOREIGN") && isWord(g[1], "KEY")) {
|
|
835
|
+
const r = names(g, 2, "FOREIGN KEY");
|
|
836
|
+
if ("error" in r) return r;
|
|
837
|
+
if (r.names.length !== 1 || !isWord(g[r.next], "REFERENCES"))
|
|
838
|
+
return {
|
|
839
|
+
error: `table "${table}": a foreign key is FOREIGN KEY (<column>) REFERENCES <table>, one column`,
|
|
840
|
+
line: g[0].line,
|
|
841
|
+
};
|
|
842
|
+
foreign.push({ column: r.names[0], rest: g.slice(r.next), line: g[0].line });
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
// A Table CHECK: what a column's CHECK (<column> IN (...)) says, and nothing else, is supported.
|
|
846
|
+
if (isWord(g[0], "CHECK") && g[1]?.kind === "(")
|
|
847
|
+
return {
|
|
848
|
+
error: `table "${table}": a table's CHECK is not supported; put CHECK (<column> IN ('a', 'b')) on the column`,
|
|
849
|
+
line: g[0].line,
|
|
850
|
+
};
|
|
851
|
+
// `id INTEGER PRIMARY KEY AUTOINCREMENT`: the Table's key, which the platform declares for every Table. A
|
|
852
|
+
// REFERENCES or CHECK on it would say something the dropped line cannot keep.
|
|
853
|
+
if (isWord(g[0], "ID") && g.some((t, k) => isWord(t, "PRIMARY") && isWord(g[k + 1], "KEY"))) {
|
|
854
|
+
if (g.some((t) => isWord(t, "REFERENCES") || isWord(t, "CHECK")))
|
|
855
|
+
return {
|
|
856
|
+
error: `table "${table}": the id line declares the platform's key and is dropped, so it takes no REFERENCES or CHECK; put them on a column of their own`,
|
|
857
|
+
line: g[0].line,
|
|
858
|
+
};
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
columns.push(g);
|
|
862
|
+
}
|
|
863
|
+
for (const f of foreign) {
|
|
864
|
+
const at = columns.findIndex((g) => g[0].kind === "word" && g[0].text === f.column);
|
|
865
|
+
if (at < 0)
|
|
866
|
+
return {
|
|
867
|
+
error: `table "${table}": FOREIGN KEY names "${f.column}", which it does not declare`,
|
|
868
|
+
line: f.line,
|
|
869
|
+
};
|
|
870
|
+
if (columns[at].some((t) => isWord(t, "REFERENCES")))
|
|
871
|
+
return {
|
|
872
|
+
error: `table "${table}": "${f.column}" has REFERENCES and a FOREIGN KEY; keep one`,
|
|
873
|
+
line: f.line,
|
|
874
|
+
};
|
|
875
|
+
ends[at] ??= columns[at][columns[at].length - 1].line;
|
|
876
|
+
columns[at] = [...columns[at], ...f.rest];
|
|
877
|
+
}
|
|
878
|
+
if (columns.length === 0) return { error: `table "${table}" needs at least one column`, line };
|
|
879
|
+
return { columns, unique, ends: columns.map((g, k) => ends[k] ?? g[g.length - 1].line) };
|
|
880
|
+
}
|
|
881
|
+
|
|
740
882
|
/** @param {Token[]} tokens @param {Token[]} comments @param {Record<string, Table>} tables @param {Token[]} [inner] @returns {{name: string, table: Table} | ParseError} */
|
|
741
883
|
function parseCreateTable(tokens, comments, tables, inner = []) {
|
|
742
884
|
const line = tokens[0].line;
|
|
@@ -753,19 +895,23 @@ function parseCreateTable(tokens, comments, tables, inner = []) {
|
|
|
753
895
|
if ("error" in list) return list;
|
|
754
896
|
if (list.groups.length === 0 || list.groups.every((g) => g.length === 0))
|
|
755
897
|
return { error: `table "${nameTok.text}" needs at least one column`, line };
|
|
898
|
+
const sorted = tableConstraints(list.groups, nameTok.text, line);
|
|
899
|
+
if ("error" in sorted) return sorted;
|
|
756
900
|
/** @type {Record<string, Column>} */
|
|
757
901
|
const columns = {};
|
|
758
|
-
|
|
759
|
-
|
|
902
|
+
/** @type {string[][]} */
|
|
903
|
+
const unique = [...sorted.unique];
|
|
904
|
+
for (const [k, g] of sorted.columns.entries()) {
|
|
760
905
|
const col = parseColumn(g, g[0].line);
|
|
761
906
|
if ("error" in col) return col;
|
|
907
|
+
if (col.unique) unique.push([col.name]);
|
|
762
908
|
if (col.name in columns)
|
|
763
909
|
return {
|
|
764
910
|
error: `column "${col.name}" is declared twice in "${nameTok.text}"`,
|
|
765
911
|
line: g[0].line,
|
|
766
912
|
};
|
|
767
|
-
// A column's doc is the comment on its own line (docs/adr/
|
|
768
|
-
const last =
|
|
913
|
+
// A column's doc is the comment on its own line (docs/adr/0222).
|
|
914
|
+
const last = sorted.ends[k];
|
|
769
915
|
const doc = inner
|
|
770
916
|
.filter((c) => c.line >= g[0].line && c.line <= last)
|
|
771
917
|
.map((c) => c.text ?? "")
|
|
@@ -789,16 +935,26 @@ function parseCreateTable(tokens, comments, tables, inner = []) {
|
|
|
789
935
|
if ("error" in policies) return policies;
|
|
790
936
|
/** @type {Table} */
|
|
791
937
|
const table = { columns, indexes: [], ...options.options };
|
|
938
|
+
for (const cols of unique) {
|
|
939
|
+
const missing = cols.find((c) => !Object.hasOwn(columns, c) && !SYSTEM_COLUMNS.includes(c));
|
|
940
|
+
if (missing !== undefined)
|
|
941
|
+
return {
|
|
942
|
+
error: `table "${nameTok.text}": UNIQUE names "${missing}", which it does not declare`,
|
|
943
|
+
line,
|
|
944
|
+
};
|
|
945
|
+
if (!(table.unique ?? []).some((have) => indexKey(have) === indexKey(cols)))
|
|
946
|
+
(table.unique ??= []).push(cols);
|
|
947
|
+
}
|
|
792
948
|
if (policies.policies.read) table.read = policies.policies.read;
|
|
793
949
|
if (policies.policies.write) table.write = policies.policies.write;
|
|
794
950
|
return { name: nameTok.text, table };
|
|
795
951
|
}
|
|
796
952
|
|
|
797
|
-
/** The most columns EXACTLY ONE OF names (docs/adr/
|
|
953
|
+
/** The most columns EXACTLY ONE OF names (docs/adr/0222). */
|
|
798
954
|
const EXACTLY_ONE_MAX = 8;
|
|
799
955
|
|
|
800
956
|
/**
|
|
801
|
-
* What follows a Table's column list (docs/adr/
|
|
957
|
+
* What follows a Table's column list (docs/adr/0222), in any order: `LABEL '<singular>' ['<plural>']`,
|
|
802
958
|
* `DISPLAY (<columns>)`, `SINGLETON` and `EXACTLY ONE OF (<columns>)`.
|
|
803
959
|
* @param {Token[]} tokens @param {number} i @param {string} name @param {Record<string, Column>} columns @param {number} line
|
|
804
960
|
* @returns {{options: Pick<Table, "label" | "plural" | "display" | "singleton" | "exactlyOne">} | ParseError}
|
|
@@ -888,7 +1044,7 @@ function parseTableOptions(tokens, i, name, columns, line) {
|
|
|
888
1044
|
|
|
889
1045
|
/**
|
|
890
1046
|
* `CREATE [UNIQUE] INDEX [IF NOT EXISTS] [<name>] ON <table> (<columns>)`; a unique index is enforced by the
|
|
891
|
-
* engine (docs/adr/
|
|
1047
|
+
* engine (docs/adr/0217).
|
|
892
1048
|
* @param {Token[]} tokens @param {Record<string, Table>} tables @param {boolean} unique @returns {{} | ParseError}
|
|
893
1049
|
*/
|
|
894
1050
|
function parseCreateIndex(tokens, tables, unique) {
|
|
@@ -913,6 +1069,7 @@ function parseCreateIndex(tokens, tables, unique) {
|
|
|
913
1069
|
};
|
|
914
1070
|
const list = parseList(tokens, i + 2, line);
|
|
915
1071
|
if ("error" in list) return list;
|
|
1072
|
+
/** @type {string[]} */
|
|
916
1073
|
const cols = [];
|
|
917
1074
|
for (const g of list.groups) {
|
|
918
1075
|
if (g.length !== 1 || g[0].kind !== "word")
|
|
@@ -924,13 +1081,16 @@ function parseCreateIndex(tokens, tables, unique) {
|
|
|
924
1081
|
if (cols.length === 0) return { error: "an index needs at least one column", line };
|
|
925
1082
|
if (list.next < tokens.length)
|
|
926
1083
|
return { error: `unexpected ${upper(tokens[list.next])} after the index columns`, line };
|
|
927
|
-
if (unique)
|
|
928
|
-
|
|
1084
|
+
if (!unique) table.indexes.push(cols);
|
|
1085
|
+
// A column's own UNIQUE may have declared it already (docs/adr/0204).
|
|
1086
|
+
else if (!(table.unique ?? []).some((have) => indexKey(have) === indexKey(cols)))
|
|
1087
|
+
(table.unique ??= []).push(cols);
|
|
929
1088
|
return {};
|
|
930
1089
|
}
|
|
931
1090
|
|
|
932
1091
|
/**
|
|
933
|
-
* Parses
|
|
1092
|
+
* Parses the Global Workspace's db/schema.sql. Returns the Declaration, or `{ error, line }` naming the rule that
|
|
1093
|
+
* refused it.
|
|
934
1094
|
* @type {typeof import("./schema.d.mts").parseSchema}
|
|
935
1095
|
*/
|
|
936
1096
|
export function parseSchema(sql) {
|
|
@@ -970,11 +1130,11 @@ export function parseSchema(sql) {
|
|
|
970
1130
|
|
|
971
1131
|
// ---- the planner ----------------------------------------------------------------------------------------
|
|
972
1132
|
//
|
|
973
|
-
// From what is live (tables, their storage columns, their index names
|
|
974
|
-
//
|
|
975
|
-
//
|
|
976
|
-
//
|
|
977
|
-
//
|
|
1133
|
+
// From what is live (tables, their storage columns, their index names) and the published Declaration, the
|
|
1134
|
+
// additive DDL a Preview or a Deploy runs; a Push plans only to refuse a conflict. Never a DROP (but a unique
|
|
1135
|
+
// index's demotion), never an ALTER other than ADD COLUMN. A declared column stored as another type is a
|
|
1136
|
+
// conflict, and then nothing runs. Table and column names are validated by parseSchema, so they are
|
|
1137
|
+
// interpolated bare; nothing here comes from a request.
|
|
978
1138
|
|
|
979
1139
|
/**
|
|
980
1140
|
* A declared table `tickets` of Instance `nike` is physically `data_nike_tickets`. Instance ids hold no `_`.
|
|
@@ -1001,7 +1161,7 @@ export function indexColumns(instance, table, name) {
|
|
|
1001
1161
|
return { columns: parts.slice(1), unique: true };
|
|
1002
1162
|
return { columns: parts, unique: false };
|
|
1003
1163
|
}
|
|
1004
|
-
/** The columns of a Declaration that are sequences (docs/adr/
|
|
1164
|
+
/** The columns of a Declaration that are sequences (docs/adr/0217). @param {Table} def */
|
|
1005
1165
|
const sequenceColumns = (def) =>
|
|
1006
1166
|
Object.entries(def.columns)
|
|
1007
1167
|
.filter(([, c]) => c.sequence)
|
|
@@ -1015,10 +1175,10 @@ const quoted = (values) => values.map((v) => `'${v}'`).join(", ");
|
|
|
1015
1175
|
* @type {typeof import("./schema.d.mts").describeColumn}
|
|
1016
1176
|
*/
|
|
1017
1177
|
export const describeColumn = (c, name = "value") =>
|
|
1018
|
-
`${c.type}${c.shape ? ` TYPE '${c.shape.replaceAll("'", "''")}'` : ""}${c.
|
|
1178
|
+
`${c.type}${c.shape ? ` TYPE '${c.shape.replaceAll("'", "''")}'` : ""}${c.ref ? ` REFERENCES ${c.ref}${c.onDelete ? " ON DELETE RESTRICT" : ""}` : ""}${c.values ? ` CHECK (${name} IN (${quoted(c.values)}))` : ""}${c.default ? ` DEFAULT ${printDefault(c.default)}` : ""}${c.sequence ? " SEQUENCE" : ""}`;
|
|
1019
1179
|
|
|
1020
1180
|
/**
|
|
1021
|
-
* A declared default as it is written (docs/adr/
|
|
1181
|
+
* A declared default as it is written (docs/adr/0224): `'open'`, `0`, `true`, `now`, `me`.
|
|
1022
1182
|
* @type {typeof import("./schema.d.mts").printDefault}
|
|
1023
1183
|
*/
|
|
1024
1184
|
export function printDefault(d) {
|
|
@@ -1027,7 +1187,7 @@ export function printDefault(d) {
|
|
|
1027
1187
|
}
|
|
1028
1188
|
|
|
1029
1189
|
/**
|
|
1030
|
-
* The value an insert that omits the column stores (docs/adr/
|
|
1190
|
+
* The value an insert that omits the column stores (docs/adr/0224), in storage form: booleans as 0/1, `now`
|
|
1031
1191
|
* as milliseconds, `me` as the inserting Member's actor id or null.
|
|
1032
1192
|
* @type {typeof import("./schema.d.mts").storedDefault}
|
|
1033
1193
|
*/
|
|
@@ -1038,7 +1198,7 @@ export function storedDefault(d, context) {
|
|
|
1038
1198
|
}
|
|
1039
1199
|
|
|
1040
1200
|
/**
|
|
1041
|
-
* The defaults a Global Push adds, changes or removes (docs/adr/
|
|
1201
|
+
* The defaults a Global Push adds, changes or removes (docs/adr/0224): Live definitions, listed under
|
|
1042
1202
|
* "Takes effect now". A Table or column new in `next` counts when it declares a default.
|
|
1043
1203
|
* @type {typeof import("./schema.d.mts").defaultChanges}
|
|
1044
1204
|
*/
|
|
@@ -1065,11 +1225,11 @@ export function defaultChanges(before, next) {
|
|
|
1065
1225
|
const NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
|
|
1066
1226
|
const VERSIONS = `${PLATFORM_PREFIX}versions`;
|
|
1067
1227
|
const CONTEXT = `${PLATFORM_PREFIX}context`;
|
|
1068
|
-
/** The actor of the write batch in flight (docs/adr/
|
|
1228
|
+
/** The actor of the write batch in flight (docs/adr/0218); app-db.ts sets it first in every write batch. */
|
|
1069
1229
|
const ACTOR = `(SELECT actor FROM ${CONTEXT} WHERE id = 1)`;
|
|
1070
|
-
/** The write's reason (docs/adr/
|
|
1230
|
+
/** The write's reason (docs/adr/0211), set beside the actor; null when the write gave none. */
|
|
1071
1231
|
const WHY = `(SELECT why FROM ${CONTEXT} WHERE id = 1)`;
|
|
1072
|
-
/** The workflow action that wrote the version (docs/adr/
|
|
1232
|
+
/** The workflow action that wrote the version (docs/adr/0227), or null. */
|
|
1073
1233
|
const TRANSITION = `(SELECT transition FROM ${CONTEXT} WHERE id = 1)`;
|
|
1074
1234
|
/** @param {string} instance @param {string} table */
|
|
1075
1235
|
const versionOf = (instance, table) =>
|
|
@@ -1125,7 +1285,7 @@ function historyLookupIndexStatements(instance, table) {
|
|
|
1125
1285
|
}
|
|
1126
1286
|
|
|
1127
1287
|
/**
|
|
1128
|
-
* The History table and its indexes (docs/adr/
|
|
1288
|
+
* The History table and its indexes (docs/adr/0218). `columns` are the Table's, name -> storage type.
|
|
1129
1289
|
* @type {typeof import("./schema.d.mts").historyStatements}
|
|
1130
1290
|
*/
|
|
1131
1291
|
export function historyStatements(instance, table, columns) {
|
|
@@ -1147,7 +1307,7 @@ export function historyStatements(instance, table, columns) {
|
|
|
1147
1307
|
* them (like the CHECK triggers). SQLite runs them with recursive triggers off, so a trigger's own UPDATE
|
|
1148
1308
|
* of the Table never re-fires that trigger; the insert trigger's actor stamp would fire the update
|
|
1149
1309
|
* trigger, though, so that one listens to every column but `created_by` and `updated_by`. An update
|
|
1150
|
-
* that sets only those two is not a change and leaves no History row. A sequence column (docs/adr/
|
|
1310
|
+
* that sets only those two is not a change and leaves no History row. A sequence column (docs/adr/0217) is
|
|
1151
1311
|
* assigned by the insert trigger the same way, before the History row is written, so it is left out of the
|
|
1152
1312
|
* watched list too: a backfill that sets only a sequence column leaves no History row.
|
|
1153
1313
|
* @type {typeof import("./schema.d.mts").bookkeepingTriggerStatements}
|
|
@@ -1187,30 +1347,6 @@ export function bookkeepingTriggerStatements(instance, table, columns, sequences
|
|
|
1187
1347
|
];
|
|
1188
1348
|
}
|
|
1189
1349
|
|
|
1190
|
-
/**
|
|
1191
|
-
* One History row per Table row that has none yet: `op = 'seed'`, no actor, an open period from now.
|
|
1192
|
-
* @type {typeof import("./schema.d.mts").seedHistoryStatement}
|
|
1193
|
-
*/
|
|
1194
|
-
export function seedHistoryStatement(instance, table, columns) {
|
|
1195
|
-
const p = physicalName(instance, table);
|
|
1196
|
-
const h = physicalName(instance, historyName(table));
|
|
1197
|
-
const list = snapshotColumns(columns).join(", ");
|
|
1198
|
-
return `INSERT INTO ${h} (${list}, row_id, op, valid_from, valid_to, by, version) SELECT ${list}, id, 'seed', ${NOW}, ${HISTORY_OPEN}, NULL, ${versionOf(instance, table)} FROM ${p} WHERE NOT EXISTS (SELECT 1 FROM ${h} WHERE ${h}.row_id = ${p}.id)`;
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
/**
|
|
1202
|
-
* Everything a Table that exists without a History needs, from its live columns.
|
|
1203
|
-
* @type {typeof import("./schema.d.mts").installHistoryStatements}
|
|
1204
|
-
*/
|
|
1205
|
-
export function installHistoryStatements(instance, table, columns) {
|
|
1206
|
-
return [
|
|
1207
|
-
versionRow(instance, table),
|
|
1208
|
-
...historyStatements(instance, table, columns),
|
|
1209
|
-
...bookkeepingTriggerStatements(instance, table, columns),
|
|
1210
|
-
seedHistoryStatement(instance, table, columns),
|
|
1211
|
-
];
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
1350
|
/**
|
|
1215
1351
|
* The statements that bring a new table into existence: the strict table, its `created_at` index, its versions row,
|
|
1216
1352
|
* its History, its triggers.
|
|
@@ -1237,7 +1373,7 @@ export function createTableStatements(instance, table, def) {
|
|
|
1237
1373
|
}
|
|
1238
1374
|
|
|
1239
1375
|
/**
|
|
1240
|
-
* The trigger that holds an assigned sequence value (docs/adr/
|
|
1376
|
+
* The trigger that holds an assigned sequence value (docs/adr/0217): only null may change, on every path,
|
|
1241
1377
|
* so a Builder can backfill rows older than the column and nothing can renumber. Recreated on every deploy.
|
|
1242
1378
|
* @type {typeof import("./schema.d.mts").sequenceTriggerStatements}
|
|
1243
1379
|
*/
|
|
@@ -1271,7 +1407,7 @@ const sameValues = (a, b) =>
|
|
|
1271
1407
|
(a === null && b === null) ||
|
|
1272
1408
|
(a !== null && b !== null && a.length === b.length && a.every((v, i) => v === b[i]));
|
|
1273
1409
|
/**
|
|
1274
|
-
* A DATE is a validated TEXT (docs/adr/
|
|
1410
|
+
* A DATE is a validated TEXT (docs/adr/0236) and MONEY an INTEGER of cents (docs/adr/0217): each pair never
|
|
1275
1411
|
* conflicts, and a column may move between them.
|
|
1276
1412
|
*/
|
|
1277
1413
|
const typeKind = (/** @type {Column["type"]} */ t) =>
|
|
@@ -1283,27 +1419,16 @@ const typeKind = (/** @type {Column["type"]} */ t) =>
|
|
|
1283
1419
|
*/
|
|
1284
1420
|
const sameColumn = (a, b) =>
|
|
1285
1421
|
typeKind(a.type) === typeKind(b.type) &&
|
|
1286
|
-
// A JSON column may gain REFERENCES, becoming an id list (docs/adr/
|
|
1422
|
+
// A JSON column may gain REFERENCES, becoming an id list (docs/adr/0219); its rows are checked as string[].
|
|
1287
1423
|
(a.ref === b.ref || (a.type === "JSON" && a.ref === null && b.ref !== null)) &&
|
|
1288
1424
|
sameValues(a.values ?? null, b.values ?? null) &&
|
|
1289
1425
|
(a.sequence ?? false) === (b.sequence ?? false);
|
|
1290
1426
|
|
|
1291
1427
|
/**
|
|
1292
|
-
* The
|
|
1428
|
+
* The Global Workspace's db/schema.sql, as parseSchema reads it.
|
|
1293
1429
|
* @type {typeof import("./schema.d.mts").parseGlobalSchema}
|
|
1294
1430
|
*/
|
|
1295
|
-
export
|
|
1296
|
-
const declaration = parseSchema(sql);
|
|
1297
|
-
if ("error" in declaration) return declaration;
|
|
1298
|
-
for (const [table, def] of Object.entries(declaration.tables))
|
|
1299
|
-
for (const [name, column] of Object.entries(def.columns))
|
|
1300
|
-
if (column.required)
|
|
1301
|
-
return {
|
|
1302
|
-
error: `${table}.${name}: all user-defined columns are nullable; NOT NULL is not supported. Require values in the app's workflow.`,
|
|
1303
|
-
line: 1,
|
|
1304
|
-
};
|
|
1305
|
-
return declaration;
|
|
1306
|
-
}
|
|
1431
|
+
export const parseGlobalSchema = (sql) => parseSchema(sql);
|
|
1307
1432
|
|
|
1308
1433
|
/**
|
|
1309
1434
|
* A global Push cannot remove or redefine anything already published, even before the first build.
|
|
@@ -1322,7 +1447,7 @@ export function schemaChangeError(previous, next) {
|
|
|
1322
1447
|
if (table.read !== added.read || table.write !== added.write)
|
|
1323
1448
|
return `${name}: published read/write policies cannot change in a schema addition.`;
|
|
1324
1449
|
// Indexed columns stay indexed. A plain index may become unique (the plain index is kept physically); a
|
|
1325
|
-
// unique index may become plain, the one relaxation the rule permits (docs/adr/
|
|
1450
|
+
// unique index may become plain, the one relaxation the rule permits (docs/adr/0217).
|
|
1326
1451
|
const stillIndexed = (/** @type {string[]} */ index) =>
|
|
1327
1452
|
[...added.indexes, ...(added.unique ?? [])].some(
|
|
1328
1453
|
(columns) => indexKey(columns) === indexKey(index),
|
|
@@ -1333,37 +1458,33 @@ export function schemaChangeError(previous, next) {
|
|
|
1333
1458
|
if (!stillIndexed(index))
|
|
1334
1459
|
return `${name}: a published unique index may become a plain index (CREATE INDEX) but cannot be removed.`;
|
|
1335
1460
|
}
|
|
1461
|
+
// A reference holds the referenced row's id, which is text: a new INTEGER (or other) column that REFERENCES a
|
|
1462
|
+
// Table, standard SQL's spelling (docs/adr/0204), could never hold one. A published one stands as it is.
|
|
1463
|
+
for (const [name, table] of Object.entries(next.tables))
|
|
1464
|
+
for (const [column, def] of Object.entries(table.columns))
|
|
1465
|
+
if (
|
|
1466
|
+
def.ref &&
|
|
1467
|
+
def.type !== "TEXT" &&
|
|
1468
|
+
def.type !== "JSON" &&
|
|
1469
|
+
!previous.tables[name]?.columns[column]
|
|
1470
|
+
)
|
|
1471
|
+
return `${name}.${column}: a reference holds the ${def.ref} row's id, which is text, so it cannot be ${def.type}; write ${column} REFERENCES ${def.ref}.`;
|
|
1336
1472
|
return null;
|
|
1337
1473
|
}
|
|
1338
1474
|
|
|
1339
1475
|
/**
|
|
1340
1476
|
* @type {typeof import("./schema.d.mts").planSchema}
|
|
1341
1477
|
*/
|
|
1342
|
-
export function planSchema(schema, mine, instance
|
|
1478
|
+
export function planSchema(schema, mine, instance) {
|
|
1343
1479
|
const statements = [];
|
|
1344
1480
|
const conflicts = [];
|
|
1345
1481
|
/** @type {import("./schema.d.mts").PlanSummary} */
|
|
1346
1482
|
const summary = { created: [], added: [], indexed: [] };
|
|
1347
|
-
const others = Object.entries(schema.declarations).filter(([s]) => s !== siteId);
|
|
1348
1483
|
|
|
1349
1484
|
for (const [t, def] of Object.entries(mine.tables)) {
|
|
1350
1485
|
const live = schema.live.tables[t];
|
|
1351
|
-
for (const [c, col] of Object.entries(def.columns))
|
|
1352
|
-
|
|
1353
|
-
for (const [site, tables] of others) {
|
|
1354
|
-
const theirs = tables[t]?.columns?.[c];
|
|
1355
|
-
if (!theirs) continue;
|
|
1356
|
-
found = true;
|
|
1357
|
-
if (!sameColumn(col, theirs))
|
|
1358
|
-
conflicts.push({
|
|
1359
|
-
table: t,
|
|
1360
|
-
column: c,
|
|
1361
|
-
mine: describeColumn(col, c),
|
|
1362
|
-
theirs: describeColumn(theirs, c),
|
|
1363
|
-
site,
|
|
1364
|
-
});
|
|
1365
|
-
}
|
|
1366
|
-
if (!found && live && c in live.columns && live.columns[c] !== RULES.types[col.type])
|
|
1486
|
+
for (const [c, col] of Object.entries(def.columns))
|
|
1487
|
+
if (live && c in live.columns && live.columns[c] !== RULES.types[col.type])
|
|
1367
1488
|
conflicts.push({
|
|
1368
1489
|
table: t,
|
|
1369
1490
|
column: c,
|
|
@@ -1371,26 +1492,11 @@ export function planSchema(schema, mine, instance, siteId) {
|
|
|
1371
1492
|
theirs: `stored as ${live.columns[c]}`,
|
|
1372
1493
|
site: null,
|
|
1373
1494
|
});
|
|
1374
|
-
}
|
|
1375
|
-
// Values are add-only: a value any registered declaration (this Site's previous one included) has must stay.
|
|
1376
|
-
for (const [c, col] of Object.entries(def.columns)) {
|
|
1377
|
-
const values = col.values;
|
|
1378
|
-
if (!values) continue;
|
|
1379
|
-
for (const [site, tables] of Object.entries(schema.declarations)) {
|
|
1380
|
-
const prev = tables[t]?.columns?.[c]?.values;
|
|
1381
|
-
if (!prev) continue;
|
|
1382
|
-
const missing = prev.find((v) => !values.includes(v));
|
|
1383
|
-
if (missing !== undefined)
|
|
1384
|
-
return {
|
|
1385
|
-
error: `${t}.${c}: CHECK values are add-only; '${missing}' is declared${site === siteId ? "" : ` by site "${site}"`} and cannot be removed`,
|
|
1386
|
-
};
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
1495
|
if (!live) {
|
|
1390
1496
|
statements.push(...createTableStatements(instance, t, def));
|
|
1391
1497
|
summary.created.push(t);
|
|
1392
1498
|
} else {
|
|
1393
|
-
// The History mirrors every physical column, declared today or not (docs/adr/
|
|
1499
|
+
// The History mirrors every physical column, declared today or not (docs/adr/0218).
|
|
1394
1500
|
const columns = { ...live.columns };
|
|
1395
1501
|
let grown = false;
|
|
1396
1502
|
for (const [c, col] of Object.entries(def.columns)) {
|
|
@@ -1402,9 +1508,8 @@ export function planSchema(schema, mine, instance, siteId) {
|
|
|
1402
1508
|
grown = true;
|
|
1403
1509
|
summary.added.push(`${t}.${c}`);
|
|
1404
1510
|
}
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
else if (grown) {
|
|
1511
|
+
if (grown) {
|
|
1512
|
+
const history = schema.live.tables[historyName(t)];
|
|
1408
1513
|
for (const [c, type] of Object.entries(columns))
|
|
1409
1514
|
if (!(c in history.columns))
|
|
1410
1515
|
statements.push(
|
|
@@ -1422,11 +1527,11 @@ export function planSchema(schema, mine, instance, siteId) {
|
|
|
1422
1527
|
}
|
|
1423
1528
|
const liveIndexes = new Set((live?.indexes ?? []).map(indexKey));
|
|
1424
1529
|
const liveUnique = new Set((live?.unique ?? []).map(indexKey));
|
|
1425
|
-
// A sequence column always has a unique index (docs/adr/
|
|
1530
|
+
// A sequence column always has a unique index (docs/adr/0217).
|
|
1426
1531
|
const unique = [...(def.unique ?? []), ...sequenceColumns(def).map((c) => [c])];
|
|
1427
1532
|
const wantUnique = new Set(unique.map(indexKey));
|
|
1428
1533
|
// Demotion: a live unique index the declaration now lists as a plain index is dropped, the one DROP the
|
|
1429
|
-
// planner emits (docs/adr/
|
|
1534
|
+
// planner emits (docs/adr/0217); the columns stay indexed by the plain index created below.
|
|
1430
1535
|
for (const cols of live?.unique ?? []) {
|
|
1431
1536
|
const key = indexKey(cols);
|
|
1432
1537
|
if (wantUnique.has(key) || !def.indexes.some((c) => indexKey(c) === key)) continue;
|
|
@@ -1452,7 +1557,7 @@ export function planSchema(schema, mine, instance, siteId) {
|
|
|
1452
1557
|
);
|
|
1453
1558
|
summary.indexed.push(`${t} (${cols.join(", ")}) UNIQUE`);
|
|
1454
1559
|
}
|
|
1455
|
-
// ADR
|
|
1560
|
+
// ADR 0240: a delete checks every ON DELETE RESTRICT column for the row's id, inside the writer; an index
|
|
1456
1561
|
// the Declaration does not give it, the platform does, under the name a declared one would have.
|
|
1457
1562
|
for (const [c, col] of Object.entries(def.columns)) {
|
|
1458
1563
|
if (col.onDelete !== "restrict" || leadsIndex(def, c)) continue;
|
|
@@ -1477,7 +1582,7 @@ export function planSchema(schema, mine, instance, siteId) {
|
|
|
1477
1582
|
}
|
|
1478
1583
|
|
|
1479
1584
|
/**
|
|
1480
|
-
* The unique indexes a Declaration adds to Tables that already exist (docs/adr/
|
|
1585
|
+
* The unique indexes a Declaration adds to Tables that already exist (docs/adr/0217): the ones whose rows the
|
|
1481
1586
|
* platform checks for duplicates before a Push, a Preview or a Deploy. Sequence columns count, since each
|
|
1482
1587
|
* carries a unique index. An index over a column not stored yet is left out: the column will hold NULL on every
|
|
1483
1588
|
* row, NULLs are distinct, and there is nothing to read it from until the artifact batch adds it.
|
|
@@ -1532,15 +1637,30 @@ export const ACTORS_TABLE = {
|
|
|
1532
1637
|
write: "none",
|
|
1533
1638
|
};
|
|
1534
1639
|
const OPS = Object.freeze(
|
|
1535
|
-
/** @type {const} */ ([
|
|
1640
|
+
/** @type {const} */ ([
|
|
1641
|
+
"eq",
|
|
1642
|
+
"ne",
|
|
1643
|
+
"lt",
|
|
1644
|
+
"lte",
|
|
1645
|
+
"gt",
|
|
1646
|
+
"gte",
|
|
1647
|
+
"in",
|
|
1648
|
+
"nin",
|
|
1649
|
+
"like",
|
|
1650
|
+
"contains",
|
|
1651
|
+
"startsWith",
|
|
1652
|
+
"endsWith",
|
|
1653
|
+
"null",
|
|
1654
|
+
"has",
|
|
1655
|
+
]),
|
|
1536
1656
|
);
|
|
1537
|
-
/** How deep a where path or an include may follow references (docs/adr/
|
|
1657
|
+
/** How deep a where path or an include may follow references (docs/adr/0219). */
|
|
1538
1658
|
const MAX_PATH = 3;
|
|
1539
1659
|
/** How many includes one query may carry, nested ones counted. */
|
|
1540
1660
|
const MAX_INCLUDES = 12;
|
|
1541
1661
|
/** How deep `or` and `and` may nest. */
|
|
1542
1662
|
const MAX_OR = 4;
|
|
1543
|
-
/** The children a reverse include brings per row, at most (docs/adr/
|
|
1663
|
+
/** The children a reverse include brings per row, at most (docs/adr/0219). */
|
|
1544
1664
|
export const MAX_CHILDREN = 100;
|
|
1545
1665
|
|
|
1546
1666
|
/**
|
|
@@ -1555,7 +1675,7 @@ export function effectivePolicies(table) {
|
|
|
1555
1675
|
}
|
|
1556
1676
|
|
|
1557
1677
|
/**
|
|
1558
|
-
* The Table a page sees for `<table>_history` (docs/adr/
|
|
1678
|
+
* The Table a page sees for `<table>_history` (docs/adr/0218): the History's own columns, then the Table's
|
|
1559
1679
|
* as nullable snapshots; read under the Table's policy, never written. `history` names the Table.
|
|
1560
1680
|
* @type {typeof import("./schema.d.mts").historyTable}
|
|
1561
1681
|
*/
|
|
@@ -1635,7 +1755,7 @@ export function storedValueError(column, stored, name) {
|
|
|
1635
1755
|
}
|
|
1636
1756
|
|
|
1637
1757
|
/**
|
|
1638
|
-
* The columns `next` makes stricter than `previous` for values already stored (docs/adr/
|
|
1758
|
+
* The columns `next` makes stricter than `previous` for values already stored (docs/adr/0236): a TEXT column
|
|
1639
1759
|
* that became DATE, a JSON column whose TYPE was added or changed. A Push checks their rows first.
|
|
1640
1760
|
* @type {typeof import("./schema.d.mts").tightenedColumns}
|
|
1641
1761
|
*/
|
|
@@ -1658,7 +1778,7 @@ export function tightenedColumns(previous, next) {
|
|
|
1658
1778
|
const ENUM_NAME_RE = /^(?:status|type|[a-z0-9_]+_type)$/;
|
|
1659
1779
|
|
|
1660
1780
|
/**
|
|
1661
|
-
* `schema-untyped-enum` (docs/adr/
|
|
1781
|
+
* `schema-untyped-enum` (docs/adr/0236): TEXT columns named status, type or *_type that `next` adds without a
|
|
1662
1782
|
* CHECK list, so their type is string. Only columns `previous` does not have: a published column cannot gain
|
|
1663
1783
|
* one. `line` is 1-based in `sql`, the column's line inside its CREATE TABLE.
|
|
1664
1784
|
* @type {typeof import("./schema.d.mts").untypedEnums}
|
|
@@ -1704,7 +1824,7 @@ const MONEY_PARTS = new Set(
|
|
|
1704
1824
|
const RATIO_PARTS = new Set("rate pct percent ratio qty quantity hours weight factor".split(" "));
|
|
1705
1825
|
|
|
1706
1826
|
/**
|
|
1707
|
-
* `schema-real-money` (docs/adr/
|
|
1827
|
+
* `schema-real-money` (docs/adr/0217): REAL columns `next` adds whose name has a money part (`price`,
|
|
1708
1828
|
* `amount_due`) and no ratio part (`tax_rate`). Only columns `previous` does not have: a published REAL column
|
|
1709
1829
|
* cannot become MONEY.
|
|
1710
1830
|
* @type {typeof import("./schema.d.mts").realMoney}
|
|
@@ -1779,7 +1899,7 @@ function toStorage(type, value, column) {
|
|
|
1779
1899
|
}
|
|
1780
1900
|
|
|
1781
1901
|
/**
|
|
1782
|
-
* Where a column of `table` leads (docs/adr/
|
|
1902
|
+
* Where a column of `table` leads (docs/adr/0219): a referenced Table's row, a list of them (a JSON id
|
|
1783
1903
|
* list), an `actors` row (a MEMBER column, created_by, updated_by), or nowhere (null).
|
|
1784
1904
|
* @param {Table} table @param {string} column
|
|
1785
1905
|
* @returns {{kind: "row" | "rows" | "actor", table: string} | null}
|
|
@@ -1827,14 +1947,14 @@ function checkWhere(spec, table, tables, depth, ors) {
|
|
|
1827
1947
|
if ("error" in checked) return checked;
|
|
1828
1948
|
items.push(checked);
|
|
1829
1949
|
}
|
|
1830
|
-
// Every branch of an `and` must pass, as the rest of the where does, so its items join it (docs/adr/
|
|
1950
|
+
// Every branch of an `and` must pass, as the rest of the where does, so its items join it (docs/adr/0219).
|
|
1831
1951
|
if (key === "and") where.push(...items.flat());
|
|
1832
1952
|
else where.push({ op: "or", items });
|
|
1833
1953
|
continue;
|
|
1834
1954
|
}
|
|
1835
1955
|
const dot = key.indexOf(".");
|
|
1836
1956
|
if (dot >= 0) {
|
|
1837
|
-
// `"sample_id.status": ...`: rows whose referenced row passes (docs/adr/
|
|
1957
|
+
// `"sample_id.status": ...`: rows whose referenced row passes (docs/adr/0219).
|
|
1838
1958
|
const column = key.slice(0, dot);
|
|
1839
1959
|
const ref = referenceOf(table, column);
|
|
1840
1960
|
if (!columnTypeOf(table, column)) return { error: `no column "${column}"` };
|
|
@@ -1877,11 +1997,21 @@ function checkWhere(spec, table, tables, depth, ors) {
|
|
|
1877
1997
|
where.push({ column, op, value: raw });
|
|
1878
1998
|
continue;
|
|
1879
1999
|
}
|
|
1880
|
-
|
|
2000
|
+
// contains, startsWith and endsWith (docs/adr/0219) take the text itself: % and _ in it are literal.
|
|
2001
|
+
if (
|
|
2002
|
+
(op === "like" || op === "contains" || op === "startsWith" || op === "endsWith") &&
|
|
2003
|
+
type !== "TEXT"
|
|
2004
|
+
)
|
|
2005
|
+
return { error: `${column}: ${op} needs a TEXT column` };
|
|
2006
|
+
if (op === "contains" || op === "startsWith" || op === "endsWith") {
|
|
2007
|
+
if (typeof raw !== "string") return { error: `${column}: ${op} takes a string` };
|
|
2008
|
+
where.push({ column, op, value: raw });
|
|
2009
|
+
continue;
|
|
2010
|
+
}
|
|
1881
2011
|
if (type === "BOOLEAN" && op !== "eq" && op !== "ne")
|
|
1882
2012
|
return { error: `${column}: a BOOLEAN column takes eq or ne only` };
|
|
1883
2013
|
if (op === "in" || op === "nin") {
|
|
1884
|
-
// An empty in matches nothing (docs/adr/
|
|
2014
|
+
// An empty in matches nothing (docs/adr/0219); nin passes NULL and an empty nin every row (docs/adr/0219).
|
|
1885
2015
|
if (!Array.isArray(raw)) return { error: `${column}: ${op} takes an array` };
|
|
1886
2016
|
if (raw.length > QUERY_MAX_LIMIT)
|
|
1887
2017
|
return { error: `${column}: ${op} takes at most ${QUERY_MAX_LIMIT} values` };
|
|
@@ -1903,6 +2033,7 @@ function checkWhere(spec, table, tables, depth, ors) {
|
|
|
1903
2033
|
}
|
|
1904
2034
|
// `{ col: null }` and `{ col: { eq: null } }` mean IS NULL, `{ ne: null }` IS NOT NULL: what an author
|
|
1905
2035
|
// writes first, and what the Framework's Query type already permits. Ordering operators keep refusing null.
|
|
2036
|
+
// `{ ne: value }` passes the rows where the column is NULL, as `!==` would (docs/adr/0219).
|
|
1906
2037
|
if (raw === null && (op === "eq" || op === "ne")) {
|
|
1907
2038
|
where.push({ column, op: "null", value: op === "eq" });
|
|
1908
2039
|
continue;
|
|
@@ -1917,7 +2048,7 @@ function checkWhere(spec, table, tables, depth, ors) {
|
|
|
1917
2048
|
}
|
|
1918
2049
|
|
|
1919
2050
|
/**
|
|
1920
|
-
* Where an include lands on its row (docs/adr/
|
|
2051
|
+
* Where an include lands on its row (docs/adr/0219): `<name>_id` -> `<name>`, `<name>_ids` -> `<name>`,
|
|
1921
2052
|
* any other column `c` -> `c_row` (`c_rows` for a list), and `<column>_row(s)` when the short name is a
|
|
1922
2053
|
* column already. A reverse include lands on its child Table's name, or `<child>_rows` when that is a column.
|
|
1923
2054
|
* @type {typeof import("./schema.d.mts").includeField}
|
|
@@ -1953,7 +2084,7 @@ function includeColumns(value, target, key) {
|
|
|
1953
2084
|
}
|
|
1954
2085
|
|
|
1955
2086
|
/**
|
|
1956
|
-
* `include` (docs/adr/
|
|
2087
|
+
* `include` (docs/adr/0219): forward paths through references and reverse child Tables, as a tree.
|
|
1957
2088
|
* @param {unknown} spec @param {Table} table @param {Record<string, Table> | undefined} tables @param {boolean} reverse whether child Tables may be named here
|
|
1958
2089
|
* @param {{count: number}} budget
|
|
1959
2090
|
* @returns {import("./schema.d.mts").Include[] | {error: string}}
|
|
@@ -2076,7 +2207,7 @@ const ORDER_RE = /^(-?)([a-z][a-z0-9_]*)(?:\s+nulls\s+(first|last))?$/i;
|
|
|
2076
2207
|
|
|
2077
2208
|
/**
|
|
2078
2209
|
* Validates a page query `{ where?, order?, limit?, offset?, include? }` against a Declaration. `tables` are
|
|
2079
|
-
* the Declaration's Tables, which paths through references and includes cross (docs/adr/
|
|
2210
|
+
* the Declaration's Tables, which paths through references and includes cross (docs/adr/0219); `table` is
|
|
2080
2211
|
* one of them, the same object.
|
|
2081
2212
|
* @type {typeof import("./schema.d.mts").checkQuery}
|
|
2082
2213
|
*/
|
|
@@ -2124,7 +2255,7 @@ export function checkQuery(q, table, tables) {
|
|
|
2124
2255
|
return { error: "offset must be a non-negative integer" };
|
|
2125
2256
|
offset = q.offset;
|
|
2126
2257
|
}
|
|
2127
|
-
// `scope: false` reads past the active scope (docs/adr/
|
|
2258
|
+
// `scope: false` reads past the active scope (docs/adr/0225); the access rules still apply.
|
|
2128
2259
|
if (q.scope !== undefined && q.scope !== false)
|
|
2129
2260
|
return { error: "scope takes false only: read past the active scope" };
|
|
2130
2261
|
/** @type {import("./schema.d.mts").Include[]} */
|
|
@@ -2210,8 +2341,8 @@ export function checkAggregate(q, table, tables) {
|
|
|
2210
2341
|
}
|
|
2211
2342
|
|
|
2212
2343
|
/**
|
|
2213
|
-
* Validates a row from a page for insert
|
|
2214
|
-
*
|
|
2344
|
+
* Validates a row from a page for insert or update (only what is given; an update gives something). Every
|
|
2345
|
+
* declared column is nullable. Returns the row in storage form.
|
|
2215
2346
|
* @type {typeof import("./schema.d.mts").checkRow}
|
|
2216
2347
|
*/
|
|
2217
2348
|
export function checkRow(body, table, mode) {
|
|
@@ -2225,7 +2356,6 @@ export function checkRow(body, table, mode) {
|
|
|
2225
2356
|
if (raw === undefined) continue;
|
|
2226
2357
|
if (mode === "update" && def.sequence)
|
|
2227
2358
|
return { error: `${column} is a sequence and cannot be changed once assigned` };
|
|
2228
|
-
if (raw === null && def.required) return { error: `${column} is required` };
|
|
2229
2359
|
const c = toStorage(def.type, raw, column);
|
|
2230
2360
|
if ("error" in c) return c;
|
|
2231
2361
|
const bad = raw !== null && def.shape ? shapeError(shapeOf(def.shape), raw, column) : null;
|
|
@@ -2234,12 +2364,7 @@ export function checkRow(body, table, mode) {
|
|
|
2234
2364
|
return { error: `${column} must be one of: ${def.values.join(", ")}` };
|
|
2235
2365
|
row[column] = c.value;
|
|
2236
2366
|
}
|
|
2237
|
-
if (mode === "
|
|
2238
|
-
for (const [column, def] of Object.entries(table.columns))
|
|
2239
|
-
if (def.required && !(column in row)) return { error: `${column} is required` };
|
|
2240
|
-
} else if (Object.keys(row).length === 0) {
|
|
2241
|
-
return { error: "nothing to update" };
|
|
2242
|
-
}
|
|
2367
|
+
if (mode === "update" && Object.keys(row).length === 0) return { error: "nothing to update" };
|
|
2243
2368
|
return { row };
|
|
2244
2369
|
}
|
|
2245
2370
|
|
|
@@ -2302,7 +2427,8 @@ const TOKEN =
|
|
|
2302
2427
|
|
|
2303
2428
|
// Locate table positions separately from the conservative identifier security scan. Parentheses form
|
|
2304
2429
|
// scopes for CTEs; expressions and column lists never become table references. `literalTables` holds the
|
|
2305
|
-
// offsets of single-quoted strings in a table position, where SQLite reads a string as a table name
|
|
2430
|
+
// offsets of single-quoted strings in a table position, where SQLite reads a string as a table name, and
|
|
2431
|
+
// `named` every name read as a table there (a CTE's name where it shadows one is not).
|
|
2306
2432
|
/** @param {string} sql @param {Map<string, string>} app */
|
|
2307
2433
|
function sqlTableReplacements(sql, app) {
|
|
2308
2434
|
/**
|
|
@@ -2362,6 +2488,8 @@ function sqlTableReplacements(sql, app) {
|
|
|
2362
2488
|
const replacements = new Map();
|
|
2363
2489
|
/** @type {Set<number>} */
|
|
2364
2490
|
const literalTables = new Set();
|
|
2491
|
+
/** @type {Set<string>} */
|
|
2492
|
+
const named = new Set();
|
|
2365
2493
|
const clauses = new Set([
|
|
2366
2494
|
"where",
|
|
2367
2495
|
"group",
|
|
@@ -2426,7 +2554,9 @@ function sqlTableReplacements(sql, app) {
|
|
|
2426
2554
|
// CTEs shadow read sources, but SQLite still resolves mutation targets as real tables.
|
|
2427
2555
|
const writeTarget =
|
|
2428
2556
|
keyword === "into" || keyword === "update" || (keyword === "from" && word(i - 1, "delete"));
|
|
2429
|
-
const
|
|
2557
|
+
const shadowed = !writeTarget && cte(s, table.name);
|
|
2558
|
+
if (!shadowed) named.add(table.name);
|
|
2559
|
+
const physical = shadowed ? null : app.get(table.name);
|
|
2430
2560
|
if (physical)
|
|
2431
2561
|
replacements.set(table.at, {
|
|
2432
2562
|
length: table.raw.length,
|
|
@@ -2437,9 +2567,14 @@ function sqlTableReplacements(sql, app) {
|
|
|
2437
2567
|
}
|
|
2438
2568
|
// Keep the logical name as an alias so qualifiers retain SQLite scope semantics, including
|
|
2439
2569
|
// correlated subqueries and different aliases in each arm of a compound SELECT.
|
|
2440
|
-
return { replacements, literalTables };
|
|
2570
|
+
return { replacements, literalTables, named };
|
|
2441
2571
|
}
|
|
2442
2572
|
|
|
2573
|
+
/** What Builder SQL answers for the platform's actors view, which it never reads. */
|
|
2574
|
+
const SQL_ACTORS =
|
|
2575
|
+
"actors is not one of your tables: it is the platform's view of who people are, which SQL does not read. " +
|
|
2576
|
+
"Run `ez db actors` for their ids, names and emails; created_by, updated_by and a MEMBER column hold an id from it.";
|
|
2577
|
+
|
|
2443
2578
|
/**
|
|
2444
2579
|
* One DML statement on the Instance's tables, named as declared. Every identifier is checked: one of the
|
|
2445
2580
|
* Instance's tables is allowed; anything else that is a table or view in the database
|
|
@@ -2474,7 +2609,7 @@ export function checkSql(statement, tables, instance) {
|
|
|
2474
2609
|
// position ("SELECT * FROM 'user'") or a qualifier ("'user'.email"), so there a literal naming a
|
|
2475
2610
|
// foreign table is refused. Anywhere else it is a value ("VALUES ('Account')") and passes; a string
|
|
2476
2611
|
// is never rewritten, even when it names one of the Instance's own tables. SQLite's authorizer in the
|
|
2477
|
-
// Builder SQL process enforces the same boundary whatever this pass concludes (ADR
|
|
2612
|
+
// Builder SQL process enforces the same boundary whatever this pass concludes (ADR 0240).
|
|
2478
2613
|
const literal = m[1].replaceAll("''", "'").toLowerCase();
|
|
2479
2614
|
if (literal.startsWith("sqlite_") || literal.startsWith("pragma_"))
|
|
2480
2615
|
return { error: `${literal} is not allowed: only your tables can be named` };
|
|
@@ -2491,8 +2626,12 @@ export function checkSql(statement, tables, instance) {
|
|
|
2491
2626
|
if (other.has(ident))
|
|
2492
2627
|
return { error: `${ident} is not one of your tables: run \`ez db tables\`` };
|
|
2493
2628
|
}
|
|
2629
|
+
// The actors view is the platform's (a reserved name, so never a Table of the Instance): SQL never reads it,
|
|
2630
|
+
// and saying only "no such table" sends its reader looking for a members Table. Only a table position is
|
|
2631
|
+
// refused: an alias or a CTE of that name keeps its meaning.
|
|
2632
|
+
if (located.named.has("actors") && !app.has("actors")) return { error: SQL_ACTORS };
|
|
2494
2633
|
const replacements = [...located.replacements].sort((a, b) => a[0] - b[0]);
|
|
2495
|
-
// A History is read-only for everyone (docs/adr/
|
|
2634
|
+
// A History is read-only for everyone (docs/adr/0218): only the platform's triggers write it.
|
|
2496
2635
|
const appNames = [...app.keys()];
|
|
2497
2636
|
for (const [, r] of replacements) {
|
|
2498
2637
|
const parent = r.write ? historyParent(r.table, appNames) : null;
|
|
@@ -2540,11 +2679,11 @@ them is "Not found". Members' groups: ez user group add <who> <name>. Check what
|
|
|
2540
2679
|
A rule goes in the push that declares the Table or column it reads: until a Preview or Deploy has added a
|
|
2541
2680
|
new column the rule reads it as NULL, which is what every row then holds.
|
|
2542
2681
|
READ lookup, department, sample_type WHERE group(staff); one rule for several Tables
|
|
2543
|
-
GROUP analyst; a group server code may assign (docs/adr/
|
|
2682
|
+
GROUP analyst; a group server code may assign (docs/adr/0225)
|
|
2544
2683
|
GROUP lab-manager IMPLIES analyst, verifier; holding it confers those too, wherever groups are tested
|
|
2545
2684
|
Keep roles in groups, not in a Table: group() needs no column on the row and the Host checks it without a
|
|
2546
2685
|
read. ez-admin (the Instance's Admins) and ez-builder (every Builder) are the Host's groups, held through
|
|
2547
|
-
the Builder roster: test them like any group, never declare or assign them (docs/adr/
|
|
2686
|
+
the Builder roster: test them like any group, never declare or assign them (docs/adr/0225). Server code
|
|
2548
2687
|
with Site authority (authority "site", jobs, Listeners) manages the roster: context.members.list() (status
|
|
2549
2688
|
invited | active | blocked, invitedAt, lastSignInAt, builder), .invite(email, { name, groups, send })
|
|
2550
2689
|
(emailed once the function commits; send: false emails no one), .resend(memberId), .setGroups(memberId,
|
|
@@ -2569,6 +2708,9 @@ export function helpDb() {
|
|
|
2569
2708
|
const refused = Object.entries(RULES.refused)
|
|
2570
2709
|
.map(([k, why]) => ` ${k.padEnd(14)}${why}`)
|
|
2571
2710
|
.join("\n");
|
|
2711
|
+
const accepted = Object.entries(RULES.accepted)
|
|
2712
|
+
.map(([k, means]) => ` ${k.padEnd(54)}${means}`)
|
|
2713
|
+
.join("\n");
|
|
2572
2714
|
return `The App Database (one per Instance, shared by every Site in it).
|
|
2573
2715
|
|
|
2574
2716
|
The Instance declares its schema once in global/${SCHEMA_FILE}. Run \`ez global pull\`, then
|
|
@@ -2577,13 +2719,13 @@ published schema on its next Preview or Deploy; existing deployments keep their
|
|
|
2577
2719
|
Admins and Builders add Tables, columns and indexes; a Limited Builder reads the schema only.
|
|
2578
2720
|
All user-defined columns are nullable, even on new Tables: NOT NULL is not supported. Inserts may
|
|
2579
2721
|
omit columns; reads return null for missing values. Require values in the app's workflow.
|
|
2580
|
-
Defaults (docs/adr/
|
|
2722
|
+
Defaults (docs/adr/0224): <name> <type> DEFAULT <value> fills the column when an insert omits it, for
|
|
2581
2723
|
every page, function and job, including deployments built before the default (it takes effect at Push).
|
|
2582
2724
|
An explicit null stays null; updates and \`ez db sql\` never apply defaults; existing rows are not
|
|
2583
2725
|
backfilled (the push says how many are null). Values: 'text' (one of its CHECK values, if any), 'YYYY-MM-DD'
|
|
2584
2726
|
for DATE, a number, true/false, now for TIMESTAMP. A default may be added, changed or removed later.
|
|
2585
2727
|
|
|
2586
|
-
Labels and integrity (docs/adr/
|
|
2728
|
+
Labels and integrity (docs/adr/0222): the schema says how records read and hold together, once.
|
|
2587
2729
|
CREATE TABLE dealers (
|
|
2588
2730
|
customer_code TEXT LABEL 'Customer ID', -- The NextGen id_customer. (a column's doc: the comment on its line)
|
|
2589
2731
|
name TEXT,
|
|
@@ -2600,9 +2742,9 @@ job write (not \`ez db sql\`) from the Push on; a Push adding SINGLETON or EXACT
|
|
|
2600
2742
|
it. A refused write is a 409 with \`code\` ("unique", "restricted", "singleton", "exactly-one"): in a page,
|
|
2601
2743
|
\`e instanceof WriteError && e.code === "restricted"\`. Never check references or owners in page code.
|
|
2602
2744
|
|
|
2603
|
-
Access (docs/adr/
|
|
2745
|
+
Access (docs/adr/0225): global/db/access.sql says who reads and writes which rows; \`ez help access\`.
|
|
2604
2746
|
|
|
2605
|
-
Rules (docs/adr/
|
|
2747
|
+
Rules (docs/adr/0226): global/rules/<table>.ts runs for every page, function and job write of that Table
|
|
2606
2748
|
(never Builder SQL), inside the write:
|
|
2607
2749
|
import { rules } from "@ezship/react/server";
|
|
2608
2750
|
export default rules<"orders">({
|
|
@@ -2615,7 +2757,7 @@ then the access condition. Push compiles them; a changed guard is replayed over
|
|
|
2615
2757
|
refusing any needs an Admin's --force (see --dry-run). Keep them fast: they run while the write holds the
|
|
2616
2758
|
database (250 ms). Put shared logic in global/lib and call it from both rules and functions.
|
|
2617
2759
|
|
|
2618
|
-
Workflows (docs/adr/
|
|
2760
|
+
Workflows (docs/adr/0227): global/workflows/<table>.ts makes a TEXT status column a state machine the Host
|
|
2619
2761
|
runs for every page, function and job write (never Builder SQL):
|
|
2620
2762
|
import { workflow } from "@ezship/react/server";
|
|
2621
2763
|
export default workflow<"sample">({
|
|
@@ -2645,8 +2787,6 @@ Backfilling rows does not synchronize old and new writers.
|
|
|
2645
2787
|
After editing, run \`ez global check\` and \`ez global push\`. Push records definitions without DDL;
|
|
2646
2788
|
a successful Site Preview or Deploy creates missing Tables, columns and indexes. Unpushed schema
|
|
2647
2789
|
changes cannot be previewed against production storage. Preview data writes remain real.
|
|
2648
|
-
For an existing Site schema, start from \`ez db schema\`, review table read/write policies, move
|
|
2649
|
-
its definitions into global, remove NOT NULL, push global, and delete the Site's schema/types copies.
|
|
2650
2790
|
Import row aliases with \`import type { Order } from "global/db/types"\`.
|
|
2651
2791
|
|
|
2652
2792
|
${SCHEMA_FILE} holds only CREATE TABLE, CREATE INDEX and CREATE UNIQUE INDEX statements, each ending with ;
|
|
@@ -2671,17 +2811,18 @@ Types:
|
|
|
2671
2811
|
${types}
|
|
2672
2812
|
Names: lowercase letters, digits, underscores; not ez_*, not a system column, not a platform table name.
|
|
2673
2813
|
CHECK: only on TEXT columns; values are letters, digits, spaces, _ . - ; published value sets are fixed; enum evolution is a separate decision.
|
|
2674
|
-
Unique keys (docs/adr/
|
|
2814
|
+
Unique keys (docs/adr/0217): CREATE UNIQUE INDEX ON <table> (<columns>) after the table, or UNIQUE on the
|
|
2815
|
+
column or UNIQUE (<columns>) in the Table's list. Matching is exact
|
|
2675
2816
|
(normalize case in the form); NULLs are distinct, so require the value in the app. An insert or update that
|
|
2676
2817
|
repeats a key is refused: pages get a rejected promise "<table>: <columns> must be unique" (409); in a
|
|
2677
2818
|
function the failed write makes the whole call roll back, so check before you insert. Pushing a unique index
|
|
2678
2819
|
over a Table that already holds duplicates is refused with the duplicate values; fix the rows with SQL first.
|
|
2679
|
-
Sequences (docs/adr/
|
|
2820
|
+
Sequences (docs/adr/0217): <name> INTEGER SEQUENCE numbers rows per Table: an insert that omits the column
|
|
2680
2821
|
gets max + 1 (from 1) inside its own write, whoever writes; a value you supply wins and later numbers continue
|
|
2681
2822
|
above it. Assigned once: updates are refused. Numbers increase and are never reused; deleted rows leave gaps;
|
|
2682
2823
|
there is no periodic reset (format SO-000123 or a yearly prefix in the app). Rows older than the column stay
|
|
2683
2824
|
null until you backfill them with SQL. A sequence column always has a unique index.
|
|
2684
|
-
Typed JSON (docs/adr/
|
|
2825
|
+
Typed JSON (docs/adr/0236): JSON TYPE '<shape>' gives a JSON column its TypeScript type and checks every page
|
|
2685
2826
|
and function write against it. A shape is string, number, boolean, null, unknown, DateString, EpochMs, Cents,
|
|
2686
2827
|
"literal" values, { name: T; optional?: T }, T[], Array<T>, Record<string, T>, unions with | and parentheses,
|
|
2687
2828
|
on one line. Objects are exact: a key the shape does not list is refused. A refused write names the path:
|
|
@@ -2691,19 +2832,23 @@ Dates and times: DATE holds a local calendar date, TEXT 'YYYY-MM-DD', and orders
|
|
|
2691
2832
|
TIMESTAMP (and created_at, updated_at) holds epoch milliseconds. Pages and functions get DateString and EpochMs
|
|
2692
2833
|
and build them with today(), toDate(year, month, day) or toDate(date), toEpoch(dateString) and now() from
|
|
2693
2834
|
@ezship/react (or @ezship/react/server). A published TEXT column may become DATE once every stored value is a date.
|
|
2694
|
-
Money (docs/adr/
|
|
2835
|
+
Money (docs/adr/0217): MONEY holds whole cents as an INTEGER, so sums are exact; never declare money REAL.
|
|
2695
2836
|
Pages and functions write Cents: toCents("1,234.50") (or toCents(12.5)) rounds to the cent, null when
|
|
2696
2837
|
unreadable; fromCents(cents) gives units for arithmetic; global Money draws it. A published INTEGER column may
|
|
2697
2838
|
become MONEY; a REAL one cannot: add a MONEY column and backfill it with ROUND(price * 100) in ez db sql.
|
|
2698
2839
|
Every table gets id, created_at, created_by, updated_at, updated_by from the platform; never declare them.
|
|
2840
|
+
Standard SQL that means the same here (docs/adr/0204): write either form.
|
|
2841
|
+
${accepted}
|
|
2699
2842
|
Not allowed in ${SCHEMA_FILE}:
|
|
2700
2843
|
${refused}
|
|
2701
2844
|
|
|
2702
2845
|
Rows: pages use the helper (see \`ez help\`); you use \`ez db sql\` with one SELECT, WITH, INSERT, UPDATE or DELETE.
|
|
2703
2846
|
SQL is SQLite; name tables as you declared them (tickets), never any other table in the database.
|
|
2847
|
+
A Table or column exists for SQL once a Preview or Deploy has created it (\`ez db tables\` lists what does);
|
|
2848
|
+
the platform's actors view is read with \`ez db actors\`, never by SQL. One statement a call, and no flags.
|
|
2704
2849
|
Table references are rewritten per Instance; column names, aliases and CTE names keep their meaning.
|
|
2705
2850
|
Never DDL: tables change only through ${SCHEMA_FILE} and \`ez deploy\`. Reads return at most ${SQL_MAX_ROWS} rows.
|
|
2706
|
-
A statement runs in its own process: a read is stopped after 10 seconds and a write after
|
|
2851
|
+
A statement runs in its own process: a read is stopped after 10 seconds and a write after 30 (a stopped write
|
|
2707
2852
|
leaves nothing), and a result over 16 MB is refused. Page through large Tables with LIMIT and a WHERE on id.
|
|
2708
2853
|
Rows you insert with SQL get id, created_at, created_by, updated_at and updated_by automatically (the actor is
|
|
2709
2854
|
you, 'builder:<your id>'); a value you set yourself wins. The changed-row count of a write is the statement's
|
|
@@ -2730,10 +2875,11 @@ useLive.aggregate("tickets", { group: ["status"] }) returns { rows: [{ group: {
|
|
|
2730
2875
|
Add sum: ["amount"] for INTEGER/MONEY/REAL columns; db.aggregate has the same query in handlers and Functions.
|
|
2731
2876
|
Filters cover all input rows. limit/offset bound only grouped output, which reports truncated.
|
|
2732
2877
|
Row queries default to ${QUERY_DEFAULT_LIMIT} and cap at ${QUERY_MAX_LIMIT}; never reduce them into a total.
|
|
2733
|
-
|
|
2878
|
+
A read is useLive.query / db.query, which answer { rows, truncated } (docs/adr/0219); useLive and db.list are
|
|
2879
|
+
shorthand for the rows alone.
|
|
2734
2880
|
Builders: ez db aggregate tickets '{"group":["status"]}'.
|
|
2735
2881
|
|
|
2736
|
-
Relations (docs/adr/
|
|
2882
|
+
Relations (docs/adr/0219): a query follows REFERENCES. include: { sample_id: ["code"], "sample_id.client_id": ["name"],
|
|
2737
2883
|
analyst: ["name"] (MEMBER, created_by, updated_by -> actors), method_instrument: { instrument_id: true } (child rows) }
|
|
2738
2884
|
brings the rows with each row, each under its Table's READ rule; where: { "sample_id.status": "received", or: [...] }
|
|
2739
2885
|
filters through them before paging. An id list is <name> JSON REFERENCES <table> (stored as JSON TYPE 'string[]',
|
|
@@ -2749,7 +2895,8 @@ Builders: ez db actors '{"where":{"kind":"builder"}}'.`;
|
|
|
2749
2895
|
// ---- ez db schema ---------------------------------------------------------------------------------------
|
|
2750
2896
|
|
|
2751
2897
|
/**
|
|
2752
|
-
* The live schema as
|
|
2898
|
+
* The live schema as CREATE TABLE statements: each column as a registered Declaration has it, else its
|
|
2899
|
+
* storage type; a History says whose it is.
|
|
2753
2900
|
* @type {typeof import("./schema.d.mts").renderSchema}
|
|
2754
2901
|
*/
|
|
2755
2902
|
export function renderSchema(schema) {
|
|
@@ -2765,20 +2912,18 @@ export function renderSchema(schema) {
|
|
|
2765
2912
|
const columnOf = (t, c, storage) => {
|
|
2766
2913
|
for (const site of declarers(t)) {
|
|
2767
2914
|
const col = schema.declarations[site][t].columns[c];
|
|
2768
|
-
if (col) return describeColumn(
|
|
2915
|
+
if (col) return describeColumn(col, c);
|
|
2769
2916
|
}
|
|
2770
2917
|
return storage;
|
|
2771
2918
|
};
|
|
2772
2919
|
const out = [];
|
|
2773
2920
|
for (const t of names) {
|
|
2774
2921
|
const live = schema.live.tables[t];
|
|
2775
|
-
const sites = declarers(t);
|
|
2776
2922
|
const parent = historyParent(t, names);
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
);
|
|
2923
|
+
if (parent)
|
|
2924
|
+
out.push(
|
|
2925
|
+
`-- ${t}: the History of ${parent} (read-only; every change to ${parent}, see ez help db)`,
|
|
2926
|
+
);
|
|
2782
2927
|
out.push(`CREATE TABLE ${t} (`);
|
|
2783
2928
|
out.push(
|
|
2784
2929
|
Object.entries(live.columns)
|
|
@@ -2840,7 +2985,7 @@ function singular(word) {
|
|
|
2840
2985
|
return word;
|
|
2841
2986
|
}
|
|
2842
2987
|
|
|
2843
|
-
// ---- the descriptor (docs/adr/
|
|
2988
|
+
// ---- the descriptor (docs/adr/0222) -------------------------------------------------------------------
|
|
2844
2989
|
//
|
|
2845
2990
|
// What the Framework's record components read at run time: each Table's labels, display columns,
|
|
2846
2991
|
// constraints and columns in declared order, and every scalar reference pointing at it. The Pipeline bundles
|
|
@@ -2866,8 +3011,8 @@ export function pluralLabel(label) {
|
|
|
2866
3011
|
}
|
|
2867
3012
|
|
|
2868
3013
|
/**
|
|
2869
|
-
* The integrity constraints a Push adds or removes (docs/adr/
|
|
2870
|
-
* DELETE RESTRICT. Live definitions (docs/adr/
|
|
3014
|
+
* The integrity constraints a Push adds or removes (docs/adr/0222): SINGLETON, EXACTLY ONE OF and each ON
|
|
3015
|
+
* DELETE RESTRICT. Live definitions (docs/adr/0224): they apply to every write from the Push on.
|
|
2871
3016
|
* @type {typeof import("./schema.d.mts").integrityChanges}
|
|
2872
3017
|
*/
|
|
2873
3018
|
export function integrityChanges(previous, next) {
|
|
@@ -2910,7 +3055,7 @@ export function integrityChanges(previous, next) {
|
|
|
2910
3055
|
}
|
|
2911
3056
|
|
|
2912
3057
|
/**
|
|
2913
|
-
* The run-time descriptor of a Declaration's Tables (docs/adr/
|
|
3058
|
+
* The run-time descriptor of a Declaration's Tables (docs/adr/0222). Histories and the actors view are left
|
|
2914
3059
|
* out: the record components draw declared Tables.
|
|
2915
3060
|
* @type {typeof import("./schema.d.mts").describeSchema}
|
|
2916
3061
|
*/
|
|
@@ -2973,13 +3118,13 @@ const tsType = (c) => {
|
|
|
2973
3118
|
return `${base} | null`;
|
|
2974
3119
|
};
|
|
2975
3120
|
|
|
2976
|
-
/** A column's label and doc as JSDoc (docs/adr/
|
|
3121
|
+
/** A column's label and doc as JSDoc (docs/adr/0222), or nothing. @param {Column} c */
|
|
2977
3122
|
const jsDoc = (c) => {
|
|
2978
3123
|
const text = [c.label, c.doc].filter(Boolean).join(": ").replaceAll("*/", "* /");
|
|
2979
3124
|
return text ? `/** ${text} */ ` : "";
|
|
2980
3125
|
};
|
|
2981
3126
|
|
|
2982
|
-
/** A History's own columns as TypeScript (docs/adr/
|
|
3127
|
+
/** A History's own columns as TypeScript (docs/adr/0218); never optional, never null but `by`, `why` and `transition`. */
|
|
2983
3128
|
const HISTORY_TS = Object.freeze({
|
|
2984
3129
|
/** @param {string} t */
|
|
2985
3130
|
row_id: (t) => `Id<${JSON.stringify(t)}>`,
|
|
@@ -2993,7 +3138,7 @@ const HISTORY_TS = Object.freeze({
|
|
|
2993
3138
|
});
|
|
2994
3139
|
|
|
2995
3140
|
/**
|
|
2996
|
-
* The References and Children interfaces of db/types.d.ts (docs/adr/
|
|
3141
|
+
* The References and Children interfaces of db/types.d.ts (docs/adr/0219), from the same rules the Host
|
|
2997
3142
|
* includes by: each forward column's target Table and the field it lands on, each indexed child Table.
|
|
2998
3143
|
* @param {import("./schema.d.mts").Declaration} decl @param {string[]} tables
|
|
2999
3144
|
*/
|
|
@@ -3059,7 +3204,7 @@ export function generateTypes(decl, workflows = {}) {
|
|
|
3059
3204
|
const member = tables.some((t) =>
|
|
3060
3205
|
Object.values(decl.tables[t].columns).some((c) => c.type === "MEMBER"),
|
|
3061
3206
|
);
|
|
3062
|
-
// Cents likewise, for MONEY columns and JSON shapes that name it (docs/adr/
|
|
3207
|
+
// Cents likewise, for MONEY columns and JSON shapes that name it (docs/adr/0217).
|
|
3063
3208
|
const cents = tables.some((t) =>
|
|
3064
3209
|
Object.values(decl.tables[t].columns).some(
|
|
3065
3210
|
(c) => c.type === "MONEY" || /\bCents\b/.test(c.shape ?? ""),
|
|
@@ -3079,7 +3224,7 @@ export function generateTypes(decl, workflows = {}) {
|
|
|
3079
3224
|
.map(([c, d]) => `${c}?: ${tsType(d)}`)
|
|
3080
3225
|
.join("; ");
|
|
3081
3226
|
const flow = flows[t];
|
|
3082
|
-
// A labelled or documented column carries its JSDoc (docs/adr/
|
|
3227
|
+
// A labelled or documented column carries its JSDoc (docs/adr/0222); the rest stay as they were.
|
|
3083
3228
|
const own = Object.entries(decl.tables[t].columns)
|
|
3084
3229
|
.map(
|
|
3085
3230
|
([c, d]) =>
|
|
@@ -3094,9 +3239,9 @@ export function generateTypes(decl, workflows = {}) {
|
|
|
3094
3239
|
}
|
|
3095
3240
|
lines.push(" }");
|
|
3096
3241
|
}
|
|
3097
|
-
// What a query may include (docs/adr/
|
|
3242
|
+
// What a query may include (docs/adr/0219): each column's target and where it lands, each child Table.
|
|
3098
3243
|
lines.push(...relationTypes(decl, tables));
|
|
3099
|
-
// Each workflow's column, states and the actions a caller may name (docs/adr/
|
|
3244
|
+
// Each workflow's column, states and the actions a caller may name (docs/adr/0227).
|
|
3100
3245
|
const flowTables = Object.keys(flows).sort();
|
|
3101
3246
|
if (flowTables.length) {
|
|
3102
3247
|
lines.push(" interface Workflows {");
|