Skip to content

Reading values out of postgres::Config #534

Closed
@benesch

Description

@benesch

Back with postgres 0.15, I had the following hunk of logic to emulate libpq's behavior around defaults for connection parameters:

let params = url.into_connect_params();

// Fill in default values for parameters using the same logic that libpq
// uses, which involves reading various environment variables.
let params = {
    let mut new_params = postgres::Config::new();

    if let Some(user) = params.user() {
        let password = user
            .password()
            .owned()
            .or_else(|| env::var("PGPASSWORD").ok());
        new_params.user(user.name(), password.as_deref());
    } else {
        let name = env::var("PGUSER").unwrap_or_else(|_| whoami::username());
        let password = env::var("PGPASSWORD").ok();
        new_params.user(&name, password.as_deref());
    }

    if let Some(database) = params
        .database()
        .owned()
        .or_else(|| env::var("PGDATABASE").ok())
    {
        new_params.database(&database);
    }
    new_params.port(params.port());

    let mut host = params.host().clone();
    if let postgres::params::Host::Tcp(hostname) = &host {
        if hostname == "" {
            let host_str = env::var("PGHOST").unwrap_or_else(|_| "localhost".into());
            host = postgres::params::Host::Tcp(host_str);
        }
    }

    new_params.build(host)
};

This was possible because of the separation between postgres::params::ConnectParams and postgres::params::Builder; in postgres 0.17 only the builder exists, so there's no way to introspect the state of a postgres::Config.

Would it be possible to bring back some form of introspection for postgres::Config?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions