ezship 0.1.15 → 0.1.17

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/schema.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // The App Database rules (docs/adr/0007, 0020, 0021, 0046): what a Site
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/0041). The guest's `db` is built from these keys and the Host validates
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/0077).
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,20 +32,38 @@ 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/0093).
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/0103): table, id, action, then an optional patch and options.
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
- * The longest Push message and write reason (docs/adr/0093), in characters.
43
+ * What server code's `db` has beyond `DATABASE_OPERATIONS` (docs/adr/0249), with the argument counts the Host
44
+ * accepts: many rows in one database operation. Never a page's, a Table rule's or the `Database` a lib module takes.
45
+ * @type {typeof import("./schema.d.mts").SERVER_DATABASE_OPERATIONS}
46
+ */
47
+ export const SERVER_DATABASE_OPERATIONS = Object.freeze({
48
+ // table, rows, then optional options
49
+ insertMany: Object.freeze([2, 3]),
50
+ // table, { where, limit? }, patch, then optional options
51
+ updateMany: Object.freeze([3, 4]),
52
+ // table, { where, limit? }, then optional options
53
+ deleteMany: Object.freeze([2, 3]),
54
+ });
55
+ /**
56
+ * The most rows one many-row operation writes (docs/adr/0228).
57
+ * @type {typeof import("./schema.d.mts").MANY_ROWS}
58
+ */
59
+ export const MANY_ROWS = 1000;
60
+ /**
61
+ * The longest Push message and write reason (docs/adr/0211), in characters.
44
62
  * @type {typeof import("./schema.d.mts").MAX_MESSAGE_CHARS}
45
63
  */
46
64
  export const MAX_MESSAGE_CHARS = 500;
47
65
  /**
48
- * A Push message or write reason as stored (docs/adr/0093): trimmed, null when absent or blank, an error
66
+ * A Push message or write reason as stored (docs/adr/0211): trimmed, null when absent or blank, an error
49
67
  * when it is not a string or too long.
50
68
  * @type {typeof import("./schema.d.mts").messageText}
51
69
  */
@@ -69,7 +87,7 @@ export const SYSTEM_COLUMNS = Object.freeze([
69
87
  "updated_by",
70
88
  ]);
71
89
  /**
72
- * Table History (docs/adr/0040): every Table `t` has a read-only `t_history` the platform writes.
90
+ * Table History (docs/adr/0218): every Table `t` has a read-only `t_history` the platform writes.
73
91
  * @type {typeof import("./schema.d.mts").HISTORY_SUFFIX}
74
92
  */
75
93
  export const HISTORY_SUFFIX = "_history";
@@ -113,24 +131,24 @@ export const NAME_RE = /^[a-z][a-z0-9_]{0,62}$/;
113
131
  */
114
132
  export const VALUE_RE = /^[A-Za-z0-9_ .-]{1,64}$/;
115
133
  /**
116
- * What a FILE column holds (docs/adr/0047): an Attachment id, the platform's random id, URL-safe.
134
+ * What a FILE column holds (docs/adr/0221): an Attachment id, the platform's random id, URL-safe.
117
135
  * @type {typeof import("./schema.d.mts").ATTACHMENT_ID_RE}
118
136
  */
119
137
  export const ATTACHMENT_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
120
138
  /**
121
- * What a MEMBER column holds (docs/adr/0098): a Member's actor id, the form of `created_by` and `actors.id`.
139
+ * What a MEMBER column holds (docs/adr/0225): a Member's actor id, the form of `created_by` and `actors.id`.
122
140
  * @type {typeof import("./schema.d.mts").MEMBER_ID_RE}
123
141
  */
124
142
  export const MEMBER_ID_RE = /^user:[A-Za-z0-9_-]{1,128}$/;
125
143
  /**
126
- * A Member group's name (docs/adr/0098): on the Instance's roster, named by `group(<name>)` in access rules.
144
+ * A Member group's name (docs/adr/0225): on the Instance's roster, named by `group(<name>)` in access rules.
127
145
  * @type {typeof import("./schema.d.mts").GROUP_RE}
128
146
  */
129
147
  export const GROUP_RE = /^[a-z][a-z0-9-]{0,39}$/;
130
148
  /** @type {typeof import("./schema.d.mts").MAX_GROUPS} */
131
149
  export const MAX_GROUPS = 50;
132
150
  /**
133
- * The Host's own groups (docs/adr/0110): `ez-admin` is held by the Instance's Admins, `ez-builder` by every
151
+ * The Host's own groups (docs/adr/0225): `ez-admin` is held by the Instance's Admins, `ez-builder` by every
134
152
  * Builder, each through the Member identity with their email. Tested like any group, never assigned or
135
153
  * declared; every other `ez-` name is reserved and held by no one.
136
154
  * @type {typeof import("./schema.d.mts").RESERVED_GROUPS}
@@ -157,13 +175,11 @@ export const RULES = Object.freeze({
157
175
  policies: Object.freeze(/** @type {const} */ (["member", "none"])),
158
176
  /** Constructs the parser refuses, with the reason an agent needs. Keys are matched as whole words, in order. */
159
177
  refused: Object.freeze({
160
- "PRIMARY KEY": "every table gets an `id` primary key automatically",
161
- "FOREIGN KEY": "put `REFERENCES <table>` on the column instead",
162
- FOREIGN: "put `REFERENCES <table>` on the column instead",
163
- UNIQUE:
164
- "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)",
165
181
  AUTOINCREMENT:
166
- "write <name> INTEGER SEQUENCE: the platform numbers rows per Table (docs/adr/0046)",
182
+ "write <name> INTEGER SEQUENCE: the platform numbers rows per Table (docs/adr/0217)",
167
183
  COLLATE: "collations are not supported",
168
184
  "WITHOUT ROWID": "not supported",
169
185
  STRICT: "every table is strict already",
@@ -197,6 +213,19 @@ export const RULES = Object.freeze({
197
213
  "ratelimit",
198
214
  "app_members",
199
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
+ }),
200
229
  limits: Object.freeze({ tablesPerInstance: 500, columnsPerTable: 200, valuesPerCheck: 50 }),
201
230
  });
202
231
 
@@ -260,7 +289,7 @@ function tokenize(sql) {
260
289
  i++;
261
290
  continue;
262
291
  }
263
- // A number (a DEFAULT, docs/adr/0097) may carry a sign and a fraction; a name never starts with a digit.
292
+ // A number (a DEFAULT, docs/adr/0224) may carry a sign and a fraction; a name never starts with a digit.
264
293
  const m = /^-?[0-9]+\.[0-9]+(?![A-Za-z0-9_])|^-[0-9]+(?![A-Za-z0-9_.])|^[A-Za-z0-9_]+/.exec(
265
294
  sql.slice(i),
266
295
  );
@@ -308,7 +337,7 @@ function checkName(name, what, line) {
308
337
  };
309
338
  if (what === "table" && name.endsWith(HISTORY_SUFFIX))
310
339
  return {
311
- error: `${what} "${name}": the ${HISTORY_SUFFIX} suffix is reserved for History (docs/adr/0040)`,
340
+ error: `${what} "${name}": the ${HISTORY_SUFFIX} suffix is reserved for History (docs/adr/0218)`,
312
341
  line,
313
342
  };
314
343
  if (name in HISTORY_COLUMNS)
