Config

Struct Config 

Source
pub struct Config {
    pub application_name: Option<ApplicationName>,
    pub database: Database,
    pub endpoint: Endpoint,
    pub password: Option<Password>,
    pub ssl_mode: SslMode,
    pub ssl_root_cert: Option<SslRootCert>,
    pub username: Username,
}
Expand description

PG connection config with various presentation modes.

Supported:

  1. Env variables via to_pg_env()
  2. JSON document via serde
  3. sqlx connect options via to_sqlx_connect_options()
  4. Individual field access

Fields§

§application_name: Option<ApplicationName>§database: Database§endpoint: Endpoint§password: Option<Password>§ssl_mode: SslMode§ssl_root_cert: Option<SslRootCert>§username: Username

Implementations§

Source§

impl Config

Source

pub fn to_url(&self) -> Url

Convert to PG connection URL


let config = Config {
    application_name: None,
    database: Database::from_str("some-database").unwrap(),
    endpoint: Endpoint::Network {
        host: Host::from_str("some-host").unwrap(),
        host_addr: None,
        port: Some(Port(5432)),
    },
    password: None,
    ssl_mode: SslMode::VerifyFull,
    ssl_root_cert: None,
    username: Username::from_str("some-username").unwrap(),
};

let options = config.to_sqlx_connect_options();

assert_eq!(
    Url::parse(
        "postgres://some-username@some-host:5432/some-database?sslmode=verify-full"
    ).unwrap(),
    config.to_url()
);

assert_eq!(
    Url::parse(
        "postgres://some-username:some-password@some-host:5432/some-database?application_name=some-app&sslmode=verify-full&sslrootcert=%2Fsome.pem"
    ).unwrap(),
    Config {
        application_name: Some(ApplicationName::from_str("some-app").unwrap()),
        password: Some(Password::from_str("some-password").unwrap()),
        ssl_root_cert: Some(SslRootCert::File("/some.pem".into())),
        ..config.clone()
    }.to_url()
);

assert_eq!(
    Url::parse(
        "postgres://some-username@some-host:5432/some-database?hostaddr=127.0.0.1&sslmode=verify-full"
    ).unwrap(),
    Config {
        endpoint: Endpoint::Network {
            host: Host::from_str("some-host").unwrap(),
            host_addr: Some("127.0.0.1".parse().unwrap()),
            port: Some(Port(5432)),
        },
        ..config.clone()
    }.to_url()
);

// IPv4 example
let ipv4_config = Config {
    application_name: None,
    database: Database::from_str("mydb").unwrap(),
    endpoint: Endpoint::Network {
        host: Host::IpAddr(std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1))),
        host_addr: None,
        port: Some(Port(5432)),
    },
    password: None,
    ssl_mode: SslMode::Disable,
    ssl_root_cert: None,
    username: Username::from_str("user").unwrap(),
};
assert_eq!(
    ipv4_config.to_url().to_string(),
    "postgres://user@127.0.0.1:5432/mydb?sslmode=disable"
);

// IPv6 example (automatically bracketed)
let ipv6_config = Config {
    application_name: None,
    database: Database::from_str("mydb").unwrap(),
    endpoint: Endpoint::Network {
        host: Host::IpAddr(std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)),
        host_addr: None,
        port: Some(Port(5432)),
    },
    password: None,
    ssl_mode: SslMode::Disable,
    ssl_root_cert: None,
    username: Username::from_str("user").unwrap(),
};
assert_eq!(
    ipv6_config.to_url().to_string(),
    "postgres://user@[::1]:5432/mydb?sslmode=disable"
);
Source

pub fn to_pg_env(&self) -> BTreeMap<&'static str, String>

Convert to PG environment variable names


let config = Config {
    application_name: None,
    database: "some-database".parse().unwrap(),
    endpoint: Endpoint::Network {
        host: "some-host".parse().unwrap(),
        host_addr: None,
        port: Some(Port(5432)),
    },
    password: None,
    ssl_mode: SslMode::VerifyFull,
    ssl_root_cert: None,
    username: "some-username".parse().unwrap(),
};

let expected = BTreeMap::from([
    ("PGDATABASE", "some-database".to_string()),
    ("PGHOST", "some-host".to_string()),
    ("PGPORT", "5432".to_string()),
    ("PGSSLMODE", "verify-full".to_string()),
    ("PGUSER", "some-username".to_string()),
]);

assert_eq!(expected, config.to_pg_env());

let config_with_optionals = Config {
    application_name: Some("some-app".parse().unwrap()),
    endpoint: Endpoint::Network {
        host: "some-host".parse().unwrap(),
        host_addr: Some("127.0.0.1".parse().unwrap()),
        port: Some(Port(5432)),
    },
    password: Some("some-password".parse().unwrap()),
    ssl_root_cert: Some(SslRootCert::File("/some.pem".into())),
    ..config
};

let expected = BTreeMap::from([
    ("PGAPPNAME", "some-app".to_string()),
    ("PGDATABASE", "some-database".to_string()),
    ("PGHOST", "some-host".to_string()),
    ("PGHOSTADDR", "127.0.0.1".to_string()),
    ("PGPASSWORD", "some-password".to_string()),
    ("PGPORT", "5432".to_string()),
    ("PGSSLMODE", "verify-full".to_string()),
    ("PGSSLROOTCERT", "/some.pem".to_string()),
    ("PGUSER", "some-username".to_string()),
]);

assert_eq!(expected, config_with_optionals.to_pg_env());
Source

pub fn to_sqlx_connect_options( &self, ) -> Result<PgConnectOptions, SqlxOptionsError>

Convert to an sqlx pg connection config


let config = Config {
    application_name: Some(ApplicationName::from_str("some-app").unwrap()),
    database: Database::from_str("some-database").unwrap(),
    endpoint: Endpoint::Network {
        host: Host::from_str("some-host").unwrap(),
        host_addr: None,
        port: Some(Port(5432)),
    },
    password: Some(Password::from_str("some-password").unwrap()),
    ssl_mode: SslMode::VerifyFull,
    ssl_root_cert: Some(SslRootCert::File("/some.pem".into())),
    username: Username::from_str("some-username").unwrap(),
};

let options = config.to_sqlx_connect_options().unwrap();

// `PgConnectOptions` does not have `PartialEq` and only partial getters
// so we can only assert a few fields.
assert_eq!(Some("some-app"), options.get_application_name());
assert_eq!("some-host", options.get_host());
assert_eq!(5432, options.get_port());
assert_eq!("some-username", options.get_username());
// No PartialEQ instance
assert_eq!(format!("{:#?}", sqlx::postgres::PgSslMode::VerifyFull), format!("{:#?}", options.get_ssl_mode()));
assert_eq!(Some("some-database"), options.get_database());
// Unsupported.
// assert_eq!("some-password", options.get_password());
// assert_eq!("/some.pem", options.get_ssl_root_cert());
§Errors

Returns an error if fields inferred from the process environment variables by PgConnectOptions::new contradict the settings in Config, and there is no public API in PgConnectOptions to reset these values.

Source

pub async fn with_sqlx_connection<T, F: AsyncFnMut(&mut PgConnection) -> T>( &self, action: F, ) -> Result<T, SqlxConnectionError>

Source

pub fn endpoint(self, endpoint: Endpoint) -> Self

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Config

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Config

Source§

fn eq(&self, other: &Config) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Config

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Config

Source§

impl StructuralPartialEq for Config

Auto Trait Implementations§

§

impl Freeze for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnwindSafe for Config

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more