/
join.js
96 lines (80 loc) 路 2.23 KB
/
join.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
const createPivotJoin = (ctx, { alias, refAlias, joinTable, targetMeta }) => {
const { qb } = ctx;
const joinAlias = qb.getAlias();
qb.join({
alias: joinAlias,
referencedTable: joinTable.name,
referencedColumn: joinTable.joinColumn.name,
rootColumn: joinTable.joinColumn.referencedColumn,
rootTable: alias,
on: joinTable.on,
});
const subAlias = refAlias || qb.getAlias();
qb.join({
alias: subAlias,
referencedTable: targetMeta.tableName,
referencedColumn: joinTable.inverseJoinColumn.referencedColumn,
rootColumn: joinTable.inverseJoinColumn.name,
rootTable: joinAlias,
});
return subAlias;
};
const createJoin = (ctx, { alias, refAlias, attributeName, attribute }) => {
const { db, qb } = ctx;
if (attribute.type !== 'relation') {
throw new Error(`Cannot join on non relational field ${attributeName}`);
}
const targetMeta = db.metadata.get(attribute.target);
const { joinColumn } = attribute;
if (joinColumn) {
const subAlias = refAlias || qb.getAlias();
qb.join({
alias: subAlias,
referencedTable: targetMeta.tableName,
referencedColumn: joinColumn.referencedColumn,
rootColumn: joinColumn.name,
rootTable: alias,
});
return subAlias;
}
const { joinTable } = attribute;
if (joinTable) {
return createPivotJoin(ctx, { alias, refAlias, joinTable, targetMeta });
}
return alias;
};
// TODO: toColumnName for orderBy & on
const applyJoin = (qb, join) => {
const {
method = 'leftJoin',
alias,
referencedTable,
referencedColumn,
rootColumn,
rootTable = qb.alias,
on,
orderBy,
} = join;
qb[method](`${referencedTable} as ${alias}`, (inner) => {
inner.on(`${rootTable}.${rootColumn}`, `${alias}.${referencedColumn}`);
if (on) {
for (const key of Object.keys(on)) {
inner.onVal(`${alias}.${key}`, on[key]);
}
}
});
if (orderBy) {
Object.keys(orderBy).forEach((column) => {
const direction = orderBy[column];
qb.orderBy(`${alias}.${column}`, direction);
});
}
};
const applyJoins = (qb, joins) => joins.forEach((join) => applyJoin(qb, join));
module.exports = {
createJoin,
createPivotJoin,
applyJoins,
applyJoin,
};