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`
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();