How to close mySql query connection in nodejs - mysql

I am using raw mySql query for my development.
I want to close the query connection after executing the query.
What can I use as per my code?
My Connection Sample:
const Sequelize = require('sequelize')
const dotenv = require('dotenv');
dotenv.config();
const sequelize =
new Sequelize(process.env.DBNAME, process.env.DBUSER, process.env.DBPASS,
{
host: process.env.HOST,
port: process.env.HOST_PORT,
dialect: 'mysql',
operatorsAliases: 0,
timezone: "+06:00",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
}
}
)
module.exports = sequelize;
My Query sample:
const dbConnect = require('../database/db');
let getEmployeeData =
await dbConnect.query(
`Select * From employee where employeeId = '00001'`,
{type: QueryTypes.SELECT});
return res.json({data: getEmployeeData});
Before return I want to close my query connection. As I am getting error "packets_out_of_order" after idle the connection in nodejs, so I decide to test by closing the connection.
Thanks in advance...

You can try with
dbConnect.end();

Related

Using mysql pool with async\await | nodeJS

I am using mysql2 with nodejs and currently using simple connection like the following:
mysql.ts
const Connect = () => {
if (!connection)
return mysql.createConnection(params);
return connection;
};
someQuery.ts
const connection = Connect();
const asyncQuery = util.promisify(connection.query).bind(connection);
Now, after a while that the server is running the app just crashes because of the connection loss, I read some online and understood that in order to solve it and also as a better practice I should use a connection pool.
The thing is that I haven't really found anything that works like the above with async-await.
Does anyone have a solution for this?
await asyncQuery('query here');
i had a project last year, where i used the mysql2/promise library.
connector.js
const mysql = require('mysql2/promise');
const con = mysql.createPool({
host: "localhost",
user: "root",
password: "pw",
database: "database",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = con;
queries.js
const db = require('../helpers/mysql/connector');
getAnything: async () => {
try {
let anything = await db.execute("SELECT * FROM anything");
return colos[0];
} catch (e) {
console.log(e);
return null;
}
},

How to renew connection of database for iam authentication

Using IAM database authentication the password expires after about 15 minutes. So I ideally have to renew the database connection before the password expires. I set up a timer on the first initialization of the database and query the passed time on each query. How can i refresh the password of the connection before the password expires? Or how can i destroy the old database object and renew the object if necessary?
The error message is: "PAM authentication failed for user iam_user".
code for getting IAM Password:
const pgp = require('pg-promise')();
const AWS = require('aws-sdk');
const ca =
'-----BEGIN CERTIFICATE-----\nMIID9DCCAtyg...
...wZfTUU=\n-----END CERTIFICATE-----\n';
const signer = new AWS.RDS.Signer({
region: process.env.REGION,
username: process.env.DATABASE_USER,
hostname: process.env.DATABASE_HOST,
port: parseInt(`${process.env.DATABASE_PORT}`, 10),
});
module.exports = pgp({
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USER,
ssl: { ca },
dialectOptions: { ssl: { require: true } },
password: signer.getAuthToken(),
});
injecting db object to graphql:
const db = require('../db/init');
server.use(
mount(
'/graphql',
graphqlHTTP( () => ({
schema: schema,
context: { startTime: Date.now(), db },
graphiql: true
})),
),
);
Using the database in the resolvers.
I could query the time of the creation of the database connection. Is there a possibility to renew the password if necessary? Or what is the best way to destroy the old database object and create a new database object?
const resolvers = {
Query: {
Post: (root, args, {db}) => {
console.log(args.id);
console.log(db.$config.options)
const postQuery = new PQ({
text:
'SELECT post_id as id FROM tbl_post where post_id = $1',
values: [parseInt(args.id, 10)],
});
return db.one(postQuery).catch((err) => console.log(err));
}
}
As suggested by vitaly-t i used a password function. To avoid adding latency this functions renews the password only every 15 minutes. If the pool gets continuously used in intervals lower than 10 seconds, than the connection stays open without calling the password function at all. According to my tests there are no new connections to the database opened at all.
const ca = '-----BEGIN CERTIFICATE-----\9DC...-----END CERTIFICATE-----\n';
const signer = new AWS.RDS.Signer({
region: process.env.REGION,
username: process.env.DATABASE_USER,
hostname: process.env.DATABASE_HOST,
port: parseInt(`${process.env.DATABASE_PORT}`, 10),
});
const SIGNER = { time: 0, password: undefined};
function getSignedPassword() {
const time = Date.now();
if (time - SIGNER.time > 900000) {
SIGNER.time = new Date().getTime();
SIGNER.password = signer.getAuthToken();
return SIGNER.password;
}
return SIGNER.password;
}
module.exports = pgp({
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USER,
ssl: { ca },
password: getSignedPassword,
});

Node.js script does not end when using await on sequelize.athenticate()

This is the code I'm using to start Sequelize and authenticate. I need to await the authenticate() method to make sure database is ready to be used by other app components:
'use strict';
(async () =>
{
let Sequelize=require('sequelize');
let seq = new Sequelize('admin_apptoolset', 'root', 'root',
{
host: 'localhost',
dialect: 'mysql',
operatorsAliases: false,
pool:
{
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
console.log("Trying to connect to database...");
await seq.authenticate();
console.log("Connected to database...");
return;
})()
I can see how both console logs are dumped to the console but the process doesn't exit after the return. Shouldn't it work?
Thanks in advance.
You need to disconnect from database, because it's prevent event loot from exit.
Add seq.close(); before return;
(async () => {
let Sequelize = require("sequelize");
let seq = new Sequelize("admin_apptoolset", "root", "root", {
host: "localhost",
dialect: "mysql",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
console.log("Trying to connect to database...");
await seq.authenticate();
console.log("Connected to database...");
seq.close(); // close connection
return;
})();

How to get the mysql connection for mysql-session (not the Sequelize instance)?

I already have the Sequelize instance, but I need to get the mysql connection for mysql-session.
This is how the Sequelize instance looks like:
var Sequelize = require('sequelize');
var sequelize = new Sequelize( 'db_name', 'root', '',
{
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
}
}
);
module.exports = sequelize;
I use Passport.js for the authentication system, but as database, I use mysql. Therefore, I am working with Sequelize module.
I want to do something like this:
var connection = mysql.createConnection(options);
var sessionStore = new MySQLStore({}/* session store options */, connection);
But since I use Sequelize, I do not want to use the mysql.createConnection method but to get the db connection object from the sequelize object (instance of Sequelize).
How to get the mysql connection for express-mysql-session (not the Sequelize instance)?

Why is testing a sequelize connection to MySQL causing timeout?

New to node and making a generic express application that connects to MySQL db using sequelize. Doing some unit tests on the db connection with jasmine-node and I keep getting timeouts when i try to connect with sequelize.
// Test the MySQL connection
describe("MySQL", function() {
it("is connectable", function(next) {
var mysql = require('mysql');
var dbconfig = require('../config/database');
var connection = mysql.createConnection(dbconfig.connection);
connection.connect(
function(err, db) {
expect(err).toBe(null);
connection.end();
next();
}
);
});
it("is connectable using sequelize", function(next){
var dbconfig = require('../config/database');
var Sequelize = require('sequelize');
var sequelize = new Sequelize(dbconfig.connection.database, dbconfig.connection.user, null,
function(err, db){
expect(err).toBe(null);
sequelize.close();
next();
}
);
});
});
Of the two tests above, the first passes fine, but the test for sequelize times out. Here is the what I get on the console.
Failures:
1) MySQL is connectable using sequelize
Message:
timeout: timed out after 5000 msec waiting for spec to complete
Stacktrace:
undefined
Finished in 6.267 seconds
Here is the database config file.
// config/database.js
module.exports = {
'connection': {
'dialect': 'mysql',
'user': 'root',
'password': '',
'host': 'localhost',
'port' : '3306',
'database': 'my_node_db'
}
};