@mistriwork/engine 1.0.0-rc.10 → 1.0.0-rc.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/adapters/adapter.d.ts +33 -0
  2. package/dist/adapters/postgres.d.ts +21 -16
  3. package/dist/adapters/postgres.js +199 -223
  4. package/dist/adapters/postgresCatalog.d.ts +12 -1
  5. package/dist/adapters/postgresCatalog.js +57 -23
  6. package/dist/adapters/postgresCatalogDigest.js +40 -34
  7. package/dist/adapters/postgresCatalogRows.d.ts +2 -0
  8. package/dist/adapters/postgresWriteAhead.d.ts +47 -0
  9. package/dist/adapters/postgresWriteAhead.js +209 -0
  10. package/dist/adapters/scoped/keyRows.js +9 -3
  11. package/dist/adapters/scoped/keyTypes.d.ts +34 -0
  12. package/dist/adapters/scoped/keyTypes.js +66 -0
  13. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +40 -1
  14. package/dist/adapters/scoped/postgresScopeCatalog.js +417 -13
  15. package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
  16. package/dist/adapters/scoped/postgresTriggers.js +1545 -0
  17. package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
  18. package/dist/adapters/scoped/scopeTriggers.js +131 -0
  19. package/dist/adapters/scoped/scopedReads.d.ts +3 -1
  20. package/dist/adapters/scoped/scopedReads.js +28 -8
  21. package/dist/adapters/scoped/scopedTransaction.d.ts +95 -6
  22. package/dist/adapters/scoped/scopedTransaction.js +308 -34
  23. package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +17 -1
  24. package/dist/adapters/scoped/sqliteScopeCatalog.js +197 -18
  25. package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
  26. package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
  27. package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
  28. package/dist/adapters/scoped/sqliteTriggers.js +822 -0
  29. package/dist/adapters/scoped/storedText.d.ts +45 -0
  30. package/dist/adapters/scoped/storedText.js +61 -0
  31. package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
  32. package/dist/adapters/scoped/triggerEffects.js +189 -0
  33. package/dist/adapters/scoped/triggerProof.d.ts +124 -0
  34. package/dist/adapters/scoped/triggerProof.js +366 -0
  35. package/dist/adapters/snapshotRead.d.ts +8 -0
  36. package/dist/adapters/snapshotRead.js +37 -0
  37. package/dist/adapters/sqlite.d.ts +13 -2
  38. package/dist/adapters/sqlite.js +139 -16
  39. package/dist/adapters/sqliteDecimals.d.ts +2 -2
  40. package/dist/adapters/sqliteDecimals.js +2 -8
  41. package/dist/adapters/storeHost.d.ts +4 -1
  42. package/dist/adapters/writeCapture.d.ts +7 -0
  43. package/dist/server/cli/args.d.ts +6 -0
  44. package/dist/server/cli/args.js +6 -0
  45. package/dist/server/columnGrants.d.ts +3 -0
  46. package/dist/server/columnGrants.js +12 -1
  47. package/dist/server/config/profile.d.ts +123 -0
  48. package/dist/server/config/profile.js +236 -0
  49. package/dist/server/connections.d.ts +5 -0
  50. package/dist/server/connections.js +11 -1
  51. package/dist/server/hiddenColumns.js +6 -0
  52. package/dist/server/http/refusalReport.js +16 -4
  53. package/dist/server/http/router.d.ts +11 -22
  54. package/dist/server/http/router.js +0 -15
  55. package/dist/server/migrate/cli.d.ts +50 -3
  56. package/dist/server/migrate/cli.js +199 -14
  57. package/dist/server/migrate/runner.js +5 -1
  58. package/dist/server/shapeonly.js +5 -0
  59. package/dist/shared/addressParams.d.ts +2 -0
  60. package/dist/shared/addressParams.js +2 -0
  61. package/dist/shared/aggregate.d.ts +49 -0
  62. package/dist/shared/aggregate.js +107 -0
  63. package/dist/shared/breakdown.js +19 -6
  64. package/dist/shared/decimals.d.ts +37 -0
  65. package/dist/shared/decimals.js +148 -0
  66. package/dist/shared/displayDefaults.js +15 -1
  67. package/dist/shared/filter.d.ts +39 -1
  68. package/dist/shared/filter.js +96 -15
  69. package/dist/shared/listPresentations.d.ts +2 -0
  70. package/dist/shared/listQuestion.d.ts +3 -1
  71. package/dist/shared/money.d.ts +9 -0
  72. package/dist/shared/money.js +17 -0
  73. package/dist/shared/moneyEntry.d.ts +6 -3
  74. package/dist/shared/moneyEntry.js +14 -7
  75. package/dist/shared/pageModel.d.ts +1 -1
  76. package/dist/shared/recordview.d.ts +1 -1
  77. package/dist/shared/refusal.d.ts +16 -0
  78. package/dist/shared/refusal.js +40 -0
  79. package/dist/shared/rowScope.js +12 -4
  80. package/dist/shared/schema.d.ts +6 -0
  81. package/dist/shared/schematext.d.ts +22 -6
  82. package/dist/shared/schematext.js +18 -2
  83. package/dist/shared/scopeCatalog.js +4 -0
  84. package/dist/shared/servedApp.d.ts +15 -4
  85. package/dist/shared/view.js +4 -4
  86. package/dist/shared/viewLabels.d.ts +1 -0
  87. package/dist/shared/viewLabels.js +8 -2
  88. package/dist/shared/viewPaths.d.ts +3 -0
  89. package/dist/shared/viewPaths.js +8 -0
  90. package/package.json +5 -2
  91. package/schema/model.d.ts +1 -1
  92. package/dist/shared/order.d.ts +0 -59
  93. package/dist/shared/order.js +0 -133
@@ -0,0 +1,37 @@
1
+ /** The scale a declared type asks for, when it is a DECIMAL/NUMERIC with one above zero. */
2
+ export declare function declaredScale(type: string | null | undefined): number;
3
+ /** Whether a SQLite sum over a column of this declared type is summed exactly (`exactSqliteSum`). */
4
+ export declare const sumsExactly: (type: string | null | undefined) => boolean;
5
+ /**
6
+ * A SQLite column of `scale` places summed as an integer count of its
7
+ * smallest unit: `total` is that integer (for ordering by it), `text` the
8
+ * decimal it says, null over no rows as `SUM` is. `read` is the column's
9
+ * expression; the scale is a number read off the catalog, never a request's
10
+ * text.
11
+ */
12
+ export declare function exactSqliteSum(read: string, scale: number, label?: string): {
13
+ total: string;
14
+ text: string;
15
+ };
16
+ /** The columns a list of measures sums, for the refusal to name. */
17
+ export declare const summed: (measures: readonly {
18
+ fn?: string;
19
+ path?: string;
20
+ column?: string;
21
+ }[] | undefined) => string[];
22
+ /**
23
+ * Runs a SQLite read whose rows may hold exact sums: a cell that says it was beyond exact range, or SQLite's own
24
+ * `integer overflow` while adding, is the refusal, naming the columns summed (`columns`).
25
+ */
26
+ export declare function readExactly<T extends {
27
+ rows: readonly Record<string, unknown>[];
28
+ }>(run: () => Promise<T>, columns: readonly string[]): Promise<T>;
29
+ /** A decimal as an integer count of units and its places, or undefined when the text is not a plain decimal. */
30
+ export declare function parseDecimal(value: string | number | bigint): {
31
+ units: bigint;
32
+ scale: number;
33
+ } | undefined;
34
+ /** An integer count of units said with `scale` places: `formatDecimal(-5n, 2)` is `-0.05`. */
35
+ export declare function formatDecimal(units: bigint, scale: number): string;
36
+ /** The mean of an exact sum over `count` values, said with `places` places, rounded half to even. */
37
+ export declare function exactAverage(sum: string | number | bigint, count: number | bigint, places: number): string | undefined;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Decimal columns said exactly: the scale a declared type asks for, and an
3
+ * exact SQLite sum over one.
4
+ *
5
+ * PostgreSQL's `numeric` is exact and `SUM` over it is too, read as text by
6
+ * `pg`. SQLite stores `numeric(12,2)` as an integer or a REAL and sums it as
7
+ * a REAL, so 0.10 + 0.20 + 0.07 + 100,000,000,000,000.00 came back as
8
+ * `100000000000000.38`. Summed here as whole hundredths instead — each value
9
+ * times 10^scale, rounded once to an integer, added as integers — and said
10
+ * with the column's places, as PostgreSQL says it, the two engines agree to
11
+ * the cent. Exact while each REAL value times 10^scale is below 2^53 (SQLite
12
+ * keeps a number with a fraction as a REAL, whose whole units stop there), an
13
+ * integer value times 10^scale and the total fit 2^63. Past either, no answer
14
+ * is the right one, so none is given: the sum says it is beyond exact range
15
+ * (`ExactnessRefusal`), where it once answered 10.223372036854775808 for
16
+ * 10 + 0.5. SQLite's own `integer overflow` of a total is the same refusal.
17
+ */
18
+ import { RequestFault } from './refusal.js';
19
+ /** The sum of a decimal column SQLite cannot add exactly: a data or schema fault (a column declared with more
20
+ places than SQLite can hold), never worth a retry. */
21
+ class ExactnessRefusal extends RequestFault {
22
+ constructor(columns) {
23
+ const named = columns.length ? columns.map((column) => `"${column}"`).join(', ') : 'a decimal column';
24
+ super(`The sum of ${named} is beyond what SQLite adds exactly: a value times 10^places passes 2^53 (a REAL) or 2^63 (an integer), ` +
25
+ 'or the total passes 2^63. Declare fewer places, hold smaller values, or run the App on PostgreSQL.', { columns });
26
+ this.name = 'ExactnessRefusal';
27
+ }
28
+ }
29
+ /** What an exact sum says in place of a number when it cannot be exact; `refuseInexact` turns it into the refusal. */
30
+ const INEXACT = '\u001finexact\u001f';
31
+ const DECLARED_SCALE = /^\s*(?:decimal|numeric)\s*\(\s*\d+\s*,\s*(\d+)\s*\)\s*$/i;
32
+ /** The scale a declared type asks for, when it is a DECIMAL/NUMERIC with one above zero. */
33
+ export function declaredScale(type) {
34
+ if (!type)
35
+ return 0;
36
+ const scale = Number(DECLARED_SCALE.exec(type)?.[1] ?? 0);
37
+ return scale > 0 ? scale : 0;
38
+ }
39
+ /** The most places an exact sum says: 10^18 is the largest power of ten a SQLite integer holds. */
40
+ const MOST_PLACES = 18;
41
+ /** Whether a SQLite sum over a column of this declared type is summed exactly (`exactSqliteSum`). */
42
+ export const sumsExactly = (type) => {
43
+ const scale = declaredScale(type);
44
+ return scale > 0 && scale <= MOST_PLACES;
45
+ };
46
+ /**
47
+ * A SQLite column of `scale` places summed as an integer count of its
48
+ * smallest unit: `total` is that integer (for ordering by it), `text` the
49
+ * decimal it says, null over no rows as `SUM` is. `read` is the column's
50
+ * expression; the scale is a number read off the catalog, never a request's
51
+ * text.
52
+ */
53
+ export function exactSqliteSum(read, scale, label = '') {
54
+ if (!Number.isInteger(scale) || scale < 1 || scale > MOST_PLACES)
55
+ throw new RangeError(`An exact sum takes 1 to ${MOST_PLACES} places.`);
56
+ const unit = `1${'0'.repeat(scale)}`;
57
+ /* A value stored as an integer is multiplied as one, exactly; a REAL is
58
+ rounded once to the nearest unit, which is what the column meant. */
59
+ const total = `SUM(CASE WHEN typeof(${read}) = 'integer' THEN ${read} * ${unit} ELSE CAST(ROUND(${read} * ${unit}) AS INTEGER) END)`;
60
+ /* A REAL past 2^53 units is rounded to a neighbor before it is added, and a total that is no longer an integer
61
+ is an integer product that overflowed into a REAL: neither is the sum, so the cell says so instead. */
62
+ const beyond = `SUM(CASE WHEN typeof(${read}) = 'real' AND abs(${read} * ${unit}) >= 9007199254740992 THEN 1 ELSE 0 END) > 0`;
63
+ const text = `CASE WHEN ${total} IS NULL THEN NULL ` +
64
+ `WHEN ${beyond} OR typeof(${total}) <> 'integer' THEN '${INEXACT}' || '${label.replaceAll("'", "''")}' ELSE ` +
65
+ `(CASE WHEN ${total} < 0 THEN '-' ELSE '' END) || printf('%d.%0${scale}d', abs(${total}) / ${unit}, abs(${total}) % ${unit}) END`;
66
+ return { total, text };
67
+ }
68
+ /** The columns a list of measures sums, for the refusal to name. */
69
+ export const summed = (measures) => (measures ?? []).flatMap((measure) => measure.fn === 'sum' && (measure.path ?? measure.column) ? [(measure.path ?? measure.column)] : []);
70
+ /**
71
+ * Runs a SQLite read whose rows may hold exact sums: a cell that says it was beyond exact range, or SQLite's own
72
+ * `integer overflow` while adding, is the refusal, naming the columns summed (`columns`).
73
+ */
74
+ export async function readExactly(run, columns) {
75
+ let result;
76
+ try {
77
+ result = await run();
78
+ }
79
+ catch (error) {
80
+ if (columns.length && error instanceof Error && /integer overflow/i.test(error.message))
81
+ throw new ExactnessRefusal(columns);
82
+ throw error;
83
+ }
84
+ const found = new Set();
85
+ for (const row of result.rows)
86
+ for (const value of Object.values(row))
87
+ if (typeof value === 'string' && value.startsWith(INEXACT))
88
+ found.add(value.slice(INEXACT.length));
89
+ if (found.size)
90
+ throw new ExactnessRefusal([...found].filter(Boolean).length ? [...found].filter(Boolean) : columns);
91
+ return result;
92
+ }
93
+ /* ---------- exact decimal text in the server ---------- */
94
+ const DECIMAL_TEXT = /^(-)?(\d+)(?:\.(\d+))?$/;
95
+ /** A decimal as an integer count of units and its places, or undefined when the text is not a plain decimal. */
96
+ export function parseDecimal(value) {
97
+ if (typeof value === 'bigint')
98
+ return { units: value, scale: 0 };
99
+ if (typeof value === 'number') {
100
+ if (!Number.isFinite(value))
101
+ return undefined;
102
+ if (Number.isInteger(value))
103
+ return Number.isSafeInteger(value) ? { units: BigInt(value), scale: 0 } : undefined;
104
+ value = String(value);
105
+ if (/e/i.test(value))
106
+ return undefined;
107
+ }
108
+ const match = DECIMAL_TEXT.exec(value.trim());
109
+ if (!match)
110
+ return undefined;
111
+ const places = match[3] ?? '';
112
+ const units = BigInt(`${match[2]}${places}`);
113
+ return { units: match[1] ? -units : units, scale: places.length };
114
+ }
115
+ /** An integer count of units said with `scale` places: `formatDecimal(-5n, 2)` is `-0.05`. */
116
+ export function formatDecimal(units, scale) {
117
+ const negative = units < 0n;
118
+ const digits = (negative ? -units : units).toString().padStart(scale + 1, '0');
119
+ const whole = scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits;
120
+ return negative && /[1-9]/.test(digits) ? `-${whole}` : whole;
121
+ }
122
+ /** `units / divisor`, rounded half to even: the banker's rounding, so ties do not drift one way. */
123
+ function divideHalfEven(units, divisor) {
124
+ if (divisor === 0n)
125
+ throw new RangeError('Division by zero.');
126
+ if (divisor < 0n)
127
+ return divideHalfEven(-units, -divisor);
128
+ let quotient = units / divisor;
129
+ const remainder = units - quotient * divisor;
130
+ const twice = (remainder < 0n ? -remainder : remainder) * 2n;
131
+ if (twice > divisor || (twice === divisor && quotient % 2n !== 0n))
132
+ quotient += remainder < 0n ? -1n : 1n;
133
+ return quotient;
134
+ }
135
+ /** The mean of an exact sum over `count` values, said with `places` places, rounded half to even. */
136
+ export function exactAverage(sum, count, places) {
137
+ const parsed = parseDecimal(sum);
138
+ if (!parsed)
139
+ return undefined;
140
+ const n = BigInt(count);
141
+ if (n <= 0n)
142
+ return undefined;
143
+ /* sum / count at `places` places: units · 10^(places − scale) / count, with the shift folded into whichever side keeps it whole. */
144
+ const shift = places - parsed.scale;
145
+ const numerator = shift >= 0 ? parsed.units * 10n ** BigInt(shift) : parsed.units;
146
+ const denominator = shift >= 0 ? n : n * 10n ** BigInt(-shift);
147
+ return formatDecimal(divideHalfEven(numerator, denominator), places);
148
+ }
@@ -293,7 +293,21 @@ const CONCERNS = [
293
293
  {
294
294
  name: 'figure',
295
295
  owns: ['format', 'bar', 'unit', 'minor', 'currency'],
296
- displaces: ['format', 'bar', 'unit', 'ring', 'slider', 'outOf', 'max', 'minor', 'currency', 'currencyColumn', 'values', 'avatar'],
296
+ displaces: [
297
+ 'format',
298
+ 'bar',
299
+ 'unit',
300
+ 'ring',
301
+ 'slider',
302
+ 'outOf',
303
+ 'max',
304
+ 'minor',
305
+ 'whole',
306
+ 'currency',
307
+ 'currencyColumn',
308
+ 'values',
309
+ 'avatar',
310
+ ],
297
311
  },
298
312
  { name: 'words', owns: ['values'], displaces: ['values', 'format'] },
299
313
  { name: 'tone', owns: ['tone'], displaces: ['tone', 'colors'] },
@@ -32,6 +32,25 @@ export interface Condition {
32
32
  * `op` is `isNotNull` for `any`, `isNull` for `no`.
33
33
  */
34
34
  any?: AnyRows;
35
+ /**
36
+ * Compare as a PostgreSQL foreign key compares a reference with its parent's key: by its own operator, named with
37
+ * its schema, the value cast to the referencing column's type and each side to the operator's, as the database's
38
+ * own check is written (ri_triggers.c). Read from the catalog for a scoped write's parent check
39
+ * (scopedTransaction.ts); SQL text, so only a builder that asks for it (`buildWhere`'s `references`) compiles it,
40
+ * and everywhere else it is refused.
41
+ */
42
+ equality?: ConditionEquality;
43
+ }
44
+ /** A foreign key's comparison of one column (`Condition.equality`): each part SQL as the catalog gave it. */
45
+ export interface ConditionEquality {
46
+ /** `schema.operator`, the schema quoted where it needs it. */
47
+ readonly operator: string;
48
+ /** The type the value is read as: the referencing column's, typmod and all. */
49
+ readonly type: string;
50
+ /** The operator's left type, where the parent column's is another. */
51
+ readonly left?: string;
52
+ /** The operator's right type, where the referencing column's is another. */
53
+ readonly right?: string;
35
54
  }
36
55
  /**
37
56
  * The child rows an `any` condition asks about: the reference they point
@@ -155,6 +174,20 @@ export interface SqlStyle {
155
174
  jsonKey?(expression: string, key: string, as: 'value' | 'text' | 'number'): string;
156
175
  /** Whether a JSON key's list (or its one value) holds any of the bound values: `has` on a many-of-a-list field. */
157
176
  jsonHas?(expression: string, key: string, holes: readonly string[]): string;
177
+ /**
178
+ * The built-in type a column of `type` (ColumnMeta.type, the catalog's own word) compares as, where a comparison
179
+ * names its operator by schema: PostgreSQL's `OPERATOR(pg_catalog.=)`, as `name` (what an IN list is read as) and
180
+ * whether a pattern reads it as text. A bare `=` resolves through the search_path, where an exact signature
181
+ * pg_catalog lacks (`varchar = varchar`) wins over pg_catalog's own. Undefined for every other type (an enum, an
182
+ * extension's citext), whose operators are its own and stay as written. Only where `buildWhere` is told the types
183
+ * (`types`): an App's scoped reads.
184
+ */
185
+ builtin?(type: string): {
186
+ readonly name: string;
187
+ readonly text: boolean;
188
+ } | undefined;
189
+ /** A condition that holds for no row, said with no operator a search_path can shadow where the dialect has one. */
190
+ never?: string;
158
191
  }
