SQL Server database access issue from AWS Lambda - node.js

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.

Related

SSL Routines error when connecting to local DB

So I have this piece of code that is responsible for checking if a connection is valid:
const sequelize = new Sequelize(req.body.database, req.body.user, req.body.password, {
host: req.body.host,
dialect: 'mssql',
port: req.body.port,
dialectOptions: {
options: {
encrypt: true,
}
}
});
sequelize.authenticate().then((err) => {
res.send('Connected');
})
.catch((err) => {
console.log(err.message)
res.send(err.message);
});
This worked perfectly when I was connecting to a local DB on my network. However, when I was trying to connect to a DB through a VPN (simulating a local network) I got the following error:
Failed to connect to 10.1.90.20:1433 - 4C300000:error:0A000102:SSL
routines:ssl_choose_client_version:unsupported
protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1983:
I read somewhere that adding
cryptoCredentialsDetails: {
minVersion: 'TLSv1'
}
in the options will resolve this but it just gave me a new error:
Failed to connect to 10.1.90.20:1433 - 70290000:error:0A0C0103:SSL
routines:tls_process_key_exchange:internal
error:c:\ws\deps\openssl\openssl\ssl\statem\statem_clnt.c:2255:
Any idea how to fix this?
Keep in mind that both Databases are local however one of them is on a remote network accessible through SSL VPN.

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
}

How to handle error of closed MySQL connection in Node.js?

I've built a Node.js API that connects to a MySQL database. I use node-mysql2 as driver. The API and the database run in separate Docker container. At some point after deployment in a Kubernetes cluster I get the following error:
Error: Can't add new command when connection is in closed state
at PromiseConnection.query (/usr/src/app/node_modules/mysql2/promise.js:92:22)
I wonder why this error happens and how to catch and handle it using Node.js. These are code snippets of my Node.js API:
const mysql = require('mysql2/promise')
...
async function main() {
try {
const client = await mysql.createConnection({
host: DATABASE_HOST,
port: DATABASE_PORT,
user: DATABASE_USERNAME,
password: DATABASE_PASSWORD,
database: DATABASE_NAME
})
client.on('error', error => {
process.stderr.write(`${error.code}\n`) // PROTOCOL_CONNECTION_LOST
process.stderr.write(`An error occurred while connecting to the db: ${error.message}\n`)
process.exit(1)
})
} catch (error) {
process.stderr.write(`Error while creating db connection: ${error.code}\n`)
}
...
}
...
main().catch(err => {
process.stderr.write(`Error message: ${err.message}\n`)
process.exit(1)
})
Do you have an idea how to handle this error?
Do you close the connection after finishing with it?
client.end();
Also considered using a pool?
const pool = mysql.createPool({
host: DATABASE_HOST,
user: DATABASE_USERNAME,
database: DATABASE_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
More info about pools: https://github.com/sidorares/node-mysql2#using-connection-pools

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.

Sequelize connection and logging issues

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);
});

Resources