1036 lines
72 KiB
JavaScript
1036 lines
72 KiB
JavaScript
// The Doctrine window (desktop IDE, bottom; projects with Doctrine ORM): the entities of the project read from their
|
||
// #[ORM\...] attributes (and XML mappings) by ide/src/Doctrine, without running anything.
|
||
// - Diagram: a box per entity, mapped superclass, embeddable and enum, their relations (owning side, inverse side, cardinalities,
|
||
// cascade, join tables), inheritance and embedded classes; pan / zoom, filter, a click focuses an entity and its neighbours,
|
||
// a click on a relation follows it, a double click opens the PHP file at the class or property.
|
||
// - Entity: the editor: fields with every Doctrine type, relations written on both sides, rename everywhere (preview), DTOs,
|
||
// the table's data and the mapping beside the real table (the Database window's connection). Every change is a diff first.
|
||
// - DQL: a visual builder (root entity, joins along relations, fields, conditions, order) writing DQL or QueryBuilder code,
|
||
// run through the console (doctrine:query:dql --show-sql) and the Database window (SQL Results).
|
||
// - Migrations: the history (executed with dates, pending, no longer available), migrate / roll back / execute one, diff with
|
||
// the SQL shown first; a production connection asks for its name before anything runs.
|
||
// Also: DQL completion in PHP strings (createQuery('...'), ->where('...')...), and actions in Search Everywhere.
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, notify, prefs, t, confirm, prompt, dialog, menu, chooser, copyText } from './ui.js';
|
||
import { packageNotice, warnMissing } from './api-install.js';
|
||
import { graph, layout, boxSize, neighbours, matches, anchors, curve, ends } from './doctrine-layout.js';
|
||
import { FIELD_TYPES, RELATION_KINDS, newRow, setType, has, validate, toBackend, previewRow, move } from './doctrine-fields.js';
|
||
import { emptyQuery, buildDql, buildQueryBuilder, parameters, inlineParameters, joinable, aliases, defaultAlias, OPERATORS } from './dql-model.js';
|
||
|
||
const cssHref = new URL('../css/doctrine.css', import.meta.url).href;
|
||
if (![...document.querySelectorAll('link[rel=stylesheet]')].some((l) => l.href === cssHref)) document.head.append(el('link', { rel: 'stylesheet', href: cssHref }));
|
||
|
||
const short = (c) => String(c || '').split('\\').pop();
|
||
const TYPES = ['string', 'text', 'integer', 'smallint', 'bigint', 'boolean', 'float', 'decimal', 'datetime_immutable', 'datetime', 'date_immutable', 'date',
|
||
'time_immutable', 'time', 'datetimetz_immutable', 'dateinterval', 'json', 'simple_array', 'guid', 'uuid', 'ulid', 'ascii_string', 'binary', 'blob', 'smallfloat'];
|
||
const KIND_SHORT = { ManyToOne: 'N–1', OneToMany: '1–N', OneToOne: '1–1', ManyToMany: 'N–N' };
|
||
const ROW = 18;
|
||
|
||
export class DoctrinePanel {
|
||
constructor(app) {
|
||
this.app = app;
|
||
this.node = el('div.dc-view');
|
||
this.tab = prefs.get('doctrineTab', 'diagram');
|
||
this.mapping = null;
|
||
this.filter = '';
|
||
this.focus = null;
|
||
this.depth = 1;
|
||
this.trail = [];
|
||
this.selected = prefs.get('doctrineEntity:' + app.projectKey, null);
|
||
this.showFields = prefs.get('doctrineFields', true);
|
||
this.positions = prefs.get('doctrinePos:' + app.projectKey, {});
|
||
this.view = null;
|
||
this.query = null;
|
||
this.migrations = null;
|
||
this.log = [];
|
||
this.whenMonaco();
|
||
}
|
||
|
||
title() { return 'Doctrine'; }
|
||
|
||
actions() {
|
||
return [
|
||
el('button', { 'data-tour': 'doctrine-new-entity', title: t('New entity…'), onclick: () => this.newEntity() }, icon('plus')),
|
||
el('button', { title: t('Migrations'), onclick: () => this.show('migrations') }, icon('history')),
|
||
el('button', { title: t('Check the database schema'), onclick: () => this.app.schemaCheck?.check() }, icon('database')),
|
||
el('button', { title: t('Refresh'), onclick: () => this.load(true) }, icon('refresh')),
|
||
el('button', { title: t('Bigger: the whole window (Escape: back)'), onclick: () => this.maximize() }, icon('expand')),
|
||
];
|
||
}
|
||
|
||
shown() { if (!this.mapping) this.load(); else this.render(); }
|
||
|
||
maximize(on = !this.node.classList.contains('dc-max')) {
|
||
this.node.classList.toggle('dc-max', on);
|
||
if (on) {
|
||
const off = (e) => { if (e.key === 'Escape') { this.maximize(false); } };
|
||
this.escape = off;
|
||
document.addEventListener('keydown', off);
|
||
} else if (this.escape) document.removeEventListener('keydown', this.escape);
|
||
this.view = null; // fit again in the new size
|
||
if (this.tab === 'diagram') this.render();
|
||
}
|
||
|
||
/** the tool window, on a tab */
|
||
show(tab) {
|
||
this.tab = tab;
|
||
prefs.set('doctrineTab', tab);
|
||
this.app.showTool('doctrine', true);
|
||
this.render();
|
||
}
|
||
|
||
async load(refresh = false) {
|
||
try {
|
||
this.mapping = await backend.invoke('doctrine.mapping', {});
|
||
if (refresh) this.view = null;
|
||
} catch (e) { notify(e.message, 'error', { title: 'Doctrine' }); this.mapping = { entities: [], enums: [], errors: [] }; }
|
||
this.render();
|
||
if (this.tab === 'migrations' && !this.migrations) this.loadMigrations();
|
||
}
|
||
|
||
entity(cls) { return this.mapping?.entities.find((e) => e.class === cls) || null; }
|
||
|
||
render() {
|
||
const scroll = this.node.querySelector('.dc-body')?.scrollTop || 0;
|
||
clear(this.node);
|
||
const tabs = [['diagram', t('Diagram'), 'hierarchy'], ['entity', t('Entity'), 'structure'], ['dql', 'DQL', 'console'], ['migrations', t('Migrations'), 'history']];
|
||
this.node.append(el('div.dc-tabs', {}, ...tabs.map(([id, label, ico]) => el('button.dc-tab' + (this.tab === id ? '.on' : ''), {
|
||
'data-tour': 'doctrine-tab-' + id,
|
||
onclick: () => { this.tab = id; prefs.set('doctrineTab', id); this.render(); if (id === 'migrations' && !this.migrations) this.loadMigrations(); },
|
||
}, icon(ico), label)), el('span.dc-spacer'),
|
||
this.mapping?.errors?.length ? el('span.dc-warn', { title: this.mapping.errors.map((x) => `${x.file}: ${x.message}`).join('\n') }, icon('warning'), t('{n} files not read', { n: this.mapping.errors.length })) : null));
|
||
const body = el('div.dc-body');
|
||
this.node.append(body);
|
||
if (!this.mapping) { body.append(el('div.dc-hint', {}, t('Loading…'))); return; }
|
||
if (this.tab === 'diagram') this.renderDiagram(body);
|
||
else if (this.tab === 'entity') this.renderEntity(body);
|
||
else if (this.tab === 'dql') this.renderDql(body);
|
||
else this.renderMigrations(body);
|
||
body.scrollTop = scroll;
|
||
}
|
||
|
||
// the diagram ---------------------------------------------------------------------------------------------------
|
||
|
||
renderDiagram(body) {
|
||
const g = graph(this.mapping, { fields: this.showFields });
|
||
if (!g.nodes.length) {
|
||
body.append(el('div.dc-empty', {}, el('p', {}, t('No Doctrine entity in this project yet.')), el('button.btn.primary', { onclick: () => this.newEntity() }, t('New entity…'))));
|
||
return;
|
||
}
|
||
const byId = new Map(g.nodes.map((n) => [n.id, n]));
|
||
let visible = g.nodes.filter((n) => matches(n, this.filter));
|
||
if (this.focus && byId.has(this.focus)) {
|
||
const near = neighbours(g.edges, this.focus, this.depth);
|
||
visible = g.nodes.filter((n) => near.has(n.id));
|
||
}
|
||
const ids = new Set(visible.map((n) => n.id));
|
||
const edges = g.edges.filter((e) => ids.has(e.from) && ids.has(e.to));
|
||
const boxes = visible.map((n) => ({ id: n.id, ...boxSize(n) }));
|
||
const auto = layout(boxes, edges, { maxWidth: 1500 });
|
||
const pos = {};
|
||
for (const b of boxes) pos[b.id] = { ...b, ...((!this.focus && this.positions[b.id]) || auto[b.id]) };
|
||
|
||
const filter = el('input.input.dc-filter', { value: this.filter, placeholder: t('Filter: class, table, field (is:api, is:embeddable)'),
|
||
oninput: () => { this.filter = filter.value; this.focus = null; this.trail = []; this.view = null; this.redraw(); } });
|
||
const bar = el('div.dc-bar', {}, filter,
|
||
el('label.dc-check', {}, el('input', { type: 'checkbox', checked: this.showFields, onchange: (e) => { this.showFields = e.target.checked; prefs.set('doctrineFields', this.showFields); this.view = null; this.render(); } }), t('Fields')),
|
||
el('button.btn.small', { title: t('Place the boxes again'), onclick: () => { this.positions = {}; prefs.set('doctrinePos:' + this.app.projectKey, {}); this.view = null; this.render(); } }, t('Layout')),
|
||
el('button.btn.small', { onclick: () => { this.view = null; this.render(); } }, t('Fit')),
|
||
el('span.dc-legend', {}, el('i.l-own'), t('owning side'), el('i.l-inv'), t('inverse side'), el('i.l-inh'), t('inheritance'), el('i.l-emb'), t('embedded')));
|
||
body.append(bar);
|
||
if (this.focus) {
|
||
bar.after(el('div.dc-trail', {}, el('span', {}, t('Following:')),
|
||
...this.trail.map((c, i) => el('a', { onclick: () => { this.trail = this.trail.slice(0, i + 1); this.focus = c; this.view = null; this.render(); } }, short(c))),
|
||
el('span.dc-sep', {}, t('Depth')),
|
||
...[1, 2, 3].map((d) => el('button.dc-depth' + (this.depth === d ? '.on' : ''), { onclick: () => { this.depth = d; this.view = null; this.render(); } }, String(d))),
|
||
el('button.btn.small', { onclick: () => { this.focus = null; this.trail = []; this.view = null; this.render(); } }, t('Show all'))));
|
||
}
|
||
const canvas = el('div.dc-canvas');
|
||
const world = el('div.dc-world');
|
||
canvas.append(world);
|
||
body.append(canvas);
|
||
const maxX = Math.max(...Object.values(pos).map((p) => p.x + p.w)) + 40;
|
||
const maxY = Math.max(...Object.values(pos).map((p) => p.y + p.h)) + 40;
|
||
const svgNs = 'http://www.w3.org/2000/svg';
|
||
const svg = document.createElementNS(svgNs, 'svg');
|
||
svg.setAttribute('width', maxX);
|
||
svg.setAttribute('height', maxY);
|
||
svg.classList.add('dc-edges');
|
||
svg.innerHTML = '<defs><marker id="dcArrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="m-arrow"/></marker>'
|
||
+ '<marker id="dcTri" viewBox="0 0 12 12" refX="12" refY="6" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M0,0 L12,6 L0,12 z" class="m-tri"/></marker>'
|
||
+ '<marker id="dcDiamond" viewBox="0 0 14 10" refX="0" refY="5" markerWidth="12" markerHeight="9" orient="auto-start-reverse"><path d="M0,5 L7,0 L14,5 L7,10 z" class="m-dia"/></marker></defs>';
|
||
world.append(svg);
|
||
const label = (x, y, text, cls = '') => { const n = document.createElementNS(svgNs, 'text'); n.setAttribute('x', x); n.setAttribute('y', y); n.setAttribute('class', 'dc-elabel ' + cls); n.textContent = text; svg.append(n); };
|
||
for (const e of edges) {
|
||
const a = pos[e.from];
|
||
const b = pos[e.to];
|
||
const [p, q] = anchors(a, b);
|
||
const path = document.createElementNS(svgNs, 'path');
|
||
path.setAttribute('d', curve(p, q));
|
||
path.setAttribute('class', 'dc-edge e-' + e.kind + (e.kind === 'relation' && !e.bidirectional ? ' e-uni' : ''));
|
||
if (e.kind === 'inheritance') path.setAttribute('marker-end', 'url(#dcTri)');
|
||
else if (e.kind === 'embedded') path.setAttribute('marker-start', 'url(#dcDiamond)');
|
||
else if (e.kind === 'relation' && !e.bidirectional) path.setAttribute('marker-end', 'url(#dcArrow)');
|
||
const tip = document.createElementNS(svgNs, 'title');
|
||
tip.textContent = e.kind === 'relation'
|
||
? `${short(e.from)}.${e.fromField} ${e.relation} ${short(e.to)}${e.toField ? '.' + e.toField : ''}${e.cascade?.length ? ' · cascade: ' + e.cascade.join(', ') : ''}${e.orphanRemoval ? ' · orphanRemoval' : ''}${e.joinTable ? ' · ' + e.joinTable : ''}`
|
||
: `${short(e.from)} → ${short(e.to)} (${e.kind}${e.label ? ': ' + e.label : ''})`;
|
||
path.append(tip);
|
||
svg.append(path);
|
||
if (e.kind === 'relation') {
|
||
const [m1, m2] = ends(e.relation);
|
||
const off = (pt, s) => ({ x: pt.x + (s === 'r' ? 8 : s === 'l' ? -14 : 6), y: pt.y + (s === 'b' ? 14 : s === 't' ? -6 : -6) });
|
||
const o1 = off(p, p.side);
|
||
const o2 = off(q, q.side);
|
||
label(o1.x, o1.y, m1, 'mult');
|
||
label(o2.x, o2.y, m2, 'mult');
|
||
if (e.joinTable) label((p.x + q.x) / 2, (p.y + q.y) / 2 - 4, e.joinTable, 'jt');
|
||
} else if (e.kind === 'inheritance' && e.label) label((p.x + q.x) / 2 + 4, (p.y + q.y) / 2, e.label, 'inh');
|
||
}
|
||
for (const n of visible) world.append(this.box(n, pos[n.id], byId));
|
||
// pan and zoom: the whole diagram fits the first time
|
||
const apply = () => { world.style.transform = `translate(${this.view.x}px, ${this.view.y}px) scale(${this.view.k})`; };
|
||
requestAnimationFrame(() => {
|
||
if (!canvas.isConnected) return; // drawn again since (maximized, filtered): that one fits
|
||
if (!this.view) {
|
||
const w = canvas.clientWidth || 800;
|
||
const h = canvas.clientHeight || 400;
|
||
const k = Math.max(0.2, Math.min(1.1, (w - 20) / maxX, (h - 20) / maxY));
|
||
this.view = { k, x: Math.max(10, (w - maxX * k) / 2), y: Math.max(10, (h - maxY * k) / 2) };
|
||
}
|
||
apply();
|
||
});
|
||
if (this.view) apply();
|
||
canvas.addEventListener('wheel', (e) => {
|
||
e.preventDefault();
|
||
const r = canvas.getBoundingClientRect();
|
||
const mx = e.clientX - r.left;
|
||
const my = e.clientY - r.top;
|
||
const k = Math.max(0.15, Math.min(2.5, this.view.k * (e.deltaY < 0 ? 1.1 : 1 / 1.1)));
|
||
this.view = { k, x: mx - (mx - this.view.x) * (k / this.view.k), y: my - (my - this.view.y) * (k / this.view.k) };
|
||
apply();
|
||
}, { passive: false });
|
||
canvas.addEventListener('mousedown', (e) => {
|
||
if (e.button !== 0 || e.target.closest('.dc-box')) return;
|
||
const start = { x: e.clientX, y: e.clientY, vx: this.view.x, vy: this.view.y };
|
||
canvas.classList.add('panning');
|
||
const move = (m) => { this.view.x = start.vx + m.clientX - start.x; this.view.y = start.vy + m.clientY - start.y; apply(); };
|
||
const up = () => { canvas.classList.remove('panning'); removeEventListener('mousemove', move); removeEventListener('mouseup', up); };
|
||
addEventListener('mousemove', move);
|
||
addEventListener('mouseup', up);
|
||
});
|
||
}
|
||
|
||
redraw() {
|
||
const filter = this.node.querySelector('.dc-filter');
|
||
const at = filter?.selectionStart;
|
||
this.render();
|
||
const again = this.node.querySelector('.dc-filter');
|
||
if (again) { again.focus(); again.setSelectionRange(at, at); }
|
||
}
|
||
|
||
box(n, p, byId) {
|
||
const e = n.entity;
|
||
const badges = [];
|
||
if (n.kind === 'mappedSuperclass') badges.push(['MS', t('mapped superclass')]);
|
||
if (n.kind === 'embeddable') badges.push(['EMB', t('embeddable')]);
|
||
if (n.kind === 'enum') badges.push(['ENUM', t('PHP enum') + (n.enum.backing ? ': ' + n.enum.backing : '')]);
|
||
if (e?.inheritance?.type === 'SINGLE_TABLE') badges.push(['STI', t('single table inheritance') + (e.inheritance.root ? '' : ' · ' + t('discriminator') + ' ' + (e.inheritance.column?.name || 'dtype'))]);
|
||
if (e?.inheritance?.type === 'JOINED') badges.push(['CTI', t('class table inheritance (joined)')]);
|
||
if (e?.abstract) badges.push(['abs', t('abstract')]);
|
||
if (e?.api) badges.push(['API', t('API Platform resource')]);
|
||
if (e?.repository) badges.push(['repo', t('Repository: {name}', { name: short(e.repository) })]);
|
||
const head = el('div.dc-head', {
|
||
ondblclick: (ev) => { ev.stopPropagation(); this.open(e?.file || n.enum?.file, e?.line || n.enum?.line); },
|
||
}, el('span.dc-name', {}, short(n.id)), ...badges.map(([b, title]) => el('span.dc-badge.b-' + b.toLowerCase(), {
|
||
title, onclick: b === 'repo' && e.repositoryFile ? (ev) => { ev.stopPropagation(); this.open(e.repositoryFile, 1); } : null,
|
||
}, b)));
|
||
const sub = e ? el('div.dc-sub', {}, e.kind === 'entity' ? e.table : e.kind === 'embeddable' ? t('embeddable') : t('mapped superclass')) : el('div.dc-sub', {}, n.enum.class);
|
||
const rows = el('div.dc-rows');
|
||
if (this.showFields && e) {
|
||
for (const f of e.fields) {
|
||
const flags = [f.nullable ? '?' : '', f.unique ? 'U' : '', f.generated ? 'AI' : ''].filter(Boolean).join(' ');
|
||
const type = f.enumType ? short(f.enumType) : f.type + (f.length ? `(${f.length})` : f.precision ? `(${f.precision},${f.scale ?? 0})` : '');
|
||
rows.append(el('div.dc-row' + (f.id ? '.pk' : '') + (f.inherited ? '.inh' : ''), {
|
||
title: `${f.name}: ${f.type}${f.enumType ? ' (' + f.enumType + ')' : ''} · ${t('column')} ${f.column}${f.nullable ? ' · nullable' : ''}${f.unique ? ' · unique' : ''}${f.inherited ? ' · ' + t('from {name}', { name: short(f.inherited) }) : ''}`,
|
||
ondblclick: (ev) => { ev.stopPropagation(); this.open(f.inherited ? this.entity(f.inherited)?.file : e.file, f.line); },
|
||
}, el('span.dc-k', {}, f.id ? 'PK' : ''), el('span.dc-f', {}, f.name), el('span.dc-flags', {}, flags), el('span.dc-t', {}, type)));
|
||
}
|
||
for (const em of e.embedded) {
|
||
rows.append(el('div.dc-row.emb', { title: `${em.name}: ${em.class}${em.columnPrefix ? ' · prefix ' + em.columnPrefix : ''}`, ondblclick: (ev) => { ev.stopPropagation(); this.open(e.file, em.line); } },
|
||
el('span.dc-k', {}, '◇'), el('span.dc-f', {}, em.name), el('span.dc-flags'), el('span.dc-t', {}, short(em.class))));
|
||
}
|
||
for (const r of e.relations) {
|
||
const target = byId.has(r.target);
|
||
rows.append(el('div.dc-row.rel' + (r.owning ? '.own' : '.inv') + (r.inherited ? '.inh' : ''), {
|
||
title: `${r.name}: ${r.kind} ${r.target} · ${r.owning ? t('owning side') : t('inverse side')}${r.mappedBy ? ' · mappedBy ' + r.mappedBy : ''}${r.inversedBy ? ' · inversedBy ' + r.inversedBy : ''}`
|
||
+ `${r.cascade?.length ? ' · cascade ' + r.cascade.join(', ') : ''}${r.orphanRemoval ? ' · orphanRemoval' : ''}${r.joinColumns?.[0]?.name ? ' · ' + r.joinColumns[0].name : ''}${r.joinTable?.name ? ' · ' + r.joinTable.name : ''}\n${t('Click: follow the relation')}`,
|
||
onclick: target ? (ev) => { ev.stopPropagation(); this.follow(r.target, e.class); } : null,
|
||
ondblclick: (ev) => { ev.stopPropagation(); this.open(e.file, r.line); },
|
||
}, el('span.dc-k', {}, r.owning ? '→' : '⇢'), el('span.dc-f', {}, r.name), el('span.dc-flags', {}, KIND_SHORT[r.kind] || ''), el('span.dc-t', {}, short(r.target))));
|
||
}
|
||
} else if (this.showFields && n.enum) {
|
||
for (const c of n.enum.cases) rows.append(el('div.dc-row', {}, el('span.dc-k'), el('span.dc-f', {}, c.name), el('span.dc-flags'), el('span.dc-t', {}, c.value === null ? '' : JSON.stringify(c.value))));
|
||
}
|
||
const node = el('div.dc-box.k-' + n.kind + (this.focus === n.id ? '.focus' : '') + (this.selected === n.id ? '.sel' : ''), {
|
||
style: { left: p.x + 'px', top: p.y + 'px', width: p.w + 'px', minHeight: p.h + 'px' },
|
||
oncontextmenu: (ev) => { ev.preventDefault(); if (e) this.entityMenu(e, ev); },
|
||
}, head, sub, rows);
|
||
// drag a box by its title; a click (no move) focuses it
|
||
head.addEventListener('mousedown', (ev) => {
|
||
if (ev.button !== 0) return;
|
||
ev.stopPropagation();
|
||
const start = { x: ev.clientX, y: ev.clientY, left: p.x, top: p.y };
|
||
let moved = false;
|
||
const move = (m) => {
|
||
const dx = (m.clientX - start.x) / this.view.k;
|
||
const dy = (m.clientY - start.y) / this.view.k;
|
||
if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
|
||
if (!moved) return;
|
||
node.style.left = start.left + dx + 'px';
|
||
node.style.top = start.top + dy + 'px';
|
||
};
|
||
const up = (m) => {
|
||
removeEventListener('mousemove', move);
|
||
removeEventListener('mouseup', up);
|
||
if (moved && !this.focus) {
|
||
this.positions[n.id] = { x: Math.round(start.left + (m.clientX - start.x) / this.view.k), y: Math.round(start.top + (m.clientY - start.y) / this.view.k) };
|
||
prefs.set('doctrinePos:' + this.app.projectKey, this.positions);
|
||
this.render();
|
||
} else if (!moved) this.select(n.id);
|
||
};
|
||
addEventListener('mousemove', move);
|
||
addEventListener('mouseup', up);
|
||
});
|
||
return node;
|
||
}
|
||
|
||
/** a click on a box: it becomes the focus, with its neighbours */
|
||
select(id) {
|
||
if (this.entity(id)) { this.selected = id; prefs.set('doctrineEntity:' + this.app.projectKey, id); }
|
||
if (this.focus !== id) { this.focus = id; this.trail = [id]; }
|
||
this.view = null;
|
||
this.render();
|
||
}
|
||
|
||
/** a click on a relation: one step further along it */
|
||
follow(target, from) {
|
||
if (!this.focus) this.trail = [from];
|
||
const at = this.trail.indexOf(target);
|
||
this.trail = at >= 0 ? this.trail.slice(0, at + 1) : [...this.trail, target];
|
||
this.focus = target;
|
||
if (this.entity(target)) { this.selected = target; prefs.set('doctrineEntity:' + this.app.projectKey, target); }
|
||
this.view = null;
|
||
this.render();
|
||
}
|
||
|
||
open(path, line) {
|
||
if (!path) return;
|
||
this.app.editors.open(path, line ? { line } : {});
|
||
}
|
||
|
||
entityMenu(e, ev) {
|
||
menu([
|
||
{ label: t('Edit the entity'), icon: 'edit', action: () => { this.selected = e.class; this.show('entity'); } },
|
||
{ label: t('Open the PHP file'), icon: 'code', action: () => this.open(e.file, e.line) },
|
||
...(this.app.apiPlatform ? [{ label: t('API Platform…'), icon: 'structure', action: () => this.app.apiPlatform.show(e.class) }] : []),
|
||
e.repositoryFile ? { label: t('Open the repository'), icon: 'code', action: () => this.open(e.repositoryFile, 1) } : null,
|
||
'-',
|
||
e.kind === 'entity' ? { label: t('Show the table\'s data'), icon: 'database', action: () => this.tableData(e) } : null,
|
||
e.kind === 'entity' ? { label: t('Compare the mapping with the table'), icon: 'diff', action: () => this.compare(e) } : null,
|
||
e.kind === 'entity' ? { label: t('New DQL query from here'), icon: 'console', action: () => { this.query = emptyQuery(e.class); this.show('dql'); } } : null,
|
||
{ label: t('Generate DTOs…'), icon: 'plus', action: () => this.dtos(e) },
|
||
'-',
|
||
{ label: t('Copy the class name'), icon: 'copy', action: () => copyText(e.class) },
|
||
].filter(Boolean), ev);
|
||
}
|
||
|
||
// the entity editor ---------------------------------------------------------------------------------------------
|
||
|
||
renderEntity(body) {
|
||
const entities = this.mapping.entities;
|
||
const e = this.entity(this.selected) || entities.find((x) => x.kind === 'entity') || entities[0];
|
||
const pick = el('select.input.dc-pick', { onchange: (ev) => { this.selected = ev.target.value; prefs.set('doctrineEntity:' + this.app.projectKey, this.selected); this.render(); } },
|
||
...entities.map((x) => el('option', { value: x.class, selected: x === e }, short(x.class) + (x.kind !== 'entity' ? ` (${x.kind})` : ''))));
|
||
body.append(el('div.dc-bar', {}, pick, el('button.btn.small', { onclick: () => this.newEntity() }, t('New entity…')),
|
||
e ? el('button.btn.small', { onclick: () => this.dtos(e) }, t('Generate DTOs…')) : null,
|
||
e?.kind === 'entity' ? el('button.btn.small', { onclick: () => this.tableData(e) }, t('Show the table\'s data')) : null,
|
||
e?.kind === 'entity' ? el('button.btn.small', { onclick: () => this.compare(e) }, t('Compare with the table')) : null));
|
||
if (!e) { body.append(el('div.dc-hint', {}, t('No Doctrine entity in this project yet.'))); return; }
|
||
const facts = [[t('Class'), e.class], [t('Database table'), e.kind === 'entity' ? e.table + (e.tableImplicit ? ' (' + t('from the class name') + ')' : '') : '—'],
|
||
[t('Repository'), e.repository || '—'], [t('Inheritance'), e.inheritance ? `${e.inheritance.type}${e.inheritance.root ? ' ← ' + short(e.inheritance.root) : ''}${e.inheritance.column ? ' · ' + e.inheritance.column.name : ''}` : (e.parent ? '← ' + short(e.parent) : '—')],
|
||
['API Platform', el('span', {}, e.api ? t('yes') : t('no'), this.app.apiPlatform ? el('a.dc-link', { style: { marginLeft: '8px' }, onclick: () => this.app.apiPlatform.show(e.class) }, t('API Platform…')) : null)]];
|
||
body.append(el('div.dc-facts', {}, ...facts.map(([k, v]) => el('div', {}, el('span.dc-fk', {}, k), el('span.dc-fv', {}, v))),
|
||
el('a.dc-link', { onclick: () => this.open(e.file, e.line) }, e.file)));
|
||
// fields
|
||
body.append(el('div.dc-section', {}, t('Fields'), el('button.btn.small', { onclick: () => this.fieldForm(e) }, t('Add a field'))));
|
||
const ft = el('table.dc-table', {}, el('tr', {}, ...[t('Name'), t('Type'), t('Column'), t('Length'), t('Nullable'), t('Unique'), ''].map((h) => el('th', {}, h))));
|
||
for (const f of e.fields) {
|
||
ft.append(el('tr' + (f.inherited ? '.inh' : ''), {},
|
||
el('td', {}, el('a', { onclick: () => this.open(f.inherited ? this.entity(f.inherited)?.file : e.file, f.line) }, f.name), f.id ? el('span.dc-badge.b-pk', {}, 'PK') : null),
|
||
el('td', {}, f.enumType ? `${f.type} · ${short(f.enumType)}` : f.type), el('td.mono', {}, f.column), el('td', {}, f.length ?? (f.precision ? `${f.precision},${f.scale ?? 0}` : '')),
|
||
el('td', {}, f.nullable ? '✓' : ''), el('td', {}, f.unique ? '✓' : ''),
|
||
el('td.dc-acts', {}, f.inherited ? el('span.dc-sub', {}, t('from {name}', { name: short(f.inherited) })) : [
|
||
el('button.icon-btn', { title: t('Edit'), onclick: () => this.fieldForm(e, f) }, icon('edit')),
|
||
el('button.icon-btn', { title: t('Rename everywhere…'), onclick: () => this.rename(e, f.name) }, icon('refresh')),
|
||
f.id ? null : el('button.icon-btn', { title: t('Remove'), onclick: () => this.removeProperty(e, f.name) }, icon('trash'))])));
|
||
}
|
||
body.append(ft);
|
||
// relations
|
||
body.append(el('div.dc-section', {}, t('Relations'), el('button.btn.small', { onclick: () => this.relationForm(e) }, t('Add a relation'))));
|
||
if (!e.relations.length) body.append(el('div.dc-hint', {}, t('No relation.')));
|
||
else {
|
||
const rt = el('table.dc-table', {}, el('tr', {}, ...[t('Name'), t('Kind'), t('Target'), t('Side'), 'mappedBy / inversedBy', 'cascade', ''].map((h) => el('th', {}, h))));
|
||
for (const r of e.relations) {
|
||
rt.append(el('tr' + (r.inherited ? '.inh' : ''), {},
|
||
el('td', {}, el('a', { onclick: () => this.open(e.file, r.line) }, r.name)), el('td', {}, r.kind),
|
||
el('td', {}, el('a', { onclick: () => { this.selected = r.target; this.render(); } }, short(r.target))),
|
||
el('td', {}, r.owning ? t('owning side') : t('inverse side')), el('td.mono', {}, r.mappedBy || r.inversedBy || '—'),
|
||
el('td', {}, [...(r.cascade || []), r.orphanRemoval ? 'orphanRemoval' : ''].filter(Boolean).join(', ')),
|
||
el('td.dc-acts', {}, r.inherited ? null : [el('button.icon-btn', { title: t('Rename everywhere…'), onclick: () => this.rename(e, r.name) }, icon('refresh')),
|
||
el('button.icon-btn', { title: t('Remove'), onclick: () => this.removeProperty(e, r.name) }, icon('trash'))])));
|
||
}
|
||
body.append(rt);
|
||
}
|
||
if (e.embedded.length) {
|
||
body.append(el('div.dc-section', {}, t('Embedded')));
|
||
for (const em of e.embedded) body.append(el('div.dc-line', {}, el('a', { onclick: () => this.open(e.file, em.line) }, em.name), ' : ', short(em.class), em.columnPrefix ? ` (${em.columnPrefix})` : ''));
|
||
}
|
||
}
|
||
|
||
fieldForm(e, f = null) {
|
||
const enums = this.mapping.enums || [];
|
||
const v = f || { name: '', type: 'string', length: 255, nullable: false, unique: false, enumType: null };
|
||
const input = (value, attrs = {}) => el('input.input', { value: value ?? '', ...attrs });
|
||
const name = input(v.name, { placeholder: 'title', disabled: !!f });
|
||
const type = el('select.input', {}, ...TYPES.map((x) => el('option', { value: x, selected: !v.enumType && v.type === x }, x)),
|
||
enums.length ? el('option', { value: '@enum', selected: !!v.enumType }, t('PHP enum…')) : null);
|
||
const enumType = el('select.input', {}, ...enums.map((x) => el('option', { value: x.class, selected: v.enumType === x.class }, `${short(x.class)}${x.backing ? ' (' + x.backing + ')' : ''}`)));
|
||
const length = input(v.length ?? '', { type: 'number', min: 1 });
|
||
const precision = input(v.precision ?? 10, { type: 'number', min: 1 });
|
||
const scale = input(v.scale ?? 2, { type: 'number', min: 0 });
|
||
const nullable = el('input', { type: 'checkbox', checked: !!v.nullable });
|
||
const unique = el('input', { type: 'checkbox', checked: !!v.unique });
|
||
const row = (label, node) => el('label.db-field', {}, el('span', {}, label), node);
|
||
const lenRow = row(t('Length'), length);
|
||
const decRow = el('div.db-two', {}, row(t('Precision'), precision), row(t('Scale'), scale));
|
||
const enumRow = row(t('Enum'), enumType);
|
||
const sync = () => {
|
||
lenRow.hidden = !['string', 'ascii_string', 'binary'].includes(type.value);
|
||
decRow.hidden = type.value !== 'decimal';
|
||
enumRow.hidden = type.value !== '@enum';
|
||
};
|
||
type.addEventListener('change', sync);
|
||
sync();
|
||
dialog({
|
||
title: f ? t('Edit the field {name}', { name: f.name }) : t('Add a field to {name}', { name: e.name }), wide: true,
|
||
body: el('div.db-form', {}, row(t('Name'), name), row(t('Type'), type), enumRow, lenRow, decRow,
|
||
el('label.db-check', {}, nullable, t('Nullable (may be empty)')), el('label.db-check', {}, unique, t('Unique')),
|
||
el('p.db-hint', {}, t('The property, its #[ORM\\Column] and its getter / setter are written in {file}; you see the change before it is saved.', { file: e.file }))),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Show the change'), primary: true, action: async () => {
|
||
const field = { name: name.value.trim(), type: type.value === '@enum' ? 'string' : type.value, enumType: type.value === '@enum' ? enumType.value : null,
|
||
length: length.value ? Number(length.value) : null, precision: Number(precision.value), scale: Number(scale.value), nullable: nullable.checked, unique: unique.checked };
|
||
const r = await backend.invoke(f ? 'doctrine.field.update' : 'doctrine.field.add', { class: e.class, name: f?.name, field });
|
||
this.preview(r.changes, { title: f ? t('Edit the field {name}', { name: f.name }) : t('Add a field to {name}', { name: e.name }) });
|
||
} }],
|
||
});
|
||
}
|
||
|
||
relationForm(e) {
|
||
const entities = this.mapping.entities.filter((x) => x.kind === 'entity');
|
||
const kinds = [
|
||
['ManyToOne', t('ManyToOne: each {a} has one {b} (a {b} has many {a})')],
|
||
['OneToMany', t('OneToMany: each {a} has many {b} (each {b} has one {a})')],
|
||
['ManyToMany', t('ManyToMany: each {a} has many {b}, each {b} has many {a}')],
|
||
['OneToOne', t('OneToOne: each {a} has one {b}, and the other way round')],
|
||
];
|
||
const target = el('select.input', {}, ...entities.map((x) => el('option', { value: x.class }, short(x.class))));
|
||
const kind = el('select.input');
|
||
const prop = el('input.input', { placeholder: 'author' });
|
||
const inverse = el('input.input', { placeholder: 'posts' });
|
||
const both = el('input', { type: 'checkbox', checked: true });
|
||
const nullable = el('input', { type: 'checkbox', checked: true });
|
||
const persist = el('input', { type: 'checkbox' });
|
||
const remove = el('input', { type: 'checkbox' });
|
||
const orphan = el('input', { type: 'checkbox' });
|
||
const onDelete = el('select.input', {}, el('option', { value: '' }, t('(nothing: the database refuses)')), el('option', { value: 'CASCADE' }, 'CASCADE'), el('option', { value: 'SET NULL' }, 'SET NULL'));
|
||
const joinTable = el('input.input', { placeholder: t('(automatic)') });
|
||
const row = (label, node) => el('label.db-field', {}, el('span', {}, label), node);
|
||
const fill = () => {
|
||
const a = e.name;
|
||
const b = short(target.value);
|
||
const selected = kind.value || 'ManyToOne';
|
||
clear(kind);
|
||
for (const [k, text] of kinds) kind.append(el('option', { value: k, selected: k === selected }, text.replace(/\{a\}/g, a).replace(/\{b\}/g, b)));
|
||
const many = ['OneToMany', 'ManyToMany'].includes(kind.value);
|
||
const otherMany = ['ManyToOne', 'ManyToMany'].includes(kind.value);
|
||
const lc = (s) => s.charAt(0).toLowerCase() + s.slice(1);
|
||
if (!prop.dataset.typed) prop.value = many ? plural(lc(b)) : lc(b);
|
||
if (!inverse.dataset.typed) inverse.value = otherMany ? plural(lc(a)) : lc(a);
|
||
joinRow.hidden = kind.value !== 'ManyToMany';
|
||
deleteRow.hidden = kind.value !== 'ManyToOne' && kind.value !== 'OneToOne';
|
||
nullRow.hidden = kind.value !== 'ManyToOne' && kind.value !== 'OneToOne';
|
||
orphanRow.hidden = kind.value !== 'OneToMany' && kind.value !== 'OneToOne';
|
||
};
|
||
prop.addEventListener('input', () => { prop.dataset.typed = '1'; });
|
||
inverse.addEventListener('input', () => { inverse.dataset.typed = '1'; });
|
||
both.addEventListener('change', () => { inverse.disabled = !both.checked; });
|
||
const joinRow = row(t('Join table'), joinTable);
|
||
const deleteRow = row(t('When the target is deleted (ON DELETE)'), onDelete);
|
||
const nullRow = el('label.db-check', {}, nullable, t('Optional (the join column may be NULL)'));
|
||
const orphanRow = el('label.db-check', {}, orphan, t('Delete the children taken out of the collection (orphanRemoval)'));
|
||
target.addEventListener('change', fill);
|
||
kind.addEventListener('change', fill);
|
||
fill();
|
||
dialog({
|
||
title: t('Add a relation to {name}', { name: e.name }), wide: true,
|
||
body: el('div.db-form', {}, row(t('Target entity'), target), row(t('Kind'), kind), row(t('Property in {name}', { name: e.name }), prop),
|
||
el('label.db-check', {}, both, t('Both sides (the property on the other entity, kept in step)')), row(t('Property on the other side'), inverse),
|
||
nullRow, deleteRow, joinRow, el('div.db-section', {}, 'cascade'), el('div.db-two', {}, el('label.db-check', {}, persist, 'persist'), el('label.db-check', {}, remove, 'remove')), orphanRow,
|
||
el('p.db-hint', {}, t('Attributes, collections initialised in the constructor and add / remove methods are written on both sides; you see the change before it is saved.'))),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Show the change'), primary: true, action: async () => {
|
||
const relation = { kind: kind.value, property: prop.value.trim(), target: target.value, inverse: both.checked ? inverse.value.trim() : '', nullable: nullable.checked,
|
||
cascade: [persist.checked ? 'persist' : '', remove.checked ? 'remove' : ''].filter(Boolean), orphanRemoval: orphan.checked, onDelete: onDelete.value || null, joinTable: joinTable.value.trim() };
|
||
const r = await backend.invoke('doctrine.relation.add', { class: e.class, relation });
|
||
this.preview(r.changes, { title: t('Add a relation to {name}', { name: e.name }) });
|
||
} }],
|
||
});
|
||
}
|
||
|
||
/** the rows of fields (doctrine-fields.js): name, type, the options of that type, relation sub-form, up / down / remove, errors and a live PHP preview */
|
||
fieldRows({ className = () => '' } = {}) {
|
||
const rows = [];
|
||
const enums = this.mapping.enums || [];
|
||
const entities = this.mapping.entities.filter((x) => x.kind === 'entity');
|
||
const targets = entities.map((x) => x.class);
|
||
const list = el('div.nf-rows');
|
||
const preview = el('pre.nf-php');
|
||
const note = el('p.db-hint', {}, t('The relations are written on both sides once the entity is created.'));
|
||
const problem = (e) => t(e.key, e.params);
|
||
const check = () => validate(rows, { className: className(), targets });
|
||
const refresh = () => {
|
||
const errors = check();
|
||
rows.forEach((r, i) => {
|
||
r.node.querySelectorAll('.bad').forEach((n) => n.classList.remove('bad'));
|
||
const mine = errors.filter((e) => e.index === i);
|
||
for (const e of mine) r.fields[e.field]?.classList.add('bad');
|
||
r.error.textContent = mine.map(problem).join(' · ');
|
||
r.error.hidden = !mine.length;
|
||
r.node.classList.toggle('invalid', mine.length > 0);
|
||
r.up.disabled = i === 0;
|
||
r.down.disabled = i === rows.length - 1;
|
||
});
|
||
preview.textContent = rows.filter((r) => r.name.trim() !== '').map(previewRow).join('\n\n') || '// ' + t('No field yet: only the id is written.');
|
||
note.hidden = !rows.some((r) => r.type === 'relation');
|
||
return errors;
|
||
};
|
||
const move1 = (r, d) => { move(rows, rows.indexOf(r), d); list.replaceChildren(...rows.map((x) => x.node)); refresh(); };
|
||
const build = (r) => {
|
||
const input = (key, spec = 'input.input', attrs = {}) => { const n = el(spec, { value: r[key] ?? '', ...attrs, oninput: (e) => { r[key] = e.target.value; refresh(); } }); r.fields[key] = n; return n; };
|
||
const flag = (key, label) => el('label.db-check', {}, el('input', { type: 'checkbox', checked: !!r[key], onchange: (e) => { r[key] = e.target.checked; refresh(); } }), label);
|
||
const sel = (key, options, onchange) => { const n = el('select.input', { onchange: (e) => { onchange(e.target.value); refresh(); } }, ...options); r.fields[key] = n; return n; };
|
||
r.fields = {};
|
||
const name = input('name', 'input.input', { placeholder: 'title', 'data-tour': 'field-name-' + (rows.indexOf(r) + 1) });
|
||
const type = el('select.input.nf-ty', { 'data-tour': 'field-type-' + (rows.indexOf(r) + 1), onchange: (e) => { setType(r, e.target.value); r.rebuild(); refresh(); } },
|
||
...FIELD_TYPES.map((x) => el('option', { value: x, selected: r.type === x }, x === 'enum' ? t('PHP enum…') : x)), el('option', { value: 'relation', selected: r.type === 'relation' }, t('Relation…')));
|
||
const opts = el('div.nf-opts');
|
||
const lab = (text, node) => el('label', {}, el('span', {}, text), node);
|
||
r.rebuild = () => {
|
||
clear(opts);
|
||
r.fields = { name, type };
|
||
if (has(r, 'length')) opts.append(lab(t('Length'), input('length', 'input.input.nf-num', { type: 'number', min: 1 })));
|
||
if (has(r, 'decimal')) opts.append(lab(t('Precision'), input('precision', 'input.input.nf-num', { type: 'number', min: 1 })), lab(t('Scale'), input('scale', 'input.input.nf-num', { type: 'number', min: 0 })));
|
||
if (has(r, 'enum')) {
|
||
opts.append(lab(t('Enum'), sel('enumType', [el('option', { value: '' }, '—'), ...enums.map((x) => el('option', { value: x.class, selected: r.enumType === x.class }, `${short(x.class)}${x.backing ? ' (' + x.backing + ')' : ''}`))], (v) => { r.enumType = v || null; })));
|
||
}
|
||
if (has(r, 'relation')) {
|
||
const inverse = el('input.input', { value: r.relation.inverse, placeholder: '—', oninput: (e) => { r.relation.inverse = e.target.value; refresh(); } });
|
||
r.fields.inverse = inverse;
|
||
opts.append(lab(t('Target entity'), sel('target', [el('option', { value: '' }, '—'), ...entities.map((x) => el('option', { value: x.class, selected: r.relation.target === x.class }, short(x.class)))], (v) => { r.relation.target = v; })),
|
||
lab(t('Kind'), sel('kind', RELATION_KINDS.map((k) => el('option', { value: k, selected: r.relation.kind === k }, k)), (v) => { r.relation.kind = v; })),
|
||
lab(t('Inverse side property'), inverse),
|
||
el('label.db-check', {}, el('input', { type: 'checkbox', checked: r.relation.orphanRemoval, onchange: (e) => { r.relation.orphanRemoval = e.target.checked; } }), t('Orphan removal')));
|
||
}
|
||
opts.append(flag('nullable', t('Nullable')));
|
||
if (has(r, 'unique')) opts.append(flag('unique', t('Unique')));
|
||
if (has(r, 'default')) opts.append(lab(t('Default value'), input('default', 'input.input', { placeholder: '—' })));
|
||
};
|
||
r.up = el('button.icon-btn', { type: 'button', title: t('Move up'), onclick: () => move1(r, -1) }, '↑');
|
||
r.down = el('button.icon-btn', { type: 'button', title: t('Move down'), onclick: () => move1(r, 1) }, '↓');
|
||
r.error = el('div.nf-err', { hidden: true });
|
||
r.node = el('div.nf-row', {}, el('div.nf-main', {}, el('span.nf-grip', {}, r.up, r.down), name, type,
|
||
el('button.icon-btn', { type: 'button', title: t('Remove'), onclick: () => { rows.splice(rows.indexOf(r), 1); r.node.remove(); refresh(); } }, '×')), opts, r.error);
|
||
r.rebuild();
|
||
return r.node;
|
||
};
|
||
const add = (over = {}) => { const r = newRow(over); rows.push(r); list.append(build(r)); refresh(); return r; };
|
||
const node = el('div.nf-fields', {}, list, el('button.btn.small', { 'data-tour': 'entity-add-field', type: 'button', onclick: () => add().node.querySelector('input').focus() }, '+ ' + t('Add a field')),
|
||
note, el('div.db-section', {}, t('Generated PHP')), preview);
|
||
refresh();
|
||
return { node, rows, check, refresh, add, result: () => toBackend(rows, { enums }) };
|
||
}
|
||
|
||
newEntity() {
|
||
const name = el('input.input', { 'data-tour': 'entity-class', placeholder: 'Product', oninput: () => fields.refresh() });
|
||
const table = el('input.input', { placeholder: t('(from the class name)') });
|
||
const repo = el('input', { type: 'checkbox', checked: true });
|
||
const api = el('input', { type: 'checkbox', onchange: () => notice.update() });
|
||
// API Platform is not in composer.json: the notice offers to install it (Composer, live output) without leaving the dialog
|
||
const notice = packageNotice(this.app, 'api');
|
||
notice.wanted = () => api.checked;
|
||
const fields = this.fieldRows({ className: () => name.value.trim() });
|
||
fields.add({ name: 'name' });
|
||
const row = (label, node) => el('label.db-field', {}, el('span', {}, label), node);
|
||
// the messages made by doctrine-fields.js, listed so that the translation check sees them
|
||
void [t('The name is empty'), t('"{name}" is not a PHP name'), t('"{name}" is a reserved word'), t('"id" is already the primary key'), t('"{name}" is used twice'), t('Pick the target entity'),
|
||
t('The length must be at least 1'), t('The precision must be at least 1'), t('The scale must be between 0 and the precision'), t('Pick a PHP enum')];
|
||
dialog({
|
||
title: t('New entity…'), wide: true,
|
||
body: el('div.db-form', {}, el('div.nf-top', {}, row(t('Class name'), name), row(t('Table name'), table)),
|
||
el('div.dc-checks', {}, el('label.db-check', {}, repo, t('With its repository')), el('label.db-check', {}, api, t('API Platform resource (#[ApiResource])'))), notice.node,
|
||
el('div.db-section', {}, t('Fields')), fields.node),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Show the change'), primary: true, tour: 'entity-show-change', action: async () => {
|
||
if (api.checked) warnMissing(notice, 'api');
|
||
const errors = fields.refresh();
|
||
if (errors.length) { notify(t('Fix the fields marked in red.'), 'warning', { title: 'Doctrine' }); return false; }
|
||
if (name.value.trim() === '') { name.classList.add('bad'); return false; }
|
||
const { fields: list, relations } = fields.result();
|
||
const cls = 'App\\Entity\\' + name.value.trim();
|
||
const r = await backend.invoke('doctrine.entity.new', { entity: { name: name.value.trim(), table: table.value.trim(), repository: repo.checked, api: api.checked, fields: list } });
|
||
this.preview(r.changes, { title: t('New entity…'), after: async (written) => {
|
||
this.selected = cls;
|
||
if (written[0]) this.open(written[0], 1);
|
||
// the relations need the class on disk: written now, on both sides, shown as a diff like any relation
|
||
for (const relation of relations) {
|
||
try {
|
||
const rr = await backend.invoke('doctrine.relation.add', { class: cls, relation });
|
||
this.preview(rr.changes, { title: t('Add a relation to {name}', { name: name.value.trim() }) });
|
||
} catch (err) { notify(err.message, 'error', { title: 'Doctrine' }); }
|
||
}
|
||
} });
|
||
} }],
|
||
});
|
||
}
|
||
|
||
async removeProperty(e, name) {
|
||
try {
|
||
const r = await backend.invoke('doctrine.property.remove', { class: e.class, name });
|
||
this.preview(r.changes, { title: t('Remove {name}', { name: `${e.name}::$${name}` }) });
|
||
} catch (err) { notify(err.message, 'error', { title: 'Doctrine' }); }
|
||
}
|
||
|
||
async rename(e, old) {
|
||
const name = await prompt(t('Rename {name} everywhere', { name: `${e.name}::$${old}` }), { value: old, label: t('New name') });
|
||
if (!name || name === old) return;
|
||
try {
|
||
const r = await backend.invoke('doctrine.rename.plan', { class: e.class, old, new: name });
|
||
this.preview(r.changes, { title: t('Rename {name} everywhere', { name: `${e.name}::$${old}` }), review: r.review });
|
||
} catch (err) { notify(err.message, 'error', { title: 'Doctrine' }); }
|
||
}
|
||
|
||
dtos(e) {
|
||
const boxes = [...e.fields.map((f) => [f.name, `${f.name}: ${f.enumType ? short(f.enumType) : f.type}`]),
|
||
...e.relations.filter((r) => ['ManyToOne', 'OneToOne'].includes(r.kind)).map((r) => [r.name, `${r.name}: ${short(r.target)} (id)`])]
|
||
.map(([n, label]) => ({ n, label, box: el('input', { type: 'checkbox', checked: true }) }));
|
||
const input = el('input', { type: 'checkbox', checked: true });
|
||
const output = el('input', { type: 'checkbox', checked: true });
|
||
const ns = el('input.input', { value: 'App\\Dto' });
|
||
dialog({
|
||
title: t('Generate DTOs…'), wide: true,
|
||
body: el('div.db-form', {}, el('div.db-section', {}, t('Fields')), el('div.dc-checks', {}, ...boxes.map((b) => el('label.db-check', {}, b.box, b.label))),
|
||
el('div.db-section', {}, t('Classes')), el('label.db-check', {}, input, t('{name}Input: what a client sends (validation constraints, applyTo())', { name: e.name })),
|
||
el('label.db-check', {}, output, t('{name}Output: what the application shows (readonly, from{name}())', { name: e.name })),
|
||
el('label.db-field', {}, el('span', {}, t('Namespace')), ns)),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Show the change'), primary: true, action: async () => {
|
||
const r = await backend.invoke('doctrine.dto', { class: e.class, fields: boxes.filter((b) => b.box.checked).map((b) => b.n),
|
||
kinds: [input.checked ? 'input' : '', output.checked ? 'output' : ''].filter(Boolean), namespace: ns.value.trim() });
|
||
this.preview(r.changes, { title: t('Generate DTOs…') });
|
||
} }],
|
||
});
|
||
}
|
||
|
||
/** The files a change writes, as diffs; Apply writes them all (each only if it did not change since). */
|
||
preview(changes, { title, review = [], after = null } = {}) {
|
||
if (!changes?.length) { notify(t('Nothing to change.'), 'info', { title: 'Doctrine' }); return; }
|
||
const monaco = window.monaco;
|
||
const host = el('div.dc-diff');
|
||
let diff = null;
|
||
let current = 0;
|
||
const list = el('div.dc-files');
|
||
const showFile = (i) => {
|
||
current = i;
|
||
list.querySelectorAll('.dc-file').forEach((n, j) => n.classList.toggle('on', j === i));
|
||
const c = changes[i];
|
||
const lang = c.path.endsWith('.twig') ? 'twig' : 'php';
|
||
if (monaco) {
|
||
if (!diff) diff = monaco.editor.createDiffEditor(host, { readOnly: true, renderSideBySide: false, automaticLayout: true, minimap: { enabled: false }, fontSize: 12.5, scrollBeyondLastLine: false });
|
||
diff.setModel({ original: monaco.editor.createModel(c.before, lang), modified: monaco.editor.createModel(c.after, lang) });
|
||
// the first change in view
|
||
const once = diff.onDidUpdateDiff(() => { once.dispose(); const first = diff.getLineChanges()?.[0]; if (first) diff.getModifiedEditor().revealLineInCenter(Math.max(1, first.modifiedStartLineNumber)); });
|
||
} else {
|
||
clear(host);
|
||
host.append(el('pre', {}, c.after));
|
||
}
|
||
};
|
||
for (const [i, c] of changes.entries()) {
|
||
list.append(el('div.dc-file', { onclick: () => showFile(i) }, el('span.dc-tag' + (c.new ? '.new' : ''), {}, c.new ? t('new') : t('changed')), el('span', {}, c.path)));
|
||
}
|
||
const body = el('div.dc-preview', {}, el('div.dc-side', {}, list, review.length ? el('div.dc-review', {}, el('div.db-section', {}, t('To check (not changed)')),
|
||
...review.map((r) => el('div.dc-rv', { title: r.text, onclick: () => this.open(r.path, r.line) }, `${r.path}:${r.line}`, el('div.dc-sub', {}, r.text)))) : null), host);
|
||
dialog({
|
||
title, wide: true, body,
|
||
onClose: () => { const m = diff?.getModel(); diff?.dispose(); m?.original?.dispose(); m?.modified?.dispose(); },
|
||
buttons: [{ label: t('Cancel') }, { label: t('Apply ({n} files)', { n: changes.length }), primary: true, tour: 'change-apply', action: async () => {
|
||
const r = await backend.invoke('doctrine.apply', { changes });
|
||
notify(t('{n} files written.', { n: r.written.length }), 'success', { title: 'Doctrine', actions: this.mapping?.migrations ? [{ label: t('Make a migration'), action: () => this.diff() }] : [] });
|
||
for (const p of r.written) this.app.editors?.changed?.(p);
|
||
await this.load();
|
||
after?.(r.written);
|
||
} }],
|
||
}).box.classList.add('dc-dialog');
|
||
showFile(current);
|
||
}
|
||
|
||
// the entity and its table ---------------------------------------------------------------------------------------
|
||
|
||
/** the Database window's connection of the project's database: the one chosen before, the one of DATABASE_URL, the only one, or asked */
|
||
async connection() {
|
||
const db = this.app.database;
|
||
if (!db) { notify(t('The Database window is not available here.'), 'warning', { title: 'Doctrine' }); return null; }
|
||
if (!db.list) await db.refresh();
|
||
const conns = db.list?.connections || [];
|
||
const key = 'doctrineConn:' + this.app.projectKey;
|
||
const chosen = prefs.get(key, null);
|
||
if (chosen && conns.some((c) => c.id === chosen)) return db.conn(chosen);
|
||
const url = this.mapping?.database;
|
||
const matching = conns.filter((c) => url && url.name && (c.database === url.name || (c.file || '').endsWith(url.name)));
|
||
if (matching.length === 1 || (!matching.length && conns.length === 1)) { prefs.set(key, (matching[0] || conns[0]).id); return matching[0] || conns[0]; }
|
||
if (!conns.length) {
|
||
const found = db.found.find((f) => f.supported);
|
||
if (found && await confirm(t('Database'), t('No database connection yet. Add {name} (found in the project)?', { name: found.name }), { ok: t('Add') })) {
|
||
await db.addFound(found);
|
||
return this.connection();
|
||
}
|
||
notify(t('No database connection yet: add one in the Database window.'), 'warning', { title: t('Database') });
|
||
return null;
|
||
}
|
||
return new Promise((resolve) => chooser((matching.length ? matching : conns).map((c) => ({ label: c.name, hint: c.database || c.file || '', icon: 'database',
|
||
action: () => { prefs.set(key, c.id); resolve(c); } })), { placeholder: t('The connection of this project\'s entities') }));
|
||
}
|
||
|
||
async databaseOf(c) {
|
||
const info = await this.app.database.connect(c.id);
|
||
if (!info) return null;
|
||
return c.database || info.database || this.mapping?.database?.name || '';
|
||
}
|
||
|
||
async tableData(e) {
|
||
const c = await this.connection();
|
||
if (!c) return;
|
||
const database = await this.databaseOf(c);
|
||
if (database === null) return;
|
||
const schema = await this.app.database.schema(c.id, database).catch((err) => { notify(err.message, 'error'); return null; });
|
||
const table = schema?.tables.find((x) => x.name.toLowerCase() === String(e.table).toLowerCase());
|
||
if (!table) { notify(t('No table {table} in {database}: make and run a migration first.', { table: e.table, database }), 'warning', { title: e.name }); return; }
|
||
this.app.database.results.openTable(c.id, database, table.name);
|
||
}
|
||
|
||
async compare(e) {
|
||
const c = await this.connection();
|
||
if (!c) return;
|
||
const database = await this.databaseOf(c);
|
||
if (database === null) return;
|
||
const schema = await this.app.database.schema(c.id, database, true).catch((err) => { notify(err.message, 'error'); return null; });
|
||
if (!schema) return;
|
||
const tableName = (e.inheritance?.type === 'SINGLE_TABLE' && e.inheritance.root ? this.entity(e.inheritance.root)?.table : e.table) || e.table;
|
||
const table = schema.tables.find((x) => x.name.toLowerCase() === String(tableName).toLowerCase()) || null;
|
||
let r;
|
||
try { r = await backend.invoke('doctrine.compare', { class: e.class, table }); } catch (err) { notify(err.message, 'error'); return; }
|
||
const describe = (x) => (x ? `${x.type}${x.length ? '(' + x.length + ')' : ''}${x.nullable ? ' NULL' : ' NOT NULL'}` : '—');
|
||
const STATUS = { ok: t('same'), missing: t('missing in the table'), extra: t('not in the mapping'), different: t('different') };
|
||
const rows = r.rows.map((x) => el('tr.cmp-' + x.status, {}, el('td.mono', {}, x.column), el('td', {}, x.expected ? describe(x.expected) + (x.expected.field ? ` · ${x.expected.field}` : '') : '—'),
|
||
el('td', {}, describe(x.actual)), el('td', {}, STATUS[x.status] + (x.detail.length ? ': ' + x.detail.join(', ') : ''))));
|
||
const s = r.summary;
|
||
dialog({
|
||
title: t('{entity} beside the table {table}', { entity: e.name, table: r.table }), wide: true,
|
||
body: el('div.db-form', {}, r.exists ? el('div.dc-cmpsum', {}, t('{ok} same · {missing} missing · {extra} extra · {different} different', s))
|
||
: el('div.db-error', {}, t('No table {table} in {database}: make and run a migration first.', { table: r.table, database })),
|
||
el('table.dc-table.dc-cmp', {}, el('tr', {}, el('th', {}, t('Column')), el('th', {}, t('Mapping')), el('th', {}, t('Database table')), el('th', {}, '')), ...rows)),
|
||
buttons: [{ label: t('Close') }, ...(s.missing + s.extra + s.different ? [{ label: t('Make a migration'), primary: true, action: () => { this.diff(); } }] : [])],
|
||
});
|
||
}
|
||
|
||
// DQL: the builder, completion in PHP strings --------------------------------------------------------------------
|
||
|
||
renderDql(body) {
|
||
const entities = this.mapping.entities.filter((e) => e.kind === 'entity');
|
||
if (!entities.length) { body.append(el('div.dc-hint', {}, t('No Doctrine entity in this project yet.'))); return; }
|
||
if (!this.query || !this.entity(this.query.root)) this.query = emptyQuery((this.entity(this.selected)?.kind === 'entity' ? this.selected : null) || entities[0].class);
|
||
const q = this.query;
|
||
const map = aliases(q, this.mapping.entities);
|
||
const fieldsOf = (alias) => { const e = this.entity(map.get(alias)); return e ? [...e.fields.map((f) => f.name), ...e.embedded.flatMap((em) => (this.entity(em.class)?.fields || []).map((f) => em.name + '.' + f.name))] : []; };
|
||
const paths = [...map.keys()].flatMap((a) => fieldsOf(a).map((f) => `${a}.${f}`));
|
||
const redo = () => this.render();
|
||
const root = el('select.input', { onchange: (ev) => { this.query = emptyQuery(ev.target.value); redo(); } }, ...entities.map((e) => el('option', { value: e.class, selected: e.class === q.root }, short(e.class))));
|
||
const alias = el('input.input.dc-alias', { value: q.alias, onchange: (ev) => { const old = q.alias; q.alias = ev.target.value.trim() || old; for (const x of [...q.joins, ...q.select, ...q.where, ...q.order]) { if (x.from === old) x.from = q.alias; if (x.alias === old) x.alias = q.alias; } redo(); } });
|
||
const sel = (value, options, onchange, cls = '') => el('select.input' + cls, { onchange: (ev) => { onchange(ev.target.value); redo(); } }, ...options.map((o) => el('option', { value: o, selected: o === value }, o)));
|
||
const del = (list, i) => el('button.icon-btn', { title: t('Remove'), onclick: () => { list.splice(i, 1); redo(); } }, icon('close'));
|
||
const left = el('div.dc-qb');
|
||
left.append(el('div.dc-qrow', {}, el('b', {}, 'FROM'), root, alias));
|
||
// joins
|
||
left.append(el('div.dc-qhead', {}, t('Joins along the relations')));
|
||
q.joins.forEach((j, i) => left.append(el('div.dc-qrow', {}, sel(j.type, ['INNER', 'LEFT'], (v) => { j.type = v; }), el('span.mono', {}, `${j.from}.${j.relation}`), el('span', {}, '→'),
|
||
el('span.mono', {}, `${j.alias} (${short(map.get(j.alias))})`), del(q.joins, i))));
|
||
const canJoin = joinable(q, this.mapping.entities);
|
||
if (canJoin.length) {
|
||
left.append(el('div.dc-qrow', {}, el('select.input', { onchange: (ev) => {
|
||
const [from, relation] = ev.target.value.split('.');
|
||
const target = canJoin.find((x) => x.from === from && x.relation === relation)?.target;
|
||
q.joins.push({ from, relation, alias: defaultAlias(target, [...map.keys()]), type: 'INNER' });
|
||
redo();
|
||
} }, el('option', { value: '' }, t('+ Join…')), ...canJoin.map((x) => el('option', { value: `${x.from}.${x.relation}` }, `${x.from}.${x.relation} (${KIND_SHORT[x.kind] || x.kind} ${short(x.target)})`)))));
|
||
}
|
||
// select
|
||
left.append(el('div.dc-qhead', {}, t('Select'), el('label.db-check', {}, el('input', { type: 'checkbox', checked: q.distinct, onchange: (ev) => { q.distinct = ev.target.checked; redo(); } }), 'DISTINCT')));
|
||
for (const a of map.keys()) {
|
||
const whole = q.select.some((s) => s.alias === a && !s.field);
|
||
const toggle = (field, on) => { const at = q.select.findIndex((s) => s.alias === a && (s.field || null) === field); if (on && at < 0) q.select.push({ alias: a, field }); if (!on && at >= 0) q.select.splice(at, 1); redo(); };
|
||
left.append(el('div.dc-qsel', {}, el('label.db-check', {}, el('input', { type: 'checkbox', checked: whole || (a === q.alias && !q.select.length), onchange: (ev) => toggle(null, ev.target.checked) }), el('b', {}, a), ` (${short(map.get(a))})`),
|
||
...fieldsOf(a).map((f) => el('label.db-check.small', {}, el('input', { type: 'checkbox', checked: q.select.some((s) => s.alias === a && s.field === f), onchange: (ev) => toggle(f, ev.target.checked) }), f))));
|
||
}
|
||
// where
|
||
left.append(el('div.dc-qhead', {}, t('Conditions (AND)'), el('button.btn.small', { onclick: () => { const [a, f] = (paths[0] || q.alias + '.id').split(/\.(.*)/); q.where.push({ alias: a, field: f, op: '=', value: '' }); redo(); } }, t('Add'))));
|
||
q.where.forEach((w, i) => left.append(el('div.dc-qrow', {}, sel(`${w.alias}.${w.field}`, paths, (v) => { [w.alias, w.field] = v.split(/\.(.*)/); }), sel(w.op, OPERATORS, (v) => { w.op = v; }),
|
||
['IS NULL', 'IS NOT NULL'].includes(w.op) ? null : el('input.input', { value: w.value ?? '', placeholder: t("value, or :parameter"), onchange: (ev) => { w.value = ev.target.value; redo(); } }), del(q.where, i))));
|
||
// order, limit
|
||
left.append(el('div.dc-qhead', {}, t('Order'), el('button.btn.small', { onclick: () => { const [a, f] = (paths[0] || q.alias + '.id').split(/\.(.*)/); q.order.push({ alias: a, field: f, dir: 'ASC' }); redo(); } }, t('Add'))));
|
||
q.order.forEach((o, i) => left.append(el('div.dc-qrow', {}, sel(`${o.alias}.${o.field}`, paths, (v) => { [o.alias, o.field] = v.split(/\.(.*)/); }), sel(o.dir, ['ASC', 'DESC'], (v) => { o.dir = v; }), del(q.order, i))));
|
||
left.append(el('div.dc-qrow', {}, el('b', {}, t('At most')), el('input.input.dc-alias', { type: 'number', min: 0, value: q.limit || '', placeholder: '∞', onchange: (ev) => { q.limit = Number(ev.target.value) || 0; redo(); } }), t('rows')));
|
||
// the code
|
||
const dql = buildDql(q);
|
||
const repoOf = this.entity(q.root)?.repositoryFile;
|
||
const qb = buildQueryBuilder(q, { inRepository: true });
|
||
const right = el('div.dc-qout', {},
|
||
el('div.dc-qhead', {}, 'DQL', el('button.btn.small', { onclick: () => { copyText(dql); notify(t('Copied.'), 'success'); } }, t('Copy')),
|
||
el('button.btn.small', { onclick: () => this.insert(`'${dql.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, ' ')}'`) }, t('Insert at the cursor'))),
|
||
el('pre.dc-code', {}, dql),
|
||
el('div.dc-qhead', {}, 'QueryBuilder', repoOf ? el('span.dc-sub', {}, t('(in {file})', { file: repoOf.split('/').pop() })) : null,
|
||
el('button.btn.small', { onclick: () => { copyText(qb); notify(t('Copied.'), 'success'); } }, t('Copy')), el('button.btn.small', { onclick: () => this.insert(qb.trimStart()) }, t('Insert at the cursor'))),
|
||
el('pre.dc-code', {}, qb),
|
||
el('div.dc-qhead', {}, t('Run'), el('button.btn.small.primary', { onclick: () => this.runDql(dql, parameters(q)) }, t('Run (SQL Results)')),
|
||
el('button.btn.small', { onclick: () => this.runDql(dql, parameters(q), 'sql') }, t('Show the SQL')), el('button.btn.small', { onclick: () => this.runDql(dql, parameters(q), 'dump') }, t('Objects (console)'))),
|
||
parameters(q).some((p) => p.value === null) ? el('div.dc-hint', {}, t('Parameters without a value (:name) cannot run: type a value in the condition.')) : null);
|
||
body.append(el('div.dc-split', {}, left, right));
|
||
}
|
||
|
||
insert(text) {
|
||
const ed = this.app.editors?.editor();
|
||
if (!ed?.getModel()) { copyText(text); notify(t('No editor open: copied instead.'), 'info'); return; }
|
||
ed.executeEdits('doctrine', [{ range: ed.getSelection(), text, forceMoveMarkers: true }]);
|
||
ed.focus();
|
||
}
|
||
|
||
/** a DQL run: its SQL from the console, then run on the Database window's connection (SQL Results); or the console's dump */
|
||
async runDql(dql, params, mode = 'run') {
|
||
if (params.some((p) => p.value === null)) { notify(t('Parameters without a value (:name) cannot run: type a value in the condition.'), 'warning', { title: 'DQL' }); return; }
|
||
const text = inlineParameters(dql, params).replace(/\s*\n\s*/g, ' ');
|
||
const busy = notify(t('Running through the console…'), 'info', { title: 'DQL', timeout: 0 });
|
||
let r;
|
||
try { r = await backend.invoke('doctrine.dql.run', { dql: text, mode: mode === 'dump' ? 'dump' : 'sql', max: 50 }); } catch (e) { busy.remove(); notify(e.message, 'error', { title: 'DQL' }); return; }
|
||
busy.remove();
|
||
if (mode === 'dump' || !r.ok) {
|
||
dialog({ title: mode === 'dump' ? t('Objects (console)') : t('The DQL did not compile'), wide: true, body: el('pre.dc-out', {}, r.output || '') });
|
||
return;
|
||
}
|
||
if (mode === 'sql') {
|
||
dialog({ title: t('The SQL of this DQL'), wide: true, body: el('pre.dc-code', {}, r.sql), buttons: [{ label: t('Close') }, { label: t('Copy'), action: () => copyText(r.sql) }] });
|
||
return;
|
||
}
|
||
const c = await this.connection();
|
||
if (!c) return;
|
||
const database = await this.databaseOf(c);
|
||
if (database === null) return;
|
||
await this.app.database.run(c.id, { script: r.sql, database, source: 'dql' });
|
||
}
|
||
|
||
whenMonaco() {
|
||
if (!window.monaco) { setTimeout(() => this.whenMonaco(), 700); return; }
|
||
const monaco = window.monaco;
|
||
const K = monaco.languages.CompletionItemKind;
|
||
const kinds = { entity: K.Class, alias: K.Variable, field: K.Field, relation: K.Reference, embedded: K.Struct, function: K.Function, keyword: K.Keyword };
|
||
monaco.languages.registerCompletionItemProvider('php', {
|
||
triggerCharacters: ['.', ' ', '\'', '"', '\\'],
|
||
provideCompletionItems: async (model, position) => {
|
||
const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
|
||
// cheap: only inside a string of a line that looks like DQL / a QueryBuilder call
|
||
if (((line.match(/'/g) || []).length % 2 === 0 && (line.match(/"/g) || []).length % 2 === 0) && !/^\s*(SELECT|FROM|WHERE|JOIN|LEFT|INNER|AND|OR|ORDER|GROUP)\b/i.test(line)) return { suggestions: [] };
|
||
let r;
|
||
try { r = await backend.invoke('doctrine.dql.complete', { text: model.getValue(), offset: model.getOffsetAt(position) }); } catch { return { suggestions: [] }; }
|
||
if (!r?.items?.length) return { suggestions: [] };
|
||
const start = position.column - (r.prefix || '').length;
|
||
const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: Math.max(1, start), endColumn: position.column };
|
||
return { suggestions: r.items.map((x, i) => ({ label: { label: x.label, description: x.detail }, kind: kinds[x.kind] ?? K.Text, insertText: x.insert, filterText: x.filter || x.label,
|
||
sortText: String(i).padStart(4, '0'), range, detail: 'DQL' })) };
|
||
},
|
||
});
|
||
}
|
||
|
||
// migrations -----------------------------------------------------------------------------------------------------
|
||
|
||
async loadMigrations() {
|
||
this.migrations = { loading: true, ...(this.migrations || {}) };
|
||
this.render();
|
||
try {
|
||
const r = await backend.invoke('doctrine.migrations', { action: 'list' });
|
||
this.migrations = r.ok ? r : { error: r.output, migrations: [], summary: null };
|
||
} catch (e) { this.migrations = { error: e.message, migrations: [], summary: null }; }
|
||
this.render();
|
||
}
|
||
|
||
renderMigrations(body) {
|
||
const m = this.migrations;
|
||
const summary = m?.summary;
|
||
const bar = el('div.dc-bar', {},
|
||
el('button.btn.small.primary', { 'data-tour': 'migrations-migrate', disabled: !summary?.pending, onclick: () => this.migrate('latest') }, icon('play'), t('Migrate to the latest')),
|
||
el('button.btn.small', { disabled: !summary?.executed, onclick: () => this.migrate('prev') }, icon('rollback'), t('Roll back one')),
|
||
el('button.btn.small', { 'data-tour': 'migrations-diff', onclick: () => this.diff() }, icon('plus'), t('Make a migration (diff)')),
|
||
el('button.btn.small', { onclick: () => this.validate() }, icon('check'), t('Validate the mapping')),
|
||
el('button.btn.small', { onclick: () => this.loadMigrations() }, icon('refresh'), t('Refresh')));
|
||
body.append(bar);
|
||
this.connectionBadge(bar);
|
||
if (!m || m.loading) { body.append(el('div.dc-hint', {}, t('Reading the migrations through the console…'))); if (!m?.migrations) return; }
|
||
if (m.error) body.append(el('pre.dc-out.err', {}, m.error));
|
||
if (summary) {
|
||
body.append(el('div.dc-msum', {}, el('span.ok', {}, t('{n} executed', { n: summary.executed })), el('span.pend', {}, t('{n} pending', { n: summary.pending })),
|
||
summary.unavailable ? el('span.bad', {}, t('{n} executed but no longer available', { n: summary.unavailable })) : null,
|
||
el('span', {}, t('Current: {v}', { v: summary.current ? short(summary.current) : t('none') }))));
|
||
}
|
||
const list = el('div.dc-timeline');
|
||
const rows = [...(m.migrations || [])].reverse();
|
||
if (!rows.length && !m.loading && !m.error) list.append(el('div.dc-hint', {}, t('No migration yet: make one from the entities with "Make a migration".')));
|
||
for (const x of rows) {
|
||
const current = summary?.current === x.version;
|
||
list.append(el('div.dc-mig.s-' + x.status + (current ? '.current' : ''), {},
|
||
el('span.dc-dot'), el('div.dc-mmain', {},
|
||
el('div', {}, el('b', {}, x.short), current ? el('span.dc-badge.b-cur', {}, t('current')) : null, el('span.dc-mstat', {},
|
||
x.status === 'executed' ? t('executed {date}', { date: x.migratedAt || '' }) + (x.time ? ` · ${x.time}` : '') : x.status === 'pending' ? t('pending') : t('executed, file missing'))),
|
||
x.description ? el('div.dc-sub', {}, x.description) : null),
|
||
el('span.dc-macts', {},
|
||
x.file ? el('button.icon-btn', { title: t('Open the file'), onclick: () => this.open(x.file, 1) }, icon('code')) : null,
|
||
x.status !== 'unavailable' && !current ? el('button.btn.small', { title: t('Migrate up or down to this version'), onclick: () => this.migrate(x.version) }, t('Go to this version')) : null,
|
||
x.status === 'pending' ? el('button.btn.small', { onclick: () => this.execute(x.version, 'up') }, t('Run up')) : null,
|
||
x.status === 'executed' ? el('button.btn.small', { onclick: () => this.execute(x.version, 'down') }, t('Run down')) : null)));
|
||
}
|
||
body.append(list);
|
||
if (this.log.length) {
|
||
body.append(el('div.dc-qhead', {}, t('Output'), el('button.btn.small', { onclick: () => { this.log = []; this.render(); } }, t('Clear'))),
|
||
...this.log.slice(-3).reverse().map((l) => el('details.dc-log' + (l.ok ? '' : '.err'), { open: !l.ok }, el('summary', {}, `${l.ok ? '✓' : '✗'} ${l.title}`), el('pre.dc-out', {}, l.output))));
|
||
}
|
||
}
|
||
|
||
async connectionBadge(bar) {
|
||
const db = this.app.database;
|
||
if (!db) return;
|
||
if (!db.list) await db.refresh().catch(() => null);
|
||
const id = prefs.get('doctrineConn:' + this.app.projectKey, null);
|
||
const c = id ? db.conn(id) : null;
|
||
const url = this.mapping?.database;
|
||
bar.append(...[el('span.dc-spacer'), c?.production ? el('span.db-prod-tag', {}, t('production')) : null,
|
||
el('span.dc-sub', { title: t('The connection of this project\'s entities') }, c ? c.name : url ? `${url.driver} · ${url.name}` : '')].filter(Boolean));
|
||
}
|
||
|
||
/** before anything that writes to the database: a production connection asks its name to be typed */
|
||
async guard(what) {
|
||
const db = this.app.database;
|
||
const id = prefs.get('doctrineConn:' + this.app.projectKey, null);
|
||
const c = db && id ? db.conn(id) : null;
|
||
if (!c?.production) return confirm(t('Migrations'), what, { ok: t('Run') });
|
||
return new Promise((resolve) => {
|
||
const input = el('input.input', { placeholder: c.name });
|
||
let done = false;
|
||
dialog({
|
||
title: t('Production: confirm the changes'),
|
||
body: el('div.db-form', {}, el('div.db-prodbar', {}, icon('warning'), t('{name} is a production database.', { name: c.name })), el('p', {}, what),
|
||
el('label.db-field', {}, el('span', {}, t('Type {name} to go on', { name: c.name })), input)),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Run on production'), danger: true, action: () => {
|
||
if (input.value.trim() !== c.name) { notify(t('The name does not match.'), 'warning'); return false; }
|
||
done = true; resolve(true);
|
||
} }],
|
||
onClose: () => { if (!done) resolve(false); },
|
||
});
|
||
});
|
||
}
|
||
|
||
async runMigrations(params, title) {
|
||
const busy = notify(t('Running through the console…'), 'info', { title, timeout: 0 });
|
||
let r;
|
||
try { r = await backend.invoke('doctrine.migrations', params); } catch (e) { r = { ok: false, output: e.message }; }
|
||
busy.remove();
|
||
this.log.push({ title, ok: r.ok, output: r.output || '' });
|
||
notify(r.ok ? t('Done.') : t('It failed: see the output in the Migrations tab.'), r.ok ? 'success' : 'error', { title });
|
||
if (r.ok) this.app.schemaCheck?.check(false); // the schema banner and the status bar follow what the migration did
|
||
return r;
|
||
}
|
||
|
||
async migrate(version) {
|
||
const label = version === 'latest' ? t('Migrate to the latest') : version === 'prev' ? t('Roll back one') : t('Go to {v}', { v: short(version) });
|
||
const pending = (this.migrations?.migrations || []).filter((x) => x.status === 'pending').length;
|
||
const text = version === 'latest' ? t('Run the {n} pending migrations?', { n: pending })
|
||
: version === 'prev' ? t('Undo the last migration ({v})? Its down() runs: the data it removes is lost.', { v: short(this.migrations?.summary?.current || '') })
|
||
: t('Migrate up or down to {v}? Going down runs the down() of the later ones: the data they remove is lost.', { v: short(version) });
|
||
if (!(await this.guard(text))) return;
|
||
await this.runMigrations({ action: 'migrate', version }, label);
|
||
this.loadMigrations();
|
||
}
|
||
|
||
async execute(version, direction) {
|
||
if (!(await this.guard(direction === 'up' ? t('Run up() of {v} only?', { v: short(version) }) : t('Run down() of {v} only? The data it removes is lost.', { v: short(version) })))) return;
|
||
await this.runMigrations({ action: 'execute', version, direction }, `${short(version)} ${direction}`);
|
||
this.loadMigrations();
|
||
}
|
||
|
||
async validate() {
|
||
const r = await this.runMigrations({ action: 'validate' }, t('Validate the mapping'));
|
||
dialog({ title: t('Validate the mapping'), wide: true, body: el('pre.dc-out' + (r.ok ? '' : '.err'), {}, r.output) });
|
||
}
|
||
|
||
/** a new migration: the SQL the entities need shown first (doctrine:schema:update --dump-sql), then the file written (make:migration / diff) */
|
||
async diff() {
|
||
this.show('migrations');
|
||
const busy = notify(t('Comparing the entities with the database…'), 'info', { title: t('Make a migration'), timeout: 0 });
|
||
let r;
|
||
try { r = await backend.invoke('doctrine.migrations', { action: 'sql' }); } catch (e) { r = { ok: false, output: e.message, statements: [] }; }
|
||
busy.remove();
|
||
if (!r.statements?.length) {
|
||
dialog({ title: t('Make a migration'), wide: true, body: el('div.db-form', {}, el('p', {}, r.ok ? t('The database already matches the entities: nothing to migrate.') : t('The comparison failed:')), el('pre.dc-out' + (r.ok ? '' : '.err'), {}, r.output || '')) });
|
||
return;
|
||
}
|
||
dialog({
|
||
title: t('Make a migration'), wide: true,
|
||
body: el('div.db-form', {}, el('p', {}, t('These {n} statements will be in the new migration:', { n: r.statements.length })), el('pre.dc-code', {}, r.statements.join(';\n') + ';')),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Write the migration'), primary: true, tour: 'migration-write', action: async () => {
|
||
const w = await this.runMigrations({ action: 'diff' }, t('Make a migration'));
|
||
if (w.file) this.open(w.file, 1);
|
||
this.loadMigrations();
|
||
} }],
|
||
});
|
||
}
|
||
|
||
// Search Everywhere / the Tools menu ------------------------------------------------------------------------------
|
||
|
||
registerActions(a) {
|
||
a.add('doctrineDiagram', 'Doctrine: Entities Diagram', () => this.show('diagram'), { icon: 'hierarchy' });
|
||
a.add('doctrineNewEntity', 'Doctrine: New Entity…', () => this.newEntity(), { icon: 'plus' });
|
||
a.add('doctrineDql', 'Doctrine: DQL Builder', () => this.show('dql'), { icon: 'console' });
|
||
a.add('doctrineMigrations', 'Doctrine: Migrations', () => { this.show('migrations'); this.loadMigrations(); }, { icon: 'history' });
|
||
a.add('doctrineMigrate', 'Doctrine: Migrate to the Latest Version', () => { this.show('migrations'); this.migrate('latest'); }, { icon: 'play' });
|
||
a.add('doctrineRollback', 'Doctrine: Roll Back the Last Migration', () => { this.show('migrations'); this.migrate('prev'); }, { icon: 'rollback' });
|
||
a.add('doctrineDiff', 'Doctrine: Make a Migration (diff)', () => this.diff(), { icon: 'plus' });
|
||
}
|
||
}
|
||
|
||
function plural(word) {
|
||
if (/[^aeiou]y$/i.test(word)) return word.slice(0, -1) + 'ies';
|
||
if (/(s|x|ch|sh|z)$/i.test(word)) return word + 'es';
|
||
return word + 's';
|
||
}
|