Skip to content

Using "attributes" and "include" at the same time results in broken query #8617

Closed

Description

@NobleUplift

What are you doing?

These are the query parameters that I am using with findAll. If I use attributes and include at the same time, the query is completely invalid for various reasons:

		var queryParameters = {
			attributes: [
				[ 'id', 'id' ],
				[ 'account_id', 'accountId' ],
				[ 'asset_id', 'assetId' ],
				[ 'name', 'name' ],
				[ 'thumbnail_name', 'thumbnailName' ],
				[ 'enabled', 'enabled' ],
				[ 'createdby', 'createdby' ],
				[ 'createdate', 'createdate' ],
				[ 'updateby', 'updateby' ],
				[ 'updatedate', 'updatedate' ],
				[ 'content_type', 'contentType' ],
				[ 'content_value', 'contentValue' ] ],
			include: 
				[ { model: asset_master, as: 'AssetMaster' },
				  { model: account_asset_folder, as: 'AccountAssetFolders', through: { attributes: [] } } ],
			where: { account_id: '100' },
			order: [ [ 'name', 'asc' ] ],
			limit: 100,
			offset: 0 };

What do you expect to happen?

If I remove the attributes property in my query parameters, it generates a functional query:

SELECT 
    `account_asset`.*,
    `AssetMaster`.`id` AS `AssetMaster.id`,
    `AssetMaster`.`name` AS `AssetMaster.name`,
    `AssetMaster`.`md5sum` AS `AssetMaster.md5sum`,
    `AssetMaster`.`width` AS `AssetMaster.width`,
    `AssetMaster`.`height` AS `AssetMaster.height`,
    `AssetMaster`.`size` AS `AssetMaster.size`,
    `AssetMaster`.`dpi` AS `AssetMaster.dpi`,
    `AssetMaster`.`update_date` AS `AssetMaster.update_date`,
    `AssetMaster`.`update_by` AS `AssetMaster.update_by`,
    `AssetMaster`.`create_date` AS `AssetMaster.create_date`,
    `AssetMaster`.`create_by` AS `AssetMaster.create_by`,
    `AssetMaster`.`enabled` AS `AssetMaster.enabled`,
    `AssetMaster`.`asset_type_id` AS `AssetMaster.asset_type_id`,
    `AccountAssetFolders`.`id` AS `AccountAssetFolders.id`,
    `AccountAssetFolders`.`account_id` AS `AccountAssetFolders.account_id`,
    `AccountAssetFolders`.`name` AS `AccountAssetFolders.name`,
    `AccountAssetFolders`.`enabled` AS `AccountAssetFolders.enabled`,
    `AccountAssetFolders`.`parent_folder_id` AS `AccountAssetFolders.parent_folder_id`,
    `AccountAssetFolders->account_asset_folder_assignment`.`id` AS `AccountAssetFolders.account_asset_folder_assignment.id`,
    `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_id` AS `AccountAssetFolders.account_asset_folder_assignment.account_asset_id`,
    `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_folder_id` AS `AccountAssetFolders.account_asset_folder_assignment.account_asset_folder_id`
FROM
    (SELECT 
        `account_asset`.`id`,
            `account_asset`.`account_id`,
            `account_asset`.`asset_id`,
            `account_asset`.`name`,
            `account_asset`.`thumbnail_name`,
            `account_asset`.`enabled`,
            `account_asset`.`createdby`,
            `account_asset`.`createdate`,
            `account_asset`.`updateby`,
            `account_asset`.`updatedate`,
            `account_asset`.`content_type`,
            `account_asset`.`content_value`
    FROM
        `account_asset` AS `account_asset`
    WHERE
        `account_asset`.`account_id` = '100'
    ORDER BY `account_asset`.`name` ASC
    LIMIT 0 , 100) AS `account_asset`
        LEFT OUTER JOIN
    `asset_master` AS `AssetMaster` ON `account_asset`.`asset_id` = `AssetMaster`.`id`
        LEFT OUTER JOIN
    (`account_asset_folder_assignment` AS `AccountAssetFolders->account_asset_folder_assignment`
    INNER JOIN `account_asset_folder` AS `AccountAssetFolders` ON `AccountAssetFolders`.`id` = `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_folder_id`) ON `account_asset`.`id` = `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_id`
ORDER BY `account_asset`.`name` ASC;

What is actually happening?

This is the result of the query with an attributes object:

SELECT 
    `account_asset`.*,
    `AssetMaster`.`id` AS `AssetMaster.id`,
    `AssetMaster`.`name` AS `AssetMaster.name`,
    `AssetMaster`.`md5sum` AS `AssetMaster.md5sum`,
    `AssetMaster`.`width` AS `AssetMaster.width`,
    `AssetMaster`.`height` AS `AssetMaster.height`,
    `AssetMaster`.`size` AS `AssetMaster.size`,
    `AssetMaster`.`dpi` AS `AssetMaster.dpi`,
    `AssetMaster`.`update_date` AS `AssetMaster.update_date`,
    `AssetMaster`.`update_by` AS `AssetMaster.update_by`,
    `AssetMaster`.`create_date` AS `AssetMaster.create_date`,
    `AssetMaster`.`create_by` AS `AssetMaster.create_by`,
    `AssetMaster`.`enabled` AS `AssetMaster.enabled`,
    `AssetMaster`.`asset_type_id` AS `AssetMaster.asset_type_id`,
    `AccountAssetFolders`.`id` AS `AccountAssetFolders.id`,
    `AccountAssetFolders`.`account_id` AS `AccountAssetFolders.account_id`,
    `AccountAssetFolders`.`name` AS `AccountAssetFolders.name`,
    `AccountAssetFolders`.`enabled` AS `AccountAssetFolders.enabled`,
    `AccountAssetFolders`.`parent_folder_id` AS `AccountAssetFolders.parent_folder_id`,
    `AccountAssetFolders->account_asset_folder_assignment`.`id` AS `AccountAssetFolders.account_asset_folder_assignment.id`,
    `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_id` AS `AccountAssetFolders.account_asset_folder_assignment.account_asset_id`,
    `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_folder_id` AS `AccountAssetFolders.account_asset_folder_assignment.account_asset_folder_id`
FROM
    (SELECT 
        `account_asset`.`id`,
            `account_asset`.`id` AS `id`,
            `account_asset`.`name` AS `name`,
            `account_asset`.`accountId` AS `accountId`,
            `account_asset`.`asset_id` AS `assetId`,
            `account_asset`.`thumbnail_name` AS `thumbnailName`,
            `account_asset`.`enabled` AS `enabled`,
            `account_asset`.`createdby` AS `createdby`,
            `account_asset`.`createdate` AS `createdate`,
            `account_asset`.`updateby` AS `updateby`,
            `account_asset`.`updatedate` AS `updatedate`,
            `account_asset`.`content_type` AS `contentType`,
            `account_asset`.`content_value` AS `contentValue`
    FROM
        `account_asset` AS `account_asset`
    WHERE
        `account_asset`.`account_id` = '100'
    ORDER BY `account_asset`.`name` ASC
    LIMIT 0 , 100) AS `account_asset`
        LEFT OUTER JOIN
    `asset_master` AS `AssetMaster` ON `account_asset`.`asset_id` = `AssetMaster`.`id`
        LEFT OUTER JOIN
    (`account_asset_folder_assignment` AS `AccountAssetFolders->account_asset_folder_assignment`
    INNER JOIN `account_asset_folder` AS `AccountAssetFolders` 
    ON `AccountAssetFolders`.`id` = `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_folder_id`) 
    ON `account_asset`.`id` = `AccountAssetFolders->account_asset_folder_assignment`.`account_asset_id`
ORDER BY `account_asset`.`name` ASC;

Which comes with this error. If I query for any of my ID columns, id, account_id, or asset_id with a corresponding join for any of the columns, the attributes property corrupts the query.

nhandled rejection SequelizeDatabaseError: Unknown column 'AccountAsset.asset_id' in 'on clause'
    at Query.formatError (/Library/WebServer/adstudio/node_modules/sequelize/lib/dialects/mysql/query.js:228:16)
    at Query.connection.query [as onResult] (/Library/WebServer/adstudio/node_modules/sequelize/lib/dialects/mysql/query.js:55:23)
    at Query.Command.execute (/Library/WebServer/adstudio/node_modules/mysql2/lib/commands/command.js:30:12)
    at Connection.handlePacket (/Library/WebServer/adstudio/node_modules/mysql2/lib/connection.js:515:28)
    at PacketParser.onPacket (/Library/WebServer/adstudio/node_modules/mysql2/lib/connection.js:94:16)
    at PacketParser.executeStart (/Library/WebServer/adstudio/node_modules/mysql2/lib/packet_parser.js:77:14)
    at Socket.<anonymous> (/Library/WebServer/adstudio/node_modules/mysql2/lib/connection.js:102:29)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:563:20)

Dialect: mysql
Dialect version: 5.6.35
Database version: 14.14
Sequelize version: 4.22.5
Tested with master branch: No

Note : Your issue may be ignored by maintainers if it's not tested against master branch OR does not follow issue template.

Activity

  1. mattdiamond commented on Nov 16, 2017

    @mattdiamond

    This is somewhat related to my bug: #8612

    The problem is that when Sequelize uses the subquery strategy, it populates the subquery select using the query attributes without checking to ensure that all necessary foreign keys are included as well.

  2. wolframkleis commented on Nov 22, 2017

    @wolframkleis

    I have the same problem. It seems to happen only if several things come together

    1. you use "limit" - otherwise no subquery is used

    2. you include one "belongsTo" association, and a second one of type "toMany" or "hasMany" -otherwise no subquery is used

    3. attributes are specified and the "belongsTo" foreign key is not in the attributes array - otherwise the subquery would select the foreign key

  3. mattdiamond commented on Nov 22, 2017

    @mattdiamond

    @wolframkleis Yeah, it's definitely a bit of an edge case. I should note that the query will work with an attributes hash as long as the belongsTo association has already been declared. The call to Model.belongsTo will add the foreign key to the model's rawAttributes object, which is used to expand the attributes for a given query. If the association hasn't been declared yet (for example, if the query is using a scope that was declared before the association) then this bug can occur.

    Hopefully they'll take a look at this... I haven't gotten a response to my bug report yet.

  4. wolframkleis commented on Nov 23, 2017

    @wolframkleis

    It happens even if you declare the foreign key attribute from the beginning with sequelize.define()
    Example:

    const Author = sequelize.define('Author',{
      id:  { type: Sequelize.INTEGER, primaryKey: true},
      name:{ type: Sequelize.STRING(50)}
    },{timestamps: false, freezeTableName: true});
    
    const Book = sequelize.define('Book',{
      id:  { type: Sequelize.INTEGER, primaryKey: true},
      title:{ type: Sequelize.STRING(50)},
      authorId:{ type: Sequelize.INTEGER,references: { model: 'Author',key: 'id'}}
    },{timestamps: false, freezeTableName: true});
    
    
    const Chapter = sequelize.define('Chapter',{
      id:  { type: Sequelize.INTEGER, primaryKey: true},
      title:{ type: Sequelize.STRING(50)},
      bookId:{ type: Sequelize.INTEGER, references: { model: 'Book',key: 'id'}}
    },{timestamps: false, freezeTableName: true});
    
    Book.hasMany(Chapter, {as: 'chapters',foreignKey: 'bookId'});
    Book.belongsTo(Author,{as: 'author',foreignKey: 'authorId'});
    
    sequelize.sync({force: true,logging:false})
    .then(()=>Book.findAll({ 
      attributes: ['title'],
      include: [{ association: 'chapters'},{ association: 'author'}
      ],
      limit: 6
    }))

    Error:
    error: column Book.authorId does not exist
    SQL:

    SELECT  "Book".*, "chapters"."id" AS "chapters.id", 
            "chapters"."title" AS "chapters.title", "chapters"."bookId" AS "chapters.bookId", 
            "author"."id" AS "author.id", "author"."name" AS "author.name" 
    FROM 
    (SELECT "Book"."id", "Book"."title" FROM "Book" AS "Book" LIMIT 6) AS "Book" 
    LEFT OUTER JOIN "Chapter" AS "chapters" ON "Book"."id" = "chapters"."bookId" 
    LEFT OUTER JOIN "Author" AS "author" ON "Book"."authorId" = "author"."id"

    The sub query does not select the authorId, and the 2nd JOIN is broken.

  5. NobleUplift commented on Dec 7, 2017

    @NobleUplift
    Author

    @wolframkleis helped me find yet another bug in Sequelize, which is evident based on query above. If I have LIMIT 0 , 100 in the subquery and it loads the first 100 rows, any rows past that that belong to the joined table are excluded from the count. I have it where any new objects created are never seen, because they all have IDs in the 1000s, even though there are only 5 items in the folder. Removing the limit/offset so that it can get the 5 items after the first couple 1000 results in:

    Fatal 
    AggregateError of:
        [object Object]
    
        at Promise.try.then (/Library/WebServer/adstudio/node_modules/sequelize/lib/model.js:2323:24)
    From previous event:
        at Promise.try.then (/Library/WebServer/adstudio/node_modules/sequelize/lib/model.js:2331:11)
    From previous event:
        at Function.bulkCreate (/Library/WebServer/adstudio/node_modules/sequelize/lib/model.js:2320:8)
        at association.through.model.findAll.then.currentRows (/Library/WebServer/adstudio/node_modules/sequelize/lib/associations/belongs-to-many.js:585:49)
    From previous event:
        at BelongsToMany.set (/Library/WebServer/adstudio/node_modules/sequelize/lib/associations/belongs-to-many.js:526:87)
        at model.obj.(anonymous function) [as setAccountAssetFolders] (/Library/WebServer/adstudio/node_modules/sequelize/lib/associations/helpers.js:69:40)
        at database_1.Database.getInstance.getModel.findOne.then.then.then.then (/Library/WebServer/adstudio/dist/routes/adstudio-asset_master-upload.js:236:30)
        at runCallback (timers.js:666:20)
        at tryOnImmediate (timers.js:639:5)
        at processImmediate [as _immediateCallback] (timers.js:611:5)
    From previous event:
        at es6_promise_1.Promise.all.then (/Library/WebServer/adstudio/dist/routes/adstudio-asset_master-upload.js:210:18)
        at invokeCallback (/Library/WebServer/adstudio/node_modules/es6-promise/dist/commonjs/promise/promise.js:54:15)
        at publish (/Library/WebServer/adstudio/node_modules/es6-promise/dist/commonjs/promise/promise.js:99:5)
        at publishFulfillment (/Library/WebServer/adstudio/node_modules/es6-promise/dist/commonjs/promise/promise.js:206:3)
        at flush (/Library/WebServer/adstudio/node_modules/es6-promise/dist/commonjs/promise/asap.js:35:5)
        at _combinedTickCallback (internal/process/next_tick.js:73:7)
        at process._tickDomainCallback (internal/process/next_tick.js:128:9)
    [nodemon] failed to start process, possible issue with exec arguments
    events.js:168
          throw err;
          ^
    
    Error: Uncaught, unspecified "error" event. (2)
        at Bus.emit (events.js:166:17)
        at ChildProcess.<anonymous> (/Library/WebServer/adstudio/node_modules/nodemon/lib/monitor/run.js:136:11)
        at emitTwo (events.js:106:13)
        at ChildProcess.emit (events.js:194:7)
        at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! adstudio@1.0.0 dev: `NODE_ENV=development nodemon --config nodemon.js --delay 15 ./bin/www`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the adstudio@1.0.0 dev script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    How do I apply limit and offset to my parent query, and not my subquery? Does this constitute a new bug?

  6. stale commented on Mar 8, 2018

    @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 🙂

  7. wolframkleis commented on Mar 8, 2018

    @wolframkleis

    Not stale. Error is still there, just tested ist with 4.35.2

  8. sushantdhiman commented on Apr 7, 2018

    @sushantdhiman
    Contributor

    Moved to #9166

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