Skip to content

findAndCountAll with LEFT OUTER JOIN #2467

Closed

Description

@ThePoloQ

Hi,

Sequelize 1.7 but maybe 2.0

When I use findAndCountAll, the count query include LEFT OUTER JOIN.
It's a problem for pagination.

Illustration of count query when I ask for 'all tasks ended' (tasks hasMany subtasks)

SELECT COUNT(`Task`.`id`) as `count` FROM `Tasks`
INNER JOIN `Users` AS `Responsible` ON `Responsible`.`id` = `Tasks`.`UserId`
INNER JOIN `Applications` AS `Application`
    ON `Application`.`id` = `Tasks`.`ApplicationId` AND `Application`.`id` IN ('7','8','9','14','15')
LEFT OUTER JOIN `Subtasks` AS `Subtasks` ON `Tasks`.`id` = `Subtasks`.`TaskId`
INNER JOIN `States` AS `State` ON `State`.`id` = `Tasks`.`StateId` AND `State`.`ended`=true

LEFT OUTER JOIN should not be here

Maybe you already know the problem ?

Thanks

Activity

  1. janmeier commented on Oct 23, 2014

    @janmeier
    Member

    Do you mean you are using sequelize 1.4? We have no form of support for that, at all and I'm pretty sure findAndCountAll is not in there :). Do you mean 1.7?

    Please shows your models, associations and the code to generate the query you show.

  2. ThePoloQ commented on Oct 23, 2014

    @ThePoloQ
    Author

    Yes sorry I meant 1.7 ... problem of my big finger

    The model

    var User = myDB.define('User', {
        username: {type: Sequelize.STRING,, unique: true, allowNull: false},
        passwordHASH: {type: Sequelize.STRING, allowNull: false},
        isAdmin: {type: Sequelize.BOOLEAN, defaultValue: false},
      },
      {
        timestamps: false,
      });
    
    var Task = myDB.define('Task', {
        title: {type: Sequelize.STRING, allowNull: false},
        ticket: Sequelize.STRING,
        description: Sequelize.TEXT,
        endedAt: Sequelize.DATE
      },
      {
        timestamps: true,
      }
    );
    
    var Subtask = myDB.define('Subtask', {
      title: {type: Sequelize.STRING, allowNull: false},
      ticket: Sequelize.STRING,
      ended: {type: Sequelize.BOOLEAN, defaultValue: false},
      },
      {
        timestamps: false,
        getterMethods: {
          text: function () {
              return [this.ended ? '[X]' : '[ ]', this.title].join(' ');
          }
        }
      });
    
    var State = myDB.define('State', {
      title: {type: Sequelize.STRING, allowNull: false},
      ended: {type: Sequelize.BOOLEAN, defaultValue: false},
      weight: {type: Sequelize.INTEGER, defaultValue: 0},
      type: {type: Sequelize.STRING, defaultValue: "default"},
      },
      {
        timestamps: false,
      });
    
    var Application = myDB.define('Application', {
      name: {type: Sequelize.STRING, allowNull: false},
      infos: {type: Sequelize.TEXT},
      weight: {type: Sequelize.INTEGER, defaultValue: 0},
      color: {type: Sequelize.STRING, defaultValue: "grey"},
      },
      {
        timestamps: false,
      });
    
    Task.belongsTo(User, { as: 'Responsible' })
    User.hasMany(Task, { as: 'Tasks' })
    
    Task.belongsTo(State, { as: 'State' })
    State.hasMany(Task, { as: 'Tasks' })
    
    Task.belongsTo(Application, { as: 'Application' })
    Application.hasMany(Task, { as: 'Tasks' })
    
    Subtask.belongsTo(Task, { as: 'Task', foreignKey: 'TaskId' })
    Task.hasMany(Subtask, { as: 'Subtasks', foreignKey: 'TaskId' })

    here the function

    exports.getEndedTasks = function(req, res) {
      var options = {
                      include:  [ {model: db.User, as: 'Responsible', attributes: ['username'], required: true},
                                  {model: db.Application, as: 'Application', attributes: ['name'], required: true},
                                  {model: db.Subtask, as: 'Subtasks', attributes: ['ended', 'title']},
                                  {model: db.State, as: 'State', attributes: ['title','type'], where: {ended:  true}, required: true}],
                      offset:   db.limit*(req.params.pageid-1),
                      limit:    db.limit,
                      order:    [ [db.sequelize.fn('unix_timestamp', db.sequelize.col('tasks.endedAt')), 'DESC'],
                                  [db.sequelize.col('Application.nom')],
                                  [db.sequelize.fn('lower',db.sequelize.col('Subtasks.title'))]
                                  ]
                      }
      if (req.user.applications && req.user.applications.length > 0){
        //TODO: change it with a relation ManyToMany and a relation table
        var arrApps = req.user.applications.split(';');
        options.include[1].where = {id: {in: arrApps}};
      }
    
      var params = {};
    
      if (req.params.appid){
        options.where.ApplicationId = parseInt(req.params.appid);
        params.FilterApplicationId = parseInt(req.params.appid);
      }
      db.Task.findAndCountAll(options).success(function(result) {
          var paginate = {  nbpages: Math.ceil(result.count/db.limit),
                            current: parseInt(req.params.pageid),
                            perpage: db.limit,
                            total: result.count,
                            };
          if (req.params.appid){
            paginate.url = '/tasks/ended/application/' + req.params.appid + '/page/';
          }else{
            paginate.url = '/tasks/ended/page/';
          }
    
          params.paginate = paginate;
          params.tasks = result.rows;
          params.tasks.forEach(function(task){
            var ret = getSubtasksHtml(task);
            if (ret){
              task.Subtasks.html = ret.html;
              task.Subtasks.ended = ret.ended;
            }
          });
          res.render('tasks/ended', params);
      }).error(function(err){
         res.send(500, err.toString());
      });
    }

    It is a problem because it is counting with subtasks
    So a task can be counting many times (number of subtask associated)

  3. janmeier commented on Oct 23, 2014

    @janmeier
    Member

    Can you pretty pretty please provide a smaller example :). And one where I don't have to guess what's inside req.params ...

  4. mickhansen commented on Oct 23, 2014

    @mickhansen
    Contributor

    There's a general bug with findAndCountAll and include.
    We need to change the logic so that count only gets the set of nested includes that are required.

  5. mickhansen commented on Dec 3, 2014

    @mickhansen
    Contributor

    Likely fixed by 82403cf - else please open new issue with specific test case.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions