Skip to content

Deep eager load chains does not produce valid sql, regression from sequelize 3 #9869

Open

Description

@linpekka

What are you doing?

When upgrading from sequelize 3, i noticed that some lookups does no longer produce valid sql.

'use strict';

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

let Model, ModelB, ModelC, ModelD, ModelE;

/**
 * @param {boolean} useEnum
 */
async function test(useEnum) {
  const db = new Sequelize('test', 'user', 'user', {
    host: '127.0.0.1',
    dialect: 'postgresql',
    "quoteIdentifiers": true, 
    "underscored": true
  });  

  Model = db.define('Model', { not_id : Sequelize.INTEGER }, {});
  ModelB = db.define('ModelB', { model_id : Sequelize.INTEGER }, {});
  ModelC = db.define('ModelC', { modelB_id : Sequelize.INTEGER }, {});
  ModelD = db.define('ModelD', { modelC_id : Sequelize.INTEGER, modelE_id : Sequelize.INTEGER }, {});
  ModelE = db.define('ModelE', {}, {});

  Model.hasMany(ModelB, {foreignKey: 'model_id'});
  ModelB.belongsTo(Model, {foreignKey: 'model_id'});

  ModelB.hasMany(ModelC, {foreignKey: 'modelB_id'});
  ModelC.belongsTo(ModelB, {foreignKey: 'modelB_id'});

  ModelC.hasMany(ModelD, {foreignKey: 'modelC_id'});
  ModelD.belongsTo(ModelC, {foreignKey: 'modelC_id'});

  ModelD.belongsTo(ModelE, {foreignKey: 'modelE_id'});
  ModelE.hasMany(ModelD, {foreignKey: 'modelE_id'});

  await db.sync({ force: true });

  await populateDb();

  console.log('Find that does not reproduce the issue')
  const t1 = await Model.findOne({where: {id:1}, include:[
    {
      model:ModelB,
      required: true,
      include:[
        {
          model:ModelC,
          required: true,
          include:[
            {
              model:ModelD,
              required: true,
              include:[
                {
                  model:ModelE,
                  required: true
                }
              ]
            }
          ]
        }
      ]
    }
  ]});

  console.log('Find that reproduces the issue')
  const t2 = await Model.findOne({where: {not_id:2}, include:[
    {
      model:ModelB,
      required: true,
      include:[
        {
          model:ModelC,
          required: true,
          include:[
            {
              model:ModelD,
              required: true,
              include:[
                {
                  model:ModelE,
                  required: true
                }
              ]
            }
          ]
        }
      ]
    }
  ]});

  await db.close();
}

async function populateDb() {
  const model = await Model.create({ not_id:2});
  const modelB = await ModelB.create({ model_id:model.id });
  const modelC = await ModelC.create({ modelB_id:modelB.id });

  const modelE = await ModelE.create({ });

  const modelD = await ModelD.create({ modelC_id:modelC.id, modelE_id:modelE.id });
}

