AWS RDS MS SQL Unable to connect - sql-server

I am trying to connect to my newly created ms sql database. However, I am getting an error when I try to connect. Error : Unable to connect to the database: { SequelizeConnectionError: Failed to connect to ....
const sequelize =new Sequelize({
dialect: 'mssql',
dialectModulePath: 'tedious',
dialectOptions: {
driver: '**SQL Server Native Client 11.0 - is this correct?**',
instanceName: '**where do i get this?**'
},
host: '**what do i put for this?'is this the end point?**',
port: '1433',
username: 'username',
password: 'password,
database: '**what do i put for this?**',
pool: {
min: 0,
max: 10,
idle: 10000
}
});

dbname is the name of the database you're interacting with (you entered this into aws)
also make sure you did npm install tedious -S
const sequelize =new Sequelize('dbname', 'dbusername', 'dbpassword', {
host: 'http://endpoint-from-aws.com'
dialect: 'mssql',
operatorsAliases: false,
pool: {
min: 0,
max: 10,
idle: 10000
}
});
http://docs.sequelizejs.com/manual/installation/getting-started.html

const sequelize = await new Sequelize(database, user, password, { host: 'rds-end-point', dialect: 'mysql' });

Related

Knex not able to connect with azure-active-directory-password

I have a project using Objection.js and Knex.
I am trying to connect to a database that is hosted in Azure and uses Azure Active Directory to authenticate.
objection: 3.0.1
knex: 2.2.0
My understanding is Knex uses Tedious to build the connection to the database. Looking into the github I am referencing this document for connection properties.
https://github.com/knex/knex/blob/master/lib/dialects/mssql/index.js
const cfg = {
authentication: {
type: settings.type || 'default',
options: {
userName: settings.userName || settings.user,
password: settings.password,
domain: settings.domain,
token: settings.token,
clientId: settings.clientId,
clientSecret: settings.clientSecret,
tenantId: settings.tenantId,
msiEndpoint: settings.msiEndpoint,
},
},
server: settings.server || settings.host,
options: {
database: settings.database,
encrypt: settings.encrypt || false,
port: settings.port || 1433,
connectTimeout: settings.connectionTimeout || settings.timeout || 15000,
requestTimeout: !isNil(settings.requestTimeout)
? settings.requestTimeout
: 15000,
rowCollectionOnDone: false,
rowCollectionOnRequestCompletion: false,
useColumnNames: false,
tdsVersion: settings.options.tdsVersion || '7_4',
appName: settings.options.appName || 'knex',
trustServerCertificate: false,
...settings.options,
},
};
Looking into Tedious it looks like the connection can be setup with these settings:
https://tediousjs.github.io/tedious/api-connection.html
I have followed various troubleshooting threads but none have worked for me and the errors I am getting are not helping.
Here are what I have as my Knex initialization.
const db = knex({
client: 'mssql'
useNullAsDefault: true,
connection: {
type: 'azure-active-directory-password',
server: 'sql-db.database.windows.net',
database: 'my-db',
user: 'myUser',
password: 'myPassword',
clientId: 'myUser-AzureAd-Object-Id',
tenantId: 'myTenantId',
encrypt: true,
...knexSnakeCaseMappers()
}
})
When I try to run my migrations I get the error:
AggregateError
at c:\path\node_modules\tedious\lib\connection.js:2759:31
at processTicksAndRejections (node:internal/process/task_queues:94:5)
While running the code normally, without applying the migration first I get this error.
this.loginError = new _esAggregateError.default([new _errors.ConnectionError('Security token could not be authenticated or authorized.', 'EFEDAUTH'), err]);
At this point I do not know why it is not connecting to the database. On the same machine I can connect to the database over SSMS using Azure Active Directory - Password and the same credentials I am passing in the knexfile.
I am lost as to why this is not connecting any help would be greatly appreciated.
FIXED: I had more of an issue with the logging of Knex, after using Tedious directly the error was a bit more clear.
The issue was related to the Client ID, it says it is going to be required, but when I provided it, it said it was incorrect. Removing the Client ID fixed the issue.

'Login failed for user' error when using SQL Server, but not when using tedious

I'm trying to connect to a SQL Server Express database setup on a Windows 10 machine in network from a macbook running the following code. I can connect using tedious, but not using mssql. It's as if the username or password is wrong. The reason I want to get mssql working is for the pooling and because it appears to have more support... otherwise I would just use tedious. The code is creating both connections and the output shows tedious connecting but mssql fails.
const express = require('express');
const sql = require('mssql');
const bodyParser = require('body-parser');
const app = express();
var Connection = require('tedious').Connection;
// Body Parser Middleware
app.use(bodyParser.json());
// CORS Middleware
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// define listineng port
const PORT = 5006;
// define tedious config
var config = {
server: "JAMBER-VR1.local",
userName: "testuser",
password: "testuserpass",
database: "SQLEXPRESS",
options: {
encrypt: false
}
};
var connection = new Connection (config);
connection.on('connect', function(err){
if(err!=null){
console.log(err);
console.log("not connected - tedious");
}
else{
console.log("Connected - tedious")
connection.close();
};
});
// Define SQL config
const dbConfig = {
user: 'testuser',
password: 'testuserpass',
server: 'JAMBER-VR1.local',
database: 'SQLEXPRESS',
// port: 1433,
// logging: true,
options: {encrypt: false},
pool: {
max: 100,
min: 0,
idleTimeoutMillis: 30000
}
}
const executeQuery = async () => {
try {
let pool = await sql.connect(dbConfig);
console.log("pool connected - mssql");
let result = await pool.request()
.input('input_parameter', sql.Int, value)
.query('select * from donor')
console.log("Result: ", result);
} catch (err) {
console.log("Error: ", err);
}
}
executeQuery();
I'm getting the following error.
[nodemon] starting node index.js
Running on port 5006
Connected - tedious
Error: { ConnectionError: Login failed for user 'testuser'.
at Connection.tedious.once.err (/Users/jordanszymczyk/Code/TRTL/server_sql /node_modules/mssql/lib/tedious.js:237:17)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Connection.processLogin7Response (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:1292:16)
at Connection.message (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:1805:14)
at Connection.dispatchEvent (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:1004:38)
at MessageIO. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:884:18)
at MessageIO.emit (events.js:182:13)
at ReadablePacketStream. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/message-io.js:104:16)
at ReadablePacketStream.emit (events.js:182:13)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user 'testuser'.
at ConnectionError (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/errors.js:12:12)
at Parser. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:628:33)
at Parser.emit (events.js:182:13)
at Parser. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/token/token-stream-parser.js:54:15)
at Parser.emit (events.js:182:13)
at addChunk (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_readable.js:291:12)
at readableAddChunk (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_readable.js:278:11)
at Parser.Readable.push (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_readable.js:245:10)
at Parser.Transform.push (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_transform.js:148:32)
at doneParsing (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/token/stream-parser.js:110:18)
message: 'Login failed for user 'testuser'.',
code: 'ELOGIN' },
name: 'ConnectionError' }
You can see the console.log("Connected - tedious") prints, then the mssql error follows immediately.
I've also tried using the local IP with the same results.
Testing through sqlcmd works.
dont forget to active both authentication
SQLEXPRESS will be the name of your SQL Server Express server instance (ie- Server). I don't see it in your code, but I'm guessing the database name is not SQLEXPRESS?
In your mssql connection dbConfig try changing Database to the real name of the database you created on your SQL Express instance.
The fixed dgconfig is as follows:
const dbConfig = {
user: 'testuser',
password: 'testuserpass',
server: 'JAMBER-VR1.local',
database: 'donor',
options: {encrypt: false},
pool: {
max: 100,
min: 0,
idleTimeoutMillis: 30000
}
}
Removed SQLEXPRESS and replaced it with the database name.

Trying to connect to Mssql server via knex

I'm trying to connect to a remote database with knex but I get this error:
"tedious deprecated The default value for options.encrypt will change from false to true. Please pass false explicitly if you want to retain current behaviour. at node_modules\mssql\lib\tedious.js:212:23
Unhandled rejection ConnectionError: Failed to connect to 151.80.119.227,14831:1433 - getaddrinfo ENOTFOUND 151.80.119.227,14831"
I can connect via Microsoft sql server management studio with same host, user, password so I'm lost.
Edit:
This is how I create my knex var:
var knex = require('knex')({
client: 'mssql',
connection: {
server : '151.80.119.227,14831',
user : '****',
password : '****',
database : '****'
}
});
I can connect to it via python with:
con = pyodbc.connect("DRIVER={SQL Server};server=151.80.119.227,14831;database=*****;uid=****;pwd=****")
So why won't it connect through node.js ....
Port should actually be specified in the MSSQL options variable:
var knex = require('knex')({
client: 'mssql',
connection: {
server : '151.80.119.227',
user : '****',
password : '****',
database : '****',
options: {
port: 14831
}
}
});
This is from reading the code at https://github.com/tgriesser/knex/blob/v0.16.2/src/dialects/mssql/index.js
port for node-mssql driver should be set like this:
{
dialect: 'mssql',
connection: {
user: "sa",
password: "S0meVeryHardPassword",
server: "151.80.119.227",
port: 14831,
database: "knex_test"
}
}

Connecting NodeJS Express to MS SQL Server

I'm a NodeJS newbie and I am building an application that talks to an MSSQL (SQL Server 2008 R2) Database. For this, I tried using Sequelize, an ORM library that claims to do so.
While I have been successful in making it work with MySQL, SQL Server connection is just not working. I connected to a local database on both the occasions. Here's what I tried (as given in the docs):
[Part 1: Establish Connection]
... Express Code ...
var Sequelize = require('sequelize');
var sequelize = new Sequelize('NewDB', '', '', {
host: '(localdb)\v11.0',
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
[Part 2: Testing]
var User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
},
lastName: {
type: Sequelize.STRING
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
User.sync({force: true}).then(function () {
// Table created
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
... Express Code ...
The database NewDB does exist on the server. Now, While using SQL Server Express, the same credentials work. But not here. The error that I see is:
Unhandled rejection SequelizeConnectionError: Failed to connect to (localdb)\v11.0:1433 = getaddrinfo ENOTFOUND (localdb)\v11.0
So, here's the question. What credentials do I put, so that it works? And if it doesn't what would be alternate library to establish a Database connection? I'll prefer an ORM, but it's not that important a thing (anything works as long as I can connect to the DB).

Node.JS can't connect a local SQL Server

I'm trying to pass my windows domain credentials to a LOCAL SQL Server and I'm getting this weird error:
Could not connect to sql: { [ConnectionError: Login failed. The login is from a
n untrusted domain and cannot be used with Windows authentication.]
name: 'ConnectionError',
message: 'Login failed. The login is from an untrusted domain and cannot be us
ed with Windows authentication.',
code: 'ELOGIN' }
I also tried connecting to a remote SQL Server without success.
When I pass SQL Authentication it works fine
Here's the code:
var sql = require('mssql');
var conn_str = {
server: 'ccc',
database: 'TEST',
domain: 'Name',
user: 'xxxxx',
password: 'xx',
options : {
trustedConnection : true
}
}
var connection = new sql.Connection(conn_str, function(err) {
// ... error checks
if(err) {
return console.log("Could not connect to sql: ", err);
}
// Query
var request = new sql.Request(connection);
request.query('select top 10 * from xxxx (nolock)', function(err,recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
});

Resources