159
192
  /** The periods a breakdown can group dates by: a calendar's (day to year), and the two that recur — the ISO
160
193
  weekday, "1" (Monday) to "7", and the hour of the day, "00" to "23" — which a heat map crosses. */
@@ -213,5 +246,10 @@ other?: (name: string) => string,
213
246
  /** How `has` is written for a column naming a record's tags, given the bound labels' placeholders; absent, `has` is refused. */
214
247
  membership?: (name: string, holes: readonly string[]) => string,
215
248
  /** How an `any` condition is written: an EXISTS over the child's rows, binding nothing of its own; absent, one is refused. */
216
- exists?: (rows: AnyRows) => string): SqlFragment;
249
+ exists?: (rows: AnyRows) => string,
250
+ /** Whether a condition may compare as a foreign key does (`Condition.equality`): a scoped write's own reads only. */
251
+ references?: boolean,
252
+ /** The catalog's type of a column the filter names, where the style names its operators by schema
253
+ * (SqlStyle.builtin): an App's scoped reads. Absent, or undefined for a name, the operator as written. */
254
+ types?: (name: string) => string | undefined): SqlFragment;
217
255
  export {};
@@ -4,7 +4,14 @@
4
4
  * it lives here rather than with the adapters that run the statements.
5
5
  */
6
6
  import { LIKE_ESCAPE, likePattern } from './like.js';
7
- import { Refusal } from './refusal.js';
7
+ import { RequestFault } from './refusal.js';
8
+ /* A type as the scope catalog names one (postgresScopeCatalog.ts sqlType): a chain of identifiers, each a word or
9
+ quoted, then at most a modifier of one or two integers and the brackets of an array — `pg_catalog."numeric"(10,2)`,
10
+ `"s"."my type"`, `pg_catalog."varchar"(3)[]`. Nothing else, so no text can end the cast and start an expression;
11
+ and an operator as `schema.=`. */
12
+ const IDENTIFIER = '(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)';
13
+ const SQL_TYPE = new RegExp(`^${IDENTIFIER}(?:\\.${IDENTIFIER})*(?:\\(\\d+(?:,-?\\d+)?\\))?(?:\\[\\])*$`);
14
+ const SQL_OPERATOR = /^(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)\.[+\-*<>=~!@#%^&|`?]{1,63}$/;
8
15
  /**
9
16
  * The operators, as a value rather than only as a type.
10
17
  *
@@ -98,7 +105,38 @@ export const POSTGRES_STYLE = {
98
105
  ? `CASE WHEN jsonb_typeof((${e})::jsonb -> '${key}') = 'number' THEN ((${e})::jsonb ->> '${key}')::numeric END`
99
106
  : `((${e})::jsonb ->> '${key}')`,
100
107
  jsonHas: (e, key, holes) => `(((${e})::jsonb -> '${key}') ?| ARRAY[${holes.join(', ')}]::text[])`,
108
+ /* information_schema's data_type, which says a domain by its base type: a varchar is read as text, as pg_catalog
109
+ compares it, and a char as bpchar, which keeps its trailing blanks insignificant without char(1)'s truncation. */
110
+ builtin: (type) => {
111
+ const name = POSTGRES_BUILTIN[type];
112
+ return name === undefined ? undefined : { name, text: name === 'text' || name === 'bpchar' };
113
+ },
114
+ never: 'FALSE',
101
115
  };
116
+ /* The types a comparison names pg_catalog's operator for, by information_schema's word for them, and the name an IN
117
+ list is cast to. Absent: USER-DEFINED (an enum, citext, an extension's type) and ARRAY. */
118
+ const POSTGRES_BUILTIN = Object.assign(Object.create(null), {
119
+ text: 'text',
120
+ 'character varying': 'text',
121
+ character: 'bpchar',
122
+ smallint: 'int2',
123
+ integer: 'int4',
124
+ bigint: 'int8',
125
+ numeric: 'numeric',
126
+ real: 'float4',
127
+ 'double precision': 'float8',
128
+ boolean: 'bool',
129
+ uuid: 'uuid',
130
+ date: 'date',
131
+ 'timestamp without time zone': 'timestamp',
132
+ 'timestamp with time zone': 'timestamptz',
133
+ 'time without time zone': 'time',
134
+ 'time with time zone': 'timetz',
135
+ interval: 'interval',
136
+ bytea: 'bytea',
137
+ jsonb: 'jsonb',
138
+ inet: 'inet',
139
+ });
102
140
  /**
103
141
  * Postgres 12 and later: row-scope CTEs stay inlined however often a read
104
142
  * joins their table. The adapter picks it once it knows the server's version
@@ -146,7 +184,7 @@ export function collate(expression, collation, style) {
146
184
  if (collation === undefined)
147
185
  return expression;
148
186
  if (collation !== 'binary' || !style.binaryText)
149
- throw new Refusal('This comparison cannot be made by bytes on this database.');
187
+ throw new RequestFault('This comparison cannot be made by bytes on this database.');
150
188
  return `${expression}${style.binaryText}`;
151
189
  }
152
190
  const COMPARISONS = new Set(['=', '!=', '>', '>=', '<', '<=']);
@@ -172,12 +210,29 @@ other,
172
210
  /** How `has` is written for a column naming a record's tags, given the bound labels' placeholders; absent, `has` is refused. */
173
211
  membership,
174
212
  /** How an `any` condition is written: an EXISTS over the child's rows, binding nothing of its own; absent, one is refused. */
175
- exists) {
213
+ exists,
214
+ /** Whether a condition may compare as a foreign key does (`Condition.equality`): a scoped write's own reads only. */
215
+ references = false,
216
+ /** The catalog's type of a column the filter names, where the style names its operators by schema
217
+ * (SqlStyle.builtin): an App's scoped reads. Absent, or undefined for a name, the operator as written. */
218
+ types) {
176
219
  if (!filter?.groups.length)
177
220
  return { text: '', params: [] };
178
221
  const params = [];
179
222
  let index = startIndex;
180
223
  const next = () => style.placeholder(index++);
224
+ const never = style.never ?? '1 = 0';
225
+ /* PostgreSQL's own operator for a built-in type, named so: a schema author's `=` on the search_path cannot decide
226
+ which rows a policy or a filter admits (SqlStyle.builtin). */
227
+ const builtin = (name) => {
228
+ const type = types?.(name);
229
+ return type === undefined ? undefined : style.builtin?.(type);
230
+ };
231
+ const operator = (op) => `OPERATOR(pg_catalog.${op === '!=' ? '<>' : op})`;
232
+ /* ILIKE … ESCAPE is `~~*` of like_escape, as the parser rewrites it; spelled so, the operator can be named. */
233
+ const pattern = (col, name) => style.likeOp === 'ILIKE' && builtin(name)?.text
234
+ ? `${col} ${operator('~~*')} pg_catalog.like_escape(${next()}, '${LIKE_ESCAPE}')`
235
+ : `${col} ${style.likeOp} ${next()} ESCAPE '${LIKE_ESCAPE}'`;
181
236
  /* A condition every group holds is said once, before the OR: the same
182
237
  rows (AND distributes over OR in SQL's three-valued logic too), and the
183
238
  shape an engine can read a range from. A keyset page's bound is in every
@@ -193,36 +248,53 @@ exists) {
193
248
  const compile = (group) => group
194
249
  .map((c) => {
195
250
  if (c.collation !== undefined && !COMPARISONS.has(c.op)) {
196
- throw new Refusal('Only a comparison can compare text by bytes.');
251
+ throw new RequestFault('Only a comparison can compare text by bytes.');
197
252
  }
198
253
  /* Before the column is written: child rows are no column of this row. Their
199
254
  values are bound where their relation is planned (rowScope.ts `filtered`),
200
255
  so the EXISTS carries no parameter here and the numbering is untouched. */
201
256
  if (c.any !== undefined) {
202
257
  if (!exists || typeof c.any !== 'object' || c.any === null)
203
- throw new Refusal('This read cannot ask about the rows that point at it.');
258
+ throw new RequestFault('This read cannot ask about the rows that point at it.');
204
259
  /* `no task …` is the same rows asked the other way: none of them matches. */
205
260
  return c.op === 'isNull' ? `NOT ${exists(c.any)}` : exists(c.any);
206
261
  }
207
262
  /* Before the column is written: a record's tags are no column. */
208
263
  if (c.op === 'has') {
209
264
  if (!membership || c.other !== undefined)
210
- throw new Refusal("This read cannot ask a record's tags.");
265
+ throw new RequestFault("This read cannot ask a record's tags.");
211
266
  const labels = (Array.isArray(c.value) ? c.value : [c.value]).filter((v) => typeof v === 'string' || typeof v === 'number');
212
267
  if (!labels.length)
213
- return '1 = 0';
268
+ return never;
214
269
  const holes = labels.map((v) => {
215
270
  params.push(String(v));
216
271
  return next();
217
272
  });
218
273
  return membership(c.column, holes);
219
274
  }
275
+ if (c.equality !== undefined) {
276
+ const { operator, type, left, right } = (c.equality ?? {});
277
+ if (!references ||
278
+ c.op !== '=' ||
279
+ c.collation !== undefined ||
280
+ (c.other !== undefined && (!other || typeof c.other !== 'string')) ||
281
+ typeof operator !== 'string' ||
282
+ !SQL_OPERATOR.test(operator) ||
283
+ ![type, left, right].every((part, at) => (at > 0 && part === undefined) || (typeof part === 'string' && SQL_TYPE.test(part))))
284
+ throw new RequestFault('This read cannot compare as a foreign key does.');
285
+ /* A reference column on the right, as ri_triggers.c joins a key to its references: of its own type already. */
286
+ if (c.other !== undefined)
287
+ return `${column(c.column, c)}${left ? `::${left}` : ''} OPERATOR(${operator}) ${other(c.other)}${right ? `::${right}` : ''}`;
288
+ params.push(c.value ?? null);
289
+ return `${column(c.column, c)}${left ? `::${left}` : ''} OPERATOR(${operator}) ${next()}::${type}${right ? `::${right}` : ''}`;
290
+ }
220
291
  const col = collate(column(c.column, c), c.collation, style);
221
292
  if (c.other !== undefined) {
222
293
  if (!other || typeof c.other !== 'string' || !COMPARISONS.has(c.op)) {
223
- throw new Refusal('This read cannot compare two columns.');
294
+ throw new RequestFault('This read cannot compare two columns.');
224
295
  }
225
- return `${col} ${c.op} ${collate(other(c.other), c.collation, style)}`;
296
+ const op = builtin(c.column) && builtin(c.other) ? operator(c.op) : c.op;
297
+ return `${col} ${op} ${collate(other(c.other), c.collation, style)}`;
226
298
  }
227
299
  switch (c.op) {
228
300
  case 'isNull':
@@ -232,11 +304,15 @@ exists) {
232
304
  case 'in': {
233
305
  const list = Array.isArray(c.value) ? c.value : [c.value];
234
306
  if (!list.length)
235
- return '1 = 0'; // an empty IN matches nothing
307
+ return never; // an empty IN matches nothing
236
308
  const holes = list.map((v) => {
237
309
  params.push(v ?? null);
238
310
  return next();
239
311
  });
312
+ /* IN has no operator to name: the same rows as `= ANY` of the list read as the column's type. */
313
+ const typed = builtin(c.column);
314
+ if (typed)
315
+ return `${col} ${operator('=')} ANY (ARRAY[${holes.join(', ')}]::pg_catalog.${typed.name}[])`;
240
316
  return `${col} IN (${holes.join(', ')})`;
241
317
  }
242
318
  /* All three go through one pattern builder, which escapes the
@@ -246,7 +322,7 @@ exists) {
246
322
  case 'startsWith':
247
323
  case 'endsWith':
248
324
  params.push(likePattern(c.value, c.op));
249
- return `${col} ${style.likeOp} ${next()} ESCAPE '${LIKE_ESCAPE}'`;
325
+ return pattern(col, c.column);
250
326
  /* Bound, not escaped: the wildcards belong to whoever typed them.
251
327
  Still a parameter — the value never becomes SQL text — so the
252
328
  safety argument is unchanged, and still `ESCAPE '#'`, so the
@@ -254,7 +330,7 @@ exists) {
254
330
  internally. */
255
331
  case 'like':
256
332
  params.push(String(c.value ?? ''));
257
- return `${col} ${style.likeOp} ${next()} ESCAPE '${LIKE_ESCAPE}'`;
333
+ return pattern(col, c.column);
258
334
  default: {
259
335
  /* The one field in a structured request that becomes SQL text
260
336
  rather than a bound parameter — and until now it was checked
@@ -267,10 +343,10 @@ exists) {
267
343
  Checked here rather than at each caller: one choke point
268
344
  covers the four endpoints and anything added later. */
269
345
  if (!OPS.has(c.op)) {
270
- throw new Refusal(`"${String(c.op)}" is not an operator this tool knows.`);
346
+ throw new RequestFault(`"${String(c.op)}" is not an operator this tool knows.`);
271
347
  }
272
348
  params.push(c.value ?? null);
273
- return `${col} ${c.op} ${next()}`;
349
+ return `${col} ${builtin(c.column) ? operator(c.op) : c.op} ${next()}`;
274
350
  }
275
351
  }
276
352
  })
