Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-mysql2 using conn.release() vs conn.end()

Tags:

node.js

Looking at Async/Await example here :

https://github.com/sidorares/node-mysql2/blob/master/documentation/Promise-Wrapper.md

the author uses c.end()

   let mysql = require('mysql2/promise');
   let pool = mysql.createPool({database: test});
   // execute in parallel, next console.log in 3 seconds
   await Promise.all([pool.query('select sleep(2)'), pool.query('select sleep(3)')]);
   console.log('3 seconds after');
   await pool.end();
   await conn.end();

However, just a few lines above, he uses conn.release()

pool.getConnection()
     .then((conn) => {
       var res = conn.query('select foo from bar');
       conn.release();
       return res;
     })

What is to be used once we are done using the connection object ?

should it be conn.release() or conn.end() ?

like image 832
runtimeZero Avatar asked Sep 28 '16 15:09

runtimeZero


1 Answers

Those examples aren't meant to be doing the same thing. And also, the first example (in your code) references a variable (conn) that it never uses. I think that's just a mistake in the example code.

The first example shows how to create a pool, run two concurrent queries (using the pool), wait for all queries to finish, and then clean up. Like I said before, conn.end() just doesn't make sense there.

The second example shows you how to request a free connection from the pool, use that connection to run a query (represented by the promise res), return the connection to the pool (by calling conn.release()), then propagate the result down the promise chain.

The second example can be rewritten to this:

let conn = await pool.getConnection();
let res  = conn.query('select foo from bar');

conn.release();

let result = await res;

So, conn.release() is used to release a connection back to the connection pool. It doesn't close the connection, it merely makes it available to be used for other queries.

conn.end() (I assume) closes the connection, and I guess you should only call it when you explicitly created the connection yourself (unlike connections retrieved from the pool, which should be managed by the pool).

like image 162
robertklep Avatar answered Oct 19 '22 19:10

robertklep