Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow joins to nest conditional statements #1397

Merged
merged 5 commits into from May 14, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 16 additions & 3 deletions index.html
Expand Up @@ -931,6 +931,19 @@ <h3>Join Methods</h3>
knex.select('*').from('users').join('accounts', function() {
this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id')
})
</pre>

<p>
For nested join statements, specify a function as first argument of <tt>on</tt>, <tt>orOn</tt> or <tt>andOn</tt>
</p>

<pre class="display">
knex.select('*').from('users').join('accounts', function() {
this.on(function() {
this.on('accounts.id', '=', 'users.account_id')
this.orOn('accounts.owner_id', '=', 'users.id')
})
})
</pre>

<p>
Expand All @@ -945,9 +958,9 @@ <h3>Join Methods</h3>
<p>
If you need to use a literal value (string, number, or boolean) in a join instead of a column, use <tt>knex.raw</tt>.</p>

<pre class="display">
knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin']))
</pre>
<pre class="display">
knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin']))
</pre>

<p id="Builder-innerJoin">
<b class="header">innerJoin</b><code>.innerJoin(column, ~mixed~)</code>
Expand Down
57 changes: 51 additions & 6 deletions src/query/compiler.js
@@ -1,8 +1,10 @@

// Query Compiler
// -------
var helpers = require('../helpers');
var Raw = require('../raw');
var helpers = require('../helpers');
var Raw = require('../raw');
var JoinClause = require('./joinclause');

import {assign, reduce, groupBy, isString, compact, isEmpty, isUndefined, bind, map, omitBy} from 'lodash'

// The "QueryCompiler" takes all of the query statements which
Expand Down Expand Up @@ -167,10 +169,15 @@ assign(QueryCompiler.prototype, {
var ii = -1
while (++ii < join.clauses.length) {
var clause = join.clauses[ii]
sql += ' ' + (ii > 0 ? clause[0] : clause[1]) + ' '
sql += this.formatter.wrap(clause[2])
if (!isUndefined(clause[3])) sql += ' ' + this.formatter.operator(clause[3])
if (!isUndefined(clause[4])) sql += ' ' + this.formatter.wrap(clause[4])
if (ii > 0) {
sql += ' ' + clause.bool + ' ';
} else {
sql += ' ' + (clause.type === 'onUsing' ? 'using' : 'on') + ' ';
}
var val = this[clause.type].call(this, clause);
if (val) {
sql += val;
}
}
}
}
Expand Down Expand Up @@ -301,6 +308,44 @@ assign(QueryCompiler.prototype, {
return this.update();
},

// On Clause
// ------

onWrapped(clause) {
var self = this;

var wrapJoin = new JoinClause();
clause.value.call(wrapJoin, wrapJoin);

var sql = '';
wrapJoin.clauses.forEach(function(wrapClause, ii) {
if (ii > 0) {
sql += ' ' + wrapClause.bool + ' ';
}
var val = self[wrapClause.type](wrapClause);
if (val) {
sql += val;
}
});

if (sql.length) {
return '(' + sql + ')';
}
return '';
},

onBasic(clause) {
return this.formatter.wrap(clause.column) + ' ' + this.formatter.operator(clause.operator) + ' ' + this.formatter.wrap(clause.value);
},

onRaw(clause) {
return this.formatter.unwrapRaw(clause.value);
},

onUsing(clause) {
return this.formatter.wrap(clause.column);
},

// Where Clause
// ------

Expand Down
19 changes: 14 additions & 5 deletions src/query/joinclause.js
Expand Up @@ -20,6 +20,15 @@ assign(JoinClause.prototype, {

// Adds an "on" clause to the current join object.
on: function(first, operator, second) {
if (typeof first === 'function') {
this.clauses.push({
type: 'onWrapped',
value: first,
bool: this._bool()
});
return this;
}

var data, bool = this._bool()
switch (arguments.length) {
case 1: {
Expand All @@ -31,20 +40,20 @@ assign(JoinClause.prototype, {
}
return this;
} else {
data = [bool, 'on', first]
data = {type: 'onRaw', value: first, bool: bool};
}
break;
}
case 2: data = [bool, 'on', first, '=', operator]; break;
default: data = [bool, 'on', first, operator, second];
case 2: data = {type: 'onBasic', column: first, operator: '=', value: operator, bool: bool}; break;
default: data = {type: 'onBasic', column: first, operator: operator, value: second, bool: bool};
}
this.clauses.push(data);
return this;
},

// Adds a "using" clause to the current join.
using: function(column) {
return this.clauses.push([this._bool(), 'using', column]);
return this.clauses.push({type: 'onUsing', column: column, bool: this._bool()});
},

// Adds an "and on" clause to the current join object.
Expand Down Expand Up @@ -82,4 +91,4 @@ Object.defineProperty(JoinClause.prototype, 'or', {
}
});

module.exports = JoinClause;
module.exports = JoinClause;
23 changes: 23 additions & 0 deletions test/unit/query/builder.js
Expand Up @@ -1582,6 +1582,28 @@ describe("QueryBuilder", function() {
});
});

it("complex join with nest conditional statements", function() {
testsql(qb().select('*').from('users').join('contacts', function(qb) {
qb.on(function(qb) {
qb.on('users.id', '=', 'contacts.id')
qb.orOn('users.name', '=', 'contacts.name');
});
}), {
mysql: {
sql: 'select * from `users` inner join `contacts` on (`users`.`id` = `contacts`.`id` or `users`.`name` = `contacts`.`name`)',
bindings: []
},
mssql: {
sql: 'select * from [users] inner join [contacts] on ([users].[id] = [contacts].[id] or [users].[name] = [contacts].[name])',
bindings: []
},
default: {
sql: 'select * from "users" inner join "contacts" on ("users"."id" = "contacts"."id" or "users"."name" = "contacts"."name")',
bindings: []
}
});
});

it("joins with raw", function() {
testsql(qb().select('*').from('users').join('contacts', 'users.id', raw(1)).leftJoin('photos', 'photos.title', '=', raw('?', ['My Photo'])), {
mysql: {
Expand Down Expand Up @@ -1615,6 +1637,7 @@ describe("QueryBuilder", function() {
}
});
});

it("raw expressions in select", function() {
testsql(qb().select(raw('substr(foo, 6)')).from('users'), {
mysql: {
Expand Down