@@ -293,7 +369,12 @@ exists) {
293
369
  function sameCondition(a, b) {
294
370
  if (a === b)
295
371
  return true;
296
- if (a.column !== b.column || a.op !== b.op || a.collation !== b.collation || a.other !== b.other || a.any !== b.any)
372
+ if (a.column !== b.column ||
373
+ a.op !== b.op ||
374
+ a.collation !== b.collation ||
375
+ a.other !== b.other ||
376
+ a.any !== b.any ||
377
+ a.equality !== b.equality)
297
378
  return false;
298
379
  if (Array.isArray(a.value) || Array.isArray(b.value)) {
299
380
  return (Array.isArray(a.value) &&
@@ -23,6 +23,8 @@ export interface AppListTab {
23
23
  slug?: string;
24
24
  /** The resource's segment the tab names (appSegments.ts): its `query` is that word, written out where it is read. */
25
25
  segment?: string;
26
+ /** What the tab says while nothing is under it and nothing narrows it past its own condition. */
27
+ empty?: AppListEmpty;
26
28
  }
27
29
  /**
28
30
  * Data only: the renderer supplies the list and detail nodes. One of the
@@ -1,6 +1,6 @@
1
1
  import { type DatabaseSchema } from './schema.js';
2
2
  import type { ServedResource } from './servedApp.js';
3
- import type { AppListPresentation } from './listPresentations.js';
3
+ import type { AppListEmpty, AppListPresentation } from './listPresentations.js';
4
4
  /** What a list's question is read over: the schema, and the App's resources — their record labels and display rules. */
5
5
  export interface ListRules {
6
6
  readonly schema: DatabaseSchema;
@@ -12,6 +12,8 @@ export interface ListTab {
12
12
  query?: string;
13
13
  /** Its word in an address where the label is said in another language (addressParams.ts `tabKey`). */
14
14
  slug?: string;
15
+ /** What it says while it holds no row and nothing narrows it past its own condition. */
16
+ empty?: AppListEmpty;
15
17
  }
16
18
  /** What of a list view its question is made from. */
17
19
  export interface ListQuestionSpec {
@@ -22,6 +22,15 @@ export declare function currencyDigits(currency: string): number;
22
22
  * then divides as a number.
23
23
  */
24
24
  export declare function minorToMajor(value: unknown, currency: string): string | undefined;
25
+ /**
26
+ * A stored amount in the major unit as its exact decimal text, to the
27
+ * currency's minor digits: 5917 → "5917.00", "-12.5" → "-12.50", 1500 in JPY
28
+ * → "1500". Padded, never rounded: a figure with more places than its
29
+ * currency keeps them, as stored. A decimal string is read by its digits, so
30
+ * one past 2^53 is not the double Number() makes of it. Undefined for no
31
+ * decimal at all.
32
+ */
33
+ export declare function majorText(value: unknown, currency: string): string | undefined;
25
34
  /**
26
35
  * A minor-unit value as the figure a money format draws: the exact major text
27
36
  * where it is a whole number of minor units, else the number divided (a
@@ -49,6 +49,23 @@ export function minorToMajor(value, currency) {
49
49
  const whole = m[2].padStart(digits + 1, '0');
50
50
  return (/[1-9]/.test(whole) ? m[1] : '') + (digits ? `${whole.slice(0, -digits)}.${whole.slice(-digits)}` : whole);
51
51
  }
52
+ /**
53
+ * A stored amount in the major unit as its exact decimal text, to the
54
+ * currency's minor digits: 5917 → "5917.00", "-12.5" → "-12.50", 1500 in JPY
55
+ * → "1500". Padded, never rounded: a figure with more places than its
56
+ * currency keeps them, as stored. A decimal string is read by its digits, so
57
+ * one past 2^53 is not the double Number() makes of it. Undefined for no
58
+ * decimal at all.
59
+ */
60
+ export function majorText(value, currency) {
61
+ const text = typeof value === 'number' ? (Number.isFinite(value) ? String(value) : '') : typeof value === 'string' ? value.trim() : '';
62
+ const m = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(text);
63
+ if (!m)
64
+ return undefined;
65
+ const places = (m[3] ?? '').padEnd(currencyDigits(currency), '0');
66
+ const figure = `${m[2]}${places ? `.${places}` : ''}`;
67
+ return (m[1] === '-' && /[1-9]/.test(figure) ? '-' : '') + figure;
68
+ }
52
69
  /**
53
70
  * A minor-unit value as the figure a money format draws: the exact major text
54
71
  * where it is a whole number of minor units, else the number divided (a
@@ -1,7 +1,10 @@
1
1
  /**
2
2
  * A major amount — a number, or decimal text with a point ("19.99", "-5",
3
- * ".5") — as the whole number of minor units it is, or undefined when it is
4
- * no amount or says more decimals than the currency has: 19.999 dollars is a
5
- * typo, not a value to round.
3
+ * ".5") — as the whole number of minor units it is, written out in digits
4
+ * ("1999"), or undefined when it is no amount or says more decimals than the
5
+ * currency has: 19.999 dollars is a typo, not a value to round. Text to text,
6
+ * never through a float, so an amount past 2^53 stays exact.
6
7
  */
8
+ export declare function majorToMinorText(major: number | string, currency: string): string | undefined;
9
+ /** The same amount as a number of minor units, or undefined past 2^53 too (use majorToMinorText there). */
7
10
  export declare function majorToMinor(major: number | string, currency: string): number | undefined;
@@ -7,11 +7,12 @@
7
7
  import { currencyDigits } from './money.js';
8
8
  /**
9
9
  * A major amount — a number, or decimal text with a point ("19.99", "-5",
10
- * ".5") — as the whole number of minor units it is, or undefined when it is
11
- * no amount or says more decimals than the currency has: 19.999 dollars is a
12
- * typo, not a value to round.
10
+ * ".5") — as the whole number of minor units it is, written out in digits
11
+ * ("1999"), or undefined when it is no amount or says more decimals than the
12
+ * currency has: 19.999 dollars is a typo, not a value to round. Text to text,
13
+ * never through a float, so an amount past 2^53 stays exact.
13
14
  */
14
- export function majorToMinor(major, currency) {
15
+ export function majorToMinorText(major, currency) {
15
16
  const text = typeof major === 'number' ? (Number.isFinite(major) ? String(major) : '') : major.trim();
16
17
  const m = /^([-+]?)(\d*)(?:\.(\d*))?$/.exec(text);
17
18
  if (!m || (!m[2] && !m[3]))
@@ -20,8 +21,14 @@ export function majorToMinor(major, currency) {
20
21
  const fraction = (m[3] ?? '').replace(/0+$/, '');
21
22
  if (fraction.length > digits)
22
23
  return undefined;
23
- const n = Number(`${m[2] || '0'}${fraction.padEnd(digits, '0')}`);
24
- if (!Number.isSafeInteger(n))
24
+ const whole = `${m[2]}${fraction.padEnd(digits, '0')}`.replace(/^0+(?=\d)/, '') || '0';
25
+ return m[1] === '-' && whole !== '0' ? `-${whole}` : whole;
26
+ }
27
+ /** The same amount as a number of minor units, or undefined past 2^53 too (use majorToMinorText there). */
28
+ export function majorToMinor(major, currency) {
29
+ const text = majorToMinorText(major, currency);
30
+ if (text === undefined)
25
31
  return undefined;
26
- return m[1] === '-' && n !== 0 ? -n : n;
32
+ const n = Number(text);
33
+ return Number.isSafeInteger(n) ? n : undefined;
27
34
  }
@@ -408,7 +408,7 @@ interface PageNote {
408
408
  /** `quiet`: small print, no mark. `callout`: a ground of its own. Absent: the plain note. */
409
409
  variant?: 'quiet' | 'callout';
410
410
  icon?: import('./appIcons.js').AppIconName;
411
- /** One of the App's list or dashboard views to open. An App page only. */
411
+ /** One of the App's rooms to open: a list, a dashboard or a signed-in form view. An App page only. */
412
412
  action?: import('./appLinks.js').AppLinkAction;
413
413
  width?: SectionWidth;
414
414
  offsetLeft?: SectionOffset;
@@ -29,7 +29,7 @@
29
29
  */
30
30
  import { type ColumnMeta, type DatabaseSchema, type ForeignKey, type TableMeta } from './schema.js';
31
31
  /** A block of the base record's own fields, or of a to-one reference's. */
32
- interface FieldSection {
32
+ export interface FieldSection {
33
33
  kind: 'fields';
34
34
  /** Shown above the block. Absent means no heading. */
35
35
  title?: string;