node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

2 consecutive getConnection() call to promise pool, returning the same connection (same thread ID)

Open joseph423 opened this issue 4 years ago • 2 comments

I have the following .js file to wrap mysql2 library and added some logics to initialize the connection.

db.js

// Database (MySQL)
// get the client
import mysql from 'mysql2/promise';
import { prettyPrint } from './common.js';

let pool;

const connect = () => {
  // Create the connection pool. The pool-specific settings are the defaults
  const poolOptions = {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0,
  };
  prettyPrint({ poolOptions });

  pool = mysql.createPool(poolOptions);

  pool.on('connection', function (err) {
    if (err.code) {
      console.log('error code', err.code); // 'ECONNREFUSED'
      console.log('error fatal', err.fatal); // true
    }
  });

  pool.on('enqueue', function () {
    console.log('Waiting for available connection slot');
  });

  pool.on('acquire', function (conn) {
    console.log('Acquired connection ', conn.threadId);
  });

  pool.on('release', function (conn) {
    console.log('connection release', conn.threadId);
  });
};

const getConn = async () => {
  return await pool.getConnection();
};

const foundRow = async conn => {
  const [rows, fields] = await conn.query(`SELECT FOUND_ROWS();`);

  console.log({ rows });

  return rows[0]['FOUND_ROWS()'];
};

export { pool, connect, foundRow, getConn };

Later I added a test.js to run the following snipet

const conn1 = await db.getConn();
const conn2 = await db.getConn();
prettyPrint({
  conn1: conn1.threadId,
  conn2: conn2.threadId,
});

It prints out the same connection thread ID, is it normal? I thought the conn1 will acquired one of the connection, then conn2 will create a new one.

joseph423 avatar Dec 06 '22 12:12 joseph423

can't reproduce, I'm getting 2 sequential ids, not the same. Please double check you don't have typos

sidorares avatar Dec 08 '22 06:12 sidorares

Getting expected response:

Acquired connection  8139
Acquired connection  8140
{ conn1: 8139, conn2: 8140 }

trasherdk avatar Dec 26 '22 11:12 trasherdk