Skip to content

Limit causing "missing FROM-clause entry for table" #4446

Closed

Description

@osteenbergen

Hi,

Got an issue with sequelize, tried 3.5 and 3.7.1, using postgres. I added as much detail as I could below, but the short version is that adding limit to a query with an include results in a different query than expected.

I simplified the models for readability, but its just a simple job system. Lets say the job is to run echo 'Hello World' than a Run would be status/result of the execution. You can run a job multiple times resulting in a new Run model. During execution the system may add RunMessages to the Run, which can be the output of the command.

What I'm trying to query is the answer to the following question:
For a given job what are the last 10 runs and the number of messages for each run

The result should be something like

[
 {"id":"...","status": "done","jobid":"...", ... , "msg_count":3},
 {"id":"...","status": "done","jobid":"...", ... , "msg_count":9},
 {"id":"...","status": "done","jobid":"...", ... , "msg_count":0},
 ...
]

Working query without limit

Query options:

{
  "where" : {
    "jobid":req.params.jobid
  },
  "attributes":
    Object.keys(this.db.model("Run").attributes).concat([
      [sequelize.fn('COUNT',sequelize.col('messages.id')),"msg_count"]
    ]),
  "include":[
      {
        "model": this.db.model("RunMessage"),
        "as" : "messages",
        "attributes":[]
      }
  ],
  "group":['"Run.id"'],
  "order":[["createdAt","DESC"]],
  "logging": console.log,
}

Query

SELECT 
  "Run"."id", 
  "Run"."status", 
  "Run"."jobid",
  "Run"."createdAt", 
  "Run"."updatedAt", 
  COUNT("messages"."id") AS "msg_count"
FROM "Runs" AS "Run" 
LEFT OUTER JOIN "RunMessages" AS "messages" ON "Run"."id" = "messages"."runid" 
WHERE "Run"."jobid" = '607169ba-e6ec-4efa-8aca-b70ffc1d2ffb' 
GROUP BY "Run"."id" 
ORDER BY "Run"."createdAt" DESC;

Adding Limit

{
  "where" : {
    "jobid":req.params.jobid
  },
  "attributes":
    Object.keys(this.db.model("Run").attributes).concat([
      [sequelize.fn('COUNT',sequelize.col('messages.id')),"msg_count"]
    ]),
  "include":[
      {
        "model": this.db.model("RunMessage"),
        "as" : "messages",
        "attributes":[]
      }
  ],
  "group":['"Run.id"'],
  "order":[["createdAt","DESC"]],
  "logging": console.log,
  "limit": 10
}

Query

SELECT 
  "Run".* 
FROM (
  SELECT 
    "Run"."id", 
    "Run"."status", 
    "Run"."jobid", 
    "Run"."createdAt", 
    "Run"."updatedAt", 
    COUNT("messages"."id") AS "msg_count" 
  FROM "Runs" AS "Run" 
  WHERE "Run"."jobid" = '607169ba-e6ec-4efa-8aca-b70ffc1d2ffb' 
  GROUP BY "Run"."id"
  ORDER BY "Run"."createdAt" DESC
  LIMIT 10
) AS "Run" 
LEFT OUTER JOIN "RunMessages" AS "messages" ON "Run"."id" = "messages"."runid"
ORDER BY "Run"."createdAt" DESC;

Error

SequelizeDatabaseError: missing FROM-clause entry for table "messages"
job_1 |     at Query.formatError (/api-jobs/node_modules/sequelize/lib/dialects/postgres/query.js:433:14)
job_1 |     at null.<anonymous> (/api-jobs/node_modules/sequelize/lib/dialects/postgres/query.js:108:19)
job_1 |     at emit (events.js:107:17)
job_1 |     at Query.handleError (/regressinator-api-jobs/node_modules/pg/lib/query.js:99:8)
job_1 |     at null.<anonymous> (/regressinator-api-jobs/node_modules/pg/lib/client.js:166:26)
job_1 |     at emit (events.js:107:17)
job_1 |     at Socket.<anonymous> (/regressinator-api-jobs/node_modules/pg/lib/connection.js:109:12)
job_1 |     at Socket.emit (events.js:107:17)
job_1 |     at readableAddChunk (_stream_readable.js:163:16)
job_1 |     at Socket.Readable.push (_stream_readable.js:126:10)
job_1 |     at TCP.onread (net.js:538:20)

Expected Query

SELECT 
  "Run"."id", 
  "Run"."status", 
  "Run"."jobid",
  "Run"."createdAt", 
  "Run"."updatedAt", 
  COUNT("messages"."id") AS "msg_count"
FROM "Runs" AS "Run" 
LEFT OUTER JOIN "RunMessages" AS "messages" ON "Run"."id" = "messages"."runid" 
WHERE "Run"."jobid" = '607169ba-e6ec-4efa-8aca-b70ffc1d2ffb' 
GROUP BY "Run"."id" 
ORDER BY "Run"."createdAt" DESC
LIMIT 10;

Models

Run

db.define(
    // Model name
    "Run",
    // Properties
    /** @lends Run.prototype */
    {
      /**
      * Identifier of the Job/Run
      * @readonly
      * @type {UUID}
      */
      id : {
        type: DataTypes.UUID,
        //Use V4 UUIDs
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        primaryKey: true
      },
      /**
      * Actual status of the job
      * @type {"created"|"running"|"done"|"failed"}
      */
      status : {
        type: DataTypes.ENUM("created","running","done","failed"),
        defaultValue: "created",
        allowNull: false
      },
      /**
      * Job that we should run
      * @type {UUID}
      */
      jobid : {
        type: DataTypes.UUID,
        allowNull:false
      },
    }
  );

RunMessage

db.define(
    // Model name
    "RunMessage",
    // Properties
    /** @lends RunMessage.prototype */
    {
      /**
      * Identifier of the Job/RunMessage
      * @readonly
      * @type {UUID}
      */
      id : {
        type: DataTypes.UUID,
        //Use V4 UUIDs
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        primaryKey: true
      },
      /**
      * Run associated with this RunMessage
      * @type {UUID}
      */
      runid : {
        type: DataTypes.UUID,
        allowNull:false
      },
      /**
      * A textual description of the notification
      *
      * @type {Text}
      */
      message : {
        type: DataTypes.TEXT,
        allowNull:false
      },
    },
  );

Association

db.model("Run").hasMany(
  db.model("RunMessage"),
  {
    "as" : "messages",
    "foreignKey" : "runid",
    "onDelete" : "cascade",
    "hooks" : true
  }
);

Activity

  1. mickhansen commented on Sep 7, 2015

    @mickhansen
    Contributor

    For limit we need a subquery, and in that case [sequelize.fn('COUNT',sequelize.col('messages.id')),"msg_count"] won't be in the right scope.

    No easy way to fix this other than set include.required = true on the messages include.

  2. osteenbergen commented on Sep 7, 2015

    @osteenbergen
    Author

    I tried the required but it returns the same issue via a different SQL query. If the new query did work it also would return an incorrect result as all runs should be visible even without messages.

    Don't fully understand why a subquery is needed for limit as its a left outer join. The expected query works and uses limit correctly. It might be required to a use-case I'm not aware of.

    Will execute the expected query natively to solve it for now.

    Code changed

    "include":[
      {
        "model": this.db.model("RunMessage"),
        "as" : "messages",
        "attributes":[],
        "required": true
      }
    ]

    Query

    SELECT 
      "Run".* 
    FROM (
      SELECT
        "Run"."id",
        "Run"."status", 
        "Run"."jobid", 
        "Run"."createdAt", 
        "Run"."updatedAt", COUNT("messages"."id") AS "msg_count" 
      FROM "Runs" AS "Run" 
      WHERE 
        "Run"."jobid" = '607169ba-e6ec-4efa-8aca-b70ffc1d2ffb' 
        AND (
          SELECT 
            "runid" 
          FROM "RunMessages" AS "RunMessage" 
          WHERE ("RunMessage"."runid" = "Run"."id") 
          LIMIT 1
        ) IS NOT NULL
      GROUP BY "Run"."id" 
      ORDER BY "Run"."createdAt" DESC 
      LIMIT 10) AS "Run" 
    INNER JOIN "RunMessages" AS "messages" ON "Run"."id" = "messages"."runid" 
    ORDER BY "Run"."createdAt" DESC;
  3. mickhansen commented on Sep 7, 2015

    @mickhansen
    Contributor

    Nevermind .required, won't work in this case because of the row duplicating include.

    The subquery is needed because the joining of messages produces a cartesian product making an outer limit effectively useless.

    You won't be able to do this query with a limit and a count on a join, you'll need to count from a subquery if you wish to limit the overall result.

  4. osteenbergen commented on Sep 7, 2015

    @osteenbergen
    Author

    Ah yes forgot about the cartesian product, although in this use case i group on the main table so it won't be one.

    Do you want to keep this ticket open so that it can be added in future?

  5. mickhansen commented on Sep 7, 2015

    @mickhansen
    Contributor

    You can try using include.duplicating = false in that case.

  6. osteenbergen commented on Sep 7, 2015

    @osteenbergen
    Author

    That did the trick!

    Is there any place where these hidden 'features' are documented? Readthedocs and even the source code don't specify the behaviour of duplicating.

    Closing ticket as its resolved.

    Final Query options

    {
      "where" : {
        "jobid":req.params.jobid
      },
      "attributes":
        Object.keys(this.db.model("Run").attributes).concat([
          [sequelize.fn('COUNT',sequelize.col('messages.id')),"msg_count"]
        ]),
      "include":[
          {
            "model": this.db.model("RunMessage"),
            "as" : "messages",
            "attributes":[],
            "duplicating":false
          }
      ],
      "group":['"Run.id"'],
      "order":[["createdAt","DESC"]],
      "logging": console.log,
    }

    Final Query

    SELECT 
      "Run"."id", 
      "Run"."status", 
      "Run"."jobid",
      "Run"."createdAt", 
      "Run"."updatedAt", 
      COUNT("messages"."id") AS "msg_count" 
    FROM "Runs" AS "Run" 
    LEFT OUTER JOIN "RunMessages" AS "messages" ON "Run"."id" = "messages"."runid" 
    WHERE "Run"."jobid" = '607169ba-e6ec-4efa-8aca-b70ffc1d2ffb' 
    GROUP BY "Run"."id" 
    ORDER BY "Run"."createdAt" DESC 
    LIMIT 10;
  7. MrOrz commented on Jan 26, 2016

    @MrOrz

    +1 for documenting include.duplicating=false.
    Came across exactly the same issue and this thread saved my day :)

  8. mickhansen commented on Jan 26, 2016

    @mickhansen
    Contributor

    @MrOrz duplicating should be in the API docs i believe

  9. kimzerokim commented on Jul 4, 2016

    @kimzerokim

    +1
    thanks for this thread.
    I was also suffered by exact same issue :(

  10. contactakagrawal commented on Apr 28, 2017

    @contactakagrawal
    Contributor

    Thank God I cam here :)

  11. lxcid commented on May 22, 2017

    @lxcid

    Interesting, adding duplicating=false to my include options make sequelize generate the right query. Anyone have any idea why this is the case?

  12. sebastian-serfe commented on Jul 27, 2017

    @sebastian-serfe

    @mickhansen

    Hi, how are you. First at all sequelize is great!

    But if I sue findAndCountAll, the result of the "count" property is the count per association

    for example, if I have 2 Runs, Run 1 has 4 messages and Run 2 has 2 messages

    {"count":[{"count":"4"},{"count":"2"}],"rows":[{"Run".....

    Thanks for your work
    Regards

  13. PorterK commented on Sep 24, 2018

    @PorterK

    duplicating: false fixed my query but I'm still left very confused. What does this option do? I can't seem to find it in the docs anywhere.. hmm

  14. dbettini commented on Dec 3, 2018

    @dbettini

    @MrOrz duplicating should be in the API docs i believe

    @mickhansen I can't find it, like many people have already mentioned. So, I'd say it isn't, since searching for the flag itself, or anywhere concerning associations (because it's an include option) does not yield anything.

  15. mickhansen commented on Dec 3, 2018

    @mickhansen
    Contributor

    @dbettini I'm not involved with maintaining Sequelize anymore so i can't speak to how the API docs look these days.

  16. alisherafat01 commented on Jun 16, 2019

    @alisherafat01

    @mickhansen
    duplicating: false breaks limit and offset

  17. johnculviner commented on Jul 26, 2019

    @johnculviner

    If above didn't work try this!
    The only way I could get this to work was to do subQuery: false when I had 2 nested includes (joins) with server side paging/sorting/filtering and reporting row counts. It still reports the row count wrong when I do findAndCountAll if the nested joins dupe up across a 1-M but that might be bareable (not really easy to fix that I don't think w/o a more expensive query!)

  18. FREEZX commented on Mar 15, 2020

    @FREEZX

    subQuery: false gives incorrect data when limit or offset are used on M:N relations

  19. Gefyaqiilah commented on Jul 8, 2021

    @Gefyaqiilah

    @mickhansen
    duplicating: false breaks limit and offset
    hi i solved this problem, for you who need count and data match.

    if you want to get duplicating data, you must add raw: true, and duplicating: false. and now total data and count must be same. like this :

    users.findAndCountAll({
    {
    "raw": true,
    "where" : {
    "jobid":req.params.jobid
    },
    "attributes":
    Object.keys(this.db.model("Run").attributes).concat([
    [sequelize.fn('COUNT',sequelize.col('messages.id')),"msg_count"]
    ]),
    "include":[
    {
    "model": this.db.model("RunMessage"),
    "as" : "messages",
    "attributes":[],
    "duplicating: false
    }
    ],
    "order":[["createdAt","DESC"]],
    "logging": console.log,
    "limit": 10,
    "offset": 1
    }
    })

  20. kvaibhav39 commented on Oct 11, 2023

    @kvaibhav39

    let attributes = [
    "candidateId",
    "candidatesCasesId",
    "verificationProcessId",
    [
    sequelize.literal(
    '"verificationProcessStatus"."verificationProcessStatusName"'
    ),
    "verificationProcessStatusName",
    ],
    "verificationResultId",
    [
    sequelize.literal(
    '"verificationResultStatus"."verificationResultStatusName"'
    ),
    "verificationResultStatusName",
    ],
    [
    sequelize.literal('"hrOrganization"."hrOrganizationName"'),
    "hrOrganizationName",
    ],
    "hrOrganizationId",
    "caseNumber",
    "candidateName",
    "candidatePhone",
    [sequelize.col("countryMaster.countryMasterId"), "hiringCountryId"],
    [sequelize.col("countryMaster.name"), "hiringCountryName"],
    [
    sequelize.literal('"candidateData->userData"."loginEmail"'),
    "candidateEmail",
    ],
    [sequelize.literal('"candidateData->userData"."usersId"'), "userId"],
    [sequelize.literal('"hrTeams"."hrTeamsId"'), "hrTeamsId"],
    [sequelize.literal('"hrTeams"."hrTeamName"'), "hrTeamName"],
    [
    sequelize.literal('"candidatesReviewsData"."createdAt"'),
    "submissionDate",
    ],
    [sequelize.literal('"assigneeData"."userName"'), "assigneeName"],
    [sequelize.literal('"assigneeData"."usersId"'), "assignee"],
    "dueDate",
    "createdBy",
    "createdAt",
    ];
    let include = [
    {
    model: db.Users,
    as: "createdByUser",
    attributes: ["usersId", "loginEmail", "userName"],
    },
    {
    model: db.Users,
    as: "assigneeData",
    attributes: [],
    required: false,
    },
    {
    model: db.HROrganizations,
    as: "hrOrganization",
    attributes: ["hrOrganizationsId"],
    include: [
    {
    model: db.OpsUserHrOrganizationsMapping,
    as: "opsUserMappingData",
    attributes: ["id"],
    required: false,
    include: [
    {
    model: db.Users,
    as: "opsUserData",
    attributes: ["userName", "usersId", "loginEmail"],
    },
    ],
    },
    ],
    },
    {
    model: db.Candidates,
    as: "candidateData",
    include: [
    {
    model: db.Users,
    as: "userData",
    attributes: [],
    },
    ],
    attributes: [],
    required: true,
    },
    {
    model: db.CandidatesVerificationProcessStatus,
    as: "verificationProcessStatus",
    attributes: [],
    duplicating: false,
    required: false,
    },
    {
    model: db.CandidatesVerificationResultStatus,
    as: "verificationResultStatus",
    attributes: [],
    required: false,
    },
    {
    model: db.CountryMaster,
    as: "countryMaster",
    attributes: [],
    required: false,
    },
    {
    model: db.CandidatesReviews,
    as: "candidatesReviewsData",
    attributes: [],
    required: false,
    },
    {
    model: db.HRTeams,
    as: "hrTeams",
    attributes: [],
    required: false,
    },
    ];
    const offset = (pageNumber - 1) * pageSize;
    const limit = pageSize;

    const candidateCases = await db.CandidatesCases.findAll({
    attributes,
    include,
    where,
    order: [["createdAt", "DESC"]],
    // subQuery: false,
    limit: limit,
    offset: offset,
    });

    Here I have added duplicating: false,
    {
    model: db.CandidatesVerificationProcessStatus,
    as: "verificationProcessStatus",
    attributes: [],
    duplicating: false,
    required: false,
    },

    but i am still get below error
    missing FROM-clause entry for table "verificationProcessStatus"
    
    if I add subQuery: false query works but
    Then it was giving me incorrect result.
    
    And Query works without limit and offset.
    
  21. kuriel-dev commented on Sep 6, 2024

    @kuriel-dev

    @mickhansen duplicating: false breaks limit and offset

    in that case, use:

        // duplicating: true/false -> not needed for fix "missing FROM" error
        required: false, // depends if you wanna force JOIN or not (you choose)
        // this is the key
        separate: false, // forces only one SQL (so aliases are available in the whole query)  <-- this is the key
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