205 lines
9.4 KiB
JavaScript
205 lines
9.4 KiB
JavaScript
// SQL written inside other files, found without Monaco (pure functions, node --test: sql-ranges.test.mjs):
|
|
// - PHP: heredocs / nowdocs labelled SQL (<<<SQL, <<<'SQL', <<<"MYSQL"... ; DQL is Doctrine's, left alone) and the string given to
|
|
// an obvious SQL call (->query('…'), ->prepare("…"), ->executeQuery(), ->executeStatement(), ->fetchAllAssociative()...) when it
|
|
// starts like SQL; comments and other strings are skipped, so a "<<<SQL" in a comment is not one;
|
|
// - Markdown: fenced blocks ```sql / ```mysql / ~~~sql (and mariadb, sqlite).
|
|
// A range: {from, to} offsets of the SQL itself in the text (to excluded), {line, endLine} 1-based lines of the opener and of the end,
|
|
// kind ('heredoc' | 'nowdoc' | 'string' | 'markdown'), interpolates (PHP variables are replaced at run time), indent (a flexible
|
|
// heredoc's closing indentation, removed from each line).
|
|
|
|
const LABELS = /^(SQL|MYSQL|MARIADB|SQLITE|EOSQL|SQLQUERY|QUERY_SQL)$/i;
|
|
const CALLS = /(?:->|::)\s*(query|prepare|exec|execute|executeQuery|executeStatement|executeUpdate|fetchAllAssociative|fetchAssociative|fetchAllNumeric|fetchNumeric|fetchOne|fetchFirstColumn|fetchAllKeyValue|iterateAssociative|raw|select|statement|unprepared|insert|update|delete|selectOne|createNativeQuery)\s*\(\s*$/;
|
|
const LOOKS_SQL = /^\s*(\(\s*)?(SELECT|INSERT|UPDATE|DELETE|REPLACE|WITH|CREATE|ALTER|DROP|TRUNCATE|SHOW|DESCRIBE|DESC|EXPLAIN|CALL|SET|USE|GRANT|REVOKE|RENAME|LOCK|UNLOCK|START|BEGIN|COMMIT|ROLLBACK|MERGE|PRAGMA)\b/i;
|
|
|
|
const lineAt = (text, offset) => {
|
|
let n = 1;
|
|
for (let i = text.indexOf('\n'); i !== -1 && i < offset; i = text.indexOf('\n', i + 1)) n++;
|
|
return n;
|
|
};
|
|
|
|
/** The SQL ranges of a file: language 'php' | 'markdown' (others: none). */
|
|
export function sqlRanges(text, language) {
|
|
if (language === 'php') return phpRanges(text);
|
|
if (language === 'markdown') return markdownRanges(text);
|
|
return [];
|
|
}
|
|
|
|
export function markdownRanges(text) {
|
|
const out = [];
|
|
const re = /^([ \t]{0,3})(`{3,}|~{3,})[ \t]*([\w+-]*)[^\n]*\n/gm;
|
|
let m;
|
|
while ((m = re.exec(text))) {
|
|
const fence = m[2];
|
|
const lang = m[3].toLowerCase();
|
|
const from = m.index + m[0].length;
|
|
const close = new RegExp(`^[ \\t]{0,3}${fence[0] === '`' ? '`' : '~'}{${fence.length},}[ \\t]*$`, 'gm');
|
|
close.lastIndex = from;
|
|
const c = close.exec(text);
|
|
const to = c ? c.index : text.length;
|
|
if (['sql', 'mysql', 'mariadb', 'sqlite', 'plsql', 'pgsql'].includes(lang)) {
|
|
out.push({ kind: 'markdown', from, to, line: lineAt(text, m.index), endLine: lineAt(text, c ? c.index : text.length), interpolates: false, indent: '' });
|
|
}
|
|
re.lastIndex = c ? c.index + c[0].length : text.length;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export function phpRanges(text) {
|
|
const out = [];
|
|
const n = text.length;
|
|
let i = 0;
|
|
// only the PHP code: outside <?php ... ?>, nothing (HTML of a template)
|
|
let inPhp = !text.startsWith('<');
|
|
while (i < n) {
|
|
if (!inPhp) {
|
|
const open = text.indexOf('<?', i);
|
|
if (open === -1) break;
|
|
i = open + (text.startsWith('<?php', open) ? 5 : text.startsWith('<?=', open) ? 3 : 2);
|
|
inPhp = true;
|
|
continue;
|
|
}
|
|
const c = text[i];
|
|
if (c === '?' && text[i + 1] === '>') { inPhp = false; i += 2; continue; }
|
|
if ((c === '/' && text[i + 1] === '/') || (c === '#' && text[i + 1] !== '[')) {
|
|
// a line comment ends at the end of the line or at ?>
|
|
let j = i;
|
|
while (j < n && text[j] !== '\n' && !(text[j] === '?' && text[j + 1] === '>')) j++;
|
|
i = j;
|
|
continue;
|
|
}
|
|
if (c === '/' && text[i + 1] === '*') {
|
|
const end = text.indexOf('*/', i + 2);
|
|
i = end === -1 ? n : end + 2;
|
|
continue;
|
|
}
|
|
if (c === '<' && text.startsWith('<<<', i)) {
|
|
const h = /^<<<[ \t]*(["']?)([A-Za-z_]\w*)\1\r?\n/.exec(text.slice(i, i + 80));
|
|
if (h) {
|
|
const label = h[2];
|
|
const from = i + h[0].length;
|
|
// the closing label: alone at the start of a line (indented: PHP 7.3), not followed by a name character
|
|
const close = new RegExp(`^([ \\t]*)${label}\\b`, 'gm');
|
|
close.lastIndex = from;
|
|
let c2 = close.exec(text);
|
|
while (c2 && c2.index < from) c2 = close.exec(text);
|
|
const to = c2 ? Math.max(from, c2.index - (text[c2.index - 1] === '\n' ? 1 : 0) - (text[c2.index - 2] === '\r' && text[c2.index - 1] === '\n' ? 1 : 0)) : n;
|
|
if (LABELS.test(label)) {
|
|
out.push({ kind: h[1] === "'" ? 'nowdoc' : 'heredoc', from, to, line: lineAt(text, i), endLine: lineAt(text, c2 ? c2.index : n),
|
|
interpolates: h[1] !== "'", indent: c2 ? c2[1] : '' });
|
|
}
|
|
i = c2 ? c2.index + c2[0].length : n;
|
|
continue;
|
|
}
|
|
}
|
|
if (c === "'" || c === '"' || c === '`') {
|
|
let j = i + 1;
|
|
while (j < n && text[j] !== c) j += text[j] === '\\' ? 2 : 1;
|
|
const from = i + 1;
|
|
const to = Math.min(j, n);
|
|
const before = text.slice(Math.max(0, i - 80), i);
|
|
if (c !== '`' && CALLS.test(before) && LOOKS_SQL.test(text.slice(from, to))) {
|
|
out.push({ kind: 'string', from, to, line: lineAt(text, i), endLine: lineAt(text, to), interpolates: c === '"', indent: '', quote: c });
|
|
}
|
|
i = j + 1;
|
|
continue;
|
|
}
|
|
i++;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** The range holding an offset (the cursor), or null. */
|
|
export function rangeAt(ranges, offset) {
|
|
return ranges.find((r) => offset >= r.from && offset <= r.to) || null;
|
|
}
|
|
|
|
/** The SQL of a range as it runs: a flexible heredoc's indentation removed, PHP escapes of a string undone. */
|
|
export function sqlOf(text, range) {
|
|
let sql = text.slice(range.from, range.to);
|
|
if (range.indent) sql = sql.split('\n').map((l) => (l.startsWith(range.indent) ? l.slice(range.indent.length) : l.replace(/^[ \t]+/, ''))).join('\n');
|
|
if (range.kind === 'string') sql = range.quote === "'" ? sql.replace(/\\(['\\])/g, '$1') : sql.replace(/\\(["\\$])/g, '$1').replace(/\\n/g, '\n').replace(/\\t/g, '\t');
|
|
return sql;
|
|
}
|
|
|
|
/**
|
|
* What must be given before a block runs: PHP variables of an interpolating heredoc / double-quoted string ({$x['a']}, {$o->f()},
|
|
* $x, $x->y, $x[0]) and the statement's placeholders (:name, ?). Quoted SQL strings and comments are skipped for placeholders.
|
|
* Returns [{token, label, offsets: [[from, to], ...], inString}] in order of appearance (each ? is its own).
|
|
*/
|
|
export function parametersOf(sql, interpolates) {
|
|
const found = new Map();
|
|
const add = (token, label, from, to, inString) => {
|
|
const key = token === '?' ? `?${found.size}` : token;
|
|
if (!found.has(key)) found.set(key, { token, label, offsets: [], inString });
|
|
found.get(key).offsets.push([from, to]);
|
|
};
|
|
const n = sql.length;
|
|
// a PHP variable at i ({$...} with nested braces / brackets / strings, or $name, $name->x, $name[...]): its end, or -1
|
|
const variable = (i) => {
|
|
if (!interpolates) return -1;
|
|
if (sql[i] === '{' && sql[i + 1] === '$') {
|
|
let depth = 0;
|
|
for (let j = i; j < n; j++) {
|
|
const d = sql[j];
|
|
if (d === "'" || d === '"') { const q = d; j++; while (j < n && sql[j] !== q) j += sql[j] === '\\' ? 2 : 1; continue; }
|
|
if (d === '{') depth++;
|
|
else if (d === '}' && --depth === 0) return j + 1;
|
|
}
|
|
return n;
|
|
}
|
|
if (sql[i] === '$' && /[A-Za-z_]/.test(sql[i + 1] || '')) return i + /^\$[A-Za-z_]\w*(?:\[[^\]\n]*\]|->[A-Za-z_]\w*)?/.exec(sql.slice(i))[0].length;
|
|
return -1;
|
|
};
|
|
let i = 0;
|
|
while (i < n) {
|
|
const c = sql[i];
|
|
const v = variable(i);
|
|
if (v !== -1) {
|
|
const token = sql.slice(i, v);
|
|
add(token, token.startsWith('{') ? token.slice(1, -1) : token, i, v, false);
|
|
i = v;
|
|
continue;
|
|
}
|
|
if (c === "'" || c === '"' || c === '`') {
|
|
let j = i + 1;
|
|
while (j < n && sql[j] !== c) {
|
|
const w = variable(j);
|
|
if (w !== -1) { const token = sql.slice(j, w); add(token, token.startsWith('{') ? token.slice(1, -1) : token, j, w, true); j = w; continue; }
|
|
j += sql[j] === '\\' ? 2 : 1;
|
|
}
|
|
i = j + 1;
|
|
continue;
|
|
}
|
|
if (c === '-' && sql[i + 1] === '-') { const e = sql.indexOf('\n', i); i = e === -1 ? n : e; continue; }
|
|
if (c === '#') { const e = sql.indexOf('\n', i); i = e === -1 ? n : e; continue; }
|
|
if (c === '/' && sql[i + 1] === '*') { const e = sql.indexOf('*/', i + 2); i = e === -1 ? n : e + 2; continue; }
|
|
if (c === ':' && sql[i + 1] !== ':' && sql[i - 1] !== ':' && /[A-Za-z_]/.test(sql[i + 1] || '')) {
|
|
const m = /^:[A-Za-z_]\w*/.exec(sql.slice(i));
|
|
add(m[0], m[0], i, i + m[0].length, false);
|
|
i += m[0].length;
|
|
continue;
|
|
}
|
|
if (c === '?') { add('?', '?', i, i + 1, false); i++; continue; }
|
|
i++;
|
|
}
|
|
return [...found.values()];
|
|
}
|
|
|
|
/** A value typed by the user as SQL: NULL, a number, or a quoted string (raw: given as it is, e.g. a column name or a list; inString: a
|
|
* variable already inside an SQL string, escaped only). */
|
|
export function literal(value, raw = false, inString = false) {
|
|
if (raw) return value;
|
|
if (inString) return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
if (/^null$/i.test(value.trim())) return 'NULL';
|
|
if (/^-?\d+(\.\d+)?$/.test(value.trim())) return value.trim();
|
|
return "'" + value.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";
|
|
}
|
|
|
|
/** The SQL with its parameters replaced: values = [{offsets, sql}]. */
|
|
export function fill(sql, values) {
|
|
const edits = [];
|
|
for (const v of values) for (const [from, to] of v.offsets) edits.push([from, to, v.sql]);
|
|
edits.sort((a, b) => b[0] - a[0]);
|
|
for (const [from, to, text] of edits) sql = sql.slice(0, from) + text + sql.slice(to);
|
|
return sql;
|
|
}
|