Removes object keys with value undefined from being added to DB in update. Clean version of pq #962 fixes issue #961.

This commit is contained in:
Mikael Lepistö 2016-02-01 11:51:02 +02:00
parent 064d416a8e
commit 79a77ac932
3 changed files with 18 additions and 2 deletions

View File

@ -1210,14 +1210,16 @@ knex('books')
<br />
Creates an <tt>update</tt> 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
<tt>undefined</tt> it is ignored.
</p>
<pre class="display">
knex('books')
.where('published_date', '<', 2000)
.update({
status: 'archived'
status: 'archived',
thisKeyIsSkipped: undefined
})
</pre>

View File

@ -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

View File

@ -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: {