Adam Halasz
Adam Halasz

Reputation: 58341

Node.js MySQL Connection Issue

What's the problem?

What I'm trying to do

// Connect Function
db.connect = function(callback){

    // Destory the Connection if there is already one
    if(db.connection) {
        console.log('[mysql]','connection destroy');
        db.connection.destroy();
        db.connection = null;

    }

    // Create the Connection
    db.connection = MySQL.createConnection(options);

    // Connect using the Connection
    db.connection.connect(function(error) {
        if(error){ 
            console.log('[mysql]', 'connect failed', error);
        } else {
            console.log('[mysql]', 'connection success');
            db.connection.database = options.database;
            callback(db.connection, error);
        }
    });

    // Listen on Connection Errors
    db.connection.on('error', function(error) {
        // Connection to the MySQL server is usually
        // lost due to either server restart, or a
        // connnection idle timeout (the wait_timeout server variable configures this)
        if(error.code === 'PROTOCOL_CONNECTION_LOST') { 
            console.log('[mysql]', 'PROTOCOL_CONNECTION_LOST')
            db.connect(callback);
        } else {                                    
            console.log('[mysql] Connection Error: ', error);               
        }
    });

    // Return Connection Instance
    return db.connection;
}

Additional Details

wait_timeout and interactive_timeout has to be set around 10 seconds in my.cnf to test the issue.

[mysqld]
wait_timeout = 10
interactive_timeout = 10

Upvotes: 1

Views: 2088

Answers (1)

Spidy
Spidy

Reputation: 23

The library is accidentally trying to write over the TCP socket after a FIN packet has been received, which means the TCP connection is half-closed by the other side. I'll fix this to give you a better error message, but it's still an error; either your network is killing your MySQL connections or something.

Are you using the connection pool? It looks like you are just making a query on a connection after some timeout according to the stack trace. It's possible you are holding onto an inactive connection too long and something on the network or MySQL server is ending the connection.

Upvotes: 1

Related Questions