Repository navigation
Open
Open
Copy link
Labels
type: bugDEPRECATED: replace with the "bug" issue type
Description
Dialect: PostgresSql
Sequelize version: 3.19.3
I have two tables that are n:m associated with a joining table. Whenever I use .findAll and include the other table, all fields in the joining table would also be selected in the generated SQL queries. The fields in the joining table would cause problems when I try to use the aggregate functions.
include[].through.attributes: [] does not stops the columns from going into the SQL query.
The example below is modified from the one in #3938.
Setup:
// MODELS
var Group = sequelize.define('Group', {
name: sequelize.Sequelize.STRING
});
var Person = sequelize.define('Person', {
name: sequelize.Sequelize.STRING
});
var GroupPerson = sequelize.define('GroupPerson', {
status: sequelize.Sequelize.STRING
});
// RELATIONS
Group.belongsToMany(Person, {through: GroupPerson, as: 'Persons'});
Person.belongsToMany(Group, {through: GroupPerson, as: 'Groups'});
sequelize.sync({force: true}).then(function(){
// EXAMPLE
Person.findAll({
attributes: [[sequelize.fn('ARRAY_AGG', sequelize.col('Groups.id')), 'groupIds']],
include: [{
model: Group,
as: 'Groups',
through:{
attributes: [],
where: {status: 'done'}
},
attributes: []
}],
group: [sequelize.col('Person.id')]
});
})Expected SQL generated:
SELECT ARRAY_AGG("Groups"."id") AS "groupIds"
FROM "People" AS "Person"
LEFT OUTER JOIN (
"GroupPeople" AS "Groups.GroupPerson"
INNER JOIN
"Groups" AS "Groups" ON "Groups"."id" = "Groups.GroupPerson"."GroupId" AND "Groups.GroupPerson"."status" = 'done'
) ON "Person"."id" = "Groups.GroupPerson"."PersonId"
GROUP BY "Person"."id";Actual SQL generated:
SELECT "Person"."id", ARRAY_AGG("Groups"."id") AS "groupIds",
"Groups.GroupPerson"."status" AS "Groups.GroupPerson.status", "Groups.GroupPerson"."createdAt" AS "Groups.GroupPerson.createdAt",
"Groups.GroupPerson"."updatedAt" AS "Groups.GroupPerson.updatedAt", "Groups.GroupPerson"."PersonId" AS "Groups.GroupPerson.PersonId",
"Groups.GroupPerson"."GroupId" AS "Groups.GroupPerson.GroupId"
FROM "People" AS "Person"
LEFT OUTER JOIN (
"GroupPeople" AS "Groups.GroupPerson"
INNER JOIN
"Groups" AS "Groups" ON "Groups"."id" = "Groups.GroupPerson"."GroupId" AND "Groups.GroupPerson"."status" = 'done'
) ON "Person"."id" = "Groups.GroupPerson"."PersonId"
GROUP BY "Person"."id";...which gives the following error:
Unhandled rejection SequelizeDatabaseError: column "Groups.GroupPerson.status" must appear in the GROUP BY clause or be used in an aggregate function
at Query.formatError (/Users/mrorz/workspace/gis-inner/node_modules/sequelize/lib/dialects/postgres/query.js:443:14)
at null.<anonymous> (/Users/mrorz/workspace/gis-inner/node_modules/sequelize/lib/dialects/postgres/query.js:118:19)
at emitOne (events.js:77:13)
at emit (events.js:169:7)
at Query.handleError (/Users/mrorz/workspace/gis-inner/node_modules/pg/lib/query.js:108:8)
at null.<anonymous> (/Users/mrorz/workspace/gis-inner/node_modules/pg/lib/client.js:171:26)
at emitOne (events.js:77:13)
at emit (events.js:169:7)
at Socket.<anonymous> (/Users/mrorz/workspace/gis-inner/node_modules/pg/lib/connection.js:109:12)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:146:16)
at Socket.Readable.push (_stream_readable.js:110:10)
at TCP.onread (net.js:523:20)
Reacted by Victor Tavares, Thomas Gak-Deluen, Damian Bouné, Drazen Bjelovuk, Hoang Dinh, Alexander, Dominik, Wilhelm Dewald, Rovack, Han Sen and 9 more
Metadata
Metadata
Assignees
Labels
type: bugDEPRECATED: replace with the "bug" issue type
Type
Projects
- StatusShow more project fieldsNo status
Activity
mickhansen commentedon Feb 24, 2016
Odd, that should simply work.
joewood commentedon Feb 26, 2016
I'm seeing something similar with the MSSQL provider. When any associations are used with an aggregate function all the fields seem to be included in the query, irrespective of the attributes/include/exclude list.
dojiboy9 commentedon Mar 9, 2016
ditto for mysql
chillichicken commentedon Jun 14, 2016
can confirm this too for mysql
mickhansen commentedon Jun 14, 2016
There's a confirmed issue with
through.attributesyocontra commentedon Jul 4, 2016
Can also confirm this for postgres on a belongsTo relationship, so definitely not just for through attributes
dongseok0 commentedon Mar 6, 2017
Any workaround or updates there?
It was fine with MySQL but I getting this error after I changed to MSSQL.
saudpunjwani101 commentedon Mar 11, 2017
Any solutions so far? the problem is a big pain in Postgres too
doublerebel commentedon Apr 25, 2017
Count query generates the expected SQL, while min/max do not. v3.30.4:
This is an actual example only user id has been anonymized.
Count
Query
SQL generated
Result
[ { count: '22' } ]Min
Query
SQL generated
Result
SequelizeDatabaseError: column "users.user_lead.userId" must appear in the GROUP BY clause or be used in an aggregate functiondoublerebel commentedon Apr 25, 2017
Found a Fix!
By changing the query to add
{includeIgnoreAttributes: false}, I now get the correct result:SQL generated
Result
2017-03-14T00:28:11.000ZHope this helps someone else! I found the clue to (the undocumented feature)
includeIgnoreAttributesin #6711, grepped the source and found it was being set tofalsein Model.count.EDIT:
includeIgnoreAttributes: falsemakesattributes: []superfluous, but if you do need any attributes from included Models, include them explicitly in theattributesarray.stale commentedon Jun 29, 2017
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 🙂
yocontra commentedon Jun 29, 2017
Still an issue, so yes keep it open.
24 remaining items
Relequestual commentedon Mar 30, 2020
I found this previously merged PR which appeared to fix it in the event you use
raw:true#4029However, at a guess, the test is bad because it didn't define the joining table to have a primary column in the definition. =/
carlosingles commentedon May 7, 2020
This is still an issue for me, however I have found a workaround if you are using a Model definition for your join table.
Using: [email protected]
The following is a stripped down example of what I have (using Typescript):
This ends up generating the following SQL:
Which gives me a single row only with 'Tenancy.id' and 'activeUsers'.
EinfachHans commentedon Mar 1, 2021
It's 2021, i use Version
6.5.0and this is still an issuelaurelgr commentedon Mar 12, 2021
Same problem, got saved by the above workaround of
includeIgnoreAttributes: false. I too believe this workaround should be documented until the issue is resolved!Between root
attributes, includeattributesandthroughattributes (plus trying outexcludemagic) on top of group/aggregate it was a pain to debug and search a correct workaround.cirosantilli commentedon Nov 9, 2021
Here's a more directly runnable repro with some assertions:
package.json
on PostgreSQL 13.4 Ubuntu 21.10 Node.js v14.17.0.
Generated query:
PostgreSQL disallows the
Users.idfromSELECTas it is not grouped by, and could lead to a random value being selected if there were different possible values. Some databases like SQLite allow that though, so it doesn't blow up there.Here's a similar older thread: #3256
I can then work around as others mentioned by using BOTH
rawandincludeIgnoreAttributes: falseas in:Another workaround: GROUP BY PK instead of by another non-PK UNIQUE field
This is not always possible, sometimes you just want to GROUP BY non-UNIQUE fields. But if the field is unique, you can do this.
The example above can be fixed by replacing:
by:
which is the most common use case for this type of action, full working querry:
It appears that as long as the GROUP BY uniquely defines the row, you can SELECT other rows according to SQL 99: https://dba.stackexchange.com/a/141600/33332
TODO but then why:
doesn't fix it as well?
EDIT: Postgresql have a TODO here for that: https://github.com/postgres/postgres/blob/REL_13_5/src/test/regress/sql/functional_deps.sql#L27 they want it to work, but it doesn't yet, as of 13.5 only GROUP BY PRIMARY KEY allows you to access other columns. Also relevant: https://dba.stackexchange.com/questions/158015/why-can-i-select-all-fields-when-grouping-by-primary-key-but-not-when-grouping-b
liorsion commentedon Feb 4, 2022
I can try to help solve this, the issue is with this line, but it's not clear why it's needed:
moda20 commentedon Jul 23, 2022
Hey, This is 2022 and i am getting an error where sequelize will add an 'id' out of nowhere and break my group query.
here is the query :
the resulting sql query is :
That bold id is not supposed to be there. I tried all the solutions above and it still creates the same sql query with an extra id
Why is this an issue are we doing it the """wrong""" way ?
laurelgr commentedon Aug 4, 2022
@moda20 you are using
findAndCountAllinstead offindAllso that may be why the previous solutions don't work for you. I'm not familiar enough with it to tell if there is any relevant difference, so you should first try with afindAllto make sure the problem is not unrelated. And I am even less familiar with the separate option.Also, your resulting query only uses one table
pricewithout any join, and you only have 1 undesired columnidinstead of all the existing columns of your table, so I believe your issue might be related specifically to the use of separate.This issue is about generated join queries selecting all columns. If you run separate queries, there is no JOIN in the database query itself since Sequelize will do the join instead.
I see you created your own issue though so I won't go further here. :)