Skip to content

include.where missing from subquery filter when using scopes #5465

Closed

Description

@panbanda

I am having some issues joining some tables, here is the situation:

Mysql Tables
tickets
tickets_pools (n:m)
pools

When I do a join on the tickets_pools using the include: [models.Pools] it joins just fine if the tickets_pools table has less than 20 records of relations for a pool to ticket. If it has more than 20, I can't do a { where: [IDS] } if the IDS are falling in the > 20 records.

The code:

      # scope
      pools: function(pools) {
        return {
          distinct: ['Ticket.id'],
          include: [{
            model: this.db.Pool,
            through: this.db.TicketPool,
            where: {
              id: pools
            }
          }]
        };
      }

      # query
      query = query.scope({
        method: ['pools', pools]
      });

The SQL generated by the simple association:

SELECT `Ticket`.*, `Pools`.`id` AS `Pools.id`, ..... 
    FROM (SELECT `Ticket`.`id`, `Ticket`.`parent_id` AS `parentId`, `Ticket`.`creator_id` AS `creatorId`, ....  
    WHERE `Ticket`.`deleted_at` IS NULL AND ( SELECT `tickets_pools`.`ticket_id` 
    FROM `tickets_pools` AS `tickets_pools` 
INNER JOIN `pools` AS `Pool` ON `tickets_pools`.`pool_id` = `Pool`.`id` 
    WHERE (`Ticket`.`id` = `tickets_pools`.`ticket_id`) 
    LIMIT 1 ) IS NOT NULL LIMIT 20) AS `Ticket` 
INNER JOIN (`tickets_pools` AS `Pools.tickets_pools` 
INNER JOIN `pools` AS `Pools` 
    ON `Pools`.`id` = `Pools.tickets_pools`.`pool_id`) 
    ON `Ticket`.`id` = `Pools.tickets_pools`.`ticket_id` 
        AND (`Pools`.`deleted_at` IS NULL AND `Pools`.`id` IN (155, 156));

As you can see above, the IS NOT NULL LIMIT 20 is automatically added. Is there a way to avoid this / do it better, or is it a bug?

On a second note, I can create a separate bug, but the distinct shows only in the COUNT() query and disappears from the actual content query. Thoughts?

Activity

  1. janmeier commented on Feb 21, 2016

    @janmeier
    Member

    Please show model definitions and find / findAll call

  2. mickhansen commented on Feb 22, 2016

    @mickhansen
    Contributor

    Looks like there's an issue with the subquery in the subquery, it's not including the Pools.id IN as it should

  3. panbanda commented on Feb 22, 2016

    @panbanda
    Author

    Here are my model defs, stripped them down for readability:

    // pool.js
    
    module.exports = function(db, DataTypes) {
      var Pool = db.define('Pool', {
        slug: {
          type: DataTypes.STRING,
          allowNull: false
        },
        name: {
          type: DataTypes.STRING,
          allowNull: false
        },
        scope: {
          type: DataTypes.STRING,
          allowNull: false
        }
      }, {
        tableName: 'pools',
        paranoid: true,
        underscored: true,
        timestamps: true,
        freezeTableName: true,
        classMethods: {
          associate: function(m) {
            this.db = m;
    
            m.Pool.belongsToMany(m.Ticket, { through: 'tickets_pools' });
          }
        }
      });
    
      return Pool;
    };
    
    // ticket.js
    
    module.exports = function(db, DataTypes) {
      var Ticket = db.define('Ticket', {
        parentId: {
          type: DataTypes.BIGINT.UNSIGNED,
          allowNull: true,
          field: 'parent_id',
          references: {
            model: 'tickets',
            key: 'id'
          }
        },
        title: {
          type: DataTypes.STRING,
          allowNull: false
        }
      }, {
        tableName: 'tickets',
        paranoid: true,
        underscored: true,
        timestamps: true,
        freezeTableName: true,
        classMethods: {
          associate: function(m) {
            this.db = m;
    
            m.Ticket.belongsToMany(m.Pool, { through: 'tickets_pools' });
          }
        },
        scopes: {
          pools: function(pools) {
            return {
              distinct: ['Ticket.id'],
              include: [{
                model: this.db.Pool,
                through: this.db.TicketPool,
                where: {
                  id: pools
                }
              }]
            };
          }
        }
      });
    
      return Ticket;
    };

    Here is the find function:

    var query = models.Ticket;
    
                query = query.scope({
                  method: ['pools', pools]
                });
    
              query.findAndCountAll({
                limit: req.paginate.perPage,
                offset: req.paginate.offset,
                include: [
                  { model: models.User, as: 'Creator', foreignKey: 'creator_id' },
                  { model: models.User, as: 'Assignee', foreignKey: 'assignee_id' }
                ]
              }).then(function(data) {
                callback(null, data);
              }).catch(callback);
  4. panbanda commented on Feb 22, 2016

    @panbanda
    Author

    @mickhansen Is there something I am missing to maybe figure out where its adding LIMIT to the subquery?

  5. mickhansen commented on Feb 23, 2016

    @mickhansen
    Contributor

    It adds a limit to the subquery in cases where the limit would be affected by the cartesian product - That is expected.

    The issue here looks like the subquery in the subquery is not getting a correct WHERE statement and there for not doing correct filtering.

  6. added
    type: bug
    on Feb 23, 2016
  7. changed the title [-]Join table includes LIMIT on queries with IN[/-] [+]include.where missing from subquery filter when using scopes[/+] on Feb 23, 2016
  8. panbanda commented on May 16, 2016

    @panbanda
    Author

    I ran into this again using a different join table so I'll include this example as well. I have the following tables: assets, assets_tags, and tags and I am trying to find an asset that has the given tags (from an array). So here is some relevant model information:

    // Scope inside of Assets (passing an array of slug / ids)
    tags: function (tags) {
      return {
        include: [{
          model: this.db.Tag,
          limit: null,
          where: {
            $or: [
              { id: tags },
              { slug: tags },
            ]
          }
        }]
      };
    }
    
    // Relationships
    m.Asset.belongsToMany(m.Tag, { through: 'assets_tags' });
    
    // Controller querying
    models.Asset.scope([{
      method: ['tags', tags] // tags being String[]
    }]).findAndCountAll({
      limit: req.paginate.perPage,
      offset: req.paginate.offset
    }).then(function (data) {
      // ...
    }).catch(callback);

    This produces this SQL:

    SELECT `Asset`.*, `Tags`.`id` AS `Tags.id`, ... FROM (SELECT `Asset`.`id`, `Asset`.`user_id` AS `userId`, ... WHERE `Asset`.`deleted_at` IS NULL AND ( SELECT `assets_tags`.`tag_id` FROM `assets_tags` AS `assets_tags` INNER JOIN `tags` AS `Tag` ON `assets_tags`.`tag_id` = `Tag`.`id` WHERE (`Asset`.`id` = `assets_tags`.`asset_id`) LIMIT 1 ) IS NOT NULL LIMIT 0, 20) AS `Asset` INNER JOIN (`assets_tags` AS `Tags.assets_tags` INNER JOIN `tags` AS `Tags` ON `Tags`.`id` = `Tags.assets_tags`.`tag_id`) ON `Asset`.`id` = `Tags.assets_tags`.`asset_id` AND (`Tags`.`deleted_at` IS NULL AND (`Tags`.`id` IN ('ipsam-nihil-minima') OR `Tags`.`slug` IN ('ipsam-nihil-minima')));

    This SQL is great except for the LIMIT 0, 20 which doesn't allow the record to be found. If I try this SQL right on the DB it works if I remove the LIMIT 0, 20.

    @mickhansen if you wanted to point me in the direction of where I could fix this I would be willing to take a look. Just a complicated system and would love a starting point.

    Thanks,
    Jon

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