简体   繁体   中英

Can you convert tokio_postgres::config::Config to connection string?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM