Not able to connect Postgres using Rust

I am new to Rust, Postgres, and trying to build a small utility to connected to Postgres database. Below is the code:

#![allow(unused_variables)]
use postgres::{Client, Error, NoTls};

fn main() -> Result<(), Error> {
    // let mut client = db_utils::connect()?;
    let client = Client::connect(
        "postgresql://postgres:postgres@localhost:5432/postgres",
        NoTls
    )?;
    Ok(())
}

And the Error is:

Error: Error { kind: Db, cause: Some(DbError { severity: "FATAL", parsed_severity: Some(Fatal), code: SqlState(E28P01), message: "password authentication failed for user \"postgres\"", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("auth.c"), line: Some(335), routine: Some("auth_failed") }) }

I understand that user 'postgres' doesn't have any password, but if I remove ":postgress" then it fails with error Error: Error { kind: Config, cause: Some("password missing") }
I tried creating another user on Postgres with password but no luck.

Please help, any pointers?

If you're unsure about what your connection string would be like, you can use the Config struct to define your connection config. So in your case it'd be:

let client = Client::configure().user("postgres").host("localhost").connect();

No luck, @RedDocMD! I am getting the same error. I've picked up connection string from postgres::Connection - Rust (docs.rs). So, I think string is correct. Also, service is up and able to connect manually.

Solved!
The issue was with Postgres configuration. In order to connect to Postgres from port, it needs 'md5' authentication configured (default, it's 'peer').

So, as solution, I created a user and database(same name as user), updated pg_hba.conf file to have user configured with 'md5' authentication.

1 Like