@skillstech/thunderlang 1.0.3 → 1.0.4
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/CHANGELOG.md +67 -0
- package/dist/core.cjs +11491 -9861
- package/dist/index.cjs +11488 -9858
- package/dist/learn.cjs +11054 -9428
- package/package.json +2 -2
- package/src/emit.mjs +1 -1
- package/src/libraries.mjs +2 -2
- package/src/meaning.mjs +2 -1
- package/src/model.mjs +13 -5
- package/src/powershell.mjs +24 -5
- package/src/read-repo.mjs +1 -0
- package/src/read.mjs +82 -8
- package/src/rlang.mjs +10 -3
- package/src/shell.mjs +45 -8
- package/src/sql-proc.mjs +1198 -0
- package/src/sql.mjs +87 -119
- package/src/steps.mjs +188 -37
package/src/sql-proc.mjs
ADDED
|
@@ -0,0 +1,1198 @@
|
|
|
1
|
+
// SQL routines in Thunder: functions, procedures, and their bodies, read by a block-structured parser.
|
|
2
|
+
//
|
|
3
|
+
// PL/pgSQL, MySQL/MariaDB stored programs, and T-SQL all nest: IF … ELSIF … ELSE … END IF, CASE … END CASE, loops,
|
|
4
|
+
// BEGIN … EXCEPTION … END, TRY/CATCH, labels. Reading them line by line put an ELSE's steps outside their IF, turned
|
|
5
|
+
// `ELSIF x = 'id'` into "Sets x to "id"", and lost `IF v_done THEN LEAVE`. So a body is tokenized (strings, quoted
|
|
6
|
+
// names, comments, and dollar quotes are single tokens), then parsed into the same nested steps every other language
|
|
7
|
+
// gives: questions with their two sides, loops with their body, tries with their handlers, and the statements that
|
|
8
|
+
// end a path (RETURN, RAISE EXCEPTION, SIGNAL, THROW) or jump out of a loop (EXIT, LEAVE, ITERATE, CONTINUE, BREAK).
|
|
9
|
+
//
|
|
10
|
+
// Faithfulness (faithful.mjs): a statement or condition is put into words only when the words account for it
|
|
11
|
+
// exactly; anything else is shown as code ("code, not explained"). A body whose structure cannot be matched (an IF
|
|
12
|
+
// without its END IF) is not guessed at: the routine is shown as not read.
|
|
13
|
+
//
|
|
14
|
+
// Deterministic, browser-safe, linear in the length of the file.
|
|
15
|
+
import { accountsFor, asCodeWords } from './faithful.mjs';
|
|
16
|
+
import { sqlCondition, sqlLogicName, sqlWords, sqlBare, sqlSingular, sqlTypeWords, sqlListWords } from './sql.mjs';
|
|
17
|
+
|
|
18
|
+
const plainName = (x) => sqlWords(String(x).replace(/^@+/, '').replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, ''));
|
|
19
|
+
const unq = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/s, '$1');
|
|
20
|
+
const cap = (s) => String(s).charAt(0).toUpperCase() + String(s).slice(1);
|
|
21
|
+
const lower1 = (s) => String(s).charAt(0).toLowerCase() + String(s).slice(1);
|
|
22
|
+
|
|
23
|
+
// ── Tokens ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
const PUNCT = ['->>', '#>>', ':=', '::', '..', '<>', '!=', '<=', '>=', '||', '=>', '<<', '>>', '->', '@>', '<@', '#>'];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Tokens of src[from, to): { t: 'word' | 'str' | 'num' | 'p', v, up, s, e }. Comments are skipped; a string, a quoted
|
|
29
|
+
* name ("x", `x`, [x]), and a dollar-quoted body are one token each. `up` is the upper-case word (unquoted words only).
|
|
30
|
+
*/
|
|
31
|
+
export function lexSql(src, from = 0, to = src.length, dialect = 'pg') {
|
|
32
|
+
const toks = [];
|
|
33
|
+
let i = from;
|
|
34
|
+
while (i < to) {
|
|
35
|
+
const c = src[i];
|
|
36
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v') { i++; continue; }
|
|
37
|
+
if (c === '-' && src[i + 1] === '-') { const n = src.indexOf('\n', i); i = n < 0 || n > to ? to : n; continue; }
|
|
38
|
+
if (c === '#' && dialect === 'mysql' && /[\s#!-]/.test(src[i + 1] || ' ')) { const n = src.indexOf('\n', i); i = n < 0 || n > to ? to : n; continue; }
|
|
39
|
+
if (c === '/' && src[i + 1] === '*' && src[i + 2] === '!' && dialect === 'mysql') {
|
|
40
|
+
// /*!50602 … */ is not a comment: MySQL 5.6.2 and later run what is inside.
|
|
41
|
+
const close = src.indexOf('*/', i + 3);
|
|
42
|
+
const e = close < 0 || close + 2 > to ? to : close + 2;
|
|
43
|
+
const ver = /^\d{5,6}/.exec(src.slice(i + 3, i + 9));
|
|
44
|
+
toks.push({ t: 'ver', v: src.slice(i, e), s: i, e, version: ver ? Number(ver[0]) : null, innerS: i + 3 + (ver ? ver[0].length : 0), innerE: close < 0 ? e : close });
|
|
45
|
+
i = e; continue;
|
|
46
|
+
}
|
|
47
|
+
if (c === '/' && src[i + 1] === '*') {
|
|
48
|
+
let d = 1, j = i + 2;
|
|
49
|
+
while (j < to && d) { if (dialect === 'pg' && src[j] === '/' && src[j + 1] === '*') { d++; j += 2; continue; } if (src[j] === '*' && src[j + 1] === '/') { d--; j += 2; continue; } j++; }
|
|
50
|
+
i = j; continue;
|
|
51
|
+
}
|
|
52
|
+
const pre = /[EeNnBbXx]/.test(c) && src[i + 1] === "'" && !/[\w$]/.test(src[i - 1] || '');
|
|
53
|
+
if (c === "'" || pre) {
|
|
54
|
+
const esc = dialect === 'mysql' || (pre && /[Ee]/.test(c));
|
|
55
|
+
let j = i + (pre ? 2 : 1);
|
|
56
|
+
for (; j < to; j++) { if (esc && src[j] === '\\') { j++; continue; } if (src[j] === "'") { if (src[j + 1] === "'") { j++; continue; } break; } }
|
|
57
|
+
const e = Math.min(j + 1, to);
|
|
58
|
+
toks.push({ t: 'str', v: src.slice(i, e), s: i, e, prefix: pre ? c.toUpperCase() : '' });
|
|
59
|
+
i = e; continue;
|
|
60
|
+
}
|
|
61
|
+
if (c === '$' && dialect === 'pg') {
|
|
62
|
+
const m = /^\$([A-Za-z_][\w]*)?\$/.exec(src.slice(i, i + 66));
|
|
63
|
+
if (m) {
|
|
64
|
+
const close = src.indexOf(m[0], i + m[0].length);
|
|
65
|
+
const e = close < 0 || close + m[0].length > to ? to : close + m[0].length;
|
|
66
|
+
toks.push({ t: 'str', dollar: m[0], v: src.slice(i, e), s: i, e });
|
|
67
|
+
i = e; continue;
|
|
68
|
+
}
|
|
69
|
+
const d = /^\$\d+/.exec(src.slice(i, i + 12));
|
|
70
|
+
if (d) { toks.push({ t: 'word', v: d[0], up: d[0], s: i, e: i + d[0].length }); i += d[0].length; continue; }
|
|
71
|
+
}
|
|
72
|
+
if (c === '"' && dialect === 'mysql') {
|
|
73
|
+
let j = i + 1;
|
|
74
|
+
for (; j < to; j++) { if (src[j] === '\\') { j++; continue; } if (src[j] === '"') { if (src[j + 1] === '"') { j++; continue; } break; } }
|
|
75
|
+
const e = Math.min(j + 1, to);
|
|
76
|
+
toks.push({ t: 'str', dq: true, v: src.slice(i, e), s: i, e });
|
|
77
|
+
i = e; continue;
|
|
78
|
+
}
|
|
79
|
+
if (c === '"' || c === '`' || (c === '[' && dialect === 'tsql')) {
|
|
80
|
+
const close = c === '[' ? ']' : c;
|
|
81
|
+
let j = i + 1;
|
|
82
|
+
for (; j < to; j++) { if (src[j] === close) { if (src[j + 1] === close) { j++; continue; } break; } }
|
|
83
|
+
const e = Math.min(j + 1, to);
|
|
84
|
+
toks.push({ t: 'word', quoted: true, v: src.slice(i, e), up: null, s: i, e });
|
|
85
|
+
i = e; continue;
|
|
86
|
+
}
|
|
87
|
+
let m;
|
|
88
|
+
const rest = src.slice(i, Math.min(to, i + 200));
|
|
89
|
+
// (A `$` inside a name only when a name character follows it: MySQL's `END$$` is END and the delimiter.)
|
|
90
|
+
if ((m = (dialect === 'pg' ? /^@[A-Za-z_]\w*@/ : /^(?:@@?|##?)[A-Za-z_][\w#@]*(?:\$+\w+)*/).exec(rest)) || (m = /^[A-Za-z_\u0080-][\w\u0080-]*(?:\$+[\w\u0080-]+)*/.exec(rest))) {
|
|
91
|
+
toks.push({ t: 'word', v: m[0], up: m[0].toUpperCase(), s: i, e: i + m[0].length });
|
|
92
|
+
i += m[0].length; continue;
|
|
93
|
+
}
|
|
94
|
+
if ((m = /^\d+(?:\.(?!\.)\d*)?(?:[eE][-+]?\d+)?/.exec(rest))) { toks.push({ t: 'num', v: m[0], s: i, e: i + m[0].length }); i += m[0].length; continue; }
|
|
95
|
+
const p = PUNCT.find((x) => src.startsWith(x, i)) ?? c;
|
|
96
|
+
toks.push({ t: 'p', v: p, s: i, e: i + p.length });
|
|
97
|
+
i += p.length;
|
|
98
|
+
}
|
|
99
|
+
return toks;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const isW = (t, ...ws) => !!t && t.t === 'word' && !t.quoted && (ws.length === 0 || ws.includes(t.up));
|
|
103
|
+
const isP = (t, v) => !!t && t.t === 'p' && t.v === v;
|
|
104
|
+
|
|
105
|
+
class Unmatched extends Error {}
|
|
106
|
+
|
|
107
|
+
// ── Words for values and conditions (faithful or code) ───────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
// Things the condition words cannot say exactly: subqueries, CASE, quantifiers, array and JSON operators.
|
|
110
|
+
const NOT_IN_WORDS = /:=|=>|\b(?:SELECT|CASE|EXISTS|ANY|ALL|SOME|ARRAY|OVER|WITHIN|FILTER|COLLATE|ESCAPE|SIMILAR|DISTINCT|ROW|AT\s+TIME\s+ZONE|IS\s+(?:NOT\s+)?DISTINCT)\b|->|#>|@>|<@|\?|~|\[|\{|\$\d|\bIS\s+(?:NOT\s+)?(?:TRUE|FALSE|UNKNOWN)\b|\bREGEXP\b|\bRLIKE\b|\bMOD\b|\bDIV\b|\bXOR\b|&|\||\^/i;
|
|
111
|
+
|
|
112
|
+
/** Strings blanked (same length), so a search never matches inside one. */
|
|
113
|
+
const blankStrings = (s) => String(s).replace(/'(?:[^']|'')*'/g, (m) => `'${'x'.repeat(Math.max(0, m.length - 2))}'`);
|
|
114
|
+
|
|
115
|
+
/** SQL code in the shape the faithfulness counts expect (`and`, `not`, `==`, `!= null` for IS NOT NULL). */
|
|
116
|
+
function countable(code) {
|
|
117
|
+
return String(code).replace(/'(?:[^']|'')*'/g, 'Q')
|
|
118
|
+
// (Names kept as written, `v_is_default`, are not counted on either side.)
|
|
119
|
+
.replace(/(?<![\w.$@])[A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*)*(?![\w$])/g, (m) => (sqlLogicName(m) ? 'Q' : m))
|
|
120
|
+
.replace(/\bIS\s+NOT\s+NULL\b/gi, ' != null ').replace(/\bIS\s+NULL\b/gi, ' == null ')
|
|
121
|
+
.replace(/\bBETWEEN\s+(\S+)\s+AND\s+/gi, ' between $1 , ')
|
|
122
|
+
.replace(/\|\|/g, ' + ')
|
|
123
|
+
// (`<>` is worded "is different from": a comparison, not a negation.)
|
|
124
|
+
.replace(/<>|!=/g, ' == ')
|
|
125
|
+
.replace(/\bNOT\b/gi, 'not').replace(/\bAND\b/gi, 'and').replace(/\bOR\b/gi, 'or').replace(/\bIN\b/gi, 'in').replace(/\bIS\b/gi, 'is')
|
|
126
|
+
.replace(/(?<![<>!:=])=(?!=)/g, '==');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A condition in words when the words keep every negation, and/or, and comparison; otherwise null. */
|
|
130
|
+
function condWords(text, ctx) {
|
|
131
|
+
const t = String(text).trim(); // (whitespace inside quoted text is kept: sqlCondition holds strings first)
|
|
132
|
+
if (!t || NOT_IN_WORDS.test(blankStrings(t))) return null;
|
|
133
|
+
// MySQL user variables (@x, @sys.debug) and system variables (@@x) are kept as written.
|
|
134
|
+
// PL/pgSQL's FOUND: whether the last query found (or changed) a row.
|
|
135
|
+
if (ctx.dialect === 'pg' && /^(NOT\s+)?FOUND$/i.test(t)) return /^NOT/i.test(t) ? 'not: the last statement found or changed a row' : 'the last statement found or changed a row';
|
|
136
|
+
let said;
|
|
137
|
+
try { said = sqlCondition(t, { vars: true, keepAt: ctx.dialect !== 'tsql' }); } catch { return null; }
|
|
138
|
+
return said && accountsFor(countable(t), said) ? said : null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** A string literal's text, exactly as the code writes it (doubled quotes undone). */
|
|
142
|
+
const strText = (tok) => (tok.dollar ? tok.v.slice(tok.dollar.length, -tok.dollar.length) : tok.v.slice(tok.prefix ? 2 : 1, -1).replace(tok.dq ? /""/g : /''/g, tok.dq ? '"' : "'"));
|
|
143
|
+
|
|
144
|
+
/** A value in words: a quoted text exactly, yes/no, a number, NULL, text joined with ||, or a condition's words. */
|
|
145
|
+
function valueWords(text, ctx, toks = null) {
|
|
146
|
+
const t = String(text).trim();
|
|
147
|
+
const ts = toks ?? lexSql(t, 0, t.length, ctx.dialect);
|
|
148
|
+
if (ts.length === 1 && ts[0].t === 'str' && !ts[0].dollar && ts[0].prefix !== 'B' && ts[0].prefix !== 'X') return `"${strText(ts[0])}"`;
|
|
149
|
+
if (ts.length === 1 && isW(ts[0], 'TRUE', 'FALSE')) return ts[0].up === 'TRUE' ? 'yes' : 'no';
|
|
150
|
+
if (ts.length === 1 && isW(ts[0], 'NULL')) return 'NULL';
|
|
151
|
+
if (ts.length === 1 && ts[0].t === 'num') return ts[0].v;
|
|
152
|
+
if (ts.length === 2 && isP(ts[0], '-') && ts[1].t === 'num') return `-${ts[1].v}`;
|
|
153
|
+
const joined = joinedText(ts, ctx);
|
|
154
|
+
if (joined) return joined;
|
|
155
|
+
return condWords(t, ctx);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Text joined with `||` whose parts are quoted texts and plain names: one quoted text with each name as a
|
|
160
|
+
* «placeholder», spelled as the code spells it ('Table '||v_name||' moved' -> "Table «v_name» moved").
|
|
161
|
+
*/
|
|
162
|
+
function joinedText(ts, ctx) {
|
|
163
|
+
if (!ts.some((x) => isP(x, '||'))) return null;
|
|
164
|
+
const parts = [[]];
|
|
165
|
+
for (const x of ts) { if (isP(x, '||')) parts.push([]); else parts.at(-1).push(x); }
|
|
166
|
+
let out = '', hasText = false;
|
|
167
|
+
for (const p of parts) {
|
|
168
|
+
if (p.length === 1 && p[0].t === 'str' && !p[0].dollar) { out += strText(p[0]); hasText = true; continue; }
|
|
169
|
+
if (p.length && p.every((x, k) => (k % 2 === 0 ? x.t === 'word' && !/^(?:NULL|TRUE|FALSE)$/.test(x.up ?? '') : isP(x, '.'))) && p.length % 2 === 1) { out += `«${p.map((x) => x.v).join('')}»`; continue; }
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
return hasText ? `"${out}"` : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The SQL text a dynamic statement runs: the text in a variable, a quoted text, text joined with ||, or
|
|
177
|
+
* format('…%I…%L…%s…', a, b, c) with each conversion paired with its value: "ALTER TABLE «a as %I» …". Null otherwise.
|
|
178
|
+
*/
|
|
179
|
+
function sqlTextWords(ts, ctx) {
|
|
180
|
+
if (!ts.length) return null;
|
|
181
|
+
if (ts.every((x, k) => (k % 2 === 0 ? x.t === 'word' && !x.quoted : isP(x, '.')))) { const v = targetWords(ctx.src.slice(ts[0].s, ts.at(-1).e), ctx); return v ? `text in ${v}` : null; }
|
|
182
|
+
if (ts.length === 1 && ts[0].t === 'str' && !ts[0].dollar) return `"${strText(ts[0])}"`;
|
|
183
|
+
const joined = joinedText(ts, ctx);
|
|
184
|
+
if (joined) return joined;
|
|
185
|
+
if (isW(ts[0], 'FORMAT') && isP(ts[1], '(') && matchParen(ts, 1) === ts.length - 1) {
|
|
186
|
+
const args = splitComma(ts.slice(2, -1));
|
|
187
|
+
if (!(args[0]?.length === 1 && args[0][0].t === 'str')) return null;
|
|
188
|
+
const vals = args.slice(1).map((p) => ctx.src.slice(p[0].s, p.at(-1).e).trim());
|
|
189
|
+
let k = 0, ok = true;
|
|
190
|
+
const out = strText(args[0][0]).replace(/%(?:\d+\$)?-?\d*[sIL%]?/g, (m) => {
|
|
191
|
+
if (m === '%%') return '%';
|
|
192
|
+
if (!/^%[sIL]$/.test(m)) { ok = false; return m; } // positions and widths are not paired here
|
|
193
|
+
const v = vals[k++];
|
|
194
|
+
if (v == null) { ok = false; return m; }
|
|
195
|
+
return m === '%s' ? `«${v}»` : `«${v} as ${m}»`;
|
|
196
|
+
});
|
|
197
|
+
return ok && k === vals.length ? `"${out}"` : null;
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A name being set or read, in words: v_total -> total, v_row.count -> the row's count; @x (MySQL) as written. */
|
|
203
|
+
function targetWords(text, ctx) {
|
|
204
|
+
const t = String(text).trim();
|
|
205
|
+
if (/^@@/.test(t) || (ctx.dialect === 'mysql' && /^@/.test(t))) return /^@@?[\w.$]+$/.test(t) ? `\`${t}\`` : null;
|
|
206
|
+
const parts = t.replace(/^@/, '').split('.');
|
|
207
|
+
if (!parts.every((p) => /^[A-Za-z_#][\w$#]*$|^"[^"]+"$|^`[^`]+`$|^\[[^\]]+\]$/.test(p))) return null;
|
|
208
|
+
if (parts.length === 1) return plainName(unq(parts[0]));
|
|
209
|
+
if (parts.length === 2) return `the ${plainName(unq(parts[0]))}'s ${sqlWords(unq(parts[1]))}`;
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── Statements ───────────────────────────────────────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
// Code on one line: a `--` comment becomes /* … */ so it does not swallow the rest of the line.
|
|
216
|
+
const code = (text) => String(text).replace(/('(?:[^']|'')*')|--([^\n]*)/g, (m, str, note) => str ?? `/*${note.replace(/\*\//g, '* /')} */`).replace(/\s+/g, ' ').trim();
|
|
217
|
+
/** "x to y", or the names as written when both read the same (v_retention := p_retention). */
|
|
218
|
+
const setPair = (target, v, rawT, rawV) => (target === v && rawT.trim() !== rawV.trim() ? `\`${rawT.trim()}\` to \`${rawV.trim()}\`` : `${target} to ${v}`);
|
|
219
|
+
const asCode = (text, base) => ({ kind: 'other', says: code(text), code: code(text), restates: code(text), ...base });
|
|
220
|
+
|
|
221
|
+
/** Top-level pieces of a token run split at commas. */
|
|
222
|
+
function splitComma(ts) {
|
|
223
|
+
const out = [[]];
|
|
224
|
+
let d = 0;
|
|
225
|
+
for (const x of ts) {
|
|
226
|
+
if (isP(x, '(') || isP(x, '[')) d++;
|
|
227
|
+
else if (isP(x, ')') || isP(x, ']')) d--;
|
|
228
|
+
if (d === 0 && isP(x, ',')) { out.push([]); continue; }
|
|
229
|
+
out.at(-1).push(x);
|
|
230
|
+
}
|
|
231
|
+
return out.filter((p) => p.length);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Index (in ts) of the first top-level word among `ws`, or -1. */
|
|
235
|
+
function topWord(ts, ws, from = 0) {
|
|
236
|
+
let d = 0;
|
|
237
|
+
for (let k = from; k < ts.length; k++) {
|
|
238
|
+
const x = ts[k];
|
|
239
|
+
if (isP(x, '(') || isP(x, '[')) d++;
|
|
240
|
+
else if (isP(x, ')') || isP(x, ']')) d--;
|
|
241
|
+
else if (d === 0 && isW(x) && ws.includes(x.up)) return k;
|
|
242
|
+
}
|
|
243
|
+
return -1;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** An error message with its % conversions paired with RAISE's arguments: "Order «p_id» does not exist". */
|
|
247
|
+
function raiseMessage(fmt, args) {
|
|
248
|
+
let k = 0, ok = true;
|
|
249
|
+
const out = fmt.replace(/%%|%/g, (m) => { if (m === '%%') return '%'; const a = args[k++]; if (!a) { ok = false; return m; } return `«${a}»`; });
|
|
250
|
+
return ok && k === args.length ? out : null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* One simple statement (tokens ts, its source text) as a step. Every wording here is exact or the statement is code.
|
|
255
|
+
*/
|
|
256
|
+
function statementStep(ts, text, base, ctx) {
|
|
257
|
+
const head = ts[0];
|
|
258
|
+
const up = head?.up;
|
|
259
|
+
const t = code(text);
|
|
260
|
+
const rest = ts.slice(1);
|
|
261
|
+
const restText = (k = 1) => (ts[k] ? ctx.src.slice(ts[k].s, ts.at(-1).e) : '');
|
|
262
|
+
const at = (k) => ts[k];
|
|
263
|
+
const fail = (says, extra = {}) => ({ kind: 'fail', says: `Fails with ${says}`, error: extra.error ?? 'an error', ...(extra.message != null ? { message: extra.message } : {}), code: t, ...base });
|
|
264
|
+
|
|
265
|
+
// ── Endings and jumps ──
|
|
266
|
+
if (up === 'RETURN') {
|
|
267
|
+
if (ctx.dialect === 'pg' && isW(at(1), 'NEXT')) {
|
|
268
|
+
const v = ts.length > 2 ? valueWords(restText(2), ctx) : null;
|
|
269
|
+
return { kind: 'call', says: ts.length > 2 ? (v ? `Adds ${v} to the rows it gives back, and carries on` : 'Adds a row to the rows it gives back, and carries on') : 'Adds the current row to the rows it gives back, and carries on', code: t, ...base, rowOut: true };
|
|
270
|
+
}
|
|
271
|
+
if (ctx.dialect === 'pg' && isW(at(1), 'QUERY')) return { kind: 'call', says: isW(at(2), 'EXECUTE') ? 'Adds the rows of a query built when it runs to the rows it gives back, and carries on' : 'Adds the rows a query finds to the rows it gives back, and carries on', code: t, ...base, rowOut: true };
|
|
272
|
+
if (ts.length === 1) return { kind: 'return', says: ctx.setof ? 'Returns the rows it has added' : 'Stops here', code: t, ...base };
|
|
273
|
+
if (ctx.trigger && ts.length === 2 && isW(at(1), 'NEW', 'OLD')) return { kind: 'return', says: at(1).up === 'NEW' ? 'Lets the change go ahead' : 'Keeps the old row', code: t, ...base };
|
|
274
|
+
const v = valueWords(restText(1), ctx, rest);
|
|
275
|
+
if (ctx.routine === 'procedure') return { kind: 'return', says: v ? `Stops here, with return code ${v}` : `Stops here, with the return code ${asCodeWords(restText(1))}`, code: t, ...base };
|
|
276
|
+
if (!v) return { kind: 'return', says: t, code: t, restates: t, ...base };
|
|
277
|
+
return { kind: 'return', says: `Returns ${v}`, code: t, ...base };
|
|
278
|
+
}
|
|
279
|
+
if (up === 'RAISE' && ctx.dialect === 'pg') {
|
|
280
|
+
let k = 1;
|
|
281
|
+
const level = isW(at(1), 'DEBUG', 'LOG', 'INFO', 'NOTICE', 'WARNING', 'EXCEPTION') ? at(k++).up : 'EXCEPTION';
|
|
282
|
+
if (ts.length === 1) return fail('the same error again: passes it on', { error: 'the same error' });
|
|
283
|
+
const fmt = at(k);
|
|
284
|
+
let message = null;
|
|
285
|
+
if (fmt?.t === 'str') {
|
|
286
|
+
const using = topWord(ts, ['USING'], k + 1);
|
|
287
|
+
const argTs = ts.slice(k + 1, using < 0 ? ts.length : using);
|
|
288
|
+
const args = isP(argTs[0], ',') ? splitComma(argTs.slice(1)).map((p) => ctx.src.slice(p[0].s, p.at(-1).e).trim()) : [];
|
|
289
|
+
if (argTs.length && !isP(argTs[0], ',')) return level === 'EXCEPTION' ? fail('an error', { message: null }) : asCode(t, base);
|
|
290
|
+
message = raiseMessage(strText(fmt), args);
|
|
291
|
+
if (message == null) return level === 'EXCEPTION' ? { ...fail('an error'), says: `Fails with an error: ${asCodeWords(t)}` } : asCode(t, base);
|
|
292
|
+
}
|
|
293
|
+
if (level === 'EXCEPTION') {
|
|
294
|
+
if (message != null) return fail(`an error: "${message}"`, { message });
|
|
295
|
+
if (fmt?.t === 'word' && !isW(fmt, 'USING')) return fail(`the error ${sqlWords(fmt.v)}`, { error: sqlWords(fmt.v) });
|
|
296
|
+
return fail('an error (its message is worked out when it runs)');
|
|
297
|
+
}
|
|
298
|
+
if (message != null) return { kind: 'call', says: `${level === 'WARNING' ? 'Warns' : 'Writes a message'}: "${message}"`, code: t, ...base };
|
|
299
|
+
return asCode(t, base);
|
|
300
|
+
}
|
|
301
|
+
if (up === 'SIGNAL' || up === 'RESIGNAL') {
|
|
302
|
+
if (up === 'RESIGNAL' && ts.length === 1) return fail('the same error again: passes it on', { error: 'the same error' });
|
|
303
|
+
const mt = ts.findIndex((x) => isW(x, 'MESSAGE_TEXT'));
|
|
304
|
+
if (mt > 0 && isP(at(mt + 1), '=')) {
|
|
305
|
+
const val = at(mt + 2), after = at(mt + 3);
|
|
306
|
+
if (val?.t === 'str' && (!after || isP(after, ','))) return fail(`an error: "${strText(val)}"`, { message: strText(val) });
|
|
307
|
+
const end = ts.findIndex((x, k) => k > mt + 1 && isP(x, ','));
|
|
308
|
+
const vw = targetWords(ctx.src.slice(val.s, (end < 0 ? ts.at(-1) : ts[end - 1]).e), ctx);
|
|
309
|
+
if (vw) return fail(`an error whose message is in ${vw}`);
|
|
310
|
+
}
|
|
311
|
+
return fail('an error', {});
|
|
312
|
+
}
|
|
313
|
+
if (up === 'THROW') {
|
|
314
|
+
if (ts.length === 1) return fail('the same error again: passes it on', { error: 'the same error' });
|
|
315
|
+
const args = splitComma(rest);
|
|
316
|
+
if (args.length === 3 && args[1].length === 1 && args[1][0].t === 'str') return fail(`an error: "${strText(args[1][0])}"`, { message: strText(args[1][0]) });
|
|
317
|
+
if (args.length === 3) { const vw = targetWords(ctx.src.slice(args[1][0].s, args[1].at(-1).e), ctx); if (vw) return fail(`an error whose message is in ${vw}`); }
|
|
318
|
+
return fail('an error');
|
|
319
|
+
}
|
|
320
|
+
if (up === 'RAISERROR' && isP(at(1), '(')) {
|
|
321
|
+
const close = matchParen(ts, 1);
|
|
322
|
+
const args = close > 0 ? splitComma(ts.slice(2, close)) : [];
|
|
323
|
+
const sev = args[1]?.length === 1 && args[1][0].t === 'num' ? Number(args[1][0].v) : null;
|
|
324
|
+
const m = args[0]?.length === 1 && args[0][0].t === 'str' ? `"${strText(args[0][0])}"` : args[0] ? (targetWords(ctx.src.slice(args[0][0].s, args[0].at(-1).e), ctx) ? `the text in ${targetWords(ctx.src.slice(args[0][0].s, args[0].at(-1).e), ctx)}` : null) : null;
|
|
325
|
+
if (sev == null || !m) return asCode(t, base);
|
|
326
|
+
// Severity 10 or less is a message; 11-19 is an error that does not stop the procedure unless it runs inside TRY.
|
|
327
|
+
if (sev <= 10) return { kind: 'call', says: `Writes a message: ${m}`, code: t, ...base };
|
|
328
|
+
if (sev >= 20 || ctx.inTry) return fail(m.startsWith('"') ? `an error: ${m}` : `an error whose message is ${m}`, m.startsWith('"') ? { message: m.slice(1, -1) } : {});
|
|
329
|
+
return { kind: 'call', says: `Reports an error and carries on (unless a TRY … CATCH that called it catches the error): ${m}`, code: t, ...base };
|
|
330
|
+
}
|
|
331
|
+
if (up === 'PRINT') {
|
|
332
|
+
const v = valueWords(restText(1), ctx, rest);
|
|
333
|
+
return v ? { kind: 'call', says: `Writes a message: ${v}`, code: t, ...base } : asCode(t, base);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ── Running other code ──
|
|
337
|
+
if ((up === 'PERFORM' || up === 'CALL') && isW(at(1))) {
|
|
338
|
+
let k = 1;
|
|
339
|
+
while (isP(at(k + 1), '.') && isW(at(k + 2))) k += 2;
|
|
340
|
+
if (isP(at(k + 1), '(') && matchParen(ts, k + 1) === ts.length - 1) return { kind: 'call', says: `Runs ${sqlWords(unq(at(k).v))}`, callee: unq(at(k).v), code: t, ...base };
|
|
341
|
+
return asCode(t, base);
|
|
342
|
+
}
|
|
343
|
+
if (up === 'EXEC' || up === 'EXECUTE') {
|
|
344
|
+
if (ctx.dialect === 'pg') {
|
|
345
|
+
// Dynamic SQL: the text it runs, with each inserted value as a «placeholder»; USING (bound values) is code.
|
|
346
|
+
const into = topWord(ts, ['INTO']);
|
|
347
|
+
if (topWord(ts, ['USING']) >= 0 || ts.length < 2) return asCode(t, base);
|
|
348
|
+
const what = sqlTextWords(ts.slice(1, into < 0 ? ts.length : into), ctx);
|
|
349
|
+
if (!what) return asCode(t, base);
|
|
350
|
+
let keep = '';
|
|
351
|
+
if (into >= 0) {
|
|
352
|
+
const strict = isW(ts[into + 1], 'STRICT') ? 1 : 0;
|
|
353
|
+
const targets = splitComma(ts.slice(into + 1 + strict)).map((p) => targetWords(ctx.src.slice(p[0].s, p.at(-1).e), ctx));
|
|
354
|
+
if (!targets.length || !targets.every(Boolean)) return asCode(t, base);
|
|
355
|
+
keep = `, and keeps what it gives back in ${sqlListWords(targets)}`;
|
|
356
|
+
}
|
|
357
|
+
return { kind: 'call', says: `Runs the SQL ${what}${keep}`, code: t, ...base };
|
|
358
|
+
}
|
|
359
|
+
if (ctx.dialect === 'mysql') {
|
|
360
|
+
if (isW(at(1)) && (ts.length === 2 || isW(at(2), 'USING'))) return { kind: 'call', says: `Runs the prepared statement ${at(1).v}`, code: t, ...base };
|
|
361
|
+
return asCode(t, base);
|
|
362
|
+
}
|
|
363
|
+
// T-SQL: EXEC proc …, EXEC @rc = proc …, EXEC (@sql), EXEC sp_executesql @sql, …; EXECUTE AS changes who it runs as.
|
|
364
|
+
if (isW(at(1), 'AS')) return asCode(t, base);
|
|
365
|
+
if (isP(at(1), '(')) {
|
|
366
|
+
const close = matchParen(ts, 1);
|
|
367
|
+
const inner = close === ts.length - 1 ? ts.slice(2, close) : null;
|
|
368
|
+
const vw = inner && inner.length === 1 && inner[0].t === 'word' ? targetWords(inner[0].v, ctx) : null;
|
|
369
|
+
return vw ? { kind: 'call', says: `Runs the SQL text in ${vw}`, code: t, ...base } : asCode(t, base);
|
|
370
|
+
}
|
|
371
|
+
let k = 1, keep = null;
|
|
372
|
+
if (isW(at(1)) && /^@/.test(at(1).v) && isP(at(2), '=')) { keep = targetWords(at(1).v, ctx); k = 3; }
|
|
373
|
+
if (!isW(at(k))) return asCode(t, base);
|
|
374
|
+
let name = at(k).v; let j = k;
|
|
375
|
+
while (isP(at(j + 1), '.') && isW(at(j + 2))) { j += 2; name = at(j).v; }
|
|
376
|
+
if (/^@/.test(at(k).v) && j === k && !keep) return asCode(t, base);
|
|
377
|
+
if (/^sp_executesql$/i.test(unq(name))) {
|
|
378
|
+
const first = at(j + 1);
|
|
379
|
+
const vw = first && first.t === 'word' && (!at(j + 2) || isP(at(j + 2), ',')) ? targetWords(first.v, ctx) : null;
|
|
380
|
+
return vw ? { kind: 'call', says: `Runs the SQL text in ${vw}`, code: t, ...base } : asCode(t, base);
|
|
381
|
+
}
|
|
382
|
+
return { kind: 'call', says: `Runs ${sqlWords(unq(name))}${keep ? ` and keeps its return code in ${keep}` : ''}`, callee: unq(name), code: t, ...base };
|
|
383
|
+
}
|
|
384
|
+
if (up === 'PREPARE' && ctx.dialect === 'mysql' && isW(at(1)) && isW(at(2), 'FROM')) {
|
|
385
|
+
const v = valueWords(restText(3), ctx, ts.slice(3));
|
|
386
|
+
return v ? { kind: 'call', says: `Prepares the statement ${at(1).v} from ${v}`, code: t, ...base } : asCode(t, base);
|
|
387
|
+
}
|
|
388
|
+
if ((up === 'DEALLOCATE' || up === 'DROP') && isW(at(1), 'PREPARE') && isW(at(2)) && ts.length === 3) return { kind: 'call', says: `Frees the prepared statement ${at(2).v}`, code: t, ...base };
|
|
389
|
+
if (up === 'DEALLOCATE' && ctx.dialect === 'tsql' && ts.length === 2 && isW(at(1))) return { kind: 'call', says: `Frees the cursor ${at(1).v}`, code: t, ...base };
|
|
390
|
+
if (up === 'OPEN' && ts.length === 2 && isW(at(1))) return { kind: 'call', says: `Opens the cursor ${at(1).v}`, code: t, ...base };
|
|
391
|
+
if (up === 'CLOSE' && ts.length === 2 && isW(at(1))) return { kind: 'call', says: `Closes the cursor ${at(1).v}`, code: t, ...base };
|
|
392
|
+
if (up === 'FETCH') {
|
|
393
|
+
const into = topWord(ts, ['INTO']);
|
|
394
|
+
const from = topWord(ts, ['FROM', 'IN']);
|
|
395
|
+
const cur = from > 0 ? at(from + 1) : at(1);
|
|
396
|
+
const plainFetch = into > 0 && cur && isW(cur) && (from > 0 ? into === from + 2 && ts.slice(1, from).every((x) => isW(x, 'NEXT')) : into === 2);
|
|
397
|
+
if (plainFetch) {
|
|
398
|
+
const targets = splitComma(ts.slice(into + 1)).map((p) => (p.length === 1 ? targetWords(p[0].v, ctx) : null));
|
|
399
|
+
if (targets.every(Boolean)) return { kind: 'call', says: `Takes the next row of ${cur.v} into ${sqlListWords(targets)}`, code: t, ...base };
|
|
400
|
+
}
|
|
401
|
+
return asCode(t, base);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// ── Setting values ──
|
|
405
|
+
if (up === 'GET' && ctx.dialect === 'pg') {
|
|
406
|
+
const m = t.match(/^GET\s+(?:CURRENT\s+)?DIAGNOSTICS\s+([\w.]+)\s*(?::=|=)\s*ROW_COUNT$/i);
|
|
407
|
+
if (m && targetWords(m[1], ctx)) return { kind: 'set', says: `Sets ${targetWords(m[1], ctx)} to how many rows the last statement changed`, code: t, ...base };
|
|
408
|
+
return asCode(t, base);
|
|
409
|
+
}
|
|
410
|
+
if (up === 'SET' && ctx.dialect !== 'pg') {
|
|
411
|
+
// SET a = x, b = y (MySQL) / SET @a = x (T-SQL). Options (SET NOCOUNT ON, SET NAMES …) are code.
|
|
412
|
+
const parts = splitComma(rest);
|
|
413
|
+
const sets = [];
|
|
414
|
+
for (const p of parts) {
|
|
415
|
+
let k = 0;
|
|
416
|
+
if (isW(p[0], 'SESSION', 'GLOBAL', 'LOCAL', 'PERSIST')) k = 1;
|
|
417
|
+
let j = k;
|
|
418
|
+
while (isP(p[j + 1], '.') && isW(p[j + 2])) j += 2;
|
|
419
|
+
const op = p[j + 1];
|
|
420
|
+
if (!isW(p[k]) || !(isP(op, '=') || isP(op, ':='))) return [asCode(t, base)];
|
|
421
|
+
const target = targetWords(ctx.src.slice(p[k].s, p[j].e), ctx);
|
|
422
|
+
const vts = p.slice(j + 2);
|
|
423
|
+
const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
|
|
424
|
+
if (!target || !v || k) return [asCode(t, base)];
|
|
425
|
+
sets.push(setPair(target, v, ctx.src.slice(p[k].s, p[j].e), ctx.src.slice(vts[0].s, vts.at(-1).e)));
|
|
426
|
+
}
|
|
427
|
+
return { kind: 'set', says: `Sets ${sqlListWords(sets)}`, code: t, ...base };
|
|
428
|
+
}
|
|
429
|
+
if (up === 'SELECT') return selectStatement(ts, t, base, ctx);
|
|
430
|
+
{
|
|
431
|
+
// PL/pgSQL assignment: target := value (or =).
|
|
432
|
+
let j = 0;
|
|
433
|
+
if (ctx.dialect === 'pg' && isW(at(0))) {
|
|
434
|
+
while (isP(at(j + 1), '.') && isW(at(j + 2))) j += 2;
|
|
435
|
+
if (isP(at(j + 1), ':=') || (isP(at(j + 1), '=') && !isW(at(0), 'UPDATE', 'DELETE', 'INSERT'))) {
|
|
436
|
+
const target = targetWords(ctx.src.slice(at(0).s, at(j).e), ctx);
|
|
437
|
+
const vts = ts.slice(j + 2);
|
|
438
|
+
const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
|
|
439
|
+
if (target && v) return { kind: 'set', says: `Sets ${setPair(target, v, ctx.src.slice(at(0).s, at(j).e), ctx.src.slice(vts[0].s, vts.at(-1).e))}`, code: t, ...base };
|
|
440
|
+
return asCode(t, base);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// ── Changing tables ──
|
|
446
|
+
if (up === 'INSERT') return insertStatement(ts, t, base, ctx);
|
|
447
|
+
if (up === 'UPDATE') {
|
|
448
|
+
const set = topWord(ts, ['SET']);
|
|
449
|
+
let tEnd = 1;
|
|
450
|
+
while (isP(at(tEnd + 1), '.') && isW(at(tEnd + 2))) tEnd += 2;
|
|
451
|
+
if (!isW(at(1)) || (set !== tEnd + 1 && !(set === tEnd + 2 && isW(at(tEnd + 1))))) return asCode(t, base);
|
|
452
|
+
if (topWord(ts, ['FROM', 'RETURNING', 'OUTPUT', 'JOIN', 'ORDER', 'LIMIT', 'WHERE CURRENT'], set) >= 0) return asCode(t, base);
|
|
453
|
+
const where = topWord(ts, ['WHERE'], set);
|
|
454
|
+
const setTs = ts.slice(set + 1, where < 0 ? ts.length : where);
|
|
455
|
+
const sets = [];
|
|
456
|
+
for (const p of splitComma(setTs)) {
|
|
457
|
+
const eq = p.findIndex((x) => isP(x, '='));
|
|
458
|
+
if (eq < 1) return asCode(t, base);
|
|
459
|
+
const target = targetWords(ctx.src.slice(p[0].s, p[eq - 1].e), { ...ctx, dialect: 'pg' });
|
|
460
|
+
const vts = p.slice(eq + 1);
|
|
461
|
+
const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
|
|
462
|
+
if (!target || !v) return asCode(t, base);
|
|
463
|
+
sets.push(`${target.replace(/^the .*'s /, '')} to ${v}`);
|
|
464
|
+
}
|
|
465
|
+
const w = where < 0 ? '' : condWords(ctx.src.slice(at(where + 1).s, ts.at(-1).e), ctx);
|
|
466
|
+
if (w == null) return asCode(t, base);
|
|
467
|
+
return { kind: 'call', says: `Records the change in ${sqlWords(sqlBare(ctx.src.slice(at(1).s, at(tEnd).e)))}: sets ${sqlListWords(sets)}${where < 0 ? ' in every row' : ` where ${w}`}`, code: t, ...base };
|
|
468
|
+
}
|
|
469
|
+
if (up === 'DELETE' && isW(at(1), 'FROM') && isW(at(2))) {
|
|
470
|
+
let j = 2;
|
|
471
|
+
while (isP(at(j + 1), '.') && isW(at(j + 2))) j += 2;
|
|
472
|
+
const table = sqlWords(sqlBare(ctx.src.slice(at(2).s, at(j).e)));
|
|
473
|
+
if (ts.length === j + 1) return { kind: 'call', says: `Removes every row in ${table}`, code: t, ...base };
|
|
474
|
+
if (!isW(at(j + 1), 'WHERE') || topWord(ts, ['USING', 'RETURNING', 'OUTPUT', 'JOIN', 'FROM', 'ORDER', 'LIMIT'], j + 1) >= 0) return asCode(t, base);
|
|
475
|
+
const w = condWords(ctx.src.slice(at(j + 2).s, ts.at(-1).e), ctx);
|
|
476
|
+
return w ? { kind: 'call', says: `Removes ${table} where ${w}`, code: t, ...base } : asCode(t, base);
|
|
477
|
+
}
|
|
478
|
+
if (up === 'TRUNCATE') {
|
|
479
|
+
const k = isW(at(1), 'TABLE') ? 2 : 1;
|
|
480
|
+
let j = k;
|
|
481
|
+
while (isP(at(j + 1), '.') && isW(at(j + 2))) j += 2;
|
|
482
|
+
if (isW(at(k)) && ts.length === j + 1) return { kind: 'call', says: `Removes every row in ${sqlWords(sqlBare(ctx.src.slice(at(k).s, at(j).e)))}`, code: t, ...base };
|
|
483
|
+
return asCode(t, base);
|
|
484
|
+
}
|
|
485
|
+
return asCode(t, base);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Index of the `)` matching the `(` at ts[k], or -1. */
|
|
489
|
+
function matchParen(ts, k) {
|
|
490
|
+
for (let d = 0, j = k; j < ts.length; j++) { if (isP(ts[j], '(')) d++; else if (isP(ts[j], ')') && --d === 0) return j; }
|
|
491
|
+
return -1;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** SELECT … INTO targets FROM table WHERE … (PL/pgSQL, MySQL); anything else is a result or code. */
|
|
495
|
+
function selectStatement(ts, t, base, ctx) {
|
|
496
|
+
const into = topWord(ts, ['INTO']);
|
|
497
|
+
const from = topWord(ts, ['FROM']);
|
|
498
|
+
if (ctx.dialect === 'tsql') {
|
|
499
|
+
// SELECT @a = x, @b = y (no FROM) sets values; SELECT … INTO #t makes a table; other SELECTs send rows back.
|
|
500
|
+
if (from < 0 && into < 0) {
|
|
501
|
+
const sets = [];
|
|
502
|
+
for (const p of splitComma(ts.slice(1))) {
|
|
503
|
+
if (!(p[0]?.t === 'word' && /^@/.test(p[0].v) && isP(p[1], '='))) return asCode(t, base);
|
|
504
|
+
const v = valueWords(ctx.src.slice(p[2]?.s ?? 0, p.at(-1).e), ctx, p.slice(2));
|
|
505
|
+
if (!p[2] || !v) return asCode(t, base);
|
|
506
|
+
sets.push(`${targetWords(p[0].v, ctx)} to ${v}`);
|
|
507
|
+
}
|
|
508
|
+
return sets.length ? { kind: 'set', says: `Sets ${sqlListWords(sets)}`, code: t, ...base } : asCode(t, base);
|
|
509
|
+
}
|
|
510
|
+
return asCode(t, base);
|
|
511
|
+
}
|
|
512
|
+
if (into < 0) return asCode(t, base);
|
|
513
|
+
if (into > from && from > 0) return asCode(t, base); // MySQL's INTO at the end
|
|
514
|
+
const strict = isW(ts[into + 1], 'STRICT') ? 1 : 0;
|
|
515
|
+
const targetTs = ts.slice(into + 1 + strict, from < 0 ? ts.length : from);
|
|
516
|
+
const targets = splitComma(targetTs).map((p) => targetWords(ctx.src.slice(p[0].s, p.at(-1).e), ctx));
|
|
517
|
+
const cols = splitComma(ts.slice(1, into));
|
|
518
|
+
if (!targets.length || !targets.every(Boolean) || !cols.length) return asCode(t, base);
|
|
519
|
+
if (from < 0) {
|
|
520
|
+
// SELECT x INTO v (no table): sets v to x.
|
|
521
|
+
if (cols.length !== targets.length) return asCode(t, base);
|
|
522
|
+
const vals = cols.map((p) => valueWords(ctx.src.slice(p[0].s, p.at(-1).e), ctx, p));
|
|
523
|
+
if (!vals.every(Boolean)) return asCode(t, base);
|
|
524
|
+
return { kind: 'set', says: `Sets ${sqlListWords(targets.map((x, k) => `${x} to ${vals[k]}`))}`, code: t, ...base };
|
|
525
|
+
}
|
|
526
|
+
// FROM one table [alias] [WHERE …] and nothing else.
|
|
527
|
+
let j = from + 1;
|
|
528
|
+
if (!isW(ts[j])) return asCode(t, base);
|
|
529
|
+
while (isP(ts[j + 1], '.') && isW(ts[j + 2])) j += 2;
|
|
530
|
+
const table = sqlWords(sqlBare(ctx.src.slice(ts[from + 1].s, ts[j].e)));
|
|
531
|
+
let k = j + 1;
|
|
532
|
+
if (isW(ts[k], 'AS')) k++;
|
|
533
|
+
if (isW(ts[k]) && !isW(ts[k], 'WHERE')) k++;
|
|
534
|
+
if (k < ts.length && !isW(ts[k], 'WHERE')) return asCode(t, base);
|
|
535
|
+
if (topWord(ts, ['GROUP', 'ORDER', 'LIMIT', 'HAVING', 'UNION', 'OFFSET', 'FOR', 'JOIN', 'WINDOW', 'FETCH'], from) >= 0) return asCode(t, base);
|
|
536
|
+
const w = k < ts.length ? condWords(ctx.src.slice(ts[k + 1].s, ts.at(-1).e), ctx) : '';
|
|
537
|
+
if (w == null) return asCode(t, base);
|
|
538
|
+
// Each column: a plain column name, or count(*) and friends.
|
|
539
|
+
const colWords = cols.map((p) => {
|
|
540
|
+
if (p.length === 1 && isW(p[0])) return sqlWords(unq(p[0].v));
|
|
541
|
+
if (p.length === 3 && isW(p[0]) && isP(p[1], '.') && isW(p[2])) return sqlWords(unq(p[2].v));
|
|
542
|
+
const agg = ctx.src.slice(p[0].s, p.at(-1).e).match(/^(count|sum|avg|min|max)\s*\(\s*(\*|[\w.]+)\s*\)$/i);
|
|
543
|
+
if (agg) { const what = agg[2] === '*' ? 'rows' : sqlWords(sqlBare(agg[2])); return { count: `how many ${what}`, sum: `the total of ${what}`, avg: `the average ${what}`, min: `the lowest ${what}`, max: `the highest ${what}` }[agg[1].toLowerCase()]; }
|
|
544
|
+
return null;
|
|
545
|
+
});
|
|
546
|
+
if (!colWords.every(Boolean) || colWords.length !== targets.length) return asCode(t, base);
|
|
547
|
+
const where = w ? ` where ${w}` : '';
|
|
548
|
+
const same = colWords.every((c, n) => c === targets[n]);
|
|
549
|
+
return { kind: 'call', callee: 'find', says: same ? `Finds ${sqlListWords(targets)} in the ${table}${where}` : `Finds ${sqlListWords(colWords)} in the ${table}${where}, as ${sqlListWords(targets)}`, code: t, ...base };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** INSERT INTO table (cols) VALUES (…) | SELECT …; anything with ON CONFLICT, RETURNING, OUTPUT is code. */
|
|
553
|
+
function insertStatement(ts, t, base, ctx) {
|
|
554
|
+
if (!isW(ts[1], 'INTO') || !isW(ts[2])) return asCode(t, base);
|
|
555
|
+
if (topWord(ts, ['ON', 'RETURNING', 'OUTPUT', 'IGNORE']) >= 0) return asCode(t, base);
|
|
556
|
+
let j = 2;
|
|
557
|
+
while (isP(ts[j + 1], '.') && isW(ts[j + 2])) j += 2;
|
|
558
|
+
const table = sqlBare(ctx.src.slice(ts[2].s, ts[j].e));
|
|
559
|
+
let k = j + 1, cols = [];
|
|
560
|
+
if (isP(ts[k], '(')) {
|
|
561
|
+
const close = matchParen(ts, k);
|
|
562
|
+
if (close < 0) return asCode(t, base);
|
|
563
|
+
cols = splitComma(ts.slice(k + 1, close)).map((p) => (p.length === 1 && isW(p[0]) ? sqlWords(unq(p[0].v)) : null));
|
|
564
|
+
if (!cols.every(Boolean)) return asCode(t, base);
|
|
565
|
+
k = close + 1;
|
|
566
|
+
}
|
|
567
|
+
const withCols = cols.length ? ` with ${sqlListWords(cols)}` : '';
|
|
568
|
+
if (isW(ts[k], 'VALUES')) {
|
|
569
|
+
const rows = splitComma(ts.slice(k + 1));
|
|
570
|
+
return { kind: 'call', says: rows.length === 1 ? `Records a new ${sqlSingular(sqlWords(table))}${withCols}` : `Records ${rows.length} new ${sqlWords(table)}${withCols}`, code: t, ...base };
|
|
571
|
+
}
|
|
572
|
+
if (isW(ts[k], 'SELECT', 'WITH')) return { kind: 'call', says: `Records in ${sqlWords(table)} the rows a query finds${withCols}`, code: t, ...base };
|
|
573
|
+
return asCode(t, base);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// ── The block parser ─────────────────────────────────────────────────────────────────────────────────────
|
|
577
|
+
|
|
578
|
+
// T-SQL has no statement terminator: a statement ends where the next one starts.
|
|
579
|
+
const TSQL_START = new Set('SELECT INSERT UPDATE DELETE SET DECLARE IF ELSE WHILE BEGIN END RETURN EXEC EXECUTE PRINT RAISERROR THROW CREATE DROP ALTER TRUNCATE MERGE OPEN FETCH CLOSE DEALLOCATE BREAK CONTINUE GOTO WAITFOR USE GRANT REVOKE DENY COMMIT ROLLBACK SAVE DBCC BULK BACKUP RESTORE KILL RECONFIGURE CHECKPOINT WITH'.split(' '));
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* The steps of a routine body: tokens toks[from, to), parsed as blocks. ctx: { src, lineAt, dialect ('pg' | 'mysql'
|
|
583
|
+
* | 'tsql'), routine ('function' | 'procedure'), setof, trigger }.
|
|
584
|
+
*/
|
|
585
|
+
export function bodySteps(toks, ctx, opts = {}) {
|
|
586
|
+
let i = 0;
|
|
587
|
+
const n = toks.length;
|
|
588
|
+
const labels = [];
|
|
589
|
+
const peek = (k = 0) => toks[i + k];
|
|
590
|
+
const lineOf = (tok) => ctx.lineAt(tok.s);
|
|
591
|
+
const baseOf = (a, b) => ({ line: lineOf(toks[a]), span: { startLine: lineOf(toks[a]), endLine: lineOf(toks[Math.max(a, b - 1)]) } });
|
|
592
|
+
const textOf = (a, b) => ctx.src.slice(toks[a].s, toks[b - 1].e);
|
|
593
|
+
const semi = ctx.dialect !== 'tsql';
|
|
594
|
+
const expect = (cond, what) => { if (!cond) throw new Unmatched(`${what} (line ${peek() ? lineOf(peek()) : 'end'})`); };
|
|
595
|
+
const skipSemis = () => { while (isP(peek(), ';')) i++; };
|
|
596
|
+
|
|
597
|
+
/** End of a simple statement starting at a: index of its last token + 1 (i is not moved). */
|
|
598
|
+
const simpleEnd = (a) => {
|
|
599
|
+
let d = 0, cs = 0;
|
|
600
|
+
const head = toks[a].up;
|
|
601
|
+
let seenSelect = false, seenSet = false, seenExec = false, cursorFor = false;
|
|
602
|
+
for (let j = a; j < n; j++) {
|
|
603
|
+
const x = toks[j];
|
|
604
|
+
if (isP(x, '(') || isP(x, '[')) { d++; continue; }
|
|
605
|
+
if (isP(x, ')') || isP(x, ']')) { d--; continue; }
|
|
606
|
+
if (d > 0) continue;
|
|
607
|
+
if (isP(x, ';')) return j;
|
|
608
|
+
if (!isW(x)) continue;
|
|
609
|
+
if (x.up === 'CASE') { cs++; continue; }
|
|
610
|
+
if (x.up === 'END') { if (cs > 0) { cs--; continue; } if (j > a) return j; continue; }
|
|
611
|
+
if (cs > 0 || j === a) continue;
|
|
612
|
+
// T-SQL RETURN (…) / a function's RETURN SELECT …: the value is part of the RETURN.
|
|
613
|
+
if (!semi && head === 'RETURN' && j === a + 1 && (isP(x, '(') || (ctx.routine === 'function' && isW(x, 'SELECT', 'WITH')))) continue;
|
|
614
|
+
if (semi) {
|
|
615
|
+
if (x.up === 'ELSIF' || x.up === 'ELSEIF' || x.up === 'ELSE' || x.up === 'UNTIL') return j;
|
|
616
|
+
if (x.up === 'EXCEPTION' && isW(toks[j + 1], 'WHEN') && !isW(toks[j - 1], 'RAISE')) return j;
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
// T-SQL: the next statement starts here unless this word continues the current one.
|
|
620
|
+
const prev = toks[j - 1];
|
|
621
|
+
if (x.up === 'FOR' && head === 'DECLARE') cursorFor = true;
|
|
622
|
+
if (!TSQL_START.has(x.up)) continue;
|
|
623
|
+
if (isP(toks[j + 1], '(') && x.up === 'UPDATE') continue; // IF UPDATE(col)
|
|
624
|
+
if (isP(prev, '.') || isP(toks[j + 1], '.')) continue; // a name: x.[delete]
|
|
625
|
+
if (isP(prev, ':') || isP(prev, '::')) continue;
|
|
626
|
+
if (head === 'MERGE') continue;
|
|
627
|
+
if (x.up === 'SELECT') {
|
|
628
|
+
if (isW(prev, 'UNION', 'ALL', 'EXCEPT', 'INTERSECT', 'DISTINCT')) continue;
|
|
629
|
+
if (!seenSelect && (head === 'INSERT' || head === 'WITH' || (head === 'DECLARE' && cursorFor) || head === 'CREATE' || head === 'GRANT' || head === 'REVOKE' || head === 'DENY')) { seenSelect = true; continue; }
|
|
630
|
+
return j;
|
|
631
|
+
}
|
|
632
|
+
if (x.up === 'SET' && !seenSet && (head === 'UPDATE' || head === 'ALTER')) { seenSet = true; continue; }
|
|
633
|
+
if ((x.up === 'EXEC' || x.up === 'EXECUTE') && !seenExec && (head === 'INSERT' || head === 'GRANT' || head === 'REVOKE' || head === 'DENY' || isW(prev, 'WITH', 'AS'))) { seenExec = true; continue; }
|
|
634
|
+
if ((x.up === 'INSERT' || x.up === 'UPDATE' || x.up === 'DELETE') && (head === 'WITH' || head === 'GRANT' || head === 'REVOKE' || head === 'DENY' || isW(prev, 'FOR', 'ON', 'OF', 'AFTER', 'INSTEAD', ','))) { if (head === 'WITH') seenSelect = true; continue; }
|
|
635
|
+
if (x.up === 'IF' && isW(toks[j + 1], 'EXISTS', 'NOT')) continue; // DROP TABLE IF EXISTS
|
|
636
|
+
if (x.up === 'WITH') { if (isW(toks[j + 1]) && isW(toks[j + 2], 'AS') && isP(toks[j + 3], '(')) return j; continue; }
|
|
637
|
+
if (x.up === 'FETCH' && isW(prev, 'ROWS', 'ROW')) continue;
|
|
638
|
+
if (x.up === 'CREATE' && head === 'WITH') continue;
|
|
639
|
+
if (x.up === 'USE' && head !== 'USE') continue;
|
|
640
|
+
if (x.up === 'BEGIN' && head === 'WITH') return j;
|
|
641
|
+
if ((x.up === 'COMMIT' || x.up === 'ROLLBACK' || x.up === 'SAVE') && isW(prev, 'ON')) continue;
|
|
642
|
+
if ((x.up === 'DROP' || x.up === 'ALTER' || x.up === 'CREATE') && (head === 'GRANT' || head === 'REVOKE' || head === 'DENY' || head === 'ALTER')) continue;
|
|
643
|
+
return j;
|
|
644
|
+
}
|
|
645
|
+
return n;
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
/** A condition from i up to (not including) a token that `stop` accepts at top level; i moves to that token. */
|
|
649
|
+
const condUntil = (stop) => {
|
|
650
|
+
const a = i;
|
|
651
|
+
let d = 0, cs = 0;
|
|
652
|
+
for (; i < n; i++) {
|
|
653
|
+
const x = toks[i];
|
|
654
|
+
if (isP(x, '(') || isP(x, '[')) { d++; continue; }
|
|
655
|
+
if (isP(x, ')') || isP(x, ']')) { d--; continue; }
|
|
656
|
+
if (d > 0) continue;
|
|
657
|
+
if (isW(x, 'CASE')) { cs++; continue; }
|
|
658
|
+
if (isW(x, 'END') && cs > 0) { cs--; continue; }
|
|
659
|
+
if (cs === 0 && i > a && stop(x, i)) break;
|
|
660
|
+
}
|
|
661
|
+
expect(i > a && i < n, 'a condition without its end');
|
|
662
|
+
return [a, i];
|
|
663
|
+
};
|
|
664
|
+
|
|
665
|
+
const branch = (a, b, children, otherwise, extraLine = null) => {
|
|
666
|
+
const text = code(textOf(a, b));
|
|
667
|
+
const w = condWords(text, ctx);
|
|
668
|
+
return { kind: 'branch', says: `If ${w ?? asCodeWords(text, 400)}`, code: text, cond: text, ...baseOf(a, b), ...(extraLine ? { line: extraLine } : {}), children, ...(otherwise ? { otherwise } : {}) };
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
const jumpStep = (kind, label, a, b) => {
|
|
672
|
+
const l = label ? labels.findLast((x) => x.name.toLowerCase() === label.toLowerCase()) : labels.findLast((x) => x.kind === 'loop');
|
|
673
|
+
const base = baseOf(a, b);
|
|
674
|
+
const t = code(textOf(a, b));
|
|
675
|
+
if (kind === 'continue') return { kind: 'call', says: `Skips to the next round of the loop${label ? ` (${label})` : ''}`, code: t, jump: 'continue', ...base };
|
|
676
|
+
if (l && l.kind === 'body') return { kind: 'return', says: 'Stops here', code: t, ...base };
|
|
677
|
+
if (l && l.kind === 'block') return { kind: 'call', says: `Leaves the block ${label}`, code: t, jump: 'break', ...base };
|
|
678
|
+
return { kind: 'call', says: `Leaves the loop${label ? ` (${label})` : ''}`, code: t, jump: 'break', ...base };
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
const block = (stop) => {
|
|
682
|
+
const out = [];
|
|
683
|
+
for (;;) {
|
|
684
|
+
skipSemis();
|
|
685
|
+
const t = peek();
|
|
686
|
+
if (!t || stop(t)) return out;
|
|
687
|
+
const before = i;
|
|
688
|
+
out.push(...statement());
|
|
689
|
+
if (i === before) i++;
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
const endsWith = (...ws) => (t) => isW(t) && ws.includes(t.up);
|
|
693
|
+
|
|
694
|
+
/** END <word> [label] [;] */
|
|
695
|
+
const closeWith = (word, what) => {
|
|
696
|
+
expect(isW(peek(), 'END') && (!word || isW(peek(1), word)), `${what} without its END${word ? ` ${word}` : ''}`);
|
|
697
|
+
i += word ? 2 : 1;
|
|
698
|
+
if (isW(peek()) && !isW(peek(), 'IF', 'WHILE', 'ELSE', 'BEGIN', 'END') && semi && (isP(peek(1), ';') || !peek(1))) i++; // END LOOP label;
|
|
699
|
+
if (isP(peek(), ';')) i++;
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
const tsqlBody = () => {
|
|
703
|
+
// One statement, or BEGIN … END as a block of statements.
|
|
704
|
+
skipSemis();
|
|
705
|
+
if (isW(peek(), 'BEGIN') && !isW(peek(1), 'TRAN', 'TRANSACTION', 'DISTRIBUTED', 'TRY', 'CATCH')) {
|
|
706
|
+
i++;
|
|
707
|
+
const kids = block(endsWith('END'));
|
|
708
|
+
closeWith(null, 'BEGIN');
|
|
709
|
+
return kids;
|
|
710
|
+
}
|
|
711
|
+
return statement();
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
const loopStep = (says, a, b, label, bodyFn) => {
|
|
715
|
+
labels.push({ name: label ?? '', kind: 'loop' });
|
|
716
|
+
const kids = bodyFn();
|
|
717
|
+
labels.pop();
|
|
718
|
+
return { kind: 'loop', says, code: code(textOf(a, b)), ...baseOf(a, b), children: kids };
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
function statement(label = null) {
|
|
722
|
+
const a = i;
|
|
723
|
+
const t = peek();
|
|
724
|
+
// Labels: <<name>> (PL/pgSQL), name: (MySQL, T-SQL).
|
|
725
|
+
if (isP(t, '<<') && isW(peek(1)) && isP(peek(2), '>>')) { i += 3; return statement(peek(-2).v); }
|
|
726
|
+
if (isW(t) && isP(peek(1), ':') && !TSQL_START.has(t.up)) {
|
|
727
|
+
i += 2;
|
|
728
|
+
if (isW(peek(), 'BEGIN', 'LOOP', 'WHILE', 'REPEAT', 'FOR', 'FOREACH')) return statement(t.v);
|
|
729
|
+
return []; // a GOTO target
|
|
730
|
+
}
|
|
731
|
+
if (t.t === 'ver') {
|
|
732
|
+
// A versioned comment at the start of a statement: its statements, on the versions that run them.
|
|
733
|
+
i++;
|
|
734
|
+
const inner = lexSql(ctx.src, t.innerS, t.innerE, 'mysql');
|
|
735
|
+
let kids;
|
|
736
|
+
try { kids = bodySteps(inner, { ...ctx, depth: 1 }); } catch (err) { if (!(err instanceof Unmatched)) throw err; kids = [asCode(t.v, baseOf(a, a + 1))]; }
|
|
737
|
+
if (t.version == null) return kids;
|
|
738
|
+
const v = `${Math.floor(t.version / 10000)}.${Math.floor(t.version / 100) % 100}.${t.version % 100}`;
|
|
739
|
+
return [{ kind: 'branch', says: `If the MySQL server is version ${v} or later`, code: code(t.v), cond: `MySQL version >= ${v}`, ...baseOf(a, a + 1), children: kids }];
|
|
740
|
+
}
|
|
741
|
+
if (!isW(t)) { const e = simpleEnd(a); i = Math.max(e, a + 1); if (isP(peek(), ';')) i++; return [asCode(textOf(a, Math.max(e, a + 1)), baseOf(a, Math.max(e, a + 1)))]; }
|
|
742
|
+
const up = t.up;
|
|
743
|
+
|
|
744
|
+
if (up === 'IF' && semi) {
|
|
745
|
+
i++;
|
|
746
|
+
const [c0, c1] = condUntil((x) => isW(x, 'THEN'));
|
|
747
|
+
i++;
|
|
748
|
+
const step = branch(c0, c1, block(endsWith('ELSIF', 'ELSEIF', 'ELSE', 'END')));
|
|
749
|
+
step.line = lineOf(toks[a]);
|
|
750
|
+
let tail = step;
|
|
751
|
+
while (isW(peek(), 'ELSIF', 'ELSEIF')) {
|
|
752
|
+
const at = i;
|
|
753
|
+
i++;
|
|
754
|
+
const [e0, e1] = condUntil((x) => isW(x, 'THEN'));
|
|
755
|
+
i++;
|
|
756
|
+
const next = branch(e0, e1, block(endsWith('ELSIF', 'ELSEIF', 'ELSE', 'END')), null, lineOf(toks[at]));
|
|
757
|
+
tail.otherwise = [next]; tail = next;
|
|
758
|
+
}
|
|
759
|
+
if (isW(peek(), 'ELSE')) { tail.otherwiseLine = lineOf(peek()); i++; tail.otherwise = block(endsWith('END')); }
|
|
760
|
+
closeWith('IF', 'IF');
|
|
761
|
+
return [step];
|
|
762
|
+
}
|
|
763
|
+
if (up === 'IF' && !semi) {
|
|
764
|
+
i++;
|
|
765
|
+
const [c0, c1] = condUntil((x) => isW(x) && TSQL_START.has(x.up) && !(x.up === 'UPDATE' && isP(toks[i + 1], '(')) && !isP(toks[i - 1], '.'));
|
|
766
|
+
const kids = tsqlBody();
|
|
767
|
+
skipSemis();
|
|
768
|
+
const step = branch(c0, c1, kids);
|
|
769
|
+
step.line = lineOf(toks[a]);
|
|
770
|
+
if (isW(peek(), 'ELSE')) { step.otherwiseLine = lineOf(peek()); i++; step.otherwise = tsqlBody(); }
|
|
771
|
+
return [step];
|
|
772
|
+
}
|
|
773
|
+
if (up === 'CASE') {
|
|
774
|
+
// A CASE statement: each WHEN a question; with no ELSE, a value that matches no WHEN is an error.
|
|
775
|
+
i++;
|
|
776
|
+
let subject = null;
|
|
777
|
+
if (!isW(peek(), 'WHEN')) { const [s0, s1] = condUntil((x) => isW(x, 'WHEN')); subject = [s0, s1]; }
|
|
778
|
+
const arms = [];
|
|
779
|
+
while (isW(peek(), 'WHEN')) {
|
|
780
|
+
const at = i;
|
|
781
|
+
i++;
|
|
782
|
+
const [w0, w1] = condUntil((x) => isW(x, 'THEN'));
|
|
783
|
+
i++;
|
|
784
|
+
arms.push({ at, w0, w1, kids: block(endsWith('WHEN', 'ELSE', 'END')) });
|
|
785
|
+
}
|
|
786
|
+
expect(arms.length, 'CASE without WHEN');
|
|
787
|
+
let elseKids = null, elseLine = null;
|
|
788
|
+
if (isW(peek(), 'ELSE')) { elseLine = lineOf(peek()); i++; elseKids = block(endsWith('END')); }
|
|
789
|
+
closeWith(semi ? 'CASE' : null, 'CASE');
|
|
790
|
+
const steps = arms.map((arm) => {
|
|
791
|
+
let text;
|
|
792
|
+
if (subject) {
|
|
793
|
+
const subj = code(textOf(subject[0], subject[1]));
|
|
794
|
+
const vals = splitComma(toks.slice(arm.w0, arm.w1)).map((p) => code(ctx.src.slice(p[0].s, p.at(-1).e)));
|
|
795
|
+
text = vals.length === 1 ? `${subj} = ${vals[0]}` : `${subj} IN (${vals.join(', ')})`;
|
|
796
|
+
} else text = code(textOf(arm.w0, arm.w1));
|
|
797
|
+
const w = condWords(text, ctx);
|
|
798
|
+
return { kind: 'branch', says: `If ${w ?? asCodeWords(text, 400)}`, code: text, cond: text, line: lineOf(toks[arm.at]), span: { startLine: lineOf(toks[arm.at]), endLine: lineOf(toks[arm.w1 - 1]) }, children: arm.kids };
|
|
799
|
+
});
|
|
800
|
+
for (let k = 0; k < steps.length - 1; k++) steps[k].otherwise = [steps[k + 1]];
|
|
801
|
+
const last = steps.at(-1);
|
|
802
|
+
if (elseKids) { last.otherwise = elseKids; last.otherwiseLine = elseLine; }
|
|
803
|
+
else last.otherwise = [{ kind: 'fail', says: 'Fails with an error: no WHEN matched and there is no ELSE (case not found)', error: 'case not found', code: code(textOf(a, i)), line: lineOf(toks[a]) }];
|
|
804
|
+
return [steps[0]];
|
|
805
|
+
}
|
|
806
|
+
if (up === 'LOOP' && semi) {
|
|
807
|
+
i++;
|
|
808
|
+
const step = loopStep('Repeats until a step inside stops it', a, a + 1, label, () => block(endsWith('END')));
|
|
809
|
+
closeWith('LOOP', 'LOOP');
|
|
810
|
+
return [step];
|
|
811
|
+
}
|
|
812
|
+
if (up === 'WHILE') {
|
|
813
|
+
i++;
|
|
814
|
+
const [c0, c1] = semi ? condUntil((x) => isW(x, 'LOOP', 'DO')) : condUntil((x) => isW(x) && TSQL_START.has(x.up) && !isP(toks[i - 1], '.'));
|
|
815
|
+
const text = code(textOf(c0, c1));
|
|
816
|
+
const w = condWords(text, ctx);
|
|
817
|
+
if (semi) {
|
|
818
|
+
const kw = peek().up;
|
|
819
|
+
i++;
|
|
820
|
+
const step = loopStep(`While ${w ?? asCodeWords(text, 400)}`, a, c1 + 1, label, () => block(endsWith('END')));
|
|
821
|
+
closeWith(kw === 'DO' ? 'WHILE' : 'LOOP', 'WHILE');
|
|
822
|
+
return [step];
|
|
823
|
+
}
|
|
824
|
+
return [loopStep(`While ${w ?? asCodeWords(text, 400)}`, a, c1, label, () => tsqlBody())];
|
|
825
|
+
}
|
|
826
|
+
if (up === 'REPEAT' && ctx.dialect === 'mysql') {
|
|
827
|
+
i++;
|
|
828
|
+
labels.push({ name: label ?? '', kind: 'loop' });
|
|
829
|
+
const kids = block(endsWith('UNTIL'));
|
|
830
|
+
labels.pop();
|
|
831
|
+
expect(isW(peek(), 'UNTIL'), 'REPEAT without UNTIL');
|
|
832
|
+
i++;
|
|
833
|
+
const [c0, c1] = condUntil((x) => isW(x, 'END'));
|
|
834
|
+
const text = code(textOf(c0, c1));
|
|
835
|
+
const w = condWords(text, ctx);
|
|
836
|
+
closeWith('REPEAT', 'REPEAT');
|
|
837
|
+
return [{ kind: 'loop', says: `Runs once, then repeats until ${w ?? asCodeWords(text, 400)}`, code: code(textOf(a, c1)), ...baseOf(a, c1), children: kids }];
|
|
838
|
+
}
|
|
839
|
+
if ((up === 'FOR' || up === 'FOREACH') && ctx.dialect === 'pg') {
|
|
840
|
+
i++;
|
|
841
|
+
const [h0, h1] = condUntil((x) => isW(x, 'LOOP'));
|
|
842
|
+
i++;
|
|
843
|
+
const head = toks.slice(h0, h1);
|
|
844
|
+
let says;
|
|
845
|
+
const inAt = head.findIndex((x) => isW(x, 'IN'));
|
|
846
|
+
const vars = inAt > 0 ? splitComma(head.slice(0, inAt)).map((p) => (p.length === 1 ? plainName(unq(p[0].v)) : null)) : [null];
|
|
847
|
+
const what = head.slice(inAt + 1);
|
|
848
|
+
const dots = what.findIndex((x) => isP(x, '..'));
|
|
849
|
+
if (!vars.every(Boolean)) says = `Repeats for ${asCodeWords(code(textOf(h0, h1)), 400)}`;
|
|
850
|
+
else if (up === 'FOREACH') {
|
|
851
|
+
const arr = what[0] && isW(what[0], 'ARRAY') ? targetWords(ctx.src.slice(what[1].s, what.at(-1).e), ctx) : null;
|
|
852
|
+
const slice = head.some((x) => isW(x, 'SLICE'));
|
|
853
|
+
says = arr && !slice ? `For each ${vars.join(' and ')} in ${arr}` : `Repeats for ${asCodeWords(code(textOf(h0, h1)), 400)}`;
|
|
854
|
+
} else if (dots > 0) {
|
|
855
|
+
let k = 0;
|
|
856
|
+
const reverse = isW(what[0], 'REVERSE');
|
|
857
|
+
if (reverse) k = 1;
|
|
858
|
+
const byAt = what.findIndex((x) => isW(x, 'BY'));
|
|
859
|
+
const lo = valueWords(ctx.src.slice(what[k].s, what[dots - 1].e), ctx, what.slice(k, dots));
|
|
860
|
+
const hiTs = what.slice(dots + 1, byAt < 0 ? what.length : byAt);
|
|
861
|
+
const hi = hiTs.length ? valueWords(ctx.src.slice(hiTs[0].s, hiTs.at(-1).e), ctx, hiTs) : null;
|
|
862
|
+
const by = byAt < 0 ? null : valueWords(ctx.src.slice(what[byAt + 1].s, what.at(-1).e), ctx, what.slice(byAt + 1));
|
|
863
|
+
says = lo && hi && (byAt < 0 || by) ? `Counts ${vars[0]} from ${lo} ${reverse ? 'down ' : ''}to ${hi}${by ? `, in steps of ${by}` : ''}` : `Repeats for ${asCodeWords(code(textOf(h0, h1)), 400)}`;
|
|
864
|
+
} else if (isW(what[0], 'EXECUTE')) says = `For each row (${vars.join(', ')}) of a query built when it runs`;
|
|
865
|
+
else if (isW(what[0], 'SELECT', 'WITH', 'VALUES', 'TABLE')) says = `For each row (${vars.join(', ')}) the query finds`;
|
|
866
|
+
else says = `Repeats for ${asCodeWords(code(textOf(h0, h1)), 400)}`;
|
|
867
|
+
const step = loopStep(says, a, h1 + 1, label, () => block(endsWith('END')));
|
|
868
|
+
closeWith('LOOP', 'FOR');
|
|
869
|
+
return [step];
|
|
870
|
+
}
|
|
871
|
+
if ((up === 'EXIT' || up === 'CONTINUE' || up === 'LEAVE' || up === 'ITERATE' || up === 'BREAK') && (semi || up === 'BREAK' || up === 'CONTINUE')) {
|
|
872
|
+
const e = simpleEnd(a);
|
|
873
|
+
const ts = toks.slice(a, e);
|
|
874
|
+
i = e;
|
|
875
|
+
if (isP(peek(), ';')) i++;
|
|
876
|
+
const kind = up === 'CONTINUE' || up === 'ITERATE' ? 'continue' : 'break';
|
|
877
|
+
const lab = isW(ts[1]) && !isW(ts[1], 'WHEN') ? ts[1].v : null;
|
|
878
|
+
const when = ts.findIndex((x) => isW(x, 'WHEN'));
|
|
879
|
+
const jump = jumpStep(kind, lab, a, e);
|
|
880
|
+
if (when > 0 && ctx.dialect === 'pg') return [branch(a + when + 1, e, [jump])];
|
|
881
|
+
return [jump];
|
|
882
|
+
}
|
|
883
|
+
if (up === 'BEGIN') {
|
|
884
|
+
if (!semi && isW(peek(1), 'TRAN', 'TRANSACTION', 'DISTRIBUTED')) { const e = simpleEnd(a + 1); i = e; if (isP(peek(), ';')) i++; return [asCode(textOf(a, e), baseOf(a, e))]; }
|
|
885
|
+
if (!semi && isW(peek(1), 'TRY')) {
|
|
886
|
+
i += 2;
|
|
887
|
+
const was = ctx.inTry; ctx.inTry = true;
|
|
888
|
+
const kids = block(endsWith('END'));
|
|
889
|
+
ctx.inTry = was;
|
|
890
|
+
closeWith('TRY', 'BEGIN TRY');
|
|
891
|
+
skipSemis();
|
|
892
|
+
expect(isW(peek(), 'BEGIN') && isW(peek(1), 'CATCH'), 'BEGIN TRY without BEGIN CATCH');
|
|
893
|
+
const hLine = lineOf(peek());
|
|
894
|
+
i += 2;
|
|
895
|
+
const handler = block(endsWith('END'));
|
|
896
|
+
closeWith('CATCH', 'BEGIN CATCH');
|
|
897
|
+
return [{ kind: 'try', says: 'Tries these steps and handles any error', code: 'BEGIN TRY', ...baseOf(a, a + 2), children: kids, handlers: [{ says: 'If anything goes wrong', line: hLine, steps: handler }] }];
|
|
898
|
+
}
|
|
899
|
+
i++;
|
|
900
|
+
if (semi && isW(peek(), 'ATOMIC')) i++;
|
|
901
|
+
const top = labels.length === 0 && ctx.depth === 0;
|
|
902
|
+
labels.push({ name: label ?? '', kind: top ? 'body' : 'block' });
|
|
903
|
+
ctx.depth++;
|
|
904
|
+
const kids = block(endsWith('END', 'EXCEPTION'));
|
|
905
|
+
let handlers = null;
|
|
906
|
+
if (ctx.dialect === 'pg' && isW(peek(), 'EXCEPTION')) {
|
|
907
|
+
i++;
|
|
908
|
+
handlers = [];
|
|
909
|
+
while (isW(peek(), 'WHEN')) {
|
|
910
|
+
const hAt = i;
|
|
911
|
+
i++;
|
|
912
|
+
const [c0, c1] = condUntil((x) => isW(x, 'THEN'));
|
|
913
|
+
i++;
|
|
914
|
+
const names = toks.slice(c0, c1).filter((x) => !isW(x, 'OR', 'SQLSTATE')).map((x) => (x.t === 'str' ? `error ${strText(x)}` : sqlWords(x.v)));
|
|
915
|
+
const any = toks.slice(c0, c1).some((x) => isW(x, 'OTHERS'));
|
|
916
|
+
handlers.push({ says: any ? 'If anything goes wrong' : `If ${names.join(' or ')} goes wrong`, line: lineOf(toks[hAt]), steps: block(endsWith('WHEN', 'END')) });
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
ctx.depth--;
|
|
920
|
+
labels.pop();
|
|
921
|
+
closeWith(null, 'BEGIN');
|
|
922
|
+
if (handlers) return [{ kind: 'try', says: 'Tries these steps and handles any error', code: 'BEGIN', ...baseOf(a, a + 1), children: kids, handlers }];
|
|
923
|
+
return kids;
|
|
924
|
+
}
|
|
925
|
+
if (up === 'DECLARE') {
|
|
926
|
+
if (ctx.dialect === 'pg') {
|
|
927
|
+
// The declaration section, up to its BEGIN: a starting value is a step; a plain declaration is not.
|
|
928
|
+
i++;
|
|
929
|
+
const out = [];
|
|
930
|
+
while (peek() && !isW(peek(), 'BEGIN')) {
|
|
931
|
+
const d0 = i;
|
|
932
|
+
let d = 0;
|
|
933
|
+
while (peek() && !(d === 0 && isP(peek(), ';'))) { if (isP(peek(), '(')) d++; else if (isP(peek(), ')')) d--; i++; }
|
|
934
|
+
const ts = toks.slice(d0, i);
|
|
935
|
+
if (isP(peek(), ';')) i++;
|
|
936
|
+
if (!ts.length || isW(ts[1], 'CURSOR', 'ALIAS') || isW(ts[0], 'DECLARE')) continue;
|
|
937
|
+
const at = ts.findIndex((x) => isP(x, ':=') || isP(x, '=') || isW(x, 'DEFAULT'));
|
|
938
|
+
if (at < 0) continue;
|
|
939
|
+
const target = targetWords(ts[0].v, ctx);
|
|
940
|
+
const vts = ts.slice(at + 1);
|
|
941
|
+
const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
|
|
942
|
+
out.push(target && v ? { kind: 'set', says: `Sets ${setPair(target, v, ts[0].v, ctx.src.slice(vts[0].s, vts.at(-1).e))}`, code: code(textOf(d0, d0 + ts.length)), ...baseOf(d0, d0 + ts.length) } : asCode(textOf(d0, d0 + ts.length), baseOf(d0, d0 + ts.length)));
|
|
943
|
+
}
|
|
944
|
+
return out;
|
|
945
|
+
}
|
|
946
|
+
if (ctx.dialect === 'mysql' && isW(peek(1), 'CONTINUE', 'EXIT', 'UNDO') && isW(peek(2), 'HANDLER') && isW(peek(3), 'FOR')) {
|
|
947
|
+
const kind = peek(1).up;
|
|
948
|
+
i += 4;
|
|
949
|
+
const conds = [];
|
|
950
|
+
for (;;) {
|
|
951
|
+
if (isW(peek(), 'NOT') && isW(peek(1), 'FOUND')) { conds.push('no row is found'); i += 2; }
|
|
952
|
+
else if (isW(peek(), 'SQLEXCEPTION')) { conds.push('an error happens'); i++; }
|
|
953
|
+
else if (isW(peek(), 'SQLWARNING')) { conds.push('a warning happens'); i++; }
|
|
954
|
+
else if (isW(peek(), 'SQLSTATE')) { i++; if (isW(peek(), 'VALUE')) i++; conds.push(`error state "${peek()?.t === 'str' ? strText(peek()) : peek()?.v}" happens`); i++; }
|
|
955
|
+
else if (peek()?.t === 'num') { conds.push(`MySQL error ${peek().v} happens`); i++; }
|
|
956
|
+
else if (isW(peek())) { conds.push(`${sqlWords(peek().v)} happens`); i++; }
|
|
957
|
+
else break;
|
|
958
|
+
if (isP(peek(), ',')) { i++; continue; }
|
|
959
|
+
break;
|
|
960
|
+
}
|
|
961
|
+
const h0 = i;
|
|
962
|
+
const was = ctx.depth; ctx.depth = 1; // a handler's BEGIN is its own block, not the body
|
|
963
|
+
const kids = statement();
|
|
964
|
+
ctx.depth = was;
|
|
965
|
+
const simple = kids.length === 1 && kids[0].kind === 'set';
|
|
966
|
+
const after = kind === 'CONTINUE' ? 'then carries on after the statement that caused it' : 'then leaves the block it is declared in';
|
|
967
|
+
const base = baseOf(a, Math.max(h0, i));
|
|
968
|
+
if (simple) return [{ kind: 'call', says: `From here on, whenever ${conds.join(' or ')}: ${lower1(kids[0].says)}, ${after}`, code: code(textOf(a, i)), ...base }];
|
|
969
|
+
return [asCode(textOf(a, i), base)];
|
|
970
|
+
}
|
|
971
|
+
// MySQL DECLARE a, b INT DEFAULT 0 / T-SQL DECLARE @a INT = 0, @b INT: a starting value is a step.
|
|
972
|
+
const e = simpleEnd(a);
|
|
973
|
+
const ts = toks.slice(a + 1, e);
|
|
974
|
+
i = e;
|
|
975
|
+
if (isP(peek(), ';')) i++;
|
|
976
|
+
if (ctx.dialect === 'mysql') {
|
|
977
|
+
const def = topWord(ts, ['DEFAULT']);
|
|
978
|
+
if (def < 0 || isW(ts[1], 'CURSOR', 'CONDITION')) return [];
|
|
979
|
+
const names = [];
|
|
980
|
+
for (let k = 0; k < ts.length && isW(ts[k]); k += 2) { names.push(ts[k].v); if (!isP(ts[k + 1], ',')) break; }
|
|
981
|
+
const vts = ts.slice(def + 1);
|
|
982
|
+
const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
|
|
983
|
+
const targets = names.map((x) => targetWords(x, ctx));
|
|
984
|
+
if (!v || !targets.every(Boolean)) return [asCode(textOf(a, e), baseOf(a, e))];
|
|
985
|
+
return [{ kind: 'set', says: `Sets ${sqlListWords(targets)} to ${v}`, code: code(textOf(a, e)), ...baseOf(a, e) }];
|
|
986
|
+
}
|
|
987
|
+
if (isW(ts[1], 'CURSOR')) return [];
|
|
988
|
+
const sets = [];
|
|
989
|
+
for (const p of splitComma(ts)) {
|
|
990
|
+
const eq = p.findIndex((x) => isP(x, '='));
|
|
991
|
+
if (eq < 0) continue;
|
|
992
|
+
const target = targetWords(p[0].v, ctx);
|
|
993
|
+
const vts = p.slice(eq + 1);
|
|
994
|
+
const v = vts.length ? valueWords(ctx.src.slice(vts[0].s, vts.at(-1).e), ctx, vts) : null;
|
|
995
|
+
if (!target || !v) return [asCode(textOf(a, e), baseOf(a, e))];
|
|
996
|
+
sets.push(setPair(target, v, p[0].v, ctx.src.slice(vts[0].s, vts.at(-1).e)));
|
|
997
|
+
}
|
|
998
|
+
return sets.length ? [{ kind: 'set', says: `Sets ${sqlListWords(sets)}`, code: code(textOf(a, e)), ...baseOf(a, e) }] : [];
|
|
999
|
+
}
|
|
1000
|
+
if (up === 'NULL' && semi) { i++; if (isP(peek(), ';')) i++; return []; } // PL/pgSQL's "do nothing"
|
|
1001
|
+
if (up === 'GOTO') { const e = simpleEnd(a); i = e; if (isP(peek(), ';')) i++; return [{ kind: 'call', says: `Jumps to ${toks[a + 1]?.v ?? 'a label'}`, code: code(textOf(a, e)), jump: 'break', ...baseOf(a, e) }]; }
|
|
1002
|
+
if (!semi && (up === 'ELSE' || up === 'END')) throw new Unmatched(`${up} without its IF or BEGIN (line ${lineOf(t)})`);
|
|
1003
|
+
if (semi && (up === 'ELSE' || up === 'ELSIF' || up === 'ELSEIF' || up === 'WHEN' || up === 'UNTIL' || up === 'EXCEPTION')) throw new Unmatched(`${up} outside its block (line ${lineOf(t)})`);
|
|
1004
|
+
if (semi && up === 'END' && !ctx.allowEnd) throw new Unmatched(`END without its BEGIN (line ${lineOf(t)})`);
|
|
1005
|
+
|
|
1006
|
+
// A simple statement.
|
|
1007
|
+
const e = Math.max(simpleEnd(a), a + 1);
|
|
1008
|
+
i = e;
|
|
1009
|
+
if (isP(peek(), ';')) i++;
|
|
1010
|
+
const step = statementStep(toks.slice(a, e), textOf(a, e), baseOf(a, e), ctx);
|
|
1011
|
+
return Array.isArray(step) ? step : [step];
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
ctx.depth = ctx.depth ?? 0;
|
|
1015
|
+
if (opts.one) { skipSemis(); const steps = statement(); return { steps, used: Math.max(i, 1) }; }
|
|
1016
|
+
return block(() => false);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
export { Unmatched };
|
|
1020
|
+
|
|
1021
|
+
// ── Routines: header, inputs, body ───────────────────────────────────────────────────────────────────────
|
|
1022
|
+
|
|
1023
|
+
/** The dialect a file is written in, from its signs: dollar quotes (PostgreSQL), DELIMITER (MySQL), GO and @ (T-SQL). */
|
|
1024
|
+
export function sqlDialect(src) {
|
|
1025
|
+
if (/^\s*DELIMITER\s+\S+/im.test(src) || /\bDEFINER\s*=\s*['`"]?\w/i.test(src) || /\bSIGNAL\s+SQLSTATE\b/i.test(src)) return 'mysql';
|
|
1026
|
+
if (/\bAS\s+\$\w*\$/i.test(src) || /\$\w*\$\s*LANGUAGE\b/i.test(src) || /\bLANGUAGE\s+'?plpgsql\b/i.test(src) || /\bDO\s+\$\w*\$/i.test(src)) return 'pg';
|
|
1027
|
+
if (/^\s*GO\s*$/im.test(src) || /\b(?:PROC|PROCEDURE|FUNCTION)\s+[\w.[\]]+\s*\(?\s*@\w/i.test(src) || /\bAS\s+BEGIN\b/i.test(src) || /\bSET\s+NOCOUNT\s+ON\b/i.test(src)) return 'tsql';
|
|
1028
|
+
return 'pg';
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const ROUTINE_WORDS = ['FUNCTION', 'PROCEDURE', 'PROC'];
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* Every routine in a file: { name, line, endLine, kind, inputs, returns, steps, unread? }. `toks` are the file's
|
|
1035
|
+
* tokens (lexSql with the file's dialect).
|
|
1036
|
+
*/
|
|
1037
|
+
export function sqlRoutines(src, lineAt, dialect = sqlDialect(src)) {
|
|
1038
|
+
const toks = lexSql(src, 0, src.length, dialect);
|
|
1039
|
+
const out = [];
|
|
1040
|
+
const lineOf = (k) => lineAt(toks[Math.min(k, toks.length - 1)].s);
|
|
1041
|
+
for (let k = 0; k < toks.length; k++) {
|
|
1042
|
+
const start = k;
|
|
1043
|
+
let j = k;
|
|
1044
|
+
if (isW(toks[j], 'CREATE')) {
|
|
1045
|
+
j++;
|
|
1046
|
+
if (isW(toks[j], 'OR') && isW(toks[j + 1], 'REPLACE', 'ALTER')) j += 2;
|
|
1047
|
+
if (isW(toks[j], 'DEFINER') && isP(toks[j + 1], '=')) { j += 2; while (toks[j] && !isW(toks[j], ...ROUTINE_WORDS, 'AGGREGATE', 'SQL', 'TRIGGER', 'EVENT', 'VIEW') && j < k + 8) j++; }
|
|
1048
|
+
if (isW(toks[j], 'SQL') && isW(toks[j + 1], 'SECURITY')) j += 3;
|
|
1049
|
+
if (isW(toks[j], 'AGGREGATE')) j++;
|
|
1050
|
+
if (!isW(toks[j], ...ROUTINE_WORDS)) continue;
|
|
1051
|
+
} else if (isW(toks[k], 'ALTER') && dialect === 'tsql' && isW(toks[k + 1], ...ROUTINE_WORDS)) j = k + 1;
|
|
1052
|
+
else continue;
|
|
1053
|
+
const kindWord = toks[j].up;
|
|
1054
|
+
j++;
|
|
1055
|
+
// The name: a.b.c, quoted parts allowed.
|
|
1056
|
+
if (toks[j]?.t !== 'word') continue;
|
|
1057
|
+
let nameEnd = j;
|
|
1058
|
+
while (isP(toks[nameEnd + 1], '.') && toks[nameEnd + 2]?.t === 'word') nameEnd += 2;
|
|
1059
|
+
const name = unq(toks[nameEnd].v);
|
|
1060
|
+
j = nameEnd + 1;
|
|
1061
|
+
if (dialect === 'tsql' && isP(toks[j], ';') ) j++;
|
|
1062
|
+
// Parameters: ( … ), or T-SQL's bare list up to AS / WITH / FOR.
|
|
1063
|
+
let params = [];
|
|
1064
|
+
if (isP(toks[j], '(')) {
|
|
1065
|
+
const close = matchParen(toks, j);
|
|
1066
|
+
if (close < 0) continue;
|
|
1067
|
+
params = splitComma(toks.slice(j + 1, close));
|
|
1068
|
+
j = close + 1;
|
|
1069
|
+
} else if (dialect === 'tsql') {
|
|
1070
|
+
const p0 = j;
|
|
1071
|
+
while (toks[j] && !isW(toks[j], 'AS', 'WITH', 'FOR', 'RETURNS')) j++;
|
|
1072
|
+
params = splitComma(toks.slice(p0, j));
|
|
1073
|
+
} else continue;
|
|
1074
|
+
const routine = /^PROC/.test(kindWord) ? 'procedure' : 'function';
|
|
1075
|
+
const inputs = [], outs = [];
|
|
1076
|
+
for (const p of params) {
|
|
1077
|
+
let q = 0, mode = 'IN';
|
|
1078
|
+
if (isW(p[0], 'IN', 'OUT', 'INOUT', 'VARIADIC') && p.length > 1) { mode = p[0].up; q = 1; }
|
|
1079
|
+
if (isW(p[q], 'IN') && mode === 'IN' && isW(p[q + 1], 'OUT')) { mode = 'INOUT'; q += 2; }
|
|
1080
|
+
const nm = p[q];
|
|
1081
|
+
const rest = p.slice(q + 1);
|
|
1082
|
+
const tsqlOut = dialect === 'tsql' && rest.some((x) => isW(x, 'OUTPUT', 'OUT'));
|
|
1083
|
+
if (tsqlOut) mode = 'INOUT';
|
|
1084
|
+
const defAt = rest.findIndex((x) => isW(x, 'DEFAULT') || isP(x, '='));
|
|
1085
|
+
const typeTs = rest.slice(isW(rest[0], 'AS') ? 1 : 0, defAt < 0 ? rest.length : defAt).filter((x) => !isW(x, 'OUTPUT', 'OUT', 'READONLY'));
|
|
1086
|
+
const typeText = typeTs.length ? src.slice(typeTs[0].s, typeTs.at(-1).e) : '';
|
|
1087
|
+
// A PostgreSQL parameter can be a type alone (no name): it is input $1, $2, …
|
|
1088
|
+
const unnamed = dialect === 'pg' && (!rest.length || defAt === 0 || isP(rest[0], '(') || isP(rest[0], '[') || isP(rest[0], '.'));
|
|
1089
|
+
const pname = unnamed ? `$${inputs.length + outs.length + 1}` : unq(nm?.v ?? '');
|
|
1090
|
+
if (!pname) continue;
|
|
1091
|
+
const param = { name: unnamed ? `input ${inputs.length + 1}` : pname.replace(/^@/, '').replace(/^(?:p|in|out|inout)_(?=\w)/i, '').replace(/^_(?=\w)/, ''), type: unnamed ? src.slice(p[q].s, (defAt < 0 ? p.at(-1) : rest[defAt - 1] ?? p[q]).e) : typeText, ...(defAt >= 0 ? { default: src.slice(rest[defAt + 1]?.s ?? 0, p.at(-1).e).trim() } : {}) };
|
|
1092
|
+
if (mode === 'OUT') outs.push(param); else inputs.push(param);
|
|
1093
|
+
if (mode === 'INOUT') outs.push(param);
|
|
1094
|
+
}
|
|
1095
|
+
// Returns, options, and the body.
|
|
1096
|
+
let returns = null, setof = false, trigger = false, bodyToks = null, bodyDialect = dialect, end = j, language = null, unreadWhy = null;
|
|
1097
|
+
if (isW(toks[j], 'RETURNS')) {
|
|
1098
|
+
j++;
|
|
1099
|
+
if (isW(toks[j], 'SETOF')) { setof = true; j++; returns = 'rows'; while (toks[j] && (isW(toks[j]) || isP(toks[j], '.')) && !isW(toks[j], 'AS', 'LANGUAGE', 'IMMUTABLE', 'STABLE', 'VOLATILE', 'STRICT', 'SECURITY', 'BEGIN', 'RETURN', 'WITH')) j++; }
|
|
1100
|
+
else if (isW(toks[j], 'TABLE') && isP(toks[j + 1], '(')) { setof = true; returns = 'rows'; j = matchParen(toks, j + 1) + 1; }
|
|
1101
|
+
else if (dialect === 'tsql' && isW(toks[j]) && /^@/.test(toks[j].v) && isW(toks[j + 1], 'TABLE')) { returns = 'rows'; j = matchParen(toks, j + 2) + 1; }
|
|
1102
|
+
else if (isW(toks[j])) {
|
|
1103
|
+
const t0 = j;
|
|
1104
|
+
while (isP(toks[j + 1], '.') && isW(toks[j + 2])) j += 2;
|
|
1105
|
+
j++;
|
|
1106
|
+
while (isW(toks[j]) && /^(?:VARYING|PRECISION|WITH|WITHOUT|TIME|ZONE|UNSIGNED|SIGNED)$/.test(toks[j].up) && !(toks[j].up === 'WITH' && dialect === 'tsql')) j++;
|
|
1107
|
+
if (isP(toks[j], '(')) j = matchParen(toks, j) + 1;
|
|
1108
|
+
if (isP(toks[j], '[') && isP(toks[j + 1], ']')) j += 2;
|
|
1109
|
+
const rt = src.slice(toks[t0].s, toks[j - 1].e);
|
|
1110
|
+
trigger = /^trigger$/i.test(rt);
|
|
1111
|
+
returns = trigger ? null : (/^TABLE$/i.test(rt) ? 'rows' : sqlTypeWords(rt) ?? sqlWords(rt));
|
|
1112
|
+
if (/^void$/i.test(rt)) returns = null;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
if (dialect === 'pg') {
|
|
1116
|
+
// Options in any order, up to the statement's `;`: LANGUAGE x, AS $$body$$, IMMUTABLE, SET x = y, …
|
|
1117
|
+
for (; j < toks.length && !isP(toks[j], ';'); j++) {
|
|
1118
|
+
if (isW(toks[j], 'LANGUAGE') && toks[j + 1]) language = unq(toks[j + 1].v).toLowerCase();
|
|
1119
|
+
if (isW(toks[j], 'AS') && toks[j + 1]?.t === 'str') { bodyToks = toks[j + 1]; j++; if (isP(toks[j + 1], ',')) { bodyToks = null; unreadWhy = 'compiled code'; } }
|
|
1120
|
+
if (isW(toks[j], 'BEGIN') && isW(toks[j + 1], 'ATOMIC')) { unreadWhy = 'a SQL-standard body'; break; }
|
|
1121
|
+
if (isW(toks[j], 'CREATE')) { j--; break; }
|
|
1122
|
+
}
|
|
1123
|
+
end = Math.min(j, toks.length - 1);
|
|
1124
|
+
} else {
|
|
1125
|
+
// MySQL characteristics / T-SQL WITH options, then the body.
|
|
1126
|
+
for (;;) {
|
|
1127
|
+
if (isW(toks[j], 'DETERMINISTIC', 'CONTAINS', 'NO', 'READS', 'MODIFIES', 'SQL', 'DATA', 'INVOKER', 'DEFINER', 'SECURITY')) { j++; continue; }
|
|
1128
|
+
if (isW(toks[j], 'NOT') && isW(toks[j + 1], 'DETERMINISTIC')) { j += 2; continue; }
|
|
1129
|
+
if (isW(toks[j], 'LANGUAGE')) { j += 2; continue; }
|
|
1130
|
+
if (isW(toks[j], 'COMMENT') && toks[j + 1]?.t === 'str') { j += 2; continue; }
|
|
1131
|
+
if (isW(toks[j], 'CHARSET', 'CHARACTER', 'COLLATE')) { j += isW(toks[j], 'CHARACTER') ? 3 : 2; continue; }
|
|
1132
|
+
if (dialect === 'tsql' && isW(toks[j], 'WITH')) { j++; while (toks[j] && !isW(toks[j], 'AS')) j++; continue; }
|
|
1133
|
+
break;
|
|
1134
|
+
}
|
|
1135
|
+
if (dialect === 'tsql') { if (!isW(toks[j], 'AS')) continue; j++; }
|
|
1136
|
+
}
|
|
1137
|
+
// The steps.
|
|
1138
|
+
let steps = [], bodyEnd = end;
|
|
1139
|
+
const ctx = { src, lineAt, dialect: bodyDialect, routine, setof, trigger, depth: 0 };
|
|
1140
|
+
try {
|
|
1141
|
+
if (dialect === 'pg') {
|
|
1142
|
+
if (bodyToks && language !== 'c' && language !== 'internal') {
|
|
1143
|
+
const inner = bodyToks.dollar ? lexSql(src, bodyToks.s + bodyToks.dollar.length, bodyToks.e - bodyToks.dollar.length, 'pg') : null;
|
|
1144
|
+
if (!inner) unreadWhy = 'a body written as a quoted string';
|
|
1145
|
+
else if (language === 'sql') { ctx.dialect = 'pg'; ctx.sqlFunction = true; steps = sqlFunctionSteps(inner, ctx); }
|
|
1146
|
+
else steps = bodySteps(inner, ctx);
|
|
1147
|
+
}
|
|
1148
|
+
bodyEnd = end;
|
|
1149
|
+
} else if (dialect === 'mysql') {
|
|
1150
|
+
// The body is one statement (often BEGIN … END).
|
|
1151
|
+
const delim = delimiterAt(src, toks[start].s);
|
|
1152
|
+
let stop = toks.length;
|
|
1153
|
+
if (delim !== ';') for (let g = j; g < toks.length; g++) if (toks[g].t === 'p' && src.startsWith(delim, toks[g].s)) { stop = g; break; }
|
|
1154
|
+
const sub = toks.slice(j, stop);
|
|
1155
|
+
const parsed = oneStatement(sub, ctx);
|
|
1156
|
+
steps = parsed.steps;
|
|
1157
|
+
bodyEnd = j + parsed.used - 1;
|
|
1158
|
+
} else {
|
|
1159
|
+
// T-SQL: the body runs to the next GO (or the end of the file).
|
|
1160
|
+
let g = j;
|
|
1161
|
+
while (g < toks.length && !(isW(toks[g], 'GO') && /(^|\n)[ \t]*$/.test(src.slice(Math.max(0, toks[g].s - 200), toks[g].s)))) g++;
|
|
1162
|
+
const sub = toks.slice(j, g);
|
|
1163
|
+
// A function's RETURN (SELECT …) / RETURN SELECT is a query: shown as code.
|
|
1164
|
+
steps = bodySteps(sub, ctx);
|
|
1165
|
+
bodyEnd = g - 1;
|
|
1166
|
+
}
|
|
1167
|
+
} catch (e) {
|
|
1168
|
+
if (!(e instanceof Unmatched)) throw e;
|
|
1169
|
+
unreadWhy = `its structure could not be matched: ${e.message}`;
|
|
1170
|
+
steps = [];
|
|
1171
|
+
}
|
|
1172
|
+
if (dialect === 'tsql' || dialect === 'mysql') end = bodyEnd;
|
|
1173
|
+
const endLine = lineOf(Math.max(end, start));
|
|
1174
|
+
out.push({ name, line: lineOf(start), endLine, kind: routine, inputs, outs, returns, setof, trigger, steps, ...(unreadWhy ? { unreadWhy } : {}), headerEnd: lineOf(Math.max(start, j - 1)) });
|
|
1175
|
+
k = Math.max(k, Math.min(end, toks.length - 1));
|
|
1176
|
+
}
|
|
1177
|
+
return out;
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/** One MySQL routine body statement: { steps, used } (used = tokens consumed). */
|
|
1181
|
+
function oneStatement(sub, ctx) {
|
|
1182
|
+
return bodySteps(sub, ctx, { one: true });
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/** The MySQL client delimiter in effect at offset `at` (DELIMITER $$ … ), or ';'. */
|
|
1186
|
+
function delimiterAt(src, at) {
|
|
1187
|
+
let d = ';';
|
|
1188
|
+
for (const m of src.slice(0, at).matchAll(/^[ \t]*DELIMITER[ \t]+(\S+)/gim)) d = m[1];
|
|
1189
|
+
return d;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/** A LANGUAGE sql function: its statements; the last SELECT is what it gives back (shown as code). */
|
|
1193
|
+
function sqlFunctionSteps(toks, ctx) {
|
|
1194
|
+
const steps = bodySteps(toks, ctx);
|
|
1195
|
+
return steps;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
export { plainName, cap as sqlCap };
|