Postgres NPM fails to connect with second DB in cypress - postgresql

I am using this NPM package for DB connection
POSTGRES NPM
I have two DBs that I need connection with, I am able to connect with first one but upon execution of second query. It throws an error error.Pool code snippet.. Any help would be much appreciated
` var pool = new pg.Pool(config.db);
var pool1 = new pg.Pool(config.db1)
tasks = postgreSQL.loadDBPlugin( pool );
on('task', tasks);`
`db: {
user: "postgres",
password: "*****",
host: "localhost",
port: "5432",
database: "global"
},
db1:{
user: "postgres",
password: "*****",
host: "localhost",
port: "5432",
database: "site"
},`

This NPM is able to connect to two DBs simultaneously
Postgres

Related

How can I start nest app with Postgress DB on Win 10?

I'm front dev and I need to test locally my front app with backend (nest js) and postgresql DB. Who can write me the right way How to run and connect to DB ? I get some errors on app start. I work on win 10 and there is my steps for start this app.
install postgresql
npm install for my nest js app
run pgAdmin4 and create DB for my app
npm start
There is my ormconfig
module.exports = {
"type": "postgres",
"host": process.env.POSTGRES_HOST || "localhost",
"port": process.env.POSTGRES_PORT || 5432,
"username": process.env.POSTGRES_USER || "", //<- Here I try to set all possible username
"password": process.env.POSTGRES_PASSWORD || "", //<- Here I try to set all possible password
"database": process.env.POSTGRES_DB || "my_database",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true,
"logging": true
}
There is error that I encountered
error
Also on other computer I try to do this and I get error like
[Nest] ERROR [TypeOrmModule] Unable to connect to the database.
FATAL: password authentication failed for user "postgres" (postgresql 14 with pgAdmin 4)
In your typeormconfig.ts , you should write this:
export class PostgresTypeormConfiguration implements TypeOrmOptionsFactory
{
createTypeOrmOptions(connectionName?: string): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
const TypeOrmOptions:TypeOrmModuleOptions=
{
type: "postgres",
host: process.env.POSTGRES_HOST ,
port: process.env.POSTGRES_PORT ,
username: process.env.POSTGRES_USER ,
password: process.env.POSTGRES_PASSWORD ,
database: process.env.POSTGRES_DB,
entities: ["dist/**/*.entity{.ts,.js}"],
synchronize: true,
logging: true
}
return TypeOrmOptions
}
}
and you should define this in your module like this:
#Module({
imports:[TypeOrmModule.forRootAsync({useClass:PostgresTypeormConfiguration})]
})
note: if you still got an error , you wrote one of the config option wrong in your .env file or you did not define .env file in your configModule

Strapi v4 PostgreSQL connection from local project to azure db

Trying to connect to an Azure PostgreSQL server from my local Strapi project (eventually deployed in a docker container).
I have the connection configured according to the strapi docs, including using the cert downloaded from the azure portal:
https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/required/databases.html#configuration-structure
my database.js file:
// PostgreSQL
////////////////////////////////////////
const fs = require("#strapi/strapi/lib/services/fs");
const parse = require("pg-connection-string").parse;
const db = parse("azure-conn-string");
module.exports = ({ env }) => ({
connection: {
client: "postgres",
connection: {
host: db.host,
port: db.port,
database: db.database,
user: db.user,
password: db.password,
ssl: {
ca: fs.readFileSync(`${__dirname}/db.crt.pem`).toString(),
},
},
},
});
when starting the server i get this in the terminal:
error: no pg_hba.conf entry for host "ip-address", user "username", database "db_name", SSL off
at Parser.parseErrorMessage (/Users/x/x/dockertest/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/x/x/dockertest/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/x/x/dockertest/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/x/x/dockertest/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (events.js:400:28)
at Socket.emit (domain.js:475:12)
at addChunk (internal/streams/readable.js:293:12)
at readableAddChunk (internal/streams/readable.js:267:9)
at Socket.Readable.push (internal/streams/readable.js:206:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
It seems like its trying to connect with ssl off, I'm not sure why since it should be configured to be enabled. If I remove the ssl rule from the azure database, the connection will go through so it seems like the problem is something with the ssl config.
Can anyone help?
module.exports = ({ env }) => ({
defaultConnection: "default",
connection: {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "postgres"),
user: env("DATABASE_USER", "postgres"),
password: env("DATABASE_PASSWORD", "0000"),
schema: env("DATABASE_SCHEMA", "public"),
},
}
});

Postgres - run \c command in github actions

In GitHub actions, I am running a JavaScript file which connects to PostgreSQL and creates the table and extension for the database.
my script looks like this:
const { Client } = require('pg')
const pgclient = new Client({
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
})
pgclient.connect()
const createDB = `
drop database mydb;
create database mydb;
\c mydb;
CREATE EXTENSION "pgcrypto";
`
pgclient.query(createDB, (err, res) => {
if (err) throw err
pgclient.end()
})
When I run the script, I get an error
error: syntax error at or near "c"
Which I am guessing is coming from \c flag.
How do I use PostgreSQL commands like this?
you can not use \c here because it is a psql meta-command, which I think you do not use here: See https://www.postgresql.org/docs/current/app-psql.html.
You need to reconnect to the new DB like so:
const pgclient_mydb = new Client({
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: 'mydb',
})
pgclient_mydb.connect()
See also https://stackoverflow.com/a/43670984/10743176

issues connecting to postgres using pg client

Trying to connect to postgres using the pg client (following these instructions).
Here is my connection string var connectionString = "postgres://postgres:pass#localhost/ip:5432/chat";
Here's the error I'm getting trying to connect:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): error: database "ip:5432/twitchchat" does not exist
However, when I run pg_isready I get the response /tmp:5432 - accepting connections Which I read as telling me postgres is running on port 5432.
The database is very definitely existing.
Here's the simple connection code:
var pg = require('pg');
var connectionString =
"postgres://postgres:pass#localhost/ip:5432/chat";
var connection = new pg.Client(connectionString);
connection.connect();
What's happening here? How do I fix this?
Your connection string is malformed:
Change it to:
`"postgres://postgres:pass#localhost:5432/chat"`
The correct format is:
postgresql://[user]:[password]#[address]:[port]/[dbname]
Ok I fixed it with the following:
const { Client } = require('pg');
const connection = new Client({
user: 'postgres',
host: 'localhost',
database: 'chat',
password: 'pass',
port: 5432,
});
connection.connect();

MongoError: failed to connect to server [mongo:27017] on first connect

Docker config:
FROM node:8
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD [ "npm", "start" ]
Docker compose:
version: "2"
services:
web:
build: .
depends_on:
- mongo
mongo:
image: mongo
ports:
- "27017:27017"
package.json:
{
"name": "docker_web_app",
"version": "1.0.0",
"description": "",
"author": "Stepan Yakovenko <stiv.yakovenko#gmail.com>",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {"express": "^4.16.1","mongodb": "~3.0.1","monk": "~6.0.5" }
}
server.js:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongo:27017/nodetest1');
db.then(function(){console.log("hello"});
Most of the time it works, but if I purge docker cache, usually it doesn't work and gives me this:
web_1 | (node:15) UnhandledPromiseRejectionWarning: MongoError: failed to connect to server [mongo:27017] on first connect [MongoErr
or: connect ECONNREFUSED 172.18.0.2:27017]
The root cause I think that docker's depends_on doesn't guarantee me that mongo has started listening, because in this case I get listening message from mongo after this error. How can I fix this? Does docker has any fix for this situation? Or how can I ask mongo to try connecting forever?
Thanx
This is sample reconnect code, which worked for me:
var connect = function () {
var db = monk('mongo:27017/nodetest1');
db.then(function () {
console.log("connected");
}).catch(function () {
// sometimes node starts before mongo, so we have to reconnect in case of error
connect();
});
};
connect();