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
impl Config
Sourcepub fn host(self, host: &str) -> Self
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).
Sourcepub fn port(self, port: u16) -> Self
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>.
Sourcepub fn database(self, database: &str) -> Self
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.
Sourcepub fn application_name(self, name: &str) -> Self
pub fn application_name(self, name: &str) -> Self
The name the server shows for this connection in pg_stat_activity
and in its logs.
Sourcepub fn param(self, name: &str, value: &str) -> Self
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.
Sourcepub fn tls(self, tls: Tls) -> Self
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).
Sourcepub fn require_auth(self, methods: &[AuthMethod]) -> Self
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).
Sourcepub fn connect_timeout(self, timeout: Duration) -> Self
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.
Sourcepub fn statement_timeout(self, timeout: impl Into<Option<Duration>>) -> Self
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).
Sourcepub fn max_result_size(self, bytes: usize) -> Self
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.
Sourcepub fn statement_cache_capacity(self, statements: usize) -> Self
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.
Sourcepub fn batch_reads(self, batch: bool) -> Self
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)). ASELECTthat writes (one that calls a function that writes, or takes a row lock withFOR UPDATE) fails with the server’s25006and 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()andtransaction_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 (alock_timeoutshorter 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.
Sourcepub fn from_url(url: &str) -> Result<Self, Error>
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).