Skip to content

Commit

Permalink
fix(upsert): do not overwrite an explcit created_at during upsert (#1…
Browse files Browse the repository at this point in the history
…3593)

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 <sdepold@users.noreply.github.com>
  • Loading branch information
slickmb and sdepold committed Nov 1, 2021
1 parent 719bb59 commit 594cee8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/model.js
Expand Up @@ -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;
}
Expand Down
9 changes: 9 additions & 0 deletions test/integration/model/upsert.test.js
Expand Up @@ -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);
Expand Down

0 comments on commit 594cee8

Please sign in to comment.