rob-revisited/ide/ui/js/sql-model.js

225 lines
11 KiB
JavaScript

// The visual SQL builder's model, without the DOM (node --test ide/ui/js/sql-model.test.mjs): tables and joins, columns
// and aggregates, WHERE / GROUP BY / HAVING / ORDER BY / LIMIT rows, written as SQL, and SQL read back into those rows
// when it is a plain SELECT (else null: the text is kept as written).
//
// state = {distinct, tables: [{name, alias}], joins: [{type: 'INNER'|'LEFT'|'RIGHT', table: alias, on: [{left: 'a.col', right: 'b.col'}]}],
// columns: [{expr: 'a.col', agg: ''|'COUNT'|..., as}], where: [{expr, op, value}], groupBy: ['a.col'], having: [{expr, agg, op, value}],
// order: [{expr, dir}], limit: 0}
export const AGGREGATES = ['', 'COUNT', 'COUNT DISTINCT', 'SUM', 'AVG', 'MIN', 'MAX'];
export const OPERATORS = ['=', '<>', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL', 'BETWEEN'];
export function emptySql() {
return { distinct: false, tables: [], joins: [], columns: [], where: [], groupBy: [], having: [], order: [], limit: 0 };
}
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** a name quoted for the dialect when it needs it (or always for MySQL keywords-looking names) */
export function quote(name, dialect = 'mysql') {
if (IDENT.test(name) && !KEYWORDS.has(name.toUpperCase())) return name;
return dialect === 'mysql' ? '`' + name.replace(/`/g, '``') + '`' : '"' + name.replace(/"/g, '""') + '"';
}
const KEYWORDS = new Set(['SELECT', 'FROM', 'WHERE', 'GROUP', 'ORDER', 'BY', 'HAVING', 'LIMIT', 'JOIN', 'ON', 'AS', 'USER', 'KEY', 'TABLE', 'INDEX', 'ORDER', 'DESC', 'ASC', 'LEFT', 'RIGHT', 'INNER', 'OUTER', 'AND', 'OR', 'NOT', 'NULL', 'IN', 'IS', 'LIKE', 'DEFAULT', 'CHECK', 'GROUPS', 'RANK', 'ROW', 'ROWS']);
const qExpr = (expr, dialect) => String(expr).split('.').map((p) => (p === '*' ? p : quote(p, dialect))).join('.');
function aggregate(agg, inner) {
if (!agg) return inner;
if (agg === 'COUNT DISTINCT') return `COUNT(DISTINCT ${inner})`;
return `${agg}(${inner})`;
}
/** an alias for a new table: its first letters, not taken */
export function tableAlias(name, taken) {
const base = name.replace(/[^A-Za-z0-9]/g, '').toLowerCase() || 't';
for (const a of [base[0], base.slice(0, 2), base.slice(0, 3), base]) if (!taken.includes(a) && !KEYWORDS.has(a.toUpperCase())) return a;
let n = 2;
while (taken.includes(base[0] + n)) n++;
return base[0] + n;
}
/**
* Joins suggested by the foreign keys when `alias` is added: one ON per foreign key linking it to a table already there.
* schemaTables: the Database window's tables ({name, foreignKeys: [{columns, table, references}]})
*/
export function suggestJoins(state, alias, schemaTables) {
const byName = new Map(schemaTables.map((t) => [t.name.toLowerCase(), t]));
const added = state.tables.find((t) => t.alias === alias);
if (!added) return [];
const out = [];
for (const other of state.tables) {
if (other.alias === alias) continue;
for (const [from, to] of [[added, other], [other, added]]) {
for (const fk of byName.get(from.name.toLowerCase())?.foreignKeys || []) {
if (fk.table.toLowerCase() !== to.name.toLowerCase()) continue;
out.push({ type: 'INNER', table: alias, on: fk.columns.map((c, i) => ({ left: `${from.alias}.${c}`, right: `${to.alias}.${(fk.references || [])[i] || 'id'}` })) });
}
}
}
return out.slice(0, 1);
}
function cond(c, dialect) {
const left = c.agg ? aggregate(c.agg, qExpr(c.expr, dialect)) : qExpr(c.expr, dialect);
if (c.op === 'IS NULL' || c.op === 'IS NOT NULL') return `${left} ${c.op}`;
if ((c.op === 'IN' || c.op === 'NOT IN') && !/^\(/.test(String(c.value).trim())) return `${left} ${c.op} (${c.value})`;
return `${left} ${c.op} ${c.value}`;
}
/** the state as SQL */
export function buildSql(s, dialect = 'mysql') {
if (!s.tables.length) return '';
const cols = s.columns.length
? s.columns.map((c) => aggregate(c.agg, c.expr === '*' ? '*' : qExpr(c.expr, dialect)) + (c.as ? ' AS ' + quote(c.as, dialect) : '')).join(', ')
: '*';
const lines = [`SELECT ${s.distinct ? 'DISTINCT ' : ''}${cols}`];
const joined = new Set(s.joins.map((j) => j.table));
const first = s.tables.filter((t) => !joined.has(t.alias));
lines.push('FROM ' + (first.length ? first : [s.tables[0]]).map((t) => quote(t.name, dialect) + (t.alias && t.alias !== t.name ? ' ' + quote(t.alias, dialect) : '')).join(', '));
for (const j of s.joins) {
const t = s.tables.find((x) => x.alias === j.table);
if (!t) continue;
const on = j.on.map((o) => `${qExpr(o.left, dialect)} = ${qExpr(o.right, dialect)}`).join(' AND ');
lines.push(`${j.type === 'LEFT' ? 'LEFT JOIN' : j.type === 'RIGHT' ? 'RIGHT JOIN' : 'JOIN'} ${quote(t.name, dialect)}${t.alias !== t.name ? ' ' + quote(t.alias, dialect) : ''}${on ? ' ON ' + on : ''}`);
}
if (s.where.length) lines.push('WHERE ' + s.where.map((c) => cond(c, dialect)).join(' AND '));
if (s.groupBy.length) lines.push('GROUP BY ' + s.groupBy.map((g) => qExpr(g, dialect)).join(', '));
if (s.having.length) lines.push('HAVING ' + s.having.map((c) => cond(c, dialect)).join(' AND '));
if (s.order.length) lines.push('ORDER BY ' + s.order.map((o) => `${qExpr(o.expr, dialect)} ${o.dir === 'DESC' ? 'DESC' : 'ASC'}`).join(', '));
if (s.limit > 0) lines.push(`LIMIT ${Number(s.limit)}`);
return lines.join('\n');
}
// reading SQL back -------------------------------------------------------------------------------------------------
function tokens(sql) {
const out = [];
const re = /\s+|--[^\n]*|\/\*[\s\S]*?\*\/|'(?:[^'\\]|\\.|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|<>|!=|<=|>=|[(),.;=<>*+\-/]|[A-Za-z_][A-Za-z0-9_$]*|\d+(?:\.\d+)?|\S/g;
let m;
while ((m = re.exec(sql))) {
const t = m[0];
if (/^\s|^--|^\/\*/.test(t)) continue;
out.push(t);
}
return out;
}
const unq = (t) => (/^[`"]/.test(t) ? t.slice(1, -1).replace(/``|""/g, (x) => x[0]) : t);
const isKw = (t, ...k) => t !== undefined && k.includes(t.toUpperCase());
/** a plain SELECT read into a state (null when it holds what the rows cannot show: subqueries, UNION, OR, functions...) */
export function parseSql(sql) {
const t = tokens(String(sql).trim().replace(/;\s*$/, ''));
let i = 0;
const peek = (n = 0) => t[i + n];
const next = () => t[i++];
const expect = (...k) => { if (!isKw(peek(), ...k)) throw new Error('expected ' + k.join('|')); return next(); };
const ident = () => { const x = next(); if (x === undefined || !/^[A-Za-z_`"]/.test(x)) throw new Error('name expected'); return unq(x); };
const dotted = () => {
if (peek() === '*') { next(); return '*'; }
let x = ident();
while (peek() === '.') { next(); x += '.' + (peek() === '*' ? next() : ident()); }
return x;
};
// a value: a literal, a parameter, a name, or a parenthesised list
const value = () => {
if (peek() === '(') {
let depth = 0;
const parts = [];
do { const x = next(); if (x === '(') depth++; if (x === ')') depth--; parts.push(x); if (x === undefined) throw new Error('unclosed'); } while (depth > 0);
if (parts.some((p) => isKw(p, 'SELECT'))) throw new Error('subquery');
return parts.join(' ').replace(/\( /g, '(').replace(/ \)/g, ')').replace(/ ,/g, ',');
}
const x = next();
if (x === undefined) throw new Error('value expected');
if (x === ':' || x === '?') return x === ':' ? ':' + next() : '?';
if (x === '-' && /^\d/.test(peek())) return '-' + next();
if (/^[A-Za-z_`"]/.test(x) && !/^'/.test(x)) { i--; return dotted(); }
return x;
};
try {
const s = emptySql();
expect('SELECT');
if (isKw(peek(), 'DISTINCT')) { next(); s.distinct = true; }
// columns
for (;;) {
let agg = '';
let expr;
if (/^[A-Za-z]+$/.test(peek()) && peek(1) === '(' && AGGREGATES.includes(peek().toUpperCase())) {
agg = next().toUpperCase(); next();
if (isKw(peek(), 'DISTINCT')) { next(); agg = agg === 'COUNT' ? 'COUNT DISTINCT' : (() => { throw new Error('distinct'); })(); }
expr = dotted();
if (next() !== ')') throw new Error(') expected');
} else expr = dotted();
let as = '';
if (isKw(peek(), 'AS')) { next(); as = ident(); } else if (peek() && /^[A-Za-z_`"]/.test(peek()) && !isKw(peek(), 'FROM')) as = ident();
if (!(expr === '*' && !agg)) s.columns.push({ expr, agg, as });
if (peek() === ',') { next(); continue; }
break;
}
expect('FROM');
const table = () => {
const name = ident();
let alias = name;
if (isKw(peek(), 'AS')) { next(); alias = ident(); } else if (peek() && /^[A-Za-z_`"]/.test(peek()) && !isKw(peek(), 'WHERE', 'JOIN', 'LEFT', 'RIGHT', 'INNER', 'GROUP', 'ORDER', 'LIMIT', 'HAVING', 'ON', 'CROSS', 'OUTER')) alias = ident();
s.tables.push({ name, alias });
return alias;
};
table();
while (peek() === ',') { next(); table(); }
while (isKw(peek(), 'JOIN', 'LEFT', 'RIGHT', 'INNER')) {
let type = 'INNER';
if (isKw(peek(), 'LEFT', 'RIGHT')) { type = next().toUpperCase(); if (isKw(peek(), 'OUTER')) next(); } else if (isKw(peek(), 'INNER')) next();
expect('JOIN');
const alias = table();
const on = [];
if (isKw(peek(), 'ON')) {
next();
for (;;) {
const left = dotted();
if (next() !== '=') throw new Error('= expected');
on.push({ left, right: dotted() });
if (isKw(peek(), 'AND')) { next(); continue; }
break;
}
}
s.joins.push({ type, table: alias, on });
}
const conds = (target, withAgg) => {
for (;;) {
let agg = '';
let expr;
if (withAgg && /^[A-Za-z]+$/.test(peek()) && peek(1) === '(' && AGGREGATES.includes(peek().toUpperCase())) {
agg = next().toUpperCase(); next();
expr = dotted();
if (next() !== ')') throw new Error(') expected');
} else expr = dotted();
let op;
if (isKw(peek(), 'IS')) { next(); op = isKw(peek(), 'NOT') ? (next(), 'IS NOT NULL') : 'IS NULL'; expect('NULL'); target.push({ expr, agg, op, value: '' }); }
else {
if (isKw(peek(), 'NOT')) { next(); op = 'NOT ' + next().toUpperCase(); }
else op = next().toUpperCase();
if (op === '!=') op = '<>';
if (!OPERATORS.includes(op)) throw new Error('operator ' + op);
let v = value();
if (op === 'BETWEEN') { expect('AND'); v += ' AND ' + value(); }
target.push({ expr, agg, op, value: v });
}
if (isKw(peek(), 'AND')) { next(); continue; }
if (isKw(peek(), 'OR')) throw new Error('OR');
break;
}
};
if (isKw(peek(), 'WHERE')) { next(); conds(s.where, false); s.where.forEach((w) => delete w.agg); }
if (isKw(peek(), 'GROUP')) { next(); expect('BY'); for (;;) { s.groupBy.push(dotted()); if (peek() === ',') { next(); continue; } break; } }
if (isKw(peek(), 'HAVING')) { next(); conds(s.having, true); }
if (isKw(peek(), 'ORDER')) {
next(); expect('BY');
for (;;) { const expr = dotted(); let dir = 'ASC'; if (isKw(peek(), 'ASC', 'DESC')) dir = next().toUpperCase(); s.order.push({ expr, dir }); if (peek() === ',') { next(); continue; } break; }
}
if (isKw(peek(), 'LIMIT')) { next(); s.limit = Number(next()); }
if (i < t.length) return null;
return s;
} catch {
return null;
}
}