1128 lines
65 KiB
JavaScript
1128 lines
65 KiB
JavaScript
// The Database window (desktop IDE): the project's databases (MySQL / MariaDB, SQLite), after jumphpsql.
|
||
// - Database (right): the connections of .jumphp/databases.json (never a password: kept by the IDE on this computer, or asked),
|
||
// their tree (databases > tables / views / routines > columns / indexes / foreign keys), the databases the project describes
|
||
// (.env DATABASE_URL, Laravel DB_*, Docker Compose services, the JumPHP web site) added in one click.
|
||
// - SQL consoles: .jumphp/consoles/<name>.sql (out of git) opened in the editor; Ctrl+Enter runs the selection or the statement
|
||
// under the cursor, tables and columns completed from the live schema. Any .sql file of the project can be run the same way.
|
||
// - SQL Results (bottom): a tab per result, pages, sort, filter, export (CSV / JSON / SQL); a table's rows edited in place, the
|
||
// UPDATE / DELETE / INSERT shown before they run in one transaction; its structure; EXPLAIN.
|
||
// - A connection marked "production": red everywhere, and nothing that writes runs without a confirmation.
|
||
// The PHP side: ide/src/Database/DatabaseCommands.php.
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, notify, prefs, t, confirm, prompt, dialog, menu, chooser, copyText } from './ui.js';
|
||
import { suggest, describe } from './sql-complete.js';
|
||
import { sqlRanges, rangeAt, sqlOf, parametersOf, literal, fill } from './sql-ranges.js';
|
||
|
||
const css = el('link', { rel: 'stylesheet', href: new URL('../css/db.css', import.meta.url).href });
|
||
document.head.append(css);
|
||
|
||
const CONSOLE = /^\.jumphp\/consoles\/.*-([a-z0-9_-]+)\.sql$/i;
|
||
const where = (c) => (c.driver === 'sqlite' ? c.file : `${c.user ? c.user + '@' : ''}${c.host}:${c.port}${c.database ? '/' + c.database : ''}`)
|
||
+ (c.ssh?.server || c.ssh?.host ? ' ' + t('via SSH') : '');
|
||
|
||
/** The state shared by the two windows and the editors. */
|
||
export class Database {
|
||
constructor(app) {
|
||
this.app = app;
|
||
this.list = null; // db.list
|
||
this.found = []; // db.detect
|
||
this.open = new Map(); // id -> {version, databases, database}
|
||
this.busy = new Set(); // ids connecting
|
||
this.schemas = new Map(); // "id|db" -> schema
|
||
this.expanded = new Set(prefs.get('dbExpanded:' + app.projectKey, []));
|
||
this.consoleDb = new Map(); // console path -> database
|
||
this.panel = new DatabasePanel(this);
|
||
this.results = new ResultsPanel(this);
|
||
backend.on('db.closed', (p) => { this.open.delete(p.id); notify(p.reason || t('Connection closed'), 'warning', { title: this.name(p.id) }); this.panel.render(); });
|
||
this.whenMonaco();
|
||
}
|
||
|
||
conn(id) { return this.list?.connections.find((c) => c.id === id) || null; }
|
||
name(id) { return this.conn(id)?.name || t('Database'); }
|
||
saveExpanded() { prefs.set('dbExpanded:' + this.app.projectKey, [...this.expanded].slice(-300)); }
|
||
|
||
async refresh() {
|
||
this.list = await backend.invoke('db.list', {}).catch((e) => { notify(e.message, 'error', { title: t('Database') }); return { connections: [], drivers: {}, sshServers: [] }; });
|
||
this.found = (await backend.invoke('db.detect', {}).catch(() => ({ found: [] }))).found;
|
||
for (const id of [...this.open.keys()]) if (!this.list.connections.some((c) => c.id === id && c.open)) this.open.delete(id);
|
||
this.panel.render();
|
||
this.lensChanged?.fire();
|
||
}
|
||
|
||
// connections -----------------------------------------------------------------------------------------------
|
||
|
||
/** Connects (asking the password when none is kept); resolves to the session or null. */
|
||
async connect(id, { quiet = false } = {}) {
|
||
if (this.open.has(id)) return this.open.get(id);
|
||
const c = this.conn(id);
|
||
if (!c) return null;
|
||
let password;
|
||
let keep = false;
|
||
if (c.driver === 'mysql' && !c.hasPassword) {
|
||
const answer = await this.askPassword(c);
|
||
if (!answer) return null;
|
||
({ password, keep } = answer);
|
||
}
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
this.busy.add(id);
|
||
this.panel.render();
|
||
try {
|
||
const info = await backend.invoke('db.connect', { id, ...(password !== undefined ? { password, keepPassword: keep } : {}) });
|
||
this.open.set(id, info);
|
||
if (keep) c.hasPassword = true;
|
||
if (info.database) this.expanded.add(`${id}|${info.database}`);
|
||
this.expanded.add(id);
|
||
return info;
|
||
} catch (e) {
|
||
if (/bad password|access denied/i.test(e.message) && c.driver === 'mysql') {
|
||
const answer = await this.askPassword(c, e.message);
|
||
if (!answer) return null;
|
||
({ password, keep } = answer);
|
||
continue;
|
||
}
|
||
if (!quiet) notify(e.message, 'error', { title: t('Cannot connect to {name}', { name: c.name }) });
|
||
return null;
|
||
} finally {
|
||
this.busy.delete(id);
|
||
this.panel.render();
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
askPassword(c, error = '') {
|
||
return new Promise((resolve) => {
|
||
const input = el('input.input', { type: 'password', autocomplete: 'off' });
|
||
const keep = el('input', { type: 'checkbox' });
|
||
let done = false;
|
||
dialog({
|
||
title: t('Password of {name}', { name: c.name }),
|
||
body: el('div.db-form', {},
|
||
error ? el('div.db-error', {}, error) : null,
|
||
el('label.db-field', {}, el('span', {}, `${c.user || ''}@${c.host}:${c.port}`), input),
|
||
el('label.db-check', {}, keep, t('Remember it on this computer (never in the project)'))),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Connect'), primary: true, action: () => { done = true; resolve({ password: input.value, keep: keep.checked }); } }],
|
||
onClose: () => { if (!done) resolve(null); },
|
||
});
|
||
});
|
||
}
|
||
|
||
async disconnect(id) {
|
||
await backend.invoke('db.disconnect', { id }).catch(() => null);
|
||
this.open.delete(id);
|
||
for (const k of [...this.schemas.keys()]) if (k.startsWith(id + '|')) this.schemas.delete(k);
|
||
this.panel.render();
|
||
}
|
||
|
||
async schema(id, database, refresh = false) {
|
||
const key = `${id}|${database}`;
|
||
if (!refresh && this.schemas.has(key)) return this.schemas.get(key);
|
||
const s = await backend.invoke('db.schema', { id, database, refresh });
|
||
this.schemas.set(key, s);
|
||
return s;
|
||
}
|
||
|
||
edit(c = null) {
|
||
const list = this.list || { drivers: {}, sshServers: [] };
|
||
const v = c || { name: '', driver: 'mysql', host: '127.0.0.1', port: 3306, user: 'root', database: '', file: '', production: false, color: '', ssh: { server: '', host: '', user: '', port: 0, jump: '' } };
|
||
const input = (value, attrs = {}) => el('input.input', { value: value ?? '', ...attrs });
|
||
const f = {
|
||
name: input(v.name, { placeholder: t('Local shop database') }),
|
||
driver: el('select.input', {}, el('option', { value: 'mysql', selected: v.driver === 'mysql' }, 'MySQL / MariaDB'),
|
||
el('option', { value: 'sqlite', selected: v.driver === 'sqlite', disabled: !list.drivers.sqlite }, list.drivers.sqlite ? 'SQLite' : t('SQLite (needs pdo_sqlite)'))),
|
||
host: input(v.host, { placeholder: '127.0.0.1' }), port: input(v.port || '', { placeholder: '3306' }), user: input(v.user, { placeholder: 'root' }),
|
||
password: input('', { type: 'password', autocomplete: 'off', placeholder: c?.hasPassword ? t('(kept: leave empty to keep it)') : '' }),
|
||
keep: el('input', { type: 'checkbox', checked: !!c?.hasPassword }),
|
||
database: input(v.database, { placeholder: t('(optional)') }), file: input(v.file, { placeholder: 'var/data.db' }),
|
||
ssh: el('select.input', {}, el('option', { value: '' }, t('No SSH tunnel')),
|
||
...list.sshServers.map((s) => el('option', { value: s.id, selected: v.ssh?.server === s.id }, `${s.name} (${s.user ? s.user + '@' : ''}${s.host})`))),
|
||
sshHost: input(v.ssh?.host ? (v.ssh.user ? v.ssh.user + '@' : '') + v.ssh.host : '', { placeholder: '[email protected]' }),
|
||
jump: input(v.ssh?.jump, { placeholder: 'user@jump' }),
|
||
production: el('input', { type: 'checkbox', checked: !!v.production }),
|
||
color: el('select.input', {}, ...[['', t('No colour')], ['#e5534b', t('Red')], ['#d4a72c', t('Yellow')], ['#57ab5a', t('Green')], ['#539bf5', t('Blue')], ['#b083f0', t('Purple')]]
|
||
.map(([value, label]) => el('option', { value, selected: (v.color || '') === value }, label))),
|
||
};
|
||
const row = (label, node, cls = '') => el('label.db-field' + cls, {}, el('span', {}, label), node);
|
||
const mysqlOnly = el('div.db-form', {}, row(t('Host'), f.host), el('div.db-two', {}, row(t('Port'), f.port), row(t('User'), f.user)),
|
||
row(t('Password'), f.password), el('label.db-check', {}, f.keep, t('Remember the password on this computer (never in the project)')),
|
||
row(t('Database'), f.database),
|
||
el('div.db-section', {}, t('SSH tunnel (the servers of the SSH window)')), row(t('Through'), f.ssh),
|
||
row(t('Or an SSH host (user@host) for teammates without that server'), f.sshHost), row(t('Jump host (ProxyJump)'), f.jump));
|
||
const sqliteOnly = el('div.db-form', {}, row(t('SQLite file (in the project, or absolute)'), f.file));
|
||
const sync = () => { mysqlOnly.hidden = f.driver.value !== 'mysql'; sqliteOnly.hidden = f.driver.value !== 'sqlite'; };
|
||
f.driver.addEventListener('change', sync);
|
||
sync();
|
||
dialog({
|
||
title: c ? t('Edit the connection') : t('New database connection'),
|
||
wide: true,
|
||
body: el('div.db-form', {}, row(t('Name'), f.name), row(t('Type'), f.driver), mysqlOnly, sqliteOnly,
|
||
el('div.db-section', {}, t('Safety')),
|
||
el('label.db-check.db-prod-check', {}, f.production, t('Production: a red bar, and every statement that writes is confirmed first')),
|
||
row(t('Colour'), f.color),
|
||
el('p.db-hint', {}, t('Saved in {file} (shared with the project); passwords stay on this computer.', { file: '.jumphp/databases.json' }))),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Save'), primary: true, action: async () => {
|
||
const [sshUser, sshHost] = f.sshHost.value.includes('@') ? f.sshHost.value.trim().split('@') : ['', f.sshHost.value.trim()];
|
||
const connection = { id: c?.id || '', name: f.name.value.trim(), driver: f.driver.value, host: f.host.value.trim(), port: Number(f.port.value) || 0,
|
||
user: f.user.value.trim(), database: f.database.value.trim(), file: f.file.value.trim(), production: f.production.checked, color: f.color.value,
|
||
ssh: { server: f.ssh.value, host: sshHost, user: sshUser, port: 0, jump: f.jump.value.trim() } };
|
||
const typed = f.password.value !== '';
|
||
const saved = await backend.invoke('db.save', { connection, ...(typed ? { password: f.password.value, keepPassword: f.keep.checked } : {}),
|
||
forgetPassword: !f.keep.checked && !!c?.hasPassword });
|
||
await this.refresh();
|
||
this.expanded.add(saved.id);
|
||
if (!this.open.has(saved.id)) {
|
||
// a password typed and not kept: used for this connection only
|
||
if (typed && !f.keep.checked && saved.driver === 'mysql') {
|
||
const info = await backend.invoke('db.connect', { id: saved.id, password: f.password.value }).catch((e) => { notify(e.message, 'error', { title: saved.name }); return null; });
|
||
if (info) this.open.set(saved.id, info);
|
||
} else this.connect(saved.id);
|
||
}
|
||
this.panel.render();
|
||
return true;
|
||
} }],
|
||
});
|
||
}
|
||
|
||
async remove(c) {
|
||
if (!(await confirm(t('Remove the connection'), t('Remove {name} from this project (its kept password too)?', { name: c.name }), { ok: t('Remove'), danger: true }))) return;
|
||
await backend.invoke('db.remove', { id: c.id }).catch((e) => notify(e.message, 'error'));
|
||
this.open.delete(c.id);
|
||
this.refresh();
|
||
}
|
||
|
||
async addFound(f) {
|
||
try {
|
||
const saved = await backend.invoke('db.detect.add', { key: f.key, keepPassword: true });
|
||
await this.refresh();
|
||
notify(t('{name} added to the project\'s connections.', { name: saved.name }), 'success', { title: t('Database') });
|
||
this.connect(saved.id);
|
||
} catch (e) { notify(e.message, 'error', { title: t('Database') }); }
|
||
}
|
||
|
||
// consoles -----------------------------------------------------------------------------------------------------
|
||
|
||
async openConsole(id, sql = '') {
|
||
if (!(await this.connect(id))) return;
|
||
const { path } = await backend.invoke('db.console', { id });
|
||
prefs.set('dbConsole:' + this.app.projectKey + ':' + path, id);
|
||
await this.app.editors.open(path);
|
||
const ed = this.app.editors.editor();
|
||
if (sql && ed) {
|
||
const model = ed.getModel();
|
||
const end = model.getFullModelRange().getEndPosition();
|
||
const text = (model.getValueInRange({ startLineNumber: end.lineNumber, startColumn: 1, endLineNumber: end.lineNumber, endColumn: end.column }).trim() ? '\n' : '') + sql;
|
||
ed.executeEdits('db', [{ range: { startLineNumber: end.lineNumber, startColumn: end.column, endLineNumber: end.lineNumber, endColumn: end.column }, text }]);
|
||
const last = model.getFullModelRange().getEndPosition();
|
||
ed.setPosition(last);
|
||
ed.revealLine(last.lineNumber);
|
||
ed.focus();
|
||
}
|
||
}
|
||
|
||
/** The connection a .sql file runs on: its console's, or the one chosen for it. */
|
||
connFor(path) {
|
||
const chosen = prefs.get('dbConsole:' + this.app.projectKey + ':' + path, null);
|
||
if (chosen && this.conn(chosen)) return chosen;
|
||
const m = CONSOLE.exec(path || '');
|
||
return m && this.conn(m[1]) ? m[1] : null;
|
||
}
|
||
|
||
pickConnection(path) {
|
||
return new Promise((resolve) => {
|
||
const items = (this.list?.connections || []).map((c) => ({ label: c.name, hint: where(c), icon: 'database', action: () => {
|
||
prefs.set('dbConsole:' + this.app.projectKey + ':' + path, c.id);
|
||
resolve(c.id);
|
||
} }));
|
||
if (!items.length) { notify(t('No database connection yet: add one in the Database window.'), 'warning', { title: t('Database') }); resolve(null); return; }
|
||
chooser(items, { placeholder: t('Run on which connection?') });
|
||
});
|
||
}
|
||
|
||
pathOf(ed) {
|
||
const uri = ed?.getModel()?.uri;
|
||
return uri && uri.scheme === 'file' && !uri.path.startsWith('/@lib') ? uri.path.slice(1) : null;
|
||
}
|
||
|
||
async runFromEditor(ed, mode = 'statement') {
|
||
const path = this.pathOf(ed);
|
||
if (!path) return;
|
||
const model = ed.getModel();
|
||
let id = this.connFor(path);
|
||
if (!id) id = await this.pickConnection(path);
|
||
if (!id || !(await this.connect(id))) return;
|
||
const selection = mode === 'file' ? '' : model.getValueInRange(ed.getSelection());
|
||
const cursor = mode === 'file' || selection.trim() ? null : model.getOffsetAt(ed.getPosition());
|
||
const script = model.getValue();
|
||
if (mode === 'explain') {
|
||
const r = await backend.invoke('db.run', { id, script, cursor, selection: '', database: this.databaseFor(path, id), confirmed: false, size: 1 }).catch(() => null);
|
||
const sql = selection.trim() || r?.results?.[0]?.sql || r?.confirm?.[0];
|
||
if (sql) this.results.explain(id, sql, this.databaseFor(path, id));
|
||
return;
|
||
}
|
||
this.run(id, { script, cursor, selection, database: this.databaseFor(path, id), source: path });
|
||
}
|
||
|
||
/** The database a console runs in: the one chosen for it (its bar's list, a USE run there), else the connection's default. */
|
||
databaseFor(path, id) {
|
||
if (!this.consoleDb.has(path)) this.consoleDb.set(path, prefs.get('dbConsoleDb:' + this.app.projectKey + ':' + path, ''));
|
||
return this.consoleDb.get(path) || this.open.get(id)?.database || '';
|
||
}
|
||
|
||
setConsoleDatabase(path, database) {
|
||
this.consoleDb.set(path, database);
|
||
prefs.set('dbConsoleDb:' + this.app.projectKey + ':' + path, database);
|
||
for (const g of this.app.editors.groups) if (g.editor && this.pathOf(g.editor) === path) this.decorate(g.editor);
|
||
}
|
||
|
||
/** Runs statements (asking first on a production connection when they write) and shows their results. */
|
||
async run(id, { script, cursor = null, selection = '', database = '', source = '' }, confirmed = false) {
|
||
let r;
|
||
try {
|
||
r = await backend.invoke('db.run', { id, script, cursor, selection, database, confirmed, size: 100 });
|
||
} catch (e) { notify(e.message, 'error', { title: this.name(id) }); return; }
|
||
if (r.confirm) {
|
||
if (await this.confirmWrites(id, r.confirm)) this.run(id, { script, cursor, selection, database, source }, true);
|
||
return;
|
||
}
|
||
if (!r.results.length) { notify(t('Nothing to run here.'), 'info', { title: this.name(id) }); return; }
|
||
this.remember(id, r.results.map((x) => x.sql));
|
||
this.results.showResults(id, r.results, source);
|
||
// a USE changed the console's database
|
||
for (const x of r.results) { const m = /^\s*USE\s+`?([^`;\s]+)`?/i.exec(x.sql || ''); if (m && !x.error && source) this.setConsoleDatabase(source, m[1]); }
|
||
}
|
||
|
||
confirmWrites(id, statements) {
|
||
const c = this.conn(id);
|
||
return new Promise((resolve) => {
|
||
let done = false;
|
||
dialog({
|
||
title: t('Production: confirm the changes'),
|
||
wide: true,
|
||
body: el('div.db-form', {}, el('div.db-prodbar', {}, icon('warning'), t('{name} is a production database.', { name: c?.name || '' })),
|
||
el('p', {}, t('These statements change it. Run them?')), el('pre.db-sql', {}, statements.join(';\n') + ';')),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Run on production'), danger: true, action: () => { done = true; resolve(true); } }],
|
||
onClose: () => { if (!done) resolve(false); },
|
||
});
|
||
});
|
||
}
|
||
|
||
remember(id, statements) {
|
||
const key = 'dbHistory:' + this.app.projectKey + ':' + id;
|
||
const list = prefs.get(key, []).filter((s) => !statements.includes(s));
|
||
prefs.set(key, [...statements.slice().reverse(), ...list].slice(0, 100));
|
||
}
|
||
|
||
history(id) {
|
||
const list = prefs.get('dbHistory:' + this.app.projectKey + ':' + id, []);
|
||
if (!list.length) { notify(t('No statement run yet on this connection.'), 'info', { title: t('History') }); return; }
|
||
chooser(list.map((sql) => ({ label: sql.replace(/\s+/g, ' ').slice(0, 160), action: () => this.openConsole(id, sql + ';') })), { placeholder: t('Statements run on {name}', { name: this.name(id) }), width: 640 });
|
||
}
|
||
|
||
// the editors: Ctrl+Enter, completion, the production bar ---------------------------------------------------
|
||
|
||
whenMonaco() {
|
||
if (!window.monaco || !this.app.editors?.groups) { setTimeout(() => this.whenMonaco(), 500); return; }
|
||
const monaco = window.monaco;
|
||
const hook = (ed) => {
|
||
if (ed.__jumphpDb) return;
|
||
ed.__jumphpDb = true;
|
||
ed.addAction({ id: 'jumphp.db.run', label: t('Run SQL (statement under the cursor or selection)'), keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
|
||
precondition: 'editorLangId == sql', contextMenuGroupId: 'navigation', contextMenuOrder: 0, run: (e) => this.runFromEditor(e) });
|
||
ed.addAction({ id: 'jumphp.db.runFile', label: t('Run the whole SQL file'), precondition: 'editorLangId == sql', contextMenuGroupId: 'navigation', contextMenuOrder: 1,
|
||
run: (e) => this.runFromEditor(e, 'file') });
|
||
ed.addAction({ id: 'jumphp.db.explain', label: t('Explain Plan'), precondition: 'editorLangId == sql', contextMenuGroupId: 'navigation', contextMenuOrder: 2,
|
||
run: (e) => this.runFromEditor(e, 'explain') });
|
||
ed.addAction({ id: 'jumphp.db.connection', label: t('Choose the Database Connection…'), precondition: 'editorLangId == sql', contextMenuGroupId: 'navigation', contextMenuOrder: 3,
|
||
run: async (e) => { const p = this.pathOf(e); if (p) { await this.pickConnection(p); this.decorate(e); } } });
|
||
ed.onDidChangeModel(() => this.decorate(ed));
|
||
this.watchEmbedded(ed);
|
||
this.decorate(ed);
|
||
};
|
||
for (const g of this.app.editors.groups) if (g.editor) hook(g.editor);
|
||
monaco.editor.onDidCreateEditor((ed) => setTimeout(() => { if (ed.addAction && ed.onDidChangeModel) hook(ed); }, 0));
|
||
monaco.languages.registerCompletionItemProvider('sql', { triggerCharacters: ['.', ' ', '`'], provideCompletionItems: (model, position) => this.complete(model, position) });
|
||
monaco.languages.registerHoverProvider('sql', { provideHover: (model, position) => this.hover(model, position) });
|
||
this.embedded(monaco);
|
||
}
|
||
|
||
/** The red bar over a console of a production connection (and the connection's name over any attached .sql file). */
|
||
decorate(ed) {
|
||
if (ed.__dbBar) { ed.removeOverlayWidget(ed.__dbBar); ed.__dbBar = null; }
|
||
const path = this.pathOf(ed);
|
||
const id = path && /\.sql$/i.test(path) ? this.connFor(path) : null;
|
||
const c = id && this.conn(id);
|
||
if (!c) return;
|
||
const node = el('div.db-editor-bar' + (c.production ? '.prod' : ''), { style: c.color && !c.production ? { borderColor: c.color } : {} },
|
||
c.production ? icon('warning') : icon('database'), c.production ? t('PRODUCTION: {name}', { name: c.name }) : c.name,
|
||
this.databaseSelect(path, id), el('span.db-editor-hint', {}, t('Ctrl+Enter runs')));
|
||
ed.__dbBar = { getId: () => 'jumphp.db.bar', getDomNode: () => node, getPosition: () => ({ preference: window.monaco.editor.OverlayWidgetPositionPreference.TOP_RIGHT_CORNER }) };
|
||
ed.addOverlayWidget(ed.__dbBar);
|
||
}
|
||
|
||
// SQL inside PHP and Markdown (sql-ranges.js): colours, completion, hovers, "▶ Run in …" lenses ------------------
|
||
|
||
/** A file's SQL ranges, computed once per version of its text (cheap: a quick test first, nothing in files without SQL). */
|
||
sqlRangesOf(model) {
|
||
const language = model.getLanguageId();
|
||
if (!['php', 'markdown'].includes(language) || model.getValueLength() > 1500000) return [];
|
||
const version = model.getVersionId();
|
||
if (model.__sqlRanges && model.__sqlRanges.version === version) return model.__sqlRanges.list;
|
||
const text = model.getValue();
|
||
const quick = language === 'php' ? /<<<[ \t]*["']?(SQL|MYSQL|MARIADB|SQLITE|EOSQL|SQLQUERY|QUERY_SQL)\b|(->|::)\s*(query|prepare|exec|execute\w*|fetch\w*|iterate\w*|raw|select|statement|unprepared|insert|update|delete|selectOne|createNativeQuery)\s*\(/i
|
||
: /^[ \t]{0,3}(`{3,}|~{3,})[ \t]*(sql|mysql|mariadb|sqlite|plsql|pgsql)\b/im;
|
||
const list = quick.test(text) ? sqlRanges(text, language).slice(0, 200) : [];
|
||
model.__sqlRanges = { version, list };
|
||
return list;
|
||
}
|
||
|
||
/** The connection SQL of a file runs on: the one chosen for it, else the only one, else the first open one. */
|
||
embeddedConn(path) {
|
||
const chosen = this.connFor(path);
|
||
if (chosen) return chosen;
|
||
const conns = this.list?.connections || [];
|
||
if (conns.length === 1) return conns[0].id;
|
||
return conns.find((c) => this.open.has(c.id))?.id || null;
|
||
}
|
||
|
||
embedded(monaco) {
|
||
this.lensChanged = new monaco.Emitter();
|
||
const self = this;
|
||
monaco.editor.registerCommand('jumphp.db.embedded', (_accessor, args) => this.runEmbedded(args));
|
||
for (const language of ['php', 'markdown']) {
|
||
monaco.languages.registerCompletionItemProvider(language, { triggerCharacters: ['.', ' ', '`'], provideCompletionItems: async (model, position) => {
|
||
const offset = model.getOffsetAt(position);
|
||
const r = rangeAt(this.sqlRangesOf(model), offset);
|
||
if (!r) return { suggestions: [] };
|
||
const path = this.pathOfModel(model);
|
||
const word = model.getWordUntilPosition(position);
|
||
const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn };
|
||
const text = model.getValue();
|
||
const id = this.embeddedConn(path);
|
||
return this.completeAt(model, text.slice(r.from, offset), text.slice(offset, r.to), range, id, path, monaco.languages.CompletionItemKind);
|
||
} });
|
||
monaco.languages.registerHoverProvider(language, { provideHover: (model, position) => {
|
||
const offset = model.getOffsetAt(position);
|
||
const r = rangeAt(this.sqlRangesOf(model), offset);
|
||
const word = r && model.getWordAtPosition(position);
|
||
const path = this.pathOfModel(model);
|
||
const id = word && this.embeddedConn(path);
|
||
if (!id || !this.open.has(id)) return null;
|
||
const text = model.getValue().slice(r.from, r.to);
|
||
return this.hoverAt(text, offset - r.from, word, id, this.databaseFor(path, id), position.lineNumber);
|
||
} });
|
||
monaco.languages.registerCodeLensProvider(language, {
|
||
onDidChange: this.lensChanged.event,
|
||
provideCodeLenses(model) {
|
||
const path = self.pathOfModel(model);
|
||
const id = self.embeddedConn(path);
|
||
const c = id && self.conn(id);
|
||
const lenses = [];
|
||
self.sqlRangesOf(model).forEach((r, index) => {
|
||
const range = new monaco.Range(r.line, 1, r.line, 1);
|
||
const place = { uri: model.uri.toString(), index, version: model.getVersionId() };
|
||
lenses.push({ range, command: { id: 'jumphp.db.embedded', title: '▶ ' + (c ? (c.production ? t('Run in {name} (production)', { name: c.name }) : t('Run in {name}', { name: c.name })) : t('Run SQL…')), arguments: [{ ...place, mode: 'run' }] } });
|
||
lenses.push({ range, command: { id: 'jumphp.db.embedded', title: t('Explain Plan'), arguments: [{ ...place, mode: 'explain' }] } });
|
||
if ((self.list?.connections || []).length > 1) lenses.push({ range, command: { id: 'jumphp.db.embedded', title: t('Connection…'), arguments: [{ ...place, mode: 'connection' }] } });
|
||
});
|
||
return { lenses, dispose() {} };
|
||
},
|
||
resolveCodeLens: (model, lens) => lens,
|
||
});
|
||
}
|
||
}
|
||
|
||
pathOfModel(model) {
|
||
const uri = model.uri;
|
||
return uri.scheme === 'file' && !uri.path.startsWith('/@lib') ? uri.path.slice(1) : uri.toString();
|
||
}
|
||
|
||
/** Colours the SQL of a PHP / Markdown editor (decorations from Monaco's own SQL tokenizer), again shortly after each change. */
|
||
watchEmbedded(ed) {
|
||
let timer = 0;
|
||
const paint = () => {
|
||
const model = ed.getModel();
|
||
if (!model) return;
|
||
const ranges = this.sqlRangesOf(model);
|
||
const decorations = [];
|
||
if (ranges.length) {
|
||
const monaco = window.monaco;
|
||
const text = model.getValue();
|
||
for (const r of ranges) {
|
||
if (r.to - r.from > 30000) continue;
|
||
const start = model.getPositionAt(r.from);
|
||
const lines = monaco.editor.tokenize(text.slice(r.from, r.to), 'sql');
|
||
lines.forEach((tokens, n) => {
|
||
const lineNumber = start.lineNumber + n;
|
||
const base = n === 0 ? start.column - 1 : 0;
|
||
const length = model.getLineMaxColumn(lineNumber) - 1;
|
||
tokens.forEach((tok, k) => {
|
||
const cls = SQL_TOKEN_CLASS(tok.type);
|
||
if (!cls) return;
|
||
const end = k + 1 < tokens.length ? tokens[k + 1].offset : length - base;
|
||
if (end <= tok.offset) return;
|
||
decorations.push({ range: new monaco.Range(lineNumber, base + tok.offset + 1, lineNumber, Math.min(length, base + end) + 1), options: { inlineClassName: cls } });
|
||
});
|
||
});
|
||
decorations.push({ range: new monaco.Range(start.lineNumber, 1, model.getPositionAt(r.to).lineNumber, 1), options: { isWholeLine: true, className: 'sqlx-block' } });
|
||
}
|
||
}
|
||
if (!ed.__sqlx) ed.__sqlx = ed.createDecorationsCollection([]);
|
||
ed.__sqlx.set(decorations);
|
||
};
|
||
const later = () => { clearTimeout(timer); timer = setTimeout(paint, 350); };
|
||
ed.onDidChangeModelContent(later);
|
||
ed.onDidChangeModel(() => { clearTimeout(timer); paint(); });
|
||
paint();
|
||
}
|
||
|
||
/** ▶ Run / Explain of a block: its variables and placeholders asked first (never run blindly), then the console's way (production guard). */
|
||
async runEmbedded({ uri, index, mode }) {
|
||
const monaco = window.monaco;
|
||
const model = monaco.editor.getModel(monaco.Uri.parse(uri));
|
||
if (!model) return;
|
||
const r = this.sqlRangesOf(model)[index];
|
||
if (!r) return;
|
||
const path = this.pathOfModel(model);
|
||
if (mode === 'connection') { await this.pickConnection(path); this.lensChanged?.fire(); return; }
|
||
let id = this.embeddedConn(path);
|
||
if (!id) id = await this.pickConnection(path);
|
||
if (!id || !(await this.connect(id))) return;
|
||
let sql = sqlOf(model.getValue(), r).trim();
|
||
const params = parametersOf(sql, r.interpolates);
|
||
if (params.length) {
|
||
sql = await this.askParameters(sql, params);
|
||
if (sql === null) return;
|
||
}
|
||
const database = this.databaseFor(path, id);
|
||
if (mode === 'explain') { this.results.explain(id, sql.replace(/;\s*$/, '').split(/;\s*\n/)[0], database); return; }
|
||
this.run(id, { script: sql, database, source: `${path}#${index}` });
|
||
this.lensChanged?.fire();
|
||
}
|
||
|
||
askParameters(sql, params) {
|
||
return new Promise((resolve) => {
|
||
const rows = params.map((p) => ({ p, input: el('input.input', { placeholder: 'NULL, 42, text…', value: prefs.get('dbParam:' + p.label, '') }), raw: el('input', { type: 'checkbox' }) }));
|
||
let done = false;
|
||
dialog({
|
||
title: t('Values of the parameters'),
|
||
wide: true,
|
||
body: el('div.db-form', {}, el('p.db-hint', {}, t('This SQL holds variables or placeholders: give each a value. A value is quoted as SQL text unless it is a number or NULL; tick "as is" to give SQL itself.')),
|
||
el('pre.db-sql', {}, sql),
|
||
...rows.map(({ p, input, raw }) => el('div.db-param', {}, el('code', {}, p.label), input, el('label.db-check', {}, raw, t('as is'))))),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Run'), primary: true, action: () => {
|
||
done = true;
|
||
for (const { p, input } of rows) prefs.set('dbParam:' + p.label, input.value);
|
||
resolve(fill(sql, rows.map(({ p, input, raw }) => ({ offsets: p.offsets, sql: literal(input.value, raw.checked, p.inString) }))));
|
||
} }],
|
||
onClose: () => { if (!done) resolve(null); },
|
||
});
|
||
});
|
||
}
|
||
|
||
/** The console's database, chosen in its bar (USE for the statements run there), remembered per console. */
|
||
databaseSelect(path, id) {
|
||
const info = this.open.get(id);
|
||
if (!info) return null;
|
||
const current = this.databaseFor(path, id);
|
||
const select = el('select.db-editor-db', { title: t('Default database of this console (USE)'), onchange: () => this.setConsoleDatabase(path, select.value) },
|
||
el('option', { value: '' }, t('(no default database)')),
|
||
...(info.databases || []).map((d) => el('option', { value: d, selected: d === current }, d)));
|
||
if (current && !(info.databases || []).includes(current)) select.append(el('option', { value: current, selected: true }, current));
|
||
return select;
|
||
}
|
||
|
||
/** The completion's data: the connection's database names, each database's schema from the cache the tree shares (loaded on demand). */
|
||
completionData(id, database) {
|
||
return { database: database || '', databases: this.open.get(id)?.databases || [], schema: (db) => this.schemas.get(`${id}|${db}`) };
|
||
}
|
||
|
||
async complete(model, position) {
|
||
const monaco = window.monaco;
|
||
const K = monaco.languages.CompletionItemKind;
|
||
const path = model.uri.path.slice(1);
|
||
const word = model.getWordUntilPosition(position);
|
||
const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn };
|
||
const offset = model.getOffsetAt(position);
|
||
const text = model.getValue();
|
||
return this.completeAt(model, text.slice(Math.max(0, offset - 6000), offset), text.slice(offset, offset + 3000), range, this.connFor(path), path, K);
|
||
}
|
||
|
||
/** Completion of SQL ending with `before` (the text after the cursor: `after`), on a connection; shared with SQL inside other files. */
|
||
async completeAt(model, before, after, range, id, path, K) {
|
||
const c = id && this.conn(id);
|
||
// a connection that can open without a question opens for the completion
|
||
if (c && !this.open.has(id) && (c.hasPassword || c.driver === 'sqlite')) await this.connect(id, { quiet: true });
|
||
const end = after.indexOf(';');
|
||
const data = { ...this.completionData(id, id ? this.databaseFor(path, id) : ''), after: end === -1 ? after : after.slice(0, end) };
|
||
let r = suggest(before, data);
|
||
if (r.missing.length && id && this.open.has(id)) {
|
||
const loads = Promise.all(r.missing.map((db) => this.schema(id, db).catch(() => null)));
|
||
const quick = await Promise.race([loads.then(() => true), new Promise((done) => setTimeout(() => done(false), 400))]);
|
||
if (quick) r = suggest(before, data);
|
||
else {
|
||
// a big database: say so, and ask again once its tables are there
|
||
loads.then(() => {
|
||
this.panel.render();
|
||
const ed = this.app.editors.editor();
|
||
if (ed && ed.getModel() === model && ed.hasTextFocus()) ed.trigger('db', 'editor.action.triggerSuggest', {});
|
||
});
|
||
return { suggestions: [{ label: t('Loading the tables of {name}…', { name: r.missing.join(', ') }), kind: K.Text, insertText: '', range, sortText: '0000',
|
||
filterText: r.context.prefix || ' ' }], incomplete: true };
|
||
}
|
||
}
|
||
const kinds = { database: K.Module, table: K.Struct, view: K.Interface, column: K.Field, routine: K.Function, keyword: K.Keyword, function: K.Function };
|
||
const plain = /^[A-Za-z_][\w$]*$/;
|
||
return { suggestions: r.items.map((item, n) => ({ label: item.label, kind: kinds[item.kind], detail: item.detail, range, sortText: String(n).padStart(5, '0'),
|
||
insertText: item.kind === 'function' ? item.label + '(' : ['keyword'].includes(item.kind) || plain.test(item.label) ? item.label : '`' + item.label.replace(/`/g, '``') + '`' })) };
|
||
}
|
||
|
||
hover(model, position) {
|
||
const path = model.uri.path.slice(1);
|
||
const id = this.connFor(path);
|
||
const word = model.getWordAtPosition(position);
|
||
if (!id || !word || !this.open.has(id)) return null;
|
||
const offset = model.getOffsetAt(position);
|
||
const text = model.getValue();
|
||
return this.hoverAt(text, offset, word, id, this.databaseFor(path, id), position.lineNumber);
|
||
}
|
||
|
||
/** What a table / column / database is, from the cached schemas (never a query: hovers stay cheap). */
|
||
hoverAt(text, offset, word, id, database, line) {
|
||
const start = text.lastIndexOf(';', offset - 1) + 1;
|
||
const stop = text.indexOf(';', offset);
|
||
const statement = text.slice(start, stop === -1 ? text.length : stop);
|
||
const d = describe(statement, word.word, this.completionData(id, database));
|
||
if (!d) return null;
|
||
let md;
|
||
if (d.kind === 'database') md = `**${d.name}** · ${t('database')}`;
|
||
else if (d.kind === 'column') md = `**${d.table}.${d.name}** \`${d.column.type}\`${d.column.nullable ? ' NULL' : ' NOT NULL'}${d.column.key ? ' · ' + d.column.key : ''}${d.column.extra ? ' · ' + d.column.extra : ''}${d.column.comment ? '\n\n' + d.column.comment : ''}`;
|
||
else md = `**${d.name}** · ${t(d.kind)}\n\n` + d.table.columns.slice(0, 30).map((c) => `- \`${c.name}\` ${c.type}${c.key === 'PRI' ? ' · PK' : ''}`).join('\n');
|
||
return { range: { startLineNumber: line, endLineNumber: line, startColumn: word.startColumn, endColumn: word.endColumn }, contents: [{ value: md }] };
|
||
}
|
||
}
|
||
|
||
/** Monaco's SQL token types -> the classes that colour SQL inside other files (db.css). */
|
||
const SQL_TOKEN_CLASS = (type) => {
|
||
const kind = type.replace(/\.sql$/, '');
|
||
if (kind.startsWith('keyword')) return 'sqlx-keyword';
|
||
if (kind.startsWith('string')) return 'sqlx-string';
|
||
if (kind.startsWith('number')) return 'sqlx-number';
|
||
if (kind.startsWith('comment')) return 'sqlx-comment';
|
||
if (kind.startsWith('predefined')) return 'sqlx-function';
|
||
if (kind.startsWith('operator')) return 'sqlx-operator';
|
||
if (kind.startsWith('identifier')) return 'sqlx-identifier';
|
||
return '';
|
||
};
|
||
|
||
/** The Database tool window: connections, their tree, the databases found in the project. */
|
||
class DatabasePanel {
|
||
constructor(db) {
|
||
this.db = db;
|
||
this.node = el('div.db-view');
|
||
}
|
||
|
||
title() { return t('Database'); }
|
||
|
||
actions() {
|
||
return [
|
||
el('button', { title: t('New database connection'), onclick: () => this.db.edit() }, icon('plus')),
|
||
el('button', { 'data-tour': 'db-console', title: t('Open a SQL console'), onclick: () => this.consoleOfSelection() }, icon('console')),
|
||
el('button', { 'data-tour': 'db-builder', title: t('Visual SQL builder'), onclick: () => this.sqlBuilder() }, icon('design')),
|
||
el('button', { 'data-tour': 'db-refresh', title: t('Refresh'), onclick: () => this.refreshAll() }, icon('refresh')),
|
||
];
|
||
}
|
||
|
||
shown() { if (!this.db.list) this.db.refresh(); }
|
||
|
||
async refreshAll() {
|
||
for (const k of [...this.db.schemas.keys()]) this.db.schemas.delete(k);
|
||
await this.db.refresh();
|
||
}
|
||
|
||
consoleOfSelection() {
|
||
const conns = this.db.list?.connections || [];
|
||
if (this.selected?.id) return this.db.openConsole(this.selected.id);
|
||
if (conns.length === 1) return this.db.openConsole(conns[0].id);
|
||
if (!conns.length) return this.db.edit();
|
||
return chooser(conns.map((c) => ({ label: c.name, hint: where(c), icon: 'database', action: () => this.db.openConsole(c.id) })), { placeholder: t('Open a SQL console') });
|
||
}
|
||
|
||
/** the visual SQL builder (sql-builder.js) on the selected connection */
|
||
sqlBuilder() {
|
||
const conns = this.db.list?.connections || [];
|
||
const go = (id) => import('./sql-builder.js').then((m) => m.openSqlBuilder(this.db, id, this.db.open.get(id)?.database || ''));
|
||
if (this.selected?.id) return go(this.selected.id);
|
||
if (conns.length === 1) return go(conns[0].id);
|
||
if (!conns.length) return this.db.edit();
|
||
return chooser(conns.map((c) => ({ label: c.name, hint: where(c), icon: 'database', action: () => go(c.id) })), { placeholder: t('Visual SQL builder') });
|
||
}
|
||
|
||
toggle(key) {
|
||
if (this.db.expanded.has(key)) this.db.expanded.delete(key); else this.db.expanded.add(key);
|
||
this.db.saveExpanded();
|
||
this.render();
|
||
}
|
||
|
||
render() {
|
||
const db = this.db;
|
||
const scroll = this.node.querySelector('.db-tree')?.scrollTop || 0;
|
||
clear(this.node);
|
||
const tree = el('div.db-tree');
|
||
this.node.append(tree);
|
||
if (!db.list) { tree.append(el('div.db-hint', {}, t('Loading…'))); return; }
|
||
if (!db.list.connections.length) {
|
||
tree.append(el('div.db-hint', {}, t('No database connection in this project yet.')),
|
||
el('div.db-toolbar', {}, el('button.btn.primary', { onclick: () => db.edit() }, t('New database connection'))));
|
||
}
|
||
for (const c of db.list.connections) tree.append(...this.connectionRows(c));
|
||
if (db.found.length) {
|
||
tree.append(el('div.db-section', {}, t('Found in this project')));
|
||
for (const f of db.found) {
|
||
tree.append(el('div.db-found', {},
|
||
icon('database'),
|
||
el('div.db-main', {}, el('div.db-name', {}, f.name), el('div.db-sub', {}, `${f.source} · ${where(f)}${f.hasPassword ? ' · ' + t('password found') : ''}`)),
|
||
f.supported ? el('button.btn.small', { 'data-tour': 'db-add-found', onclick: () => db.addFound(f), title: t('Add it to the project\'s connections (its password kept on this computer)') }, t('Add'))
|
||
: el('span.db-sub', {}, t('{driver}: not supported yet', { driver: f.driver }))));
|
||
}
|
||
}
|
||
tree.scrollTop = scroll;
|
||
}
|
||
|
||
row(depth, key, label, { ico, sub = '', open = null, onclick, ondblclick, oncontextmenu, cls = '', title = '', actions = [], tour } = {}) {
|
||
const node = el('div.db-row' + cls, { 'data-tour': tour, style: { paddingLeft: 4 + depth * 14 + 'px' }, title,
|
||
onclick: (e) => { this.select(node, key); (onclick || (() => open !== null && this.toggle(key)))(e); }, ondblclick, oncontextmenu: oncontextmenu ? (e) => { e.preventDefault(); this.select(node, key); oncontextmenu(e); } : null },
|
||
el('span.db-caret', {}, open === null ? '' : open ? '▾' : '▸'), ico ? icon(ico) : null, el('span.db-label', {}, label), sub ? el('span.db-sub', {}, sub) : null,
|
||
actions.length ? el('span.db-actions', {}, ...actions) : null);
|
||
if (this.selectedKey === key) node.classList.add('sel');
|
||
return node;
|
||
}
|
||
|
||
select(node, key) {
|
||
this.node.querySelectorAll('.db-row.sel').forEach((n) => n.classList.remove('sel'));
|
||
node.classList.add('sel');
|
||
this.selectedKey = key;
|
||
this.selected = { id: key.split('|')[0] };
|
||
}
|
||
|
||
btn(title, ico, fn) { return el('button.icon-btn', { title, onclick: (e) => { e.stopPropagation(); fn(); } }, icon(ico)); }
|
||
|
||
connectionRows(c) {
|
||
const db = this.db;
|
||
const info = db.open.get(c.id);
|
||
const busy = db.busy.has(c.id);
|
||
const open = db.expanded.has(c.id) && !!info;
|
||
const rows = [];
|
||
const head = this.row(0, c.id, c.name, {
|
||
ico: 'database', sub: where(c), open: info ? open : false,
|
||
cls: (c.production ? '.prod' : '') + '.conn', tour: 'db-connection',
|
||
title: info ? `${info.version}` : '',
|
||
onclick: () => (info ? this.toggle(c.id) : db.connect(c.id)),
|
||
ondblclick: () => db.openConsole(c.id),
|
||
oncontextmenu: (e) => menu([
|
||
info ? { label: t('Disconnect'), icon: 'close', action: () => db.disconnect(c.id) } : { label: t('Connect'), icon: 'play', action: () => db.connect(c.id) },
|
||
{ label: t('Open a SQL console'), icon: 'console', action: () => db.openConsole(c.id) },
|
||
{ label: t('History'), icon: 'history', action: () => db.history(c.id) },
|
||
'-',
|
||
{ label: t('Edit the connection'), icon: 'edit', action: () => db.edit(c) },
|
||
{ label: t('Remove the connection'), icon: 'trash', action: () => db.remove(c) },
|
||
], { x: e.clientX, y: e.clientY }),
|
||
actions: [busy ? el('span.db-busy', {}, '…') : null,
|
||
this.btn(t('Open a SQL console'), 'console', () => db.openConsole(c.id)),
|
||
info ? this.btn(t('Disconnect'), 'close', () => db.disconnect(c.id)) : this.btn(t('Connect'), 'play', () => db.connect(c.id)),
|
||
this.btn(t('Edit the connection'), 'edit', () => db.edit(c))].filter(Boolean),
|
||
});
|
||
head.prepend(el('span.db-dot' + (busy ? '.busy' : info ? '.on' : '')));
|
||
if (c.color) head.style.boxShadow = `inset 3px 0 0 ${c.color}`;
|
||
if (c.production) head.append(el('span.db-prod-tag', {}, t('production')));
|
||
rows.push(head);
|
||
if (!open) return rows;
|
||
const databases = info.databases || [];
|
||
const shown = info.database ? [info.database, ...databases.filter((d) => d !== info.database)] : databases;
|
||
for (const name of shown) rows.push(...this.databaseRows(c, name));
|
||
return rows;
|
||
}
|
||
|
||
databaseRows(c, name) {
|
||
const db = this.db;
|
||
const key = `${c.id}|${name}`;
|
||
const open = db.expanded.has(key);
|
||
const rows = [this.row(1, key, name, { ico: 'disk', open, oncontextmenu: (e) => menu([
|
||
{ label: t('Open a SQL console'), icon: 'console', action: () => { db.openConsole(c.id, `USE ${quote(c, name)};`); } },
|
||
{ label: t('Visual SQL builder'), icon: 'design', action: () => import('./sql-builder.js').then((m) => m.openSqlBuilder(db, c.id, name)) },
|
||
{ label: t('Refresh'), icon: 'refresh', action: async () => { await db.schema(c.id, name, true).catch((err) => notify(err.message, 'error')); this.render(); } },
|
||
], { x: e.clientX, y: e.clientY }) })];
|
||
if (!open) return rows;
|
||
const schema = db.schemas.get(key);
|
||
if (!schema) {
|
||
rows.push(this.row(2, key + '|loading', t('Loading…'), {}));
|
||
db.schema(c.id, name).then(() => this.render(), (e) => { notify(e.message, 'error', { title: name }); db.expanded.delete(key); this.render(); });
|
||
return rows;
|
||
}
|
||
const groups = [['tables', t('Tables'), schema.tables.filter((x) => x.type === 'table')], ['views', t('Views'), schema.tables.filter((x) => x.type === 'view')],
|
||
['routines', t('Routines'), schema.routines]];
|
||
for (const [kind, label, items] of groups) {
|
||
if (!items.length) continue;
|
||
const gk = `${key}|${kind}`;
|
||
const gopen = db.expanded.has(gk) || (kind === 'tables' && !db.expanded.has(gk + '!'));
|
||
rows.push(this.row(2, gk, label, { ico: 'folder', sub: String(items.length), open: gopen, onclick: () => {
|
||
if (kind === 'tables') { if (gopen) db.expanded.add(gk + '!'); else db.expanded.delete(gk + '!'); db.expanded.delete(gk); db.saveExpanded(); this.render(); } else this.toggle(gk);
|
||
} }));
|
||
if (!gopen) continue;
|
||
for (const item of items) {
|
||
if (kind === 'routines') { rows.push(this.row(3, `${gk}|${item.name}`, item.name, { ico: 'code', sub: item.type })); continue; }
|
||
rows.push(...this.tableRows(c, name, item));
|
||
}
|
||
}
|
||
return rows;
|
||
}
|
||
|
||
tableRows(c, database, table) {
|
||
const db = this.db;
|
||
const key = `${c.id}|${database}|t|${table.name}`;
|
||
const open = db.expanded.has(key);
|
||
const res = db.results;
|
||
const rows = [this.row(3, key, table.name, {
|
||
tour: 'db-table-' + table.name, ico: table.type === 'view' ? 'eye' : 'structure', sub: table.rows !== null && table.rows !== undefined ? '~' + table.rows : '', open,
|
||
ondblclick: () => res.openTable(c.id, database, table.name),
|
||
oncontextmenu: (e) => menu([
|
||
{ label: t('Open the data'), icon: 'structure', action: () => res.openTable(c.id, database, table.name) },
|
||
{ label: t('Structure'), icon: 'hierarchy', action: () => res.openStructure(c.id, database, table.name) },
|
||
{ label: t('SELECT in a console'), icon: 'console', action: () => db.openConsole(c.id, `SELECT * FROM ${quote(c, database, table.name)} LIMIT 100;`) },
|
||
{ label: t('Visual SQL builder'), icon: 'design', action: () => import('./sql-builder.js').then((m) => m.openSqlBuilder(db, c.id, database, { table: table.name })) },
|
||
{ label: t('Copy the name'), icon: 'copy', action: () => copyText(table.name) },
|
||
], { x: e.clientX, y: e.clientY }),
|
||
})];
|
||
if (!open) return rows;
|
||
rows.push(this.row(4, key + '|c', t('Columns'), { ico: 'folder', sub: String(table.columns.length), open: true, onclick: () => null }));
|
||
for (const col of table.columns) {
|
||
rows.push(this.row(5, `${key}|c|${col.name}`, col.name, { ico: col.key === 'PRI' ? 'star' : 'minus', sub: col.type + (col.nullable ? '' : ' NOT NULL') + (col.extra ? ' ' + col.extra : ''),
|
||
title: col.comment || '' }));
|
||
}
|
||
if (table.indexes.length) {
|
||
rows.push(this.row(4, key + '|i', t('Indexes'), { ico: 'folder', sub: String(table.indexes.length), open: true, onclick: () => null }));
|
||
for (const i of table.indexes) rows.push(this.row(5, `${key}|i|${i.name}`, i.name, { ico: i.primary ? 'star' : 'search', sub: `(${i.columns.join(', ')})${i.unique && !i.primary ? ' UNIQUE' : ''}` }));
|
||
}
|
||
if (table.foreignKeys.length) {
|
||
rows.push(this.row(4, key + '|f', t('Foreign keys'), { ico: 'folder', sub: String(table.foreignKeys.length), open: true, onclick: () => null }));
|
||
for (const f of table.foreignKeys) rows.push(this.row(5, `${key}|f|${f.name}`, f.name, { ico: 'fork', sub: `(${f.columns.join(', ')}) → ${f.table}(${f.references.join(', ')})` }));
|
||
}
|
||
return rows;
|
||
}
|
||
}
|
||
|
||
const quote = (c, ...names) => names.map((n) => (c.driver === 'sqlite' ? `"${n.replace(/"/g, '""')}"` : '`' + n.replace(/`/g, '``') + '`')).join('.');
|
||
|
||
/** The SQL Results tool window: a tab per result, a table's data, its structure. */
|
||
class ResultsPanel {
|
||
constructor(db) {
|
||
this.db = db;
|
||
this.node = el('div.db-results');
|
||
this.tabs = [];
|
||
this.active = null;
|
||
this.render();
|
||
}
|
||
|
||
title() { return t('SQL Results'); }
|
||
|
||
actions() {
|
||
return [el('button', { title: t('Close all the results'), onclick: () => { this.tabs = this.tabs.filter((x) => x.pinned); this.active = this.tabs[0]?.key || null; this.render(); } }, icon('close'))];
|
||
}
|
||
|
||
show() { this.db.app.showTool('dbresults'); }
|
||
|
||
add(tab, replaceSource = '') {
|
||
if (replaceSource) this.tabs = this.tabs.filter((x) => x.pinned || x.source !== replaceSource);
|
||
const same = this.tabs.findIndex((x) => x.key === tab.key);
|
||
if (same >= 0) this.tabs[same] = tab; else this.tabs.push(tab);
|
||
while (this.tabs.length > 30) this.tabs.splice(this.tabs.findIndex((x) => !x.pinned), 1);
|
||
this.active = tab.key;
|
||
this.render();
|
||
this.show();
|
||
}
|
||
|
||
showResults(id, results, source) {
|
||
let n = 0;
|
||
for (const r of results) {
|
||
n++;
|
||
const label = r.error ? t('Error') : (r.sql || '').replace(/^(\s*(--[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/))*\s*/, '').replace(/\s+/g, ' ').slice(0, 28);
|
||
this.add({ key: `run:${source}:${Date.now()}:${n}`, kind: 'result', id, title: label, source, data: r, sort: null, desc: false, filter: '' }, n === 1 ? source : '');
|
||
}
|
||
}
|
||
|
||
async openTable(id, database, table) {
|
||
const tab = { key: `table:${id}:${database}:${table}`, kind: 'table', id, database, table, title: table, page: 0, size: 100, sort: '', desc: false, where: '',
|
||
edits: new Map(), deletes: new Set(), inserts: [] };
|
||
this.add(tab);
|
||
this.loadTable(tab);
|
||
}
|
||
|
||
async loadTable(tab) {
|
||
tab.loading = true;
|
||
this.render();
|
||
try {
|
||
tab.data = await backend.invoke('db.rows', { id: tab.id, database: tab.database, table: tab.table, page: tab.page, size: tab.size, sort: tab.sort, desc: tab.desc, where: tab.where });
|
||
tab.error = null;
|
||
tab.edits = new Map(); tab.deletes = new Set(); tab.inserts = [];
|
||
} catch (e) { tab.error = e.message; }
|
||
tab.loading = false;
|
||
this.render();
|
||
}
|
||
|
||
async openStructure(id, database, table) {
|
||
const tab = { key: `structure:${id}:${database}:${table}`, kind: 'structure', id, database, table, title: table + ' · ' + t('Structure') };
|
||
this.add(tab);
|
||
try {
|
||
const schema = await this.db.schema(id, database);
|
||
tab.info = schema.tables.find((x) => x.name === table);
|
||
tab.ddl = (await backend.invoke('db.ddl', { id, database, table })).sql;
|
||
} catch (e) { tab.error = e.message; }
|
||
this.render();
|
||
}
|
||
|
||
async explain(id, sql, database) {
|
||
try {
|
||
const r = await backend.invoke('db.explain', { id, sql, database });
|
||
this.add({ key: `explain:${Date.now()}`, kind: 'result', id, title: 'EXPLAIN', data: r, sort: null, desc: false, filter: '' });
|
||
} catch (e) { notify(e.message, 'error', { title: t('Explain Plan') }); }
|
||
}
|
||
|
||
async page(tab, page, extra = {}) {
|
||
Object.assign(tab, extra);
|
||
try {
|
||
tab.data = { ...tab.data, ...(await backend.invoke('db.page', { result: tab.data.result, page, size: tab.data.size || 100, sort: tab.sort, desc: tab.desc, filter: tab.filter })) };
|
||
} catch (e) { notify(e.message, 'error', { title: t('SQL Results') }); }
|
||
this.render();
|
||
}
|
||
|
||
render() {
|
||
clear(this.node);
|
||
const tab = this.tabs.find((x) => x.key === this.active) || this.tabs[this.tabs.length - 1];
|
||
if (!this.tabs.length) {
|
||
this.node.append(el('div.db-hint.db-empty', {}, t('Run a statement with Ctrl+Enter in a SQL console, or open a table of the Database window.')));
|
||
return;
|
||
}
|
||
const strip = el('div.db-tabs', {}, ...this.tabs.map((x) => el('div.db-tab' + (x === tab ? '.on' : '') + (this.db.conn(x.id)?.production ? '.prod' : '') + (x.data?.error || x.error ? '.err' : ''), {
|
||
onclick: () => { this.active = x.key; this.render(); },
|
||
onauxclick: (e) => { if (e.button === 1) this.close(x); },
|
||
title: x.data?.sql || x.title,
|
||
}, icon(x.kind === 'table' ? 'structure' : x.kind === 'structure' ? 'hierarchy' : 'console'), el('span', {}, x.title),
|
||
el('button.db-pin' + (x.pinned ? '.on' : ''), { title: t('Keep this result (the next run does not replace it)'), onclick: (e) => { e.stopPropagation(); x.pinned = !x.pinned; this.render(); } }, icon('star')),
|
||
el('button.db-x', { title: t('Close'), onclick: (e) => { e.stopPropagation(); this.close(x); } }, '×'))));
|
||
this.node.append(strip);
|
||
const c = this.db.conn(tab.id);
|
||
if (c?.production) this.node.append(el('div.db-prodbar', {}, icon('warning'), t('PRODUCTION: {name} — every statement that writes is confirmed first', { name: c.name })));
|
||
const body = el('div.db-body');
|
||
this.node.append(body);
|
||
if (tab.kind === 'structure') this.renderStructure(body, tab);
|
||
else if (tab.kind === 'table') this.renderTable(body, tab);
|
||
else this.renderResult(body, tab);
|
||
}
|
||
|
||
close(tab) {
|
||
this.tabs = this.tabs.filter((x) => x !== tab);
|
||
if (this.active === tab.key) this.active = this.tabs[this.tabs.length - 1]?.key || null;
|
||
this.render();
|
||
}
|
||
|
||
pager(tab, total, page, size, go) {
|
||
const pages = Math.max(1, Math.ceil(total / size));
|
||
return el('span.db-pager', {},
|
||
el('button.icon-btn', { title: t('First page'), disabled: page <= 0, onclick: () => go(0) }, '«'),
|
||
el('button.icon-btn', { title: t('Previous page'), disabled: page <= 0, onclick: () => go(page - 1) }, '‹'),
|
||
el('span', {}, t('{from}–{to} of {total}', { from: total ? page * size + 1 : 0, to: Math.min(total, (page + 1) * size), total })),
|
||
el('button.icon-btn', { title: t('Next page'), disabled: page >= pages - 1, onclick: () => go(page + 1) }, '›'),
|
||
el('button.icon-btn', { title: t('Last page'), disabled: page >= pages - 1, onclick: () => go(pages - 1) }, '»'));
|
||
}
|
||
|
||
exportMenu(tab, at) {
|
||
const result = tab.data?.result;
|
||
if (!result) return;
|
||
const copy = async (format) => { try { await copyText((await backend.invoke('db.export', { result, format })).text); notify(t('Copied.'), 'success', { title: t('Export') }); } catch (e) { notify(e.message, 'error'); } };
|
||
const save = async (format) => {
|
||
const dir = await backend.invoke('native.open', { folder: true, title: t('The folder to save into') }).catch(() => null);
|
||
if (typeof dir !== 'string' || !dir) return;
|
||
const name = await prompt(t('File name'), { value: `${tab.table || 'result'}.${format}` });
|
||
if (!name) return;
|
||
try { const r = await backend.invoke('db.export.save', { result, format, path: dir.replace(/[\\/]+$/, '') + '/' + name }); notify(r.path, 'success', { title: t('Export') }); } catch (e) { notify(e.message, 'error'); }
|
||
};
|
||
menu([
|
||
{ label: t('Copy as CSV'), icon: 'copy', action: () => copy('csv') }, { label: t('Copy as JSON'), icon: 'copy', action: () => copy('json') },
|
||
{ label: t('Copy as SQL INSERTs'), icon: 'copy', action: () => copy('sql') }, '-',
|
||
{ label: t('Save as CSV…'), icon: 'download', action: () => save('csv') }, { label: t('Save as JSON…'), icon: 'download', action: () => save('json') },
|
||
{ label: t('Save as SQL…'), icon: 'download', action: () => save('sql') },
|
||
], at);
|
||
}
|
||
|
||
renderResult(body, tab) {
|
||
const r = tab.data;
|
||
if (r.error) { body.append(el('div.db-error', {}, r.error), el('pre.db-sql', {}, r.sql || '')); return; }
|
||
const bar = el('div.db-bar', {}, el('span.db-summary', { title: r.sql }, r.summary || ''));
|
||
if (r.hasRows) {
|
||
const filter = el('input.input.db-filter', { value: tab.filter, placeholder: t('Filter the rows'), onkeydown: (e) => { if (e.key === 'Enter') this.page(tab, 0, { filter: filter.value }); } });
|
||
bar.append(filter, this.pager(tab, r.total, r.page, r.size, (p) => this.page(tab, p)),
|
||
el('button.btn.small', { onclick: (e) => this.exportMenu(tab, e.currentTarget) }, t('Export')),
|
||
el('button.btn.small', { title: t('Statements run on {name}', { name: this.db.name(tab.id) }), onclick: () => this.db.history(tab.id) }, t('History')),
|
||
r.sql && !/^EXPLAIN/i.test(tab.title) ? el('button.btn.small', { onclick: () => this.explain(tab.id, r.sql, '') }, t('Explain Plan')) : null);
|
||
if (r.truncated) bar.append(el('span.db-warn', {}, t('only the first {n} rows are kept', { n: r.rows.length && r.totalRows ? Math.min(r.totalRows, 10000) : 10000 })));
|
||
}
|
||
body.append(bar);
|
||
if (!r.hasRows) { body.append(el('div.db-hint', {}, r.summary || '')); return; }
|
||
body.append(this.grid(tab, r, {
|
||
sortIndex: tab.sort, desc: tab.desc,
|
||
onSort: (i) => this.page(tab, 0, { sort: i, desc: tab.sort === i ? !tab.desc : false }),
|
||
}));
|
||
}
|
||
|
||
renderTable(body, tab) {
|
||
const where = el('input.input.db-where', { value: tab.where, placeholder: t('WHERE … (e.g. id > 10)'), onkeydown: (e) => { if (e.key === 'Enter') { tab.where = where.value; tab.page = 0; this.loadTable(tab); } } });
|
||
const changes = tab.edits.size + tab.deletes.size + tab.inserts.length;
|
||
const bar = el('div.db-bar', {}, el('span.db-where-label', {}, 'WHERE'), where,
|
||
el('button.icon-btn', { title: t('Reload'), onclick: () => this.loadTable(tab) }, icon('refresh')));
|
||
if (tab.data) {
|
||
bar.append(this.pager(tab, tab.data.total, tab.data.page, tab.data.size, (p) => { tab.page = p; this.loadTable(tab); }),
|
||
el('button.btn.small', { title: t('Add a row'), onclick: () => { tab.inserts.push({}); this.render(); } }, '+ ' + t('Row')),
|
||
el('button.btn.small' + (changes ? '.primary' : ''), { disabled: !changes, onclick: () => this.saveEdits(tab) }, changes ? t('Save {n} changes…', { n: changes }) : t('Save changes…')),
|
||
el('button.btn.small', { disabled: !changes, onclick: () => { tab.edits = new Map(); tab.deletes = new Set(); tab.inserts = []; this.render(); } }, t('Revert')),
|
||
el('button.btn.small', { onclick: (e) => this.exportMenu(tab, e.currentTarget) }, t('Export')),
|
||
el('button.btn.small', { onclick: () => this.openStructure(tab.id, tab.database, tab.table) }, t('Structure')));
|
||
}
|
||
body.append(bar);
|
||
if (tab.error) { body.append(el('div.db-error', {}, tab.error)); return; }
|
||
if (tab.loading && !tab.data) { body.append(el('div.db-hint', {}, t('Loading…'))); return; }
|
||
if (!tab.data) return;
|
||
if (!tab.data.key?.length) body.append(el('div.db-warn', {}, t('This table has no primary key: an edited row is found again by all its values.')));
|
||
const sortIndex = tab.data.columns.findIndex((col) => col.name === tab.sort);
|
||
body.append(this.grid(tab, tab.data, {
|
||
editable: true, sortIndex: sortIndex >= 0 ? sortIndex : null, desc: tab.desc,
|
||
onSort: (i) => { const name = tab.data.columns[i].name; tab.desc = tab.sort === name ? !tab.desc : false; tab.sort = name; tab.page = 0; this.loadTable(tab); },
|
||
}));
|
||
}
|
||
|
||
/** The grid: a header that sorts, NULL in grey, binary as 0x…; editable: double click a cell, right click a row. */
|
||
grid(tab, r, { editable = false, sortIndex = null, desc = false, onSort }) {
|
||
const table = el('table.db-grid');
|
||
const head = el('tr', {}, el('th.db-rownum', {}, '#'), ...r.columns.map((col, i) => el('th' + (col.numeric ? '.num' : ''), {
|
||
title: col.table ? `${col.table}.${col.column || col.name}` : col.name, onclick: () => onSort(i),
|
||
}, col.name, sortIndex === i ? (desc ? ' ▼' : ' ▲') : '')));
|
||
table.append(el('thead', {}, head));
|
||
const tbody = el('tbody');
|
||
const base = (r.page || 0) * (r.size || 100);
|
||
r.rows.forEach((row, n) => {
|
||
const edits = editable ? tab.edits.get(row.i) || {} : {};
|
||
const deleted = editable && tab.deletes.has(row.i);
|
||
const tr = el('tr' + (deleted ? '.deleted' : ''), { oncontextmenu: editable ? (e) => { e.preventDefault(); this.rowMenu(tab, row, e); } : null },
|
||
el('td.db-rownum', {}, String(base + n + 1)));
|
||
r.columns.forEach((col, i) => {
|
||
const changed = Object.prototype.hasOwnProperty.call(edits, col.name);
|
||
const value = changed ? edits[col.name] : row.v[i];
|
||
const td = el('td' + (col.numeric ? '.num' : '') + (value === null ? '.null' : '') + (changed ? '.changed' : ''), {
|
||
title: value === null ? 'NULL' : String(value).slice(0, 2000),
|
||
ondblclick: editable && !col.binary && !deleted ? () => this.editCell(tab, td, row, col, value) : null,
|
||
}, value === null ? 'NULL' : String(value).slice(0, 300));
|
||
tr.append(td);
|
||
});
|
||
tbody.append(tr);
|
||
});
|
||
if (editable) {
|
||
tab.inserts.forEach((values, n) => {
|
||
const tr = el('tr.inserted', { oncontextmenu: (e) => { e.preventDefault(); menu([{ label: t('Remove this new row'), icon: 'trash', action: () => { tab.inserts.splice(n, 1); this.render(); } }], { x: e.clientX, y: e.clientY }); } },
|
||
el('td.db-rownum', {}, '+'));
|
||
r.columns.forEach((col) => {
|
||
const td = el('td' + (values[col.name] === undefined ? '.default' : ''), {
|
||
ondblclick: () => this.editCell(tab, td, null, col, values[col.name] ?? '', (v) => { values[col.name] = v; }),
|
||
}, values[col.name] === undefined ? t('default') : values[col.name] === null ? 'NULL' : values[col.name]);
|
||
tr.append(td);
|
||
});
|
||
tbody.append(tr);
|
||
});
|
||
}
|
||
table.append(tbody);
|
||
return el('div.db-grid-wrap', {}, table);
|
||
}
|
||
|
||
editCell(tab, td, row, col, value, store = null) {
|
||
const input = el('textarea.db-cell-input', { rows: 1 }, value === null ? '' : String(value));
|
||
clear(td);
|
||
td.append(input);
|
||
input.focus();
|
||
input.select();
|
||
let done = false;
|
||
const commit = (v) => {
|
||
if (done) return;
|
||
done = true;
|
||
if (store) store(v);
|
||
else {
|
||
const original = row.v[tab.data.columns.indexOf(col)];
|
||
const edits = tab.edits.get(row.i) || {};
|
||
if (v === original) delete edits[col.name]; else edits[col.name] = v;
|
||
if (Object.keys(edits).length) tab.edits.set(row.i, edits); else tab.edits.delete(row.i);
|
||
}
|
||
this.render();
|
||
};
|
||
input.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); commit(input.value); }
|
||
if (e.key === 'Escape') { e.preventDefault(); done = true; this.render(); }
|
||
});
|
||
input.addEventListener('blur', () => commit(input.value));
|
||
}
|
||
|
||
rowMenu(tab, row, e) {
|
||
const deleted = tab.deletes.has(row.i);
|
||
menu([
|
||
{ label: deleted ? t('Keep this row') : t('Delete this row'), icon: 'trash', action: () => { if (deleted) tab.deletes.delete(row.i); else tab.deletes.add(row.i); this.render(); } },
|
||
{ label: t('Set a cell to NULL…'), icon: 'minus', action: () => chooser(tab.data.columns.filter((col) => !col.binary).map((col) => ({ label: col.name, action: () => {
|
||
const edits = tab.edits.get(row.i) || {};
|
||
edits[col.name] = null;
|
||
tab.edits.set(row.i, edits);
|
||
this.render();
|
||
} })), { placeholder: t('Which column?') }) },
|
||
{ label: t('Copy the row as JSON'), icon: 'copy', action: () => copyText(JSON.stringify(Object.fromEntries(tab.data.columns.map((col, i) => [col.name, row.v[i]])), null, 2)) },
|
||
], { x: e.clientX, y: e.clientY });
|
||
}
|
||
|
||
async saveEdits(tab) {
|
||
const payload = { id: tab.id, result: tab.data.result, edits: [...tab.edits].map(([index, set]) => ({ index, set })), deletes: [...tab.deletes],
|
||
inserts: tab.inserts.filter((v) => Object.keys(v).length) };
|
||
let preview;
|
||
try { preview = await backend.invoke('db.edit', { ...payload, apply: false }); } catch (e) { notify(e.message, 'error'); return; }
|
||
if (!preview.statements.length) { tab.edits = new Map(); this.render(); return; }
|
||
const c = this.db.conn(tab.id);
|
||
dialog({
|
||
title: preview.production ? t('Production: confirm the changes') : t('Save the changes'),
|
||
wide: true,
|
||
body: el('div.db-form', {},
|
||
preview.production ? el('div.db-prodbar', {}, icon('warning'), t('{name} is a production database.', { name: c?.name || '' })) : null,
|
||
preview.keyless ? el('div.db-warn', {}, t('This table has no primary key: an edited row is found again by all its values.')) : null,
|
||
el('p', {}, t('These statements run in one transaction: if one fails, none is kept.')),
|
||
el('pre.db-sql', {}, preview.statements.join(';\n') + ';')),
|
||
buttons: [{ label: t('Cancel') }, { label: preview.production ? t('Run on production') : t('Run'), primary: !preview.production, danger: preview.production, action: async () => {
|
||
try {
|
||
const r = await backend.invoke('db.edit', { ...payload, apply: true, confirmed: true });
|
||
notify(t('{n} statements run, {rows} rows changed.', { n: r.applied, rows: r.affected }), 'success', { title: tab.table });
|
||
this.loadTable(tab);
|
||
} catch (e) { notify(e.message, 'error', { title: tab.table }); return false; }
|
||
return true;
|
||
} }],
|
||
});
|
||
}
|
||
|
||
renderStructure(body, tab) {
|
||
if (tab.error) { body.append(el('div.db-error', {}, tab.error)); return; }
|
||
if (!tab.info) { body.append(el('div.db-hint', {}, t('Loading…'))); return; }
|
||
const table = (heads, rows) => el('table.db-grid.db-struct', {}, el('thead', {}, el('tr', {}, ...heads.map((h) => el('th', {}, h)))),
|
||
el('tbody', {}, ...rows.map((cells) => el('tr', {}, ...cells.map((v) => el('td' + (v === null ? '.null' : ''), {}, v === null ? 'NULL' : String(v)))))));
|
||
const i = tab.info;
|
||
body.append(el('div.db-bar', {}, el('span.db-summary', {}, `${tab.database}.${i.name}${i.engine ? ' · ' + i.engine : ''}${i.comment ? ' · ' + i.comment : ''}`),
|
||
el('button.btn.small', { onclick: () => this.openTable(tab.id, tab.database, tab.table) }, t('Open the data'))));
|
||
const wrap = el('div.db-grid-wrap');
|
||
wrap.append(el('div.db-section', {}, t('Columns')),
|
||
table([t('Name'), t('Type'), t('Null'), t('Key'), t('Default'), t('Extra'), t('Comment')], i.columns.map((c) => [c.name, c.type, c.nullable ? t('yes') : t('no'), c.key, c.default, c.extra, c.comment])));
|
||
if (i.indexes.length) wrap.append(el('div.db-section', {}, t('Indexes')), table([t('Name'), t('Columns'), t('Unique')], i.indexes.map((x) => [x.name, x.columns.join(', '), x.unique ? t('yes') : t('no')])));
|
||
if (i.foreignKeys.length) wrap.append(el('div.db-section', {}, t('Foreign keys')), table([t('Name'), t('Columns'), t('References')], i.foreignKeys.map((f) => [f.name, f.columns.join(', '), `${f.table}(${f.references.join(', ')})`])));
|
||
const ddl = el('pre.db-sql.db-ddl');
|
||
ddl.textContent = tab.ddl || '';
|
||
if (window.monaco && tab.ddl) window.monaco.editor.colorize(tab.ddl, 'sql', {}).then((html) => { ddl.innerHTML = html; });
|
||
wrap.append(el('div.db-section', {}, 'DDL'), ddl);
|
||
body.append(wrap);
|
||
}
|
||
}
|