From 594cee88a54ef82709b04c5ffd9a1f03d76b2d18 Mon Sep 17 00:00:00 2001 From: Matthew Blasius Date: Mon, 1 Nov 2021 12:57:09 -0500 Subject: [PATCH] fix(upsert): do not overwrite an explcit created_at during upsert (#13593) We found that when doing an upsert with model data that already included a `createdAt` timestampe, our explcit `createdAt` was being overwritten with the current time any time we also utilized the `fields` option. e.g. ``` const instance = await MyModel.upsert({ id: 1, myfield: 'blah', createdAt: new Date('2010-01-01T12:00:00.000Z') }, { fields: [ 'myfield' ], returning: true }); console.log(instance.createdAt); // expected 2010-01-01T12:00:00.000Z, but got a now()-ish timestamp. ``` Issue appears to be that the check for a provided `createdAt` was being checked against the `updateValues` instead of the `insertValues`. Most of the time, this is inconsequential because the `insertValues` and `updateValues` both contain the same fields. But, when using the `fields` feature, the `createdAt` field is stripped away from the `updateValues`, so sequelize happily overwrites the `insertValues.createAt` value. Co-authored-by: Sascha Depold --- lib/model.js | 2 +- test/integration/model/upsert.test.js | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index 8e1b98e6a765..22bb01ead46b 100644 --- a/lib/model.js +++ b/lib/model.js @@ -2480,7 +2480,7 @@ class Model { const now = Utils.now(this.sequelize.options.dialect); // Attach createdAt - if (createdAtAttr && !updateValues[createdAtAttr]) { + if (createdAtAttr && !insertValues[createdAtAttr]) { const field = this.rawAttributes[createdAtAttr].field || createdAtAttr; insertValues[field] = this._getDefaultTimestamp(createdAtAttr) || now; } diff --git a/test/integration/model/upsert.test.js b/test/integration/model/upsert.test.js index 2a67cb18e6c7..26e51c7bbc26 100644 --- a/test/integration/model/upsert.test.js +++ b/test/integration/model/upsert.test.js @@ -302,6 +302,15 @@ describe(Support.getTestDialectTeaser('Model'), () => { clock.restore(); }); + it('does not overwrite createdAt when supplied as an explicit insert value when using fields', async function() { + const clock = sinon.useFakeTimers(); + const originalCreatedAt = new Date('2010-01-01T12:00:00.000Z'); + await this.User.upsert({ id: 42, username: 'john', createdAt: originalCreatedAt }, { fields: ['id', 'username'] }); + const user = await this.User.findByPk(42); + expect(user.createdAt).to.deep.equal(originalCreatedAt); + clock.restore(); + }); + it('does not update using default values', async function() { await this.User.create({ id: 42, username: 'john', baz: 'new baz value' }); const user0 = await this.User.findByPk(42);