I am trying to drop a database called test from node.js postgres sql but it is not working.
var express = require('express');
var app = express();
var pg = require('pg');
var pgp = require('pg-promise')();
// Connect to PostgreSQL database
var connectionString = process.env.DATABASE_URL || 'postgres://postgres:pass123#localhost:5432/test';
var db = pgp(connectionString);
db.connect();
db.query("DROP DATABASE test").then(function()
{
//createDatabases(db);
}).catch(function(err)
{
console.log(err);
});
But I am getting an error
{ [error: cannot drop the currently open database]
name: 'error',
length: 87,
severity: 'ERROR',
code: '55006',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'dbcommands.c',
line: '834',
routine: 'dropdb' }
Does anyone know how to fix it?
Thanks
As the error says, you can't be connected to the DB in question to drop it. You can connect to a different DB in order to do so, or use a tool like pgtools
var pgtools = require('pgtools');
// This can also be a connection string
// (in which case the database part is ignored and replaced with postgres)
const config = {
user: 'postgres',
password: 'some pass',
port: 5432,
host: 'localhost'
}
pgtools.dropdb(config, 'test-db', function (err, res) {
if (err) {
console.error(err);
process.exit(-1);
}
console.log(res);
});
Related
I'm currently trying to create a functional query from the database to post it into a created a csv file, however I am unable to connect to the PSQL host programmatically. So what I am trying to do is :-
Connect to DB and query results
Push results to an Excel File
Continue()
SFTP Results to myself on SFTP Server and place file in directory.
I am able to connect to the PostgresDB manually by the following in CLI:-
ssh username#xx.xx.xx.xx //Doesnt need password because my id_rsa key is stored on the Server
psql -U username -h LOCALHOST -p 5432 -d databasename pass- password (Manually input)
Furthermore, connecting through Visual Studio Code works as well however I need to connect to the server (Remote Connection) and then connect to the Database using a postgres Driver.
After investigating it, I figured I firstly need to connect using SSH to the server, then and only then I will be allowed to access the Database.
This is how I approached it through Code :-
Index.js
const serverConnectionParams = require('./src/config/serverConn');
function testConnectionServer() {
try {
serverConnectionParams.connectToServer();
} catch (err) {
console.error(err);
}
}
testConnectionServer();
serverConn.js
const { Client } = require('ssh2');
const { readFileSync } = require('fs');
const databaseConnectionParams = require('./databaseConn');
function connectToServer() {
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('uptime', (err, stream) => {
if (err) throw err;
databaseConnectionParams.auth(); *// This is the database connection param*
stream.on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'xx.xx.xx.xx',
username: 'username',
privateKey: readFileSync('src/key/id_rsa')
});
}
exports.connectToServer = connectToServer;
databaseConn.js
const { readFileSync } = require('fs');
const envParam = require('./env.js');
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(envParam.database, envParam.username, envParam.password, {
host: envParam.host,
dialect: envParam.dialect,
ssl: true,
pool: {
max: envParam.pool.max,
min: envParam.pool.min,
acquire: envParam.pool.aquire,
idle: envParam.pool.idle
}
});
async function auth() {
try {
console.log('trying to connect')
sequelize.validate();
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
exports.auth = auth;
env.js
const env = {
database: 'databasename',
username: 'username',
password: 'password',
host: 'ip#',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
aquire: 30000,
idle: 10000
}
};
module.exports = env;
After running my node index.js I receive the following error statement :-
Client :: ready
trying to connect
STDOUT: 10:43:09 up 1:21, 1 user, load average: 5.71, 6.03, 5.15
C:\Users\~\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:184
reject(new sequelizeErrors.ConnectionError(err));
^
ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Client._connectionCallback
{
parent: error: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Parser.parseErrorMessage
{
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
},
original: error: no pg_hba.conf entry for host "x.x.x.x", user "username", database "password", SSL off
at Parser.parseErrorMessage (C:\Users\~\node_modules\pg-protocol\dist\parser.js:287:98)
at Parser.handlePacket (C:\Users\~\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Users\~\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket.<anonymous> (C:\Users\~\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:394:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
}
}
Investigating the Error Code: 28000
Found this link explaining the issue as an authentication attempt failure
https://help.heroku.com/DR0TTWWD/seeing-fatal-no-pg_hba-conf-entry-errors-in-postgres
Also found several solutions online regarding pg_hba.conf needs to use md5 and then restart postgress (Not tried, as i cannot restart the postgress service)
error: Ident authentication failed for user
Found another solution explaining it was an SSL issue (Tried it and it didnt work)
Node.js, PostgreSQL error: no pg_hba.conf entry for host
After using SSL it would change the error code to the following :-
SequelizeConnectionError: self signed certificate
Found a solution to that here:-
SequelizeConnectionError: self signed certificate
After I put that it would give me a different error that rejectUnauthorized is depreciated and very old version (Cant seem to reproduce the error code as of the moment)
So my hands are tied at the moment, any help will be great!
I've also tried using different Javascript modules instead of sequelize however they all have the same authentication issue.
I also tried to pass my id_rsa key, however it wouldnt solve my issue at all.
My assumptions are even though I am passing the connToDatabase function inside the SSH connection, it is still searching for the ip# in the incorrect location. (Ip# of DB on the server is 192.168.31.4)
But when using that IP# it will say ERR Connection Timed out
Another Assumption I have is that the Database has many restrictions from connecting and require further more params.
UPDATE:
I tried editting the pg_hba.conf file through remote access on VSC however it would give me error cannot read file.
Any help would be great!
I had completely forgotten that I posted this question.
The solution to it was pretty straight forward, after investigating it for a while I realized I was making a mistake in connection params.
For others who require help with such issues I will post the solution in a simple manner.
Basically, I needed first to SSH to the server and add a tunnel to my connection to connect to the database. Then and only then will my sequelize params for the database pass through because I have completely connected to the server and internal postgresql database.
So TLDR
SSH -> Tunnel -> Sequelize
ssh(10.x.x.1, etc) -> addTunnel(localhost, etc) -> sequelize(databaseName, etc)
EDIT: Added Code for reference
const Ssh2Promise = require('ssh2-promise');
const { readFileSync } = require('fs');
async function connectToServer(callback) {
const ssh = new Ssh2Promise({
host: '10.x.x.1',
username: 'usernameofssh',
privateKey: readFileSync('src/key/id_rsa'), //This is only for RSA Fingerprint, if you do not have said fingerprint you can use "passphrase" with your password instead
});
const tunnel = await ssh.addTunnel({
remoteAddr: '192.168.0.1', //This is the database connection ip#, once connected to it you can fetch from LOCALHOST. Incase its AWS it would be test.test-test.amazonaws.com
remotePort: 1234, //Port for connection
localPort: 1234,
});
//Don't forget to throw it in a try catch for feedback
await auth(callback); //Send it wherever you need it to go
}
I am trying to use Sequelize (v 5.21.13) to connect to my SQL Server database in my Expressjs app.
dbconfig.js
var dbConfig = {
server: process.env.DB_HOST,
authentication: {
type: 'default',
options: {
userName: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
}
},
options: {
database: process.env.DB_NAME
}
};
module.exports = dbConfig;
index.js:
const dbConfig = require('./dbConfig');
const Sequelize = require('sequelize');
const connection = new Sequelize(
dbConfig.options.database,
dbConfig.authentication.options.userName,
dbConfig.authentication.options.password,
{
host: dbConfig.server,
dialect: 'mssql',
}
);
connection.sync().then(() => {
console.log('Connected!');
}).catch((e) => {
console.log('Error:\n', e);
});
Now the thing is that each time I run the server, I get this error
AccessDeniedError [SequelizeAccessDeniedError]: Login failed for user 'master'.
I have also tried adding additional properties to the new Sequelize() like the following with no luck.
dialectOptions: {
instanceName: 'instance',
options: {
encrypt: true,
trustServerCertificate: true,
requestTimeout: 30000
}
}
I even tried changing the password to a very simple one with no special characters, connection with Datagrip works after changing but not using Sequelize.
Everything on the dbconfig object is correct so I don't see what the issue might be.
Solved it. I was putting the the db instance id as the database name, I realized that the database name was different. Changed it and I'm now connected through Sequelize.
I've written a code to fetch the data from postgres database using express and NODE.js. the database is connected with the backend code but still it is showing error like relation does not exit.
Please check the code and error that I got:
var express = require('express');
var pg = require("pg");
var app = express();
var connectionString = "postgres://postgres:postgres#localhost:5432/testDatabase?currentSchema=testSchema";
app.get('/', function(req, res, next) {
pg.connect(connectionString, function(err, client, done) {
if (err) {
console.log("Not able to get Connection " + err);
res.status(400).send(err);
} else {
console.log("Connected.!");
}
const
query = {
// give the query a unique name
name : 'fetch-user-details',
text : 'SELECT * FROM loginTable',
}
client.query(query, function(err, result) {
done(); // closing the connection;
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});
app.listen(4000, function() {
console.log('Server is running.. on Port 4000');
});
and the error response that I got is like:
Server is running.. on Port 4000
Connected.!
{ error: relation "logintable" does not exist
at Connection.parseE (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:554:11)
at Connection.parseMessage (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:381:17)
at Socket.<anonymous> (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:117:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:594:20)
name: 'error',
length: 120,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '15',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'src\\backend\\parser\\parse_relation.c',
line: '986',
routine: 'parserOpenTable' }
just run this db dump at my Postgres
CREATE SCHEMA "testSchema";
ALTER SCHEMA "testSchema" OWNER TO postgres;
SET search_path = "testSchema", pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
CREATE TABLE "loginTable" ( "ID" numeric NOT NULL, "Name" text );
ALTER TABLE "loginTable" OWNER TO postgres;
this was the problem
change your query to this
query = {
// give the query a unique name
name : 'fetch-user-details',
text : `SELECT * FROM "testSchema".logintable`,
}
you should mention the schema name
tasted on
Ubuntu
postgres 10.6
pg: 6.4.2
node v10.14.1
I have connection but i do not know if it exists in connection the key odbc... but even if i throw it away the error informed below persists
const knex = require('knex');
// connection database
const dbmdlog = knex({
client: 'oracle',
connection: {
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydb',
odbc: 'MYDB'
}
});
module.exports = dbmdlogp;
I'm doing a select simple in a collun
But always return error:
Unhandled rejection TypeError: _this2.driver.connect is not a function
at /var/www/html/myapp/node_modules/knex/lib/dialects/oracle/index.js:143:21
at Promise._execute (/var/www/html/myapp/node_modules/bluebird/js/release/debuggability.js:299:9)
at Promise._resolveFromExecutor (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:481:18)
at new Promise (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:77:14)
at Client_Oracle.acquireRawConnection (/var/www/html/myapp/node_modules/knex/lib/dialects/oracle/index.js:142:12)
at Object.create (/var/www/html/myapp/node_modules/knex/lib/client.js:231:16)
at Pool._createResource (/var/www/html/myapp/node_modules/generic-pool/lib/generic-pool.js:326:17)
at Pool.dispense [as _dispense] (/var/www/html/myapp/node_modules/generic-pool/lib/generic-pool.js:314:12)
at Pool.acquire (/var/www/html/myapp/node_modules/generic-pool/lib/generic-pool.js:392:8)
at /var/www/html/myapp/node_modules/knex/lib/client.js:281:19
at Promise._execute (/var/www/html/myapp/node_modules/bluebird/js/release/debuggability.js:299:9)
at Promise._resolveFromExecutor (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:481:18)
at new Promise (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:77:14)
at Client_Oracle.acquireConnection (/var/www/html/myapp/node_modules/knex/lib/client.js:272:12)
at /var/www/html/myapp/node_modules/knex/lib/runner.js:200:30
at Promise._execute (/var/www/html/myapp/node_modules/bluebird/js/release/debuggability.js:299:9)
A combination of knex and OracleDB works fine. Here are packages from package.json: "knex": "0.13.0", "oracledb": "1.13.1"
And the knex call:
var conn = knex({
client: 'oracledb',
connection: {
host: config.oracle.host,
user: config.oracle.user,
password: config.oracle.password,
database: config.oracle.database,
}
});
In case someone needs to pass a connection string. Please note however, the details inside the connection string will need to match your own environment.
const oracledb = require("oracledb");
oracledb.initOracleClient({ libDir: "C:\\oracle\\instantclient_12_1" });
const knex = require("knex")({
client: "oracledb",
connection: {
user: "YOUR_USER",
password: "YOUR_PASSWORD",
connectString: "(DESCRIPTION=(CONNECT_TIMEOUT=10)(RETRY_COUNT=3)(SOURCE_ROUTE=yes)(ADDRESS_LIST=(LOAD_BALANCE=on)(ADDRESS=(PROTOCOL=tcp)(HOST=your2.domain.com)(PORT=11529))(ADDRESS=(PROTOCOL=tcp)(HOST=your2.domain.com)(PORT=11529)))(ADDRESS_LIST=(FAILOVER=on)(LOAD_BALANCE=off)(ADDRESS=(PROTOCOL=tcp)(HOST=your3.domain.com)(port=1521))(ADDRESS=(PROTOCOL=tcp)(HOST=your4.domain.com)(port=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=YOUR_SERVICE.your5.domain.com)))",
requestTimeout: 100
},
fetchAsString: ["number", "clob"]
});
knex.select().from("TABLE1").asCallback(function(err, rows){
if(err)
console.log(err);
else
console.table(rows);
});
I'm trying to connect to a local SQL Express server using Tedious but keep getting
failed Error: getaddrinfo ENOTFOUND
Am I using the wrong address here?
var Connection = require('tedious').Connection;
var config = {
userName: 'sa',
password: 'mypassword',
server: 'LOCALHOST\\SQLEXPRESS',
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to go...
if(err) {
console.log(err);
return;
}
executeStatement();
}
);
"Microsoft style strings of hostname\instancename are not supported."
- pekim
I posted the same issue on github and here is the full answer: https://github.com/pekim/tedious/issues/118
Just as #Cotten said, but here is an example.
TCP/IP connection must be enabled and the port shouldn't be included within the server string, it must go inside the configuration as a numeric value.
var config = {
server: 'your_ip_address',
authentication: {
type: 'default',
options: {
userName: 'your_username',
password: 'your_password'
}
},
options: {
database: 'your_database',
port: 1234 //your port number
}
};