knex/lib/query/joinclause.js

85 lines
2.1 KiB
JavaScript
Raw Normal View History

'use strict';
2015-04-29 15:13:15 -04:00
var assign = require('lodash/object/assign');
2013-09-13 16:58:38 -04:00
// JoinClause
// -------
// The "JoinClause" is an object holding any necessary info about a join,
// including the type, and any associated tables & columns being joined.
2014-04-27 19:36:40 -04:00
function JoinClause(table, type) {
this.table = table;
this.joinType = type;
this.and = this;
this.clauses = [];
2014-04-27 19:36:40 -04:00
}
2015-04-29 15:13:15 -04:00
assign(JoinClause.prototype, {
2015-04-29 15:13:15 -04:00
grouping: 'join',
2015-04-29 15:13:15 -04:00
// Adds an "on" clause to the current join object.
on: function(first, operator, second) {
var data, bool = this._bool()
switch (arguments.length) {
case 1: {
if (typeof first === 'object' && typeof first.toSQL !== 'function') {
var i = -1, keys = Object.keys(first)
var method = bool === 'or' ? 'orOn' : 'on'
while (++i < keys.length) {
this[method](keys[i], first[keys[i]])
}
return this;
} else {
data = [bool, 'on', first]
2015-04-29 15:13:15 -04:00
}
break;
2015-04-29 15:13:15 -04:00
}
case 2: data = [bool, 'on', first, '=', operator]; break;
default: data = [bool, 'on', first, operator, second];
}
this.clauses.push(data);
return this;
},
2015-04-29 15:13:15 -04:00
// Adds a "using" clause to the current join.
using: function(table) {
return this.clauses.push([this._bool(), 'using', table]);
},
2015-04-29 15:13:15 -04:00
// Adds an "and on" clause to the current join object.
andOn: function() {
return this.on.apply(this, arguments);
},
2015-04-29 15:13:15 -04:00
// Adds an "or on" clause to the current join object.
orOn: function(first, operator, second) {
/*jshint unused: false*/
return this._bool('or').on.apply(this, arguments);
},
2015-04-29 15:13:15 -04:00
// Explicitly set the type of join, useful within a function when creating a grouped join.
type: function(type) {
this.joinType = type;
return this;
2015-04-29 15:13:15 -04:00
},
_bool: function(bool) {
if (arguments.length === 1) {
this._boolFlag = bool;
return this;
}
var ret = this._boolFlag || 'and';
this._boolFlag = 'and';
return ret;
2013-12-27 14:44:21 -05:00
}
2015-04-29 15:13:15 -04:00
})
2014-07-01 08:53:35 -04:00
Object.defineProperty(JoinClause.prototype, 'or', {
get: function () {
return this._bool('or');
}
});
module.exports = JoinClause;