Skip to content

Limit doesn't work as I expect #2886

Closed
Closed

Description

@milushov

Hello, thanks for sequelize, but I stuck with problem:

Here's my code:

models.Product.belongsToMany(models.Category, through: 'CategoriesProducts')
models.Category.belongsToMany(models.Product, through: 'CategoriesProducts')

...

db.Product.findAll(
  order: 'Product.id asc'

  limit: params.limit
  offset: params.offset

  where:
    merchantId: params.merchants,
    price:
      gte: params.price.min
      lte: params.price.max

  include:
    model: db.Category
    where:
      id: params.categories
).then (items) ->
  ...

and it's build next query:

SELECT `Product`.*, 
       `categories`.`id`                            AS `Categories.id`, 
       ...
       `Categories.CategoriesProducts`.`createdat`  AS 
       `Categories.CategoriesProducts.createdAt`, 
       ...
FROM   (SELECT `Product`.`id`, 
               `Product`.`image`, 
                ...
        FROM   `products` AS `Product` 
        WHERE  `Product`.`merchantid` IN ( '1', '2' ) 
               AND `Product`.`price` >= '0' 
               AND `Product`.`price` <= '10000' 
               AND (SELECT `categoriesproducts`.`productid` 
                    FROM   `categoriesproducts` AS `CategoriesProducts` 
                           INNER JOIN `categories` AS `Category` 
                                   ON `categoriesproducts`.`categoryid` = 
                                      `Category`.`id` 
                    WHERE  `Product`.`id` = `categoriesproducts`.`productid` 
                    LIMIT  1) IS NOT NULL 
        LIMIT  0, 12) AS `Product` 
       INNER JOIN `categoriesproducts` AS `Categories.CategoriesProducts` 
               ON `Product`.`id` = `Categories.CategoriesProducts`.`productid` 
       INNER JOIN `categories` AS `Categories` 
               ON `categories`.`id` = 
`Categories.CategoriesProducts`.`categoryid` 
                  AND `categories`.`id` IN ( '1' ) 
ORDER  BY product.id ASC; 

it's mean that I often get less than 12 rows, but I expect something like that:

SELECT `Product`.`id`, 
      ...
       `categories`.`id`                            AS `Categories.id`,     
      ...
       `Categories.CategoriesProducts`.`createdat`  AS   `Categories.CategoriesProducts.createdAt`, 
      ...
FROM   `products` AS `Product` 
       INNER JOIN `categoriesproducts` AS `Categories.CategoriesProducts` 
               ON `Product`.`id` = `Categories.CategoriesProducts`.`productid` 
       INNER JOIN `categories` AS `Categories` 
               ON `categories`.`id` = `Categories.CategoriesProducts`.`categoryid` 
                  AND `categories`.`id` IN ( '1' ) 
WHERE  `Product`.`merchantid` IN ( '1', '2' ) 
       AND `Product`.`price` >= '0' 
       AND `Product`.`price` <= '10000' 
ORDER  BY product.id ASC 
LIMIT 12 OFFSET 0; 

I get this built query just by deleting

limit: params.limit
offset: params.offset

from parameters object and write LIMIT 12 OFFSET 0; manually.

Question: how to get what I expect (returning 12 rows) or how to get built query for manually changing it?

Activity

  1. mickhansen commented on Jan 10, 2015

    @mickhansen
    Contributor

    Your expected query wouldn't ever actually work in terms of limit because of row duplication.
    As for the sequelize calls, it appears it's not accurately using the include tables in the subquery for checking (categories.id IN ( '1' ) should be checked but it isnt)
    What version are you using? Have you tested on the latest?

  2. milushov commented on Jan 10, 2015

    @milushov
    Author

    my version is Sequelize [Node: 0.10.26, CLI: 1.0.2, ORM: 2.0.0-rc7, sqlite3: ^3.0.4]

  3. mickhansen commented on Jan 10, 2015

    @mickhansen
    Contributor

    Okay, so appears you uncovered yet a case :)
    If you want to help out we would appreciate a PR with a failing unit test.

  4. milushov commented on Jan 10, 2015

    @milushov
    Author

    ok, I will try in the near future

    hmm, btw, where is proper place for this test case?

  5. mickhansen commented on Jan 10, 2015

    @mickhansen
    Contributor

    test/include/findAll has a ton of other cases so that's fine :)

  6. milushov commented on Jan 13, 2015

    @milushov
    Author

    @mickhansen, hey, can you prompt me where is placed migration files for these models? I want to create new join table for belongToMany association.

  7. mickhansen commented on Jan 13, 2015

    @mickhansen
    Contributor

    @milushov sorry? We don't use migrations for general testing - We use sync()

  8. milushov commented on Jan 13, 2015

    @milushov
    Author

    @mickhansen, ok, so how and where I can create join table without defining model?

  9. mickhansen commented on Jan 13, 2015

    @mickhansen
    Contributor

    @milushov If it doesn't need to hold more than the foreign key attributes you just use through: 'tableName' on your BTM relations.

  10. BridgeAR commented on May 31, 2015

    @BridgeAR
    Contributor
  11. NOX73 commented on Sep 9, 2015

    @NOX73

    Is anybody doing anything about this? btw counting in this case works properly

  12. janmeier commented on Sep 9, 2015

    @janmeier
    Member

    @NOX73 Can you describe the issue you are having? Model definition, associations etc? It's always easier to figure out the bug with more test cases

  13. abossard commented on Oct 14, 2015

    @abossard

    I have the same problem. I have these models:

         let Product = sequelize.define("Product", {
            uuid: {
                type: DataTypes.UUID,
                unique: true,
                allowNull: false,
                defaultValue: DataTypes.UUIDV4,
                validate: {
                    isUUID: 4
                }
            },
            architonic_product_id: {
                type: DataTypes.INTEGER,
                unique: true,
                allowNull: false
            },
            architonic_family_id: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
            manufacturer_product_code: {
                type: DataTypes.STRING(255),
                unique: true,
                allowNull: false
            },
            designer_name: {
                type: DataTypes.STRING(255),
                allowNull: true
            }
        })
    
       //.....
    
        let ProductColor = sequelize.define("ProductColor", {
            slug: {
                type: DataTypes.STRING(1024),
                allowNull: false,
                unique: true
            }
        })
    
       //.....
    
       Product.belongsToMany(ProductColor, {through: 'ProductToProductColor'})

    And my query looks like this:

        Product.findAndCountAll({
            limit:68,
            offset:0,
            include: [
            {
                model: ProductColor,
                where: {id: {$in: '1','2' }
           }]
        })

    I get the current count (e.g. 42), but the rows have only 6 in them.

  14. abossard commented on Oct 14, 2015

    @abossard

    If I raise the limit from 68 to e.g. 999 I get all the 42 results! The sweet spot is around limit 661, from there I get all the rows.

    Here is the full SQL (I omitted some of the classes before):

    SELECT "Product".*,
           "ProductManufacturer.ProductManufacturerLabels"."id"
           AS
           "ProductManufacturer.ProductManufacturerLabels.id",
           "ProductManufacturer.ProductManufacturerLabels"."language"
           AS
           "ProductManufacturer.ProductManufacturerLabels.language",
           "ProductManufacturer.ProductManufacturerLabels"."manufacturer_profile"
           AS
           "ProductManufacturer.ProductManufacturerLabels.manufacturer_profile",
           "ProductManufacturer.ProductManufacturerLabels"."created_at"
           AS
           "ProductManufacturer.ProductManufacturerLabels.created_at",
           "ProductManufacturer.ProductManufacturerLabels"."updated_at"
           AS
           "ProductManufacturer.ProductManufacturerLabels.updated_at",
           "ProductManufacturer.ProductManufacturerLabels"."product_manufacturer_id"
           AS
           "ProductManufacturer.ProductManufacturerLabels.product_manufacturer_id",
           "ProductLabels"."id"
           AS "ProductLabels.id",
           "ProductLabels"."language"
           AS "ProductLabels.language",
           "ProductLabels"."product_id"
           AS "ProductLabels.product_id",
           "ProductLabels"."product_title"
           AS "ProductLabels.product_title",
           "ProductLabels"."product_description"
           AS "ProductLabels.product_description",
           "ProductLabels"."additional_product_info"
           AS
           "ProductLabels.additional_product_info",
           "ProductLabels"."delivery_time"
           AS "ProductLabels.delivery_time",
           "ProductLabels"."created_at"
           AS "ProductLabels.created_at",
           "ProductLabels"."updated_at"
           AS "ProductLabels.updated_at",
           "ProductCategories"."id"
           AS "ProductCategories.id",
           "ProductCategories"."slug"
           AS "ProductCategories.slug",
           "ProductCategories"."created_at"
           AS "ProductCategories.created_at",
           "ProductCategories"."updated_at"
           AS "ProductCategories.updated_at",
           "ProductCategories"."hierarchylevel"
           AS "ProductCategories.hierarchyLevel",
           "ProductCategories"."parentid"
           AS "ProductCategories.parentId",
           "ProductCategories.ProductToProductCategory"."created_at"
           AS
           "ProductCategories.ProductToProductCategory.created_at",
           "ProductCategories.ProductToProductCategory"."updated_at"
           AS
           "ProductCategories.ProductToProductCategory.updated_at",
           "ProductCategories.ProductToProductCategory"."product_id"
           AS
           "ProductCategories.ProductToProductCategory.product_id",
           "ProductCategories.ProductToProductCategory"."product_category_id"
           AS
           "ProductCategories.ProductToProductCategory.product_category_id",
           "ProductCategories.ProductCategoryLabels"."id"
           AS
           "ProductCategories.ProductCategoryLabels.id",
           "ProductCategories.ProductCategoryLabels"."language"
           AS
           "ProductCategories.ProductCategoryLabels.language",
           "ProductCategories.ProductCategoryLabels"."title"
           AS
           "ProductCategories.ProductCategoryLabels.title",
           "ProductCategories.ProductCategoryLabels"."created_at"
           AS
           "ProductCategories.ProductCategoryLabels.created_at",
           "ProductCategories.ProductCategoryLabels"."updated_at"
           AS
           "ProductCategories.ProductCategoryLabels.updated_at",
           "ProductCategories.ProductCategoryLabels"."product_category_id"
           AS
           "ProductCategories.ProductCategoryLabels.product_category_id",
           "ProductImages"."id"
           AS "ProductImages.id",
           "ProductImages"."product_id"
           AS "ProductImages.product_id",
           "ProductImages"."url"
           AS "ProductImages.url",
           "ProductImages"."created_at"
           AS "ProductImages.created_at",
           "ProductImages"."updated_at"
           AS "ProductImages.updated_at",
           "ProductPrices"."id"
           AS "ProductPrices.id",
           "ProductPrices"."product_id"
           AS "ProductPrices.product_id",
           "ProductPrices"."currency"
           AS "ProductPrices.currency",
           "ProductPrices"."amount"
           AS "ProductPrices.amount",
           "ProductPrices"."created_at"
           AS "ProductPrices.created_at",
           "ProductPrices"."updated_at"
           AS "ProductPrices.updated_at",
           "ProductColors"."id"
           AS "ProductColors.id",
           "ProductColors"."slug"
           AS "ProductColors.slug",
           "ProductColors"."created_at"
           AS "ProductColors.created_at",
           "ProductColors"."updated_at"
           AS "ProductColors.updated_at",
           "ProductColors.ProductToProductColor"."created_at"
           AS
           "ProductColors.ProductToProductColor.created_at",
           "ProductColors.ProductToProductColor"."updated_at"
           AS
           "ProductColors.ProductToProductColor.updated_at",
           "ProductColors.ProductToProductColor"."product_id"
           AS
           "ProductColors.ProductToProductColor.product_id",
           "ProductColors.ProductToProductColor"."product_color_id"
           AS
           "ProductColors.ProductToProductColor.product_color_id",
           "ProductColors.ProductColorLabels"."id"
           AS "ProductColors.ProductColorLabels.id",
           "ProductColors.ProductColorLabels"."language"
           AS
           "ProductColors.ProductColorLabels.language",
           "ProductColors.ProductColorLabels"."color_name"
           AS
           "ProductColors.ProductColorLabels.color_name",
           "ProductColors.ProductColorLabels"."created_at"
           AS
           "ProductColors.ProductColorLabels.created_at",
           "ProductColors.ProductColorLabels"."updated_at"
           AS
           "ProductColors.ProductColorLabels.updated_at",
           "ProductColors.ProductColorLabels"."product_color_id"
           AS
           "ProductColors.ProductColorLabels.product_color_id"
    FROM   (SELECT "product"."id",
                   "product"."uuid",
                   "product"."architonic_product_id",
                   "product"."architonic_family_id",
                   "product"."manufacturer_product_code",
                   "product"."designer_name",
                   "product"."created_at",
                   "product"."updated_at",
                   "product"."product_manufacturer_id",
                   "productmanufacturer"."id"                 AS
                   "ProductManufacturer.id",
                   "productmanufacturer"."manufacturer_brand" AS
                   "ProductManufacturer.manufacturer_brand",
                   "productmanufacturer"."manufacturer_logo"  AS
                   "ProductManufacturer.manufacturer_logo",
                   "productmanufacturer"."created_at"         AS
                          "ProductManufacturer.created_at",
                   "productmanufacturer"."updated_at"         AS
                          "ProductManufacturer.updated_at"
            FROM   "product" AS "Product"
                   INNER JOIN "productmanufacturer" AS "ProductManufacturer"
                           ON "product"."product_manufacturer_id" =
                              "productmanufacturer"."id"
                              AND "productmanufacturer"."id" IN ( '1' )
            WHERE  (SELECT "producttoproductcategory"."product_id"
                    FROM   "producttoproductcategory" AS "ProductToProductCategory"
                           INNER JOIN "productcategory" AS "ProductCategory"
                                   ON
                           "producttoproductcategory"."product_category_id" =
                           "productcategory"."id"
                    WHERE  ( "product"."id" =
                             "producttoproductcategory"."product_id" )
                    LIMIT  1) IS NOT NULL
                   AND (SELECT "producttoproductcolor"."product_id"
                        FROM   "producttoproductcolor" AS "ProductToProductColor"
                               INNER JOIN "productcolor" AS "ProductColor"
                                       ON "producttoproductcolor"."product_color_id"
                                          =
                                          "productcolor"."id"
                        WHERE  ( "product"."id" =
                                 "producttoproductcolor"."product_id" )
                        LIMIT  1) IS NOT NULL
            LIMIT  661) AS "Product"
           LEFT OUTER JOIN "productmanufacturerlabel" AS
                           "ProductManufacturer.ProductManufacturerLabels"
                        ON "productmanufacturer.id" =
           "ProductManufacturer.ProductManufacturerLabels"."product_manufacturer_id"
           LEFT OUTER JOIN "productlabel" AS "ProductLabels"
                        ON "Product"."id" = "ProductLabels"."product_id"
           INNER JOIN ("producttoproductcategory" AS
                      "ProductCategories.ProductToProductCategory"
                       INNER JOIN "productcategory" AS "ProductCategories"
                               ON "ProductCategories"."id" =
    "ProductCategories.ProductToProductCategory"."product_category_id")
    ON "Product"."id" =
    "ProductCategories.ProductToProductCategory"."product_id"
    LEFT OUTER JOIN "productcategorylabel" AS
        "ProductCategories.ProductCategoryLabels"
     ON "ProductCategories"."id" =
    "ProductCategories.ProductCategoryLabels"."product_category_id"
    LEFT OUTER JOIN "productimage" AS "ProductImages"
     ON "Product"."id" = "ProductImages"."product_id"
    LEFT OUTER JOIN "productprice" AS "ProductPrices"
     ON "Product"."id" = "ProductPrices"."product_id"
    INNER JOIN ("producttoproductcolor" AS "ProductColors.ProductToProductColor"
    INNER JOIN "productcolor" AS "ProductColors"
            ON "ProductColors"."id" =
    "ProductColors.ProductToProductColor"."product_color_id")
    ON "Product"."id" = "ProductColors.ProductToProductColor"."product_id"
    AND "ProductColors"."id" IN ( '3' )
    LEFT OUTER JOIN "productcolorlabel" AS "ProductColors.ProductColorLabels"
     ON "ProductColors"."id" =
    "ProductColors.ProductColorLabels"."product_color_id"
    ORDER  BY "ProductLabels"."product_title" ASC; 
  15. abossard commented on Oct 15, 2015

    @abossard

    Clearly it's not possible to use LIMIT with this SQL. It would only work, if everything could be loaded separate.

  16. mickhansen commented on Oct 15, 2015

    @mickhansen
    Contributor

    @abossard We actually have include.separate for hasMany, belongsToMany support is pending.
    Limits do become tricky with large includes.

  17. abossard commented on Oct 15, 2015

    @abossard

    I'd be happy to ditch all includes and have them all in separate queries, if that would make LIMIT work better. Funny thing is, if there'd be a count query, that returns the IDs instead of the counts, these could be used to make the huge query with includes without regarding the limits.

    SELECT
        "Product"."id"
    FROM
        "Product" AS "Product"
    INNER JOIN "ProductManufacturer" AS "ProductManufacturer" ON "Product"."product_manufacturer_id" = "ProductManufacturer"."id"
    AND "ProductManufacturer"."id" IN ('1')
    INNER JOIN (
        "ProductToProductCategory" AS "ProductCategories.ProductToProductCategory"
        INNER JOIN "ProductCategory" AS "ProductCategories" ON "ProductCategories"."id" = "ProductCategories.ProductToProductCategory"."product_category_id"
    ) ON "Product"."id" = "ProductCategories.ProductToProductCategory"."product_id"
    INNER JOIN (
        "ProductToProductColor" AS "ProductColors.ProductToProductColor"
        INNER JOIN "ProductColor" AS "ProductColors" ON "ProductColors"."id" = "ProductColors.ProductToProductColor"."product_color_id"
    ) ON "Product"."id" = "ProductColors.ProductToProductColor"."product_id"
    AND "ProductColors"."id" IN ('10', '4');
  18. abossard commented on Oct 15, 2015

    @abossard

    well, it would not regard the sorting. I see. It is a tricky problem.

  19. abossard commented on Oct 15, 2015

    @abossard

    Currently the LIMIT is on the inner table, but the WHERE clause is on the outer table. That limits the products before they even get to the matching with the WHERE clause.

    I wish I had the skills and time to supply you with a test and make a pull request :-/

  20. BridgeAR commented on Jun 30, 2016

    @BridgeAR
    Contributor

    @abossard to reach what you want you currently would have to write something like:

    const queryObject = {
        limit:68,
        offset:0,
        include: [ProductColor],
        where: {}
    }
    queryObject.where['$' + ProductColor.name + '.id$'] = ['1', '2']
    
    Product.findAndCountAll(queryObject)
    

    But this is not yet working, as the ProductColor would be removed in the count query and produce a database error. I'm about to fix this though and look through all issues that correspond to this.

  21. stale commented on Jun 29, 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 🙂

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions