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

Missing "connection state"

Open EWalkerDev opened this issue 7 years ago • 4 comments

"connection.state" seems to be available, I wanted to test https://stackoverflow.com/questions/34542902/nodejs-mysql-how-to-know-connection-is-release-or-not

EWalkerDev avatar Aug 27 '18 00:08 EWalkerDev

Can you describe your use case? Why do you need this state flag?

sidorares avatar Aug 27 '18 00:08 sidorares

I use it one time by day (will change in the future). I don't know howto avoid this error

Promise { <pending> }
CRON for sending power to DATABASE done...
/home/pi/ProjetJS/velbusLib/node_modules/mysql2/promise.js:93
    const localErr = new Error();
                     ^

Error: Can't add new command when connection is in closed state
    at PromiseConnection.query (/home/pi/ProjetJS/velbusLib/node_modules/mysql2/promise.js:93:22)

droumanet avatar Sep 03 '22 12:09 droumanet

"closed" is not the same as "idle pool connection", closed means that underlying tcp connection is closed because of COM_CLOSE client command ( via connection.end() ) or server closing its side of connection

I'd recommend reviewing how you handle errors so that your code is discarding connection after fatal error, but state is based on this check: https://github.com/sidorares/node-mysql2/blob/3a250e51d20507be3293bbdeedbcb50811d23a3e/lib/connection.js#L168 you can probably replicate it in your code with something like conn.addCommand === conn.__addCommandClosedState ( this is not documented api, might be changed in the future )

sidorares avatar Sep 04 '22 08:09 sidorares

I have a Jest unit test that does this with mysql:

expect( iConn.state ).toBe( 'authenticated' );

What should I use instead with mysql2?

ghost avatar Sep 22 '22 01:09 ghost

I have a Jest unit test that does this with mysql:

expect( iConn.state ).toBe( 'authenticated' );

What should I use instead with mysql2?

Digging through the code I determined that connection.authorized === true works as a replacement for connection.state === "authorized".

ghost avatar Sep 30 '22 18:09 ghost