Skip to content

Scopes' includes are not shallowly merged as the documentation claims #9087

Closed

Description

@papb

What are you doing?

I am testing with a minimal example whether or not scopes' includes are shallowly merged, as the documentation claims: limit, offset, order, paranoid, lock and raw are overwritten, while where and include are shallowly merged. (source: http://docs.sequelizejs.com/manual/tutorial/scopes.html)

const Sequelize = require("sequelize");
const sequelize = new Sequelize({ dialect: "sqlite", storage: "db.sqlite" });
const Foo = sequelize.define("foo", { name: Sequelize.STRING }, { timestamps: false });
const Bar = sequelize.define("bar", { name: Sequelize.STRING }, { timestamps: false });
Foo.hasMany(Bar, { foreignKey: "fooId" });
Foo.addScope("testScope", {
    include: [{
        model: Bar,
        where: {
            name: "bar1"
        }
    }]
});
sequelize.sync({ force: true })
    .then(() => Foo.create({ name: "foo1" }))
    .then(foo1 => Bar.create({ name: "bar1", fooId: foo1.id }))
    .then(() => Foo.create({ name: "foo2" }))
    .then(foo2 => Bar.create({ name: "bar2", fooId: foo2.id }))
    .then(() => Foo.scope("testScope").findAll({
        include: [{
            model: Bar,
            attributes: { exclude: ["name"] }
        }]
    }))
    .then(result => console.log(JSON.stringify(result, null, 4)));

What do you expect to happen?

I expected the scope to be merged with the findAll options, which should yield the following output:

[
    {
        "id": 1,
        "name": "foo1",
        "bars": [
            {
                "id": 1,
                "fooId": 1
            }
        ]
    }
]

What is actually happening?

The output was:

[
    {
        "id": 1,
        "name": "foo1",
        "bars": [
            {
                "id": 1,
                "fooId": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "foo2",
        "bars": [
            {
                "id": 2,
                "fooId": 2
            }
        ]
    }
]

Clearly, the scope was completely overwritten by the findAll options.

I wanted my code to behave exactly as if I had called the following:

Foo.scope("testScope").findAll({
    include: [{
        model: Bar,
        where: {
            name: "bar1"
        },
        attributes: { exclude: ["name"] }
    }]
})

Dialect: sqlite (sqlite3 v3.1.13)
Dialect version: 3.1.13
Sequelize version: 4.33.4
Tested with latest release: Yes

Note: if somehow this is the correct behavior, honestly the docs should be clarified. The include field is an array of objects, and "shallowly merging" an array of objects is not perfectly clear, does it mean that the arrays are concatenated? I hope not. I understand that the behavior I'm expecting is not trivial to code, but if the documentation claims it, it should do it. My understanding of "shallowly merging" in this context would be that the objects in the include arrays are "matched" to each other based on the "model-as" pairs, shallowly merging the other fields (and hopefully, recursively, since I could have nested includes in my scopes).

Thank you very much in advance, sequelize has been very useful so far 😁

Activity

  1. added
    type: bug
    on Feb 25, 2018
  2. yocontra commented on Mar 29, 2018

    @yocontra
    Contributor

    @sushantdhiman Can you point me to where this behavior is supposed to happen? I can fix this and send a PR today.

    This is important behavior to fix since people use these exclusion rules in scopes to hide password fields, api keys, etc. and specifying additional exclusion rules in a query will then override the scope and show these attributes. There are probably many people who are leaking sensitive attributes in the wild and don't even know it.

  3. yocontra commented on Mar 29, 2018

    @yocontra
    Contributor

    This might be a pretty easy fix - Line 2875 of model.js:

    let attributes = Object.keys(this.rawAttributes);

    should be replaced with:

    let hasScope = this._scope && this._scope.attributes
    let attributes = hasScope ? this._scope.attributes : Object.keys(this.rawAttributes);

    This will only allow future attributes options to pick from the output of the scope, which is the desired behavior. From my own tests this has fixed the issue for us.

  4. sushantdhiman commented on Mar 30, 2018

    @sushantdhiman
    Contributor

    So I would like to clarify how scopes behave (as per my findings, they have been long part of sequelize before my involvement with project)

    1. attributes and where options from all scopes combined under ._scope defaults over to what is passed as options.attributes and options.where. Consider this example
    Foo.scope(['testScopeA', 'testScopeB']).findAll({
        attributes: ['id'],
        where: {
          'name': 'foo1'
        },
        include: [{
          model: Bar,
          where: {
            name: 'bar1'
          }
        }]
      }))
    
    // a. suppose `testScopeA` and `testScopeB` results in some `where` and `attributes` options
    //     but as findAll.options is already supplying that, scope options wont be used
    // b. special case for where though, where = defaults(options.where, scope.where)
    //     if same where keys are not passed by `options.where`, `scope.where` key will be defaulted
    1. options.include of same model/association pair will replace any same include from scopes
    Foo.scope(['testScopeA', 'testScopeB']).findAll({
        include: [{
          model: Bar,
          where: {
            name: 'bar1'
          }
        }]
      }))
    
    // suppose `testScopeA` and `testScopeB` also trying to include { model: Bar }
    // it wont be used as findAll.options.include already contain an entry with `{ model:  Bar }`
    1. Scopes themselves are shallow merged with other scopes to result in a combined scope (this is what documentation mean by shallow merging of scopes). They wont be merged with findAll.options as explained above.
    Foo.addScope('testScopeA', {
      attributes: { exclude: ['id'] },
      where: {
        name: 'xx'
      },
      include: [{
        model: Bar,
        where: {
          [Sequelize.Op.and]: [{
            name: 'bar1'
          }]
        },
        attributes: { exclude: ['id'] }
      }]
    });
    
    Foo.addScope('testScopeB', {
      attributes: { exclude: ['name'] },
      include: [{
        model: Bar,
        where: {
          [Sequelize.Op.and]: [{
            name: 'bar2'
          }]
        },
        attributes: { exclude: ['name'] }
      }]
    });
    
    Foo.scope(['testScopeA', 'testScopeB']).findAll({}))
      .then(result => console.log('just scopes', JSON.stringify(result, null, 4)))
    
    [
        {
            "name": "foo2",
            "id": 2,
            "bars": [
                {
                    "id": 2,
                    "fooId": 2
                }
            ]
        }
    ]
    
    
    // a. where options are merged together from all scopes
    // b. attributes, includes and group are concated from all scopes in play
    // c. If there are multiple includes of same model/association pair
    //     only include from last scope will take precedence
    //     same include wont be merged

    @contra #9252 looks invalid as per current behaviour which is to treat scope.where / scope.attributes etc as defaults for findAll.options

  5. yocontra commented on Mar 30, 2018

    @yocontra
    Contributor

    @sushantdhiman Do you think that behavior is right? That sounds wrong to me IMO. I would expect that when I scope a model I won't be able to "escape" that scope no matter what options I pass to it later on. When I read the documentation previously I got the impression that this was how it was intended to work.

    Could we discuss changing this behavior for v5? #9252 does some of it, would need a few additional changes to tackle where merging if that isn't there already.

  6. papb commented on Apr 3, 2018

    @papb
    MemberAuthor

    Sorry to take so long to reply! Thanks @contra for taking the time to look into this, and thanks @sushantdhiman for the clarifications 😁. I'm looking forward to see this fixed, so I will do my best to reply faster.

    Let me start with a few points:

    • 1. I totally agree with @contra's last comment above. If the current behavior is the expected behavior, I think it should be changed.

    • 2. In my opinion, the current docs for scopes does not reflect very well what was said in @sushantdhiman's clarifications above.
      Whether or not the behavior will be changed, I think the docs deserve some improvements, but we can worry about improving the docs later (after we agree on the behavior itself).

    • 3. @sushantdhiman - you said in your third bullet above that scopes are shallowly merged among themselves but not merged with findAll.options. The docs seem to imply otherwise, where it says that Here the deleted scope is merged with the finder. Regardless, if we make a minor change in my snippet from the first post, moving the options from the findAll into another new scope, testScope2, and calling Foo.scope("testScope", "testScope2").findAll() instead, we will get the same result anyway (and I still stand for my opinion that such behavior is wrong).

  7. papb commented on Apr 4, 2018

    @papb
    MemberAuthor

    Another very important clarification that I'd like to make is: when opening the issue, I tried to make a minimal example to convey my problem, and for that I arbitrarily chose to use the attributes option, but it could easily have been anything else, like a limit option, or a nested include. To expand on this, hoping to clarify my goal when I opened the issue, I prepared another example:

    Take the following code:

    const Sequelize = require('sequelize');
    const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'db.sqlite' });
    
    const Foo = sequelize.define("foo", { name: Sequelize.STRING }, { timestamps: false });
    const Bar = sequelize.define("bar", { name: Sequelize.STRING }, { timestamps: false });
    const Baz = sequelize.define("baz", { name: Sequelize.STRING }, { timestamps: false });
    Foo.hasMany(Bar, { foreignKey: "fooId" });
    Bar.hasMany(Baz, { foreignKey: "barId" });
    
    Foo.addScope("includeBaz", {
        include: [{
            model: Bar,
            include: [{
                model: Baz
            }]
        }]
    });
    Foo.addScope("limitedBars", {
        include: [{
            model: Bar,
            limit: 2
        }]
    });
    
    var foo;
    
    sequelize.sync()
        .then(() => Foo.create({ name: "foo" })).then(created => { foo = created; })
        .then(() => Promise.all([
            Bar.create({ name: "bar1" }).then(bar => bar.createBaz({ name: "baz1" })),
            Bar.create({ name: "bar2" }).then(bar => bar.createBaz({ name: "baz2" })),
            Bar.create({ name: "bar3" }).then(bar => bar.createBaz({ name: "baz3" }))
        ]))
        .then(createdBars => foo.setBars(createdBars.map(b => b.id)))
        .then(() => {
            // Situation A: we ignore the scopes defined above and specify the options directly
            return Foo.findAll({
                include: [{
                    model: Bar,
                    limit: 2,
                    include: [{
                        model: Baz
                    }]
                }]
            });
    
            // Situation B: we use the scopes
            // return Foo.scope("includeBaz", "limitedBars").findAll();
    
            // Situation C: we use the scopes in reversed order
            // return Foo.scope("limitedBars", "includeBaz").findAll();
        })
        .then(result => {
            console.log(JSON.stringify(result.map(x => x.toJSON()), null, 4));
        });

    Situation A results in:

    [
        {
            "id": 1,
            "name": "foo",
            "bars": [
                {
                    "id": 1,
                    "name": "bar1",
                    "fooId": 1,
                    "bazs": [
                        {
                            "id": 1,
                            "name": "baz1",
                            "barId": 1
                        }
                    ]
                },
                {
                    "id": 2,
                    "name": "bar2",
                    "fooId": 1,
                    "bazs": [
                        {
                            "id": 2,
                            "name": "baz2",
                            "barId": 2
                        }
                    ]
                }
            ]
        }
    ]

    Situation B results in:

    [
        {
            "id": 1,
            "name": "foo",
            "bars": [
                {
                    "id": 1,
                    "name": "bar1",
                    "fooId": 1
                },
                {
                    "id": 2,
                    "name": "bar2",
                    "fooId": 1
                }
            ]
        }
    ]

    Situation C results in:

    [
        {
            "id": 1,
            "name": "foo",
            "bars": [
                {
                    "id": 1,
                    "name": "bar1",
                    "fooId": 1,
                    "bazs": [
                        {
                            "id": 1,
                            "name": "baz1",
                            "barId": 1
                        }
                    ]
                },
                {
                    "id": 2,
                    "name": "bar2",
                    "fooId": 1,
                    "bazs": [
                        {
                            "id": 2,
                            "name": "baz2",
                            "barId": 2
                        }
                    ]
                },
                {
                    "id": 3,
                    "name": "bar3",
                    "fooId": 1,
                    "bazs": [
                        {
                            "id": 3,
                            "name": "baz3",
                            "barId": 3
                        }
                    ]
                }
            ]
        }
    ]

    As you can see, all results were different. I don't know if this is the expected behavior or not, but regardless, I think this is bad and counter-intuitive. Instead, I think Situations B and C should behave exactly as Situation A.

    @contra and @sushantdhiman, do you agree with me?

    Thanks again for taking the time!! 😃

  8. added
    status: in discussion
    on Apr 19, 2018
  9. sushantdhiman commented on Apr 19, 2018

    @sushantdhiman
    Contributor

    Sorry I haven't got back to this issue, busy with v5 milestone.

    There is only one important change from milestone remaining after that I will propose something to tackle this issue. I intend to overhaul scopes in v5

  10. papb commented on Apr 19, 2018

    @papb
    MemberAuthor

    @sushantdhiman Looks good, thanks for the update and for all the good work with Sequelize :)

    When you do get back on this, I will be happy to discuss it further with you/others.

  11. papb commented on May 27, 2018

    @papb
    MemberAuthor

    @sushantdhiman Hello again :) Have you considered adding this to the v5 milestone? Since you said you intend to overhaul scopes in v5, I think it would be a good idea to have this issue in the list.

    The change I am proposing here is probably a breaking change, and this way it would be best if included in the v5 milestone (otherwise it would have to wait for v6?)

  12. added this to the v5 milestone on May 28, 2018
  13. sushantdhiman commented on Aug 31, 2018

    @sushantdhiman
    Contributor

    Can you guys take a look at #9735 , essentially this PR is trying to fix #6245 but now we have came to a point that we have to change merge strategy for scopes.

    If you can share your ideas in that PR we may be able to cover changes we discussed here in that PR

  14. sushantdhiman commented on Oct 28, 2018

    @sushantdhiman
    Contributor

    @u9r52sld tackled some issues with scopes in #9735, now AFAICT we just need to decide merge strategy for scopes with finder options.

    Can you guys reiterate your suggestions on how scopes should merge with finder options. What should get more priority i.e. attributes, includes etc from scopes or finder options

  15. papb commented on Oct 28, 2018

    @papb
    MemberAuthor

    Hello @sushantdhiman. In my point of view, the options passed to findAll() and findOne() should merge exactly as if they were another scope.

    But the changes made by #9735 already address this - I've just retested to be sure, and everything I asked in this issue is indeed covered by #9735.

    To me, there is nothing else to be done, you can close this issue if you want 😁

    Let me know if you want further clarfications.

  16. added a commit that references this issue on Mar 16, 2019
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

    status: in discussiontype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions