How do we close the database connection in the below app.post. Do sequelize will automatically taken care of it ?
server.js
const sequelize = new Sequelize(DB_NAME, DB_USERNAME, DB_PASSWORD, {
host: DB_HOST,
dialect: DB_DIALECT,
pool: DB_POOL,
port: DB_PORT
});
const Availability = availabilitySchema(sequelize, DataTypes);
app.post('/service/availability', async (req, res) => {
try {
const userEmail = req.query.email;
const dailyStatus = req.body.dailystatus;
var playerData = {email:userEmail, dailystatus: dailyStatus};
const playerDailyStatus = await Availability.create(playerData);
res.status(200).json({ success: true });
} catch (e) {
res.status(500).json({ message: e.message });
}
});
As i understand it (and I only started looking at sequelize yesterday - comments if I'm wrong, please) Sequelize pools its connections, so there isn't really anything for you to close; it opens and closes connections as necessary much like any other ORM, and mostly those connections are open and live in a pool, are leased from the pool and do some work, then are returned to the pool. You can configure the pool options (looks like you already have) if you want to limit the number of concurrently open connections to your DB but if you're looking in your DB manager and seeing "omg, my sequelize appp has 5 open connections.. now it has 10.. now 15!" that's just how it is; it opens as many connections as necessary (up to the max) to service the workload and leaves them open because it's a huge waste of time to actually open (TCP connect) and close them constantly (TCP disconnect).
When using an ORM you don't micromanage the connections, you just carry out queries using the modeled objects and let the ORM deal with the low level stuff (opening and closing a connection is a level below crafting the SQL to run, and you hand that off to the ORM too). Even in something you've been used to elsewhere, like C# new SqlConnection("connstr").Open() might not actually be opening a TCP cnnection to the DB and closing it; it's probably just leasing and returning to a pool and the underlying framework manages the actual TCP connections and their state
Related
Currently I am experiencing a very frustrating issue with inserting data into my MySQL db using my NodeJS Express server.
My current setup is the following:
• MySQL server db on DigitalOcean droplet.
• NodeJS Express server on the same DigitalOcean droplet. It is being proxied by my Apache server that is on the same droplet. I keep Node server running with PM2.
I have been able to successfully read data from my db (i.e. SELECT * from performance);).
However, no matter what I try I cannot insert any data into my db. I have tried countless different solutions but none have worked.
Help would be greatly appreciated. Please ask any questions for further clarification if needed. Thank you.
My current code relating to MySQL:
server.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'analytics',
supportBigNumbers: true,
debug: true,
});
server.post('/performance', (req, res) => {
let d = req.body;
con.connect(function (err) {
if (err) throw err;
let q =
'INSERT INTO performance (uid, reqStart, resEnd, loadDuration) VALUES ?';
let values = []; // values to be inserted into db
// for testing purposes I have commented this out and tried inserting a hardcoded set of values instead
/*let body = JSON.parse(req.body); // json string body to json obj
body.data.forEach((x) => {
values.push([body.uid, x.reqStart, x.resEnd, x.loadDuration]);
});*/
values = [
[23299730, 8.3282343284, 8.121252244, 2.238932989],
[23288734, 8.3282343284, 8.121292244, 2.238932989],
];
con.query(q, [values], function (err, result) {
if (err) throw err;
});
});
res.send(d);
});
Update: I just ran my server manually (without PM2). This has allowed me to view console messages. For the first time I have seen a successful insert query. And upon running the server with PM2 I also get a successful query. However, on the second attempt I get PROTOCOL_ENQUEUE_HANDSHAKE_TWICE error.
Based on multiple other posts/articles I thought my code avoided this problem, but it's erroring on the line where I call con.connect(...). I have con.connect in a server.get route, but I haven't been hitting that endpoint at all.
After many hours of debugging, I think I found the problem.
Almost all tutorials showing how to connect to MySQL db using Node show that you should embed a con.query() call within a con.connect() call, and using connect() is recommended on MySQL docs.
However, con.query() also establishes a connection. Maybe it's because I am keeping the server live across multiple calls, but this results in the Handshake error I described in the post. Removing the wrapping con.connect() call fixed my problem.
I have two node microservices talking to one common mysql database. Both microservices have this below code to create a connection pool with a connectionlimit of 10 as follows:
// Initializing pool
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
port: '3306',
user: 'root',
password: 'root'
});
function addConnection(req, res) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
res.json({ "code": 500, "status": "Error" });
return;
}
connection.query("select * from user", function (err, rows) {
connection.release();
if (!err) {
res.json(rows);
}
});
connection.on('error', function (err) {
res.json({ "code": 500, "status": "Error" });
return;
});
});
}
For mysql database I have the max_connections set to 200(SHOW VARIABLES LIKE 'max_connections'; returns 200).
With the pool connectionLimit set to 10 for each of the microservice, in which cases or scenarios will the number of connections for any of the microservice will go above 10?
i.e. When and how the node services would be able to maintain more connections then expected?
If I have 3 instances running of same microservice then how does the pool connectionLimit works? What would be the limit of connections for each instance of microservice?
In one of the microservice say I have two apis which does database transactions and both connects to the database(getting connection) through two different functions having
same implementation of mysql.createPool({}) as above. What would happen if both apis are called concurrently and the number of requests made for each of them per second is 100 or more?
Will the number of connections made available be 10 or 20(since there are two mysql pools created with a connectionLimit of 10 each)?
Ideally it would not; but it can go above 10; if suppose some connections become stale i.e. they are closed from client end but are still open on Server end.
If you have multiple instances of same micro-service deployed in multiple VM or docker containers; they are like independent services.. and they have no connection among each other.. Hence, each of them will create its own 10 connection.
Firstly if u set connection pool limit as 10; that does NOT mean that during first moment 10 connections would be created.. While creating a pool; you also specify initial connection parameter suppose 5.. so, when service starts only 5 connections would be created.. and more created only when needed.. with UPPER Limit set as defined by parameter max_connections. Coming back to your question; well if you have NOT implemented synchronization etc. properly then yes it is possible that both pools will initialize their INITIAL_CONNECTIONS..
We are trying to create backend - RESTFUL api based on mysql DB - in express Nodejs. My boss (self acclaimed mysql guru) insist that we should use more connection pools than 1 - based on the different roles that users are grouped in.
So I need to define/create different connection pools in file B.js - > and make them as global variables so that I could access them later.
In file A.js I have a this route - in which looged in users will be able to call stored procedures with arguments. However, I would like to be able to define from which connection pool the connection will be called - in route itself (based on the session (req.user.role) variable).
So that:
pool1.getConnection(function(err,connection){
if (err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
console.log('connected as id ' + connection.threadId);
connection.query(query1, val, function (err, rows, fields) {
connection.release();
if(!err) {
var results = JSON.stringify(rows[0]);
console.log(results);
console.log(typeof(results));
console.log(rows[0][0]);
console.log(typeof(rows[0]));
res.send(JSON.stringify(results));
}
});
connection.on('error', function(err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
});
});
});
};
refers to pool1, but in case with other user -> pool1 should connect to other pool - defined in other files.
I hope I am clear with my issue.
You don't need to use global variables, you can export an object that holds each pool:
// B.js
module.exports = {
regular : mysql.createPool({ ... }),
admin : mysql.createPool({ ... }),
};
// A.js
const pools = require('./B');
...
let pool = pools[req.user.role];
if (! pool) {
throw Error('there is no pool for user role ' + req.user.role);
}
pool.getConnection(...);
So this declares two pools, one for "regular" users and one for "admin" users. It uses the value of req.user.role (which is assumed to contain one of two values: "regular" or "admin", but that's just for the purpose of this example) to pick the pool that should be used.
I'm not sure what the upside is of having more than one pool, unless they connect to two different databases or use different database credentials.
I don't know why you're doing this or your boss want to do this, more connection pools won't make the application more efficient, it just confuse people. Since the MySQL server has its limit of clients. And by the way, if you want to know a user's role, you have to connect the database and fetch the user data in the first place. Why don't you just use the same connection to do other things and that will be fine.
We have more than one UI developer, each develops one role so we don't want that all UI developers can see all store procedures... (That boss)
I'm trying to figure out what the best time to actually initialize connections for mysql in node is.
Am I supposed to create a pool of connections and then set them to some global so that all my models have access to the pool? Or am I supposed to initialize connections whenever I'm doing queries?(Seems bad).
I'm sure there's some "proper" way to do it, but I'm not really certain what the best way is.
If you are going to pool connections, then don't initialize connections right when they're needed. When not using a pool, you can just store connection information when your application is starting up, and use it when you need it:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret'
});
Then for single use cases:
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// we are done with the connection
connection.end();
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
If you're pooling, you should just create a connection pool when your application is starting and fetch connections when you need them. You should not make more than one pool.
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'example.org',
user: 'bob',
password: 'secret'
});
Then when you need a connection, you'd do something like this:
pool.getConnection(function(err, connection) {
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// we are done using the connection, return it to the pool
connection.release();
// the connection is in the pool, don't use it here
});
});
After more research, think I've figured out the right way.
1) Create a connection pool on app start
2) Include that file in your models.
3) Get a connection from the pool.
In the interest of keeping your code cleaner, I think you can also just invoke the pool object directly, according to the manual at https://github.com/felixge/node-mysql. This should abstract the logic for getting and releasing connections from the pool.
EG:
var result = yield pool.query("SELECT * FROM users");
(I'm using co-mysql with support for generators, but syntactically it should be the same w/out the callbacks)
I've begun playing around with Node.js lately, for many reasons but most importantly the ease at which I can write a chat-server utilising HTML5 WebSockets. However, I've been stuck for weeks with MySQL.
I'm currently using this MySQL client module: https://github.com/sidorares/nodejs-mysql-native
I've connected to the database and managed to store data using the following code:
// MySQL database
var db = require("mysql-native").createTCPClient(); // localhost:3306 by default
db.auto_prepare = true;
db.auth(dbName, dbUser, dbPass);
// Update the database
db.execute("UPDATE server_data SET value='" + new Date() + "' WHERE name='lastLoaded'");
How may I go about retrieving data from the database using a SELECT * FROM x WHERE y=z query?
Is there any specific reason you chose nodejs-mysql-native over node-mysql which is a really good node module. If there is none, then you should probably try node-mysql. I've tried it and it is great to start off using MySQL with Node. You could do something like:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'your_username',
password : 'your_password',
});
connection.connect();
connection.query("UPDATE server_data SET value=? WHERE name=?", [new Date(), 'lastLoaded'] function(err, result) {
if (err) throw err;
console.log('Result: ', result);
});
connection.end();
The advantage you get by using it this way is that you can prevent SQL injection, which is taken care of internally in node-mysql (by using the connection.escape() method).