Struct sqlx::postgres::PgConnectOptions

source ยท
pub struct PgConnectOptions { /* private fields */ }
Available on crate feature postgres only.
Expand description

Options and flags which can be used to configure a PostgreSQL connection.

A value of PgConnectOptions can be parsed from a connection URL, as described by libpq.

The general form for a connection URL is:

postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...]

This type also implements FromStr so you can parse it from a string containing a connection URL and then further adjust options if necessary (see example below).

ยงParameters

ParameterDefaultDescription
sslmodepreferDetermines whether or with what priority a secure SSL TCP/IP connection will be negotiated. See PgSslMode.
sslrootcertNoneSets the name of a file containing a list of trusted SSL Certificate Authorities.
statement-cache-capacity100The maximum number of prepared statements stored in the cache. Set to 0 to disable.
hostNonePath to the directory containing a PostgreSQL unix domain socket, which will be used instead of TCP if set.
hostaddrNoneSame as host, but only accepts IP addresses.
application-nameNoneThe name will be displayed in the pg_stat_activity view and included in CSV log entries.
userresult of whoamiPostgreSQL user name to connect as.
passwordNonePassword to be used if the server demands password authentication.
port5432Port number to connect to at the server host, or socket file name extension for Unix-domain connections.
dbnameNoneThe database name.
optionsNoneThe runtime parameters to send to the server at connection start.

The URL scheme designator can be either postgresql:// or postgres://. Each of the URL parts is optional.

postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://localhost?dbname=mydb&user=postgres&password=postgres

ยงExample

use sqlx::{Connection, ConnectOptions};
use sqlx::postgres::{PgConnectOptions, PgConnection, PgPool, PgSslMode};

// URL connection string
let conn = PgConnection::connect("postgres://localhost/mydb").await?;

// Manually-constructed options
let conn = PgConnectOptions::new()
    .host("secret-host")
    .port(2525)
    .username("secret-user")
    .password("secret-password")
    .ssl_mode(PgSslMode::Require)
    .connect()
    .await?;

// Modifying options parsed from a string
let mut opts: PgConnectOptions = "postgres://localhost/mydb".parse()?;

// Change the log verbosity level for queries.
// Information about SQL queries is logged at `DEBUG` level by default.
opts = opts.log_statements(log::LevelFilter::Trace);

let pool = PgPool::connect_with(&opts).await?;

Implementationsยง

sourceยง

impl PgConnectOptions

source

pub fn new() -> PgConnectOptions

Creates a new, default set of options ready for configuration.

By default, this reads the following environment variables and sets their equivalent options.

  • PGHOST
  • PGPORT
  • PGUSER
  • PGPASSWORD
  • PGDATABASE
  • PGSSLROOTCERT
  • PGSSLCERT
  • PGSSLKEY
  • PGSSLMODE
  • PGAPPNAME
ยงExample
let options = PgConnectOptions::new();
source

pub fn new_without_pgpass() -> PgConnectOptions

source

pub fn host(self, host: &str) -> PgConnectOptions

Sets the name of the host to connect to.

If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication; the value is the name of the directory in which the socket file is stored.

The default behavior when host is not specified, or is empty, is to connect to a Unix-domain socket

ยงExample
let options = PgConnectOptions::new()
    .host("localhost");
source

pub fn port(self, port: u16) -> PgConnectOptions

Sets the port to connect to at the server host.

The default port for PostgreSQL is 5432.

ยงExample
let options = PgConnectOptions::new()
    .port(5432);
source

pub fn socket(self, path: impl AsRef<Path>) -> PgConnectOptions

Sets a custom path to a directory containing a unix domain socket, switching the connection method from TCP to the corresponding socket.

By default set to None.

source

pub fn username(self, username: &str) -> PgConnectOptions

Sets the username to connect as.

Defaults to be the same as the operating system name of the user running the application.

ยงExample
let options = PgConnectOptions::new()
    .username("postgres");
source

pub fn password(self, password: &str) -> PgConnectOptions

Sets the password to use if the server demands password authentication.

ยงExample
let options = PgConnectOptions::new()
    .username("root")
    .password("safe-and-secure");
source

pub fn database(self, database: &str) -> PgConnectOptions

Sets the database name. Defaults to be the same as the user name.

ยงExample
let options = PgConnectOptions::new()
    .database("postgres");
source

pub fn ssl_mode(self, mode: PgSslMode) -> PgConnectOptions

Sets whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.

By default, the SSL mode is Prefer, and the client will first attempt an SSL connection but fallback to a non-SSL connection on failure.

Ignored for Unix domain socket communication.

ยงExample
let options = PgConnectOptions::new()
    .ssl_mode(PgSslMode::Require);
source

pub fn ssl_root_cert(self, cert: impl AsRef<Path>) -> PgConnectOptions

Sets the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the serverโ€™s certificate will be verified to be signed by one of these authorities.

ยงExample
let options = PgConnectOptions::new()
    // Providing a CA certificate with less than VerifyCa is pointless
    .ssl_mode(PgSslMode::VerifyCa)
    .ssl_root_cert("./ca-certificate.crt");
source

pub fn ssl_client_cert(self, cert: impl AsRef<Path>) -> PgConnectOptions

Sets the name of a file containing SSL client certificate.

ยงExample
let options = PgConnectOptions::new()
    // Providing a CA certificate with less than VerifyCa is pointless
    .ssl_mode(PgSslMode::VerifyCa)
    .ssl_client_cert("./client.crt");
source

pub fn ssl_client_cert_from_pem( self, cert: impl AsRef<[u8]> ) -> PgConnectOptions

Sets the SSL client certificate as a PEM-encoded byte slice.

This should be an ASCII-encoded blob that starts with -----BEGIN CERTIFICATE-----.

ยงExample

Note: embedding SSL certificates and keys in the binary is not advised. This is for illustration purposes only.


const CERT: &[u8] = b"\
-----BEGIN CERTIFICATE-----
<Certificate data here.>
-----END CERTIFICATE-----";
    
let options = PgConnectOptions::new()
    // Providing a CA certificate with less than VerifyCa is pointless
    .ssl_mode(PgSslMode::VerifyCa)
    .ssl_client_cert_from_pem(CERT);
source

pub fn ssl_client_key(self, key: impl AsRef<Path>) -> PgConnectOptions

Sets the name of a file containing SSL client key.

ยงExample
let options = PgConnectOptions::new()
    // Providing a CA certificate with less than VerifyCa is pointless
    .ssl_mode(PgSslMode::VerifyCa)
    .ssl_client_key("./client.key");
source

pub fn ssl_client_key_from_pem(self, key: impl AsRef<[u8]>) -> PgConnectOptions

Sets the SSL client key as a PEM-encoded byte slice.

This should be an ASCII-encoded blob that starts with -----BEGIN PRIVATE KEY-----.

ยงExample

Note: embedding SSL certificates and keys in the binary is not advised. This is for illustration purposes only.


const KEY: &[u8] = b"\
-----BEGIN PRIVATE KEY-----
<Private key data here.>
-----END PRIVATE KEY-----";

let options = PgConnectOptions::new()
    // Providing a CA certificate with less than VerifyCa is pointless
    .ssl_mode(PgSslMode::VerifyCa)
    .ssl_client_key_from_pem(KEY);
source

pub fn ssl_root_cert_from_pem( self, pem_certificate: Vec<u8> ) -> PgConnectOptions

Sets PEM encoded trusted SSL Certificate Authorities (CA).

ยงExample
let options = PgConnectOptions::new()
    // Providing a CA certificate with less than VerifyCa is pointless
    .ssl_mode(PgSslMode::VerifyCa)
    .ssl_root_cert_from_pem(vec![]);
source

pub fn statement_cache_capacity(self, capacity: usize) -> PgConnectOptions

Sets the capacity of the connectionโ€™s statement cache in a number of stored distinct statements. Caching is handled using LRU, meaning when the amount of queries hits the defined limit, the oldest statement will get dropped.

The default cache capacity is 100 statements.

source

pub fn application_name(self, application_name: &str) -> PgConnectOptions

Sets the application name. Defaults to None

ยงExample
let options = PgConnectOptions::new()
    .application_name("my-app");
source

pub fn extra_float_digits( self, extra_float_digits: impl Into<Option<i8>> ) -> PgConnectOptions

Sets or removes the extra_float_digits connection option.

This changes the default precision of floating-point values returned in text mode (when not using prepared statements such as calling methods of Executor directly).

Historically, Postgres would by default round floating-point values to 6 and 15 digits for float4/REAL (f32) and float8/DOUBLE (f64), respectively, which would mean that the returned value may not be exactly the same as its representation in Postgres.

The nominal range for this value is -15 to 3, where negative values for this option cause floating-points to be rounded to that many fewer digits than normal (-1 causes float4 to be rounded to 5 digits instead of six, or 14 instead of 15 for float8), positive values cause Postgres to emit that many extra digits of precision over default (or simply use maximum precision in Postgres 12 and later), and 0 means keep the default behavior (or the โ€œoldโ€ behavior described above as of Postgres 12).

SQLx sets this value to 3 by default, which tells Postgres to return floating-point values at their maximum precision in the hope that the parsed value will be identical to its counterpart in Postgres. This is also the default in Postgres 12 and later anyway.

However, older versions of Postgres and alternative implementations that talk the Postgres protocol may not support this option, or the full range of values.

If you get an error like โ€œunknown option extra_float_digitsโ€ when connecting, try setting this to None or consult the manual of your database for the allowed range of values.

For more information, see:

ยงExamples

let mut options = PgConnectOptions::new()
    // for Redshift and Postgres 10
    .extra_float_digits(2);

let mut options = PgConnectOptions::new()
    // don't send the option at all (Postgres 9 and older)
    .extra_float_digits(None);
source

pub fn options<K, V, I>(self, options: I) -> PgConnectOptions
where K: Display, V: Display, I: IntoIterator<Item = (K, V)>,

Set additional startup options for the connection as a list of key-value pairs.

ยงExample
let options = PgConnectOptions::new()
    .options([("geqo", "off"), ("statement_timeout", "5min")]);
sourceยง

impl PgConnectOptions

source

pub fn get_host(&self) -> &str

Get the current host.

ยงExample
let options = PgConnectOptions::new()
    .host("127.0.0.1");
assert_eq!(options.get_host(), "127.0.0.1");
source

pub fn get_port(&self) -> u16

Get the serverโ€™s port.

ยงExample
let options = PgConnectOptions::new()
    .port(6543);
assert_eq!(options.get_port(), 6543);
source

pub fn get_socket(&self) -> Option<&PathBuf>

Get the socket path.

ยงExample
let options = PgConnectOptions::new()
    .socket("/tmp");
assert!(options.get_socket().is_some());
source

pub fn get_username(&self) -> &str

Get the serverโ€™s port.

ยงExample
let options = PgConnectOptions::new()
    .username("foo");
assert_eq!(options.get_username(), "foo");
source

pub fn get_database(&self) -> Option<&str>

Get the current database name.

ยงExample
let options = PgConnectOptions::new()
    .database("postgres");
assert!(options.get_database().is_some());
source

pub fn get_ssl_mode(&self) -> PgSslMode

Get the SSL mode.

ยงExample
let options = PgConnectOptions::new();
assert!(matches!(options.get_ssl_mode(), PgSslMode::Prefer));
source

pub fn get_application_name(&self) -> Option<&str>

Get the application name.

ยงExample
let options = PgConnectOptions::new()
    .application_name("service");
assert!(options.get_application_name().is_some());
source

pub fn get_options(&self) -> Option<&str>

Get the options.

ยงExample
let options = PgConnectOptions::new()
    .options([("foo", "bar")]);
assert!(options.get_options().is_some());

Trait Implementationsยง

sourceยง

impl Clone for PgConnectOptions

sourceยง

fn clone(&self) -> PgConnectOptions

Returns a copy 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 ConnectOptions for PgConnectOptions

ยง

type Connection = PgConnection

sourceยง

fn from_url(url: &Url) -> Result<PgConnectOptions, Error>

Parse the ConnectOptions from a URL.
sourceยง

fn to_url_lossy(&self) -> Url

Get a connection URL that may be used to connect to the same database as this ConnectOptions. Read more
sourceยง

fn connect( &self ) -> Pin<Box<dyn Future<Output = Result<<PgConnectOptions as ConnectOptions>::Connection, Error>> + Send + '_>>

Establish a new database connection with the options specified by self.
sourceยง

fn log_statements(self, level: LevelFilter) -> PgConnectOptions

Log executed statements with the specified level
sourceยง

fn log_slow_statements( self, level: LevelFilter, duration: Duration ) -> PgConnectOptions

Log executed statements with a duration above the specified duration at the specified level.
sourceยง

fn disable_statement_logging(self) -> Self

Entirely disables statement logging (both slow and regular).
sourceยง

impl Debug for PgConnectOptions

sourceยง

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

Formats the value using the given formatter. Read more
sourceยง

impl Default for PgConnectOptions

sourceยง

fn default() -> PgConnectOptions

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl FromStr for PgConnectOptions

ยง

type Err = Error

The associated error which can be returned from parsing.
sourceยง

fn from_str(s: &str) -> Result<PgConnectOptions, Error>

Parses a string s to return a value of this type. Read more
sourceยง

impl<'a> TryFrom<&'a AnyConnectOptions> for PgConnectOptions

ยง

type Error = Error

The type returned in the event of a conversion error.
sourceยง

fn try_from( value: &'a AnyConnectOptions ) -> Result<PgConnectOptions, <PgConnectOptions as TryFrom<&'a AnyConnectOptions>>::Error>

Performs the conversion.

Auto Trait Implementationsยง

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> 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> Same for T

ยง

type Output = T

Should always be Self
sourceยง

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

ยง

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>,

ยง

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>,

ยง

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