Repository navigation
Closed
Description
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
}
);Reacted by Pedro Machado, Raymond Phu Nguyen, Alexander Zai, Temitope, Erkan Zileli, Ishan, Norbert Nemeth, YiFanChen99, Lucas, kashlo and 5 more
Metadata
Metadata
Assignees
Labels
No labels
Activity
mickhansen commentedon Sep 7, 2015
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 = trueon the messages include.osteenbergen commentedon Sep 7, 2015
I tried the
requiredbut 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
Query
mickhansen commentedon Sep 7, 2015
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.
osteenbergen commentedon Sep 7, 2015
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?
mickhansen commentedon Sep 7, 2015
You can try using
include.duplicating = falsein that case.osteenbergen commentedon Sep 7, 2015
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
MrOrz commentedon Jan 26, 2016
+1 for documenting
include.duplicating=false.Came across exactly the same issue and this thread saved my day :)
mickhansen commentedon Jan 26, 2016
@MrOrz duplicating should be in the API docs i believe
kimzerokim commentedon Jul 4, 2016
+1
thanks for this thread.
I was also suffered by exact same issue :(
contactakagrawal commentedon Apr 28, 2017
Thank God I cam here :)
lxcid commentedon May 22, 2017
Interesting, adding
duplicating=falseto my include options make sequelize generate the right query. Anyone have any idea why this is the case?sebastian-serfe commentedon Jul 27, 2017
@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
PorterK commentedon Sep 24, 2018
duplicating: falsefixed 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.. hmmdbettini commentedon Dec 3, 2018
@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
includeoption) does not yield anything.mickhansen commentedon Dec 3, 2018
@dbettini I'm not involved with maintaining Sequelize anymore so i can't speak to how the API docs look these days.
alisherafat01 commentedon Jun 16, 2019
@mickhansen
duplicating: falsebreaks limit and offsetjohnculviner commentedon Jul 26, 2019
If above didn't work try this!
The only way I could get this to work was to do
subQuery: falsewhen 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 dofindAndCountAllif 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!)FREEZX commentedon Mar 15, 2020
subQuery: falsegives incorrect data when limit or offset are used on M:N relationsGefyaqiilah commentedon Jul 8, 2021
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
}
})
kvaibhav39 commentedon Oct 11, 2023
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,
},
kuriel-dev commentedon Sep 6, 2024
in that case, use: