pub struct Pool { /* private fields */ }Expand description
Connections to one server, for the tasks of one worker thread.
Make one pool per worker, inside giong::Runtime::run: nothing is
shared between threads, so nothing is locked.
use giong_postgres::{Config, Pool};
fn main() -> std::io::Result<()> {
let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
giong::Builder::new().build()?.run(move |_worker| {
let pool = Pool::new(config.clone(), 4);
async move {
let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
let n: i64 = row.get(0).unwrap();
println!("{n} orders");
}
})
}query and the other statement methods do not take a
connection for themselves: they run on the least busy connection, beside
statements from other tasks (pipelining), and the pool opens another
connection, up to its maximum, when every open one is busy. That is the
fast path for statements that stand alone. On one connection the server
answers in order, so a statement waits for those sent before it; the pool
steers new statements away from a connection whose oldest statement has
been running for more than 5 ms. Run statements known to be slow (reports,
migrations) on a connection of their own, from get. At most
1024 statements run on one connection at a time; past that, statements
use another connection or wait for room.
How many connections. Because statements pipeline, a few connections keep the server busy: start with the server’s cores, shared among the workers’ pools. More than that adds no throughput and raises tail latency, since a backend waiting for a core holds up every statement queued on its connection. Statements that wait on disk or on locks need more.
get takes a connection for one task alone: for a
transaction, for session settings (SET, SET ROLE, temporary tables,
advisory locks, LISTEN), or for a slow statement. While it is out, no
shared statement runs on it. Tasks waiting in get are served in the
order they came, and shared statements stop using a connection while a
get waits for it, so get is served even when shared statements keep
every connection busy; shared statements always keep at least one
connection when the pool has room for two. The connection comes back when
the PooledClient is dropped, and its session is reset before anything
else runs on it: a transaction left open is rolled back, and if anything
was sent on it, SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES follows (plus DEALLOCATE ALL after an SQL-level PREPARE).
Settings given to Config survive the reset; settings made with SET
do not. These requests are pipelined in front of the next statement, so
nobody waits a round trip for them; if they fail, the connection is closed
instead of reused.
Transactions and session changes never run on the shared
connections, since the statements of other tasks would run inside them
or under them. query, query_one, query_opt and execute refuse
BEGIN, COMMIT, ROLLBACK and the other transaction statements, and
all the statement methods refuse statements that change the session
(SET without LOCAL, RESET, DISCARD, LISTEN, UNLISTEN,
PREPARE, DEALLOCATE, DECLARE, LOAD, CREATE TEMP ...) and
COPY ... FROM STDIN, before sending anything (ErrorKind::Statement).
Functions that change the session (set_config(.., false),
pg_advisory_lock) cannot be recognised this way: call them on a
connection from get. batch_execute may carry a
whole transaction (BEGIN; ...; COMMIT); if a batch leaves one open, its
connection is closed, which rolls it back, and the batch and every
statement sent on that connection after it fail with
ErrorKind::Closed.
Connections the server closed, or that broke, are left behind as soon as that is noticed, which is when it happens: each connection is read continuously. A connection unused for the idle timeout is closed, and so is one older than the maximum lifetime or whose server refused a write because it is a standby (after a failover), once no statement uses it.
Implementations§
Source§impl Pool
impl Pool
Sourcepub fn new(config: Config, max_size: usize) -> Self
pub fn new(config: Config, max_size: usize) -> Self
A pool of at most max_size connections to the server in config.
Connections are opened when needed, not here.
Size it from the server’s max_connections: the pools of all workers
of all processes together must stay below it.
§Panics
Panics if max_size is 0.
Sourcepub fn wait_timeout(self, timeout: Duration) -> Self
pub fn wait_timeout(self, timeout: Duration) -> Self
The longest a task waits for a connection when all max_size are
taken or busy: 5 seconds by default. A longer wait fails with
ErrorKind::PoolTimeout. A task that opens a new connection waits
for it up to Config::connect_timeout instead.
§Panics
Panics if other clones of this pool exist; set it right after
new.
Sourcepub fn idle_timeout(self, timeout: Duration) -> Self
pub fn idle_timeout(self, timeout: Duration) -> Self
Sourcepub fn max_lifetime(self, lifetime: Duration) -> Self
pub fn max_lifetime(self, lifetime: Duration) -> Self
How long a connection may live: 30 minutes by default, less up to a tenth at random so that the connections of a pool do not all close at once. An older connection is closed as soon as no statement uses it, and replaced when needed, so that connections follow DNS changes and failovers, and the server’s per-connection memory is given back.
§Panics
Panics if other clones of this pool exist; set it right after
new.
Sourcepub async fn query(
&self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<Vec<Row>, Error>
pub async fn query( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Vec<Row>, Error>
Runs a statement on a shared connection and returns its rows; see
Client::query. Statements that control a transaction or change
the session are refused (ErrorKind::Statement): run them on a
connection from get.
Not cancel safe: if the future is dropped, the statement may still run on the server, and what it changes stays; the pool and its connections stay usable.
Sourcepub async fn query_one(
&self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<Row, Error>
pub async fn query_one( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Row, Error>
Runs a statement that returns exactly one row; see
Client::query_one. Refuses the statements query
refuses.
Not cancel safe, like query.
Sourcepub async fn query_opt(
&self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<Option<Row>, Error>
pub async fn query_opt( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Option<Row>, Error>
Runs a statement that returns at most one row; see
Client::query_opt. Refuses the statements query
refuses.
Not cancel safe, like query.
Sourcepub async fn execute(
&self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<u64, Error>
pub async fn execute( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<u64, Error>
Runs a statement and returns the number of rows it changed; see
Client::execute. Refuses the statements query
refuses.
Not cancel safe, like query.
Sourcepub async fn batch_execute(&self, sql: &str) -> Result<(), Error>
pub async fn batch_execute(&self, sql: &str) -> Result<(), Error>
Runs several statements without parameters; see
Client::batch_execute.
The batch may hold a whole transaction, BEGIN; ...; COMMIT. If it
leaves one open, the connection is closed, which rolls the
transaction back, and the batch fails with ErrorKind::Closed, as
do the statements other tasks sent on that connection after it: they
would otherwise have run inside the transaction. Statements that
change the session (SET without LOCAL, LISTEN,
COPY ... FROM STDIN and the others listed on Pool) are refused
before anything is sent (ErrorKind::Statement).
Not cancel safe, like query.
Sourcepub async fn get(&self) -> Result<PooledClient, Error>
pub async fn get(&self) -> Result<PooledClient, Error>
Takes a connection for this task alone, for a transaction, session settings or a slow statement:
let mut conn = pool.get().await?;
let tx = conn.transaction().await?;
tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
tx.commit().await?;Waits up to the wait timeout when every
connection is taken or busy and the pool is full. Tasks waiting here
are served in the order they came. The session is reset when the
connection comes back (see Pool).
Cancel safe: if the future is dropped, no connection is taken, and the place in line goes to the next task.