SQL Server host not found error with sequelize - node.js

I am trying to use SQL Server with node.js using sequelize orm. But I keep getting host not found error:
HostNotFoundError [SequelizeHostNotFoundError]: Failed to connect to
localhost//SQLEXPRESS:1433 - getaddrinfo ENOTFOUND localhost//SQLEXPRESS
Failed to connect to localhost//SQLEXPRESS:1433 - getaddrinfo ENOTFOUND localhost//SQLEXPRESS', code: 'ESOCKET
Code:
var db = new Sequelize('test', 'root', 'secret', {
host: 'localhost\\SQLEXPRESS',
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
db.authenticate()
.then(()=>console.log('Database connected'))
.catch(err=> console.log(err))
Please help me!

trying
options.port The port of the relational database.
var db = new Sequelize('test', 'root', 'secret', {
host: 'localhost\\SQLEXPRESS',
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
port:56198,
});

Related

Failed to connect to *name_server* - getaddrinfo ENOTFOUND

When connecting to the database with sequelize-typescript, an error occurs
Failed to connect to SERVER\SQL2016:1433 - getaddrinfo ENOTFOUND SERVER\SQL2016
Connection settings
import { Sequelize } from 'sequelize-typescript'
import { environment } from '../config'
import { normalize, join } from 'path'
export default new Sequelize({
database: environment.database.database,
dialect: "mssql",
username: environment.database.username,
// port: environment.database.port,
password: environment.database.password,
host: environment.database.host,
logging: !environment.production ? console.log : false,
models: [normalize(join(__dirname, "..", "models"))],
dialectOptions: {
options: {
enableArithAbort: true,
cryptoCredentialsDetails: {
minVersion: "TLSv1",
},
},
},
})
interface DatabaseConnection {
database: string
username: string
port: number
password: string
host: string
hostAsodu: string
databaseAsodu: string
}
export const environment: Environment = {
port: process.env.PORT ? Number(process.env.PORT) : 3030,
production: process.env.NODE_ENV === "production",
database: {
database: process.env.DB_DATABASE ?? String(),
username: process.env.DB_USERNAME ?? String(),
port: process.env.DB_PORT ? Number(process.env.DB_PORT) : 0,
password: process.env.DB_PASSWORD ?? String(),
host: process.env.DB_HOST ?? String(),
hostAsodu: process.env.DB_HOST_ASODU ?? String(),
databaseAsodu: process.env.DB_DATABASE_ASODU ?? String()
},
}
I tried connectit with and without a port, the error is the same. It just connects to SERVER, but does not want to connect to the named SERVER \ SQL2016. How can I fix this error? Found nothing on the docks
ENOTFOUND is an operating-system-level error from your OS's networking code. It means you asked it to look up a hostname and it came up with nothing. In the lingo, your name "could not be resolved." (www.stackoverflow.com is a hostname, for example. https://www.stackoverflow.com is a URL, which happens to contain a hostname.)
getaddrinfo() is OS method that asks the domain name service (DNS) to look up a hostname.
It looks to me like you tried to look up the hostname SERVER\SQL2016. That's not a hostname. You probably want something like sql2016.example.com instead. Ask the person who operates that SQL Server instance for the correct hosthame.
The SQL Server instance I use has a hostname something like devdatabase.dev.example.com.
Edit The SQL2016 part of your connection string is known as the server instance or DataSource. You need to specify it separately from the hostname. See this. Error connecting to SQL Server database with sequelize You also need to make sure your SQL Server software is configured to allow TCP connections.
Try this as you connect.
export default new Sequelize({
database: environment.database.database,
dialect: "mssql",
username: environment.database.username,
// port: environment.database.port,
password: environment.database.password,
host: environment.database.host, /* should be the hostname without \SQL2016 */
logging: !environment.production ? console.log : false,
models: [normalize(join(__dirname, "..", "models"))],
dialectOptions: {
instanceName: 'SQL2016',
options: {
enableArithAbort: true,
cryptoCredentialsDetails: {
minVersion: "TLSv1",
},
},
},
})

Sequelize connection to AWS RDS SQL Express Database in AWS Beanstalk

I have an elastic beanstalk website and a separate RDS database (SQL Express). When I ssh into the beanstalk instance, I can connect to the database on the server so the security groups are setup up correctly. However, when I use sequelize in my app, I cannot connect to the database.
I receive the below error in sequelize:
[SequelizeConnectionError]: Failed to lookup instance on web.cluster-qwertyuiop.us-west-2.rds.amazonaws.com - getaddrinfo ENOTFOUND web.cluster-qwertyuiop.us-west-2.rds.amazonaws.com
at ConnectionManager.connect (/var/app/current/node_modules/sequelize/lib/dialects/mssql/connection-manager.js:145:17) {
parent: ConnectionError: Failed to lookup instance on web.cluster-qwertyuiop.us-west-2.rds.amazonaws.com - getaddrinfo ENOTFOUND web.cluster-qwertyuiop.us-west-2.rds.amazonaws.com
at ConnectionError (/var/app/current/node_modules/tedious/lib/errors.js:13:12)
at /var/app/current/node_modules/tedious/lib/connection.js:1077:60
at /var/app/current/node_modules/tedious/lib/instance-lookup.js:116:20
at GetAddrInfoReqWrap.callback (/var/app/current/node_modules/tedious/lib/sender.js:140:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:74:17) {
code: 'EINSTLOOKUP'
},
This is my connection string:
new Sequelize('DATABASE', username, password, {
dialect: 'mssql',
dialectOptions: {
requestTimeout: 300000,
options: {
driver: 'SQL Server Native Client 11.0',
instanceName: 'SQLEXPRESS',
trustedConnection: true,
},
},
logging: false,
port: 1433,
host: 'web.cluster-qwertyuiop.us-west-2.rds.amazonaws.com',
pool: {
max: 20,
min: 3,
idle: 20000,
evict: 0,
acquire: 20000,
handleDisconnects: true,
},
There's very little to find online when trying to connect to MS SQL instances. I've been stuck on this one for a few days now.

sequelize connection timeout with cloud sql proxy in node.js

Running a local config, the connection works fine. I've installed and have a cloud_sql_proxy running and ready for new connections.
Here's my sequelize connection code:
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, {
dialect: 'mysql',
host: `/cloudsql/${CLOUD_SQL_CONNECTION_NAME}`,
pool: {
max: 30,
min: 0,
idle: 10000,
acquire: 1000000,
},
dialectOptions: {
connectTimeout: 100000
}
});
At some point I set my max connection, acquire, and connectTimeout variables to absurdly high numbers, but still no luck, but I started getting a specific IP address located in London on port 3306.
I was able to connect to the cloud db by modifying my config to the following:
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, {
dialect: 'mysql',
host: DB_HOST,
timestamps: false,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
The difference is I pointed the host to the actual db IP address instead of the /cloudsql/${CLOUD_SQL_CONNECTION_NAME} path.

Knex:Error Pool2 - Error: The server does not support SSL connections

Trying to connect with Postgres Node js and ran into the error
Resource Wall is listening on port 8080
Knex:Error Pool2 - Error: The server does not support SSL connections
Knex:Error Pool2 - Error: The server does not support SSL connections
How to turn off SSL connection? Here is my environment setup
DB_HOST=localhost
DB_USER=postgres
DB_PASS=password
DB_NAME=dbname
DB_SSL=true if heroku
DB_PORT=5432
And my knexfile.js
require('dotenv').config();
module.exports = {
development: {
client: 'postgresql',
connection: {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB_NAME,
port : process.env.DB_PORT,
ssl : process.env.DB_SSL
},
migrations: {
directory: './db/migrations',
tableName: 'migrations'
},
seeds: {
directory: './db/seeds'
}
},
production: {
client: 'postgresql',
connection: process.env.DATABASE_URL + '?ssl=true',
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'migrations'
}
}
};
Since I am running in dev, I expected that it won't go through SSL. Tried removing that SSL part from object and URL too. No luck.
There is no reason why knex would try to force using ssl connection when it is not explicitly asked to do that (well actually pg driver takes care of that part).
You may want to use this as a base to connect heroku and then work more complex configuration on top of this:
const knex = require('knex')({
client: 'pg',
connection: 'postgres://user:pass#server:port/database'
});
knex.raw('select 1')
.then(res => {
console.log('Success');
})
.catch(err => {
console.log('Something failed', err);
});

Can't connect to heroku postgresql database from local node app with sequelize

I'm trying to connect to a Heroku postgresql database from a local nodejs app with Sequelize. I followed this two guides an everything is working perfectly fine on the heroky server side, but my node app won't connect to heroku when I run it locally on my Mac.
http://sequelizejs.com/articles/heroku
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku
Here is how I start the local app:
DATABASE_URL=$(heroku config:get DATABASE_URL) nodemon
Gets me:
Sequelize: Unable to connect to the database:
But I get the correct URL by doing this:
echo $(heroku config:get DATABASE_URL)
And those commands are working fine:
heroku pg:psql
psql $(heroku config:get DATABASE_URL)
Here is my nodejs code :
var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^#]+)#([^:]+):(\d+)\/(.+)/)
sequelize = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: false
})
sequelize
.authenticate()
.complete(function(err) {
if (!!err) {
log('Sequelize: Unable to connect to the database:', err);
} else {
http.listen(process.env.PORT || config.server.port, function(){
log('Web server listening on port '+process.env.PORT || config.server.port);
});
}
});
I tried to add native: true to the sequelize options, but then I get:
/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188
throw new Error('The dialect ' + this.getDialect() + ' is not supported.
^
Error: The dialect postgres is not supported. (Error: Please install postgres package manually)
at new module.exports.Sequelize (/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188:13)
at Object.<anonymous> (/Users/clement/Projets/XMM/server.js:17:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Even after doing:
npm install pg
npm install -g pg
brew install postgresql
This is working by the way:
var pg = require('pg');
pg.connect(process.env.DATABASE_URL+'?ssl=true', function(err, client, done) {
if (err) return console.log(err);
client.query('SELECT * FROM pg_catalog.pg_tables', function(err, result) {
done();
if(err) return console.error(err);
console.log(result.rows);
});
});
But i'd rather use Sequelize.
OK, found the answer by browsing sequelize source code :
https://github.com/sequelize/sequelize/blob/master/lib/dialects/postgres/connection-manager.js#L39
To activate SSL for PG connections you don't need native: true or ssl: true but dialectOptions.ssl: true so the following did finally work:
sequelize = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: true
}
});
To work around the self signed certificate bug on node-postgres version 8 mentioned at SequelizeConnectionError: self signed certificate you can use instead:
sequelize = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
});
You no longer need to parse the DATABASE_URL env variable, there is a Sequelize constructor which accepts the connection URL:
sequelize = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: true
}
});
One needs to add dialectOptions under ssl
"development": {
"username": process.env.DB_USERNAME,
"password": process.env.DB_PASSWORD,
"database": process.env.DB_NAME,
"host": process.env.DB_HOST,
"dialect": process.env.DB_DIALECT,
"dialectOptions": {
ssl: {
require: true,
rejectUnauthorized: false
}
}
},
Source is as per official sequelize github
You need just these 2 things
Append ?sslmode=require to your POSTGRES DATABASE URI
Make sure you have rejectUnauthorized: false in your dialectOptions
const sequelize = new Sequelize(`${process.env.DATABASE_URI}?sslmode=require`, {
url: process.env.DATABASE_URI,
dialect: 'postgres',
logging: false,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false, // very important
}
}
}
For More Information, here is an Article on Heroku DevCenter about it
https://devcenter.heroku.com/articles/heroku-postgresql#heroku-postgres-ssl
I had the same problem and for these cases you can consider the following documentation example on how to connect the heroku database:
https://sequelize.readthedocs.io/en/1.7.0/articles/heroku/
At the end i did implement a code like :
const sequelize = new Sequelize(
process.env.DATABASE_NAME_DB_CONFIG,
process.env.USER_NAME_DB_CONFIG,
process.env.USER_PASSWORD_DB_CONFIG,
{
host: process.env.HOST_DB_CONFIG,
dialect: process.env.DIALECT_DB_CONFIG,
protocol: process.env.PROTOCOL_DB_CONFIG,
logging: true,
dialectOptions: {
ssl: true
},
pool: {
max: 5,
min: 0,
idle: 10000
}
}
);
where you need to take account the dialectOptions with ssl: true.
That's all you need to know.

Resources