UNPKG

1.16 kBJavaScriptView Raw
1'use strict';
2
3var getPrimaryKeyColumn = function(table) {
4 for (var i = 0; i < table.columns.length; i++) {
5 var col = table.columns[i];
6 if (col.primaryKey) {
7 return col;
8 }
9 }
10};
11
12var findReference = function(left, right) {
13 // find reference
14 for (var i = 0; i < right.columns.length; i++) {
15 var col = right.columns[i];
16 if (col.references) {
17 var leftName = left.getName();
18 if (col.references === leftName || col.references.table === leftName) {
19 var leftCol = left[col.references.column] || getPrimaryKeyColumn(left);
20 return {
21 left: leftCol,
22 right: col
23 };
24 }
25 }
26 }
27};
28
29module.exports = {
30 // auto-join two tables based on column properties
31 // requires one column to have { references: {table: 'foreignTableName', column: 'foreignColumnName'}}
32 // or to have { references: 'foreignTableName'} -- in which case the foreign table's primary key is assumed
33 leftJoin: function(left, right) {
34 var ref = findReference(left, right);
35 if (!ref) {
36 ref = findReference(right, left);
37 }
38 return left.join(right).on(ref.left.equals(ref.right));
39 }
40};