Skip to content

Incorrect SELECT query generation including "LIMIT" clause and "M:N" association with "where" clause returns unexpected results #4716

Closed

Description

@fogine

Hello,

I've come across a bug with query generation which include limiting results with including belongsToMany relation containing WHERE clause.

I made executable script to demonstrate this behavior as they are cases when generated query might return expected result if query and data in database are in specific state.

if you investigate the file the following are queries generated for particular demonstration cases:

"Test 1": Works

    Student.findAndCount({
        offset: 6,
        order: [["id", "DESC"]],
        include: [
            {
                model: Teacher,
                as: 'teachers',
                where: {
                    id: {$in: [3, 2]}
                }
            }
        ]
    });
SELECT "student"."id", "student"."age", "student"."name",
"student"."created_at", "student"."updated_at", "teachers"."id" AS
"teachers.id", "teachers"."age" AS "teachers.age", "teachers"."name" AS
"teachers.name", "teachers"."created_at" AS "teachers.created_at",
"teachers"."updated_at" AS "teachers.updated_at",
"teachers.student_teacher"."id" AS "teachers.student_teacher.id",
"teachers.student_teacher"."teacher_id" AS
"teachers.student_teacher.teacher_id", "teachers.student_teacher"."student_id"
AS "teachers.student_teacher.student_id"
FROM "student" AS "student"
INNER JOIN (
    "student_teacher" AS "teachers.student_teacher"
    INNER JOIN "teacher" AS "teachers"
    ON "teachers"."id" = "teachers.student_teacher"."teacher_id"
)
ON "student"."id"  = "teachers.student_teacher"."student_id"
AND "teachers"."id" IN (3, 2)
ORDER BY "student"."id" DESC OFFSET 6;

"Test 2": Bug - Wrong query generated... but this case returns expected result by "coincidence"

    Student.findAndCount({
        limit: 5,
        offset: 6,
        order: [["id", "DESC"]],
        include: [
            {
                model: Teacher,
                as: 'teachers',
                where: {
                    id: {$in: [3, 2]}
                }
            }
        ]
    });
SELECT "student".*, "teachers"."id" AS "teachers.id", "teachers"."age" AS
"teachers.age", "teachers"."name" AS "teachers.name", "teachers"."created_at"
AS "teachers.created_at", "teachers"."updated_at" AS "teachers.updated_at",
"teachers.student_teacher"."id" AS "teachers.student_teacher.id",
"teachers.student_teacher"."teacher_id" AS
"teachers.student_teacher.teacher_id", "teachers.student_teacher"."student_id"
AS "teachers.student_teacher.student_id"
FROM (
    SELECT "student"."id", "student"."age", "student"."name",
    "student"."created_at", "student"."updated_at"
    FROM "student" AS "student"
    WHERE (
        SELECT "student_teacher"."id"
        FROM "student_teacher" AS "student_teacher"
        INNER JOIN "teacher" AS "teacher"
        ON "student_teacher"."teacher_id" = "teacher"."id"
        WHERE ("student"."id" = "student_teacher"."student_id")
        LIMIT 1
    ) IS NOT NULL
    ORDER BY "student"."id" DESC LIMIT 5 OFFSET 6
) AS "student"
INNER JOIN (
    "student_teacher" AS "teachers.student_teacher"
    INNER JOIN "teacher" AS "teachers"
    ON "teachers"."id" = "teachers.student_teacher"."teacher_id"
)
ON "student"."id" = "teachers.student_teacher"."student_id"
AND "teachers"."id" IN (3, 2)
ORDER BY "student"."id" DESC;

"Test 3": Bug - Wrong query - returns unexpected results

    Student.findAndCount({
        limit: 5,
        offset: 6,
        include: [
            {
                model: Teacher,
                as: 'teachers',
                where: {
                    id: {$in: [3, 2]}
                }
            }
        ]
    });
