diff --git a/lib/sql.js b/lib/sql.js index e4479c19..65a0b098 100644 --- a/lib/sql.js +++ b/lib/sql.js @@ -1131,11 +1131,13 @@ SQLConnector.prototype._buildWhere = function(model, where) { branches.push(stmtForClause.sql); } } - stmt.merge({ - sql: '(' + branches.join(' ' + key.toUpperCase() + ' ') + ')', - params: branchParams, - }); - whereStmts.push(stmt); + if (branches.length > 0) { + stmt.merge({ + sql: '(' + branches.join(' ' + key.toUpperCase() + ' ') + ')', + params: branchParams, + }); + whereStmts.push(stmt); + } continue; } // The value is not an array, fall back to regular fields diff --git a/test/sql.test.js b/test/sql.test.js index 2fd635ea..213b47b7 100644 --- a/test/sql.test.js +++ b/test/sql.test.js @@ -259,6 +259,47 @@ describe('sql connector', function() { expect(where.sql).to.not.match(/ AND $/); }); + it('builds where and drops an or with only invalid clauses', function() { + const where = connector.buildWhere('customer', { + name: 'icecream', + or: [{notAColumnName: ''}, {notAColumnNameEither: ''}], + }); + expect(where.toJSON()).to.eql({ + sql: 'WHERE `NAME`=?', + params: ['icecream'], + }); + }); + + it('builds empty where for an or with only invalid clauses', function() { + const where = connector.buildWhere('customer', { + or: [{notAColumnName: ''}, {notAColumnNameEither: ''}], + }); + expect(where.toJSON()).to.eql({ + sql: '', + params: [], + }); + }); + + it('builds empty where for an and with only invalid clauses', function() { + const where = connector.buildWhere('customer', { + and: [{notAColumnName: ''}, {notAColumnNameEither: ''}], + }); + expect(where.toJSON()).to.eql({ + sql: '', + params: [], + }); + }); + + it('builds where and drops a nested or with only invalid clauses', function() { + const where = connector.buildWhere('customer', { + and: [{name: 'John'}, {or: [{notAColumnName: ''}]}], + }); + expect(where.toJSON()).to.eql({ + sql: 'WHERE ((`NAME`=?))', + params: ['John'], + }); + }); + it('builds order by with one field', function() { const orderBy = connector.buildOrderBy('customer', 'name'); expect(orderBy).to.eql('ORDER BY `NAME`');