Connection Pooling in Nodejs (Using sequelize) - javascript

I write the code below. According to my understanding the "max:" in pool shows the max number of connection we can create in pool. So if I set the value of max as 0. Then it should not established any connection. I just want to clarify this.
var sequelize = new Sequelize(
process.env.DATABASE_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD, {
pool:{
max: 0,
min: 0,
idle: 10000,
acquire:30000
},
logging: console.log("connection created"),
host: process.env.DATABASE_HOST,
dialect: 'mysql',
operatorsAliases: false
}
);

I have no idea about Sequelize but simply we can create a connection this way.I think this will be little bit helpful for you.
/**
* create connection pool
*/
var con = mysql.createPool({
connectionLimit: 100000,
host: 'enter host',
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME
});
con.getConnection(async function(err, connection) {
let result=connection.query('SELECT * FROM table_name');
console.log(result);
if(err) throw err;
})

what's wrong with the way they have it set up in their examples exactly?
const sequelize = new Sequelize(config.db.uri, {
pool: {
max: 100,
min: 0,
idle: 10000,
},
dialectOptions: {
ssl: config.db.ssl,
},
// logging: logger.debug.bind(logger),
});
the models utilize it on their own... what am i missing here?

For "sequelize": "^5.21.3", you can't set pool.max to 0 anymore. If you do this, sequelize will throw an error:
max must be an integer > 0

Related

Timezone Issue In Sequelize Nodejs

I want Sequelize to use my local time for reading and writing to database.
in Sequelize config file I added timezone: "+04:30", but it is just for writing in database.
for writing in database when i add
dialectOptions: {
useUTC: false, // -->Add this line. for reading from database
},
i get this error :
Ignoring invalid configuration option passed to Connection: useUTC. This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection
full config file :
const Sequelize = require("sequelize");
const sequelize = new Sequelize("db", "root", "", {
dialect: "mysql",
port: process.env.SQL_PORT,
host: "localhost",
charset: "utf8",
collate: "utf8_persian_ci",
logging: false,
dialectOptions: {
useUTC: false, // -->Add this line. for reading from database
},
timezone: "+04:30",
});
Finally I fixed it by getter in my model:
createdAt: {
type: Sequelize.DATE,
defaultValue: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
get: function () {
var isoDateString = new Date(this.getDataValue("createdAt"));
return new Date(
isoDateString.getTime() -
isoDateString.getTimezoneOffset() * 60 * 1000
);
},
},
and change my config file to :
const Sequelize = require("sequelize");
const sequelize = new Sequelize("db", "root", "", {
dialect: "mysql",
port: process.env.SQL_PORT,
host: "localhost",
charset: "utf8",
collate: "utf8_persian_ci",
logging: false,
timezone: "+04:30",
});

knex broken after upgrading from Node.js v12 to Node.js v16.4.0

I'm experiencing below error after upgrading to Node.js v16.4.0 (from Node.js v12).
I'm using knex to connect to db (postgres) and using ORM - objection.js.
KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
Please help to resolve!
import Knex from "knex";
const getConnection = () => {
try {
return Knex({
client: 'pg',
connection: {
user: 'user',
password: 'password',
host: 'dbhost',
port: 5432,
database: 'dbname',
},
pool: {
min: 0,
max: 10,
idleTimeoutMillis: 10000,
acquireTimeoutMillis: 30000,
},
acquireConnectionTimeout: 2000,
});
}
catch (err) {
throw err;
}
}
const getTransaction = () => {
const con = getConnection();
const trx = con.transaction();
return trx;
}
Having had the same issue, I traced the problem to an old version of the "pg" package.
Doing
npm i pg#latest
fixed it

Conditionally Assign const value in js

I'm trying to assign a different value to sequelize based on whether the app is running locally or on the server. This is my code:
const sequelize = production
? sequelizeHeroku.connect(Sequelize)
: new Sequelize(database, user, password, {
host,
dialect: "mysql",
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
This doesn't work locally, as when I log the value of sequelize it is false. However, if I try to assign the variable like this:
const sequelize = new Sequelize(database, user, password, {
host,
dialect: "mysql",
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
it works just fine. I also checked that console.log(production == true) prints out false. What am I doing wrong?
It's better to use NODE_ENV environment variable. E.g.
index.ts:
import { Sequelize } from 'sequelize';
import assert from 'assert';
const database = 'sample';
const user = 'testuser';
const password = 'testpass';
const host = '127.0.0.1';
const sequelize =
process.env.NODE_ENV === 'production'
? 'sequelize heroku'
: new Sequelize(database, user, password, {
host,
dialect: 'mysql',
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000,
},
});
assert(process.env.NODE_ENV === 'production', 'NODE_ENV should be "production"');
assert(sequelize === 'sequelize heroku', 'Should use heroku sequelize in production environment');
Execute code in production environment:
NODE_ENV=production npx ts-node ./index.ts
No assertion failed. It works as expected.

Too many connection error in mysql - Nodejs & Mysql?

I am using nodejs-v9.2.0 and mysql in my application.
Error:
code: 'ER_CON_COUNT_ERROR'
errno: 1040
NPM Modules:
Mysql
Mysql wrapper
Code:
var mysql = require('mysql');
var pool = mysql.createPool({
canRetry: true,
database: "dbname",
host: "host",
user: "user",
password: "password",
connectionLimit: 100,
supportBigNumbers: true,
bigNumberStrings: true,
charset: 'utf8mb4_unicode_ci',
multipleStatements: true,
debug: true
waitForConnections: true,
queueLimit: 0
});
pool.on('connection', (connection) => {
connection.on('error', (err) => {
connection.release();
});
connection.on('close', (err) => {
console.error(new Date(), 'MySQL close', err);
});
});
var createMySQLWrap = require('mysql-wrap');
var sql = createMySQLWrap(pool);
Note:
I have noticed an open issue in the mysql npm github.
Any work around to solve this issue?
Any suggestion will be grateful

How to export database connection string node / node.js

I am trying to turn the following database connection string into a module:
require('dotenv').load();
var knex = require('knex')({
client: 'pg',
connection: {
host: 'localhost',
user: process.env.DB_USER,
password: process.env.DB_USER_PASSWORD,
database: process.env.DB_NAME
},
pool: {
min: 0,
max: 7
}
});
So far I tried:
require('dotenv').load();
module.exports = {
knex : require('knex')({
client: 'pg',
connection: {
host: 'localhost',
user: process.env.DB_USER,
password: process.env.DB_USER_PASSWORD,
database: process.env.DB_NAME
},
pool: {
min: 0,
max: 7
}
})
}
In my app.js file:
var knex = require('./models/database');
knex.select().table('users').then(function(result) {
result.forEach(function(value) {
console.log(value.first_name);
});
});
This returns the error 'knex' is undefined. I think the way my module is being exported is incorrect... can someone help?
Thank you!
It's because you're exporting an object containing knex.
Either add knex to the require:
var knex = require('./models/database').knex;
or change your export to
module.exports = require('knex')({ ... })

Categories

Resources