Sequelize connection and logging issues - node.js

I am trying to use Sequelize to connect with a SQL Server 2012 database. When my connection string was clearly wrong, I was seeing ECONN REFUSED messages and timeout. Now, I am not getting any response, despite logging on success and fail, per this code:
import * as Sequelize from 'sequelize';
-- connection string redacted
let seqConn = new Sequelize("mssql://**;Initial Catalog=**;Persist Security Info=True;Integrated Security=SSPI; User ID=**; Password=**")
seqConn
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
I was previously using the syntax:
let seqConn = new Sequelize("DB", "Username", "Password",
{
dialect: 'mssql',
dialectOptions: {
instanceName: 'dev'
},
host: '**'
};
But I couldn't find a setting for integrated security or other fancy SQL Server things.
Regardless, my current connection string isn't erroring. But also, it is not saying the connection was established.
I tried passing my seqConn to a model to use it to retrieve a model:
getModel(seqConn): void {
console.log("Getting");
var model = seqConn.define("dbo.Model", {
modelID: Sequelize.INTEGER,
modelNo: Sequelize.INTEGER,
modelName: Sequelize.STRING(50),
modelAge: Sequelize.DATE
});
seqConn.sync().then(function() {
model.findOne()
.then( function (modelRes){
console.log("got a result!?");
console.log(modelRes.get("modelName"));
})
.catch( function (error){
console.log("it didn't work :( ");
});
});
console.log('after getter');
return;
}
I'm not confident that this is the right way to use sequelize, and I'm still establishing my project structure, but for now I expect to either see a "got a result" or an error, but nothing is logging here from either the then() or the catch(). The before/after getter logs are logging fine.
I have considered that it takes a long time to connect, but my IT says that he saw my successful connection in our SQL logs, and previously I was getting timeouts in about 15,000 ms, I think.

The problem was solved by including another NPM module: `sequelize-msnodesqlv8'
And then the code to connect to Sequelize looked like:
var Sequelize = require('sequelize');
var seqConn = new Sequelize({
dialect: 'mssql',
dialectModulePath: 'sequelize-msnodesqlv8',
dialectOptions: {
connectionString: 'Driver={SQL Server Native Client 11.0};[REDACTED]'
}
});
seqConn
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});

Related

SQL Server database access issue from AWS Lambda

I'm getting this error while accessing SQL Server database from aws-lambda. Everything works fine from local machine.Only having access issue when executing the code from lambda.
ConnectionError: Failed to connect to 10.2.3.44\SQLSRVR code: ETIMEOUT
This is my code snippet, any help would be appreciated!
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('DBname', null, null, {
dialect: 'mssql',
host: '10.2.3.44', //MSSQL Server IP sample
dialectOptions: {
authentication: {
type: 'ntlm',
options: {
domain: 'addidas',
userName: "uname",
password: "pwd"
}
},
options: {
instanceName: 'SQLSRVR'
}
}
})
async function connect() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
connect();
It was because of the network restrictions only, as assumed. So had to assign lambdas in the same network which SQL server is hosted.
Thanks for all the suggestions.

Failed to connect to mydb.database.windows.net:1433 in 15000ms (Microsoft Azure SQL Database)

I am able to retrieve data from Microsoft Azure SQL Database using below code: -
const sql = require("mssql");
var config = {
user: "user_name",
password: "Pass#1234",
server: "mydb.database.windows.net",
database: "db_name",
options: {
enableArithAbort: true,
},
stream: true,
};
module.exports = function getQueryResult(query) {
return new Promise((res, rej) => {
sql.connect(config).then((pool) => {
pool.query(query, (err, result) => {
if (err) rej(err);
res(result);
});
});
});
};
I am using getQueryResult function to get the data from database.
Everything is going perfect accept the thing that the below errors occurs in between.
Failed to connect to mydb.database.windows.net:1433 in 15000ms (Microsoft Azure SQL Database)
ConnectionError: Failed to connect to mydb.database.windows.net:1433 read ECONNRESET
ConnectionError: Failed to connect to mydb.database.windows.net:1433 socket hang up
I know this question has been asked before. But I have tried all the solutions. None of the solution was specifically for Microsoft Azure SQL Database so I thought might be there is some problem in database.
Thanks in advance.
Your code is a bit different from mine, my options is enclosed in double quotes. You also can download my sample code, it works for me, I have test it.
Tips:
You need set the rule of Firewalls. Make sure your local or webapp can access dbserver.
My code:
const sql = require('mssql')
const config = {
user: 'username',
password: 'pwd',
server: '***sqlserver.database.windows.net', // You can use 'localhost\\instance' to connect to named instance
database: 'yourdb',
"options": {
"encrypt": true,
"enableArithAbort": true
}
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = {
sql, poolPromise
}

Exception handling not working for PG npm package

I installed "pg": "^8.0.2" and created the database.js file with database credentials. But no matter what go wrong it never enters in the catch block to show error. Instead it always logs connected to the database. Can anyone point out what I'm doing wrong. Thank You!
Database.js
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'roothjk',
host: 'localhost',
database: 'sf',
password: 'admin',
port: 5432
});
try {
pool.connect()
console.log('connected to the db');
} catch (e) {
console.log('Error connecting to db');
}
connect returns a Promise, and then you move to the next statement. Instead, you should use the then and cath methods:
pool.connect()
.then(c => console.log('connected to the db'))
.catch(e => console.log('Error connecting to db'));

Unable to use tedious with Azure database

I've a node application which do have a connection to SQL Server.
Also, I'm using database as a service from Azure.
Code Snippet :
import { Connection } from 'tedious';
import { Request } from 'tedious';
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
instanceName: 'SQLEXPRESS', // Removed this line while deploying it on server as it has no instance.
database: 'dbname'
}
};
connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log('error : '+err);
} else {
console.log("Connected to Database");
}
});
It has a successful connection, if done, locally.
Console Output => Connected to Database.
Deep dive done using console log :
-> Connection object is being created, but, the event ".on" is not being able to establish.
-> The connection gets established when deployed locally, while, when deployed on server, it doesn't works.
Based on the documentation here, you need to provide an additional option for encrypted connection.
Please try the following for config:
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
database: 'dbname',
encrypt: true //Need to add this for connecting to Azure DB
}
};
Using this configuration, I was able to connect to my database hosted in Azure.

how to catch Sequelize connection error

How to catch a sequelize connection error in case there is one?
I tried to do
var connection = new Sequelize("db://uri");
connection.on("error", function() { /* perhaps reconnect here */ });
but apparently this is not supported.
I wanted to do this because I think sequelize might be throwing an occasional unhandled ETIMEOUT and crashing my node process.
Currently I am using sequelize to connect a mysql instance. I only need it for like 2-3 hours and during that time I will be doing a many read queries. The mysql server will not be connected to anything else during that time.
Using sync() for this is considerably dangerous when using external migrations or when database integrity is paramount (when isn't it!)
The more up-to-date way of doing this is to use authenticate()
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
Using sequelize sync method provides an easy way to catch the error.
The then block handles a Successful connection and the catch handles the rejection.To get a detailed reason for a failure access the error object.
example: error.message e.t.c
Hope this helps.
sequelize.sync().
then(function() {
console.log('DB connection sucessful.');
}).catch(err=> console.log('error has occured'));
Use sequelize sync for that
var Sequelize = require('sequelize');
sequelize = new Sequelize(config.database, config.username, config.password, {
'host' : config.host,
'dialect' : config.dialect,
'port' : config.port,
'logging' : false
})
sequelize.sync().then(function(){
console.log('DB connection sucessful.');
}, function(err){
// catch error here
console.log(err);
});

Resources