SELECT "student".*, "teachers"."id" AS "teachers.id", "teachers"."age" AS
"teachers.age", "teachers"."name" AS "teachers.name", "teachers"."created_at"
AS "teachers.created_at", "teachers"."updated_at" AS "teachers.updated_at",
"teachers.student_teacher"."id" AS "teachers.student_teacher.id",
"teachers.student_teacher"."teacher_id" AS
"teachers.student_teacher.teacher_id", "teachers.student_teacher"."student_id"
AS "teachers.student_teacher.student_id"
FROM (
    SELECT "student"."id", "student"."age", "student"."name",
    "student"."created_at", "student"."updated_at"
    FROM "student" AS "student"
    WHERE (
        SELECT "student_teacher"."id"
        FROM "student_teacher" AS "student_teacher"
        INNER JOIN "teacher" AS "teacher"
        ON "student_teacher"."teacher_id" = "teacher"."id"
        WHERE ("student"."id" = "student_teacher"."student_id")
        LIMIT 1
    ) IS NOT NULL LIMIT 5 OFFSET 6
) AS "student"
INNER JOIN (
    "student_teacher" AS "teachers.student_teacher"
    INNER JOIN "teacher" AS "teachers"
    ON "teachers"."id" = "teachers.student_teacher"."teacher_id"
)
ON "student"."id" = "teachers.student_teacher"."student_id"
AND "teachers"."id" IN (3, 2);

As I look at queries it seems it would be great if generated queries for test cases 2 and 3 would be the same as in 1 with LIMIT included at the end of query, wouldn't it?

Thank you for your work!

Activity

  1. mickhansen commented on Oct 23, 2015

    @mickhansen
    Contributor

    Does it work findAll rather than findAndCount?
    The limit is the culprit here since it triggers subquery logic.

  2. fogine commented on Oct 23, 2015

    @fogine
    ContributorAuthor

    No, It seems it behaves the same way. Is it working for you with findAll?
    It rather looks like that LIMIT is causing subquery generation...

  3. mickhansen commented on Oct 23, 2015

    @mickhansen
    Contributor

    Haven't tested it yet, just wanted to make sure that the method was not a factor.
    Unfortunately limit doesn't work in all cases with includes because of cartesian products.

  4. fogine commented on Oct 23, 2015

    @fogine
    ContributorAuthor

    well, do you mean it might be problem to generate appropriate sql query in this case? Could you be more specific in which cases with cross-joins it's not currently possible, please?
    It really looks like the problem is caused by LIMIT here. In this case use of subquery is not neccesary, is it?

  5. mickhansen commented on Oct 25, 2015

    @mickhansen
    Contributor

    The limit is necessary when you include an association that result in a cartesian product, which would be the case for a belongsToMany association.

    limit for includes is not supported in all cases as i said, but it would. In this case it looks like the where statement is missing from the nested filter subquery, which is highly odd.

    It would be helpfull if you could provide a SSCCE - Preferably as a PR with an integration test.

  6. fogine commented on Oct 25, 2015

    @fogine
    ContributorAuthor

    I'm not sure you've noticed that I've made a SSCCE:
    https://gist.github.com/fogine/acb637ec1b4ab2ef5d81
    I think it should demonstrate the problem pretty well.
    I can make PR with an integration test though.

  7. added
    type: bug
    on Oct 26, 2015
  8. self-assigned this
    on Oct 26, 2015
  9. mickhansen commented on Oct 26, 2015

    @mickhansen
    Contributor

    @fogine Ah no i missed that. That looks pretty copy/pasteable into a test, so no need to provide a PR.

  10. markdboyd commented on Jan 6, 2016

    @markdboyd

    Any progress here? I'm fairly sure that I'm running into a similar situation, where I'm using limit and a join that I need isn't being provided on the subquery

  11. mickhansen commented on Jan 7, 2016

    @mickhansen
    Contributor

    @markdboyd Not much, overall we're working on simplifying this by running associations in seperate queries.
    However if you could provide a SSCCE for your case i'd be happy to take a look.

  12. markdboyd commented on Jan 7, 2016

    @markdboyd

    Basically, my problem is that I have a where clause on the subquery (which is triggered by a limit), but it it isn't working because it references a table that is joined outside the subquery. I'm not sure how much detail to provide for a SSCCE, but here goes: https://gist.github.com/markdboyd/cf19937dec07b1af2bd7

    It also seems like #4737 is a related issue here.

  13. mickhansen commented on Jan 8, 2016

    @mickhansen
    Contributor

    Because of your custom where that is played inside the subquery, don't have a workaround for a planned fix for that at the moment.

  14. markdboyd commented on Jan 8, 2016

    @markdboyd

    Just so I understand, are you saying that the custom where condition itself is the problem? I was under the impression the problem was the table that needs to be joined for the custom where condition (in the subquery) is only joined on the outer query, not the subquery.

  15. mickhansen commented on Jan 8, 2016

    @mickhansen
    Contributor

    It gets places inside the subquery cause we wouldn't know not to.

  16. dmgallardo commented on Mar 10, 2016

    @dmgallardo

    Hi, Im having the same issue.
    Any progress on this topic.

  17. ybrodsky commented on Aug 3, 2016

    @ybrodsky

    Same issue here. Any progress or workaround?

    Is there any reason for those subqueries being there?

  18. janmeier commented on Aug 3, 2016

    @janmeier
    Member

    @demege @ybrodsky More test cases are always welcome

  19. ybrodsky commented on Aug 3, 2016

    @ybrodsky

    @janmeier my case is exactly the same as @fogine first post.

    I have noticed that adding the option subQuery: false seems to produce the desired mysql query. Is there any downside of using this?

  20. janmeier commented on Aug 3, 2016

    @janmeier
    Member

    When adding offset and limit to a duplicating (hasMany or belongsToMany relations) you need a subquery - otherwise the offset and limit is applied to the cartesian product, and not the the main table

  21. ybrodsky commented on Aug 3, 2016

    @ybrodsky

    Shouldnt it be applied to the cartesian product if it's an inner join?

    My case:

    Oportunity belongsToMany Client (through ClientOportunity)
    Oportunity belongsTo User
    Client belongsToMany Oportunity (through ClientOportunity)
    
    Oportunity.findAll({
      status: {'$in': [1, 2, 0]}
      attributes: ['blablabla'],
      offset: 0,
      limit: 10,
      include: [
        {
          model: Client,
          as: 'client',
          attributes: ['blablabla']
        }
        {
          model: User,
          as: 'user',
          attributes: ['blablabla']
        }
      ]
    })
    
    

    Produced query:

    SELECT `Oportunity`.*, `user`.`id` AS `user.id`, `user`.`name` AS `user.name`,
     `user`.`surname` AS `user.surname`, `client`.`id` AS `client.id`, 
    `client`.`name` AS `client.name`, `client`.`surname` AS `client.surname`, 
    `client.ClientOportunity`.`id` AS `client.ClientOportunity.id`, 
    `client.ClientOportunity`.`client_id` AS `client.ClientOportunity.client_id`, 
    `client.ClientOportunity`.`oportunity_id` AS `client.ClientOportunity.oportunity_id`, 
    `client.ClientOportunity`.`createdAt` AS `client.ClientOportunity.createdAt`, 
    `client.ClientOportunity`.`updatedAt` AS `client.ClientOportunity.updatedAt` 
    FROM (
      SELECT `Oportunity`.`id`, `Oportunity`.`name`, `Oportunity`.`status`, 
    `Oportunity`.`createdAt`, `Oportunity`.`user_id` FROM `oportunity` AS `Oportunity` 
      WHERE `Oportunity`.`status` IN (0, 1, 2) LIMIT 0, 10
    ) AS `Oportunity` 
    LEFT OUTER JOIN `user` AS `user` ON `Oportunity`.`user_id` = `user`.`id` 
    LEFT OUTER JOIN (
      `client_oportunity` AS `client.ClientOportunity` 
      INNER JOIN `client` AS `client` ON `client`.`id` = `client.ClientOportunity`.`client_id`
    ) ON `Oportunity`.`id` = `client.ClientOportunity`.`oportunity_id` 
    ORDER BY id DESC
    
  22. ybrodsky commented on Aug 4, 2016

    @ybrodsky

    I have tested further and noted two things:

    • The resulting query doesn't have the ORDER clause inside the subquery. So the results in the subquery are messed up to start with.
    • If you have conditions for your joined models, the conditions are not inside the subquery neither. So again the results in the subquery are messed up.

    Testing with raw mysql, if you add the order clause inside the subquery and (if any) the join conditions inside the subquery, the results are as expected.

    Example query which returns expected results when using limit and a condition for the joined model.

    SELECT `Oportunity`.*, `user`.`id` AS `user.id`, `user`.`name` AS `user.name`, `user`.`surname` AS `user.surname`,
    `client`.`id` AS `client.id`, `client`.`name` AS `client.name`, `client`.`surname` AS `client.surname`,
    `client.ClientOportunity`.`id` AS `client.ClientOportunity.id`, `client.ClientOportunity`.`client_id` AS
    `client.ClientOportunity.client_id`, `client.ClientOportunity`.`oportunity_id` AS `client.ClientOportunity.oportunity_id`,
    `client.ClientOportunity`.`createdAt` AS `client.ClientOportunity.createdAt`, `client.ClientOportunity`.
    `updatedAt` AS `client.ClientOportunity.updatedAt`
    
    FROM (
      SELECT `Oportunity`.`id`, `Oportunity`.`name`, `Oportunity`.`status`, `Oportunity`.`createdAt`, `Oportunity`.`user_id`
      FROM `oportunity` AS `Oportunity`
      WHERE `Oportunity`.`status` IN (0, 1, 2)
      AND (
        SELECT `ClientOportunity`.`id`
        FROM `client_oportunity` AS `ClientOportunity`
        INNER JOIN `client` AS `Client` ON `ClientOportunity`.`client_id` = `Client`.`id`
          AND (`Client`.`email` LIKE '%cacalano%' OR `Client`.`name` LIKE '%cacalano%' OR `Client`.`surname` LIKE '%cacalano%')
        WHERE (`Oportunity`.`id` = `ClientOportunity`.`oportunity_id`) LIMIT 1
      ) IS NOT NULL ORDER BY id DESC LIMIT 0, 10
    ) AS `Oportunity`
    LEFT OUTER JOIN `user` AS `user` ON `Oportunity`.`user_id` = `user`.`id`
    INNER JOIN (`client_oportunity` AS `client.ClientOportunity`
      INNER JOIN `client` AS `client` ON `client`.`id` = `client.ClientOportunity`.`client_id`
    ) ON `Oportunity`.`id` = `client.ClientOportunity`.`oportunity_id`
    
    AND (`client`.`email` LIKE '%cacalano%' OR `client`.`name` LIKE '%cacalano%' OR `client`.`surname` LIKE '%cacalano%')
    ORDER BY Oportunity.id DESC
    
  23. Alexsey commented on Jun 9, 2017

    @Alexsey
    Contributor

    My issue #7344 is looks like related. And adding of subQuery: false is looks like a fix for my case as well

  24. stale commented on Aug 12, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  25. brianemoore57 commented on Jan 8, 2019

    @brianemoore57

    I ran into this because of the deletedAt issue. I want to use userName column in my User table, and as a soft-delete, preserve the option to re-use the userName if first record deleted. I had to change to a exclude constraint to get this behaviour. Then, sequelize.model inserted this options.limit since logic adds it unless a Pk, or a unique column. It doesnt see my exclude constraint as a unique. I know the deletedAt is changed to a boolean flag, so I will be able to use a regular multi-column unique constraint. However, this logic here seems to just generate wrong SQL, at least for postgresql, limiting its use.

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

    staletype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions