Having troubles connecting sequelize with SQL Server - sql

I'm experiencing some stupid problem while connecting sequelize with SQL Server and the error that is thrown looks something like this :
(node:13096) UnhandledPromiseRejectionWarning: SequelizeConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionManager.connect (E:\ProgramFiles\MojeVjezbe\sidejob_test\node_modules\sequelize\lib\dialects\mssql\connection-manager.js:138:17)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async ConnectionManager._connect (E:\ProgramFiles\MojeVjezbe\sidejob_test\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:318:24)
at async E:\ProgramFiles\MojeVjezbe\sidejob_test\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:250:32
at async ConnectionManager.getConnection (E:\ProgramFiles\MojeVjezbe\sidejob_test\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:280:7)
Here is my configuration for sequelize code :
module.exports = {
//host: "localhost",
database: "testdb",
//server : 'localhost',
dialectModulePath: 'sequelize-msnodesqlv8',
dialect: "mssql",
port : 1433,
dialectOptions : {
//encrypt: true,
InstanceName : "MSSQLSERVER",
//connectionString : 'Server=localhost\MSSQLSERVER01;Database=master;Trusted_Connection=yes;'
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
As you can see I've tried changing connection string, host, server but the error is still the same. I've also tried enabling TCP/IP for SQL Server and it hasn't worked either.
What am I missing? I don't have a username nor password so I don't think it may be a problem in this case.

Related

mssql in nodejs not connecting

Trying to connect to my database to create a local website but having connection issues.
Running in node.js, this is my server.js file:
let sql = require('mssql');
let config = {
user: 'sa',
password: 'password',
server: '10.0.1.130\\SQLSERVER',
database: 'MY_DB',
};
function connect() {
let dbConn = new sql.ConnectionPool(config);
dbConn.connect()
}
connect();
Upon running this I get the following error:
ConnectionError: Failed to connect to 10.0.1.130:undefined - self signed certificate
code: 'ESOCKET'
Not sure why it is removing \SQLSERVER but that seems to be my issue.
I know the credentials are all correct as I connect to this on another computer (ubuntu) but its being removed and we want to move it to windows, have not been able to connect to this point.
Any suggestions are appreciated.

Cannot find host name for ElephantSQL server

I've been trying to set up an express server. All my routes seem to work correctly, it's connecting to the database that's giving me issues. I'm not great at backend but I feel like getting the host name shouldn't give me this many problems.
Here's my error: (batyr.db.elephantsql.com is my DB_HOST name):
Error: getaddrinfo ENOTFOUND 'batyr.db.elephantsql.com';
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: "'batyr.db.elephantsql.com';"
}
Here's my repository
Here's my knexfile.js:
require('dotenv').config();
const path = require("path");
module.exports = {
development: {
client: 'pg',
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
},
charset: 'utf8',
pool: { min: 1, max: 5 },
migrations: {
directory: path.join(__dirname, "src", "db", "migrations"),
},
},
};
Here's my .env file:
DATABASE_URL = 'postgres://pausapcx:vxSa5l3ZK_F2lrlMGhyt0XBlYbX7hfWY#batyr.db.elephantsql.com/pausapcx';
DB_HOST = 'batyr.db.elephantsql.com';
DB_USERNAME = 'pausapcx';
DB_PASSWORD = '***'; // cut just for this post
DB_NAME = 'pausapcx';
My server.js is running on port 8080, pgAdmin is running on port 5432
Here are the host and server names from elephantsql:
(https://i.stack.imgur.com/CnGQ4.png)
(https://i.stack.imgur.com/EVRkP.png)
I've tried with several differnet host names:
batyr.db.elephantsql.com (pgAdmin accepted this one)
batyr
I've tried the database URL
I've even tried just Elephantsql.com
I've pinged batyr.db.elephantsql.com in the terminal and gotten this response:
Pinging ec2-3-89-203-254.compute-1.amazonaws.com [3.89.203.254] with 32 bytes of data:
Reply from 3.89.203.254: bytes=32 time=41ms TTL=44
Reply from 3.89.203.254: bytes=32 time=76ms TTL=44
Reply from 3.89.203.254: bytes=32 time=38ms TTL=44
Reply from 3.89.203.254: bytes=32 time=37ms TTL=44
Ping statistics for 3.89.203.254:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 37ms, Maximum = 76ms, Average = 48ms
I really suck at backend, I'd appreciate any help.
Was able to get data!
terminal screenshot
The solution was to just swap out all the random connection data with a single database URL (I'll secure it in .env once it's all working)
// works:
connection: 'postgres://pausapcx:***#batyr.db.elephantsql.com/pausapcx',
// doesn't work:
connection: {
host: 'batyr.db.elephantsql.com',
user: 'pausapcx',
password: '***',
database: 'pausapcx',
},

NesJS RabbitMQ with #golevelup/nestjs-rabbitmq no connection when using new connectioninit

Using #golevelup/nestjs-rabbitmq I tried the connection manager to not wait for a connection. According to the readme it can handle reconnections and wait for a connection without crashing the app. However, when I use the connectionInitOptions as stated and set wait to false, I get a connection error. When I don't use it (default behavior setting wait to true) , it connects to the RabbitMQ server. Below are examples importing the RabbitMQModule in a NestJS module.
This works and connects to the RabbitMQ server
RabbitMQModule.forRoot(RabbitMQModule, {
exchanges: [{ type: 'topic', name: 'main' }],
uri: 'amqp://guest:guest#localhost:5672',
}
This doesn't work and won't connect
RabbitMQModule.forRoot(RabbitMQModule, {
exchanges: [{ type: 'topic', name: 'main' }],
uri: 'amqp://guest:guest#localhost:5672',
connectionInitOptions: {
wait: false,
},
With the second option I get the following error:
Error: AMQP connection is not available
at AmqpConnection.publish (/home/xxx/node_modules/#golevelup/nestjs-rabbitmq/src/amqp/connection.ts:424:13)
at BootstrapService.onApplicationBootstrap (/home/xxx/src/bootstrap/bootstrap.service.ts:20:25)
at MapIterator.iteratee (/home/xxx/node_modules/#nestjs/core/hooks/on-app-bootstrap.hook.js:22:43)
at MapIterator.next (/home/xxx/node_modules/iterare/src/map.ts:9:39)
at IteratorWithOperators.next (/home/xxx/node_modules/iterare/src/iterate.ts:19:28)
at Function.from (<anonymous>)
at IteratorWithOperators.toArray (/home/xxx/node_modules/iterare/src/iterate.ts:227:22)
at callOperator (/home/xxx/node_modules/#nestjs/core/hooks/on-app-bootstrap.hook.js:23:10)
at callModuleBootstrapHook (/home/xxx/node_modules/#nestjs/core/hooks/on-app-bootstrap.hook.js:43:23)
at NestApplication.callBootstrapHook (/home/xxx/node_modules/#nestjs/core/nest-application-context.js:199:55)
at NestApplication.init (/home/xxx/node_modules/#nestjs/core/nest-application.js:98:9)
at NestApplication.listen (/home/xxx/node_modules/#nestjs/core/nest-application.js:155:33)
at bootstrap (/home/xxx/src/main.ts:12:3)
The last line (main.ts:12:3) is the app.listen(3000) statement.
There are other options you can set with the connectionInitOptions (reject and timeout) and I've tried the combinations but still no connection.
RabbitMQ is running in a docker container on Linux but that should be no problem. I posted the same question on NestJS discord but got no reply, so hopefully someone on SO has an idea.
Any idea what could be the cause?
Found the problem, I was using the connection in a onApplicationBootstrap method and then the connection is apparently not present yet.
you can wait for connection asynchronously 'onApplicationBootstrap':
or on :
async onModuleInit() {
await this.amqpConnection.managedChannel.waitForConnect(async () => {
await this.assertQueueAndBindToExchange(
transferRequestQueueName,
transferRequestExchangeName,
createdRoutingKey
);

Jest + knex 'Unable to acquire a connection' during integration tests (sequelize works fine)

I have both sequelize and knex in my project (node.js, express, using TypeScript). Just introduced knex as I don't like sequelize and just want a light-weight query builder.
In non-test environments both sequelize and knex work fine, however when running tests (using jest) knex is, apparently, not able to connect to the database. They both use the same databaseUrl, though sequelize has a few more options configured. When running my tests under jest I can't figure out why I am getting
Error: Unable to acquire a connection\n at
Client_PG.acquireConnection
When NODE_ENV is set to 'test', the express app uses a postgres database on my local machine.
Here is the configuration code
const _sqlz = new Sequelize(
config.dbConString,
{
logging: config.nodeEnv === 'test' ? false : false,
define: { freezeTableName: true },
dialect: 'postgres',
...config.sslDB === 'true'
? {
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
}
: {}
}
);
const knexConfig = {
client: 'postgres',
connection: config.dbConString,
pool: {
min: 0,
max: 15
}
};
const _knex = knex(knexConfig)
When running jest it will give me a Unable to acquire a connection when trying to execute a simple knex query like so
await _knex('myTable').select('*');
To figure out what's happening I configured things such that jest would use the same test database when I set my node environment to be development, i.e. NODE_ENV=development. Interestingly now that development and test point to the same local database, if I run jest, it still gives me the same error about not being able to acquire a connection. So me setting NODE_ENV=test in of itself is not the issue. If I run the app (npm run start) while pointing to my local database, knex works fine, which leads me to think something about jest + knex isn't meshing well. jest + sequelize is working fine.
I tried playing around with the SSL settings but to no avail (I did see some knex + heroku blog posts needing ssl to be explicitly set), e.g.:
const knexConfig = {
client: 'pg',
connection: {
connectionString: config.databaseUrl,
ssl: {
require: true,
rejectUnauthorized: false
}
},
pool: {
min: 0,
max: 15
}
};
Hoping someone with more experience might have some ideas.
Thanks

Timeout error while connecting to SQL Server: Connection Error: Failed to connect to servername\instancename in 15000ms

The error code is code ETIMEOUT. I am using SQL Server 2014, NodeJs version v12.16.2 and I am running this code in Visual Studio Code.
I have created the database and the table is also created with some records. For the server name, I have also tried giving the FQDN, but it didn't work.
This is the code snippet:
const express = require('express');
const app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
app.get('/', function(req, res) {
res.send('<hHii</h');
});
const sql = require('mssql');
var config = {
user: 'domain\username',
password: 'mypwd',
server: 'servername',
host: 'hostname',
port: '1433',
driver: 'tedious',
database: 'DBname',
options: {
instanceName: 'instancename'
}
};
sql.connect(config, function(err) {
if (err)
console.log(err);
let sqlRequest = new sql.Request();
//var sqlRequest = new sql.Request(connection)
let sqlQuery = 'SELECT * from TestTable';
sqlRequest.query(sqlQuery, function(err, data) {
if (err) console.log(err);
console.log(data);
//console.table(data.recordset);
// console.log(data.rowAffected);
//console.log(data.recordset[0]);
sql.close()
});
});
const webserver = app.listen(5000, function() {
console.log('server is up and running....');
});
Error:
tedious deprecated The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or`false` explicitly to silence this message.
node_modules\mssql\lib\tedious\connection-pool.js:61:23
server is up and running....
ConnectionError: Failed to connect to servername\instantname in 15000ms
at Connection.<anonymous(..\SQL\Sample\sample\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:417:26)
at Connection.emit (events.js:310:20)
at Connection.connectTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1195:10)
at Timeout._onTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1157:12)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ETIMEOUT',
originalError: ConnectionError: Failed to connect to INPUNPSURWADE\DA in 15000ms
at ConnectionError (..\SQL\Sample\sample\node_modules\tedious\lib\errors.js:13:12)
at Connection.connectTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1195:54)
at Timeout._onTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1157:12)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
message: 'Failed to connect to servername\instantname in 15000ms',
code: 'ETIMEOUT'
},
name: 'ConnectionError'
}
ConnectionError: Connection is closed.
at Request._query (..\SQL\Sample\sample\node_modules\mssql\lib\base\request.js:462:37)
at Request._query (..\SQL\Sample\sample\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (..\SQL\Sample\sample\node_modules\mssql\lib\base\request.js:398:12)
at Immediate.<anonymous(..\SQL\Sample\sample\index.js:43:12)
at processImmediate (internal/timers.js:458:21) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}
Go to Start menu in Windows, search for "Services" and open it.
Look for "SQL Server Browser"
Right click on it and go to Properties.
Switch "Start up type" to "Automatic"
Click Ok
Right click on it again and Start the service.
It should work after that!
You might make a typo in host/port, or the server doesn't listen external interfaces (it might be configured to liten 127.0.0.1 only)
to check that the server is listening to incoming connections, run in terminal the following:
telnet <hostname> <port>
(mac/linux only)
If it says "Unable to connect to remote host: Connection refused" it means the host is there but it doesn't listen the port.
If it says "Unable to connect to remote host: Connection timed out" then the host might not be there, ot doesn't listen to the port.
You may also want to check if your firewall allows connection to that server.