157 lines
7.5 KiB
JavaScript
157 lines
7.5 KiB
JavaScript
// The visual DQL builder's model, without the DOM (node --test ide/ui/js/dql-model.test.mjs): a query made of a root entity,
|
|
// joins along relations, selected aliases / fields, conditions, order and a limit, written as DQL or as QueryBuilder code.
|
|
//
|
|
// state = {root: 'App\Entity\Post', alias: 'p', distinct, joins: [{from: 'p', relation: 'author', alias: 'a', type: 'INNER'|'LEFT'}],
|
|
// select: [{alias, field: null|'title', fn: ''|'COUNT'...}], where: [{alias, field, op, value, param}], order: [{alias, field, dir}], limit: 0}
|
|
|
|
const short = (c) => String(c || '').split('\\').pop();
|
|
export const OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL', 'MEMBER OF'];
|
|
const NO_VALUE = new Set(['IS NULL', 'IS NOT NULL']);
|
|
|
|
export function emptyQuery(root, alias) {
|
|
return { root, alias: alias || defaultAlias(root), distinct: false, joins: [], select: [], where: [], order: [], limit: 0 };
|
|
}
|
|
|
|
/** the first letter of an entity, lower case, not taken yet */
|
|
export function defaultAlias(cls, taken = []) {
|
|
const base = short(cls).replace(/[^A-Za-z]/g, '').toLowerCase() || 'x';
|
|
for (const a of [base[0], base.slice(0, 2), base.slice(0, 3), base]) if (a && !taken.includes(a) && !RESERVED.has(a)) return a;
|
|
let n = 2;
|
|
while (taken.includes(base[0] + n)) n++;
|
|
return base[0] + n;
|
|
}
|
|
const RESERVED = new Set(['as', 'by', 'in', 'is', 'of', 'on', 'or', 'and', 'asc', 'end', 'new', 'not', 'set', 'all', 'any', 'max', 'min', 'sum', 'avg']);
|
|
|
|
/** alias => entity class of a query, the joins resolved through the mapping's relations */
|
|
export function aliases(state, entities) {
|
|
const byClass = new Map(entities.map((e) => [e.class, e]));
|
|
const out = new Map([[state.alias, state.root]]);
|
|
for (const j of state.joins) {
|
|
const from = byClass.get(out.get(j.from));
|
|
const r = from?.relations.find((x) => x.name === j.relation);
|
|
if (r?.target) out.set(j.alias, r.target);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** the relations one can join along from the aliases of a query: [{from, relation, target, kind}] */
|
|
export function joinable(state, entities) {
|
|
const byClass = new Map(entities.map((e) => [e.class, e]));
|
|
const out = [];
|
|
for (const [alias, cls] of aliases(state, entities)) {
|
|
for (const r of byClass.get(cls)?.relations || []) {
|
|
if (!state.joins.some((j) => j.from === alias && j.relation === r.name)) out.push({ from: alias, relation: r.name, target: r.target, kind: r.kind });
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** a condition's parameter name: given, else the field's (title, title2...) */
|
|
function paramNames(state) {
|
|
const used = new Set();
|
|
return state.where.map((w) => {
|
|
if (NO_VALUE.has(w.op)) return null;
|
|
const v = String(w.value ?? '').trim();
|
|
if (v.startsWith(':')) { used.add(v.slice(1)); return v.slice(1); }
|
|
let name = w.param || w.field || 'value';
|
|
let n = 2;
|
|
const base = name;
|
|
while (used.has(name)) name = base + n++;
|
|
used.add(name);
|
|
return name;
|
|
});
|
|
}
|
|
|
|
/** the parameters of a query: [{name, value}] (values typed in the conditions; a ":name" typed there has no value) */
|
|
export function parameters(state) {
|
|
const names = paramNames(state);
|
|
const out = [];
|
|
state.where.forEach((w, i) => {
|
|
if (names[i] === null || out.some((p) => p.name === names[i])) return;
|
|
const v = String(w.value ?? '').trim();
|
|
out.push({ name: names[i], value: v.startsWith(':') ? null : parseValue(v, w.op) });
|
|
});
|
|
return out;
|
|
}
|
|
|
|
function parseValue(v, op) {
|
|
if (op === 'IN' || op === 'NOT IN') return v.replace(/^\(|\)$/g, '').split(',').map((x) => parseValue(x.trim(), '='));
|
|
if (/^-?\d+$/.test(v)) return Number(v);
|
|
if (/^-?\d+\.\d+$/.test(v)) return Number(v);
|
|
if (/^(true|false)$/i.test(v)) return v.toLowerCase() === 'true';
|
|
return v.replace(/^'(.*)'$/s, '$1');
|
|
}
|
|
|
|
const path = (x) => (x.field ? `${x.alias}.${x.field}` : x.alias);
|
|
|
|
function selectList(state) {
|
|
const parts = state.select.length ? state.select.map((s) => (s.fn ? `${s.fn}(${path(s)})` : path(s)) + (s.as ? ` AS ${s.as}` : '')) : [state.alias];
|
|
return (state.distinct ? 'DISTINCT ' : '') + parts.join(', ');
|
|
}
|
|
|
|
function conditions(state) {
|
|
const names = paramNames(state);
|
|
return state.where.map((w, i) => {
|
|
const left = path(w);
|
|
if (NO_VALUE.has(w.op)) return `${left} ${w.op}`;
|
|
if (w.op === 'MEMBER OF') return `:${names[i]} MEMBER OF ${left}`;
|
|
if (w.op === 'IN' || w.op === 'NOT IN') return `${left} ${w.op} (:${names[i]})`;
|
|
return `${left} ${w.op} :${names[i]}`;
|
|
});
|
|
}
|
|
|
|
/** the query as DQL */
|
|
export function buildDql(state) {
|
|
const lines = [`SELECT ${selectList(state)}`, `FROM ${state.root} ${state.alias}`];
|
|
for (const j of state.joins) lines.push(`${j.type === 'LEFT' ? 'LEFT JOIN' : 'JOIN'} ${j.from}.${j.relation} ${j.alias}`);
|
|
const c = conditions(state);
|
|
if (c.length) lines.push('WHERE ' + c.join(' AND '));
|
|
if (state.order.length) lines.push('ORDER BY ' + state.order.map((o) => `${path(o)} ${o.dir === 'DESC' ? 'DESC' : 'ASC'}`).join(', '));
|
|
return lines.join('\n');
|
|
}
|
|
|
|
const phpString = (s) => `'${String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
|
|
function phpValue(v) {
|
|
if (Array.isArray(v)) return '[' + v.map(phpValue).join(', ') + ']';
|
|
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
|
if (v === null) return 'null';
|
|
return phpString(v);
|
|
}
|
|
|
|
/**
|
|
* The query as QueryBuilder code: in a repository of the root entity `$this->createQueryBuilder('p')`, elsewhere
|
|
* `$em->createQueryBuilder()->select(...)->from(Post::class, 'p')`. Parameters typed as values are set with setParameter().
|
|
*/
|
|
export function buildQueryBuilder(state, { inRepository = true, indent = ' ', variable = '$em' } = {}) {
|
|
const lines = [];
|
|
const i2 = indent + ' ';
|
|
if (inRepository) {
|
|
lines.push(`${indent}return $this->createQueryBuilder(${phpString(state.alias)})`);
|
|
if (state.select.length || state.distinct) lines.push(`${i2}->select(${phpString(selectList(state))})`);
|
|
} else {
|
|
lines.push(`${indent}return ${variable}->createQueryBuilder()`);
|
|
lines.push(`${i2}->select(${phpString(selectList(state))})`);
|
|
lines.push(`${i2}->from(${short(state.root)}::class, ${phpString(state.alias)})`);
|
|
}
|
|
for (const j of state.joins) lines.push(`${i2}->${j.type === 'LEFT' ? 'leftJoin' : 'innerJoin'}(${phpString(j.from + '.' + j.relation)}, ${phpString(j.alias)})`);
|
|
conditions(state).forEach((c, n) => lines.push(`${i2}->${n === 0 ? 'where' : 'andWhere'}(${phpString(c)})`));
|
|
for (const p of parameters(state)) lines.push(`${i2}->setParameter(${phpString(p.name)}, ${p.value === null ? '$' + p.name : phpValue(p.value)})`);
|
|
state.order.forEach((o, n) => lines.push(`${i2}->${n === 0 ? 'orderBy' : 'addOrderBy'}(${phpString(path(o))}, ${phpString(o.dir === 'DESC' ? 'DESC' : 'ASC')})`));
|
|
if (state.limit > 0) lines.push(`${i2}->setMaxResults(${Number(state.limit)})`);
|
|
lines.push(`${i2}->getQuery()`);
|
|
lines.push(`${i2}->getResult();`);
|
|
return lines.join('\n');
|
|
}
|
|
|
|
const dqlLiteral = (v) => (Array.isArray(v) ? v.map(dqlLiteral).join(', ') : typeof v === 'number' ? String(v) : typeof v === 'boolean' ? (v ? 'true' : 'false')
|
|
: `'${String(v ?? '').replace(/'/g, "''")}'`);
|
|
|
|
/** the DQL with its parameters written in as literals (to run it as it is, e.g. with doctrine:query:dql) */
|
|
export function inlineParameters(dql, params) {
|
|
let out = dql;
|
|
for (const p of [...params].sort((a, b) => b.name.length - a.name.length)) {
|
|
if (p.value === null || p.value === undefined) continue;
|
|
out = out.replace(new RegExp(':' + p.name + '\\b', 'g'), dqlLiteral(p.value));
|
|
}
|
|
return out;
|
|
}
|