Mysql connection after release in node.js + mysql pool - mysql

I cannot understand why could I connect to Mysql after release.
And is there a way to check the status of Mysql ?
Thanks for the help !
var mysqlConfig = {
host : "abcd",
port : "3306",
user : "root",
password : "root",
database : "test"
};
var pool = mysql.createPool(mysqlConfig);
pool.getConnection(function(err, conn) {
// release pool
conn.release();
// After release, Why could I connect to Mysql ????
conn.query('SELECT * FROM user_info WHERE user_id = ?', [id], function(err, rows) {
if (err) {
pushErr();
}
// ...
});
});

Based on the documentation here: https://github.com/felixge/node-mysql it looks like the connection being 'released' doesn't destroy the connection per se, it just signals the pool that it can be used by someone else if needed. If you notice the example, they release as part of the query callback. If you need to actually get rid of the connection, you should use conn.destroy().

Related

Proper Implementation of Multi Tenancy in Node Application

I currently have to decide how to implement multi tenancy with my node application the best way possible.
For now, I have got my common_db_connection where I have a lookup table in which I can query the tenant database name for each specific user.
I have a resolver function which uses the users ID to get the tenant database name and finally return the my mysql connector.
My solution looks like this:
var conn_common_db = mysql.createPool({
connectionLimit : 150,
host : 'localhost',
user : 'root',
password : '',
database : 'common_db'
});
function conn_resolver(req) {
conn_common_db.query("SELECT tenant_db_name from tenants where tenant_uid = (SELECT tenant_uid from tenant_user where user_uid = ?)",
[requst.session.user_uid], function(err, result) {
if(!err) {
tenant_db_name = result[0].tenant_db_name
return mysql.createPool({
connectionLimit : 150,
host : 'localhost',
user : 'root',
password : '',
database : tenant_db_name
});
}
else{
console.log(err)
return null;
}
})
}
app.get('/', function(request, response) {
conn_resolver(req).query("SELECT * FROM user", function(err, result) {
if(!err) {
console.log(result)
}
else{
//res.send(err)
}
})
});
Is this the right way to do this and is it safe to do it like this?
Thanks in advance!
Actually no. You either need to set up a pool per tenant or just a singular connection each time.
The concept of a pool is to have a reusable connection that is already connected to the database. The next tenant will be connected to the wrong database. So you will have to recreate the pool as each tenant tries to connect to their database. You could create a pool per tenant or just do a connection on the fly.

NodeJS MySQL - How to know connection is release or not

I am developing NodeJS + MySQL web API.
I am using mysql npm module.
I want know connection is release or not is there any function or variable.
Like
if(!connection.isRelease() OR !connection.isClose() OR !connection.end()) {
connection.release();
}
Is there any specific function to know connection is release or not?
I am getting error like "connection already release"
You can check if the connection is in the pool to see if it was released. The index in the free connections will be -1 if the connection is not released. Here is an example.
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : ''
});
pool.getConnection(function(err, connection) {
connection.query( 'SELECT something FROM sometable', function(err, rows) {
console.log(pool._freeConnections.indexOf(connection)); // -1
connection.release();
console.log(pool._freeConnections.indexOf(connection)); // 0
});
});
Just in case you don't have access to the pool you can also do this:
connection._pool._freeConnections.indexOf(connection)
This will give you the same answer as the accepted answer.

Node.js mysql query response delay

I am using node.js mysql driver. But when the server under high load, i guess mysql is doing queue for queries. How can I prevent this? I want to do query instantly.
How can I resolve this? My queries are laggy.
My code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'ip',
user : 'db',
password : 'pass'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.query('USE db');
connection.query({ sql:"select token,COUNT(token) as sayim from tokens where username=? or anon=?", timeout: 10000},[data,data],function(err,info) {
if (info[0].sayim != 0) {
callback(info[0].token);
}else{
callback("0");
}
});
Ps: The server is not returning any error for this. But when I do a query, server is responding after approximately 10 seconds. If server is not under the high load it is responding instantly.
You could use PoolConnection instead.
var connection = mysql.createPool({
host : 'ip',
user : 'db',
password : 'pass',
database : 'db'
});
Another thing that comes to mind: In your example, you use asynchronous functions one after the other which should cause you some troubles as well.

How to configure custom database Mysql in Auth0 Connection?

I'm using auth0 as my authentification services into my project. I really love it, but I have a problem when using custom database(MySql), I sure that I have configured the db.connection parameter to my remote shared hosting database in Plesk. It always show : "[Error] Script execution did not complete within 20 seconds. Are you calling the callback function?", When I trying to run "Create" script.
here the script :
function create (user, callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.23.16',
user : 'user',
password : 'pass',
port : '3306',
database : 'dbname' });
connection.connect();
var query = "INSERT INTO users SET ?";
var insert = {
password: bcrypt.hashSync(user.password, 10),
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
}
What should I'm doing right now to solve this problem? I'm new to this
Thanks..
Regards,
fxbayuanggara
You're trying to connect to a local IP address (192.168.23.16), which will always fail since database scripts and rules are executed from Auth0's servers. You'll need to make your MySQL server accessible from Auth0's IP addresses, which at the time of writing are the following:
US domains: 138.91.154.99, 54.221.228.15, 54.183.64.135, 54.67.77.38, 54.67.15.170, 54.183.204.205, 54.173.21.107, 54.85.173.28
EU domains: 52.28.56.226, 52.28.45.240, 52.16.224.164, 52.16.193.66

Pooling keeps incrementing connections and ends up in ER_CON_COUNT_ERROR

I have a class called Connection like one below. This only executes select statements. I have non pooling connection for insert or update.
var _mysql = require('mysql');
function Connection()
{
//private variables and dependencies includes
//create mysql pool connection requires nodejs mysql this connection is used only for selects.
var _connectionSelect = _mysql.createPool({
host : _config.mySQLDB.select.dbHost,
user : _config.mySQLDB.select.dbUser,
password : _config.mySQLDB.select.dbPass,
database : _config.mySQLDB.select.dbName,
supportBigNumbers : true,
connectTimeout : 7000,
connectionLimit : 5,
queueLimit : 5
});
this.executeSelect = function(sql, callback, Message)
{
//connects to mysql.
_connectionSelect.getConnection(function(connectionError, Connection){
if(connectionError)
{
console.log(connectionError);
//throws error if connection or sql gone wrong
Message.add("error", 'serviceDown');
Message.add("devError", 'unknownError');
callback(false);
}
else
{
//executes the query passed
Connection.query(sql, function(error, rows) {
Message.incerementQuery();
if(error)
{
Connection.release();
console.log(error+sql);
//throws error if connection or sql gone wrong
Message.add("error", 'unknownError');
Message.add("devError", "seriousError", "Database errors at resource server side");
callback(false);
}
else
{
Connection.release();
//executes the callback function
callback(rows);
}
});
}
});
};
}
exports.Connection = Connection;
I created an instance of this class whenever I want to execute a query.
I am aware that the default concurrent connections in MySQL is 100 and I wanted to keep that number.
Whenever I try running my application, this connection pooling is incrementing every select and reaches 100 connections pretty soon.
As you can see I am releasing the connection on success or error states. I am pretty sure that I must be doing something wrong, but difficult to figure out.
Is it because how I create instances of this class? I was hoping that if I supply
connectionLimit : 5
even if I create many instances of this class it should only utilise 5 connection?
Note: I have only one instance of this app in my local machine.
Sorry to be so amateur, I am new to this streaming I/O business. I love the idea of pooling but if I cant sort this out, I may need to use traditional open and close connection for every query . Any help would be much appreciated.
Many thanks,
Karthik
Got the answer from Doug Wilson from git hub https://github.com/dougwilson.
I should have instantiated createPool outside of the function. Works like a charm.
The code goes like
var _mysql = require('mysql');
//create mysql pool connection requires nodejs mysql this connection is used only for selects.
var _connectionSelect = _mysql.createPool({
host : _config.mySQLDB.select.dbHost,
user : _config.mySQLDB.select.dbUser,
password : _config.mySQLDB.select.dbPass,
database : _config.mySQLDB.select.dbName,
supportBigNumbers : true,
connectTimeout : 7000,
connectionLimit : 5,
queueLimit : 5
}
function Connection()
{
//private variables and dependencies includes
);
this.executeSelect = function(sql, callback, Message)
{
//connects to mysql.
_connectionSelect.getConnection(function(connectionError, Connection){
if(connectionError)
{
console.log(connectionError);
//throws error if connection or sql gone wrong
Message.add("error", 'serviceDown');
Message.add("devError", 'unknownError');
callback(false);
}
else
{
//executes the query passed
Connection.query(sql, function(error, rows) {
Message.incerementQuery();
if(error)
{
Connection.release();
console.log(error+sql);
//throws error if connection or sql gone wrong
Message.add("error", 'unknownError');
Message.add("devError", "seriousError", "Database errors at resource server side");
callback(false);
}
else
{
Connection.release();
//executes the callback function
callback(rows);
}
});
}
});
};
}
exports.Connection = Connection;
Thanks a lot. Sorry to be so stupid.
Karthik