(PostgreSQL) 12.7 (Ubuntu 12.7-0ubuntu0.20.04.1) can't connect to the database? - postgresql

This is on WSl 2 following the instructions from the official documentation
I created a simple postgresql and I try to connect to it like so:
const Sequelize = require("sequelize");
const sequelize = new Sequelize('postgres://postgres:w#localhost:5432/messenger', {
logging: false,
dialect: 'postgre'
});
async function test(){
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
test();
This will tell me if the connection was successful or not, but for some reason, I keep getting this error. The URI string seems correct, the only user is the default created Postgres where I changed the password to be "w" for testing purposes.
Not sure what that 12/main part is about but the server is online so I am really not sure what the problem is.

Either you specified the wrong password for the database user "postgres", or your server isn't configured to allow password authentication on localhost. You can see this link: https://www.postgresql.org/docs/current/auth-methods.html for more information on the authentication methods postgresql supports, or this one: https://www.postgresql.org/docs/current/auth-pg-hba-conf.html for information on how to set up authentication on your postgresql server.

Related

NextJs + Mongoose + Mongo Atlas multiple connections even with caching

I am using NextJS to build an app. I am using MongoDB via mongoosejs to connect to my database hosted in mongoAtlas.
My database connection file looks like below
import mongoose from "mongoose";
const MONGO_URI =
process.env.NODE_ENV === "development"
? process.env.MONGO_URI_DEVELOPMENT
: process.env.MONGO_URI_PRODUCTION;
console.log(`Connecting to ${MONGO_URI}`);
const database_connection = async () => {
if (global.connection?.isConnected) {
console.log("reusing database connection")
return;
}
const database = await mongoose.connect(MONGO_URI, {
authSource: "admin",
useNewUrlParser: true
});
global.connection = { isConnected: database.connections[0].readyState }
console.log("new database connection created")
};
export default database_connection;
I have seen this MongoDB developer community thread and this GitHub thread.
The problem seems to happen only in dev mode(when you run yarn run dev). In the production version hosted on Vercel there seems to be no issue. I understand that in dev mode the server is restarted every time a change is saved so to cache a connection you need to use as global variable. As you can see above, I have done exactly that. The server even logs: reusing database connection, then in mongoAtlas it shows like 10 more connections opened.
How can I solve this issue or what am I doing wrong?

Connect to Amazon RDS PostgresQL Proxy with IAM Credentials using TypeORM

I'm trying to figure out how to connect to a RDS PG Proxy within a lambda function using TypeORM (so there's no issues establishing connections). I'm able to connect to the RDS instance with the Lambda function successfully - however, when I point the information at the proxy (change the environment variables within the Lambda function) I am greeted with the following error:
{
"errorType": "Error",
"errorMessage": "read ECONNRESET",
"code": "ECONNRESET",
"errno": "ECONNRESET",
"syscall": "read",
"stack": [
"Error: read ECONNRESET",
" at TCP.onStreamRead (internal/stream_base_commons.js:205:27)"
]
}
Here is the code used to create the connection with TypeORM:
const config = getDBConfig();
connection = await createConnection(config);
// Retrieve database connection options
const getDBConfig = (): ConnectionOptions => {
// Use IAM-based authentication to connect
const signer = new RDS.Signer({
region: "us-east-1",
username: process.env.USERNAME,
hostname: process.env.HOSTNAME,
port: 5432,
});
// Retrieve password dynamically from RDS
const token = signer.getAuthToken({
username: process.env.USERNAME,
});
// Return configuration object
return {
username: process.env.USERNAME,
host: process.env.HOSTNAME,
port: 5432,
password: token,
ssl: {
ca: fs.readFileSync("./config/rds-ca-2019-root.pem").toString(),
},
type: "postgres",
database: "postgres",
synchronize: false,
entities: [],
};
};
In terms of the two environment variables, HOSTNAME is equal to the URL provided by RDS proxy, and USERNAME is the username assigned within the secret for the RDS Proxy. Both the Lambda function and RDS Proxy have been given admin access, just to ensure there's no interference there (I know this is horrible, will reduce privileges once I get this working!). IAM authentication has been set to required for the proxy.
Update 8/14/2020
This article explains how you would connect RDS MySQL Proxy with TypeORM, still have not figured out how to connect to a RDS PG Proxy though.
https://dev.to/vikasgarghb/rds-proxy-via-sam-15gn
I've finally found the instructions to setup DB user for PG in the AWS docs. Posting this here for anyone also having trouble finding them.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html#UsingWithRDS.IAMDBAuth.DBAccounts.PostgreSQL
Basically you just need to add user to existing rds_iam group.
CREATE USER lambda;
GRANT ALL PRIVILEGES ON DATABASE postgres TO lambda;
GRANT rds_iam TO lambda;

