@skillstech/thunderlang 0.5.9 → 0.5.10

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/src/sql.mjs ADDED
@@ -0,0 +1,387 @@
1
+ // SQL in Thunder. Tables are Data (or Things, when they enforce rules), each column with its kind in words, its
2
+ // default, whether it is always set, and what it points to; CHECK and UNIQUE constraints are rules the database
3
+ // enforces (a No stops the row); CREATE TYPE … AS ENUM is a set of choices; views, functions, procedures, and
4
+ // triggers are steps a person can follow. Deterministic, browser-safe, no SQL engine: read by pattern, like every
5
+ // other language Thunder reads. Dialects: PostgreSQL first; MySQL, SQLite, and SQL Server syntax where it agrees.
6
+
7
+ const words = (s) => String(s).replace(/^["`[]|["`\]]$/g, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
8
+ const unquote = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/, '$1');
9
+ const bare = (name) => unquote(String(name).split('.').pop());
10
+ const singular = (w) => w.replace(/ies$/, 'y').replace(/(ss|sh|ch|x)es$/, '$1').replace(/([^s])s$/, '$1');
11
+ const article = (w) => (/^[aeiou]/i.test(w) ? `an ${w}` : `a ${w}`);
12
+
13
+ /** Line-start offsets once; line lookups are a binary search. */
14
+ function lineFinder(src) {
15
+ const starts = [0];
16
+ for (let i = src.indexOf('\n'); i >= 0; i = src.indexOf('\n', i + 1)) starts.push(i + 1);
17
+ return (idx) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= idx) lo = mid; else hi = mid - 1; } return lo + 1; };
18
+ }
19
+
20
+ /** Blank out comments and string contents (same length), so searches never match inside them. */
21
+ function mask(src) {
22
+ let out = '';
23
+ for (let i = 0; i < src.length; i++) {
24
+ const c = src[i];
25
+ if (c === '-' && src[i + 1] === '-') { const n = src.indexOf('\n', i); const end = n < 0 ? src.length : n; out += ' '.repeat(end - i); i = end - 1; continue; }
26
+ if (c === '/' && src[i + 1] === '*') { const n = src.indexOf('*/', i + 2); const end = n < 0 ? src.length : n + 2; out += src.slice(i, end).replace(/[^\n]/g, ' '); i = end - 1; continue; }
27
+ if (c === "'") { let j = i + 1; for (; j < src.length; j++) { if (src[j] === "'" && src[j + 1] === "'") { j++; continue; } if (src[j] === "'") break; } out += "'" + src.slice(i + 1, j).replace(/[^\n]/g, 'x') + (j < src.length ? "'" : ''); i = j; continue; }
28
+ out += c;
29
+ }
30
+ return out;
31
+ }
32
+
33
+ /** Index of the `)` closing the `(` at `open` in masked text. */
34
+ function parenEnd(m, open) {
35
+ for (let i = open, d = 0; i < m.length; i++) { if (m[i] === '(') d++; else if (m[i] === ')' && --d === 0) return i; }
36
+ return -1;
37
+ }
38
+
39
+ /** Split at top-level commas (masked text decides; the original text is returned). */
40
+ function splitTop(text, masked = mask(text)) {
41
+ const out = [];
42
+ let d = 0, start = 0;
43
+ for (let i = 0; i < masked.length; i++) {
44
+ if (masked[i] === '(') d++;
45
+ else if (masked[i] === ')') d--;
46
+ else if (masked[i] === ',' && d === 0) { out.push({ text: text.slice(start, i), at: start }); start = i + 1; }
47
+ }
48
+ out.push({ text: text.slice(start), at: start });
49
+ return out.filter((p) => p.text.trim());
50
+ }
51
+
52
+ /** The `--` comment lines (or one block comment) right above a position: the author's note. */
53
+ function docAbove(src, idx) {
54
+ const lines = src.slice(0, idx).split('\n');
55
+ lines.pop(); // the text before the statement on its own line
56
+ const run = [];
57
+ for (let k = lines.length - 1; k >= 0 && /^\s*--/.test(lines[k]); k--) run.unshift(lines[k].replace(/^\s*--+\s?/, '').trim());
58
+ const text = run.filter(Boolean).join(' ');
59
+ return text || null;
60
+ }
61
+
62
+ const TYPE_WORDS = [
63
+ [/^(small|big)?serial\b|^serial\d/i, 'a number, given automatically'],
64
+ [/^(int|integer|smallint|bigint|tinyint|mediumint|numeric|decimal|real|float|double|money|number)\b|^int\d/i, 'a number'],
65
+ [/^(text|varchar|char|character|nvarchar|nchar|citext|string|clob)\b/i, 'words'],
66
+ [/^(bool|boolean|bit)\b/i, 'yes or no'],
67
+ [/^(date|time|timestamp|timestamptz|datetime|datetime2|interval)\b/i, 'a date'],
68
+ [/^uuid\b|^uniqueidentifier\b/i, 'an id'],
69
+ [/^jsonb?\b/i, 'structured data'],
70
+ [/^(bytea|blob|binary|varbinary)\b/i, 'a file or bytes'],
71
+ ];
72
+ const typeWords = (t) => { for (const [re, w] of TYPE_WORDS) if (re.test(String(t).trim())) return w; return /\[\]$/.test(String(t).trim()) ? 'a list' : null; };
73
+
74
+ /** A default value in words, as other languages say a starting value. */
75
+ function defaultWords(v) {
76
+ const e = String(v).trim().replace(/::\w+(\[\])?$/, '');
77
+ if (/^null$/i.test(e)) return 'nothing at first';
78
+ if (/^(true|false)$/i.test(e)) return `${/^true$/i.test(e) ? 'yes' : 'no'} at first`;
79
+ if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
80
+ if (/^'.*'$/s.test(e)) return `"${e.slice(1, -1).replace(/''/g, "'")}" at first`;
81
+ if (/^(now\(\)|current_timestamp|current_date|getdate\(\)|sysdate|localtimestamp|transaction_timestamp\(\))$/i.test(e)) return 'the moment it is saved';
82
+ if (/gen_random_uuid|uuid_generate|newid\(\)/i.test(e)) return 'a new id';
83
+ return 'worked out when it is saved';
84
+ }
85
+
86
+ /** A SQL condition as Thunder words: total >= 0 AND status IN ('a','b') -> "total is at least 0 and status is one of a, b". */
87
+ export function sqlCondition(cond, { aliases = {}, vars = false } = {}) {
88
+ let c = String(cond).trim().replace(/\s+/g, ' ');
89
+ while (/^\(.*\)$/.test(c) && parenEnd(mask(c), 0) === c.length - 1) c = c.slice(1, -1).trim();
90
+ // Strings first, in Thunder's quotes, so a possessive apostrophe is never mistaken for one.
91
+ c = c.replace(/'((?:[^']|'')*)'/g, (m, v) => `"${v.replace(/''/g, "'")}"`);
92
+ const plain = (x) => words(vars ? String(x).replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, '') : x);
93
+ const name = (x) => { const p = String(x).split('.'); if (p.length < 2) return plain(x); const table = aliases[p[0].toLowerCase()] ?? p[0]; return `the ${singular(words(table))}'s ${words(p[1])}`; };
94
+ return c
95
+ .replace(/\b(NEW|OLD)\.(\w+)/g, (m, which, col) => `the ${which === 'NEW' ? 'new' : 'old'} ${words(col)}`)
96
+ .replace(/([\w."]+)\s+NOT\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => `${name(a)} is not one of ${l.split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).join(', ')}`)
97
+ .replace(/([\w."]+)\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => (/^\s*select\b/i.test(l) ? `${name(a)} is in the results of a query` : `${name(a)} is one of ${l.split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).join(', ')}`))
98
+ .replace(/([\w."]+)\s+IS\s+NOT\s+NULL/gi, (m, a) => `${name(a)} is set`)
99
+ .replace(/([\w."]+)\s+IS\s+NULL/gi, (m, a) => `${name(a)} is empty`)
100
+ .replace(/([\w.]+)\s+NOT\s+LIKE\s+"([^"]*)"/gi, (m, a, p) => `${name(a)} does not match "${p.replace(/%/g, '…')}"`)
101
+ .replace(/([\w.]+)\s+I?LIKE\s+"([^"]*)"/gi, (m, a, p) => (/^[^%]+%$/.test(p) ? `${name(a)} starts with "${p.slice(0, -1)}"` : /^%[^%]+%$/.test(p) ? `${name(a)} contains "${p.slice(1, -1)}"` : `${name(a)} matches "${p.replace(/%/g, '…')}"`))
102
+ .replace(/([\w."]+)\s+BETWEEN\s+(\S+)\s+AND\s+(\S+)/gi, (m, a, lo, hi) => `${name(a)} is from ${lo} to ${hi}`)
103
+ .replace(/\s*(<>|!=)\s*/g, ' is not ').replace(/\s*>=\s*/g, ' is at least ').replace(/\s*<=\s*/g, ' is at most ')
104
+ .replace(/\s*>\s*/g, ' is more than ').replace(/\s*<\s*/g, ' is less than ').replace(/\s*=\s*/g, ' is ')
105
+ .replace(/\bAND\b/gi, 'and').replace(/\bOR\b/gi, 'or').replace(/\bNOT\s+/gi, 'not ')
106
+ .replace(/\b(?:length|char_length)\s*\(\s*([\w."]+)\s*\)/gi, (m, a) => `the length of ${name(a)}`)
107
+ .replace(/\b(?!is\b|and\b|or\b|not\b|at\b|least\b|most\b|more\b|less\b|than\b|one\b|of\b|the\b|set\b|empty\b|from\b|to\b|new\b|old\b|starts\b|with\b|contains\b|does\b|match\b|matches\b|in\b|results\b|a\b|query\b|length\b|s\b)([a-z_][\w]*\.)?([a-z_][\w]*)\b(?![^"]*"(?:[^"]*"[^"]*")*[^"]*$)/gi, (m, t, col) => (t ? name(`${t}${col}`) : /^[A-Z_]+$/.test(col) && col.length > 1 ? m : plain(col)))
108
+ .replace(/\s+/g, ' ').trim();
109
+ }
110
+
111
+ // ── Tables, types: Things, Data, and Choices ─────────────────────────────────────────────────────────────
112
+
113
+ /** Tables, enums, and the rules (CHECK, UNIQUE) each table enforces, with their lines. */
114
+ function readSchema(src) {
115
+ const m = mask(src);
116
+ const lineAt = lineFinder(src);
117
+ const tables = [], choices = [], rules = [];
118
+ const docs = new Map();
119
+ for (const c of src.matchAll(/COMMENT\s+ON\s+TABLE\s+([\w."]+)\s+IS\s+'((?:[^']|'')*)'/gi)) docs.set(bare(c[1]).toLowerCase(), c[2].replace(/''/g, "'"));
120
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."[\]`]+)\s*\(/gi)) {
121
+ const open = t.index + t[0].length - 1;
122
+ const close = parenEnd(m, open);
123
+ if (close < 0) continue;
124
+ const name = bare(src.slice(t.index, open).match(/([\w."[\]`]+)\s*$/)[1]);
125
+ const table = { name, lines: [lineAt(t.index), lineAt(close)], doc: docs.get(name.toLowerCase()) ?? docAbove(src, t.index), columns: [], checks: [], uniques: [], refs: [] };
126
+ for (const part of splitTop(src.slice(open + 1, close), m.slice(open + 1, close))) {
127
+ const text = part.text.trim().replace(/\s+/g, ' ');
128
+ const line = lineAt(open + 1 + part.at + (part.text.length - part.text.trimStart().length));
129
+ let x;
130
+ if ((x = text.match(/^(?:CONSTRAINT\s+([\w"]+)\s+)?CHECK\s*\((.*)\)$/i))) { table.checks.push({ name: x[1] && unquote(x[1]), cond: x[2], line }); continue; }
131
+ if ((x = text.match(/^(?:CONSTRAINT\s+([\w"`]+)\s+)?UNIQUE(?:\s+(?:KEY|INDEX))?(?:\s+([\w"`]+))?\s*\(([^)]*)\)/i))) { table.uniques.push({ name: (x[1] || x[2]) && unquote(x[1] || x[2]), cols: x[3].split(',').map((c) => unquote(c.trim())), line }); continue; }
132
+ if ((x = text.match(/^(?:CONSTRAINT\s+[\w"]+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s+REFERENCES\s+([\w."]+)/i))) { for (const c of x[1].split(',')) table.refs.push({ col: unquote(c.trim()), to: bare(x[2]) }); continue; }
133
+ if (/^(?:CONSTRAINT\s+[\w"]+\s+)?(PRIMARY\s+KEY|INDEX|KEY|EXCLUDE)\b/i.test(text)) continue;
134
+ const col = text.match(/^([\w"`[\]]+)\s+([\w]+(?:\s*\([^)]*\))?(?:\s+(?:varying|precision|with(?:out)?\s+time\s+zone))*(?:\[\])?)(.*)$/i);
135
+ if (!col || /^(LIKE|PERIOD)$/i.test(col[1])) continue;
136
+ const rest = col[3] || '';
137
+ const ref = rest.match(/\bREFERENCES\s+([\w."]+)/i);
138
+ const def = rest.match(/\bDEFAULT\s+('(?:[^']|'')*'|\([^)]*\)|[\w.:]+(?:\(\))?)/i);
139
+ const column = { name: unquote(col[1]), type: col[2], line, primary: /\bPRIMARY\s+KEY\b/i.test(rest), notNull: /\bNOT\s+NULL\b/i.test(rest), ...(def ? { default: def[1] } : {}), ...(ref ? { ref: bare(ref[1]) } : {}) };
140
+ table.columns.push(column);
141
+ const check = rest.match(/\bCHECK\s*\((.*)\)/i);
142
+ if (check) table.checks.push({ cond: check[1], line });
143
+ if (/\bUNIQUE\b/i.test(rest)) table.uniques.push({ cols: [column.name], line });
144
+ }
145
+ tables.push(table);
146
+ }
147
+ for (const e of m.matchAll(/\bCREATE\s+TYPE\s+([\w."]+)\s+AS\s+ENUM\s*\(/gi)) {
148
+ const open = e.index + e[0].length - 1;
149
+ const close = parenEnd(m, open);
150
+ if (close < 0) continue;
151
+ const values = [...src.slice(open + 1, close).matchAll(/'((?:[^']|'')*)'/g)].map((v) => v[1].replace(/''/g, "'").replace(/_/g, ' '));
152
+ choices.push({ name: bare(e[1]), lines: [lineAt(e.index), lineAt(close)], doc: docAbove(src, e.index), values });
153
+ }
154
+ for (const t of tables) {
155
+ for (const c of t.checks) rules.push({ table: t.name, kind: 'check', ...c });
156
+ for (const u of t.uniques) rules.push({ table: t.name, kind: 'unique', ...u });
157
+ }
158
+ return { tables, choices, rules };
159
+ }
160
+
161
+ /** Things, Data, and Choices from a SQL file, in the same shape as the other languages' readers. */
162
+ export function sqlThings(src, file) {
163
+ const { tables, choices } = readSchema(src);
164
+ const enums = new Set(choices.map((c) => c.name.toLowerCase()));
165
+ const out = [];
166
+ for (const t of tables) {
167
+ const refs = new Map(t.refs.map((r) => [r.col, r.to]));
168
+ const knows = t.columns.map((c) => {
169
+ const to = c.ref ?? refs.get(c.name);
170
+ const kind = to ? `${article(singular(words(to)))} (by its id)` : c.primary ? `${typeWords(c.type) ?? 'a value'}, the id` : enums.has(bare(c.type).toLowerCase()) ? article(words(bare(c.type))) : typeWords(c.type);
171
+ return { name: c.name, label: words(c.name), kind: kind && c.notNull && !c.primary ? `${kind}, always set` : kind, start: c.default != null ? defaultWords(c.default) : null, line: c.line };
172
+ });
173
+ out.push({ kind: t.checks.length || t.uniques.length ? 'thing' : 'record', name: t.name, file, lines: t.lines, ...(t.doc ? { doc: t.doc } : {}), knows, choices: [] });
174
+ }
175
+ for (const c of choices) out.push({ kind: 'choices', name: c.name, file, lines: c.lines, ...(c.doc ? { doc: c.doc } : {}), knows: [], choices: c.values });
176
+ return out;
177
+ }
178
+
179
+ // ── Queries, views, functions, procedures, triggers: steps ───────────────────────────────────────────────
180
+
181
+ const colWords = (expr) => {
182
+ const e = expr.trim();
183
+ const as = e.match(/\s+(?:AS\s+)?([\w"]+)$/i);
184
+ if (as && !/^(DESC|ASC|END)$/i.test(as[1]) && /[\s)]/.test(e.slice(0, as.index + 1))) return words(unquote(as[1]));
185
+ const agg = e.match(/^(count|sum|avg|min|max)\s*\(\s*(distinct\s+)?([^)]*)\)$/i);
186
+ if (agg) { const what = agg[3].trim() === '*' ? 'rows' : words(bare(agg[3])); return { count: `how many ${what === 'rows' ? 'rows' : what}`, sum: `the total of ${what}`, avg: `the average ${what}`, min: `the lowest ${what}`, max: `the highest ${what}` }[agg[1].toLowerCase()]; }
187
+ if (e === '*') return 'every column';
188
+ if (/^\w+\.\*$/.test(e)) return `every column of ${words(e.split('.')[0])}`;
189
+ return /^[\w."]+$/.test(e) ? words(bare(e)) : 'a worked-out value';
190
+ };
191
+ const listWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} and ${xs.at(-1)}`);
192
+
193
+ /** The steps of one SELECT: finds, joins, keeps only, groups, sorts, takes, gives back. */
194
+ function selectSteps(sql, line, { give = true, vars = false } = {}) {
195
+ const s = sql.replace(/\s+/g, ' ').trim().replace(/;$/, '');
196
+ const m = mask(s);
197
+ const at = (kw) => { const r = new RegExp(`\\b${kw}\\b`, 'i').exec(m); return r ? r.index : -1; };
198
+ const clauses = ['SELECT', 'FROM', 'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT', 'OFFSET', 'INTO'].map((k) => [k, at(k)]).filter(([, i]) => i >= 0).sort((a, b) => a[1] - b[1]);
199
+ const part = (k) => { const i = clauses.findIndex(([n]) => n === k); if (i < 0) return null; const start = clauses[i][1] + k.length; const end = clauses[i + 1]?.[1] ?? s.length; return s.slice(start, end).trim(); };
200
+ const steps = [];
201
+ const code = s;
202
+ const from = part('FROM');
203
+ // Table aliases (orders o, customers AS c) read as their table: o.status -> "the order's status".
204
+ const aliases = {};
205
+ for (const a of (from || '').matchAll(/([\w."]+)\s+(?:AS\s+)?([a-z_]\w*)\b(?=\s*(?:,|$|\bON\b|\bJOIN\b|\bLEFT\b|\bRIGHT\b|\bINNER\b|\bFULL\b|\bCROSS\b|\bWHERE\b))/gi)) {
206
+ if (!/^(ON|JOIN|LEFT|RIGHT|INNER|FULL|CROSS|OUTER|WHERE|AS)$/i.test(a[2])) aliases[a[2].toLowerCase()] = bare(a[1]);
207
+ }
208
+ const cond = (text) => sqlCondition(text, { aliases, vars });
209
+ if (from) {
210
+ const [first, ...joins] = from.split(/\b(?:(?:LEFT|RIGHT|INNER|FULL|CROSS)\s+(?:OUTER\s+)?)?JOIN\b/i);
211
+ const base = bare(first.trim().split(/\s+/)[0]);
212
+ steps.push({ kind: 'call', callee: 'find', says: `Finds the ${words(base)}`, code, line });
213
+ for (const j of joins) {
214
+ const jt = bare(j.trim().split(/\s+/)[0]);
215
+ const left = /\bLEFT\b/i.test(from.slice(0, from.indexOf(j)).slice(-20));
216
+ steps.push({ kind: 'call', callee: 'find', says: `${left ? 'Adds, when there is one,' : 'Adds'} the matching ${words(singular(jt))} to each`, code, line });
217
+ }
218
+ }
219
+ const where = part('WHERE');
220
+ if (where) steps.push({ kind: 'call', callee: 'filter', says: `Keeps only those where ${cond(where)}`, code, line });
221
+ const group = part('GROUP BY');
222
+ if (group) steps.push({ kind: 'set', says: `Groups them by ${listWords(splitTop(group).map((p) => words(bare(p.text.trim()))))}`, code, line });
223
+ const having = part('HAVING');
224
+ if (having) steps.push({ kind: 'call', callee: 'filter', says: `Keeps only groups where ${cond(having.replace(/\b(count|sum|avg|min|max)\s*\(([^)]*)\)/gi, (x) => colWords(x).replace(/ /g, '_')))}`.replace(/_/g, ' '), code, line });
225
+ const order = part('ORDER BY');
226
+ if (order) steps.push({ kind: 'set', says: `Sorts them by ${listWords(splitTop(order).map((p) => { const t = p.text.trim(); return `${colWords(t.replace(/\s+(ASC|DESC)(\s+NULLS\s+(FIRST|LAST))?$/i, ''))}${/\bDESC\b/i.test(t) ? ', highest first' : ''}`; }))}`, code, line });
227
+ const limit = part('LIMIT');
228
+ if (limit && /^\d+/.test(limit)) steps.push({ kind: 'set', says: `Takes the first ${limit.match(/^\d+/)[0]}`, code, line });
229
+ const cols = part('SELECT');
230
+ if (give && cols) {
231
+ const names = splitTop(cols.replace(/^DISTINCT\s+/i, '')).map((p) => colWords(p.text));
232
+ steps.push({ kind: 'return', says: `Returns ${listWords(names.length > 8 ? [...names.slice(0, 7), 'more'] : names)}`, code, line });
233
+ }
234
+ return steps;
235
+ }
236
+
237
+ /** One statement in a function or procedure body, read as a step. */
238
+ function bodyStatement(text, line) {
239
+ const cnd = (x) => sqlCondition(x, { vars: true });
240
+ const v = (x) => words(String(x).replace(/^(?:p|v|l|var)_(?=\w)/i, ''));
241
+ const t = text.replace(/\s+/g, ' ').trim().replace(/;$/, '');
242
+ const code = t;
243
+ let x;
244
+ if ((x = t.match(/^RAISE\s+(?:EXCEPTION|ERROR)\s+'((?:[^']|'')*)'/i))) { const msg = x[1].replace(/''/g, "'").replace(/%/g, '…'); return { kind: 'fail', says: `Fails with an error: "${msg}"`, error: 'an error', message: msg, code, line }; }
245
+ if ((x = t.match(/^(?:RAISERROR|THROW)\s*\(?\s*(?:\d+\s*,\s*)?N?'((?:[^']|'')*)'/i)) || (x = t.match(/^SIGNAL\s+SQLSTATE\s+'\w+'\s+SET\s+MESSAGE_TEXT\s*=\s*'((?:[^']|'')*)'/i))) return { kind: 'fail', says: `Fails with an error: "${x[1].replace(/''/g, "'")}"`, error: 'an error', message: x[1].replace(/''/g, "'"), code, line };
246
+ if ((x = t.match(/^RETURN\s+QUERY\s+(SELECT\b.*)$/i))) return { kind: 'return', says: selectSteps(x[1], line).at(-1)?.says ?? 'Returns the rows a query finds', code, line, query: selectSteps(x[1], line, { give: false }) };
247
+ if ((x = t.match(/^RETURN\s+(NEW|OLD)$/i))) return { kind: 'return', says: x[1].toUpperCase() === 'NEW' ? 'Lets the change go ahead' : 'Keeps the old row', code, line };
248
+ if ((x = t.match(/^RETURN\s*(.*)$/i))) return { kind: 'return', says: x[1] ? (/^'(.*)'$/.test(x[1]) ? `Returns "${x[1].slice(1, -1)}"` : /^(true|false)$/i.test(x[1]) ? `Returns ${x[1].toLowerCase() === 'true' ? 'yes' : 'no'}` : `Returns ${cnd(x[1])}`) : 'Stops here', code, line };
249
+ if ((x = t.match(/^INSERT\s+INTO\s+([\w."]+)(?:\s*\(([^)]*)\))?/i))) return { kind: 'call', says: `Records a new ${singular(words(bare(x[1])))}${x[2] ? ` with ${listWords(x[2].split(',').map((c) => words(c.trim())))}` : ''}`, code, line };
250
+ if ((x = t.match(/^UPDATE\s+([\w."]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/i))) {
251
+ const sets = splitTop(x[2]).map((p) => { const kv = p.text.match(/^\s*([\w."]+)\s*=\s*(.*)$/s); return kv ? `${words(bare(kv[1]))} to ${/^'.*'$/.test(kv[2].trim()) ? `"${kv[2].trim().slice(1, -1)}"` : cnd(kv[2])}` : null; }).filter(Boolean);
252
+ return { kind: 'call', says: `Records the change in ${words(bare(x[1]))}: sets ${listWords(sets)}${x[3] ? ` where ${cnd(x[3])}` : ''}`, code, line };
253
+ }
254
+ if ((x = t.match(/^DELETE\s+FROM\s+([\w."]+)(?:\s+WHERE\s+(.*))?$/i))) return { kind: 'call', says: `Removes ${words(bare(x[1]))}${x[2] ? ` where ${cnd(x[2])}` : ''}`, code, line };
255
+ if ((x = t.match(/^SELECT\s+(.*?)\s+INTO\s+(?:STRICT\s+)?([\w,\s]+?)\s+FROM\s+(.*)$/i))) {
256
+ const from = x[3].match(/^([\w."]+)(?:\s+(?:AS\s+)?\w+)?(?:\s+WHERE\s+(.*))?$/i);
257
+ const what = listWords(x[2].split(',').map((n) => v(n.trim())));
258
+ if (from) return { kind: 'call', callee: 'find', says: `Finds ${what} in the ${words(bare(from[1]))}${from[2] ? ` where ${cnd(from[2])}` : ''}`, code, line };
259
+ const found = selectSteps(`SELECT ${x[1]} FROM ${x[3]}`, line, { give: false, vars: true });
260
+ return { kind: 'call', callee: 'find', says: `Finds ${what}: ${found.map((f) => f.says.charAt(0).toLowerCase() + f.says.slice(1)).join(', ')}`, code, line };
261
+ }
262
+ if ((x = t.match(/^(?:PERFORM|CALL|EXEC(?:UTE)?)\s+([\w.]+)\s*\(/i))) return { kind: 'call', says: `Runs ${words(bare(x[1]))}`, code, line };
263
+ if ((x = t.match(/^(?:SET\s+)?@?([\w.]+)\s*:?=\s*(.+)$/i))) return { kind: 'set', says: `Sets ${v(bare(x[1]))} to ${/^'.*'$/.test(x[2].trim()) ? `"${x[2].trim().slice(1, -1)}"` : cnd(x[2])}`, code, line };
264
+ return { kind: 'other', says: code, code, line, restates: code };
265
+ }
266
+
267
+ /**
268
+ * The steps of a procedural body (PL/pgSQL and friends): IF/ELSIF/ELSE/END IF become branches with their other
269
+ * side, everything else one step per statement.
270
+ */
271
+ function procSteps(body, firstLine) {
272
+ const m = mask(body);
273
+ const stmts = [];
274
+ let start = 0;
275
+ // Split at semicolons and around THEN/ELSE/ELSIF/END IF/LOOP keywords so IF headers stand alone.
276
+ const re = /;|\bTHEN\b|\bELSE\b(?!\s*IF)|\bELSIF\b|\bELSEIF\b|\bEND\s+IF\b|\bBEGIN\b|\bEND\b(?!\s+IF)/gi;
277
+ const lineAt = lineFinder(body);
278
+ let r;
279
+ while ((r = re.exec(m))) {
280
+ const kw = r[0].toUpperCase().replace(/\s+/g, ' ');
281
+ if (kw === ';') { const text = body.slice(start, r.index).trim(); if (text) stmts.push({ text, line: firstLine + lineAt(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1 }); start = r.index + 1; continue; }
282
+ if (kw === 'THEN') { stmts.push({ text: body.slice(start, r.index).trim(), line: firstLine + lineAt(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1, then: true }); start = r.index + r[0].length; continue; }
283
+ const before = body.slice(start, r.index).trim();
284
+ if (before) stmts.push({ text: before, line: firstLine + lineAt(start) - 1 });
285
+ stmts.push({ keyword: kw === 'ELSEIF' ? 'ELSIF' : kw });
286
+ start = r.index + r[0].length;
287
+ }
288
+ const tail = body.slice(start).trim();
289
+ if (tail) stmts.push({ text: tail, line: firstLine + lineAt(start) - 1 });
290
+ let i = 0;
291
+ const block = (stop) => {
292
+ const out = [];
293
+ while (i < stmts.length) {
294
+ const s = stmts[i];
295
+ if (s.keyword && stop.includes(s.keyword)) return out;
296
+ i++;
297
+ if (s.keyword === 'BEGIN' || s.keyword === 'END') continue;
298
+ if (s.then && /^(IF|ELSIF)\b/i.test(s.text)) {
299
+ const cond = s.text.replace(/^(IF|ELSIF)\s+/i, '');
300
+ const step = { kind: 'branch', says: `If ${sqlCondition(cond, { vars: true })}`, code: s.text, line: s.line, children: block(['ELSIF', 'ELSE', 'END IF']) };
301
+ let tail = step;
302
+ while (stmts[i]?.keyword === 'ELSIF') {
303
+ i++;
304
+ const h = stmts[i++];
305
+ const next = { kind: 'branch', says: `If ${sqlCondition(h.text.replace(/^ELSIF\s+/i, ''), { vars: true })}`, code: h.text, line: h.line, children: block(['ELSIF', 'ELSE', 'END IF']) };
306
+ tail.otherwise = [next]; tail = next;
307
+ }
308
+ if (stmts[i]?.keyword === 'ELSE') { i++; tail.otherwise = block(['END IF']); }
309
+ if (stmts[i]?.keyword === 'END IF') i++;
310
+ out.push(step);
311
+ continue;
312
+ }
313
+ if (s.text && !/^(DECLARE|LANGUAGE|AS)\b/i.test(s.text) && !/^\w+\s+[\w(),]+(\s*:=.*)?$/.test(s.text) || /:=/.test(s.text ?? '')) {
314
+ if (s.text && !/^DECLARE\b/i.test(s.text)) out.push(bodyStatement(s.text.replace(/^DECLARE\s+/i, ''), s.line));
315
+ }
316
+ }
317
+ return out;
318
+ };
319
+ return block([]);
320
+ }
321
+
322
+ /** Functions, procedures, views, triggers, and CHECK/UNIQUE rules as reading items (kind 'function'). */
323
+ export function sqlItems(src) {
324
+ const m = mask(src);
325
+ const lineAt = lineFinder(src);
326
+ const items = [];
327
+ const push = (name, line, steps, extra = {}) => {
328
+ const code = steps.filter((s) => s.kind === 'other').length;
329
+ items.push({ id: `${name}:${line}`, name, label: words(name).charAt(0).toUpperCase() + words(name).slice(1), line, inputs: extra.inputs ?? [], returns: extra.returns ?? null,
330
+ ...(extra.doc ? { doc: extra.doc } : {}), provenance: 'inferred-from-code', kind: 'function', status: 'signature-only', steps, stepsMore: 0,
331
+ stepsReadable: steps.length ? Math.round(((steps.length - code) / steps.length) * 100) / 100 : 0,
332
+ says: extra.says ?? `${words(name)} has ${steps.length} step${steps.length === 1 ? '' : 's'}.`, headline: extra.headline ?? `${words(name)}.`, guards: [], unread: [] });
333
+ };
334
+ // Views: the query, as steps.
335
+ for (const v of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."]+)(?:\s*\([^)]*\))?\s+AS\s+/gi)) {
336
+ const end = m.indexOf(';', v.index);
337
+ const query = src.slice(v.index + v[0].length, end < 0 ? src.length : end);
338
+ const name = bare(v[1]);
339
+ push(name, lineAt(v.index), selectSteps(query, lineAt(v.index + v[0].length)), { doc: docAbove(src, v.index), says: `${words(name)} is a saved query.`, headline: `${words(name)}: a saved query.` });
340
+ }
341
+ // Functions and procedures: their parameters and body.
342
+ for (const f of m.matchAll(/\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?(?:DEFINER\s*=\s*\S+\s+)?(FUNCTION|PROCEDURE|PROC)\s+([\w."[\]]+)\s*\(/gi)) {
343
+ const open = f.index + f[0].length - 1;
344
+ const close = parenEnd(m, open);
345
+ if (close < 0) continue;
346
+ const name = bare(f[2]);
347
+ const inputs = splitTop(src.slice(open + 1, close)).map((p) => {
348
+ const pm = p.text.trim().match(/^(?:IN\s+|OUT\s+|INOUT\s+)?@?([\w"]+)\s+(.+?)(?:\s+(?:DEFAULT|=)\s+.+)?$/i);
349
+ return pm ? { name: unquote(pm[1]).replace(/^p_|^_/, ''), type: pm[2].trim() } : null;
350
+ }).filter(Boolean);
351
+ const after = src.slice(close + 1);
352
+ const ret = after.match(/^\s*RETURNS\s+(TABLE\s*\([^)]*\)|SETOF\s+[\w.]+|[\w.]+(?:\[\])?)/i);
353
+ const dollar = after.match(/\$(\w*)\$([\s\S]*?)\$\1\$/);
354
+ const beginAt = mask(after).search(/\bBEGIN\b/i);
355
+ const bodyText = dollar ? dollar[2] : beginAt >= 0 ? after.slice(beginAt) : '';
356
+ const bodyStart = close + 1 + (dollar ? dollar.index + dollar[0].indexOf(dollar[2]) : Math.max(beginAt, 0));
357
+ const isTrigger = ret && /^trigger$/i.test(ret[1]);
358
+ const steps = procSteps(bodyText, lineAt(bodyStart));
359
+ const returns = ret && !isTrigger ? (typeWords(ret[1]) ?? (/^(SETOF|TABLE)\b/i.test(ret[1]) ? 'rows' : words(ret[1]))) : null;
360
+ push(name, lineAt(f.index), steps, { inputs, returns, doc: docAbove(src, f.index),
361
+ says: `${words(name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(', ') : 'no inputs'}${returns ? ` and returns ${returns}` : ''}.`,
362
+ headline: `${words(name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(', ') : 'no inputs'}.` });
363
+ }
364
+ // Triggers: when the database runs a function by itself.
365
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+([\w."]+)\s+(BEFORE|AFTER|INSTEAD\s+OF)\s+([\w\s,]+?)\s+ON\s+([\w."]+)[\s\S]*?EXECUTE\s+(?:FUNCTION|PROCEDURE)\s+([\w.]+)/gi)) {
366
+ const events = t[3].split(/\s+OR\s+/i).map((e) => ({ INSERT: 'added', UPDATE: 'changed', DELETE: 'removed', TRUNCATE: 'emptied' })[e.trim().split(/\s+/)[0].toUpperCase()] || words(e)).filter(Boolean);
367
+ const what = article(singular(words(bare(t[4]))));
368
+ const when = `${t[2].toUpperCase() === 'BEFORE' ? 'Before' : t[2].toUpperCase() === 'AFTER' ? 'After' : 'Instead of when'} ${what} is ${events.join(' or ')}`;
369
+ push(bare(t[1]), lineAt(t.index), [{ kind: 'call', says: `${when}, runs ${words(bare(t[5]))}`, code: t[0].replace(/\s+/g, ' '), line: lineAt(t.index) }], { says: `${when}, the database runs ${words(bare(t[5]))}.`, headline: `${when}.`, doc: docAbove(src, t.index) });
370
+ }
371
+ // Rules the database enforces: CHECK and UNIQUE. A No stops the row.
372
+ for (const r of readSchema(src).rules) {
373
+ const table = words(r.table);
374
+ if (r.kind === 'check') {
375
+ const cond = sqlCondition(r.cond);
376
+ const name = r.name || `${(r.cond.match(/[a-z_]\w*/i) || ['value'])[0]}_check`;
377
+ push(name, r.line, [{ kind: 'branch', says: `If not: ${cond}`, code: `CHECK (${r.cond})`, line: r.line, children: [{ kind: 'fail', says: `Fails with Refused by the database: "The ${singular(table)} needs ${cond.replace(/"/g, "'")}"`, error: 'Refused by the database', message: `The ${singular(table)} needs ${cond.replace(/"/g, "'")}`, code: `CHECK (${r.cond})`, line: r.line }] }],
378
+ { says: `Every ${singular(table)} must have ${cond}.`, headline: `Every ${singular(table)} must have ${cond}.` });
379
+ } else {
380
+ const cols = listWords(r.cols.map(words));
381
+ push(r.name || `unique_${r.cols.join('_and_')}`, r.line, [{ kind: 'branch', says: `If not: no other ${singular(table)} has the same ${cols}`, code: `UNIQUE (${r.cols.join(', ')})`, line: r.line, children: [{ kind: 'fail', says: `Fails with Refused by the database: "Each ${cols} can be used only once"`, error: 'Refused by the database', message: `Each ${cols} can be used only once`, code: `UNIQUE (${r.cols.join(', ')})`, line: r.line }] }],
382
+ { says: `Each ${cols} can be used by only one ${singular(table)}.`, headline: `Each ${cols} can be used by only one ${singular(table)}.` });
383
+ }
384
+ }
385
+ items.sort((a, b) => a.line - b.line);
386
+ return items;
387
+ }