From 79a77ac9322782182c14bbad1b25172103021b92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mikael=20Lepist=C3=B6?= Date: Mon, 1 Feb 2016 11:51:02 +0200 Subject: [PATCH] Removes object keys with value undefined from being added to DB in update. Clean version of pq #962 fixes issue #961. --- index.html | 6 ++++-- src/query/compiler.js | 1 + test/unit/query/builder.js | 13 +++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 8ff966657f..09a14df6fe 100644 --- a/index.html +++ b/index.html @@ -1210,14 +1210,16 @@

Join Methods


Creates an update query, taking a hash of properties or a key/value pair to be updated based on the other query constraints. Resolves the promise / fulfills the - callback with the number of affected rows for the query. + callback with the number of affected rows for the query. If a key to be updated has value + undefined it is ignored.

 knex('books')
   .where('published_date', '<', 2000)
   .update({
-    status: 'archived'
+    status: 'archived',
+    thisKeyIsSkipped: undefined
   })
 
diff --git a/src/query/compiler.js b/src/query/compiler.js index 9676c01522..07ddfc92c5 100644 --- a/src/query/compiler.js +++ b/src/query/compiler.js @@ -396,6 +396,7 @@ assign(QueryCompiler.prototype, { // "Preps" the update. _prepUpdate: function(data) { + data = _.omit(data, _.isUndefined) var vals = [] var sorted = Object.keys(data).sort() var i = -1 diff --git a/test/unit/query/builder.js b/test/unit/query/builder.js index 661d6dcda3..3896a9ced6 100644 --- a/test/unit/query/builder.js +++ b/test/unit/query/builder.js @@ -2129,6 +2129,19 @@ describe("QueryBuilder", function() { }); }); + it("should not update columns undefined values", function() { + testsql(qb().update({'email': 'foo', 'name': undefined}).table('users').where('id', '=', 1), { + mysql: { + sql: 'update `users` set `email` = ? where `id` = ?', + bindings: ['foo', 1] + }, + default: { + sql: 'update "users" set "email" = ? where "id" = ?', + bindings: ['foo', 1] + } + }); + }); + it("should allow for 'null' updates", function() { testsql(qb().update({email: null, 'name': 'bar'}).table('users').where('id', 1), { mysql: {