The first part before dot operator of the PostgreSQL service host name is not validated by the IBM PostgreSQL cloud service

We have IBM Cloud PostgreSQL instance. We are connecting to it using node-postgres client or odbc client with Data Direct Driver. As per our understanding the PostgreSQL service instance should throw error when provide incorrect host while connecting. However, the instance is not throwing any error when providing incorrect host (incorrect value for the first part of the host string before dot operator).
Steps to reproduce the issue
Create IBM Cloud PostgreSQL instance. Below is the format of host string
<<1st part of host>>.<<2nd part of host>>.databases.appdomain.cloud
Connect to instance using node client using node-postgres client or odbc client with Data Direct Driver with incorrect value for the first portion(<<1st part of host>>) of the host.
It will connect successfully without any issue. If we provide incorrect value(<<2nd part of host>>.databases.appdomain.cloud) for remaining portion it throws error.
Used below code snippet for validating this scenario:
const pg = require('pg')
const connectionString = 'postgres://user:password#<<1st part of host>>.<<2nd part of host>>.databases.appdomain.cloud:31974/ibmclouddb?sslmode=verify-full'
const caCert = 'Self Signed CA Certificate'
const client = new pg.Client(
{
connectionString: connectionString,
ssl: {
ca: caCert,
rejectUnauthorized: false
}
}
)
client.connect()
client.query('select * from test_pg.char_test4').then(res => {
console.log('res.rows :::::: ', res)
}).finally(() => client.end())

Get the PostgreSQL server version from connection?

Is there anything in the modern PostgreSQL connection protocol that would indicate the server version?
And if not, is there a special low-level request that an endpoint can execute against an open connection to pull the server details that would contain the version?
I'm looking at a possible extension of node-postgres that would automatically provide the server version upon every fresh connection. And I want to know if this is at all possible.
Having to execute SELECT version() upon every new connection and then parsing it is too high-level for the base driver that manages the connection. It should be done on the protocol level.
After a bit of research, I found that PostgreSQL does provide server version during connection, within the start-up message.
And specifically within node-postgres driver, we can make Pool provide a custom Client that handles event parameterStatus on the connection, and exposes the server version:
const {Client, Pool} = require('pg');
class MyClient extends Client {
constructor(config) {
super(config);
this.connection.on('parameterStatus', msg => {
if (msg.parameterName === 'server_version') {
this.version = msg.parameterValue;
}
});
}
}
const cn = {
database: 'my-db',
user: 'postgres',
password: 'bla-bla',
Client: MyClient // here's our custom Client type
};
const pool = new Pool(cn);
pool.connect()
.then(client => {
console.log('Server Version:', client.version);
client.release(true);
})
.catch(console.error);
On my test PC, I use PostgreSQL v11.2, so this test outputs:
Server Version: 11.2
UPDATE - 1
Library pg-promise has been updated to support the same functionality in TypeScript. And you can find a complete example in this ticket.
UPDATE - 2
See example here:
// tests connection and returns Postgres server version,
// if successful; or else rejects with connection error:
async function testConnection() {
const c = await db.connect(); // try to connect
c.done(); // success, release connection
return c.client.serverVersion; // return server version
}

nodejs chat example does not work

I've come across a node chat example on github, When I try to run it, I see the following error:
Error connecting to mongo perhaps it isn't running ?
I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io
I can not determine whether if the example not really works or I didn't run it right. Please help.
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.
Check out the follwing code excerpts from chat.io.
main.js:
/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).
UserProvider.js:
UserProvider = function(host, port) {
this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
this.db.addListener('error', function(error) {
console.log('Error connecting to mongo -- perhaps it isn\'t running?');
});
this.db.open(function() {
});
};
Opening the connection to the server, printing out an error on failure (the error you mentioned above).
Consider reading up on the mongo-db docs concerning installation and setup here