Skip to content

Exception thrown when eager loading n:m association with require: true and attributes: [] #5958

Closed

Description

@Mumeii

I found a bug while trying to eager load a n:m association and using both require: true and attributes: [] at the same time.

To reproduce please use the two following files :

  • server.js for the code itself
  • package.json for Sequelize version and extra dependencies

Then simply npm start

Here is the server.js file :

var _         = require( 'lodash' )
var fs        = require( 'fs' )
var sqlite3   = require( 'sqlite3' ).verbose();
var Sequelize = require( 'sequelize' )
​
​
const fileName = 'test.db'
​
var exists = fs.existsSync( fileName )
​
var db = new sqlite3.Database( fileName )
​
var orm = new Sequelize( 'database', 'username', 'password', {
  dialect: 'sqlite',
  storage: fileName
})
​
// table definitions
var News = orm.define( 'News', {
    title: {
      type: Sequelize.STRING( 128 ),
      allowNull: false
    },
    description: {
      type: Sequelize.STRING( 2048 ),
      allowNull: true
    }
} )
​
var Tag = orm.define( 'Tag', {
    value: {
      type: Sequelize.STRING( 64 ),
      allowNull: false
    },
    description: {
      type: Sequelize.STRING( 256 ),
      allowNull: true
    }
} )
​
// n:m association definition
News.belongsToMany( Tag, { through: 'news_tag' } )
Tag.belongsToMany( News, { through: 'news_tag' } )
​
// let's feed database with something :
orm.sync( {force: true} )
.then( afterSyncResult =>{
    return orm.Promise.all( [
        Tag.create( { value: 'Music' } ),
        Tag.create( { value: 'Sport' } ),
        Tag.create( { value: 'Canada' } ),
        Tag.create( { value: 'France' } ),
        News.create( { title: 'Euro is about to start and stades are not ready' } ),
        News.create( { title: 'Mainsquare festival will host Renaud this year' } ),
        News.create( { title: 'Next Devin Townsend album will be a musical' } ),
        News.create( { title: 'Golden Canada at hokey world championship !' } ) ] )
} )
.then( instanceArray => {
    // store those datas into dedicated maps :
    var tagsArray = instanceArray.slice( 0, 4 )
    var newsArray = instanceArray.slice( 4 )
​
    var tagMap = _.keyBy( tagsArray, e => e.value )
    var newsMap = _.keyBy( newsArray, e => e.title )
​
    // knit the relashionships :
    return orm.Promise.all( [
        // newsMap[ 'Euro is about to start and stades are not ready' ].addTags( [ tagMap.Sport, tagMap.France ] ),
        // newsMap[ 'Mainsquare festival will host Renaud this year' ].addTags( [ tagMap.Music, tagMap.France ] ),
        // newsMap[ 'Next Devin Townsend album will be a musical' ].addTags( [ tagMap.Music, tagMap.Canada ] ),
        newsMap[ 'Golden Canada at hokey world championship !' ].addTags( [ tagMap.Sport, tagMap.Canada ] ),
    ] )
​
} )
.then( placeHolder => {
    // test a request that eager load all news been related to Sport or Canada tags but whithout loading any of the tags fields (attributes : []) :
    return News.findAll( {
        include: [ {
            required: true, // mixing required: true and attributes: [] lead to an exception
            model: Tag,
            attributes: [], // comment this line out and it will work fine
            where: {
                value: {
                    $in: ['Sport', 'Canada']
                }
            }
        } ]
    } )
} )
.then( result => {
    console.log( "It's working !!" )
} )
.catch( err => {
    console.log( "It's NOT working :( ... reason :" )
    console.log( err )
} )

And here is the package.json file :

{
  "name": "sequelize_bug_test",
  "version": "1.0.0",
  "description": "a project to test a sequelize bug",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "prewindebug": "start node-inspector",
    "postwindebug": "powershell -Command \"Get-WmiObject Win32_Process ^| where-object {$_.Name -eq 'node.exe' -and $_.CommandLine -match 'inspector.js'} ^| Stop-Process -id {$_.ProcessId}\"",
    "windebug": "nodemon --debug --harmony --throw-deprecation --use_strict server.js",
    "prewindebugbrk": "start node-inspector",
    "postwindebugbrk": "powershell -Command \"Get-WmiObject Win32_Process ^| where-object {$_.Name -eq 'node.exe' -and $_.CommandLine -match 'inspector.js'} ^| Stop-Process -id {$_.ProcessId}\"",
    "windebugbrk": "nodemon --debug-brk --harmony --throw-deprecation --use_strict server.js"
  },
  "author": "benoit lefevre",
  "license": "ISC",
  "dependencies": {
    "lodash": "^4.13.1",
    "sequelize": "^3.23.2",
    "sqlite3": "^3.1.4"
  }
}

What do you expect to happen?

I expected that eager loading with require: true and attributes: [] both set at the same time would work in order to simulate some kind of EXISTS behavior without having to use a raw query

What is actually happening?

Using both of these options at the same time lead to an exception. npm start to reproduce it.

Output :

it will output the exception and its call stack :

C:\Dev\Project\nc\testBugSequlize\node_modules\sqlite3\lib\trace.js:28
                    throw err;
                    ^

TypeError: Cannot set property 'news_tag' of undefined
    at groupJoinData (C:\Dev\Project\nc\testBugSequlize\node_modules\sequelize\lib\dialects\abstract\query.js:364:37)
    at AbstractQuery.handleSelectQuery (C:\Dev\Project\nc\testBugSequlize\node_modules\sequelize\lib\dialects\abstract\query.js:658:15)
    at Statement.afterExecute (C:\Dev\Project\nc\testBugSequlize\node_modules\sequelize\lib\dialects\sqlite\query.js:178:33)
--> in Database#all('SELECT `News`.`id`, `News`.`title`, `News`.`description`, `News`.`createdAt`, `News`.`updatedAt`, `Tags.news_tag`.`createdAt` AS `Tags.news_tag.createdAt`, `Tags.news_tag`.`updatedAt` AS `Tags.news_tag.updatedAt`, `Tags.news_tag`.`NewsId` AS `Tags.news_tag.NewsId`, `Tags.news_tag`.`TagId` AS `Tags.news_tag.TagId` FROM `News` AS `News` INNER JOIN `news_tag` AS `Tags.news_tag` ON `News`.`id` = `Tags.news_tag`.`NewsId` INNER JOIN `Tags` AS `Tags` ON `Tags`.`id` = `Tags.news_tag`.`TagId` AND `Tags`.`value` IN (\'Sport\', \'Canada\');', [], [Function])
    at C:\Dev\Project\nc\testBugSequlize\node_modules\sequelize\lib\dialects\sqlite\query.js:241:36
    at Promise._execute (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\debuggability.js:272:9)
    at Promise._resolveFromExecutor (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:473:18)
    at new Promise (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:77:14)
    at executeSql (C:\Dev\Project\nc\testBugSequlize\node_modules\sequelize\lib\dialects\sqlite\query.js:103:19)
    at tryCatcher (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:502:31)
    at Promise._settlePromise (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:559:18)
    at Promise._settlePromise0 (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:604:10)
    at Promise._settlePromises (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:683:18)
    at Promise._fulfill (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:628:18)
    at MappingPromiseArray.PromiseArray._resolve (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise_array.js:125:19)
    at MappingPromiseArray._promiseFulfilled (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\map.js:97:18)
    at Promise._settlePromise (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:564:26)
    at Promise._settlePromise0 (C:\Dev\Project\nc\testBugSequlize\node_modules\bluebird\js\release\promise.js:604:10)

Dialect & versions :

Dialect: sqlite for ease of reproducing the bug but not relevant in that case
Database version: not relevant
Sequelize version: see the package.json file

Notice

The code where the exception occurs been awfully complex and lacking of comments I can't help with any pull request.
On the other hand I think the previous sample code can be easily turned into a test

Extra thoughts :

Would using options.include[].separate: true would cause extra troubles ?

Activity

  1. mickhansen commented on May 25, 2016

    @mickhansen
    Contributor

    No idea why you're seeing that error.
    separate would make it run in a separate query, so effectively pointless.

  2. Mumeii commented on Jun 12, 2016

    @Mumeii
    Author

    @mickhansen : Sorry for the late reply, I've been quite busy with family troubles recently.

    By

    No idea why you're seeing that error.

    Do you mean you couldn't reproduce the trouble ?

    The separate reference was simply coming from an extra thought on which other options could also come interfering with this part of the code, but it's not directly related to the exception encountered here.

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