rob-revisited/ide/ui/js/doctrine-models.test.mjs

143 lines
9.6 KiB
JavaScript

// The Doctrine window's and the SQL builder's models (no DOM): the diagram's graph and layout, the DQL builder, the SQL builder.
// Run: docker run --rm -v $PWD:/w -w /w node:22-alpine node --test ide/ui/js/doctrine-models.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { graph, layout, boxSize, overlaps, neighbours, matches, ends, anchors } from './doctrine-layout.js';
import { emptyQuery, buildDql, buildQueryBuilder, parameters, inlineParameters, joinable, aliases, defaultAlias } from './dql-model.js';
import { emptySql, buildSql, parseSql, suggestJoins, tableAlias } from './sql-model.js';
const f = (name, type = 'string', extra = {}) => ({ name, type, nullable: false, id: name === 'id', ...extra });
const rel = (name, kind, target, extra = {}) => ({ name, kind, target, owning: kind === 'ManyToOne' || (kind !== 'OneToMany' && !extra.mappedBy), mappedBy: null, inversedBy: null, cascade: [], ...extra });
const ent = (cls, fields, relations = [], extra = {}) => ({ class: cls, name: cls.split('\\').pop(), kind: 'entity', table: cls.split('\\').pop().toLowerCase(), fields, relations, embedded: [], ...extra });
const mapping = {
entities: [
ent('App\\Entity\\User', [f('id', 'integer'), f('email')], [rel('posts', 'OneToMany', 'App\\Entity\\Post', { mappedBy: 'author' })], { embedded: [{ name: 'address', class: 'App\\Entity\\Address' }] }),
ent('App\\Entity\\Post', [f('id', 'integer'), f('title'), f('status', 'string', { enumType: 'App\\Enum\\Status' })],
[rel('author', 'ManyToOne', 'App\\Entity\\User', { inversedBy: 'posts' }), rel('tags', 'ManyToMany', 'App\\Entity\\Tag', { inversedBy: 'posts' })]),
ent('App\\Entity\\Tag', [f('id', 'integer'), f('label')], [rel('posts', 'ManyToMany', 'App\\Entity\\Post', { mappedBy: 'tags' })]),
ent('App\\Entity\\Address', [f('city')], [], { kind: 'embeddable' }),
ent('App\\Entity\\Video', [f('seconds', 'integer')], [], { parent: 'App\\Entity\\Post', inheritance: { type: 'SINGLE_TABLE', root: 'App\\Entity\\Post' } }),
ent('App\\Entity\\Lonely', [f('id', 'integer')]),
],
enums: [{ class: 'App\\Enum\\Status', name: 'Status', cases: [{ name: 'Draft' }, { name: 'Published' }] }, { class: 'App\\Enum\\Unused', cases: [] }],
};
test('the graph draws each bidirectional relation once, from its owning side, with inheritance, embedded and enums', () => {
const g = graph(mapping);
assert.deepEqual(g.nodes.map((n) => n.id.split('\\').pop()), ['User', 'Post', 'Tag', 'Address', 'Video', 'Lonely', 'Status']);
const rels = g.edges.filter((e) => e.kind === 'relation').map((e) => `${e.from.split('\\').pop()}.${e.fromField} ${e.relation} ${e.to.split('\\').pop()}.${e.toField}`);
assert.deepEqual(rels.sort(), ['Post.author ManyToOne User.posts', 'Post.tags ManyToMany Tag.posts']);
assert.ok(g.edges.some((e) => e.kind === 'inheritance' && e.from.endsWith('Video') && e.label === 'SINGLE_TABLE'));
assert.ok(g.edges.some((e) => e.kind === 'embedded' && e.to.endsWith('Address')));
assert.ok(g.edges.some((e) => e.kind === 'enum' && e.to.endsWith('Status')));
assert.deepEqual(ends('ManyToOne'), ['*', '1']);
});
test('the layout places linked boxes in neighbouring columns, never on top of each other, the same way every time', () => {
const g = graph(mapping);
const boxes = g.nodes.map((n) => ({ id: n.id, ...boxSize(n) }));
const pos = layout(boxes, g.edges);
const placed = boxes.map((b) => ({ ...b, ...pos[b.id] }));
for (let i = 0; i < placed.length; i++) for (let j = i + 1; j < placed.length; j++) assert.ok(!overlaps(placed[i], placed[j]), `${placed[i].id} / ${placed[j].id}`);
assert.deepEqual(layout(boxes, g.edges), pos);
// Post (most linked) first, its neighbours one column further
assert.ok(pos['App\\Entity\\Post'].x < pos['App\\Entity\\User'].x);
assert.equal(pos['App\\Entity\\User'].x, pos['App\\Entity\\Tag'].x);
const [a, b] = anchors({ x: 0, y: 0, w: 100, h: 50 }, { x: 300, y: 0, w: 100, h: 50 });
assert.deepEqual([a.side, b.side, a.x, b.x], ['r', 'l', 100, 300]);
});
test('focus follows the relations step by step, and the filter finds classes, fields and kinds', () => {
const g = graph(mapping);
assert.deepEqual([...neighbours(g.edges, 'App\\Entity\\User', 1)].sort(), ['App\\Entity\\Address', 'App\\Entity\\Post', 'App\\Entity\\User']);
assert.ok(neighbours(g.edges, 'App\\Entity\\User', 2).has('App\\Entity\\Tag'));
const byId = Object.fromEntries(g.nodes.map((n) => [n.id, n]));
assert.ok(matches(byId['App\\Entity\\Post'], 'title'));
assert.ok(!matches(byId['App\\Entity\\Tag'], 'title'));
assert.ok(matches(byId['App\\Entity\\Address'], 'is:embeddable'));
assert.ok(matches(byId['App\\Enum\\Status'], 'draft'));
});
test('the DQL builder writes DQL and QueryBuilder code with parameters', () => {
const q = emptyQuery('App\\Entity\\Post');
assert.equal(q.alias, 'p');
q.joins.push({ from: 'p', relation: 'author', alias: 'a', type: 'LEFT' });
q.select.push({ alias: 'p', field: null }, { alias: 'a', field: 'email' });
q.where.push({ alias: 'p', field: 'title', op: 'LIKE', value: "'%php%'" }, { alias: 'a', field: 'email', op: 'IS NOT NULL' }, { alias: 'p', field: 'id', op: 'IN', value: '1, 2' });
q.order.push({ alias: 'p', field: 'title', dir: 'DESC' });
q.limit = 10;
const dql = buildDql(q);
assert.equal(dql, 'SELECT p, a.email\nFROM App\\Entity\\Post p\nLEFT JOIN p.author a\nWHERE p.title LIKE :title AND a.email IS NOT NULL AND p.id IN (:id)\nORDER BY p.title DESC');
assert.deepEqual(parameters(q), [{ name: 'title', value: '%php%' }, { name: 'id', value: [1, 2] }]);
assert.equal(inlineParameters(dql, parameters(q)), "SELECT p, a.email\nFROM App\\Entity\\Post p\nLEFT JOIN p.author a\nWHERE p.title LIKE '%php%' AND a.email IS NOT NULL AND p.id IN (1, 2)\nORDER BY p.title DESC");
assert.equal(buildQueryBuilder(q, { indent: '' }), [
"return $this->createQueryBuilder('p')",
" ->select('p, a.email')",
" ->leftJoin('p.author', 'a')",
" ->where('p.title LIKE :title')",
" ->andWhere('a.email IS NOT NULL')",
" ->andWhere('p.id IN (:id)')",
" ->setParameter('title', '%php%')",
" ->setParameter('id', [1, 2])",
" ->orderBy('p.title', 'DESC')",
' ->setMaxResults(10)',
' ->getQuery()',
' ->getResult();'].join('\n'));
assert.match(buildQueryBuilder(q, { inRepository: false, indent: '' }), /->from\(Post::class, 'p'\)/);
// a ":name" typed is a parameter without a value: the code takes a variable
const r = emptyQuery('App\\Entity\\User');
r.where.push({ alias: 'u', field: 'email', op: '=', value: ':email' });
assert.match(buildQueryBuilder(r), /->setParameter\('email', \$email\)/);
});
test('the DQL builder offers the relations to join along and resolves the aliases', () => {
const q = emptyQuery('App\\Entity\\Post');
assert.deepEqual(joinable(q, mapping.entities).map((j) => `${j.from}.${j.relation}`), ['p.author', 'p.tags']);
q.joins.push({ from: 'p', relation: 'author', alias: 'a', type: 'INNER' });
assert.equal(aliases(q, mapping.entities).get('a'), 'App\\Entity\\User');
assert.deepEqual(joinable(q, mapping.entities).map((j) => `${j.from}.${j.relation}`), ['p.tags', 'a.posts']);
assert.equal(defaultAlias('App\\Entity\\Order', ['o']), 'ord');
});
const schema = [
{ name: 'post', columns: [{ name: 'id' }, { name: 'author_id' }, { name: 'title' }], foreignKeys: [{ columns: ['author_id'], table: 'user', references: ['id'] }] },
{ name: 'user', columns: [{ name: 'id' }, { name: 'email' }], foreignKeys: [] },
];
test('the SQL builder writes SQL and joins tables along their foreign keys', () => {
const s = emptySql();
s.tables.push({ name: 'post', alias: 'p' });
s.tables.push({ name: 'user', alias: tableAlias('user', ['p']) });
assert.equal(s.tables[1].alias, 'u');
const joins = suggestJoins(s, 'u', schema);
assert.deepEqual(joins, [{ type: 'INNER', table: 'u', on: [{ left: 'p.author_id', right: 'u.id' }] }]);
s.joins.push(...joins);
s.columns.push({ expr: 'u.email', agg: '', as: '' }, { expr: 'p.id', agg: 'COUNT', as: 'posts' });
s.where.push({ expr: 'p.title', op: 'LIKE', value: "'%a%'" });
s.groupBy.push('u.email');
s.having.push({ expr: 'p.id', agg: 'COUNT', op: '>', value: '2' });
s.order.push({ expr: 'posts', dir: 'DESC' });
s.limit = 20;
const sql = buildSql(s);
assert.equal(sql, "SELECT u.email, COUNT(p.id) AS posts\nFROM post p\nJOIN `user` u ON p.author_id = u.id\nWHERE p.title LIKE '%a%'\nGROUP BY u.email\nHAVING COUNT(p.id) > 2\nORDER BY posts DESC\nLIMIT 20");
assert.match(buildSql(s, 'sqlite'), /JOIN "user" u ON/);
});
test('SQL is read back into rows when it is a plain SELECT, else kept as written', () => {
const s = emptySql();
s.tables.push({ name: 'post', alias: 'p' }, { name: 'user', alias: 'u' });
s.joins.push({ type: 'LEFT', table: 'u', on: [{ left: 'p.author_id', right: 'u.id' }] });
s.columns.push({ expr: 'u.email', agg: '', as: '' }, { expr: 'p.id', agg: 'COUNT DISTINCT', as: 'n' });
s.where.push({ expr: 'p.id', op: 'IN', value: '(1, 2, 3)' }, { expr: 'u.email', op: 'IS NOT NULL', value: '' }, { expr: 'p.title', op: 'BETWEEN', value: "'a' AND 'm'" });
s.groupBy.push('u.email');
s.order.push({ expr: 'u.email', dir: 'ASC' });
s.limit = 5;
const sql = buildSql(s);
const back = parseSql(sql);
assert.deepEqual(back, s);
assert.equal(buildSql(back), sql);
assert.equal(parseSql('SELECT * FROM post WHERE a = 1 OR b = 2'), null);
assert.equal(parseSql('SELECT * FROM (SELECT 1) x'), null);
assert.equal(parseSql('SELECT id FROM post WHERE id IN (SELECT post_id FROM tag)'), null);
assert.deepEqual(parseSql('select * from `user` as u where u.id = :id;'), { ...emptySql(), tables: [{ name: 'user', alias: 'u' }], where: [{ expr: 'u.id', op: '=', value: ':id' }] });
});