async function main() {
  try {
    console.log('Bad sql');
    await test();
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
}

main();

What do you expect to happen?

I want the findOne to generate valid sql

What is actually happening?

SequelizeDatabaseError: missing FROM-clause entry for table "ModelBs->ModelCs->ModelDs->ModelE"

Output, either JSON or SQL

'SELECT "Model".*, "ModelBs"."id" AS "ModelBs.id", "ModelBs"."model_id" AS "ModelBs.model_id", "ModelBs"."createdAt" AS "ModelBs.createdAt", "ModelBs"."updatedAt" AS "ModelBs.updatedAt", "ModelBs->ModelCs"."id" AS "ModelBs.ModelCs.id", "ModelBs->ModelCs"."modelB_id" AS "ModelBs.ModelCs.modelB_id", "ModelBs->ModelCs"."createdAt" AS "ModelBs.ModelCs.createdAt", "ModelBs->ModelCs"."updatedAt" AS "ModelBs.ModelCs.updatedAt", "ModelBs->ModelCs->ModelDs"."id" AS "ModelBs.ModelCs.ModelDs.id", "ModelBs->ModelCs->ModelDs"."modelC_id" AS "ModelBs.ModelCs.ModelDs.modelC_id", "ModelBs->ModelCs->ModelDs"."modelE_id" AS "ModelBs.ModelCs.ModelDs.modelE_id", "ModelBs->ModelCs->ModelDs"."createdAt" AS "ModelBs.ModelCs.ModelDs.createdAt", "ModelBs->ModelCs->ModelDs"."updatedAt" AS "ModelBs.ModelCs.ModelDs.updatedAt" FROM (SELECT "Model"."id", "Model"."not_id", "Model"."createdAt", "Model"."updatedAt", "ModelBs->ModelCs->ModelDs->ModelE"."id" AS "ModelBs.ModelCs.ModelDs.ModelE.id", "ModelBs->ModelCs->ModelDs->ModelE"."createdAt" AS "ModelBs.ModelCs.ModelDs.ModelE.createdAt", "ModelBs->ModelCs->ModelDs->ModelE"."updatedAt" AS "ModelBs.ModelCs.ModelDs.ModelE.updatedAt" FROM "Models" AS "Model" WHERE "Model"."not_id" = 2 AND ( SELECT "ModelBs"."model_id" FROM "ModelBs" AS "ModelBs" INNER JOIN "ModelCs" AS "ModelCs" ON "ModelBs"."id" = "ModelCs"."modelB_id" INNER JOIN "ModelDs" AS "ModelCs->ModelDs" ON "ModelCs"."id" = "ModelCs->ModelDs"."modelC_id" INNER JOIN "ModelEs" AS "ModelCs->ModelDs->ModelE" ON "ModelCs->ModelDs"."modelE_id" = "ModelCs->ModelDs->ModelE"."id" WHERE ("ModelBs"."model_id" = "Model"."id") LIMIT 1 ) IS NOT NULL LIMIT 1) AS "Model" INNER JOIN "ModelBs" AS "ModelBs" ON "Model"."id" = "ModelBs"."model_id" INNER JOIN "ModelCs" AS "ModelBs->ModelCs" ON "ModelBs"."id" = "ModelBs->ModelCs"."modelB_id" INNER JOIN "ModelDs" AS "ModelBs->ModelCs->ModelDs" ON "ModelBs->ModelCs"."id" = "ModelBs->ModelCs->ModelDs"."modelC_id";'

__Dialect:postgres
__Dialect version:(PostgreSQL) 9.6.5
__Database version:(PostgreSQL) 9.6.5
__Sequelize version:4.38.0
__Tested with latest release:4.38.0

Note : Your issue may be ignored OR closed by maintainers if it's not tested against latest version OR does not follow issue template.

Activity

  1. sushantdhiman commented on Sep 4, 2018

    @sushantdhiman
    Contributor

    How I am supposed to solve this :D Please distil your issue to proper test case which represents what is not working


    Please use Github Issue Tracker only for reporting bugs, requesting new features or discussions. Ask questions on Stackoverflow sequelize.js tag or Slack. While I would like to help answer any questions but it still take too much time.

    If you are reporting a bug please isolate it as SSCCE, present it nicely and follow issue template. This will help maintainers and contributors understand your issue quickly.

    If you are requesting a feature spend some time to properly present your use case with some examples, current and expected outcome.

    ( What is SSCCE ? You can find template for Sequelize here )

    A few good example of SSCCE

    1. ResourceRequest timed out - connection not reestablished after db restarted #8014 (comment)
    2. removeAttribute('id') results in undefined: null data value #7318 (comment)
    3. toJSON converting booleans to "t" (true) or "f" (false) #8749 (comment)
  2. linpekka commented on Sep 5, 2018

    @linpekka
    Author

    I edited the original post with a new self contained testcase structured similarily to #8749

  3. linpekka commented on Sep 5, 2018

    @linpekka
    Author

    @sushantdhiman - seems like i cannot reopen it, or perhaps I am just blind. If I dont hear from you in a couple of hours I guess I will open a new defect with the new test data in it.

  4. linpekka commented on Sep 5, 2018

    @linpekka
    Author

    Updated testcase, removed a few models that did not affect reproduction of the issue

  5. papigers commented on Sep 5, 2018

    @papigers

    @sushantdhiman @linpekka A similar bug can be found at my issue #9861.
    They might be both be a cause of the same bug, but my issue also adds another info on the issue: the temporary solution of using duplicating: false and how using scope breaks this solution.

  6. linpekka commented on Sep 6, 2018

    @linpekka
    Author

    @papigers, I see the similarities, hopefully enough information will soon be gathered so someone that maintains the project can figure out the issue, or issues that may well be the case. If you are looking for workarounds, what I ended up doing was to split the query into 2 smaller chained lookups, which in the end may not be that bad for performance since scheduling of the big sql might not be optimal. Another thing that could perhaps help is to split the where clause up and move it into the includes, not sure if that has any effect, but it looks like the missing table is used in the where part of the generated query.

  7. added
    type: bug
    regression
    and removed on Sep 8, 2018
  8. sushantdhiman commented on Sep 9, 2018

    @sushantdhiman
    Contributor

    Please try against PR #9900 that tries to fix this issue, test case is generated after studying similar issues.

    You can install this patch using npm install git://github.com/sequelize/sequelize.git#fix-deep-includes --save for testing its working. If enough users confirm this fix works I will merge and release it.

  9. papigers commented on Sep 9, 2018

    @papigers

    @sushantdhiman So I've tested it a bit and it seems it helps, but not entirely:
    This references my issue (#9861):

    1. The deep include I've mentioned seems to work without adding duplicating: false;
    2. Limit breaks it again with the same error:
    SELECT "Video".*, "channel"."id" AS "channel.id", "channel"."name" AS "channel.name" FROM (SELECT "Video"."id", "Video"."createdAt", "Video"."name", "Video"."description" FROM "Videos" AS "Video" WHERE ("Video"."channelId" = \'MOCK_USER_ID\' OR "Video"."privacy" = \'public\' OR ((("videoACL"."id" = \'MOCK_USER_ID\' AND "videoACL"."type" = \'USER\') OR ("videoACL"."id" IN (NULL) AND "videoACL"."type" = \'AD_GROUP\')) AND "Video"."privacy" != \'public\') OR ((("channel->channelACL"."id" = \'MOCK_USER_ID\' AND "channel->channelACL"."type" = \'USER\') OR ("channel->channelACL"."id" IN (NULL) AND "channel->channelACL"."type" = \'AD_GROUP\')) AND "Video"."privacy" = \'channel\')) AND "Video"."published" = true LIMIT
    12) AS "Video" LEFT OUTER JOIN "Channels" AS "channel" ON "Video"."channelId" = "channel"."id" LEFT OUTER JOIN "ChannelAccesses" AS "channel->channelACL" ON "channel"."id" = "channel->channelACL"."ChannelId" LEFT OUTER JOIN "VideoAccesses" AS "videoACL" ON "Video"."id" = "videoACL"."VideoId";
    1. When the same query with the deep includes is transferred to a scope, things not working either (even without a limit):
    'SELECT "Video"."id", "Video"."createdAt", "Video"."name", "Video"."description", "channel"."id" AS "channel.id", "channel"."name" AS "channel.name" FROM "Videos" AS "Video" LEFT OUTER JOIN "Channels" AS "channel" ON "Video"."channelId" = "channel"."id" LEFT OUTER JOIN "VideoAccesses" AS "videoACL" ON "Video"."id" = "videoACL"."VideoId" WHERE ("Video"."channelId" = \'MOCK_USER_ID\' OR "Video"."privacy" = \'public\' OR ((("videoACL"."id" = \'MOCK_USER_ID\' AND "videoACL"."type" = \'USER\') OR ("videoACL"."id" IN (NULL) AND "videoACL"."type" = \'AD_GROUP\')) AND "Video"."privacy" != \'public\') OR ((("channel->channelACL"."id" = \'MOCK_USER_ID\' AND "channel->channelACL"."type" = \'USER\') OR ("channel->channelACL"."id" IN (NULL) AND "channel->channelACL"."type" = \'AD_GROUP\')) AND "Video"."privacy" = \'channel\'));'
  10. linpekka commented on Sep 10, 2018

    @linpekka
    Author

    @sushantdhiman, it does seem to fix this issue. I tried running the tests in my real project against this version as well, for extra testing, even if the issue here has been worked around in these tests, but failed with an error message. I noticed that the version you refered to seems to be based on version 5, and I am currently on version 4, so if it is possible to get a version 4 variant of the fix, I would be happy to run the rest of my tests against it.

    "version": "5.0.0-beta.12"

    The error message was from sequelize-hierarchy, so may be that the version of it I have been using is not compatible with sequelize 5, or that other parts of my code needs to be updated to comply with sequalize 5, but since I'm currently not done upgrading to version 4 I would not like to jump forward to version 5 yet.

    "sequelize-hierarchy": "^1.3.2"

    TypeError: semverSelect(...) is not a function
    at module.exports (.../node_modules/sequelize-hierarchy/lib/errors.js:32:4)
    at module.exports (.../node_modules/sequelize-hierarchy/lib/index.js:23:2)

  11. 53 remaining items

  12. alexgbor commented on Mar 3, 2022

    @alexgbor

    Any update on this issue?

  13. ephys commented on Mar 4, 2022

    @ephys
    Member

    I can confirm that unfortunately the issue is still present in latest Sequelize (6.17).
    My only advice right now if you're encountering this issue is to use a raw query.

    We're a bit short on maintainers and the ones that are active already have their hands very full so I can't promise when a fix will be made available.

    If someone is willing to open a PR that includes tests & a fix, we'll gladly merge it!

  14. collin-pham commented on Mar 23, 2022

    @collin-pham
  15. higuitamartinez commented on Jul 9, 2022

    @higuitamartinez

    For doing a where with some field(s) from the models n:m with separate: true and limit, a way is the following:

    //Here get the user_id according to where
    const usersId = await Users.findAll({
        attributes: ['user_id'],
        include:[
            {
                model: Friends,
                attributes: []
            },
            {
                model: School,
                attributes: [],
                include: {
                    model: Class,
                    attributes: []
                }
            }
        ],
        where: {
            //If we use this with separate: true or limit is a error 'Unknown Column'
            '$school.class.class_id$': { //This names can see in the server console
                [Op.or]: [class_id_1, class_id_2]
            },
            '$friends.friend_id$': friend_id
        }
    });
    
    const arrayId = [];
    usersId.forEach(user => {
        arrayId.push(user.user_id)
    });
    
    //Here get the data with limit and offset
    const users = await Users.findAndCountAll({
        include:[
            {
                model: Friends,
                separate: true, //For all m:n
            },
            {
                model: School,
                include:{
                    model: Class
                }
            },
        ],
        distinct: true,
        limit,
        offset,
        where: {
            user_id: {
                [Op.in]: arrayId //Get data with WHERE IN
            }
        }
    });
  16. jkuri commented on Oct 4, 2022

    @jkuri

    I also solved this as higuitamartinez suggested, adding a separate query above and then include array of ids as [Op.in] statement in where condition. That is basically something that sequelize should do automatically imho.

  17. HyopeR commented on Oct 26, 2022

    @HyopeR

    This problem still persists. Limit and offset should be supported as a basis. I think pagination should be applied to the result after eager loading has taken place.

  18. ephys commented on Oct 26, 2022

    @ephys
    Member

    I'm working on it but it's going to be a little while before it's ready. I'm redesigning findAll from the ground up to make sure all relevant options interact well with each-other (this is the current draft).

  19. l2ysho commented on Nov 3, 2022

    @l2ysho
    Contributor

    I'm working on it but it's going to be a little while before it's ready. I'm redesigning findAll from the ground up to make sure all relevant options interact well with each-other (this is the current draft).

    well It looks really promising 👍

  20. added theissue type on Mar 9, 2025
  21. removed
    type: bug
    on Mar 9, 2025
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

    P1: importantregressiontopic: limit & offset

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions