0

I want to establish a database connection with tokio_postgres crate. I created a Config object with a connection configuration. However, connect function takes connection string (&str) as an argument. In the docs I couldn't find any way to convert it to (str). Is manually building a connection string an only option?

I also tried to use Display trait

let mut db_config = Config::new();
db_config.
    host("localhost").
    user("admin").
    port(5432).
    password("secret_password").
    dbname("admin");

let (client, connection) =
    tokio_postgres::connect(format!("{}", db_config), NoTls).await.unwrap();

But without success

tokio_postgres::connect(format!("{}", db_config), NoTls).await.unwrap()                                            
                                      ^^^^^^^^^ `Config` cannot be formatted with the default formatter
   
= help: the trait `std::fmt::Display` is not implemented for `Config`
Piotr
  • 91
  • 1
  • 4
  • 2
    `Config` has a [`connect`](https://docs.rs/tokio-postgres/latest/tokio_postgres/config/struct.Config.html#method.connect) method. I guess you should use that rather than the freestanding function. – Jmb Jan 12 '22 at 07:21
  • @Jmb Works! That's exactly what I wanted. Thanks! – Piotr Jan 12 '22 at 07:45

1 Answers1

2

Looking at the source code for tokio_postgres::connect, you can see that it first parses its &str argument into a Config, then calls Config::connect on the result. Since you already have a Config, you can call its connect method directly:

let (client, connection) = Config::new()
    .host("localhost")
    .user("admin")
    .port(5432)
    .password("secret_password")
    .dbname("admin")
    .connect(NoTls)
    .await
    .unwrap();
Jmb
  • 18,893
  • 2
  • 28
  • 55