Skip to content

JSON property dirty checking broken in v6 #13006

Closed

Description

@erwinw

Issue Description

What are you doing?

Updating a JSON property on a model instance does not check for dirty; changes do not get submitted.

class User extends Model {}
User.init({
  id: {type: Sequelize.UUID, primaryKey: true, defaultValue: Sequelize.UUIDV4},
  status: DataTypes.JSON
}, { sequelize, modelName: 'user' });

await sequelize.sync();

const aUser = await User.create({
    status: { mood: 'sad' }
 };

aUser.status.mood = 'happy';
aUser.update({status: aUser.status });

const bUser = await User.findByPk(aUser.id);
console.log(bUser.status.mood); // 'sad', not 'happy'

What do you expect to happen?

Just like in Sequelize v5, I expected the row to be updated in the database.

What is actually happening?

Nothing; the record is not updated.

Additional context

As mentioned, this is a breaking change from v5 to v6.

This problem was actually first raised in #12960 , but then closed again 🤷🏻

We were in the process of migrating from Sequelize v5 to v6 in a medium-large code base (50+ models), and have to put that on hold because of this breaking change, and the risk that not all instances of this behaviour have been identified by our tests.

Environment

  • Sequelize version: 6.4.0
  • Node.js version: v12.17.0
  • Operating System: MacOS Big Sur 11.2, Alpine Linux 3.12
  • If TypeScript related: TypeScript version: 4.1.3 (not TS related)

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. RufusHamade commented on Apr 13, 2021

    @RufusHamade

    I'm suffering from the same issue. Interestingly, it is very much dependent on how you do the update. Using the following test script:

    
    (async () => {
      const path = 'mysql://os_moderator:password@localhost:3306/testdb';
      const sequelize = new Sequelize(path, {
        operatorsAliases: false
      });
    
      class Dummy extends Model {}
    
      Dummy.init({
        description: DataTypes.STRING,
        otherAt: DataTypes.DATE,
        data: DataTypes.JSON,
      }, {
        sequelize,
        modelName: 'Dummy',
      });
    
      await Dummy.sync();
      console.log('New table created');
      let id;
      {
        const d = Dummy.build({
          description: 'test',
          otherAt: Sequelize.fn('now'),
          data: {counter: 1},
        });
        await d.save();
        id = d.id
      }
    
      {
        const d = await Dummy.findByPk(id)
        console.log(d.id, d.data)
        await d.update({
          description: 'test2',
          data: {counter: 2},
        })
      }
    
      {
        const d = await Dummy.findByPk(id)
        console.log(d.id, d.data)
        const data = d.data;
        data.counter = 3;
        await d.update({
          description: 'test3',
          data,
        })
      }
      {
        const d = await Dummy.findByPk(id)
        console.log(d.id, d.data)
      }
      await sequelize.close()
    })();
    

    Produces the following output:

    New table created
    Executing (default): INSERT INTO `Dummies` (`id`,`description`,`otherAt`,`data`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,now(),?,?,?);
    Executing (default): SELECT `id`, `description`, `otherAt`, `data`, `createdAt`, `updatedAt` FROM `Dummies` AS `Dummy` WHERE `Dummy`.`id` = 7;
    7 { counter: 1 }
    Executing (default): UPDATE `Dummies` SET `description`=?,`data`=?,`updatedAt`=? WHERE `id` = ?
    Executing (default): SELECT `id`, `description`, `otherAt`, `data`, `createdAt`, `updatedAt` FROM `Dummies` AS `Dummy` WHERE `Dummy`.`id` = 7;
    7 { counter: 2 }
    Executing (default): UPDATE `Dummies` SET `description`=?,`updatedAt`=? WHERE `id` = ?
    Executing (default): SELECT `id`, `description`, `otherAt`, `data`, `createdAt`, `updatedAt` FROM `Dummies` AS `Dummy` WHERE `Dummy`.`id` = 7;
    7 { counter: 2 }
    

    Notice the first update works, but the second one does not.

    Tested with Sequelize 6.6.2

  2. vkaracic commented on Jul 14, 2021

    @vkaracic

    I had the same issue and after going through the source code I believe the issue is the way that Sequelize now tests what has changed. As evident from @RufusHamade comment, Sequelize now checks if the updated value is the same as the model instance property value instead of the value that is currently in the database.
    So in this case:

    class User extends Model {}
    User.init({
      id: {type: Sequelize.UUID, primaryKey: true, defaultValue: Sequelize.UUIDV4},
      status: DataTypes.JSON
    }, { sequelize, modelName: 'user' });
    
    await sequelize.sync();
    
    const aUser = await User.create({
        status: { mood: 'sad' }
     };
    
    const { status } = aUser;
    status.mood = 'happy';
    aUser.update({ status });
    
    const bUser = await User.findByPk(aUser.id);
    console.log(bUser.status.mood); // 'sad', not 'happy'

    the aUser.update checks if aUser.status === status, which is equal since it is the same object, and doesn't run any save/updates to the database. Even if you would clone the object it wouldn't work because the values are still the same. I presume in the previous Sequelize version it would check if the database value has changed, so something like aUser.valuesFromDatabase.status === status and make the change. Not sure if this change is intentional, I certainly couldn't find any documentation explaining this.

  3. mekantor commented on Sep 20, 2021

    @mekantor

    Came by this today, you can manually do instance.changed('column', true); but this is not ideal. My basic test for it:

    model = sequelize.define('table', {
        test: {
            type: DataTypes.JSON,
            defaultValue: {}
        }
    });
    
    instance = new model();
    instance.test.foo = 'bar';
    
    // expecting true, get false
    console.log(instance.changed('test'));
    

    Update: pass {raw: true} as an option parameter, and the column will be marked as changed:
    instance.set('column', value, {raw: true});

  4. github-actions commented on Oct 27, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  5. zorji commented on Oct 29, 2021

    @zorji
    Contributor

    I have added a test case but haven't got time to complete the implementation not sure if anyone could help with this? https://github.com/zorji/sequelize/commit/d2836801f9eb95cfdd92b1a86d5fa11b51b43274

  6. mooncfrat2019 commented on Nov 6, 2021

    @mooncfrat2019

    Confirming the issue. Very annoying. Hope someone can fix it soon)

  7. github-actions commented on Nov 21, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  8. added
    type: bug
    and removed on Nov 22, 2021
  9. wbourne0 commented on Apr 18, 2023

    @wbourne0
    Member

    fwiw the issue appears to be that sequelize only checks to see if the reference to the object is the same, i.e. oldValues.status === newValues.status. Could probably solve this by saving the jsonified value as a string and comparing, though that would be at the cost of memory usage.

  10. ephys commented on Jun 22, 2023

    @ephys
    Member

    That's by design. The new documentation has a big warning about treating the values as immutable: https://sequelize.org/docs/v7/querying/update/#updating-a-row-using-modelsave

    Keeping a stringified version (or ideally a structuredClone), then deep-equaling them would be expensive. I think it's better to make them immutable. In the future we could even switch to Record & Tuples

    I'll close this as working as designed now that it's documented

  11. anthonyorona commented on Jul 24, 2023

    @anthonyorona

    Not so sure this is isolated to JSON datatype.

    I have a model where a field using an extended datatype "LTREE" is not updated on save.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions