diff --git a/Makefile b/Makefile index 9e05038..70039db 100755 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ TESTS = test/mysql/*.js test/mssql/*.js test/*.js -#TESTS = test/mssql/05-tests-multiple-pools.js +#TESTS = test/mysql/03-tests-update_batch.js #TESTS = test/05-multiple-drivers.js test: mocha --timeout 5000 --reporter spec $(TESTS) diff --git a/drivers/query_builder.js b/drivers/query_builder.js index 0323ce6..346ccd4 100755 --- a/drivers/query_builder.js +++ b/drivers/query_builder.js @@ -1529,8 +1529,18 @@ class GenericQueryBuilder { cases += `ELSE ${l} END, `; } + // Remove the trailing comma sql += cases.substr(0, cases.length - 2); - sql += ` WHERE ${where + index} IN (${ids.join(',')})`; + + // Make sure we don't double-up on the "WHERE" directive + if (where) { + sql += ` ${where}`; + } else { + sql += ' WHERE '; + } + + + sql += `${index} IN (${ids.join(',')})`; // Add query to batch batches.push(sql); diff --git a/test/mysql/03-tests-update_batch.js b/test/mysql/03-tests-update_batch.js index be4ddea..673a6ea 100755 --- a/test/mysql/03-tests-update_batch.js +++ b/test/mysql/03-tests-update_batch.js @@ -3,7 +3,7 @@ const expect = require('chai').expect; const QueryBuilder = require('../../drivers/mysql/query_builder.js'); const qb = new QueryBuilder(); -const test_where = {id:3}; +const test_where = {quadrant: 'Alpha'}; const test_data = [{id:3, name:'Milky Way', type: 'spiral'}, {id:4, name: 'Andromeda', type: 'spiral'}]; describe('MySQL: update_batch()', () => { @@ -18,4 +18,9 @@ describe('MySQL: update_batch()', () => { const sql = qb.update_batch('galaxies', test_data, 'id'); sql.should.eql(["UPDATE (`galaxies`) SET `name` = CASE WHEN `id` = 3 THEN 'Milky Way' WHEN `id` = 4 THEN 'Andromeda' ELSE `name` END, `type` = CASE WHEN `id` = 3 THEN 'spiral' WHEN `id` = 4 THEN 'spiral' ELSE `type` END WHERE `id` IN (3,4)"]); }); + it('should build a proper batch UPDATE string when where clause is provided', () => { + qb.reset_query(); + const sql = qb.update_batch('galaxies', test_data, 'id', test_where); + sql.should.eql(["UPDATE (`galaxies`) SET `name` = CASE WHEN `id` = 3 THEN 'Milky Way' WHEN `id` = 4 THEN 'Andromeda' ELSE `name` END, `type` = CASE WHEN `id` = 3 THEN 'spiral' WHEN `id` = 4 THEN 'spiral' ELSE `type` END WHERE `quadrant` = 'Alpha' AND `id` IN (3,4)"]); + }); });