sequelize: Cannot read property '0' of undefined with pg 7

What you are doing?

I just upgraded to Sequelize 4.4.2 and node-postgres (pg) version 7.0.2

Then, when I call sync() to connecto the db and create tables. I get an error

It happens, for example, when I run this command:

models.sequelize.sync({force: true}).

What do you expect to happen?

Sequelize should connect to Postgres and the create tables.

What is actually happening?

TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
    at Promise.then.result (C:\test\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:157:31)
    at tryCatcher (C:\test\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\test\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (C:\test\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (C:\test\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (C:\test\node_modules\bluebird\js\release\promise.js:693:18)
    at Async._drainQueue (C:\test\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (C:\test\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (C:\test\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

__Dialect: postgres __Database version: 9.6.2 (pg 7.0.2) __Sequelize version: 4.4.2

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 53
  • Comments: 70 (5 by maintainers)

Commits related to this issue

Most upvoted comments

I just installed pg@6.4.1. it may be an issue related with the support for pg ^7.0.2

I found that switching from findOrCreate to findCreateFind (documentation here) solved this issue for me

to anyone who downgraded to 6.4.1 to get around this issue… you should go to 6.4.2 since a security vulnerability was recently patched in some old versions: https://node-postgres.com/announcements

cc: @Anatoly-Ktitarov, @shime , @crabicode , @yszk0123

this happens to me while migration queryInterface.changeColumn

+1 for a fix for this.

I tried sync: false and commenting out sync all together, but it didnt work

I also tried to work around the upsert error, by just doing an update instead, but the same error still occurs.

The downgrade to 6.4.2 works for me

Please stop posting +1. Emoji responses serve that purpose without sending an email to everyone subscribed for updates.

Hi Guys…Any news on the development of the solution for this issue ? Already 6 months since the beginning of this issue and we had no information about a possible fix of this… Do you plan to support pg7 in a near future ? Thanks in advance for your answers

So, I would say there is a problem as soon as their is more than one query executed at a time. Given the following code:

const { Client } = require('pg')
const query = "SELECT 'hello'; SELECT 'world';";
const client = new Client()

const f = async () => {
	await client.connect()
	const res = await client.query(query);
	console.log(res);
	await client.end()
};

f();

It outputs with pg 6:

➜  /tmp node pg6/index.js
Result {
  command: 'SELECT',
  rowCount: 1,
  oid: NaN,
  rows:
   [ anonymous { '?column?': 'hello' },
     anonymous { '?column?': 'world' } ],
  fields:
   [ Field {
       name: '?column?',
       tableID: 0,
       columnID: 0,
       dataTypeID: 705,
       dataTypeSize: -2,
       dataTypeModifier: -1,
       format: 'text' } ],
  _parsers: [ [Function: noParse] ],
  RowCtor: [Function: anonymous],
  rowAsArray: false,
  _getTypeParser: [Function: bound ] }

And it outputs with pg 7 :

➜  /tmp node pg7/index.js
[ Result {
    command: 'SELECT',
    rowCount: 1,
    oid: null,
    rows: [ [anonymous] ],
    fields: [ [Field] ],
    _parsers: [ [Function: noParse] ],
    RowCtor: [Function: anonymous],
    rowAsArray: false,
    _getTypeParser: [Function: bound ] },
  Result {
    command: 'SELECT',
    rowCount: 1,
    oid: null,
    rows: [ [anonymous] ],
    fields: [ [Field] ],
    _parsers: [ [Function: noParse] ],
    RowCtor: [Function: anonymous],
    rowAsArray: false } ]
➜  /tmp

So the way to access the result is not the same anymore.

In sequelize, after the query completion with the postgres dialect:

https://github.com/sequelize/sequelize/blob/bb25c19b34f47eeec8f3556b087c2926898d5bbd/lib/dialects/postgres/query.js#L97-L99

Sequelize assumes that queryResult is an object, but in fact, if multiple queries were executed, it’s an array.

Hope it’ll help.

Is there any update on this? 😃

I think the downgrade the pg package is not a permament solution because in this case we can loose some new functionalities that new versions of postgresql will give to programmers in time so I think will be best to investigate the code of sequalize in order to match the changes in the package and go to follow those changes instead of avoid them in long run!

similar to @fnando, the issue I’m seeing is when running raw queries with multiple statements, where the rows param is now a Result array containing rows and the first result was empty


[ Result {
    command: 'SELECT',
    rowCount: 0,
    oid: NaN,
    rows: [],
    fields: [ ... ],
    _parsers: [ ... ],
    RowCtor: [Function: anonymous],
    rowAsArray: false,
    _getTypeParser: [Function: bound ] },
  Result {
    command: 'SELECT',
    rowCount: 1,
    oid: NaN,
    rows: [ [Object] ],
    fields: [ [Object], [Object], [Object] ],
    _parsers: [ [Function: noParse], [Function: noParse], [Function: noParse] ],
    RowCtor: [Function: anonymous],
    rowAsArray: false } ]

thx @Anatoly-Ktitarov for quick fix, can confirm was on 7.0.2 and downgrading pg to 6.4.1 works

I’m getting the same error when running sync({force: true}) on postgres 9.6.5

Without testing on other conditions (complex queries or other cases) I found a solution that works on pg:latest and don’t give an error during init, because the @Anatoly-Ktitarov solution fail on project startup because queryResult is an array and doesn’t have a rows property. Change line 98 of query.js

   const rows = queryResult.rows || queryResult[1].rows;

I think the solution not cover all cases, because some queries could have more than two or three results inside and you would need to access other.

But at the moment, it works for me.

This is amazing! Thanks!

A lot of people are upgrading to pg@7 this weekend 😁 Thanks @sushantdhiman!!

I’m also seeing this while using sync({ force: true }) in sequelize v4.20.1 with PostgreSQL server 10 running on Windows. The workaround of downgrading pg to 6.4.2 worked for me as well.

I get this as well, I can solve it by checking that the rows array exists in query.js:112

        // change to (rows && rows[0] && ...)
        if (rows[0] && rows[0].sequelize_caught_exception !== undefined) {
          if (rows[0].sequelize_caught_exception !== null) {
            throw this.formatError({
              code: '23505',
              detail: rows[0].sequelize_caught_exception
            });
          } else {
            for (const row of rows) {
              delete row.sequelize_caught_exception;
            }
          }
        }

+1 for this, had to downgrade pg to 6.4.2 to fix our production app

Just ran into the same issue with MyModel.upsert()

-> TypeError: Cannot read property ‘0’ of undefined

versions:

  • sequelize@4.19.0
  • pg@7.3.0

no solution so far?

still seeing this problem with pg@7.2.0 as well… as @morficus said, 6.4.2 is the correct and last version that does not have this issue.

We get the following exception:

migrations_1  | TypeError: Cannot read property '0' of undefined
migrations_1  |     at query.catch.then.then.queryResult (/migrations/node_modules/sequelize/lib/dialects/postgres/query.js:112:17)
migrations_1  |     at tryCatcher (/migrations/node_modules/bluebird/js/release/util.js:16:23)
migrations_1  |     at Promise._settlePromiseFromHandler (/migrations/node_modules/bluebird/js/release/promise.js:512:31)
migrations_1  |     at Promise._settlePromise (/migrations/node_modules/bluebird/js/release/promise.js:569:18)
migrations_1  |     at Promise._settlePromise0 (/migrations/node_modules/bluebird/js/release/promise.js:614:10)
migrations_1  |     at Promise._settlePromises (/migrations/node_modules/bluebird/js/release/promise.js:693:18)
migrations_1  |     at Async._drainQueue (/migrations/node_modules/bluebird/js/release/async.js:133:16)
migrations_1  |     at Async._drainQueues (/migrations/node_modules/bluebird/js/release/async.js:143:10)
migrations_1  |     at Immediate.Async.drainQueues (/migrations/node_modules/bluebird/js/release/async.js:17:14)
migrations_1  |     at runCallback (timers.js:789:20)
migrations_1  |     at tryOnImmediate (timers.js:751:5)
migrations_1  |     at processImmediate [as _immediateCallback] (timers.js:722:5)
migrations_1  |
migrations_1  | ERROR: Cannot read property '0' of undefined

This happens when using sequelize to run a DB migration which creates some tables using a blob of raw SQL. Making the change mentioned here https://github.com/sequelize/sequelize/issues/8043#issuecomment-319499298 fixes it. But obviously we can’t make that change everywhere so we’ve had to downgrade to 6.4.2 for now.

+1

I have the same problem with “pg”: “^ 7.4.0” what is the milestone of this?

Hi Guys…I’m having this issue too. For me, it happens when using the method “upsert”.

Using pg@6.4.2 does not trigger the error…

Do you have any news about a possible fix for this ? Thank you very much for your answer

Mine throws right after db.sequelize.sync & findOrCreate are invoked. However when commenting db.sequelize.sync & calling just findOrCreate it worked.

Hm…

I’m still having this problem on pg 7.4.1

I ran into this while trying to create an index. Downgrading from pg@7.3.0 to 6.4.2 made the error go away.

return db.addIndex("blocks", [Sequelize.literal('CAST("time" AS date)')], {
  name: "blocks_date_index"
});

// Error: Cannot read property '0' of undefined

@farzd transaction is a term that is not specific to Sequelize.

What is a database transaction how to do Sequelize transactions

I just got this error and the code is something like this:

db
  .query(sql, {raw: true})
  .then(done)
  .catch((error) => { throw error })

And this is the backtrace:

Unhandled rejection TypeError: Cannot read property '0' of undefined
    at query.catch.then.then.queryResult (myproject/node_modules/sequelize/lib/dialects/postgres/query.js:112:17)
    at tryCatcher (myproject/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (myproject/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (myproject/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (myproject/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (myproject/node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (myproject/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (myproject/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (myproject/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
    at processImmediate [as _immediateCallback] (timers.js:617:5)

Diff:

diff --git a/package.json b/package.json
index 6375a9ef..a23925d8 100644
--- a/package.json
+++ b/package.json
@@ -88,7 +88,7 @@
-    "pg": "6.2.4",
+    "pg": "^7.0.2",
@@ -119,7 +119,7 @@
-    "sequelize": "4.1.0",
+    "sequelize": "^4.4.2",

@dsullivan7 thank you for the fix. Worked for me as well…

I found that switching from findOrCreate to findCreateFind (documentation here) solved this issue for me

Is there an update here? I’m running into this issue when I try Model.upsert(args).

@Anatoly-Ktitarov thanks, that fixed for me…

but still looking to this being resolved any time soon