pub struct PgConnectOptions { /* private fields */ }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&...]The URL scheme designator can be either postgresql:// or postgres://.
Each of the URL parts is optional. For defaults, see the next section.
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).
Note that characters not allowed in URLs must be percent-encoded.
ยงParameters
This API accepts many of the same parameters as libpq; if a parameter is not passed in via URL, it is populated by reading environment variables or choosing customary defaults.
| Parameter | Environment Variable | Default / Remarks |
|---|---|---|
user | PGUSER | The whoami of the currently running process. |
password | PGPASSWORD | Read from passfile, if it exists. |
passfile | PGPASSFILE | ~/.pgpass or %APPDATA%\postgresql\pgpass.conf (Windows) |
host | PGHOST | See Note: Default Host. |
hostaddr | PGHOSTADDR | See Note: Default Host. |
port | PGPORT | 5432 |
dbname | PGDATABASE | Unset; defaults to the username server-side. |
sslmode | PGSSLMODE | prefer. See PgSslMode for details. |
sslrootcert | PGSSLROOTCERT | Unset. See Note: SSL. |
sslcert | PGSSLCERT | Unset. See Note: SSL. |
sslkey | PGSSLKEY | Unset. See Note: SSL. |
options | PGOPTIONS | Unset. |
application_name | PGAPPNAME | Unset. |
passfile handling may be bypassed using PgConnectOptions::new_without_pgpass().
ยงSQLx-Specific
SQLx also parses some bespoke parameters. These are not configurable by environment variable. Instead, the name is linked to the method to set the value.
| Parameter | Default |
|---|---|
statement-cache-capacity | 100 |
ยงExample URLs
postgresql://
postgresql://:5433
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://user:correct%20horse%20battery%20staple@localhost
postgresql://localhost?dbname=mydb&user=postgres&password=postgresSee also Note: Unix Domain Sockets below.
ยงNote: Default Host
If the connection URL does not contain a hostname and PGHOST is not set,
this constructor looks for an open Unix domain socket in one of a few standard locations
(configured when Postgres is built):
/var/run/postgresql/.s.PGSQL.{port}(Debian)/private/tmp/.s.PGSQL.{port}(macOS when installed through Homebrew)/tmp/.s.PGSQL.{port}(default otherwise)
This depends on the value of port being correct.
If Postgres is using a port other than the default (5432), port must be set.
If no Unix domain socket is found, localhost is assumed.
Note: this description is updated on a best-effort basis.
See default_host() in the same source file as this method for the current behavior.
ยงNote: SSL
ยงRoot Certs
If sslrootcert is not set, the default root certificates used depends on Cargo features:
- If
tls-native-tlsis enabled, the system root certificates are used. - If
tls-rustls-ring-native-rootsis enabled, the system root certificates are used. - Otherwise, TLS roots are populated using the
webpki-rootscrate.
ยงEnvironment Variables
Unlike with libpq, the following environment variables may be either
a path to a file or a string value containing a PEM-encoded value:
PGSSLROOTCERTPGSSLCERTPGSSLKEY
If the string begins with the standard -----BEGIN <CERTIFICATE | PRIVATE KEY>----- header
and ends with the standard -----END <CERTIFICATE | PRIVATE KEY>----- footer,
it is parsed directly.
This behavior is only implemented for the environment variables, not the URL parameters.
Note: passing the SSL private key via environment variable may be a security risk.
ยงNote: Unix Domain Sockets
If you want to connect to Postgres over a Unix domain socket, you can pass the path
to the directory containing the socket as the host parameter.
The final path to the socket will be {host}/.s.PGSQL.{port} as is standard for Postgres.
If youโre passing the domain socket path as the host segment of the URL, forward slashes
in the path must be percent-encoded (replacing / with %2F), e.g.:
postgres://%2Fvar%2Frun%2Fpostgresql/dbname
Different port:
postgres://%2Fvar%2Frun%2Fpostgresql:5433/dbname
With username and password:
postgres://user:password@%2Fvar%2Frun%2Fpostgresql/dbname
With username and password, and different port:
postgres://user:password@%2Fvar%2Frun%2Fpostgresql:5432/dbnameInstead, the hostname can be passed in the query segment of the URL, which does not require forward-slashes to be percent-encoded (however, other characters are):
postgres:dbname?host=/var/run/postgresql
Different port:
postgres://:5433/dbname?host=/var/run/postgresql
With username and password:
postgres://user:password@/dbname?host=/var/run/postgresql
With username and password, and different port:
postgres://user:password@:5433/dbname?host=/var/run/postgresqlยง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
impl PgConnectOptions
Sourcepub fn new() -> PgConnectOptions
pub fn new() -> PgConnectOptions
Create a default set of connection options populated from the current environment.
This behaves as if parsed from the connection string postgres://
See the type-level documentation for details.
Sourcepub fn new_without_pgpass() -> PgConnectOptions
pub fn new_without_pgpass() -> PgConnectOptions
Create a default set of connection options without reading from passfile.
Equivalent to PgConnectOptions::new() but passfile is ignored.
See the type-level documentation for details.
Sourcepub fn host(self, host: &str) -> PgConnectOptions
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");Sourcepub fn port(self, port: u16) -> PgConnectOptions
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);Sourcepub fn socket(self, path: impl AsRef<Path>) -> PgConnectOptions
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.
Sourcepub fn username(self, username: &str) -> PgConnectOptions
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");Sourcepub fn password(self, password: &str) -> PgConnectOptions
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");Sourcepub fn database(self, database: &str) -> PgConnectOptions
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");Sourcepub fn ssl_mode(self, mode: PgSslMode) -> PgConnectOptions
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);Sourcepub fn ssl_root_cert(self, cert: impl AsRef<Path>) -> PgConnectOptions
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");Sourcepub fn ssl_client_cert(self, cert: impl AsRef<Path>) -> PgConnectOptions
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");Sourcepub fn ssl_client_cert_from_pem(
self,
cert: impl AsRef<[u8]>,
) -> PgConnectOptions
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);Sourcepub fn ssl_client_key(self, key: impl AsRef<Path>) -> PgConnectOptions
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");Sourcepub fn ssl_client_key_from_pem(self, key: impl AsRef<[u8]>) -> PgConnectOptions
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);Sourcepub fn ssl_root_cert_from_pem(
self,
pem_certificate: Vec<u8>,
) -> PgConnectOptions
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![]);Sourcepub fn statement_cache_capacity(self, capacity: usize) -> PgConnectOptions
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.
Sourcepub fn application_name(self, application_name: &str) -> PgConnectOptions
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");Sourcepub fn extra_float_digits(
self,
extra_float_digits: impl Into<Option<i8>>,
) -> PgConnectOptions
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:
- Postgres manual, 20.11.2: Client Connection Defaults; Locale and Formatting
- Postgres manual, 8.1.3: Numeric Types; Floating-point Types
ยง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);Sourcepub fn options<K, V, I>(self, options: I) -> PgConnectOptions
pub fn options<K, V, I>(self, options: I) -> PgConnectOptions
Set additional startup options for the connection as a list of key-value pairs.
Escapes the optionsโ backslash and space characters as per https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
ยงExample
let options = PgConnectOptions::new()
.options([("geqo", "off"), ("statement_timeout", "5min")]);Sourceยงimpl PgConnectOptions
impl PgConnectOptions
Sourcepub fn get_host(&self) -> &str
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");Sourcepub fn get_port(&self) -> u16
pub fn get_port(&self) -> u16
Get the serverโs port.
ยงExample
let options = PgConnectOptions::new()
.port(6543);
assert_eq!(options.get_port(), 6543);Sourcepub fn get_socket(&self) -> Option<&PathBuf>
pub fn get_socket(&self) -> Option<&PathBuf>
Get the socket path.
ยงExample
let options = PgConnectOptions::new()
.socket("/tmp");
assert!(options.get_socket().is_some());Sourcepub fn get_username(&self) -> &str
pub fn get_username(&self) -> &str
Get the serverโs port.
ยงExample
let options = PgConnectOptions::new()
.username("foo");
assert_eq!(options.get_username(), "foo");Sourcepub fn get_database(&self) -> Option<&str>
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());Sourcepub fn get_ssl_mode(&self) -> PgSslMode
pub fn get_ssl_mode(&self) -> PgSslMode
Get the SSL mode.
ยงExample
let options = PgConnectOptions::new();
assert!(matches!(options.get_ssl_mode(), PgSslMode::Prefer));Sourcepub fn get_application_name(&self) -> Option<&str>
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());Sourcepub fn get_options(&self) -> Option<&str>
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
impl Clone for PgConnectOptions
Sourceยงfn clone(&self) -> PgConnectOptions
fn clone(&self) -> PgConnectOptions
1.0.0 ยท Sourceยงfn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSourceยงimpl ConnectOptions for PgConnectOptions
impl ConnectOptions for PgConnectOptions
type Connection = PgConnection
Sourceยงfn from_url(url: &Url) -> Result<PgConnectOptions, Error>
fn from_url(url: &Url) -> Result<PgConnectOptions, Error>
ConnectOptions from a URL.Sourceยงfn to_url_lossy(&self) -> Url
fn to_url_lossy(&self) -> Url
ConnectOptions. Read moreSourceยงfn connect(
&self,
) -> impl Future<Output = Result<<PgConnectOptions as ConnectOptions>::Connection, Error>> + Send
fn connect( &self, ) -> impl Future<Output = Result<<PgConnectOptions as ConnectOptions>::Connection, Error>> + Send
self.Sourceยงfn log_statements(self, level: LevelFilter) -> PgConnectOptions
fn log_statements(self, level: LevelFilter) -> PgConnectOptions
levelSourceยงfn log_slow_statements(
self,
level: LevelFilter,
duration: Duration,
) -> PgConnectOptions
fn log_slow_statements( self, level: LevelFilter, duration: Duration, ) -> PgConnectOptions
duration
at the specified level.Sourceยงfn disable_statement_logging(self) -> Self
fn disable_statement_logging(self) -> Self
Sourceยงimpl Debug for PgConnectOptions
impl Debug for PgConnectOptions
Sourceยงimpl Default for PgConnectOptions
impl Default for PgConnectOptions
Sourceยงfn default() -> PgConnectOptions
fn default() -> PgConnectOptions
Sourceยงimpl FromStr for PgConnectOptions
impl FromStr for PgConnectOptions
Sourceยงimpl<'a> TryFrom<&'a AnyConnectOptions> for PgConnectOptions
impl<'a> TryFrom<&'a AnyConnectOptions> for PgConnectOptions
Sourceยงfn try_from(
value: &'a AnyConnectOptions,
) -> Result<PgConnectOptions, <PgConnectOptions as TryFrom<&'a AnyConnectOptions>>::Error>
fn try_from( value: &'a AnyConnectOptions, ) -> Result<PgConnectOptions, <PgConnectOptions as TryFrom<&'a AnyConnectOptions>>::Error>
Auto Trait Implementationsยง
impl Freeze for PgConnectOptions
impl RefUnwindSafe for PgConnectOptions
impl Send for PgConnectOptions
impl Sync for PgConnectOptions
impl Unpin for PgConnectOptions
impl UnwindSafe for PgConnectOptions
Blanket Implementationsยง
Sourceยงimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Sourceยงfn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Sourceยงimpl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Sourceยงimpl<T> Instrument for T
impl<T> Instrument for T
Sourceยงfn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Sourceยงfn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Sourceยงimpl<T> IntoEither for T
impl<T> IntoEither for T
Sourceยงfn into_either(self, into_left: bool) -> Either<Self, Self> โ
fn into_either(self, into_left: bool) -> Either<Self, Self> โ
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 moreSourceยงfn into_either_with<F>(self, into_left: F) -> Either<Self, Self> โ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> โ
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