Error cannot enqueue query after invoking quit

Hi I keep getting this error on my code and I don't know how to fix it I've tried a lot of things. I don't know but I think its a problem with connection.end() even with it I still get ...
var Winston           = require('winston'); // For logging
var SteamUser         = require('steam-user'); // The heart of the bot.  We'll write the soul ourselves.
var TradeOfferManager = require('steam-tradeoffer-manager'); // Only required if you're using trade offers
var config            = require('./config.js');
var fs                = require('fs'); // For writing a dope-ass file for TradeOfferManager
var mysql             = require('mysql');
var market            = require('steam-market-pricing');


var appid = {
    TF2:   440,
    DOTA2: 570,
    CSGO:  730,
    Steam: 753
};

var contextid = {
    TF2:   2,
    DOTA2: 2,
    CSGO:  2,
    Steam: 6
};



var logger = new (Winston.Logger)({
        transports: [
            new (Winston.transports.Console)({
                colorize: true, 
                level: 'debug'
            }),
            new (Winston.transports.File)({
                level: 'info', 
                timestamp: true, 
                filename: 'cratedump.log', 
                json: false
            })
        ]
});

// Initialize the Steam client and our trading library
var client = new SteamUser();
var offers = new TradeOfferManager({
    steam:        client,
    domain:       config.domain, 
    language:     "en", // English item descriptions
    pollInterval: 10000, // (Poll every 10 seconds (10,000 ms)
    cancelTime:   300000 // Expire any outgoing trade offers that have been up for 5+ minutes (300,000 ms)
});

client.logOn({
    accountName: config.username,
    password: config.password
});

client.on('loggedOn', function (details) {
    logger.info("Logged into Steam as " + client.steamID.getSteamID64());
});

client.on('error', function (e) {
    logger.error(e);
    process.exit(1);
});

client.on('webSession', function (sessionID, cookies) {
    logger.debug("Got web session");
    // Set our status to "Online" (otherwise we always appear offline)
    client.friends.setPersonaState(SteamUser.Steam.EPersonaState.Online);
    offers.setCookies(cookies, function (err){
        if (err) {
            logger.error('Unable to set trade offer cookies: '+err);
            process.exit(1); // No point in staying up if we can't use trade offers
        }
        logger.debug("Trade offer cookies set.  Got API Key: "+offers.apiKey);
    });
});

client.on('accountLimitations', function (limited, communityBanned, locked, canInviteFriends) {
    if (limited) {
        logger.warn("Our account is limited. We cannot send friend invites, use the market, open group chat, or access the web API.");
    }
    if (communityBanned){
        logger.warn("Our account is banned from Steam Community");
    }
    if (locked){
        logger.error("Our account is locked. We cannot trade/gift/purchase items, play on VAC servers, or access Steam Community.  Shutting down.");
        process.exit(1);
    }
    if (!canInviteFriends){
        logger.warn("Our account is unable to send friend requests.");
    }
});

offers.on('newOffer', function(offer) {
  var steamAccountID64 = offer.partner.getSteamID64();

  var connection = mysql.createConnection({
    host: '***********',
    user: '***********',
    password: '**********',
    database: '*************'
  });

    connection.query('SELECT COUNT(*) AS Total FROM incomingPlayers WHERE accountID=' + steamAccountID64, function(err, rows, fields) {


    if (rows[0].Total == 0) {

      if (offer.partner.getSteamID64() === config.admin || offer.itemsToGive.length === 0) {
        console.log(steamAccountID64);
        offer.accept(function(err) {
          if (err) {
            logger.error("Unable to accept offer " + offer.id + ": " + err.message);
          } else {
            logger.info("Offer accepted");
          }
        });

        var numberofitems = offer.itemsToReceive.length;

        for (var i = 0; i < numberofitems; i++) {

          if (offer.itemsToReceive[i].appid == "730") {

            var itemInfo = {
              itemName: offer.itemsToReceive[i].market_hash_name,
              assetID: offer.itemsToReceive[i].assetid,
              iconURL: offer.itemsToReceive[i].icon_url,
              accountID: steamAccountID64
            };

            connection.query('INSERT INTO incomingOffers SET ?', itemInfo);

            market.getItemPrice(730, 'MP9 | Storm (Minimal Wear)', function(err, data) {
                    connection.query("UPDATE incomingOffers SET itemValue='" + data.lowest_price.replace('$','') + "' WHERE assetID='4361351533'");
            });

            console.log(itemInfo.itemName + " of ID:" + itemInfo.assetID + " was accepted for trade by user : " + steamAccountID64);


          } else {
            console.log("Attempted to add item of appid: " + offer.itemsToReceive[i].appid);
          };

        };

        connection.query('INSERT INTO incomingPlayers SET ?', {
          accountID: steamAccountID64,
          itemCount: numberofitems
        });

      } else {

        offer.decline(function(err) {
          if (err) {
            logger.error("Unable to decline offer " + offer.id + ": " + err.message);
          } else {
            console.log("Trade was declined from " + offer.partner.getSteamID64() + ", user is not admin or sent dodgy offer");
          };
        });
      };
    } else {
      offer.decline(function(err) {
        if (err) {
          logger.error("Unable to decline offer " + offer.id + ": " + err.message);
        } else {
          console.log("Trade was declined from " + offer.partner.getSteamID64() + ", user already went in");
        };
      });

    };

  connection.end();
  });

});

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server
startup and use the connection/client object to query all the time.
You can listen on the error event to handle server disconnection and
for reconnecting purposes. Full code
here.


From:

  • Readme.md — Server disconnects:

    https://github.com/felixge/node-mysql#server-disconnects

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems,
the server timing you out, or the server crashing. All of these events
are considered fatal errors, and will have the err.code =
'PROTOCOL_CONNECTION_LOST'
. See the Error
Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is
done by establishing a new connection. Once terminated, an existing
connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool
freeing up space for a new connection to be created on the next
getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you’re experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

Содержание

  1. Cannot enqueue Query after invoking quit. #1296
  2. Comments
  3. Footer
  4. Node.js + mysql вложенные запросы, где ошибка?
  5. Error: Cannot enqueue Quit after invoking quit #238
  6. Comments
  7. Fixing Node Mysql “Error: Cannot enqueue Handshake after invoking quit.”
  8. Cannot enqueue Quit after invoking quit. #10
  9. Comments

Cannot enqueue Query after invoking quit. #1296

Hi I keep getting this error on my code and I don’t know how to fix it I’ve tried a lot of things. I don’t know but I think its a problem with connection.end() even with it I still get this error. If anyone could help me fix this that would be great.

This is the code:

The text was updated successfully, but these errors were encountered:

Hi! The error you provided is because you are chronologically calling connection.query() after you called connection.end() . I see that from the error, the particular call happening after the .end() call is coming from file C:UsersIainSteambotEditedBotJS.js , line 139. The code you provided is much shorter than 139 lines, so I don’t know which one is line 139 to give any pointers? Would you be willing to provide your entire, complete code, or point out which one line line 139?

Hi there! Thanks for the fast reply, this is line 139 from the code:

Thanks, any helpers would be much appreciated

Thanks for what the line is! In order to help at all, I would need to see the entire contents on the file, with the line pointed out on it, rather than just the single line out of context. Without fully understanding your code, there isn’t any guidance I can provide besides the explanation I provided above as to what the error means.

Sorry I was a little unclear, here is the full code from the file

Thanks! So the issue is that in your code, line 139 you are calling the .query() method chronologically after you called the .end() method. You’ll have to do a lot of refactoring to correct that (I wouldn’t have enough time to rewrite your code), but that’s the reason. This is because of how event loop-based systems function, as you are calling market.getItemPrice , which sets a function to run later in time, but then later down the file you call .end() right away. Then later, the market.getItemPrice callback is called and you’ve already ended the connection, so the inner .query() will fail.

Do you have any ideas about how to get it to run the function when it is listed in the loop, instead of running after it has ended. Sorry for the hassle I really appreciate your time!

Unfortunately to rewrite your code will take a lot of time. I can always put it on my to do list and see if I can get to providing you an example within the next 3 weeks sometime. In the meantime, you may want to read up on how to write Node.js code, how event loops works, and how to manage callback code flows and timings, which would hopefully clear up the answer for you. It’s understandable you don’t quite know the answer, though the issue is that it’s a question regarding basic Node.js programming, rather than anything that has to do with this module specifically.

I’ll see when I can find time to provide an exmaple of callback temporal management sometime in the next 3 weeks, stay tuned!

Thanks so much for the help, i’ll read up on this in the meantime and hopefully come up with an alternative at the moment. I’ll stay tuned!

I think the error comes up when you put your mysql db authentication stuff in an extra file, to get rid of it within every file, where you connect / query.

I just took my var connection = mysql.createConnection ( <. out of my routes and set up one file (db.js) containing the createConnection function call.
I used var connection=require(‘./db.js’); to import it. after that I got the same error. I guess the connection kind of gets screwed up.. one time I even had Cannot enqueue Handshake after invoking quit

now I’ve put my createConnection call back in my routes and everything is working — I just don’t like the idea that I have to copy that stuff in every route making a query to the db..

Hi @icphoton , I still have not yet had time to follow up, I’m sorry.

I see logical errors all over the code in regards to Asynchronous programming.

the creators of mysql need to check their code again. Once i commented out the connection.connect and connection.end functions, it started working again.

@gorkemt I think you don’t understand what conection.connect() is doing. It does not create new connection, connect() method only kicks off handshake sequence. Once .end() ed the connection object must be disposed, you can’t reconnect it ( just create a new one )

Turns out global variables stay with the same value across different Lambda executions, since they may run in the same container, so set the value of variables inside the exports.handler function and not in the global scope. So now I put const connection = mysql.createConnection( <inside the exports.handler function and I don’t get this MySQL connection errors.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Node.js + mysql вложенные запросы, где ошибка?

Подскажите в чем ошибка? Не могу понять, вроде бы правильный код, но второй запрос на срабатывает.
выдает ошибку: Cannot enqueue Query after invoking quit

Такую ошибку валит из второго запроса:
2Error while performing Query.Error: Cannot enqueue Query after invoking quit

  • Вопрос задан более трёх лет назад
  • 1398 просмотров

Но вообще зачем вам мускул на ноде? все эти запросы.. не лень их писать? проще монга, где использован тотже JS

Дмитрий Беляев: не для всего, а для ноды. Все ведь рекомендуют для пхп мускул, так и для ноды лучше монга.

Давайте не будем заводить спор про связаность и целосность, вы явно ничего не знаете о монге раз говорите про такие веши по отнолшению к монге, темболее вы явно не использовали монгу с нодой, раз вспоминаете про релативность в целом, вы еще вспосните о транзакциях, которые в монге кстати есть.

Однако, если вам есть что возразить всетаки, приведите реальный пример, для какой задачи будет более удобно использовать мускул+ноду, чем монго+ноду.

Источник

Error: Cannot enqueue Quit after invoking quit #238

I keep on getting this error although the migrations run smoothly. How do I get rid of this and whats the reason behind it ?

The text was updated successfully, but these errors were encountered:

Hi @gayanhewa
I can’t help you if you don’t specify what exactly the failure is plus, which version of node you use and a log from a run in the verbose mode (-v).

Also please add details about your configuration.

This is how the error looks like :

Output from the db-migration up -v

NPM Version — 1.4.28
DB-Migrate — ^0.9.7

Server : Ubuntu 14.04 -/ Vagrant instance.

Ok, in your last run you didn’t run into a failure. I must be able to reproduce this bug to fix it.
Cannot enqueue Query after fatal error. Sounds like there went something wrong just before, in the migration or the db connection itself.

Could you please also deliver your node.js version?

Can you provide me more to reproduce this? Migrations with which this error is raised for example?

How do I know for which migration this happened ? , I have a few migrations and it happens even if I run just one.

Does this happen with every of your migrations? Try up -count 1 and look if this happens to all migrations even if they’re started single.

Yes. if I use the flag -c 1 it will happen aswell , but just once.

Well I still can’t reproduce this, could you please post one of your migrations. Of course you should delete everything that’s maybe confidential.

I’m away for some hours now, so I wont answere from now on.

Please provide enough information to make it possible to anyone to reproduce your issue. Without the possibility to reproduce no one can help you and the bug keeps unsolved.

  • Used configuration tweaks.
  • How does db-migrate gets invoked
  • The full log of the full run where the error occurs in verbose mode, also including the queries generated. Replace confidential informations if needed.
  • Post your migrations

Also answere these common questions:

  • Do you have used db-migrate before?
  • Does this error exist in an earlier release?

Hi, Thank you for the help. Here is what I could gather from my findings :

The Error doesn’t result in a failure. Its more connected to node-mysql rather the db-migrate module.

I was able to come down to the point where , after the migration is processed and a onComplete call back attempts to close the connection with the db and if it is already close there will be an error popping out.

For now I can suppress the erros from here. But not ideal.

Could you show me this migration?

Normaly db-migrate shouldn’t execute this twice. And also shouldn’t write that much entries to the migrations table.

It definitely seems that you made a mistake in your migrations. I suspect you’re calling the callback multiple times, which you mustn’t do!

I do have the call back multiple times since within a migration I called createTable and addIndex

Источник

Fixing Node Mysql “Error: Cannot enqueue Handshake after invoking quit.”

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

I was using the popular Mysql module for Node.js which is node-mysql and everytime, after the first page load was encountering a weird error with full stack trace.

What’s the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Basically, the problem is that, if you’ve terminated an existing connection object then that cannot be re-connected afterwards.

So the solution is to call the createConnection method (followed by connect() ) to create a new connection whenever you have terminated the old/existing connection.

If you’re using the node-postgres module for postgresql support in Node, then you’ll have to do something similar, i.e., call the connect method with the connection string to create new connections if you terminate the old connection (during the previous process/request) by calling pg.end() or client.end() .

Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.

Источник

Cannot enqueue Quit after invoking quit. #10

I’m working to get backup for multi database in for loop, but i got this error.

`events.js:154
throw er; // Unhandled ‘error’ event
^
Error: Cannot enqueue Quit after invoking quit.
at Protocol._validateEnqueue (/home/mohammad/wallet_webservices/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/home/mohammad/wallet_webservices/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Protocol.quit (/home/mohammad/wallet_webservices/node_modules/mysql/lib/protocol/Protocol.js:88:23)
at Connection.end (/home/mohammad/wallet_webservices/node_modules/mysql/lib/Connection.js:242:18)
at /home/mohammad/wallet_webservices/node_modules/mysqldump/index.js:158:20
at /home/mohammad/wallet_webservices/node_modules/async/lib/async.js:52:16
at /home/mohammad/wallet_webservices/node_modules/async/lib/async.js:550:17
at /home/mohammad/wallet_webservices/node_modules/async/lib/async.js:544:17
at _arrayEach (/home/mohammad/wallet_webservices/node_modules/async/lib/async.js:85:13)
at Immediate.taskComplete (/home/mohammad/wallet_webservices/node_modules/async/lib/async.js:543:13)

The text was updated successfully, but these errors were encountered:

@pcnetsoft-projects i don’t have time to work on a feature to fix this today.
But this is a problem because the last patch, If you use the version 1.1.0 It will probably work just fine.

Thanks for the report, will looking on that soon.

@pcnetsoft-projects check out if this works for you.

Источник

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

I was using the popular Mysql module for Node.js which is node-mysql and everytime, after the first page load was encountering a weird error with full stack trace.

What’s the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue ......
    ...
    ...

Basically, the problem is that, if you’ve terminated an existing connection object then that cannot be re-connected afterwards.

So the solution is to call the createConnection method (followed by connect()) to create a new connection whenever you have terminated the old/existing connection.

If you’re using the node-postgres module for postgresql support in Node, then you’ll have to do something similar, i.e., call the connect method with the connection string to create new connections if you terminate the old connection (during the previous process/request) by calling pg.end() or client.end().

Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.

You can do something similar with the postgres module’s clients if you’re creating them manually using pg.Client. Although when using the built-in pool approach to serve web requests, call pg.connect() on every request and you should be fine. Just make sure you’ve attached an event handler on the error event to prevent Node from crashing if the postgres server stops/restarts for some reason.

Calling pg.connect() will retrieve an existing pooled client or create a new one ONLY if all the pooled clients are busy and the pool is NOT full.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Hi! The error you provided is because you are chronologically calling connection.query() after you called connection.end(). I see that from the error, the particular call happening after the .end() call is coming from file C:UsersIainSteambotEditedBotJS.js, line 139. The code you provided is much shorter than 139 lines, so I don’t know which one is line 139 to give any pointers? Would you be willing to provide your entire, complete code, or point out which one line line 139?

Hi there! Thanks for the fast reply, this is line 139 from the code:

 connection.query("UPDATE incomingOffers SET itemValue='" + data.lowest_price.replace('$','') + "' WHERE assetID='4361351533'");

Thanks, any helpers would be much appreciated

Thanks for what the line is! In order to help at all, I would need to see the entire contents on the file, with the line pointed out on it, rather than just the single line out of context. Without fully understanding your code, there isn’t any guidance I can provide besides the explanation I provided above as to what the error means.

var Winston           = require('winston'); // For logging
var SteamUser         = require('steam-user'); // The heart of the bot.  We'll write the soul ourselves.
var TradeOfferManager = require('steam-tradeoffer-manager'); // Only required if you're using trade offers
var config            = require('./config.js');
var fs                = require('fs'); // For writing a dope-ass file for TradeOfferManager
var mysql             = require('mysql');
var market            = require('steam-market-pricing');


var appid = {
    TF2:   440,
    DOTA2: 570,
    CSGO:  730,
    Steam: 753
};

var contextid = {
    TF2:   2,
    DOTA2: 2,
    CSGO:  2,
    Steam: 6
};



var logger = new (Winston.Logger)({
        transports: [
            new (Winston.transports.Console)({
                colorize: true, 
                level: 'debug'
            }),
            new (Winston.transports.File)({
                level: 'info', 
                timestamp: true, 
                filename: 'cratedump.log', 
                json: false
            })
        ]
});

// Initialize the Steam client and our trading library
var client = new SteamUser();
var offers = new TradeOfferManager({
    steam:        client,
    domain:       config.domain, 
    language:     "en", // English item descriptions
    pollInterval: 10000, // (Poll every 10 seconds (10,000 ms)
    cancelTime:   300000 // Expire any outgoing trade offers that have been up for 5+ minutes (300,000 ms)
});

client.logOn({
    accountName: config.username,
    password: config.password
});

client.on('loggedOn', function (details) {
    logger.info("Logged into Steam as " + client.steamID.getSteamID64());
});

client.on('error', function (e) {
    logger.error(e);
    process.exit(1);
});

client.on('webSession', function (sessionID, cookies) {
    logger.debug("Got web session");
    // Set our status to "Online" (otherwise we always appear offline)
    client.friends.setPersonaState(SteamUser.Steam.EPersonaState.Online);
    offers.setCookies(cookies, function (err){
        if (err) {
            logger.error('Unable to set trade offer cookies: '+err);
            process.exit(1); // No point in staying up if we can't use trade offers
        }
        logger.debug("Trade offer cookies set.  Got API Key: "+offers.apiKey);
    });
});

client.on('accountLimitations', function (limited, communityBanned, locked, canInviteFriends) {
    if (limited) {
        logger.warn("Our account is limited. We cannot send friend invites, use the market, open group chat, or access the web API.");
    }
    if (communityBanned){
        logger.warn("Our account is banned from Steam Community");
    }
    if (locked){
        logger.error("Our account is locked. We cannot trade/gift/purchase items, play on VAC servers, or access Steam Community.  Shutting down.");
        process.exit(1);
    }
    if (!canInviteFriends){
        logger.warn("Our account is unable to send friend requests.");
    }
});

offers.on('newOffer', function(offer) {
  var steamAccountID64 = offer.partner.getSteamID64();

  var connection = mysql.createConnection({
    host: '***********',
    user: '***********',
    password: '**********',
    database: '*************'
  });

    connection.query('SELECT COUNT(*) AS Total FROM incomingPlayers WHERE accountID=' + steamAccountID64, function(err, rows, fields) {


    if (rows[0].Total == 0) {

      if (offer.partner.getSteamID64() === config.admin || offer.itemsToGive.length === 0) {
        console.log(steamAccountID64);
        offer.accept(function(err) {
          if (err) {
            logger.error("Unable to accept offer " + offer.id + ": " + err.message);
          } else {
            logger.info("Offer accepted");
          }
        });

        var numberofitems = offer.itemsToReceive.length;

        for (var i = 0; i < numberofitems; i++) {

          if (offer.itemsToReceive[i].appid == "730") {

            var itemInfo = {
              itemName: offer.itemsToReceive[i].market_hash_name,
              assetID: offer.itemsToReceive[i].assetid,
              iconURL: offer.itemsToReceive[i].icon_url,
              accountID: steamAccountID64
            };

            connection.query('INSERT INTO incomingOffers SET ?', itemInfo);

            market.getItemPrice(730, 'MP9 | Storm (Minimal Wear)', function(err, data) {
                    connection.query("UPDATE incomingOffers SET itemValue='" + data.lowest_price.replace('$','') + "' WHERE assetID='4361351533'");
            });

            console.log(itemInfo.itemName + " of ID:" + itemInfo.assetID + " was accepted for trade by user : " + steamAccountID64);


          } else {
            console.log("Attempted to add item of appid: " + offer.itemsToReceive[i].appid);
          };

        };

        connection.query('INSERT INTO incomingPlayers SET ?', {
          accountID: steamAccountID64,
          itemCount: numberofitems
        });

      } else {

        offer.decline(function(err) {
          if (err) {
            logger.error("Unable to decline offer " + offer.id + ": " + err.message);
          } else {
            console.log("Trade was declined from " + offer.partner.getSteamID64() + ", user is not admin or sent dodgy offer");
          };
        });
      };
    } else {
      offer.decline(function(err) {
        if (err) {
          logger.error("Unable to decline offer " + offer.id + ": " + err.message);
        } else {
          console.log("Trade was declined from " + offer.partner.getSteamID64() + ", user already went in");
        };
      });

    };

  connection.end();
  });

});

Sorry I was a little unclear, here is the full code from the file

Thanks! So the issue is that in your code, line 139 you are calling the .query() method chronologically after you called the .end() method. You’ll have to do a lot of refactoring to correct that (I wouldn’t have enough time to rewrite your code), but that’s the reason. This is because of how event loop-based systems function, as you are calling market.getItemPrice, which sets a function to run later in time, but then later down the file you call .end() right away. Then later, the market.getItemPrice callback is called and you’ve already ended the connection, so the inner .query() will fail.

Do you have any ideas about how to get it to run the function when it is listed in the loop, instead of running after it has ended. Sorry for the hassle I really appreciate your time!

Unfortunately to rewrite your code will take a lot of time. I can always put it on my to do list and see if I can get to providing you an example within the next 3 weeks sometime. In the meantime, you may want to read up on how to write Node.js code, how event loops works, and how to manage callback code flows and timings, which would hopefully clear up the answer for you. It’s understandable you don’t quite know the answer, though the issue is that it’s a question regarding basic Node.js programming, rather than anything that has to do with this module specifically.

I’ll see when I can find time to provide an exmaple of callback temporal management sometime in the next 3 weeks, stay tuned!

Thanks so much for the help, i’ll read up on this in the meantime and hopefully come up with an alternative at the moment. I’ll stay tuned!

I think the error comes up when you put your mysql db authentication stuff in an extra file, to get rid of it within every file, where you connect / query.

I just took my var connection = mysql.createConnection ({.... out of my routes and set up one file (db.js) containing the createConnection function call.
I used var connection=require('./db.js'); to import it. after that I got the same error. I guess the connection kind of gets screwed up.. one time I even had Cannot enqueue Handshake after invoking quit

now I’ve put my createConnection call back in my routes and everything is working — I just don’t like the idea that I have to copy that stuff in every route making a query to the db..

Hi @icphoton , I still have not yet had time to follow up, I’m sorry.

I see logical errors all over the code in regards to Asynchronous programming.

the creators of mysql need to check their code again. Once i commented out the connection.connect and connection.end functions, it started working again.

console.log('connection is created');
        //connection.connect();
        connection.query('call getcurrentitems()', function (err, rows, fields) {
            if (err) {
                //connection.end();
                next(err, null);

            } else {
                if (rows.length > 0) {
                    //connection.end();
                    console.log(rows.length);
                    console.log('The solution is: ', rows[0]);

                    next(null, rows);
                }
                else {
                    //connection.end();
                    console.log('No records found')
                }
            }

            //connection.end();
        });

@gorkemt I think you don’t understand what conection.connect() is doing. It does not create new connection, connect() method only kicks off handshake sequence. Once .end() ed the connection object must be disposed, you can’t reconnect it ( just create a new one )

Turns out global variables stay with the same value across different Lambda executions, since they may run in the same container, so set the value of variables inside the exports.handler function and not in the global scope. So now I put const connection = mysql.createConnection({ inside the exports.handler function and I don’t get this MySQL connection errors.

More on the matter:
https://forums.aws.amazon.com/thread.jspa?threadID=223230

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server
startup and use the connection/client object to query all the time.
You can listen on the error event to handle server disconnection and
for reconnecting purposes. Full code
here.


From:

  • Readme.md — Server disconnects:

    https://github.com/felixge/node-mysql#server-disconnects

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems,
the server timing you out, or the server crashing. All of these events
are considered fatal errors, and will have the err.code =
'PROTOCOL_CONNECTION_LOST'
. See the Error
Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is
done by establishing a new connection. Once terminated, an existing
connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool
freeing up space for a new connection to be created on the next
getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you’re experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

Error Background:
When the database operation is performed for the first time, it is successful. The second time a database operation is performed, an error is reported as shown in the title.
The reason:
This is because after we close the connection with the.end() method, we need to re-call createConnection to recreate a connection.
Solutions:
For example, the following encapsulates a method that operates on database queries and additions. Each time a new connection is created using mysql.createconnection () before the database operation is performed, instead of putting it directly to the outermost layer.

var mysql  = require('mysql');  
exports.find=function(findSql,callback){
    var connection = mysql.createConnection({     
        host     : 'localhost',       
        user     : 'root',              
        password : '123456', 
        port: '3306',                   
        database: 'namesharing',
    });
    connection.connect();
    connection.query(findSql,function (err, result) {
        if(err){
          console.log('[SELECT ERROR] - ',err.message);
          return;
        }
        connection.end();
        callback(result)
    });
}


exports.insert=function(addSql,addSqlParams,callback){
    var connection = mysql.createConnection({     
        host     : 'localhost',       
        user     : 'root',              
        password : '123456',       
        port: '3306',                   
        database: 'namesharing',
    });
    connection.connect();
    connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
            console.log('[INSERT ERROR] - ',err.message);
            return;
        }
        connection.end();
        // console.log('INSERT ID:',result);  
        callback(result)
    });
}

Read More:

Понравилась статья? Поделить с друзьями:
  • Error cannot enqueue query after fatal error
  • Error cannot enqueue handshake after invoking quit
  • Error cannot enqueue handshake after already enqueuing a handshake
  • Error cannot determine path to tools jar library for 16
  • Error cannot delete branch test checked out at