Skip to content

model.get() does not clone objects for JSON data-type #10052

Closed

Description

@justinkalland

What are you doing?

const Sequelize = require('sequelize')

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: ':memory:'
})

const Album = sequelize.define('User', {
  name: Sequelize.TEXT,
  attributes: Sequelize.JSON
})

Album.sync().then(() => {
  return Album.create({
    name: 'Slow Dance Showdown',
    attributes: {
      artist: 'john smith',
      genre: 'rock'
    }
  })
}).then(album => {
  const dataCopy = album.toJSON()

  dataCopy.attributes.genre = 'classical'
  dataCopy.name = 'Workout Jams'

  console.log('Name compare: ' + (dataCopy.name === album.name)) // works properly
  console.log('Attributes compare: ' + (dataCopy.attributes === album.attributes)) // does not work properly
})

What do you expect to happen?

Using JSON data-type I expect model.get() and model.toJSON() to return a copy of the object.

What is actually happening?

Instead of a copy of the object representing the JSON you get a reference to the same object that the model uses.

Dialect: mysql / postgres / sqlite
Dialect version: various
Database version: various
Sequelize version: master branch
Tested with latest release: Yes

Activity

  1. added
    type: bug
    good first issue
    on Oct 21, 2018
  2. sushantdhiman commented on Oct 21, 2018

    @sushantdhiman
    Contributor

    We need to cloneDeep

    return _.clone(

  3. SimonSchick commented on Oct 21, 2018

    @SimonSchick
    Contributor

    @sushantdhiman shouldn't it perform the deep clone here instead?

    if (Array.isArray(this.dataValues[key])) {
    ? then you could probably get rid of the clone in the toJSON call too.

  4. ALiangLiang commented on Oct 21, 2018

    @ALiangLiang
    Contributor

    @sushantdhiman shouldn't it perform the deep clone here instead?

    sequelize/lib/model.js

    Line 3308 in be958ac

    if (Array.isArray(this.dataValues[key])) {
    ? then you could probably get rid of the clone in the toJSON call too.

    It's only deep clone Array data. But @justinkalland want to deep clone whole Object JSON.

  5. justinkalland commented on Oct 21, 2018

    @justinkalland
    ContributorAuthor

    @sushantdhiman That is an easy fix, and I will submit a pull request. I just wasn't sure what the intended behavior of .get() without a key was supposed to be. Do you believe only model.toJSON() should return a clone, but not model.get()? It seems in some cases .get returns a clone and some cases this.dataValues. This is why I submitted an issue instead of just a pull request with cloneDeep.

    Here is an example of what I mean. Two cases where .get returns either a reference to this.dataValues OR a "clone":

    const Sequelize = require('sequelize')
    
    const sequelize = new Sequelize({
      dialect: 'sqlite',
      storage: ':memory:',
      logging: false
    })
    
    const Album = sequelize.define('Album', {
      name: Sequelize.TEXT
    })
    
    const AlbumWithGetter = sequelize.define('AlbumWithGetter', {
      name: {
        type: Sequelize.TEXT,
        get () {
          // custom getter
        }
      }
    })
    
    Album.sync().then(() => {
      return Album.create({
        name: 'Slow Dance Showdown'
      })
    }).then(album => {
      const dataCopy = album.get()
    
      dataCopy.name = 'Workout Jams'
    
      console.log('Album Name compare: ' + (dataCopy.name === album.name)) // true, because reference
    })
    
    AlbumWithGetter.sync().then(() => {
      return AlbumWithGetter.create({
        name: 'Slow Dance Showdown'
      })
    }).then(album => {
      const dataCopy = album.get()
    
      dataCopy.name = 'Slow Sleepy Hits'
    
      console.log('AlbumWithGetter Name compare: ' + (dataCopy.name === album.name)) //false, because clone
    
      return AlbumWithGetter.sync()
    })
  6. SimonSchick commented on Oct 21, 2018

    @SimonSchick
    Contributor

    @sushantdhiman I wasn't talking about the exact line but the general location, you'd have to check if typeof this.dataValues[key] === 'object' before returning the data, avoid having to deep clone the entire object.

  7. sushantdhiman commented on Oct 21, 2018

    @sushantdhiman
    Contributor

    Do you believe only model.toJSON() should return a clone, but not model.get()? It seems in some cases .get returns a clone and some cases this.dataValues. This is why I submitted an issue instead of just a pull request with cloneDeep.

    I personally believe they both (and other cases) all should return a deep cloned value. We never want mutations from get() or toJSON() to affect our next save or update call.

    As for its implications I am not so sure

    1. There is a clone option for get, but I don't see it used any where
    2. Performance impact, I see internal codebase is using mostly key based case which should not be affected. This is just a concern, any incorrect behaviour should be correct regardless of performance impact.

    This code is so old I am not sure, @justinkalland I say let's try a PR which iron out these cases so we return deep cloned value for all cases. As @SimonSchick suggested we can use selective cases to avoid cloning whole objects

  8. justinkalland commented on Oct 21, 2018

    @justinkalland
    ContributorAuthor

    I agree @sushantdhiman ,get() should always returned a deep clone value, and toJSON() should just alias get() with no key (as it is documented as doing). But I suspect that the inconsistent behavior of get() may be relied upon in sequelize.

  9. justinkalland commented on Oct 21, 2018

    @justinkalland
    ContributorAuthor

    I worked on a fix for this but changing get() gets complicated. It has a default option options.plain=false and so by default it returns references to included Model instances (rather than "clones" of their data). This behavior is in use many places. If this was a new library I would argue to remove options.plain and always return cloned. But with the age of Sequelize perhaps just changing the toJSON to cloneDeep would be an acceptable solution.

  10. sushantdhiman commented on Oct 22, 2018

    @sushantdhiman
    Contributor

    @justinkalland Yeah deep clone for toJSON is good enough

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

    good first issuetype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions