Skip to content

Unhandled rejection TypeError: Cannot read property 'query' of undefined #8087

Closed

Description

@ryanSN

What you are doing?

    return sequelize.transaction((tx) => {
      return Topping.destroy({where: {pizza_id: request.params.id}, transaction: tx})
        .then((res) => {
          return Pizza.destroy({
            where: {id: request.params.id},
            transaction: tx
          })
        })
    }).then((res) => reply('Pizza removed'))
      .catch((err) => reply(err)
  })

What do you expect to happen?

A Transaction!

What is actually happening?

Unhandled rejection TypeError: Cannot read property 'query' of undefined
at parameters.length.Promise (/Users/me/projects/pizza-api/node_modules/sequelize/lib/dialects/postgres/query.js:65:53)
    at Promise._execute (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/debuggability.js:300:9)
    at Promise._resolveFromExecutor (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:483:18)
    at new Promise (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:79:10)
    at Query.run (/Users/me/projects/pizza-api/node_modules/sequelize/lib/dialects/postgres/query.js:65:9)
    at retry (/Users/me/projects/pizza-api/node_modules/sequelize/lib/sequelize.js:529:32)
    at /Users/me/projects/pizza-api/node_modules/retry-as-promised/index.js:40:21
    at Promise._execute (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/debuggability.js:300:9)
    at Promise._resolveFromExecutor (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:483:18)
    at new Promise (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:79:10)
    at retryAsPromised (/Users/me/projects/pizza-api/node_modules/retry-as-promised/index.js:30:10)
    at Promise.try.then.connection (/Users/me/projects/pizza-api/node_modules/sequelize/lib/sequelize.js:529:14)
    at bound (domain.js:280:14)
    at runBound (domain.js:293:12)
    at tryCatcher (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromiseCtx (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/promise.js:606:10)
    at Async._drainQueue (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/async.js:138:12)
    at Async._drainQueues (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (/Users/me/projects/pizza-api/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:666:20)

Dialect: postgres
Database version: 9.4.5.0
Sequelize version: 4.4.2
Bluebird version: 3.5.0

To note I downgraded to version Sequelize version: 3.29.0, code above goes through fine as expected as a transaction

Activity

  1. axetroy commented on Aug 15, 2017

    @axetroy
    Contributor

    same problem.

  2. prokopsimek commented on Aug 15, 2017

    @prokopsimek

    same problem

  3. mhuggins commented on Aug 20, 2017

    @mhuggins

    I'm also encountering this on sequelize 4.6.0 with pg 6.4.1.

  4. mhuggins commented on Aug 20, 2017

    @mhuggins

    Downgrading to sequelize 3.29.0 fixed the problem for me as well.

  5. ddura commented on Aug 27, 2017

    @ddura

    What version of pg module are you using? I am getting the same error but downgrading to 3.29.0 did not fix the problem for me.

  6. mhuggins commented on Aug 27, 2017

    @mhuggins

    I'm using pg 6.4.1 with sequelize 3.30.4.

  7. ryanSN commented on Sep 5, 2017

    @ryanSN
    Author

    @ddura pg 6.4.1

  8. santiagodoldan commented on Sep 25, 2017

    @santiagodoldan

    We're also having this issue in production

    pg 6.4.0 and sequelize 4.10.0

  9. knowtheory commented on Sep 29, 2017

    @knowtheory

    Hey i bumped into this issue while using sequelize in an AWS Lambda function.

    The issue ended up being the fact that i was initially instantiating a sequelize object & database connections in a db.js file i was requiring at the top of my lambda function, rather than actually initializing the database connections w/in the lambda function itself.

    Why does that matter? Well if you're declaring stuff outside of your lambda function, AWS may keep your code hot, and reuse objects you've already declared (and just rerun your lambda function).

    So, my lambda function was running fine on first run, and then happily closed down the db connection. All subsequent attempts to connect to the DB would toss the error that folks are seeing above.

    I ended up wrapping all of my database code in a class which i could use to instantiate and then close down connections to my DB, and only instantiated that class from w/in the body of the lambda function.

    Not positive that this is everybody's issue, but maybe this'll help some of you.

  10. dskvr commented on Oct 3, 2017

    @dskvr

    🤦‍♂️

  11. santiagodoldan commented on Oct 3, 2017

    @santiagodoldan

    I was able to stop getting this issue increasing the pool of connections and setting a higher value to the new acquire config.

      pool: {
        max: 15,
        min: 0,
        idle: 10000,
        acquire: 10000
      }
    
  12. nutheory commented on Oct 13, 2017

    @nutheory

    santiagodoldan solution worked perfectly for me... i was running transactional seeds that choked after a certain amount....

  13. shanmarkus commented on Nov 18, 2017

    @shanmarkus

    Any update on this ?

    i'm using sequelize 4.13.5 and pg 6.2.0

  14. ahlwong commented on Nov 19, 2017

    @ahlwong

    Just upgraded sequelize 4.22.8 and ran into this issue

    Adding the default pool option in sequelize config helped me:

    const pool = {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
    };

  15. gabegorelick commented on Feb 8, 2018

    @gabegorelick
    Contributor

    Still seeing this on Sequelize v4.32.7 and pg v7.4.1. Set acquire to 20000 and still see it.

  16. 7 remaining items

  17. papandreou commented on Feb 14, 2018

    @papandreou
    Contributor

    @sushantdhiman, in the experiment I'm running, the connection.connect callback gets called twice, but only once per connection instance, both times with an artificial ETIMEDOUT error. In other words, it doesn't seem like the pg module does anything weird here.

    The function starting at

    const isFirstTry = retryParameters.current === 1;
    only gets run once and when
    return options.transaction

    is executed, options.transaction is there, but options.transaction.connection is undefined. That explains why the promise is fulfilled with undefined.

    Are you able to reproduce it by patching the pg module and trying to run a query in a transaction?

  18. holm commented on Feb 14, 2018

    @holm
    Contributor

    I added a PR at #9051 which I believe fixes the issue

  19. sushantdhiman commented on Feb 16, 2018

    @sushantdhiman
    Contributor

    This testcase is able to reproduce this issue with same stack as most have reported with. I think application is running out of connections as defined by pool configuration thus unable to acquire new connection because all other open connections are busy right now.

    @holm fix doesn't seems to work for my testcase, does it work for your testcase @papandreou ?

    I think we can throw a special error like SequelizeConnectionTimeout or something which tells you pool is full or connection was not acquired, rather than a cryptic error like this. For MySQL aleast it fails with ResourceRequestTimeout

    'use strict';
    
    const Sequelize = require('./index');
    const sequelize = require('./test/support').createSequelizeInstance({
      pool: {
        max: 1,
        acquire: 1000
      }
    });
    
    function createAndHold(timeout) {
      return sequelize.transaction(transaction => {
        return M.create({ name: 'A' }, { transaction }).then(() => {
          return Sequelize.Promise.delay(timeout);
        });
      });
    }
    
    const M = sequelize.define('M', {
      name: Sequelize.STRING
    });
    
    sequelize
      .sync({ force: true })
      .then(() => {
        return Sequelize.Promise.all([
          createAndHold(5000),
          createAndHold(100)
        ]);
      })
      .then(() => {
        return M.findAll({ raw: true });
      })
      .then(results => {
        console.log(results);
      });
    TypeError: Cannot read property 'query' of undefined
        at parameters.length.Promise (/var/www/github/sequelize/lib/dialects/postgres/query.js:65:53)
        at Query.run (/var/www/github/sequelize/lib/dialects/postgres/query.js:65:9)
        at Promise.try.then.connection (/var/www/github/sequelize/lib/sequelize.js:558:20)
    From previous event:
        at retryParameters (/var/www/github/sequelize/lib/sequelize.js:555:8)
        at /var/www/github/sequelize/node_modules/retry-as-promised/index.js:39:21
        at retryAsPromised (/var/www/github/sequelize/node_modules/retry-as-promised/index.js:29:10)
        at Sequelize.query (/var/www/github/sequelize/lib/sequelize.js:454:12)
        at QueryInterface.rollbackTransaction (/var/www/github/sequelize/lib/query-interface.js:1449:36)
        at Transaction.rollback (/var/www/github/sequelize/lib/transaction.js:93:8)
        at connectionPromise.then.then.then.then.then.catch.setupErr (/var/www/github/sequelize/lib/transaction.js:128:31)
    From previous event:
        at Transaction.prepareEnvironment (/var/www/github/sequelize/lib/transaction.js:128:13)
        at Sequelize._clsRun (/var/www/github/sequelize/lib/sequelize.js:997:26)
        at Function._clsRun (/var/www/github/sequelize/lib/sequelize.js:1042:21)
        at Sequelize.transaction (/var/www/github/sequelize/lib/sequelize.js:996:22)
        at createAndHold (/var/www/github/sequelize/sscce.js:12:20)
        at sequelize.sync.then (/var/www/github/sequelize/sscce.js:28:7)
        at runCallback (timers.js:672:20)
        at tryOnImmediate (timers.js:645:5)
        at processImmediate [as _immediateCallback] (timers.js:617:5)
    From previous event:
        at Object.<anonymous> (/var/www/github/sequelize/sscce.js:25:4)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Module.runMain (module.js:604:10)
        at run (bootstrap_node.js:383:7)
        at startup (bootstrap_node.js:149:9)
        at bootstrap_node.js:496:3
  20. papandreou commented on Feb 16, 2018

    @papandreou
    Contributor

    @sushantdhiman, yes, @holm's fix does prevent the error in my test case.

  21. holm commented on Feb 16, 2018

    @holm
    Contributor

    Just to clarify. My PR will avoid the unhandled rejection, but the underlying reason for the connection not being established will not be fixed. However that rejection cause should still be returned directly from the main transaction promise.

    I think it is likely that there is no one reason for that across all the problems reported here, but it does remove the noise of the unhandled rejection. I guess for the timeout case it could be an option to catch the error from the pool and rethrow some other error. I am not sure how much that actually helps though.

  22. gabegorelick commented on Feb 16, 2018

    @gabegorelick
    Contributor

    I think application is running out of connections as defined by pool configuration thus unable to acquire new connection because all other open connections are busy right now.

    @sushantdhiman In this case, does Sequelize not retry the request? How should application code deal with full connection pools?

  23. sushantdhiman commented on Mar 20, 2018

    @sushantdhiman
    Contributor

    🎉 This issue has been resolved in version 4.37.3 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

  24. sushantdhiman commented on Mar 20, 2018

    @sushantdhiman
    Contributor

    In this case, does Sequelize not retry the request? How should application code deal with full connection pools?

    @gabegorelick Sorry for really late reply, but here goes

    This is handled by acquire timeout, if application is fully utilizing pool and new connection is demanded then node-pool decide as maximum number of resources are being used let wait till acquire timeout. If any resource get released before first Resource Timeout is triggered that resource is allocated to next waiting client.

    As you can see when pool is already full there is no need for creating new connection, pool is already at its limits. Only thing pool can do is to wait for any resource to get released.

    In your application you can deal with this situation by setting acquire above your average transaction runtime

  25. gabegorelick commented on Mar 22, 2018

    @gabegorelick
    Contributor

    Still seeing this error for other cases. I filed #9218 to track.

  26. PaulMest commented on Mar 6, 2019

    @PaulMest

    My team was getting this error, but it was due to our own misuse -- we accidentally nested a transaction inside an object.

    Here's a sample:

    // BAD
    sequelize.transaction(async (transaction) => {
      models.File.create(fileInfo, {transaction: {transaction}});
    }

    Note that the transaction is inside an unnecessary object. It should look like this:

    // GOOD
    sequelize.transaction(async (transaction) => {
      models.File.create(fileInfo, {transaction: transaction});
    }
  27. marcogrcr commented on Aug 26, 2020

    @marcogrcr
    Contributor

    For people experiencing issues in AWS Lambda, I have created a pull request that documents how to properly configure sequelize for Lambda. Hopefully you'll be able to see it in https://sequelize.org/master/manual/aws-lambda.html once it gets merged. In the meantime, please check #12642 out and provide feedback if you find any inaccuracies or space for improvement.

  28. mor-ndiaye commented on Nov 29, 2020

    @mor-ndiaye
    // GOOD
    sequelize.transaction(async (transaction) => {
      models.File.create(fileInfo, {transaction: transaction});
    }

    Work well for me. Thanks man.

  29. vatsalpatel68 commented on May 8, 2021

    @vatsalpatel68
    //Use Managed Transaction instead of Unmanaged transaction.
    sequelize.transaction(async t => {})
    
  30. mauro-n commented on Jun 20, 2024

    @mauro-n

    after being stuck on this for 1 hour i found that i forgot to add await before sequelize.transaction() and was passing a promise bogos

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