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

133 lines
7.9 KiB
JavaScript

// What to propose at the cursor of SQL (consoles, .sql files, SQL inside PHP / Markdown), without Monaco: node --test sql-complete.test.mjs.
// The data is the Database window's own: the connection's database names (known at once), each database's schema loaded when it is
// needed (the tree's cache). suggest() says which schemas it lacks: the caller loads them and asks again.
export const KEYWORDS = ['SELECT', 'FROM', 'WHERE', 'AND', 'OR', 'NOT', 'NULL', 'IS', 'IN', 'LIKE', 'BETWEEN', 'ORDER BY', 'GROUP BY', 'HAVING', 'LIMIT', 'OFFSET',
'JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'ON', 'AS', 'DISTINCT', 'INSERT INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE FROM', 'CREATE TABLE',
'ALTER TABLE', 'DROP TABLE', 'TRUNCATE', 'SHOW TABLES', 'SHOW DATABASES', 'SHOW CREATE TABLE', 'DESCRIBE', 'EXPLAIN', 'UNION', 'CASE', 'WHEN', 'THEN',
'ELSE', 'END', 'EXISTS', 'ASC', 'DESC', 'USE', 'WITH'];
export const FUNCTIONS = ['COUNT', 'SUM', 'AVG', 'MIN', 'MAX', 'NOW', 'CURDATE', 'DATE', 'YEAR', 'MONTH', 'DAY', 'DATE_FORMAT', 'DATE_ADD', 'DATE_SUB', 'DATEDIFF',
'CONCAT', 'CONCAT_WS', 'GROUP_CONCAT', 'COALESCE', 'IFNULL', 'NULLIF', 'IF', 'LOWER', 'UPPER', 'LENGTH', 'CHAR_LENGTH', 'SUBSTRING', 'TRIM', 'REPLACE',
'ROUND', 'FLOOR', 'CEIL', 'ABS', 'CAST', 'CONVERT', 'JSON_EXTRACT', 'JSON_UNQUOTE', 'JSON_OBJECT', 'JSON_ARRAYAGG', 'UUID', 'LAST_INSERT_ID', 'FOUND_ROWS'];
const TABLE_KEYWORDS = /\b(FROM|JOIN|UPDATE|INTO|TABLE|DESCRIBE|DESC|TRUNCATE)\s+((?:[`"]?[\w$]+[`"]?(?:\.[`"]?[\w$]+[`"]?)?(?:\s+(?:AS\s+)?[\w$]+)?\s*,\s*)*)$/i;
const unquote = (s) => s.replace(/^[`"]|[`"]$/g, '');
const RESERVED = /^(WHERE|ON|SET|JOIN|LEFT|RIGHT|INNER|OUTER|CROSS|ORDER|GROUP|LIMIT|VALUES|USING|HAVING|UNION|AS|NATURAL|STRAIGHT_JOIN|FOR|LOCK|WINDOW)$/i;
/** The statement the cursor is in: from the last ';' before it (quotes and comments are not looked at: good enough while typing). */
export function statementBefore(before) {
const i = before.lastIndexOf(';');
return i === -1 ? before : before.slice(i + 1);
}
/**
* The context at the end of `before` (the statement up to the cursor):
* {mode: 'databases' | 'tables' | 'columns' | 'dotted' | 'any', parts: names before the word, prefix: the word being typed}.
*/
export function sqlContext(before) {
const m = /((?:(?:`[^`]*`|"[^"]*"|[\w$]+)\.){0,2})([\w$]*)$/.exec(before);
const parts = m[1] ? m[1].slice(0, -1).match(/`[^`]*`|"[^"]*"|[\w$]+/g).map(unquote) : [];
const prefix = m[2];
const head = before.slice(0, before.length - m[0].length);
if (parts.length === 2) return { mode: 'columns', parts, prefix };
if (parts.length === 1) return { mode: 'dotted', parts, prefix };
if (/\bUSE\s+$/i.test(head)) return { mode: 'databases', parts, prefix };
if (TABLE_KEYWORDS.test(head)) return { mode: 'tables', parts, prefix };
return { mode: 'any', parts, prefix };
}
/** The tables a statement names, by alias and by name (lower case): {db, table}. */
export function aliasesOf(statement) {
const map = new Map();
const re = /\b(?:FROM|JOIN|UPDATE|INTO|TABLE)\s+((?:`[^`]+`|"[^"]+"|[\w$]+)(?:\.(?:`[^`]+`|"[^"]+"|[\w$]+))?)(?![\w$`".])(?:\s+(?:AS\s+)?([\w$]+))?/gi;
for (const m of statement.matchAll(re)) {
const names = m[1].match(/`[^`]+`|"[^"]+"|[\w$]+/g).map(unquote);
const ref = names.length === 2 ? { db: names[0], table: names[1] } : { db: null, table: names[0] };
map.set(ref.table.toLowerCase(), ref);
if (m[2] && !RESERVED.test(m[2])) map.set(m[2].toLowerCase(), ref);
}
// comma lists: FROM a x, b y
for (const m of statement.matchAll(/,\s*((?:`[^`]+`|[\w$]+)(?:\.(?:`[^`]+`|[\w$]+))?)(?:\s+(?:AS\s+)?([\w$]+))?/gi)) {
const names = m[1].match(/`[^`]+`|[\w$]+/g).map(unquote);
const ref = names.length === 2 ? { db: names[0], table: names[1] } : { db: null, table: names[0] };
if (m[2] && !RESERVED.test(m[2]) && !map.has(m[2].toLowerCase())) map.set(m[2].toLowerCase(), ref);
}
return map;
}
/**
* The proposals. data: {database: the default ('' when none), databases: names, schema(db): its schema, or undefined while not
* loaded}. Returns {items: [{label, kind: 'database' | 'table' | 'view' | 'column' | 'routine' | 'keyword' | 'function', detail}],
* missing: databases whose schema is needed and not loaded}.
*/
export function suggest(before, data) {
const statement = statementBefore(before);
const ctx = sqlContext(statement);
const items = [];
const missing = new Set();
const dbs = data.databases || [];
const findDb = (name) => dbs.find((d) => d.toLowerCase() === String(name).toLowerCase()) || null;
const schemaOf = (db) => {
if (!db) return null;
const s = data.schema(db);
if (s === undefined) missing.add(db);
return s || null;
};
const tableIn = (db, name) => (schemaOf(db)?.tables || []).find((x) => x.name.toLowerCase() === String(name).toLowerCase()) || null;
const tablesOf = (db) => {
for (const x of schemaOf(db)?.tables || []) items.push({ label: x.name, kind: x.type === 'view' ? 'view' : 'table', detail: db + (x.type === 'view' ? ' · view' : '') });
};
const columnsOf = (db, table, detail = '') => {
for (const c of tableIn(db, table)?.columns || []) items.push({ label: c.name, kind: 'column', detail: (detail ? detail + ' · ' : '') + c.type + (c.key === 'PRI' ? ' · PK' : '') });
};
const databases = () => { for (const d of dbs) items.push({ label: d, kind: 'database', detail: 'database' }); };
const aliases = aliasesOf(statement + ' ' + (data.after || ''));
const resolve = (ref) => ({ db: ref.db ? findDb(ref.db) || ref.db : data.database, table: ref.table });
if (ctx.mode === 'databases') databases();
else if (ctx.mode === 'tables') { if (data.database) tablesOf(data.database); databases(); }
else if (ctx.mode === 'columns') columnsOf(findDb(ctx.parts[0]) || ctx.parts[0], ctx.parts[1]);
else if (ctx.mode === 'dotted') {
const name = ctx.parts[0];
const ref = aliases.get(name.toLowerCase());
if (ref) { const r = resolve(ref); columnsOf(r.db, r.table, r.table); }
else if (findDb(name)) { tablesOf(findDb(name)); }
else if (data.database && tableIn(data.database, name)) columnsOf(data.database, name);
} else {
// columns of the statement's tables, then tables of the default database, databases, routines, keywords, functions
const seen = new Set();
for (const ref of aliases.values()) {
const r = resolve(ref);
const key = `${r.db}|${r.table}`.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
columnsOf(r.db, r.table, r.table);
}
if (data.database) {
tablesOf(data.database);
for (const r of schemaOf(data.database)?.routines || []) items.push({ label: r.name, kind: 'routine', detail: r.type });
}
databases();
for (const k of KEYWORDS) items.push({ label: k, kind: 'keyword', detail: '' });
for (const f of FUNCTIONS) items.push({ label: f, kind: 'function', detail: 'function' });
}
return { items, missing: [...missing], context: ctx };
}
/** What a word under the mouse is (hover): a column of the statement's tables, a table, a database. */
export function describe(statement, word, data) {
const lower = word.toLowerCase();
const aliases = aliasesOf(statement);
const dbs = data.databases || [];
if (dbs.some((d) => d.toLowerCase() === lower)) return { kind: 'database', name: word };
const fromDb = (db) => (data.schema(db)?.tables || []).find((x) => x.name.toLowerCase() === lower);
const ref = aliases.get(lower);
const table = (ref && fromDb(ref.db || data.database)) || (data.database && fromDb(data.database));
if (table) return { kind: table.type === 'view' ? 'view' : 'table', name: table.name, table };
for (const r of aliases.values()) {
const t = (data.schema(r.db || data.database)?.tables || []).find((x) => x.name.toLowerCase() === r.table.toLowerCase());
const c = t?.columns.find((x) => x.name.toLowerCase() === lower);
if (c) return { kind: 'column', name: c.name, table: t.name, column: c };
}
return null;
}