Skip to content

Empty rows returning, when n:m assotiation and limit condition, but count is right #11313

Open

Description

@MegaFAX

What are you doing?

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('postgres://postgres@localhost:5432/testdb', { logging: false });

const User = sequelize.define('User', {
    id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: sequelize.fn('gen_random_uuid')
    },
    login: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: false // just for demo
    }
}, {
    timestamps: true,
    paranoid: false,
    tableName: 'users',
    freezeTableName: true,
    underscored: true,
    modelName: 'Users',
    scopes: {
        page(index = 1, limit = 10) {
            let $return = {
                offset: 0,
                limit: 10
            };

            if (limit !== Infinity && !isNaN(index) && !isNaN(limit)) {
                $return = {
                    offset: (index - 1) * limit,
                    limit
                };
            }

            return $return;
        }
    }
});

const ParentChild = sequelize.define('ParentChild', {}, {
    timestamps: false,
    paranoid: false,
    tableName: 'users_parent_child',
    freezeTableName: true,
    underscored: true,
    modelName: 'ParentChild'
});

User.belongsToMany(User, {
    hooks: false,
    as: {
        singular: 'Parent',
        plural: 'Parents'
    },
    through: {
        model: ParentChild,
        unique: true
    },
    foreignKey: 'child_id',
    otherKey: 'parent_id'
});
User.belongsToMany(User, {
    hooks: false,
    as: {
        singular: 'Child',
        plural: 'Children'
    },
    through: {
        model: ParentChild,
        unique: true
    },
    foreignKey: 'parent_id',
    otherKey: 'child_id'
});

let someParent = '';

sequelize.query(`CREATE EXTENSION IF NOT EXISTS "pgcrypto"`)
    .then(() => sequelize.sync({ force: true }))
    .then(() => Promise.all([
        User.bulkCreate([...Array(10).keys()].map(() => ({login: 'c'}))),
        User.bulkCreate([...Array(10).keys()].map(() => ({login: 'p'})))
    ])) // generate parents and children
    .then(() => {
        return Promise.all([
            User.findAll({where: {login: 'c'}}),
            User.findAll({where: {login: 'p'}})
        ]);
    }) // find them
    .then(([children, parents]) => {
        someParent = parents[0].id;

        return Promise.all(children.map(
            (child, i) => child.setParents([
                parents[i],
                parents[(i + 1) % 10]
            ])
        ));
    }) // set every child two parents
    .then(() => {
        return Promise.all([
            User.scope({method: ['page', 1, 5]})
                .findAndCountAll({
                    where: {
                        login: 'c'
                    },
                    include: [
                        {
                            association: 'Parents',
                            required: true,
                            attributes: [],
                            where: {
                                id: someParent
                            }
                        }
                    ]
                }),
            User.findAndCountAll({
                where: {
                    login: 'c'
                },
                include: [
                    {
                        association: 'Parents',
                        required: true,
                        attributes: [],
                        where: {
                            id: someParent
                        }
                    }
                ]
            })
        ]);
    }) // try to find children who has parent with id "someParent" and count them
    .then(res => console.log(JSON.stringify(res, null, 4)))
    .finally(() => sequelize.close());

To Reproduce
Steps to reproduce the behavior:

  1. Run the following

What do you expect to happen?

[ { count: 2, rows: [ [User], [User] ] },
  { count: 2, rows: [ [User], [User] ] } ]

What is actually happening?

[ { count: 2, rows: [] },
  { count: 2, rows: [ [User], [User] ] } ]

Environment

Dialect:

  • mysql
  • postgres
  • sqlite
  • mssql
  • any
    Dialect library (pg) version: 7.12.1
    Database version: Postgres 10
    Sequelize version: 5.13.1
    Node Version: 10.16.0
    OS: Win7x64
    Tested with latest release:
  • No
  • Yes

Activity

  1. papb commented on Aug 13, 2019

    @papb
    Member

    Thanks for the great SSCCE 👍! I was able to reproduce.

    Note: I made very minor edits to your SSCCE to make it even better (but it was already great!)

  2. added
    dialect: postgres
    Great SSCCE
    status: understood
    type: bug
    on Aug 13, 2019
  3. papb commented on Aug 13, 2019

    @papb
    Member

    Do you think this could happen with another dialect other than postgres? Of course 'gen_random_uuid would not be used. Can you try to come up with another SSCCE for other dialects?

  4. MegaFAX commented on Aug 13, 2019

    @MegaFAX
    Author

    Thx, I tried to do this SSCCE. I think this dont depend on dialect, because this bug with self multi association. It generate SQL that has multiple "AS" and db dont know which one need to use. SQL, that genered with "wrong" query:

    SELECT "User".*,
           "Parents->ParentChild"."child_id"  AS "Parents.ParentChild.child_id",
           "Parents->ParentChild"."parent_id" AS "Parents.ParentChild.parent_id"
    FROM (SELECT "User"."id", "User"."login", "User"."created_at" AS "createdAt", "User"."updated_at" AS "updatedAt"
          FROM "users" AS "User"
          WHERE "User"."login" = 'c'
            AND (SELECT "ParentChild"."child_id"
                 FROM "users_parent_child" AS "ParentChild"
                          INNER JOIN "users" AS "User" ON "ParentChild"."parent_id" = "User"."id" AND
                                                          "User"."id" = 'bbaa9fcc-b5ee-416d-9d97-a243a5b67e93'
                 WHERE ("User"."id" = "ParentChild"."child_id")
                 LIMIT 1) IS NOT NULL
          LIMIT 5 OFFSET 0) AS "User"
             INNER JOIN ( "users_parent_child" AS "Parents->ParentChild" INNER JOIN "users" AS "Parents" ON "Parents"."id" = "Parents->ParentChild"."parent_id")
                        ON "User"."id" = "Parents->ParentChild"."child_id" AND
                           "Parents"."id" = 'bbaa9fcc-b5ee-416d-9d97-a243a5b67e93';

    but when I change some

    SELECT "User".*,
           "Parents->ParentChild"."child_id"  AS "Parents.ParentChild.child_id",
           "Parents->ParentChild"."parent_id" AS "Parents.ParentChild.parent_id"
    FROM (SELECT "User"."id", "User"."login", "User"."created_at" AS "createdAt", "User"."updated_at" AS "updatedAt"
          FROM "users" AS "User"
          WHERE "User"."login" = 'c'
            AND (SELECT "ParentChild"."child_id"
                 FROM "users_parent_child" AS "ParentChild"
                          INNER JOIN "users" AS "User1" ON "ParentChild"."parent_id" = "User1"."id" AND
                                                          "User1"."id" = 'bbaa9fcc-b5ee-416d-9d97-a243a5b67e93'
                 WHERE ("User"."id" = "ParentChild"."child_id") -- in this subquery
                 LIMIT 1) IS NOT NULL
          LIMIT 5 OFFSET 0) AS "User"
             INNER JOIN ( "users_parent_child" AS "Parents->ParentChild" INNER JOIN "users" AS "Parents" ON "Parents"."id" = "Parents->ParentChild"."parent_id")
                        ON "User"."id" = "Parents->ParentChild"."child_id" AND
                           "Parents"."id" = 'bbaa9fcc-b5ee-416d-9d97-a243a5b67e93';

    it's right, or, as I think, it must be something like

    SELECT "User"."id",
           "User"."login",
           "User"."created_at"                AS "createdAt",
           "User"."updated_at"                AS "updatedAt",
           "Parents->ParentChild"."child_id"  AS "Parents.ParentChild.child_id",
           "Parents->ParentChild"."parent_id" AS "Parents.ParentChild.parent_id"
    FROM "users" AS "User"
             INNER JOIN ( "users_parent_child" AS "Parents->ParentChild" INNER JOIN "users" AS "Parents" ON "Parents"."id" = "Parents->ParentChild"."parent_id")
                        ON "User"."id" = "Parents->ParentChild"."child_id" AND
                           "Parents"."id" = 'bbaa9fcc-b5ee-416d-9d97-a243a5b67e93'
    WHERE "User"."login" = 'c'
    LIMIT 5
    OFFSET 0;
  5. added and removed
    dialect: postgres
    on Aug 13, 2019
  6. mjy78 commented on Sep 22, 2019

    @mjy78
    Contributor

    I'm seeing a similar symptom where count is correct, but rows are empty, when using limit/offset (also Postgres dialect). In my case I've enabled query logging, and can actually see the rows are being returned from the query in both cases (with and without limit/offset).

    I've dug deeper and it looks like the call to AbstractQuery._groupJoinData() inside of handleSelectQuery() is wiping out the result set after the data is returned.

    Looking closer at the data that is being fed into this function, when limit/offset is in use, it looks like the primary key of the parent model is included in each object twice, one with a key of "_id" (the field name as defined in the model definition) and then also as "installation_request_id" (which is the db column name for the pk field).

    I'll keep digging further into this function, but just mentioning it here in case it is of any consequence.

  7. MegaFAX commented on Sep 22, 2019

    @MegaFAX
    Author

    Any forecast?

  8. papb commented on Oct 4, 2019

    @papb
    Member

    Hi @mjy78 thanks for the post, hopefully you can dig further indeed!

    @MegaFAX I'm sorry but I am super busy already, I can't help right now...

  9. hoan006 commented on Dec 5, 2019

    @hoan006

    I suppose the combination of limit and belongsToMany (in my situation hasMany) relationship confused the _groupJoinData() as @mjy78 observed. I have to do it the Rails/Django way to workaround this issue:

    • findAndCountAll as before, but removing all hasMany include associations. Only return id attributes.
    • findAll using filtered ids above, removing limit, offset parameters.
  10. theRichu commented on Jan 28, 2020

    @theRichu

    I'm struggle with this problem, any progress?

  11. 9 remaining items

  12. github-actions commented on Nov 8, 2021

    @github-actions
  13. testn commented on Dec 13, 2021

    @testn
  14. oliveiragit commented on Dec 14, 2021

    @oliveiragit
  15. BabichTatsiana commented on Sep 22, 2022

    @BabichTatsiana
  16. Lynn93 commented on Nov 8, 2022

    @Lynn93
  17. kieded commented on Nov 22, 2022

    @kieded

    in what version of sequelize was this issue fixed??

  18. ephys commented on Nov 22, 2022

    @ephys
    Member

    It's not, the issue is still open

  19. moisfelix commented on Mar 31, 2023

    @moisfelix

    Nobody founded a good workaround for this issue?

  20. RamadanIbrahem98 commented on Nov 16, 2023

    @RamadanIbrahem98

    I tried a workaround that actually worked for me. I don't think if it's good for everybody.

    And that's by adding subQuery: false

    User.scope({method: ['page', 1, 5]})
    .findAndCountAll({
        where: {
            login: 'c'
        },
        include: [
            {
                association: 'Parents',
                required: true,
                attributes: [],
                where: {
                    id: someParent
                }
            }
        ],
        subQuery: false,
    }),
  21. wangxiaodong commented on Jan 25, 2024

    @wangxiaodong

    i meet the same situation
    using duplicating = false can resolve for me, include[].duplicating,
    inspired by @RamadanIbrahem98

  22. miftakhussalam commented on Sep 20, 2024

    @miftakhussalam

    Hi, I am facing same issue, and I try to do this

    image

    change version sequelize to 6.6.2 and ORM to 6.37.2

    make sure you are uninstall existing sequelize

    then install again with specific version
    npm install -g [email protected]
    npm install [email protected]

    That worked for me.

  23. added theissue type 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

    Great SSCCEstatus: understoodtype: bug

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions