Skip to main content

Config

Struct Config 

Source
pub struct Config { /* private fields */ }
Expand description

Connection settings: where the server is, who to log in as, and the limits that apply to the connection.

Build one with Config::from_url or with the setters:

use std::time::Duration;
use giong_postgres::Config;

let config = Config::from_url("postgres://app:secret@db.internal:5432/shop?sslmode=verify-full")?;

let same_place = Config::new()
    .host("db.internal")
    .user("app")
    .password("secret")
    .database("shop")
    .statement_timeout(Duration::from_secs(5));

Every limit has a finite default, documented on its setter: a connection never waits forever, and a result never grows without bound.

TLS. Unless tls or sslmode says otherwise, a TCP connection to anything but a loopback address uses TLS and checks the server’s certificate against the certificate authorities installed on the machine; connections over a Unix socket or to a loopback address do not use TLS.

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Settings for localhost:5432, with no user yet and the default limits.

Source

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

The server’s host: a DNS name, an IP address, or the absolute path of the directory holding its Unix socket (such as /var/run/postgresql, or on Windows C:\pgsql\run: PostgreSQL 13 and later listen on Unix sockets there too).

Source

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

The server’s port, 5432 by default. For a Unix socket it picks the socket file, .s.PGSQL.<port>.

Source

pub fn user(self, user: &str) -> Self

The user to log in as. Required.

Source

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

The password, if the server asks for one.

The copy kept here, and every copy made while logging in, is wiped from memory when dropped; the string passed in is the caller’s.

Source

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

The database; the server uses the user’s name when it is not set. In a URL it is the path, or the dbname parameter.

Source

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

The name the server shows for this connection in pg_stat_activity and in its logs.

Source

pub fn param(self, name: &str, value: &str) -> Self

Sets a server setting for the whole session when connecting, such as search_path or TimeZone.

Source

pub fn tls(self, tls: Tls) -> Self

Whether and how to use TLS (see the type’s documentation for what happens when this is not set).

Source

pub fn require_auth(self, methods: &[AuthMethod]) -> Self

The only authentication methods the server may use; by default, any this crate supports. Connecting fails with ErrorKind::Auth, before anything is sent for the password, when the server asks for another method or lets the connection in without one.

Without TLS (over a Unix socket, to a loopback address, or with sslmode=disable), nothing proves that the server is the real one: an impostor can ask for MD5 instead of SCRAM and attack the answer offline, or let the client in without asking anything. require_auth(&[AuthMethod::ScramSha256]) rules that out, since SCRAM makes the server prove that it knows the password too. In a URL: require_auth=scram-sha-256 (a comma-separated list, as in libpq, without libpq’s ! negations).

Source

pub fn connect_timeout(self, timeout: Duration) -> Self

The longest that opening a connection may take, from name resolution to the end of authentication: 10 seconds by default.

Source

pub fn statement_timeout(self, timeout: impl Into<Option<Duration>>) -> Self

The longest a statement may run on the server before the server cancels it: 30 seconds by default.

It is sent as the session’s statement_timeout when connecting, so the server enforces it exactly, and only on the statement that runs too long (SQLSTATE 57014). It is rounded up to whole milliseconds and must be from 1 ms to i32::MAX milliseconds (24.8 days): connecting fails with ErrorKind::Config otherwise. Raise it for the connections that run migrations or reports, rather than turning it off with SET.

None sends nothing, leaving the limit to the server’s own setting, which is no limit unless someone set one. Through a connection pooler such as PgBouncer, give None and set the limit on the role (ALTER ROLE app SET statement_timeout = '30s'): PgBouncer refuses a connection that sends statement_timeout, and its settings that accept it (track_extra_parameters, ignore_startup_parameters) do not pass it on to the server (checked with PgBouncer 1.22).

Source

pub fn max_result_size(self, bytes: usize) -> Self

The largest result one statement may return, in bytes of row data: 64 MiB by default. A larger result fails with ErrorKind::TooLarge, and the connection stays usable.

Source

pub fn statement_cache_capacity(self, statements: usize) -> Self

How many prepared statements each connection keeps, 256 by default.

Every statement is prepared on the server the first time a connection runs it, and kept, so running it again takes one round trip instead of two. The least recently used statement is closed when the cache is full. 0 prepares and closes every statement each time it runs, which takes two round trips; the statement is still a named one, prepared in one request and run in the next, so 0 does not make a connection pooler in transaction mode work: that needs PgBouncer 1.21 or newer with max_prepared_statements above 0, which supports any cache size.

Source

pub fn batch_reads(self, batch: bool) -> Self

Lets Pool send the SELECT statements it runs on its shared connections (query, query_one, query_opt) in batches: off by default.

The server sends its answers to the statements before one Sync message in one write, where it otherwise makes a write, and wakes the client, for each statement; when it is the busy side, it then answers more statements a second (on PostgreSQL 16, about 50% more one-row SELECTs, measured with pgbench in batches of 16). A batch is the SELECTs that are waiting to be written to one connection when it writes, at most 16: a statement never waits for others to join it.

A SELECT whose text contains set_config runs alone, never in a batch: the statements of a batch share one transaction, and a transaction-local setting (set_config(name, value, true), as row-level security set up per request uses) would apply to the statements of other tasks after it. The text is matched in any case, quoted strings and comments included; a false match only costs the statement its batch. Do not turn it on if functions that statements call make such settings (set_config(.., true) or SET LOCAL inside a function): those calls cannot be seen in the statement’s text.

What changes for a statement in a batch:

  • It runs in one transaction with the others, made read-only first (set_config('transaction_read_only', 'on', true)). A SELECT that writes (one that calls a function that writes, or takes a row lock with FOR UPDATE) fails with the server’s 25006 and is sent again on its own, where it runs as it would without batches; it is not batched again on that connection.
  • When a statement in a batch fails, or the batch’s commit does (a deferred constraint on a temporary table, say), the batch’s transaction is rolled back: the statement that failed fails, and every other statement of the batch is sent again, on its own, whether it had run (what it did was rolled back) or the server had skipped it. What a transaction’s rollback does not undo happens twice then: a sequence advanced by nextval (allowed on temporary sequences) is advanced again, and a session-level advisory lock (pg_advisory_lock, pg_try_advisory_lock) is taken twice, so one unlock leaves it held. One statement that fails on its input (a bad $1::int4, say) also makes up to 15 statements before it run again: bounded, but more work for a database that is the limit.
  • Its answer arrives when the batch ends, once its commit is known: a statement waits for up to 15 others that were written after it. They run one after another on the server either way, so this is added only to the statements early in a batch; keep slow statements and fast ones in different pools when that matters.
  • now() and transaction_timestamp() give the time the batch started, and a transaction-scoped advisory lock is held until the batch ends.
  • The locks its statements take are held until the batch ends, so a statement of a batch waits at most 50 ms for a lock: past that, or when it fails with a deadlock (40P01) or a serialization failure (40001), the batch is rolled back and the statement is sent again alone, where it waits as it would without batches (a lock_timeout shorter than 50 ms then applies to that run). Without that, a batch could deadlock with a transaction that the same statements one by one never would (a migration that locks two tables the batch reads), and the server would roll one of them back.
Source

pub fn from_url(url: &str) -> Result<Self, Error>

Reads a connection URL:

postgres://user:password@host:port/dbname?param=value&...

postgresql:// works too. User, password and database are percent-decoded. The host can be an IPv6 address in brackets, or, as with libpq, empty with the socket directory in a host parameter: postgres:///shop?host=/var/run/postgresql.

The parameters understood are sslmode, sslrootcert, host, port, user, password, dbname, application_name, connect_timeout (seconds) and require_auth (see require_auth); any other is an error rather than being ignored. sslmode is disable, or require, verify-ca or verify-full, which all check the certificate and the host name (stricter than libpq, which checks nothing for require). sslrootcert is a PEM file of authorities to trust instead of the machine’s, or system.

The user name, the password and the database name are percent-decoded: write / as %2F, ? as %3F and @ as %40 in them. A URL with an @ after the first / or ? that would otherwise not read, or with an @ in its database name, is refused with a message that quotes none of it, since a piece of a password with an unescaped / or ? would end up in the message (or, as the database name, be sent to the wrong host).

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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 Default for Config

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl FromStr for Config

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(url: &str) -> Result<Self, Error>

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

Auto Trait Implementations§

§

impl !RefUnwindSafe for Config

§

impl !UnwindSafe for Config

§

impl Forget for Config

§

impl Freeze for Config
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze, PhantomData<(String, String)>: Freeze, *const ArcInner<ClientConfig> is !null: Freeze, PhantomData<ArcInner<ClientConfig>>: Freeze, *const ArcInner<str> is !null: Freeze, PhantomData<ArcInner<str>>: Freeze, *const ArcInner<OnceLock<Result<TlsConnector, String>>> is !null: Freeze, PhantomData<ArcInner<OnceLock<Result<TlsConnector, String>>>>: Freeze, PhantomData<AuthMethod>: Freeze, *const ArcInner<KeyCache> is !null: Freeze, PhantomData<ArcInner<KeyCache>>: Freeze,

§

impl Move for Config

§

impl Send for Config
where RawVecInner: Send, Arc<ClientConfig>: Send, Arc<str>: Send, Arc<OnceLock<Result<TlsConnector, String>>>: Send, Arc<KeyCache>: Send,

§

impl Sync for Config
where RawVecInner: Sync, Arc<ClientConfig>: Sync, Arc<str>: Sync, Arc<OnceLock<Result<TlsConnector, String>>>: Sync, Arc<KeyCache>: Sync,

§

impl Unpin for Config

§

impl UnsafeUnpin 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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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 = !

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

fn try_from(value: U) -> Result<T, !>

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.