@@ -327,7 +356,7 @@ function checkName(name, what, line) {
327
356
  function splitStatements(tokens) {
328
357
  const statements = [];
329
358
  let comments = [];
330
- /** The comments inside a statement: a column's doc is the one on its line (docs/adr/0109). */
359
+ /** The comments inside a statement: a column's doc is the one on its line (docs/adr/0222). */
331
360
  let inner = [];
332
361
  let current = [];
333
362
  let lastLine = 0;
@@ -368,7 +397,7 @@ function parsePolicies(comments) {
368
397
  const value = RULES.policies.find((policy) => policy === m[2].toLowerCase());
369
398
  if (!value)
370
399
  return {
371
- error: `${m[1].toLowerCase()} policy "${m[2]}" must be member or none; public access is no longer supported.`,
400
+ error: `${m[1].toLowerCase()} policy "${m[2]}" must be member or none.`,
372
401
  line: c.line,
373
402
  };
374
403
  out[/** @type {"read" | "write"} */ (m[1].toLowerCase())] = value;
@@ -380,7 +409,7 @@ function parsePolicies(comments) {
380
409
  const DEFAULT_MAX_CHARS = 256;
381
410
 
382
411
  /**
383
- * The token after DEFAULT (docs/adr/0097): a quoted string, a number, true/false, now or me. Checked against
412
+ * The token after DEFAULT (docs/adr/0224): a quoted string, a number, true/false, now or me. Checked against
384
413
  * the column's type once the whole definition is read.
385
414
  * @param {Token | undefined} t @param {string} column @param {number} line
386
415
  * @returns {{value: import("./schema.d.mts").ColumnDefault, quoted: boolean} | ParseError}
@@ -425,7 +454,7 @@ function defaultError(col, d, column, line) {
425
454
  if (v.kind === "me")
426
455
  return col.type === "MEMBER"
427
456
  ? null
428
- : { error: `column "${column}": DEFAULT me needs a MEMBER column (docs/adr/0098)`, line };
457
+ : { error: `column "${column}": DEFAULT me needs a MEMBER column (docs/adr/0225)`, line };
429
458
  if (col.type === "MEMBER")
430
459
  return { error: `column "${column}": a MEMBER column's DEFAULT is me`, line };
431
460
  if (v.kind === "now")
@@ -462,8 +491,8 @@ function defaultError(col, d, column, line) {
462
491
  }
463
492
 
464
493
  /**
465
- * One column definition: `<name> [<type>] [NOT NULL] [REFERENCES <table>] [CHECK (<name> IN (...))] [DEFAULT <value>] [SEQUENCE]`.
466
- * @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}
467
496
  */
468
497
  function parseColumn(tokens, line) {
469
498
  const [nameTok, ...rest] = tokens;
@@ -472,13 +501,17 @@ function parseColumn(tokens, line) {
472
501
  if (bad) return refuse(bad, line);
473
502
  const nameErr = checkName(nameTok.text, "column", line);
474
503
  if (nameErr) return nameErr;
475
- if (isWord(nameTok, "DEFAULT"))
476
- return { error: `column "${nameTok.text}": DEFAULT is a keyword; pick another name`, line };
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
+ };
477
509
  /** @type {{value: import("./schema.d.mts").ColumnDefault, quoted: boolean} | null} */
478
510
  let fallback = null;
479
511
  /** @type {Omit<Column, "type"> & {type: Column["type"] | null}} */
480
512
  const col = { type: null, required: false, ref: null, values: null };
481
513
  let sequence = false;
514
+ let unique = false;
482
515
  /** @type {string | undefined} */
483
516
  let label;
484
517
  /** @type {"restrict" | undefined} */
@@ -490,7 +523,7 @@ function parseColumn(tokens, line) {
490
523
  }
491
524
  /** @type {string | undefined} */
492
525
  let shape;
493
- // `JSON TYPE '<shape>'` (docs/adr/0078): the column's TypeScript type and what every write must match.
526
+ // `JSON TYPE '<shape>'` (docs/adr/0236): the column's TypeScript type and what every write must match.
494
527
  if (isWord(rest[i], "TYPE")) {
495
528
  const text = rest[i + 1];
496
529
  if (col.type !== "JSON")
@@ -508,20 +541,30 @@ function parseColumn(tokens, line) {
508
541
  while (i < rest.length) {
509
542
  const key = refusedAt(rest, i);
510
543
  if (key) return refuse(key, line);
511
- if (isWord(rest[i], "NOT") && isWord(rest[i + 1], "NULL")) {
512
- col.required = true;
513
- i += 2;
514
- continue;
515
- }
516
544
  const referenced = rest[i + 1];
517
545
  if (isWord(rest[i], "REFERENCES") && referenced?.kind === "word") {
518
546
  const refErr = checkName(referenced.text, "referenced table", line);
519
547
  if (refErr) return refErr;
520
548
  col.ref = referenced.text;
521
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
+ }
522
559
  continue;
523
560
  }
524
- // `REFERENCES <table> ON DELETE RESTRICT` (docs/adr/0109): the referenced row cannot be deleted while
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++;
565
+ continue;
566
+ }
567
+ // `REFERENCES <table> ON DELETE RESTRICT` (docs/adr/0222): the referenced row cannot be deleted while
525
568
  // this column holds its id. DELETE is otherwise a refused word, so the clause is read whole here.
526
569
  if (isWord(rest[i], "ON") && isWord(rest[i + 1], "DELETE")) {
527
570
  if (col.ref === null)
@@ -531,7 +574,7 @@ function parseColumn(tokens, line) {
531
574
  };
532
575
  if (!isWord(rest[i + 2], "RESTRICT"))
533
576
  return {
534
- error: `column "${nameTok.text}": ON DELETE takes RESTRICT only (CASCADE and SET NULL are not supported, docs/adr/0109)`,
577
+ error: `column "${nameTok.text}": ON DELETE takes RESTRICT only (CASCADE and SET NULL are not supported, docs/adr/0222)`,
535
578
  line,
536
579
  };
537
580
  onDelete = "restrict";
@@ -565,7 +608,7 @@ function parseColumn(tokens, line) {
565
608
  continue;
566
609
  }
567
610
  return {
568
- error: `unexpected ${upper(rest[i])} in column "${nameTok.text}": a column is <name> <type> [TYPE '<shape>'] [NOT NULL] [REFERENCES <table> [ON DELETE RESTRICT]] [CHECK (<name> IN ('a', 'b'))] [DEFAULT <value>] [SEQUENCE] [LABEL '<label>']`,
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>']`,
569
612
  line,
570
613
  };
571
614
  }
@@ -579,7 +622,7 @@ function parseColumn(tokens, line) {
579
622
  }
580
623
  if (col.values && col.type !== "TEXT")
581
624
  return { error: `column "${nameTok.text}": CHECK (... IN (...)) needs a TEXT column`, line };
582
- // `<name> JSON REFERENCES <table>` (docs/adr/0102): a list of ids, stored as JSON TYPE 'string[]'.
625
+ // `<name> JSON REFERENCES <table>` (docs/adr/0219): a list of ids, stored as JSON TYPE 'string[]'.
583
626
  if (col.type === "JSON" && col.ref !== null) {
584
627
  if (shape !== undefined && shape !== "string[]")
585
628
  return {
@@ -590,22 +633,22 @@ function parseColumn(tokens, line) {
590
633
  }
591
634
  if (col.type === "FILE" && col.ref !== null)
592
635
  return {
593
- error: `column "${nameTok.text}": a FILE column holds an Attachment id and cannot REFERENCES a table (docs/adr/0047)`,
636
+ error: `column "${nameTok.text}": a FILE column holds an Attachment id and cannot REFERENCES a table (docs/adr/0221)`,
594
637
  line,
595
638
  };
596
639
  if (onDelete && col.type === "JSON")
597
640
  return {
598
- error: `column "${nameTok.text}": an id list takes no ON DELETE; only a single reference can restrict deletes (docs/adr/0109)`,
641
+ error: `column "${nameTok.text}": an id list takes no ON DELETE; only a single reference can restrict deletes (docs/adr/0222)`,
599
642
  line,
600
643
  };
601
644
  if (col.type === "MEMBER" && col.ref !== null)
602
645
  return {
603
- error: `column "${nameTok.text}": a MEMBER column holds a Member and cannot REFERENCES a table (docs/adr/0098)`,
646
+ error: `column "${nameTok.text}": a MEMBER column holds a Member and cannot REFERENCES a table (docs/adr/0225)`,
604
647
  line,
605
648
  };
606
649
  if (sequence && (col.type !== "INTEGER" || col.ref !== null))
607
650
  return {
608
- error: `column "${nameTok.text}": SEQUENCE needs a plain INTEGER column (the platform numbers rows per Table, docs/adr/0046)`,
651
+ error: `column "${nameTok.text}": SEQUENCE needs a plain INTEGER column (the platform numbers rows per Table, docs/adr/0217)`,
609
652
  line,
610
653
  };
611
654
  const typed = {
@@ -617,8 +660,10 @@ function parseColumn(tokens, line) {
617
660
  const bad = defaultError(typed, fallback, nameTok.text, line);
618
661
  if (bad) return bad;
619
662
  }
663
+ // A column's UNIQUE is the unique index CREATE UNIQUE INDEX declares, on any type, as SQLite holds it.
620
664
  return {
621
665
  name: nameTok.text,
666
+ unique,
622
667
  column: {
623
668
  ...typed,
624
669
  ...(shape ? { shape } : {}),
@@ -629,13 +674,13 @@ function parseColumn(tokens, line) {
629
674
  };
630
675
  }
631
676
 
632
- /** The longest LABEL, in characters (docs/adr/0109). */
677
+ /** The longest LABEL, in characters (docs/adr/0222). */
633
678
  const LABEL_MAX_CHARS = 80;
634
- /** The longest column doc, in characters (docs/adr/0109). */
679
+ /** The longest column doc, in characters (docs/adr/0222). */
635
680
  const DOC_MAX_CHARS = 500;
636
681
 
637
682
  /**
638
- * The quoted text after LABEL (docs/adr/0109): one line, at most LABEL_MAX_CHARS.
683
+ * The quoted text after LABEL (docs/adr/0222): one line, at most LABEL_MAX_CHARS.
639
684
  * @param {Token | undefined} t @param {string} what @param {number} line @returns {string | ParseError}
640
685
  */
641
686
  function labelText(t, what, line) {
@@ -719,6 +764,121 @@ function parseList(tokens, i, line) {
719
764
  return { groups, next: j + 1 };
720
765
  }
721
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
+
722
882
  /** @param {Token[]} tokens @param {Token[]} comments @param {Record<string, Table>} tables @param {Token[]} [inner] @returns {{name: string, table: Table} | ParseError} */
723
883
  function parseCreateTable(tokens, comments, tables, inner = []) {
724
884
  const line = tokens[0].line;
@@ -735,19 +895,23 @@ function parseCreateTable(tokens, comments, tables, inner = []) {
735
895
  if ("error" in list) return list;
736
896
  if (list.groups.length === 0 || list.groups.every((g) => g.length === 0))
737
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;
738
900
  /** @type {Record<string, Column>} */
739
901
  const columns = {};
740
- for (const g of list.groups) {
741
- if (g.length === 0) return { error: `table "${nameTok.text}": empty column definition`, line };
902
+ /** @type {string[][]} */
903
+ const unique = [...sorted.unique];
904
+ for (const [k, g] of sorted.columns.entries()) {
742
905
  const col = parseColumn(g, g[0].line);
743
906
  if ("error" in col) return col;
907
+ if (col.unique) unique.push([col.name]);
744
908
  if (col.name in columns)
745
909
  return {
746
910
  error: `column "${col.name}" is declared twice in "${nameTok.text}"`,
747
911
  line: g[0].line,
748
912
  };
749
- // A column's doc is the comment on its own line (docs/adr/0109).
750
- const last = g[g.length - 1].line;
913
+ // A column's doc is the comment on its own line (docs/adr/0222).
914
+ const last = sorted.ends[k];
751
915
  const doc = inner
752
916
  .filter((c) => c.line >= g[0].line && c.line <= last)
753
917
  .map((c) => c.text ?? "")
@@ -771,16 +935,26 @@ function parseCreateTable(tokens, comments, tables, inner = []) {
771
935
  if ("error" in policies) return policies;
772
936
  /** @type {Table} */
773
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
+ }
774
948
  if (policies.policies.read) table.read = policies.policies.read;
775
949
  if (policies.policies.write) table.write = policies.policies.write;
776
950
  return { name: nameTok.text, table };
777
951
  }
778
952
 
779
- /** The most columns EXACTLY ONE OF names (docs/adr/0109). */
953
+ /** The most columns EXACTLY ONE OF names (docs/adr/0222). */
780
954
  const EXACTLY_ONE_MAX = 8;
781
955
 
782
956
  /**
783
- * What follows a Table's column list (docs/adr/0109), in any order: `LABEL '<singular>' ['<plural>']`,
957
+ * What follows a Table's column list (docs/adr/0222), in any order: `LABEL '<singular>' ['<plural>']`,
784
958
  * `DISPLAY (<columns>)`, `SINGLETON` and `EXACTLY ONE OF (<columns>)`.
785
959
  * @param {Token[]} tokens @param {number} i @param {string} name @param {Record<string, Column>} columns @param {number} line
786
960
  * @returns {{options: Pick<Table, "label" | "plural" | "display" | "singleton" | "exactlyOne">} | ParseError}
@@ -870,7 +1044,7 @@ function parseTableOptions(tokens, i, name, columns, line) {
870
1044
 
871
1045
  /**
872
1046
  * `CREATE [UNIQUE] INDEX [IF NOT EXISTS] [<name>] ON <table> (<columns>)`; a unique index is enforced by the
873
- * engine (docs/adr/0046).
1047
+ * engine (docs/adr/0217).
874
1048
  * @param {Token[]} tokens @param {Record<string, Table>} tables @param {boolean} unique @returns {{} | ParseError}
875
1049
  */
876
1050
  function parseCreateIndex(tokens, tables, unique) {
@@ -895,6 +1069,7 @@ function parseCreateIndex(tokens, tables, unique) {
895
1069
  };
896
1070
  const list = parseList(tokens, i + 2, line);
897
1071
  if ("error" in list) return list;
1072
+ /** @type {string[]} */
898
1073
  const cols = [];
899
1074
  for (const g of list.groups) {
900
1075
  if (g.length !== 1 || g[0].kind !== "word")
@@ -906,13 +1081,16 @@ function parseCreateIndex(tokens, tables, unique) {
906
1081
  if (cols.length === 0) return { error: "an index needs at least one column", line };
907
1082
  if (list.next < tokens.length)
908
1083
  return { error: `unexpected ${upper(tokens[list.next])} after the index columns`, line };
909
- if (unique) (table.unique ??= []).push(cols);
910
- else table.indexes.push(cols);
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);
911
1088
  return {};
912
1089
  }
913
1090
 
914
1091
  /**
915
- * Parses a Site's db/schema.sql. Returns the Declaration, or `{ error, line }` naming the rule that refused it.
1092
+ * Parses the Global Workspace's db/schema.sql. Returns the Declaration, or `{ error, line }` naming the rule that
1093
+ * refused it.
916
1094
  * @type {typeof import("./schema.d.mts").parseSchema}
917
1095
  */
918
1096
  export function parseSchema(sql) {
@@ -952,11 +1130,11 @@ export function parseSchema(sql) {
952
1130
 
953
1131
  // ---- the planner ----------------------------------------------------------------------------------------
954
1132
  //
955
- // From what is live (tables, their storage columns, their index names, every Site's registered Declaration)
956
- // and what this Site declares, the additive DDL to run at deploy. Never a DROP, never an ALTER other than ADD
957
- // COLUMN. A column two Sites declare must be declared identically: a difference is a conflict, the deploy is
958
- // refused, and the other Site changes its declaration first. Table and column names are validated by
959
- // parseSchema, so they are interpolated bare; nothing here comes from a request.
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.
960
1138
 
961
1139
  /**
962
1140
  * A declared table `tickets` of Instance `nike` is physically `data_nike_tickets`. Instance ids hold no `_`.
@@ -983,7 +1161,7 @@ export function indexColumns(instance, table, name) {
983
1161
  return { columns: parts.slice(1), unique: true };
984
1162
  return { columns: parts, unique: false };
985
1163
  }
986
- /** The columns of a Declaration that are sequences (docs/adr/0046). @param {Table} def */
1164
+ /** The columns of a Declaration that are sequences (docs/adr/0217). @param {Table} def */
987
1165
  const sequenceColumns = (def) =>
988
1166
  Object.entries(def.columns)
989
1167
  .filter(([, c]) => c.sequence)
@@ -997,10 +1175,10 @@ const quoted = (values) => values.map((v) => `'${v}'`).join(", ");
997
1175
  * @type {typeof import("./schema.d.mts").describeColumn}
998
1176
  */
999
1177
  export const describeColumn = (c, name = "value") =>
1000
- `${c.type}${c.shape ? ` TYPE '${c.shape.replaceAll("'", "''")}'` : ""}${c.required ? " NOT NULL" : ""}${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" : ""}`;
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" : ""}`;
1001
1179
 
1002
1180
  /**
1003
- * A declared default as it is written (docs/adr/0097): `'open'`, `0`, `true`, `now`, `me`.
1181
+ * A declared default as it is written (docs/adr/0224): `'open'`, `0`, `true`, `now`, `me`.
1004
1182
  * @type {typeof import("./schema.d.mts").printDefault}
1005
1183
  */
1006
1184
  export function printDefault(d) {
@@ -1009,7 +1187,7 @@ export function printDefault(d) {
1009
1187
  }
1010
1188
 
1011
1189
  /**
1012
- * The value an insert that omits the column stores (docs/adr/0097), in storage form: booleans as 0/1, `now`
1190
+ * The value an insert that omits the column stores (docs/adr/0224), in storage form: booleans as 0/1, `now`
1013
1191
  * as milliseconds, `me` as the inserting Member's actor id or null.
1014
1192
  * @type {typeof import("./schema.d.mts").storedDefault}
1015
1193
  */
@@ -1020,7 +1198,7 @@ export function storedDefault(d, context) {
1020
1198
  }
1021
1199
 
1022
1200
  /**
1023
- * The defaults a Global Push adds, changes or removes (docs/adr/0096, 0097): Live definitions, listed under
1201
+ * The defaults a Global Push adds, changes or removes (docs/adr/0224): Live definitions, listed under
1024
1202
  * "Takes effect now". A Table or column new in `next` counts when it declares a default.
1025
1203
  * @type {typeof import("./schema.d.mts").defaultChanges}
1026
1204
  */
@@ -1047,11 +1225,11 @@ export function defaultChanges(before, next) {
1047
1225
  const NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
1048
1226
  const VERSIONS = `${PLATFORM_PREFIX}versions`;
1049
1227
  const CONTEXT = `${PLATFORM_PREFIX}context`;
1050
- /** The actor of the write batch in flight (docs/adr/0040); app-db.ts sets it first in every write batch. */
1228
+ /** The actor of the write batch in flight (docs/adr/0218); app-db.ts sets it first in every write batch. */
1051
1229
  const ACTOR = `(SELECT actor FROM ${CONTEXT} WHERE id = 1)`;
1052
- /** The write's reason (docs/adr/0093), set beside the actor; null when the write gave none. */
1230
+ /** The write's reason (docs/adr/0211), set beside the actor; null when the write gave none. */
1053
1231
  const WHY = `(SELECT why FROM ${CONTEXT} WHERE id = 1)`;
1054
- /** The workflow action that wrote the version (docs/adr/0103), or null. */
1232
+ /** The workflow action that wrote the version (docs/adr/0227), or null. */
1055
1233
  const TRANSITION = `(SELECT transition FROM ${CONTEXT} WHERE id = 1)`;
1056
1234
  /** @param {string} instance @param {string} table */
1057
1235
  const versionOf = (instance, table) =>
@@ -1107,7 +1285,7 @@ function historyLookupIndexStatements(instance, table) {
1107
1285
  }
1108
1286
 
1109
1287
  /**
1110
- * The History table and its indexes (docs/adr/0040). `columns` are the Table's, name -> storage type.
1288
+ * The History table and its indexes (docs/adr/0218). `columns` are the Table's, name -> storage type.
1111
1289
  * @type {typeof import("./schema.d.mts").historyStatements}
1112
1290
  */
1113
1291
  export function historyStatements(instance, table, columns) {
@@ -1129,7 +1307,7 @@ export function historyStatements(instance, table, columns) {
1129
1307
  * them (like the CHECK triggers). SQLite runs them with recursive triggers off, so a trigger's own UPDATE
1130
1308
  * of the Table never re-fires that trigger; the insert trigger's actor stamp would fire the update
1131
1309
  * trigger, though, so that one listens to every column but `created_by` and `updated_by`. An update
1132
- * that sets only those two is not a change and leaves no History row. A sequence column (docs/adr/0046) is
1310
+ * that sets only those two is not a change and leaves no History row. A sequence column (docs/adr/0217) is
1133
1311
  * assigned by the insert trigger the same way, before the History row is written, so it is left out of the
1134
1312
  * watched list too: a backfill that sets only a sequence column leaves no History row.
1135
1313
  * @type {typeof import("./schema.d.mts").bookkeepingTriggerStatements}
@@ -1169,30 +1347,6 @@ export function bookkeepingTriggerStatements(instance, table, columns, sequences
1169
1347
  ];
1170
1348
  }
1171
1349
 
1172
- /**
1173
- * One History row per Table row that has none yet: `op = 'seed'`, no actor, an open period from now.
1174
- * @type {typeof import("./schema.d.mts").seedHistoryStatement}
1175
- */
1176
- export function seedHistoryStatement(instance, table, columns) {
1177
- const p = physicalName(instance, table);
1178
- const h = physicalName(instance, historyName(table));
1179
- const list = snapshotColumns(columns).join(", ");
1180
- 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)`;
1181
- }
1182
-
1183
- /**
1184
- * Everything a Table that exists without a History needs, from its live columns.
1185
- * @type {typeof import("./schema.d.mts").installHistoryStatements}
1186
- */
1187
- export function installHistoryStatements(instance, table, columns) {
1188
- return [
1189
- versionRow(instance, table),
1190
- ...historyStatements(instance, table, columns),
1191
- ...bookkeepingTriggerStatements(instance, table, columns),
1192
- seedHistoryStatement(instance, table, columns),
1193
- ];
1194
- }
1195
-
1196
1350
  /**
1197
1351
  * The statements that bring a new table into existence: the strict table, its `created_at` index, its versions row,
1198
1352
  * its History, its triggers.
@@ -1219,7 +1373,7 @@ export function createTableStatements(instance, table, def) {
1219
1373
  }
1220
1374
 
1221
1375
  /**
1222
- * The trigger that holds an assigned sequence value (docs/adr/0046): only null may change, on every path,
1376
+ * The trigger that holds an assigned sequence value (docs/adr/0217): only null may change, on every path,
1223
1377
  * so a Builder can backfill rows older than the column and nothing can renumber. Recreated on every deploy.
1224
1378
  * @type {typeof import("./schema.d.mts").sequenceTriggerStatements}
1225
1379
  */
@@ -1253,7 +1407,7 @@ const sameValues = (a, b) =>
1253
1407
  (a === null && b === null) ||
1254
1408
  (a !== null && b !== null && a.length === b.length && a.every((v, i) => v === b[i]));
1255
1409
  /**
1256
- * A DATE is a validated TEXT (docs/adr/0078) and MONEY an INTEGER of cents (docs/adr/0107): each pair never
1410
+ * A DATE is a validated TEXT (docs/adr/0236) and MONEY an INTEGER of cents (docs/adr/0217): each pair never
1257
1411
  * conflicts, and a column may move between them.
1258
1412
  */
1259
1413
  const typeKind = (/** @type {Column["type"]} */ t) =>
@@ -1265,27 +1419,16 @@ const typeKind = (/** @type {Column["type"]} */ t) =>
1265
1419
  */
1266
1420
  const sameColumn = (a, b) =>
1267
1421
  typeKind(a.type) === typeKind(b.type) &&
1268
- // A JSON column may gain REFERENCES, becoming an id list (docs/adr/0102); its rows are checked as string[].
1422
+ // A JSON column may gain REFERENCES, becoming an id list (docs/adr/0219); its rows are checked as string[].
1269
1423
  (a.ref === b.ref || (a.type === "JSON" && a.ref === null && b.ref !== null)) &&
1270
1424
  sameValues(a.values ?? null, b.values ?? null) &&
1271
1425
  (a.sequence ?? false) === (b.sequence ?? false);
1272
1426
 
1273
1427
  /**
1274
- * The authored global schema. The older parser remains able to read retained Site declarations.
1428
+ * The Global Workspace's db/schema.sql, as parseSchema reads it.
1275
1429
  * @type {typeof import("./schema.d.mts").parseGlobalSchema}
1276
1430
  */
1277
- export function parseGlobalSchema(sql) {
1278
- const declaration = parseSchema(sql);
1279
- if ("error" in declaration) return declaration;
1280
- for (const [table, def] of Object.entries(declaration.tables))
1281
- for (const [name, column] of Object.entries(def.columns))
1282
- if (column.required)
1283
- return {
1284
- error: `${table}.${name}: all user-defined columns are nullable; NOT NULL is not supported. Require values in the app's workflow.`,
1285
- line: 1,
1286
- };
1287
- return declaration;
1288
- }
1431
+ export const parseGlobalSchema = (sql) => parseSchema(sql);
1289
1432
 
1290
1433
  /**
1291
1434
  * A global Push cannot remove or redefine anything already published, even before the first build.
@@ -1304,7 +1447,7 @@ export function schemaChangeError(previous, next) {
1304
1447
  if (table.read !== added.read || table.write !== added.write)
1305
1448
  return `${name}: published read/write policies cannot change in a schema addition.`;
1306
1449
  // Indexed columns stay indexed. A plain index may become unique (the plain index is kept physically); a
1307
- // unique index may become plain, the one relaxation the rule permits (docs/adr/0046).
1450
+ // unique index may become plain, the one relaxation the rule permits (docs/adr/0217).
1308
1451
  const stillIndexed = (/** @type {string[]} */ index) =>
1309
1452
  [...added.indexes, ...(added.unique ?? [])].some(
1310
1453
  (columns) => indexKey(columns) === indexKey(index),
@@ -1315,37 +1458,33 @@ export function schemaChangeError(previous, next) {
1315
1458
  if (!stillIndexed(index))
1316
1459
  return `${name}: a published unique index may become a plain index (CREATE INDEX) but cannot be removed.`;
1317
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}.`;
1318
1472
  return null;
1319
1473
  }
1320
1474
 
1321
1475
  /**
1322
1476
  * @type {typeof import("./schema.d.mts").planSchema}
1323
1477
  */
1324
- export function planSchema(schema, mine, instance, siteId) {
1478
+ export function planSchema(schema, mine, instance) {
1325
1479
  const statements = [];
1326
1480
  const conflicts = [];
1327
1481
  /** @type {import("./schema.d.mts").PlanSummary} */
1328
1482
  const summary = { created: [], added: [], indexed: [] };
1329
- const others = Object.entries(schema.declarations).filter(([s]) => s !== siteId);
1330
1483
 
1331
1484
  for (const [t, def] of Object.entries(mine.tables)) {
1332
1485
  const live = schema.live.tables[t];
1333
- for (const [c, col] of Object.entries(def.columns)) {
1334
- let found = false;
1335
- for (const [site, tables] of others) {
1336
- const theirs = tables[t]?.columns?.[c];
1337
- if (!theirs) continue;
1338
- found = true;
1339
- if (!sameColumn(col, theirs))
1340
- conflicts.push({
1341
- table: t,
1342
- column: c,
1343
- mine: describeColumn(col, c),
1344
- theirs: describeColumn(theirs, c),
1345
- site,
1346
- });
1347
- }
1348
- 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])
1349
1488
  conflicts.push({
1350
1489
  table: t,
1351
1490
  column: c,
@@ -1353,26 +1492,11 @@ export function planSchema(schema, mine, instance, siteId) {
1353
1492
  theirs: `stored as ${live.columns[c]}`,
1354
1493
  site: null,
1355
1494
  });
1356
- }
1357
- // Values are add-only: a value any registered declaration (this Site's previous one included) has must stay.
1358
- for (const [c, col] of Object.entries(def.columns)) {
1359
- const values = col.values;
1360
- if (!values) continue;
1361
- for (const [site, tables] of Object.entries(schema.declarations)) {
1362
- const prev = tables[t]?.columns?.[c]?.values;
1363
- if (!prev) continue;
1364
- const missing = prev.find((v) => !values.includes(v));
1365
- if (missing !== undefined)
1366
- return {
1367
- error: `${t}.${c}: CHECK values are add-only; '${missing}' is declared${site === siteId ? "" : ` by site "${site}"`} and cannot be removed`,
1368
- };
1369
- }
1370
- }
1371
1495
  if (!live) {
1372
1496
  statements.push(...createTableStatements(instance, t, def));
1373
1497
  summary.created.push(t);
1374
1498
  } else {
1375
- // The History mirrors every physical column, declared today or not (docs/adr/0040).
1499
+ // The History mirrors every physical column, declared today or not (docs/adr/0218).
1376
1500
  const columns = { ...live.columns };
1377
1501
  let grown = false;
1378
1502
  for (const [c, col] of Object.entries(def.columns)) {
@@ -1384,9 +1508,8 @@ export function planSchema(schema, mine, instance, siteId) {
1384
1508
  grown = true;
1385
1509
  summary.added.push(`${t}.${c}`);
1386
1510
  }
1387
- const history = schema.live.tables[historyName(t)];
1388
- if (!history) statements.push(...installHistoryStatements(instance, t, columns));
1389
- else if (grown) {
1511
+ if (grown) {
1512
+ const history = schema.live.tables[historyName(t)];
1390
1513
  for (const [c, type] of Object.entries(columns))
1391
1514
  if (!(c in history.columns))
1392
1515
  statements.push(
@@ -1404,11 +1527,11 @@ export function planSchema(schema, mine, instance, siteId) {
1404
1527
  }
1405
1528
  const liveIndexes = new Set((live?.indexes ?? []).map(indexKey));
1406
1529
  const liveUnique = new Set((live?.unique ?? []).map(indexKey));
1407
- // A sequence column always has a unique index (docs/adr/0046).
1530
+ // A sequence column always has a unique index (docs/adr/0217).
1408
1531
  const unique = [...(def.unique ?? []), ...sequenceColumns(def).map((c) => [c])];
1409
1532
  const wantUnique = new Set(unique.map(indexKey));
1410
1533
  // Demotion: a live unique index the declaration now lists as a plain index is dropped, the one DROP the
1411
- // planner emits (docs/adr/0046); the columns stay indexed by the plain index created below.
1534
+ // planner emits (docs/adr/0217); the columns stay indexed by the plain index created below.
1412
1535
  for (const cols of live?.unique ?? []) {
1413
1536
  const key = indexKey(cols);
1414
1537
  if (wantUnique.has(key) || !def.indexes.some((c) => indexKey(c) === key)) continue;
@@ -1434,7 +1557,7 @@ export function planSchema(schema, mine, instance, siteId) {
1434
1557
  );
1435
1558
  summary.indexed.push(`${t} (${cols.join(", ")}) UNIQUE`);
1436
1559
  }
1437
- // ADR 0143: a delete checks every ON DELETE RESTRICT column for the row's id, inside the writer; an index
1560
+ // ADR 0240: a delete checks every ON DELETE RESTRICT column for the row's id, inside the writer; an index
1438
1561
  // the Declaration does not give it, the platform does, under the name a declared one would have.
1439
1562
  for (const [c, col] of Object.entries(def.columns)) {
1440
1563
  if (col.onDelete !== "restrict" || leadsIndex(def, c)) continue;
@@ -1459,9 +1582,10 @@ export function planSchema(schema, mine, instance, siteId) {
1459
1582
  }
1460
1583
 
1461
1584
  /**
1462
- * The unique indexes a Declaration adds to Tables that already exist (docs/adr/0046): the ones whose rows the
1585
+ * The unique indexes a Declaration adds to Tables that already exist (docs/adr/0217): the ones whose rows the
1463
1586
  * platform checks for duplicates before a Push, a Preview or a Deploy. Sequence columns count, since each
1464
- * carries a unique index.
1587
+ * carries a unique index. An index over a column not stored yet is left out: the column will hold NULL on every
1588
+ * row, NULLs are distinct, and there is nothing to read it from until the artifact batch adds it.
1465
1589
  * @type {typeof import("./schema.d.mts").newUniqueIndexes}
1466
1590
  */
1467
1591
  export function newUniqueIndexes(live, decl) {
@@ -1470,8 +1594,12 @@ export function newUniqueIndexes(live, decl) {
1470
1594
  const existing = live.tables[table];
1471
1595
  if (!existing) continue;
1472
1596
  const have = new Set((existing.unique ?? []).map(indexKey));
1473
- for (const columns of [...(def.unique ?? []), ...sequenceColumns(def).map((c) => [c])])
1474
- if (!have.has(indexKey(columns))) out.push({ table, columns });
1597
+ for (const columns of [...(def.unique ?? []), ...sequenceColumns(def).map((c) => [c])]) {
1598
+ if (have.has(indexKey(columns))) continue;
1599
+ // A live Table's `columns` omit the system columns, which every Table stores.
1600
+ if (columns.every((c) => c in existing.columns || SYSTEM_COLUMNS.includes(c)))
1601
+ out.push({ table, columns });
1602
+ }
1475
1603
  }
1476
1604
  return out;
1477
1605
  }
@@ -1509,15 +1637,30 @@ export const ACTORS_TABLE = {
1509
1637
  write: "none",
1510
1638
  };
1511
1639
  const OPS = Object.freeze(
1512
- /** @type {const} */ (["eq", "ne", "lt", "lte", "gt", "gte", "in", "nin", "like", "null", "has"]),
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
+ ]),
1513
1656
  );
1514
- /** How deep a where path or an include may follow references (docs/adr/0102). */
1657
+ /** How deep a where path or an include may follow references (docs/adr/0219). */
1515
1658
  const MAX_PATH = 3;
1516
1659
  /** How many includes one query may carry, nested ones counted. */
1517
1660
  const MAX_INCLUDES = 12;
1518
1661
  /** How deep `or` and `and` may nest. */
1519
1662
  const MAX_OR = 4;
1520
- /** The children a reverse include brings per row, at most (docs/adr/0102). */
1663
+ /** The children a reverse include brings per row, at most (docs/adr/0219). */
1521
1664
  export const MAX_CHILDREN = 100;
1522
1665
 
1523
1666
  /**
@@ -1532,7 +1675,7 @@ export function effectivePolicies(table) {
1532
1675
  }
1533
1676
 
1534
1677
  /**
1535
- * The Table a page sees for `<table>_history` (docs/adr/0040): the History's own columns, then the Table's
1678
+ * The Table a page sees for `<table>_history` (docs/adr/0218): the History's own columns, then the Table's
1536
1679
  * as nullable snapshots; read under the Table's policy, never written. `history` names the Table.
1537
1680
  * @type {typeof import("./schema.d.mts").historyTable}
1538
1681
  */
@@ -1612,7 +1755,7 @@ export function storedValueError(column, stored, name) {
1612
1755
  }
1613
1756
 
1614
1757
  /**
1615
- * The columns `next` makes stricter than `previous` for values already stored (docs/adr/0078): a TEXT column
1758
+ * The columns `next` makes stricter than `previous` for values already stored (docs/adr/0236): a TEXT column
1616
1759
  * that became DATE, a JSON column whose TYPE was added or changed. A Push checks their rows first.
1617
1760
  * @type {typeof import("./schema.d.mts").tightenedColumns}
1618
1761
  */
@@ -1635,7 +1778,7 @@ export function tightenedColumns(previous, next) {
1635
1778
  const ENUM_NAME_RE = /^(?:status|type|[a-z0-9_]+_type)$/;
1636
1779
 
1637
1780
  /**
1638
- * `schema-untyped-enum` (docs/adr/0078): TEXT columns named status, type or *_type that `next` adds without a
1781
+ * `schema-untyped-enum` (docs/adr/0236): TEXT columns named status, type or *_type that `next` adds without a
1639
1782
  * CHECK list, so their type is string. Only columns `previous` does not have: a published column cannot gain
1640
1783
  * one. `line` is 1-based in `sql`, the column's line inside its CREATE TABLE.
1641
1784
  * @type {typeof import("./schema.d.mts").untypedEnums}
@@ -1681,7 +1824,7 @@ const MONEY_PARTS = new Set(
1681
1824
  const RATIO_PARTS = new Set("rate pct percent ratio qty quantity hours weight factor".split(" "));
1682
1825
 
1683
1826
  /**
1684
- * `schema-real-money` (docs/adr/0107): REAL columns `next` adds whose name has a money part (`price`,
1827
+ * `schema-real-money` (docs/adr/0217): REAL columns `next` adds whose name has a money part (`price`,
1685
1828
  * `amount_due`) and no ratio part (`tax_rate`). Only columns `previous` does not have: a published REAL column
1686
1829
  * cannot become MONEY.
1687
1830
  * @type {typeof import("./schema.d.mts").realMoney}
@@ -1756,7 +1899,7 @@ function toStorage(type, value, column) {
1756
1899
  }
1757
1900
 
1758
1901
  /**
1759
- * Where a column of `table` leads (docs/adr/0102): a referenced Table's row, a list of them (a JSON id
1902
+ * Where a column of `table` leads (docs/adr/0219): a referenced Table's row, a list of them (a JSON id
1760
1903
  * list), an `actors` row (a MEMBER column, created_by, updated_by), or nowhere (null).
1761
1904
  * @param {Table} table @param {string} column
1762
1905
  * @returns {{kind: "row" | "rows" | "actor", table: string} | null}
@@ -1804,14 +1947,14 @@ function checkWhere(spec, table, tables, depth, ors) {
1804
1947
  if ("error" in checked) return checked;
1805
1948
  items.push(checked);
1806
1949
  }
1807
- // Every branch of an `and` must pass, as the rest of the where does, so its items join it (docs/adr/0115).
1950
+ // Every branch of an `and` must pass, as the rest of the where does, so its items join it (docs/adr/0219).
1808
1951
  if (key === "and") where.push(...items.flat());
1809
1952
  else where.push({ op: "or", items });
1810
1953
  continue;
1811
1954
  }
1812
1955
  const dot = key.indexOf(".");
1813
1956
  if (dot >= 0) {
1814
- // `"sample_id.status": ...`: rows whose referenced row passes (docs/adr/0102).
1957
+ // `"sample_id.status": ...`: rows whose referenced row passes (docs/adr/0219).
1815
1958
  const column = key.slice(0, dot);
1816
1959
  const ref = referenceOf(table, column);
1817
1960
  if (!columnTypeOf(table, column)) return { error: `no column "${column}"` };
@@ -1854,11 +1997,21 @@ function checkWhere(spec, table, tables, depth, ors) {
1854
1997
  where.push({ column, op, value: raw });
1855
1998
  continue;
1856
1999
  }
1857
- if (op === "like" && type !== "TEXT") return { error: `${column}: like needs a TEXT column` };
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
+ }
1858
2011
  if (type === "BOOLEAN" && op !== "eq" && op !== "ne")
1859
2012
  return { error: `${column}: a BOOLEAN column takes eq or ne only` };
1860
2013
  if (op === "in" || op === "nin") {
1861
- // An empty in matches nothing (docs/adr/0102); nin passes NULL and an empty nin every row (docs/adr/0115).
2014
+ // An empty in matches nothing (docs/adr/0219); nin passes NULL and an empty nin every row (docs/adr/0219).
1862
2015
  if (!Array.isArray(raw)) return { error: `${column}: ${op} takes an array` };
1863
2016
  if (raw.length > QUERY_MAX_LIMIT)
1864
2017
  return { error: `${column}: ${op} takes at most ${QUERY_MAX_LIMIT} values` };
@@ -1880,6 +2033,7 @@ function checkWhere(spec, table, tables, depth, ors) {
1880
2033
  }
1881
2034
  // `{ col: null }` and `{ col: { eq: null } }` mean IS NULL, `{ ne: null }` IS NOT NULL: what an author
1882
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).
1883
2037
  if (raw === null && (op === "eq" || op === "ne")) {
1884
2038
  where.push({ column, op: "null", value: op === "eq" });
1885
2039
  continue;
@@ -1894,7 +2048,7 @@ function checkWhere(spec, table, tables, depth, ors) {
1894
2048
  }
1895
2049
 
1896
2050
  /**
1897
- * Where an include lands on its row (docs/adr/0102): `<name>_id` -> `<name>`, `<name>_ids` -> `<name>`,
2051
+ * Where an include lands on its row (docs/adr/0219): `<name>_id` -> `<name>`, `<name>_ids` -> `<name>`,
1898
2052
  * any other column `c` -> `c_row` (`c_rows` for a list), and `<column>_row(s)` when the short name is a
1899
2053
  * column already. A reverse include lands on its child Table's name, or `<child>_rows` when that is a column.
1900
2054
  * @type {typeof import("./schema.d.mts").includeField}
@@ -1930,7 +2084,7 @@ function includeColumns(value, target, key) {
1930
2084
  }
1931
2085
 
1932
2086
  /**
1933
- * `include` (docs/adr/0102): forward paths through references and reverse child Tables, as a tree.
2087
+ * `include` (docs/adr/0219): forward paths through references and reverse child Tables, as a tree.
1934
2088
  * @param {unknown} spec @param {Table} table @param {Record<string, Table> | undefined} tables @param {boolean} reverse whether child Tables may be named here
1935
2089
  * @param {{count: number}} budget
1936
2090
  * @returns {import("./schema.d.mts").Include[] | {error: string}}
@@ -2053,7 +2207,7 @@ const ORDER_RE = /^(-?)([a-z][a-z0-9_]*)(?:\s+nulls\s+(first|last))?$/i;
2053
2207
 
2054
2208
  /**
2055
2209
  * Validates a page query `{ where?, order?, limit?, offset?, include? }` against a Declaration. `tables` are
2056
- * the Declaration's Tables, which paths through references and includes cross (docs/adr/0102); `table` is
2210
+ * the Declaration's Tables, which paths through references and includes cross (docs/adr/0219); `table` is
2057
2211
  * one of them, the same object.
2058
2212
  * @type {typeof import("./schema.d.mts").checkQuery}
2059
2213
  */
@@ -2101,7 +2255,7 @@ export function checkQuery(q, table, tables) {
2101
2255
  return { error: "offset must be a non-negative integer" };
2102
2256
  offset = q.offset;
2103
2257
  }
2104
- // `scope: false` reads past the active scope (docs/adr/0098); the access rules still apply.
2258
+ // `scope: false` reads past the active scope (docs/adr/0225); the access rules still apply.
2105
2259
  if (q.scope !== undefined && q.scope !== false)
2106
2260
  return { error: "scope takes false only: read past the active scope" };
2107
2261
  /** @type {import("./schema.d.mts").Include[]} */
@@ -2187,8 +2341,8 @@ export function checkAggregate(q, table, tables) {
2187
2341
  }
2188
2342
 
2189
2343
  /**
2190
- * Validates a row from a page for insert (every required column present) or update (only what is given, and
2191
- * a required column may not become null). Returns the row in storage form.
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.
2192
2346
  * @type {typeof import("./schema.d.mts").checkRow}
2193
2347
  */
2194
2348
  export function checkRow(body, table, mode) {
@@ -2202,7 +2356,6 @@ export function checkRow(body, table, mode) {
2202
2356
  if (raw === undefined) continue;
2203
2357
  if (mode === "update" && def.sequence)
2204
2358
  return { error: `${column} is a sequence and cannot be changed once assigned` };
2205
- if (raw === null && def.required) return { error: `${column} is required` };
2206
2359
  const c = toStorage(def.type, raw, column);
2207
2360
  if ("error" in c) return c;
2208
2361
  const bad = raw !== null && def.shape ? shapeError(shapeOf(def.shape), raw, column) : null;
@@ -2211,12 +2364,7 @@ export function checkRow(body, table, mode) {
2211
2364
  return { error: `${column} must be one of: ${def.values.join(", ")}` };
2212
2365
  row[column] = c.value;
2213
2366
  }
2214
- if (mode === "insert") {
2215
- for (const [column, def] of Object.entries(table.columns))
2216
- if (def.required && !(column in row)) return { error: `${column} is required` };
2217
- } else if (Object.keys(row).length === 0) {
2218
- return { error: "nothing to update" };
2219
- }
2367
+ if (mode === "update" && Object.keys(row).length === 0) return { error: "nothing to update" };
2220
2368
  return { row };
2221
2369
  }
2222
2370
 
@@ -2279,7 +2427,8 @@ const TOKEN =
2279
2427
 
2280
2428
  // Locate table positions separately from the conservative identifier security scan. Parentheses form
2281
2429
  // scopes for CTEs; expressions and column lists never become table references. `literalTables` holds the
2282
- // 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).
2283
2432
  /** @param {string} sql @param {Map<string, string>} app */
2284
2433
  function sqlTableReplacements(sql, app) {
2285
2434
  /**
@@ -2339,6 +2488,8 @@ function sqlTableReplacements(sql, app) {
2339
2488
  const replacements = new Map();
2340
2489
  /** @type {Set<number>} */
2341
2490
  const literalTables = new Set();
2491
+ /** @type {Set<string>} */
2492
+ const named = new Set();
2342
2493
  const clauses = new Set([
2343
2494
  "where",
2344
2495
  "group",
@@ -2403,7 +2554,9 @@ function sqlTableReplacements(sql, app) {
2403
2554
  // CTEs shadow read sources, but SQLite still resolves mutation targets as real tables.
2404
2555
  const writeTarget =
2405
2556
  keyword === "into" || keyword === "update" || (keyword === "from" && word(i - 1, "delete"));
2406
- const physical = !writeTarget && cte(s, table.name) ? null : app.get(table.name);
2557
+ const shadowed = !writeTarget && cte(s, table.name);
2558
+ if (!shadowed) named.add(table.name);
2559
+ const physical = shadowed ? null : app.get(table.name);
2407
2560
  if (physical)
2408
2561
  replacements.set(table.at, {
2409
2562
  length: table.raw.length,
@@ -2414,9 +2567,14 @@ function sqlTableReplacements(sql, app) {
2414
2567
  }
2415
2568
  // Keep the logical name as an alias so qualifiers retain SQLite scope semantics, including
2416
2569
  // correlated subqueries and different aliases in each arm of a compound SELECT.
2417
- return { replacements, literalTables };
2570
+ return { replacements, literalTables, named };
2418
2571
  }
2419
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
+
2420
2578
  /**
2421
2579
  * One DML statement on the Instance's tables, named as declared. Every identifier is checked: one of the
2422
2580
  * Instance's tables is allowed; anything else that is a table or view in the database
@@ -2451,7 +2609,7 @@ export function checkSql(statement, tables, instance) {
2451
2609
  // position ("SELECT * FROM 'user'") or a qualifier ("'user'.email"), so there a literal naming a
2452
2610
  // foreign table is refused. Anywhere else it is a value ("VALUES ('Account')") and passes; a string
2453
2611
  // is never rewritten, even when it names one of the Instance's own tables. SQLite's authorizer in the
2454
- // Builder SQL process enforces the same boundary whatever this pass concludes (ADR 0052).
2612
+ // Builder SQL process enforces the same boundary whatever this pass concludes (ADR 0240).
2455
2613
  const literal = m[1].replaceAll("''", "'").toLowerCase();
2456
2614
  if (literal.startsWith("sqlite_") || literal.startsWith("pragma_"))
2457
2615
  return { error: `${literal} is not allowed: only your tables can be named` };
@@ -2468,8 +2626,12 @@ export function checkSql(statement, tables, instance) {
2468
2626
  if (other.has(ident))
2469
2627
  return { error: `${ident} is not one of your tables: run \`ez db tables\`` };
2470
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 };
2471
2633
  const replacements = [...located.replacements].sort((a, b) => a[0] - b[0]);
2472
- // A History is read-only for everyone (docs/adr/0040): only the platform's triggers write it.
2634
+ // A History is read-only for everyone (docs/adr/0218): only the platform's triggers write it.
2473
2635
  const appNames = [...app.keys()];
2474
2636
  for (const [, r] of replacements) {
2475
2637
  const parent = r.write ? historyParent(r.table, appNames) : null;
@@ -2514,12 +2676,14 @@ owner), and a my() Table must be WRITE BY functions, BY none or WHERE group(...)
2514
2676
  themselves rows. Reads, counts, aggregates, Histories and attachments see only admitted rows; a row outside
2515
2677
  them is "Not found". Members' groups: ez user group add <who> <name>. Check what someone sees with
2516
2678
  \`ez db query <table> --as <who>\`; \`ez global push --dry-run\` reports what a change does to each Member.
2679
+ A rule goes in the push that declares the Table or column it reads: until a Preview or Deploy has added a
2680
+ new column the rule reads it as NULL, which is what every row then holds.
2517
2681
  READ lookup, department, sample_type WHERE group(staff); one rule for several Tables
2518
- GROUP analyst; a group server code may assign (docs/adr/0101)
2682
+ GROUP analyst; a group server code may assign (docs/adr/0225)
2519
2683
  GROUP lab-manager IMPLIES analyst, verifier; holding it confers those too, wherever groups are tested
2520
2684
  Keep roles in groups, not in a Table: group() needs no column on the row and the Host checks it without a
2521
2685
  read. ez-admin (the Instance's Admins) and ez-builder (every Builder) are the Host's groups, held through
2522
- the Builder roster: test them like any group, never declare or assign them (docs/adr/0110). Server code
2686
+ the Builder roster: test them like any group, never declare or assign them (docs/adr/0225). Server code
2523
2687
  with Site authority (authority "site", jobs, Listeners) manages the roster: context.members.list() (status
2524
2688
  invited | active | blocked, invitedAt, lastSignInAt, builder), .invite(email, { name, groups, send })
2525
2689
  (emailed once the function commits; send: false emails no one), .resend(memberId), .setGroups(memberId,
@@ -2544,6 +2708,9 @@ export function helpDb() {
2544
2708
  const refused = Object.entries(RULES.refused)
2545
2709
  .map(([k, why]) => ` ${k.padEnd(14)}${why}`)
2546
2710
  .join("\n");
2711
+ const accepted = Object.entries(RULES.accepted)
2712
+ .map(([k, means]) => ` ${k.padEnd(54)}${means}`)
2713
+ .join("\n");
2547
2714
  return `The App Database (one per Instance, shared by every Site in it).
2548
2715
 
2549
2716
  The Instance declares its schema once in global/${SCHEMA_FILE}. Run \`ez global pull\`, then
@@ -2552,13 +2719,13 @@ published schema on its next Preview or Deploy; existing deployments keep their
2552
2719
  Admins and Builders add Tables, columns and indexes; a Limited Builder reads the schema only.
2553
2720
  All user-defined columns are nullable, even on new Tables: NOT NULL is not supported. Inserts may
2554
2721
  omit columns; reads return null for missing values. Require values in the app's workflow.
2555
- Defaults (docs/adr/0097): <name> <type> DEFAULT <value> fills the column when an insert omits it, for
2722
+ Defaults (docs/adr/0224): <name> <type> DEFAULT <value> fills the column when an insert omits it, for
2556
2723
  every page, function and job, including deployments built before the default (it takes effect at Push).
2557
2724
  An explicit null stays null; updates and \`ez db sql\` never apply defaults; existing rows are not
2558
2725
  backfilled (the push says how many are null). Values: 'text' (one of its CHECK values, if any), 'YYYY-MM-DD'
2559
2726
  for DATE, a number, true/false, now for TIMESTAMP. A default may be added, changed or removed later.
2560
2727
 
2561
- Labels and integrity (docs/adr/0109): the schema says how records read and hold together, once.
2728
+ Labels and integrity (docs/adr/0222): the schema says how records read and hold together, once.
2562
2729
  CREATE TABLE dealers (
2563
2730
  customer_code TEXT LABEL 'Customer ID', -- The NextGen id_customer. (a column's doc: the comment on its line)
2564
2731
  name TEXT,
@@ -2575,9 +2742,9 @@ job write (not \`ez db sql\`) from the Push on; a Push adding SINGLETON or EXACT
2575
2742
  it. A refused write is a 409 with \`code\` ("unique", "restricted", "singleton", "exactly-one"): in a page,
2576
2743
  \`e instanceof WriteError && e.code === "restricted"\`. Never check references or owners in page code.
2577
2744
 
2578
- Access (docs/adr/0098): global/db/access.sql says who reads and writes which rows; \`ez help access\`.
2745
+ Access (docs/adr/0225): global/db/access.sql says who reads and writes which rows; \`ez help access\`.
2579
2746
 
2580
- Rules (docs/adr/0099): global/rules/<table>.ts runs for every page, function and job write of that Table
2747
+ Rules (docs/adr/0226): global/rules/<table>.ts runs for every page, function and job write of that Table
2581
2748
  (never Builder SQL), inside the write:
2582
2749
  import { rules } from "@ezship/react/server";
2583
2750
  export default rules<"orders">({
@@ -2590,7 +2757,7 @@ then the access condition. Push compiles them; a changed guard is replayed over
2590
2757
  refusing any needs an Admin's --force (see --dry-run). Keep them fast: they run while the write holds the
2591
2758
  database (250 ms). Put shared logic in global/lib and call it from both rules and functions.
2592
2759
 
2593
- Workflows (docs/adr/0103): global/workflows/<table>.ts makes a TEXT status column a state machine the Host
2760
+ Workflows (docs/adr/0227): global/workflows/<table>.ts makes a TEXT status column a state machine the Host
2594
2761
  runs for every page, function and job write (never Builder SQL):
2595
2762
  import { workflow } from "@ezship/react/server";
2596
2763
  export default workflow<"sample">({
@@ -2620,8 +2787,6 @@ Backfilling rows does not synchronize old and new writers.
2620
2787
  After editing, run \`ez global check\` and \`ez global push\`. Push records definitions without DDL;
2621
2788
  a successful Site Preview or Deploy creates missing Tables, columns and indexes. Unpushed schema
2622
2789
  changes cannot be previewed against production storage. Preview data writes remain real.
2623
- For an existing Site schema, start from \`ez db schema\`, review table read/write policies, move
2624
- its definitions into global, remove NOT NULL, push global, and delete the Site's schema/types copies.
2625
2790
  Import row aliases with \`import type { Order } from "global/db/types"\`.
2626
2791
 
2627
2792
  ${SCHEMA_FILE} holds only CREATE TABLE, CREATE INDEX and CREATE UNIQUE INDEX statements, each ending with ;
@@ -2646,17 +2811,18 @@ Types:
2646
2811
  ${types}
2647
2812
  Names: lowercase letters, digits, underscores; not ez_*, not a system column, not a platform table name.
2648
2813
  CHECK: only on TEXT columns; values are letters, digits, spaces, _ . - ; published value sets are fixed; enum evolution is a separate decision.
2649
- Unique keys (docs/adr/0046): CREATE UNIQUE INDEX ON <table> (<columns>) after the table. Matching is exact
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
2650
2816
  (normalize case in the form); NULLs are distinct, so require the value in the app. An insert or update that
2651
2817
  repeats a key is refused: pages get a rejected promise "<table>: <columns> must be unique" (409); in a
2652
2818
  function the failed write makes the whole call roll back, so check before you insert. Pushing a unique index
2653
2819
  over a Table that already holds duplicates is refused with the duplicate values; fix the rows with SQL first.
2654
- Sequences (docs/adr/0046): <name> INTEGER SEQUENCE numbers rows per Table: an insert that omits the column
2820
+ Sequences (docs/adr/0217): <name> INTEGER SEQUENCE numbers rows per Table: an insert that omits the column
2655
2821
  gets max + 1 (from 1) inside its own write, whoever writes; a value you supply wins and later numbers continue
2656
2822
  above it. Assigned once: updates are refused. Numbers increase and are never reused; deleted rows leave gaps;
2657
2823
  there is no periodic reset (format SO-000123 or a yearly prefix in the app). Rows older than the column stay
2658
2824
  null until you backfill them with SQL. A sequence column always has a unique index.
2659
- Typed JSON (docs/adr/0078): JSON TYPE '<shape>' gives a JSON column its TypeScript type and checks every page
2825
+ Typed JSON (docs/adr/0236): JSON TYPE '<shape>' gives a JSON column its TypeScript type and checks every page
2660
2826
  and function write against it. A shape is string, number, boolean, null, unknown, DateString, EpochMs, Cents,
2661
2827
  "literal" values, { name: T; optional?: T }, T[], Array<T>, Record<string, T>, unions with | and parentheses,
2662
2828
  on one line. Objects are exact: a key the shape does not list is refused. A refused write names the path:
@@ -2666,19 +2832,23 @@ Dates and times: DATE holds a local calendar date, TEXT 'YYYY-MM-DD', and orders
2666
2832
  TIMESTAMP (and created_at, updated_at) holds epoch milliseconds. Pages and functions get DateString and EpochMs
2667
2833
  and build them with today(), toDate(year, month, day) or toDate(date), toEpoch(dateString) and now() from
2668
2834
  @ezship/react (or @ezship/react/server). A published TEXT column may become DATE once every stored value is a date.
2669
- Money (docs/adr/0107): MONEY holds whole cents as an INTEGER, so sums are exact; never declare money REAL.
2835
+ Money (docs/adr/0217): MONEY holds whole cents as an INTEGER, so sums are exact; never declare money REAL.
2670
2836
  Pages and functions write Cents: toCents("1,234.50") (or toCents(12.5)) rounds to the cent, null when
2671
2837
  unreadable; fromCents(cents) gives units for arithmetic; global Money draws it. A published INTEGER column may
2672
2838
  become MONEY; a REAL one cannot: add a MONEY column and backfill it with ROUND(price * 100) in ez db sql.
2673
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}
2674
2842
  Not allowed in ${SCHEMA_FILE}:
2675
2843
  ${refused}
2676
2844
 
2677
2845
  Rows: pages use the helper (see \`ez help\`); you use \`ez db sql\` with one SELECT, WITH, INSERT, UPDATE or DELETE.
2678
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.
2679
2849
  Table references are rewritten per Instance; column names, aliases and CTE names keep their meaning.
2680
2850
  Never DDL: tables change only through ${SCHEMA_FILE} and \`ez deploy\`. Reads return at most ${SQL_MAX_ROWS} rows.
2681
- A statement runs in its own process: a read is stopped after 10 seconds and a write after 5 (a stopped write
2851
+ A statement runs in its own process: a read is stopped after 10 seconds and a write after 30 (a stopped write
2682
2852
  leaves nothing), and a result over 16 MB is refused. Page through large Tables with LIMIT and a WHERE on id.
2683
2853
  Rows you insert with SQL get id, created_at, created_by, updated_at and updated_by automatically (the actor is
2684
2854
  you, 'builder:<your id>'); a value you set yourself wins. The changed-row count of a write is the statement's
@@ -2705,10 +2875,11 @@ useLive.aggregate("tickets", { group: ["status"] }) returns { rows: [{ group: {
2705
2875
  Add sum: ["amount"] for INTEGER/MONEY/REAL columns; db.aggregate has the same query in handlers and Functions.
2706
2876
  Filters cover all input rows. limit/offset bound only grouped output, which reports truncated.
2707
2877
  Row queries default to ${QUERY_DEFAULT_LIMIT} and cap at ${QUERY_MAX_LIMIT}; never reduce them into a total.
2708
- Use useLive.query / db.query to inspect rows and truncated instead of the legacy array-only results.
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.
2709
2880
  Builders: ez db aggregate tickets '{"group":["status"]}'.
2710
2881
 
2711
- Relations (docs/adr/0102): a query follows REFERENCES. include: { sample_id: ["code"], "sample_id.client_id": ["name"],
2882
+ Relations (docs/adr/0219): a query follows REFERENCES. include: { sample_id: ["code"], "sample_id.client_id": ["name"],
2712
2883
  analyst: ["name"] (MEMBER, created_by, updated_by -> actors), method_instrument: { instrument_id: true } (child rows) }
2713
2884
  brings the rows with each row, each under its Table's READ rule; where: { "sample_id.status": "received", or: [...] }
2714
2885
  filters through them before paging. An id list is <name> JSON REFERENCES <table> (stored as JSON TYPE 'string[]',
@@ -2724,7 +2895,8 @@ Builders: ez db actors '{"where":{"kind":"builder"}}'.`;
2724
2895
  // ---- ez db schema ---------------------------------------------------------------------------------------
2725
2896
 
2726
2897
  /**
2727
- * The live schema as declarations a site can copy into db/schema.sql, with who declares each table.
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.
2728
2900
  * @type {typeof import("./schema.d.mts").renderSchema}
2729
2901
  */
2730
2902
  export function renderSchema(schema) {
@@ -2740,20 +2912,18 @@ export function renderSchema(schema) {
2740
2912
  const columnOf = (t, c, storage) => {
2741
2913
  for (const site of declarers(t)) {
2742
2914
  const col = schema.declarations[site][t].columns[c];
2743
- if (col) return describeColumn({ ...col, required: false }, c);
2915
+ if (col) return describeColumn(col, c);
2744
2916
  }
2745
2917
  return storage;
2746
2918
  };
2747
2919
  const out = [];
2748
2920
  for (const t of names) {
2749
2921
  const live = schema.live.tables[t];
2750
- const sites = declarers(t);
2751
2922
  const parent = historyParent(t, names);
2752
- out.push(
2753
- parent
2754
- ? `-- ${t}: the History of ${parent} (read-only; every change to ${parent}, see ez help db)`
2755
- : `-- ${t}: declared by ${sites.length ? sites.join(", ") : "no site"}`,
2756
- );
2923
+ if (parent)
2924
+ out.push(
2925
+ `-- ${t}: the History of ${parent} (read-only; every change to ${parent}, see ez help db)`,
2926
+ );
2757
2927
  out.push(`CREATE TABLE ${t} (`);
2758
2928
  out.push(
2759
2929
  Object.entries(live.columns)
@@ -2815,7 +2985,7 @@ function singular(word) {
2815
2985
  return word;
2816
2986
  }
2817
2987
 
2818
- // ---- the descriptor (docs/adr/0109) -------------------------------------------------------------------
2988
+ // ---- the descriptor (docs/adr/0222) -------------------------------------------------------------------
2819
2989
  //
2820
2990
  // What the Framework's record components read at run time: each Table's labels, display columns,
2821
2991
  // constraints and columns in declared order, and every scalar reference pointing at it. The Pipeline bundles
@@ -2841,8 +3011,8 @@ export function pluralLabel(label) {
2841
3011
  }
2842
3012
 
2843
3013
  /**
2844
- * The integrity constraints a Push adds or removes (docs/adr/0109): SINGLETON, EXACTLY ONE OF and each ON
2845
- * DELETE RESTRICT. Live definitions (docs/adr/0096): they apply to every write from the Push on.
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.
2846
3016
  * @type {typeof import("./schema.d.mts").integrityChanges}
2847
3017
  */
2848
3018
  export function integrityChanges(previous, next) {
@@ -2885,7 +3055,7 @@ export function integrityChanges(previous, next) {
2885
3055
  }
2886
3056
 
2887
3057
  /**
2888
- * The run-time descriptor of a Declaration's Tables (docs/adr/0109). Histories and the actors view are left
3058
+ * The run-time descriptor of a Declaration's Tables (docs/adr/0222). Histories and the actors view are left
2889
3059
  * out: the record components draw declared Tables.
2890
3060
  * @type {typeof import("./schema.d.mts").describeSchema}
2891
3061
  */
@@ -2948,13 +3118,13 @@ const tsType = (c) => {
2948
3118
  return `${base} | null`;
2949
3119
  };
2950
3120
 
2951
- /** A column's label and doc as JSDoc (docs/adr/0109), or nothing. @param {Column} c */
3121
+ /** A column's label and doc as JSDoc (docs/adr/0222), or nothing. @param {Column} c */
2952
3122
  const jsDoc = (c) => {
2953
3123
  const text = [c.label, c.doc].filter(Boolean).join(": ").replaceAll("*/", "* /");
2954
3124
  return text ? `/** ${text} */ ` : "";
2955
3125
  };
2956
3126
 
2957
- /** A History's own columns as TypeScript (docs/adr/0040); never optional, never null but `by`, `why` and `transition`. */
3127
+ /** A History's own columns as TypeScript (docs/adr/0218); never optional, never null but `by`, `why` and `transition`. */
2958
3128
  const HISTORY_TS = Object.freeze({
2959
3129
  /** @param {string} t */
2960
3130
  row_id: (t) => `Id<${JSON.stringify(t)}>`,
@@ -2968,7 +3138,7 @@ const HISTORY_TS = Object.freeze({
2968
3138
  });
2969
3139
 
2970
3140
  /**
2971
- * The References and Children interfaces of db/types.d.ts (docs/adr/0102), from the same rules the Host
3141
+ * The References and Children interfaces of db/types.d.ts (docs/adr/0219), from the same rules the Host
2972
3142
  * includes by: each forward column's target Table and the field it lands on, each indexed child Table.
2973
3143
  * @param {import("./schema.d.mts").Declaration} decl @param {string[]} tables
2974
3144
  */
@@ -3034,7 +3204,7 @@ export function generateTypes(decl, workflows = {}) {
3034
3204
  const member = tables.some((t) =>
3035
3205
  Object.values(decl.tables[t].columns).some((c) => c.type === "MEMBER"),
3036
3206
  );
3037
- // Cents likewise, for MONEY columns and JSON shapes that name it (docs/adr/0107).
3207
+ // Cents likewise, for MONEY columns and JSON shapes that name it (docs/adr/0217).
3038
3208
  const cents = tables.some((t) =>
3039
3209
  Object.values(decl.tables[t].columns).some(
3040
3210
  (c) => c.type === "MONEY" || /\bCents\b/.test(c.shape ?? ""),
@@ -3054,7 +3224,7 @@ export function generateTypes(decl, workflows = {}) {
3054
3224
  .map(([c, d]) => `${c}?: ${tsType(d)}`)
3055
3225
  .join("; ");
3056
3226
  const flow = flows[t];
3057
- // A labelled or documented column carries its JSDoc (docs/adr/0109); the rest stay as they were.
3227
+ // A labelled or documented column carries its JSDoc (docs/adr/0222); the rest stay as they were.
3058
3228
  const own = Object.entries(decl.tables[t].columns)
3059
3229
  .map(
3060
3230
  ([c, d]) =>
@@ -3069,9 +3239,9 @@ export function generateTypes(decl, workflows = {}) {
3069
3239
  }
3070
3240
  lines.push(" }");
3071
3241
  }
3072
- // What a query may include (docs/adr/0102): each column's target and where it lands, each child Table.
3242
+ // What a query may include (docs/adr/0219): each column's target and where it lands, each child Table.
3073
3243
  lines.push(...relationTypes(decl, tables));
3074
- // Each workflow's column, states and the actions a caller may name (docs/adr/0103).
3244
+ // Each workflow's column, states and the actions a caller may name (docs/adr/0227).
3075
3245
  const flowTables = Object.keys(flows).sort();
3076
3246
  if (flowTables.length) {
3077
3247
  lines.push(" interface Workflows {");