-
-
Notifications
You must be signed in to change notification settings - Fork 618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error: Can't add new command when connection is in closed state #939
Comments
+1 we have been getting this issue since yesterday. Error: This socket has been ended by the other party followed by Error: Can't add new command when connection is in closed state |
we too :[ |
Same issue here, the only hack is to stop and restart the node app... |
Same issue here, please tell me how we can resolve it |
Anyone found a fix for this? |
Any news on this problem ? After connection timed out, it cannot be restored at all - as all activity related to network side is performed in constructor. Also, this error is returned as text message only, no codes provided. Is it safe just to recreate connection object ? Actually it's very pour idea, as connection instance is passed to many structures in the program... |
Still an issue, anyone found any solution for this? |
me too |
I got this as well |
Hey @Coder77 @jovemnf @ovidiu-balau @Akash0333 @zebullax and everyone else experience issue - is there a reliable way to reproduce? Ideally dockerized self contained , or at least sequence of instructions |
It's extremely easy to reproduce - just start a connection and wait for default timeout (you can emulate it changing default mysql timeout setting to some smaller value - by default it's around 8 hours). Btw, I tested it not on pool, but with raw connection - in this case error object is empty at all, only text message is present. As I checked source code, seems this problem has no way to be solved in current state. When mysql connection is gone away, the network connection instance data inside the component is destroyed, so you cannot just restart the net - must create a new connection instance at all (network connection instance is created in the constructor !!!). |
Yes, individual |
But as I see previous messages, pool seems to have same problems ? The only way I found is just send stub queries every hour to keep connection alive. In the other case, I cannot even make correct destruction - it hangs forever, so must forget about the instance and create new one - rely that garbage collector makes it's job right. |
Unless I'm mistaken, issue is not limited to single connection but also connection managed by pool (that s what I was using as a setup), and that would make sense since the pool is only managing creating and yielding connection, if an existing connections has been remotely closed, and is yielded by the pool, we get the same error that if we were working with a simple connection |
I'm happy to try to investigate, if I have simple way to reproduce with pool that would help me a lot
In the case of pool it's different in terms of who is responsible for tracking and recycling of dead connection. Pool should do it all for you while when you use individual connection you must listen for error ( both on connection and on query results ) |
having the same problem with pooled connections. Our code looks pretty much like in the docs https://github.com/mysqljs/mysql#pooling-connections. The most logic is simple (get new Connection from permanent Pool, query it, release it). |
I'm using a single connection and after the connection is lost con.end() or con.release() throws the error. if (con) con=null |
I have the same problem |
Mee toO! any fix ? |
Guys I'm having the same issue. |
Me too. |
Switching to createPool resolved my issue. |
@jmordica What do you mean by switching to createPool? That is what I am using and I am getting this problem. Also that is what Rakeshvishnoi029's initial code used. Are you passing something special as an option? |
Hi @jmordica I have the same issue. Can you please tell how did you get it fix? Thx
|
I have same issue! |
any update for this issue ? i got the same problem. Thanks, |
Same issue here, using createPool. Any updates on this?
at least update the docs to remove the misleading information that pool handles this for you. |
@davehorton unfortunately not enough information to debug. Can you make a test repo to reproduce? This can happen if you call |
(EDIT: I see that I was running an old version of the package (1.7.0). I tried upgrading to the newest vesrion. I don't know if there is any difference yet) I too get this error from time to time. I haven't investigated the problem in detail, but it seems to occur every couple of days, and lasts untill the app is restarted. The connection pool is created with:
The error occurs when I run: The error says: |
In my case, I perform insertMany exceed 30,000 records at one time. I resolved my issue by increase |
@HsinHeng interesting, maybe that can be solved at driver level. We should be able to automatically detect mysql2 does support large incoming packet sizes ( see node-mysql2/lib/packet_parser.js Lines 83 to 97 in 442d304
max_allowed_packet can be automatically sent at connection but if not still can be queried using .query()
|
@HsinHeng what was exactly error code in your case? Having some help in error message would be useful I guess. Something along the lines |
@sidorares Here is my error details. "name":"SequelizeDatabaseError","parent":{"code":"ER_NET_PACKET_TOO_LARGE","errno":1153,"sqlState":"08S01","sqlMessage":"Got a packet bigger than 'max_allowed_packet' bytes" } Hope you could resolve this issue. |
@HsinHeng well in your case error text from the server already had some hints What we can do is have |
Still an issue, anyone found any solution for this? |
the same problem |
We also have this issue, when the connections in the connection pool are long in idle mode. Line 45 in 07a429d
The contents of the connection are as follows:
So the error seems to come in effect when the mysql server closes the connection "Connection lost: The server closed the connection.". Do you have any hints to prevent this? |
Same issue here |
Error: Can't add new command when connection is in closed state Same issue here, any suggestion ? |
Possible workaround could be to check if any of connection's properties _fatalError, _protocolError, _closing is true before executing the query and to get new connection. But that is ugly and looking for better solution, probably based on events. |
I solved this problem by refactoring my code to use pool.query (which releases connection internally) instead of using connection.query and releasing connection manually. Looks like there was a connection leak in my code. |
Do you have an example? I did the same thing using pool.query and it worked fine for much longer, but then it happened again. Did yours permanently fix? |
It didn't happen again in my case. Here is an example what was change: Old code: New code: |
Has anyone else been able to confirm that this works or found other fixes? I'll try refactoring my code anyways to test this out, but I would love to get more information if possible. I'm currently using mysql2's promise API to create the connection but also getting the same error: // connect to MySQL database
async function sql_connect() {
// connect to database
db = await mysql.createConnection({
host : 'localhost',
user : 'lucca',
password : process.env.MYSQL_PASSWORD,
database : 'tank_battle'
});
return db;
} |
Thanks for that. I changed my code to use promise pool and it seems to have resolved itself, but I'm still cautious. Thanks for showing me the snippet. |
I'll show you what is currently working for me: Database file:
Controller file snippet
I haven't had any issues ever in my local environment and the issue seems to have fixed on live server. Project is still in development so when I update live server with finished program I'll update if there is an issue. I also have a custom function set up to do multiple SQL statements in a loop, but I am going to remove it as promise pooling seems to work without issues now.
And use like this inside controller:
|
The socket it internally uses, has a |
Update: it works! Async/await connection pooling seems to have done the trick. For the first time, my server has been running for a whole day now without throwing any errors. If anyone's still having any issues, I suggest following irepela's and MaksemM's examples. My current setup is described below. First, I'm creating a connection pool with
// package imports
const mysql = require('mysql2/promise');
require('dotenv').config();
// exporting MySQL connection pool object
module.exports = mysql.createPool({
host: 'localhost',
user: 'lucca',
password: process.env.MYSQL_PASSWORD,
database: 'tank_battle',
waitForConnections: true,
connectionLimit: 20,
queueLimit: 0
}) Then, in my routes/middleware/APIs/whatever, I'm just importing the
const { private } = require('../middleware/private'); // -> custom middleware for private routes
const pool = require('../sql_util'); // -> creates connection pool (see above)
const jwt = require("jsonwebtoken"); // -> "jsonwebtoken" package from npm
// Express Router setup
const router = express.Router();
router.use(private);
// GET /user --> returns user information
router.get('/user', async (req, res) => {
const decoded = jwt.decode(req.token, {complete: true});
const name = decoded.payload.username.toString();
const sql = "select username, elo, lb_rank, tank_color from users where username=?"
try {
const [query_result, fields, err] = await pool.query(sql, [name]);
if (query_result.length > 0) {
const q = query_result[0]
// BinaryRow {
// username: 'Lucca',
// elo: 1000,
// lb_rank: 1,
// tank_color: #12fca7
// }
const userData = {
error: false,
name: q.username,
elo: q.elo,
lb_rank: q.lb_rank,
tank_color: q.tank_color
}
res.status(200);
res.json(userData);
return;
} else {
console.log('user not found');
res.status(404);
res.json({
error: true,
message: 'User not found'
});
return;
}
}
catch (e) {
res.status(500);
res.json({
error: true,
message: 'Server Error'
});
console.log(e);
return;
}
});
module.exports = router; |
I have come across the same error and found out that i have: The above mentioned behavior is common for all type of queries that share same connection object. Thanks. |
I am having the same issue (mysql 8 and knex.js with pool of connections) |
This is what I did to prevent this error from happening. I'm using async functions, so you may need to adapt this to your code, however, the important things to note are that you can check the const mysql = require('mysql2/promise');
const bluebird = require('bluebird');
let mysqlConnection = null;
const getMysqlConnection = async () => {
// Check to see if connection exists and is not in the "closing" state
if (!mysqlConnection || mysqlConnection?.connection?._closing) {
mysqlConnection = await createNewMysqlConnection();
}
return mysqlConnection;
}
const createNewMysqlConnection = async () => {
const connection = await mysql.createConnection({
host: process.env.MYSQL_HOST,
database: process.env.MYSQL_DATABASE,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
Promise: bluebird,
});
// You can do something here to handle the connection
// being closed when it occurs.
connection.connection.stream.on('close', () => {
console.log("MySQL connection closed");
});
return connection;
} Then in any functions that need access, just do const connection = await getMysqlConnection(); |
2 years, no solution, amazing why people still use this library?)))) |
Many people have already provided their own solutions on this issue thread, and most of them appear to work just fine. Could you at least read through a couple of them? |
yes, copy/paste the best solution, since 1950 ;) i think we did some progress at 2021, but looks like no))) Good i will copy paste code as all world. |
???????? <rant> Now, If you're so keen on figuring out stuff on your own, then by all means, feel free to keep banging your head on your keyboard while you sift through the meh-ish docs. Alternatively, you could save some time and frustration and take advantage of the work that the kind folks here have done for you by detailing their solutions to this, frankly, very dumb problem. Honestly, you won't be gaining much by not copying and pasting code from this thread. Since this discussion is incredibly unproductive, I'll shut up now. Sorry. |
While I don't have a good actual answer there are some useful proposals. If anyone wants to help to contribute there are some good ways do do so:
Closing the issue and locking comments, looks like discussion here does not add much value. = |
Hi
I fascing last 2 days this error please help me...
{ Error: read ETIMEDOUT
at TCP.onread (net.js:622:25)
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'read',
fatal: true }
{ Error: Can't add new command when connection is in closed state
at PoolConnection._addCommandClosedState
I use mysql 2 and connect Pool
var mysql = require('mysql2');
var mysqlPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'xyz',
database: 'xyz',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = mysqlPool;
55|| { Error: read ETIMEDOUT
55|| at TCP.onread (net.js:622:25)
55|| errno: 'ETIMEDOUT',
55|| code: 'ETIMEDOUT',
55| | syscall: 'read',
55|| fatal: true }
55|| { Error: Can't add new command when connection is in closed state
55| at PoolConnection._addCommandClosedState
The text was updated successfully, but these errors were encountered: