CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 63 forks source link

Using a query in a pool the program hangs #86

Closed vgaltes closed 6 years ago

vgaltes commented 6 years ago

Hi,

I'm sure I'm doing something wrong but when I execute this simple code using a pool it hangs (if I use a connection it finishes correctly).

#! /usr/bin/env node
"use strict"

const program = require('commander');
const pkg = require('./package.json');
const mysql = require('promise-mysql');

program
    .version(pkg.version)
    .command('run')
    .action(run);

program.parse(process.argv);

function scalar (databaseConnection, query, selector) {
  let connection;

  let pool = mysql
    .createPool({
      host: databaseConnection.host,
      user: databaseConnection.user,
      password: databaseConnection.password,
      database: databaseConnection.database
    });

  return pool.query(query)
    .then(rows => {
      return rows[0][selector];
    })
    .catch(error => {
      console.log(error);
      return 'CONNECTION FAILURE';
    });
};

function run(){
  const connection = {
        host     : 'host',
        user     : 'user',
        password : 'password',
        database : 'database'
      };

  const query = 'SELECT 1 + 1 AS solution';

  return scalar(connection, query, 'solution').then(s => {
    console.log(`Solution is ${s}`);
  }).catch(e =>  console.log(e));
}

What am I doing wrong?

Thanks,

vgaltes commented 6 years ago

Should I call pool.end() at the end of my program?

CodeFoodPixels commented 6 years ago

I believe that calling pool.end() at the end should solve this

vgaltes commented 6 years ago

Yes, thanks!

bdmason commented 6 years ago

EDIT: I've moved the below issue to #90

I've got a similar problem, in that my connection hangs only every now and again. I'm exporting my pool and using it in a bunch of routes, so calling pool.end() closes the pool before any of the routes can use it.

In the mysql error log I get:

[Note] Aborted connection 3018 to db: myDb' user: 'myUsr' host: 'localhost' (Got an error reading communication packets)

My pool is exported like this:

const mysql = require("promise-mysql");

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  connectionLimit: 10
});

module.exports = pool;

There are very few mysql connections on the server, and the issue is rare - one in every several dozen database queries hangs and logs the above error.

I'm on Ubuntu 16.04, and typing mysql --version prints:

mysql  Ver 14.14 Distrib 5.7.22, for Linux (x86_64) using  EditLine wrapper

And all my databases are InnoDB. I'm struggling to see what I've got wrong. Is there anything in the above that stands out?