Skip to content

fix(query-generator): generate subQueryFilter even for nested joins - #9188

Merged
sushantdhiman merged 1 commit into
sequelize:masterfrom
jharting:fix-9157
Mar 22, 2018
Merged

sushantdhiman merged 1 commit into
sequelize:masterfrom
jharting:fix-9157

Conversation

@jharting

Copy link
Copy Markdown
Contributor

Closes #9157

Please make sure to review and check all of these items:

  • Does npm run test or npm run test-DIALECT pass with this change (including linting)?
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
  • Did you follow the commit message conventions explained in CONTRIBUTING.md?

Description of change

This code introduces generateSubQueryFilter() which builds upon code previously developed in generateThroughJoin() and generateInclude() to guarantee that proper subQueryFilter even in scenarios where multiple levels of duplicating joins are nested in a query that uses LIMIT / OFFSET.

Here's an example:

Consider the following query:

Project.findAll({
  include: [{
    model: this.User,
    required: true,
    include: [{
      model: this.Hobby,
      where: {
        name: 'archery'
      }
    }]
  }],
  order: ['name'],
  limit: 1,
  offset: 1
})

Project --> User and User --> Hobby are many-to-many queries.

For limit and offset to work properly with duplicating joins it is necessary to push the required joins and where clauses down to subQueryFilter. Currently, sequelize produces the following output:

SELECT `Project`.*, `Users`.`name` AS `Users.name`, `Users->user_project`.`createdAt` AS `Users.user_project.createdAt`, `Users->user_project`.`updatedAt` AS `Users.user_project.updatedAt`, `Users->user_project`.`UserName` AS `Users.user_project.UserName`, `Users->user_project`.`ProjectName` AS `Users.user_project.ProjectName`, `Users->Hobbies`.`name` AS `Users.Hobbies.name`, `Users->Hobbies->user_hobby`.`createdAt` AS `Users.Hobbies.user_hobby.createdAt`, `Users->Hobbies->user_hobby`.`updatedAt` AS `Users.Hobbies.user_hobby.updatedAt`, `Users->Hobbies->user_hobby`.`UserName` AS `Users.Hobbies.user_hobby.UserName`, `Users->Hobbies->user_hobby`.`HobbyName` AS `Users.Hobbies.user_hobby.HobbyName` FROM 
(
    SELECT `Project`.`name` FROM `Projects` AS `Project` WHERE (
        SELECT `user_project`.`UserName` FROM `user_project` AS `user_project` INNER JOIN `Users` AS `User` ON `user_project`.`UserName` = `User`.`name` WHERE (`Project`.`name` = `user_project`.`ProjectName`) LIMIT 1 
    ) IS NOT NULL ORDER BY `Project`.`name` LIMIT 1, 1
) AS `Project` INNER JOIN ( `user_project` AS `Users->user_project` INNER JOIN `Users` AS `Users` ON `Users`.`name` = `Users->user_project`.`UserName`) ON `Project`.`name` = `Users->user_project`.`ProjectName` INNER JOIN ( `user_hobby` AS `Users->Hobbies->user_hobby` INNER JOIN `Hobbies` AS `Users->Hobbies` ON `Users->Hobbies`.`name` = `Users->Hobbies->user_hobby`.`HobbyName`) ON `Users`.`name` = `Users->Hobbies->user_hobby`.`UserName` AND `Users->Hobbies`.`name` = 'archery' ORDER BY `Project`.`name`;

Upon closer inspection this is wrong as the subQueryFilter (most nested query) does not join into the required Hobbies table nor does it check for name: 'archery'. As a result a User that is associated with the Project but does not have association with archery Hobby entity may come out of the subQuery. Such user would then be filtered out in the top-most query, resulting in an empty result set.

SQL generated after this patch:

SELECT `Project`.*, `Users`.`name` AS `Users.name`, `Users->user_project`.`createdAt` AS `Users.user_project.createdAt`, `Users->user_project`.`updatedAt` AS `Users.user_project.updatedAt`, `Users->user_project`.`UserName` AS `Users.user_project.UserName`, `Users->user_project`.`ProjectName` AS `Users.user_project.ProjectName`, `Users->Hobbies`.`name` AS `Users.Hobbies.name`, `Users->Hobbies->user_hobby`.`createdAt` AS `Users.Hobbies.user_hobby.createdAt`, `Users->Hobbies->user_hobby`.`updatedAt` AS `Users.Hobbies.user_hobby.updatedAt`, `Users->Hobbies->user_hobby`.`UserName` AS `Users.Hobbies.user_hobby.UserName`, `Users->Hobbies->user_hobby`.`HobbyName` AS `Users.Hobbies.user_hobby.HobbyName` FROM 
(
    SELECT `Project`.`name` FROM `Projects` AS `Project` WHERE ((
        SELECT `user_project`.`UserName` FROM `user_project` AS `user_project` INNER JOIN `Users` AS `User` ON `user_project`.`UserName` = `User`.`name` INNER JOIN ( `user_hobby` AS `User->Hobbies->user_hobby` INNER JOIN `Hobbies` AS `User->Hobbies` ON `User->Hobbies`.`name` = `User->Hobbies->user_hobby`.`HobbyName`) ON `User`.`name` = `User->Hobbies->user_hobby`.`UserName` AND `User->Hobbies`.`name` = 'archery' WHERE (`Project`.`name` = `user_project`.`ProjectName`) LIMIT 1
    ) IS NOT NULL) ORDER BY `Project`.`name` LIMIT 1, 1
) AS `Project` INNER JOIN ( `user_project` AS `Users->user_project` INNER JOIN `Users` AS `Users` ON `Users`.`name` = `Users->user_project`.`UserName`) ON `Project`.`name` = `Users->user_project`.`ProjectName` INNER JOIN ( `user_hobby` AS `Users->Hobbies->user_hobby` INNER JOIN `Hobbies` AS `Users->Hobbies` ON `Users->Hobbies`.`name` = `Users->Hobbies->user_hobby`.`HobbyName`) ON `Users`.`name` = `Users->Hobbies->user_hobby`.`UserName` AND `Users->Hobbies`.`name` = 'archery' ORDER BY `Project`.`name`;

Notice how here the subQueryFilter joins into Hobies table and checks for name=archery.

I tested this patch extensively both in our project and with Sequelize testsuite. However, please review generateSubQueryFilter carefully as may have missed some special cases.

@jharting

Copy link
Copy Markdown
Contributor Author

@sushantdhiman FYI a new PR that supersedes #9165
With SQL samples and test model scoping fixed.

@jharting
jharting force-pushed the fix-9157 branch 2 times, most recently from ca34b53 to 8a1776c Compare March 15, 2018 17:15
@codecov

codecov Bot commented Mar 15, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #9188 into master will increase coverage by 0.02%.
The diff coverage is 100%.

@sushantdhiman sushantdhiman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a few code related changes but fix otherwise looks good to me.

Code is extracted away to its own method so it can be used in two different segments, but still I have not worked with this code segment and would like reviews from other maintainers

: this.escape(attr);
}
if (options.include && attr.indexOf('.') === -1 && addTable) {
if (options.include && !_.isEmpty(options.include) && attr.indexOf('.') === -1 && addTable) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just use !_.isEmpty(options.include) instead of options.include && !_.isEmpty(options.include)

* table to the include table plus everything that's in required transitive closure of the
* given include.
*/
generateSubQueryFilter(include, includeAs, topLevelInfo) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename to _generateSubQueryFilter

* For a given include hierarchy creates a copy of it where only the required includes
* are preserved.
*/
getRequiredClosure(include) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prefix this one with _ as well

@sushantdhiman
sushantdhiman requested a review from a team March 21, 2018 16:21
…d joins (sequelize#9157)

fixes sequelize#9157

This code introduces generateSubQueryFilter() which builds upon code previously found
in generateThroughJoin() and generateInclude() to guarantee that proper subQueryFilter
even in scenarios where multiple levels of duplicating joins are nested in a query that uses
LIMIT / OFFSET.
@jharting

Copy link
Copy Markdown
Contributor Author

@sushantdhiman thanks for feedback. I updated the PR.

@sushantdhiman

Copy link
Copy Markdown
Contributor

@jharting Looks like this can fix #7344 , which got $200 bounty

@Alexsey @jamiesoncj Can you verify this, if this PR solves that issue you may award that bounty to @jharting

@Alexsey

Alexsey commented Mar 22, 2018

Copy link
Copy Markdown
Contributor

@sunshinewyin I think after this PR would get released we can write about it in both #7344 and #3007 and ask everyone for the feedback. If everything would work fine for a week - I'll be happy to verify it on the bountysource in favor of @jharting. @jamiesoncj what do you think about that?

@sushantdhiman

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 4.37.4 🎉

The release is available on:

Your semantic-release bot 📦🚀

@dlferro

dlferro commented Mar 25, 2018 •

Copy link
Copy Markdown

This appears to have resolved my issue, however I'm experiencing fairly large query times.

  const { count: total, rows: posts } = await Post.findAndCountAll({
    distinct: true,
    col: 'post.id',
    attributes: ['id', 'title', 'description', 'slug', 'createdAt', 'updatedAt', 'authorId'],
    include: [ 
      { model: models.Collection, attributes: ['id'], required: false },
      { model: models.User, as: 'author', attributes: ['id', 'firstName', 'lastName', 'myTeam', 'picture'] } ] },
      { model: models.Tag, where: { id: { [Op.in]: ids } }, attributes: [], through: { attributes: [] } }
    ],
    where: {
      status: {
        [sequelize.Op.or]: [STATUS.ARCHIVED, STATUS.PUBLISHED]
      }
    },
    order: [['updatedAt', 'desc']]
    limit: 10,
    offset: 0
  });

In this case, Collection and Tag are n:m polymorphic relationships.

Post.belongsToMany(models.Tag, { through: { model: models.ItemTag, unique: false, scope: { taggable: 'post' } }, foreignKey: 'taggableId', constraints: false });
Post.belongsToMany(models.Collection, { through: { model: models.CollectionItem, unique: false, scope: { collectable: 'post' } }, foreignKey: 'collectableId', constraints: false });

Which creates the following query

SELECT
  "post".*,
  "tags -> item_tag"."id" AS "tags.item_tag.id",
  "tags -> item_tag"."tagId" AS "tags.item_tag.tagId",
  "tags -> item_tag"."taggable" AS "tags.item_tag.taggable",
  "tags -> item_tag"."taggableId" AS "tags.item_tag.taggableId",
  "tags -> item_tag"."createdAt" AS "tags.item_tag.createdAt",
  "tags -> item_tag"."updatedAt" AS "tags.item_tag.updatedAt",
  "tags -> item_tag"."industryId" AS "tags.item_tag.industryId",
  "collections"."id" AS "collections.id",
  "collections -> collection_item"."id" AS "collections.collection_item.id",
  "collections -> collection_item"."collectionId" AS "collections.collection_item.collectionId",
  "collections -> collection_item"."collectable" AS "collections.collection_item.collectable",
  "collections -> collection_item"."collectableId" AS "collections.collection_item.collectableId",
  "collections -> collection_item"."createdAt" AS "collections.collection_item.createdAt",
  "collections -> collection_item"."updatedAt" AS "collections.collection_item.updatedAt",
  "author"."id" AS "author.id",
  "author"."firstName" AS "author.firstName",
  "author"."lastName" AS "author.lastName",
  "author"."myTeam" AS "author.myTeam",
  "author"."picture" AS "author.picture" 
FROM
  (
    SELECT
      "post"."id",
      "post"."title",
      "post"."description",
      "post"."slug",
      "post"."createdAt",
      "post"."updatedAt",
      "post"."authorId" 
    FROM
      "posts" AS "post" 
    WHERE
      (
("post"."deletedAt" > '2018-03-25 00:01:27.226 +00:00' 
        OR "post"."deletedAt" IS NULL) 
        AND 
        (
          "post"."status" = 'Archived' 
          OR "post"."status" = 'Published'
        )
      )
      AND 
      (
        SELECT
          "item_tag"."id" 
        FROM
          "item_tags" AS "item_tag" 
          INNER JOIN
            "tags" AS "tag" 
            ON "item_tag"."tagId" = "tag"."id" 
            AND "tag"."id" IN 
            (
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>',
              '<guid>'
            )
        WHERE
          (
            "post"."id" = "item_tag"."taggableId" 
            AND "item_tag"."taggable" = 'post'
          )
          LIMIT 1 
      )
      IS NOT NULL 
    ORDER BY
      "post"."updatedAt" DESC LIMIT 10 OFFSET 0
  )
  AS "post" 
  INNER JOIN
    (
      "item_tags" AS "tags -> item_tag" 
      INNER JOIN
        "tags" AS "tags" 
        ON "tags"."id" = "tags -> item_tag"."tagId" 
        AND "tags -> item_tag"."taggable" = 'post'
    )
    ON "post"."id" = "tags -> item_tag"."taggableId" 
    AND "tags"."id" IN 
    (
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>',
      '<guid>'
    )
  LEFT OUTER JOIN
    (
      "collection_items" AS "collections -> collection_item" 
      INNER JOIN
        "collections" AS "collections" 
        ON "collections"."id" = "collections -> collection_item"."collectionId" 
        AND "collections -> collection_item"."collectable" = 'post'
    )
    ON "post"."id" = "collections -> collection_item"."collectableId" 
    AND 
    (
      "collections"."deletedAt" > '2018-03-25 00:01:27.226 +00:00' 
      OR "collections"."deletedAt" IS NULL
    )
  LEFT OUTER JOIN
    "users" AS "author" 
    ON "post"."authorId" = "author"."id" 
ORDER BY
  "post"."updatedAt" DESC;

@janmeier

janmeier commented Mar 26, 2018 •

Copy link
Copy Markdown
Member

@DanFerro That query actually looks pretty reasonable to me - Given what input you've provided (there's a lot to take into account, so it's a complicated query). If you upgraded from v3 or an old v4 you might also be affected by this part: ("post"."deletedAt" > '2018-03-25 00:01:27.226 +00:00' OR "post"."deletedAt" IS NULL) - which may mean that the query is not hitting the index it should. See #8496.

Can you do an EXPLAIN ANALYZE on the query to see what's slowing it down?

You might get better results by doing separate find and count queries - Some of the joins could be trimmed of the count querying, making it faster.

You might also write the tag part as raw SQL - That would probably prevent the need for a subquery:

where: {
  ....
  db.literal(`EXISTS (
SELECT 1
FROM item_tag
WHERE "post"."id" = "item_tag"."taggableId" 
  AND "item_tag"."taggable" = 'post'
  AND item_tag."tagId" IN (SELECT id FROM tag WHERE ...)
)`)
}

@rusekr

rusekr commented Mar 28, 2018

Copy link
Copy Markdown

REGRESSION: This PR has great job for its purpose but breaks findOne filter by association result as described in #9228

@chris-jamieson

Copy link
Copy Markdown

Just want to add my thanks to @jharting for this PR. The fix looks like it is working fine in production for me. So feel free to claim the bounty for the fix (assuming @Alexsey agrees?)

@Alexsey

Alexsey commented Apr 9, 2018

Copy link
Copy Markdown
Contributor

@jamiesoncj it has been only 3 days since the fix for regression #9273 has been merged, and it was Friday. I think we should wait for a few working days to be sure that everything is finally fine

@chris-jamieson

Copy link
Copy Markdown

👍 @Alexsey thanks - sounds good to me. Happy to let you decide once you're happy.

@sushantdhiman

sushantdhiman commented Apr 9, 2018 •

Copy link
Copy Markdown
Contributor

@Alexsey FYI regression was fixed 11 days ago by #9247, but it's upto you :)

@Alexsey

Alexsey commented Apr 9, 2018

Copy link
Copy Markdown
Contributor

@sunshinewyin It was an upstream to regression fix so I thought that they are related. Now I see that they aren't, at least not directly. So I agree with @jamiesoncj that we should allow the reward rightaway. @jharting I'm sorry I didn't rise this question in a week after #9247 was merged. I have never claimed a bounty but I think you should go throught the link that @jamiesoncj has provided and press the "Claim Bounty" button. Thank you for this fix - you have killed a giant here :)

@jharting

Copy link
Copy Markdown
Contributor Author

Glad to hear the fix works and helped others. I submitted the bounty claim. If it gets accepted I intend to donate the full bounty to the Sequelize team.

@Wrufesh

Wrufesh commented Apr 17, 2018 •

Copy link
Copy Markdown

I still cannot get the correct result.
My query is as follow:

db.Call.findAndCountAll(
    {
      where: queryObj,
      include: {
        model: db.User,
        as: 'staff',
        attributes: ['fullName', 'id']
      },
      limit: req.query.limit,
      offset: req.skip
    }
  )
    .then(results => {
      const itemCount = results.count;
      const pageCount = Math.ceil(results.count / req.query.limit);
      res.status(200).json({
        results: results.rows,
        pageCount,
        itemCount,
        pages: paginate.getArrayPages(req)(3, pageCount, req.query.page)
      });
    }).catch(err => {
    return res.status(500).json({message: "Error"})
  })

Generated query is:

Executing (default): SELECT count("Call"."id") AS "count" FROM "Calls" AS "Call" LEFT OUTER JOIN "Users" AS "staff" ON "Call"."staffId" = "staff"."id";

