0

I have an application nodejs running on top of a pm2.

My application has a strange behavior where I can not identify the problem, for some time running, 3 4 or 5 days the application when trying to do a simple login where it needs a connection with the database the following error occurs:

Can not enqueue Query after fatal error

I have done everything possible to try to identify the cause of this problem, and it has not been identified a drop in the database server.

Someone could try to help, maybe it's the way that getting the connection to the bank is wrong.

Database connection configuration db.js

const mysql = require('mysql');

const connection = mysql.createConnection({
    connectionLimit : 20,
    host     : '******',
    port     : 3306,
    user     : '******',
    password : '******',
    database : '******'
});

connection.connect(function(err) {
    if (err) {
        console.log('Conexão com banco ocorreu erro. ' + err + ' ' + err.code);
        return;
    }
    console.log('Conexão com banco ok!');
});

module.exports = connection;

route usuario

var express = require('express');
var router = express.Router();

var usuarioController  = require('../controllers/usuario-controller');

router.get('/find/:id', usuarioController.findUsuario);

module.exports = router;

usuarioController

var db = require('../models/db');

var usuarioController = {


    findUsuario: function(req, res) {

        var codigoPessoa = req.params.id;

        var sql = "SELECT p.codigoPessoa As codigo, "+
                  "  p.nome AS nome "+
                  "  FROM tpessoa p, "+
                  "      tusuario u "+
                  "  WHERE p.codigoPessoa = u.codigoPessoa "+
                  "  AND u.codigoPessoa = " + codigoPessoa;

        db.query(sql, function (err, rows) {
            if (err) {

                var message = err.message;

                return res.status(500).send(message);

            } else {

                res.status(200).json(rows);
            }
        });
    },
};

module.exports = usuarioController;

Error

Error: Connection lost: The server closed the connection.
    at Protocol.end (/home/softaction/apps_nodejs/node_modules/mysql/lib/protocol/Protocol.js:112:13)
    at Socket.<anonymous> (/home/softaction/apps_nodejs/node_modules/mysql/lib/Connection.js:97:28)
    at Socket.<anonymous> (/home/softaction/apps_nodejs/node_modules/mysql/lib/Connection.js:502:10)
    at emitNone (events.js:111:20)
    at Socket.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at args.(anonymous function) (/opt/nvm/versions/node/v8.11.3/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:138:29)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
Error: Cannot enqueue Query after fatal error.
    at Protocol._validateEnqueue (/home/softaction/apps_nodejs/node_modules/mysql/lib/protocol/Protocol.js:200:16)
    at Protocol._enqueue (/home/softaction/apps_nodejs/node_modules/mysql/lib/protocol/Protocol.js:138:13)
    at Connection.query (/home/softaction/apps_nodejs/node_modules/mysql/lib/Connection.js:200:25)
    at Strategy._verify (/home/softaction/apps_nodejs/security/autenticacao.js:66:16)
    at Strategy.authenticate (/home/softaction/apps_nodejs/node_modules/passport-local/lib/strategy.js:88:12)
    at attempt (/home/softaction/apps_nodejs/node_modules/passport/lib/middleware/authenticate.js:361:16)
    at authenticate (/home/softaction/apps_nodejs/node_modules/passport/lib/middleware/authenticate.js:362:7)

My database connection configuration file is in a separate folder in the project.

Example:

-app
--models
---db.js
--controllers
---usuario-controller.js
--routes
---usuario-route.js
Ger
  • 583
  • 2
  • 13
  • 35

3 Answers3

0

The common way to handle this with seems to use a pool of connections.

You can see examples based on the same problem you have in this post. One of the answers there shows a way to override the query method so that you don't need to rewrite each call with getConnection/release.

You can probably test this with a local DB:

  • start the DB
  • start the server
  • try a login (or a mocked route that queries something)
  • ensure it works
  • kill/restart the DB
  • try the route again
  • ensure you have the same error
  • implement the solution based on the link above
  • test again and check the problem is gone
Stock Overflaw
  • 3,203
  • 1
  • 13
  • 14
  • Thanks for the response @Stock Overflaw, I'll do the tests and post the results. – Ger Feb 26 '19 at 16:32
  • It worked perfectly, thank you very much for the help. I did according to the post that indicated, the guys are grade 10 – Ger Feb 26 '19 at 23:05
0

I had this same problem, found this, tested it, and it worked. It's an NPM module called serverless-mysql.

Taylor Evanson
  • 384
  • 4
  • 16
0

Use createPool for making connection.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54