Executing (default): SELECT "Call"."id", "Call"."consumerName", "Call"."consumerId", "Call"."start", "Call"."end", "Call"."callStart", "Call"."callEnd", "Call"."recordedVideoFile", "Call"."recordedVideoExtraDetailFile", "Call"."status", "Call"."createdAt", "Call"."updatedAt", "Call"."originId", "Call"."staffId", "staff"."fullName" AS "staff.fullName", "staff"."id" AS "staff.id" FROM "Calls" AS "Call" LEFT OUTER JOIN "Users" AS "staff" ON "Call"."staffId" = "staff"."id" LIMIT 10 OFFSET 0;

Executing (default): SELECT count("Call"."id") AS "count" FROM "Calls" AS "Call" LEFT OUTER JOIN "Users" AS "staff" ON "Call"."staffId" = "staff"."id";

Executing (default): SELECT "Call"."id", "Call"."consumerName", "Call"."consumerId", "Call"."start", "Call"."end", "Call"."callStart", "Call"."callEnd", "Call"."recordedVideoFile", "Call"."recordedVideoExtraDetailFile", "Call"."status", "Call"."createdAt", "Call"."updatedAt", "Call"."originId", "Call"."staffId", "staff"."fullName" AS "staff.fullName", "staff"."id" AS "staff.id" FROM "Calls" AS "Call" LEFT OUTER JOIN "Users" AS "staff" ON "Call"."staffId" = "staff"."id" LIMIT 10 OFFSET 10;

@jharting

Copy link
Copy Markdown
Contributor Author

@Wrufesh this PR fixes subqueries. Your query has subQuery: false which disables subqueries altogether.

@Wrufesh

Wrufesh commented Apr 17, 2018 •

Copy link
Copy Markdown

Sorry to say but still after I remove subQuery: false I get wrong data with limit: 10 and offset: 10.

I have updated code and sql query generated.

@jharting

Copy link
Copy Markdown
Contributor Author

@Wrufesh please create a new issue with description of your tables and what the expected and wrong output looks like

@bbalban

bbalban commented May 2, 2018

Copy link
Copy Markdown

Hello, is the fix available in latest npm version? I pulled npm 4.37.6 and seeing that limit is ignored.

@Vovka19 Vovka19 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m not sure what I need to do. I made a lot of moves. Now I had too many folders and other copies. I cannot collect it together to make database and something visual.

@v1shva

v1shva commented Jun 23, 2018

Copy link
Copy Markdown

This issue is still there, I am getting an error, Unknown column when I am trying to do this.

      context.params.sequelize = {
          raw: false,
          offset: parseInt(query.$skip),
          limit: parseInt(query.$limit),
          include: [{
            model: sequelize.models.class_fees,
            paranoid: true,
            distinct: true,
            where: {
              status: query.status
            },
            include:[{
              model: sequelize.models.classes,
              where: {
                id: query.classId
              },
              attribute:['name']
            }],
          },]
        };
        context.result=  await sequelize.models.student.findAndCountAll(context.params.sequelize);
        console.log(context.result);

I am getting the following error

info: error: student - Method: find: Unknown column 'class_fees.classId' in 'on clause'
error: SequelizeDatabaseError: Unknown column 'class_fees.classId' in 'on clause'
at Query.formatError (\node_modules\sequelize\lib\dialects\mysql\query.js:247:16)
at Query.handler [as onResult] (\node_modules\sequelize\lib\dialects\mysql\query.js:68:23)
at Query.Command.execute \node_modules\mysql2\lib\commands\command.js:30:12)
at Connection.handlePacket (\node_modules\mysql2\lib\connection.js:502:28)
at PacketParser.onPacket (\node_modules\mysql2\lib\connection.js:81:16)
at PacketParser.executeStart (\node_modules\mysql2\lib\packet_parser.js:77:14)
at Socket. (\node_modules\mysql2\lib\connection.js:89:29)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:561:20)

I was able to fix the issue temporarily by using subQuery: false.

@XBeg9

XBeg9 commented Dec 12, 2018

Copy link
Copy Markdown

An ordering of results fixes the issue, but yeah, it reproduces easily:

order: [['id', 'DESC']]

@daxfrost

daxfrost commented Feb 5, 2019

Copy link
Copy Markdown

I am also having a similar problem, I have to to still use subQuery: false

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

limit/offset produces invalid result if included model has where clause