Skip to main content

giong_postgres/
client.rs

1//! A connection: requests are queued, written by one task and answered in
2//! order by another, so that any number of tasks can use one connection at
3//! once and their statements share round trips.
4
5use std::cell::{Cell, RefCell};
6use std::collections::{HashMap, VecDeque};
7use std::future::{poll_fn, Future};
8use std::net::Shutdown;
9use std::ops::Deref;
10use std::pin::Pin;
11use std::rc::{Rc, Weak};
12use std::sync::atomic::{AtomicU32, Ordering};
13use std::sync::Arc;
14use std::task::{Context, Poll, Waker};
15
16use crate::config::Config;
17use crate::connect::{self, ReadBuf, Startup, Stream};
18use crate::error::{DbError, Error, ErrorKind};
19use crate::protocol::{self, parse_backend, Backend, MAX_PARAMS};
20use crate::row::{Column, ResultSet, Row, RowsBuilder};
21use crate::types::{ToSql, Type};
22
23/// A connection to a PostgreSQL server.
24///
25/// Every method takes `&self`, so tasks can share a client (through an `Rc`)
26/// and run statements at the same time: their messages go out together and
27/// the server answers them in order, one round trip for all of them
28/// (pipelining). A [`Transaction`] needs `&mut self`, so that no other task
29/// can slip a statement into it.
30///
31/// Statements are prepared on the server the first time the connection runs
32/// them and kept (see
33/// [`Config::statement_cache_capacity`](crate::Config::statement_cache_capacity)),
34/// so a statement that ran before takes a single round trip.
35///
36/// A client lives on the worker thread that opened it. Dropping it closes the
37/// connection once the statements already sent have been written.
38pub struct Client {
39    conn: Rc<Conn>,
40}
41
42/// A prepared statement on one connection.
43pub(crate) struct Statement {
44    sql: Rc<str>,
45    name: Box<str>,
46    params: Vec<Type>,
47    columns: Rc<[Column]>,
48    /// Set for a statement that is not cached: the connection, so that the
49    /// statement can be closed if it was never run.
50    conn: Option<Weak<Conn>>,
51    closed: Cell<bool>,
52    /// It failed in a batch because it writes (`25006`): it is sent on its
53    /// own from then on.
54    writes: Cell<bool>,
55}
56
57impl Drop for Statement {
58    fn drop(&mut self) {
59        let Some(conn) = self.conn.as_ref().and_then(Weak::upgrade) else {
60            return;
61        };
62        if !self.closed.get() {
63            // No Sync: the close travels with the next request.
64            if let Ok(mut st) = conn.state.try_borrow_mut() {
65                if st.broken.is_none() {
66                    let _ = protocol::close_statement(&mut st.out, &self.name);
67                    // A batch must end `out` to take more statements.
68                    st.batch = None;
69                }
70            }
71        }
72    }
73}
74
75/// The error for a statement sent in a transaction that can no longer be
76/// committed.
77#[cold]
78#[inline(never)]
79fn abandoned() -> Error {
80    Error::new(
81        ErrorKind::Db,
82        "a statement of this transaction was given up before its answer came (its future was \
83         dropped, by a timeout say), and it may have run, so the transaction cannot be \
84         committed; this statement was not sent. Drop the transaction (which rolls it back) and \
85         run it again from the start",
86    )
87}
88
89/// Why a shared connection was closed under its statements.
90const LEFT_OPEN: &str = "a statement sent through the pool's shared methods (Pool::batch_execute) \
91     left a transaction open on a connection other tasks share, so the connection was closed and \
92     the transaction rolled back, with every statement sent on it since BEGIN, this one included. \
93     Run transactions on a connection of the task's own: pool.get().await?.transaction()";
94
95/// What a pool sends when a connection taken with `get()` comes back, so
96/// that the next task finds a clean session: `DISCARD ALL` without
97/// `DEALLOCATE ALL` (which would also drop the statement cache) and without
98/// `DISCARD PLANS` (plans are not session state). `RESET ALL` returns the
99/// settings sent when connecting (`statement_timeout`, `Config::param`) to
100/// those values, not to the server's defaults.
101const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
102     SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";
103
104/// The prefix of the names of the statements this crate prepares, chosen to
105/// stay clear of names an application would give its own.
106const NAME_PREFIX: &str = "__giong_";
107
108/// The state shared by a client and its two tasks.
109struct Conn {
110    weak: Weak<Conn>,
111    stream: Stream,
112    state: RefCell<State>,
113    /// When the oldest unanswered request became the oldest; `None` with
114    /// nothing in flight.
115    head_since: Cell<Option<giong::time::Instant>>,
116    config: Config,
117    key: Option<(i32, i32)>,
118    /// Several tasks send statements on this connection at once (it is among
119    /// a pool's shared connections): none of them may leave a transaction
120    /// open, which would take in the statements of the others.
121    shared: Cell<bool>,
122    /// Woken when nothing is in flight any more, or the connection fails.
123    idle_wakers: RefCell<Vec<Waker>>,
124    /// Requests sent since the connection opened: a pool compares the count
125    /// before and after lending it, to know whether it was used.
126    requests: Cell<u64>,
127    /// While a pool lends the connection to one task: the flag its cancel
128    /// tokens check, cleared when the connection goes back.
129    lease: RefCell<Option<Arc<Lease>>>,
130    /// The server refused a write because it is a standby (it was a primary
131    /// once, or DNS still points at it): a pool closes the connection rather
132    /// than keep sending writes there.
133    retire: Cell<bool>,
134    /// A statement ran SQL-level `PREPARE`, whose prepared statement outlives
135    /// the task that made it.
136    user_prepared: Cell<bool>,
137    /// The state of the [`Transaction`] open on this connection.
138    tx: Cell<Tx>,
139}
140
141/// Where a [`Transaction`] stands, as the client sees it.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143enum Tx {
144    /// No `Transaction` is open.
145    None,
146    Open,
147    /// A statement in it was given up before its answer came (its future
148    /// was dropped): it may have run, so committing would commit work the
149    /// application believes undone. Nothing more is sent until it ends.
150    Abandoned,
151}
152
153struct State {
154    /// Messages waiting to be written.
155    out: Vec<u8>,
156    writer: Option<Waker>,
157    /// One entry per `Sync` or simple query sent, answered in order.
158    queue: VecDeque<Rc<Slot>>,
159    /// Why the connection stopped working, once it has.
160    broken: Option<Error>,
161    /// The client was dropped: write what is queued, then `Terminate`.
162    closing: bool,
163    /// The transaction status from the last `ReadyForQuery`.
164    status: u8,
165    cache: HashMap<Rc<str>, Entry>,
166    clock: u64,
167    next_name: u64,
168    server_params: Vec<(String, String)>,
169    /// The last request in `out`, while it may still grow into a batch, or
170    /// the batch it grew into.
171    batch: Option<OpenBatch>,
172    /// How many slots of `queue` are a batch's guard or end, not requests.
173    extra: usize,
174    /// [`READ_ONLY`] is prepared (or its Parse is queued).
175    read_only_prepared: bool,
176    /// The statements of the batch being answered that have their answer:
177    /// they complete with the batch's `ReadyForQuery`, once it is known
178    /// whether its transaction committed.
179    held: Vec<Rc<Slot>>,
180    /// The batch being answered had an error: its transaction rolled back.
181    batch_failed: bool,
182}
183
184/// Statements in `out` that end with one `Sync` (see [`Config::batch_reads`]).
185struct OpenBatch {
186    /// Where the first statement's messages start in `out`.
187    start: usize,
188    /// How many statements it holds.
189    members: usize,
190}
191
192/// The most statements in one batch.
193const BATCH_MAX: usize = 16;
194/// The length of a `Sync` message.
195const SYNC_LEN: usize = 5;
196/// Makes the transaction of a batch read-only, until its `Sync`: a
197/// statement that writes then fails instead of writing what the batch's
198/// rollback would undo.
199///
200/// It also caps how long a statement of the batch waits for a lock, at 50 ms
201/// (a constant: computed from the session's `lock_timeout`, the guard cost
202/// the batch 10% of its speed): a batch holds the locks its statements took
203/// until it ends, so a statement that waits behind another transaction while
204/// earlier ones hold their locks could close a cycle that the statements one
205/// by one never would (a migration that locks two tables, say), and the
206/// server would roll back one side after its `deadlock_timeout`. Given up within 50 ms instead, the wait fails the
207/// batch, whose statements run again on their own and wait as they would
208/// without batches.
209const READ_ONLY: &str =
210    "SELECT set_config('transaction_read_only', 'on', true), set_config('lock_timeout', '50ms', true)";
211
212/// The name [`READ_ONLY`] is prepared under, once per connection.
213const READ_ONLY_NAME: &str = "__giong_read_only";
214
215/// Bind and Execute of [`READ_ONLY`], after its Parse unless `prepared`.
216fn read_only_guard(out: &mut Vec<u8>, prepared: bool) {
217    let parsed = if prepared {
218        Ok(())
219    } else {
220        protocol::parse(out, READ_ONLY_NAME, READ_ONLY)
221    };
222    let encoded = parsed
223        .and_then(|()| {
224            protocol::bind(
225                out,
226                READ_ONLY_NAME,
227                0,
228                |_, _| unreachable!("no parameters"),
229                [].into_iter(),
230            )
231        })
232        .and_then(|()| protocol::execute(out));
233    debug_assert!(encoded.is_ok(), "a constant statement encodes");
234}
235
236enum Entry {
237    Ready { stmt: Rc<Statement>, used: u64 },
238    Preparing(Rc<Slot>),
239}
240
241/// A request in flight and what has arrived for it.
242struct Slot {
243    kind: Kind,
244    /// Sent while the connection was shared.
245    shared: bool,
246    /// The pool's session reset: if it fails, the session is in an unknown
247    /// state, so the connection is closed rather than reused.
248    close_on_error: bool,
249    /// A statement of an open transaction: giving it up before its answer
250    /// marks the transaction [`Tx::Abandoned`].
251    in_tx: Option<Weak<Conn>>,
252    /// Its part in a batch: it ends with its own `CommandComplete` or
253    /// error, or (the batch's end) with the `ReadyForQuery`.
254    batch: Cell<Role>,
255    inner: RefCell<SlotInner>,
256}
257
258#[derive(Clone, Copy, PartialEq, Eq, Debug)]
259enum Role {
260    /// A request of its own, ended by its `ReadyForQuery`.
261    Alone,
262    /// One of the batch's statements.
263    Member,
264    /// The statement that makes the batch's transaction read-only.
265    Guard,
266    /// The batch's `Sync`.
267    End,
268}
269
270enum Kind {
271    Prepare {
272        sql: Rc<str>,
273        name: Box<str>,
274        cached: bool,
275    },
276    Execute {
277        stmt: Rc<Statement>,
278    },
279    Simple,
280}
281
282/// The tasks waiting for a request's answer: almost always one, which is
283/// kept without an allocation.
284#[derive(Default)]
285struct Wakers {
286    first: Option<Waker>,
287    more: Vec<Waker>,
288}
289
290impl Wakers {
291    /// Adds `waker` unless it would wake a task already here.
292    fn register(&mut self, waker: &Waker) {
293        match &self.first {
294            None => self.first = Some(waker.clone()),
295            Some(w) if w.will_wake(waker) => {}
296            Some(_) => {
297                if !self.more.iter().any(|w| w.will_wake(waker)) {
298                    self.more.push(waker.clone());
299                }
300            }
301        }
302    }
303
304    fn wake_all(&mut self) {
305        if let Some(w) = self.first.take() {
306            w.wake();
307        }
308        for w in self.more.drain(..) {
309            w.wake();
310        }
311    }
312}
313
314#[derive(Default)]
315struct SlotInner {
316    wakers: Wakers,
317    /// Nobody is waiting for the result any more: rows are not kept.
318    abandoned: bool,
319    /// The outcome was handed to the caller.
320    delivered: bool,
321    error: Option<Error>,
322    params: Option<Vec<Type>>,
323    columns: Option<Vec<Column>>,
324    rows: RowsBuilder,
325    tag: Option<Tag>,
326    /// The server confirmed the Bind: the statement started running.
327    bound: bool,
328    /// The transaction status in the `ReadyForQuery` that ended the request.
329    status: u8,
330    /// The request failed on a stale cached statement before running, outside
331    /// a transaction: running it again is safe.
332    retry: bool,
333    /// A statement of a batch that did not run (the server skipped it after
334    /// another failed), or that failed because it writes: it is sent again on
335    /// its own.
336    alone: bool,
337    outcome: Option<Result<Response, Error>>,
338}
339
340enum Response {
341    Statement(Rc<Statement>),
342    Rows(ResultSet, Option<Tag>),
343    Done(Option<Tag>),
344}
345
346impl Slot {
347    fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
348        Rc::new(Slot {
349            kind,
350            shared,
351            close_on_error,
352            in_tx,
353            batch: Cell::new(Role::Alone),
354            inner: RefCell::default(),
355        })
356    }
357}
358
359/// Waits for a slot's outcome. Dropping it lets the reader throw the rows
360/// away; the statement still runs.
361struct Wait {
362    slot: Rc<Slot>,
363}
364
365impl Future for Wait {
366    type Output = Result<Response, Error>;
367
368    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
369        let mut inner = self.slot.inner.borrow_mut();
370        let shared = matches!(self.slot.kind, Kind::Prepare { .. });
371        match &inner.outcome {
372            Some(Ok(Response::Statement(stmt))) if shared => {
373                return Poll::Ready(Ok(Response::Statement(stmt.clone())))
374            }
375            Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
376            Some(_) => {
377                inner.delivered = true;
378                return Poll::Ready(inner.outcome.take().expect("checked"));
379            }
380            None => {}
381        }
382        inner.wakers.register(cx.waker());
383        Poll::Pending
384    }
385}
386
387impl Drop for Wait {
388    fn drop(&mut self) {
389        if matches!(self.slot.kind, Kind::Prepare { .. }) {
390            return;
391        }
392        // Its answer arrived (handed over or not): its outcome is known.
393        let known = {
394            let mut inner = self.slot.inner.borrow_mut();
395            inner.abandoned = true;
396            inner.rows = RowsBuilder::default();
397            inner.delivered || inner.outcome.is_some()
398        };
399        // The application gave up on a statement of its transaction, which
400        // may run all the same: the transaction must not commit it unseen.
401        if !known && self.slot.in_tx.is_some() {
402            abandon_tx(&self.slot);
403        }
404    }
405}
406
407/// Marks the transaction `slot` was sent in as abandoned (see [`Tx::Abandoned`]).
408#[cold]
409#[inline(never)]
410fn abandon_tx(slot: &Slot) {
411    if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
412        if conn.tx.get() == Tx::Open {
413            conn.tx.set(Tx::Abandoned);
414        }
415    }
416}
417
418/// Whether the server's error says a prepared statement no longer fits: the
419/// schema changed under its cached plan (`0A000` from
420/// `RevalidateCachedQuery`; the message is matched too, for servers that send
421/// no routine, but it is translated when `lc_messages` is not English), or it
422/// does not exist any more (`26000`, after `DEALLOCATE` or `DISCARD ALL`).
423fn is_stale(db: &DbError) -> bool {
424    match db.code() {
425        "26000" => true,
426        "0A000" => {
427            db.routine() == Some("RevalidateCachedQuery")
428                || db.message().contains("cached plan must not change")
429        }
430        _ => false,
431    }
432}
433
434/// What this crate uses of a command tag (`INSERT 0 5`, `ROLLBACK`), read
435/// as it arrives so that the tag itself need not be kept.
436#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
437struct Tag {
438    /// The rows it reports: `INSERT 0 5`, `UPDATE 3`, `SELECT 7`; 0 for a
439    /// tag without a count.
440    rows: u64,
441    /// `COMMIT` ended a failed transaction with a rollback.
442    rollback: bool,
443}
444
445impl Tag {
446    fn of(tag: &str) -> Self {
447        Self {
448            rows: tag
449                .rsplit(' ')
450                .next()
451                .and_then(|n| n.parse().ok())
452                .unwrap_or(0),
453            rollback: tag == "ROLLBACK",
454        }
455    }
456}
457
458impl Client {
459    /// Opens a connection and logs in.
460    ///
461    /// Fails with [`ErrorKind::Connect`] when the server cannot be reached
462    /// within [`Config::connect_timeout`](crate::Config::connect_timeout),
463    /// [`ErrorKind::Auth`] when it refuses the credentials, and
464    /// [`ErrorKind::Config`] when the configuration is incomplete.
465    ///
466    /// # Panics
467    ///
468    /// Panics when called outside of a giong runtime.
469    ///
470    /// Cancel safe: if the future is dropped, the connection being opened is
471    /// closed.
472    pub async fn connect(config: &Config) -> Result<Client, Error> {
473        let startup = connect::connect(config).await?;
474        Ok(Self::start(startup, config.clone()))
475    }
476
477    pub(crate) fn start(startup: Startup, config: Config) -> Client {
478        let Startup {
479            stream,
480            buf,
481            params,
482            key,
483            status,
484        } = startup;
485        let conn = Rc::new_cyclic(|weak| Conn {
486            weak: weak.clone(),
487            head_since: Cell::new(None),
488            stream,
489            config,
490            key,
491            shared: Cell::new(false),
492            idle_wakers: RefCell::new(Vec::new()),
493            requests: Cell::new(0),
494            lease: RefCell::new(None),
495            retire: Cell::new(false),
496            user_prepared: Cell::new(false),
497            tx: Cell::new(Tx::None),
498            state: RefCell::new(State {
499                out: Vec::new(),
500                writer: None,
501                queue: VecDeque::new(),
502                extra: 0,
503                read_only_prepared: false,
504                held: Vec::new(),
505                batch_failed: false,
506                broken: None,
507                closing: false,
508                status,
509                cache: HashMap::new(),
510                clock: 0,
511                next_name: 0,
512                server_params: params,
513                batch: None,
514            }),
515        });
516        giong::spawn(read_loop(conn.clone(), buf));
517        giong::spawn(write_loop(conn.clone()));
518        Client { conn }
519    }
520
521    /// Runs a statement and returns its rows.
522    ///
523    /// Parameters are written `$1`, `$2`... in the SQL and passed in order:
524    ///
525    /// ```no_run
526    /// # async fn f(client: &giong_postgres::Client) -> Result<(), giong_postgres::Error> {
527    /// let rows = client
528    ///     .query("SELECT id, email FROM users WHERE created_at > now() - $1::interval", &[&"7 days"])
529    ///     .await?;
530    /// for row in &rows {
531    ///     let id: i64 = row.get("id")?;
532    ///     let email: &str = row.get("email")?;
533    /// }
534    /// # Ok(()) }
535    /// ```
536    ///
537    /// The server decides each parameter's type from the SQL; see the
538    /// [`types`](crate::types) module for which Rust types fit which.
539    ///
540    /// Not cancel safe: if the future is dropped, the statement may still run
541    /// on the server, and what it changes stays; the connection stays usable.
542    /// Inside a [`Transaction`], a later [`commit`](Transaction::commit)
543    /// commits it.
544    pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
545        let (set, _) = self.run(sql, params, false).await?;
546        Ok(set.into_rows())
547    }
548
549    /// [`query`](Self::query) for the pool's shared connections: `batch`
550    /// lets the statement join a batch ([`Config::batch_reads`]).
551    pub(crate) async fn query_shared(
552        &self,
553        sql: &str,
554        params: &[&dyn ToSql],
555        batch: bool,
556    ) -> Result<Vec<Row>, Error> {
557        let (set, _) = self.run(sql, params, batch).await?;
558        Ok(set.into_rows())
559    }
560
561    /// Runs a statement that must return exactly one row, and returns it.
562    ///
563    /// No row or several rows fail with [`ErrorKind::RowCount`].
564    ///
565    /// Not cancel safe, like [`query`](Self::query).
566    pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
567        one_row(self.query(sql, params).await?)
568    }
569
570    /// Runs a statement that returns at most one row.
571    ///
572    /// Several rows fail with [`ErrorKind::RowCount`].
573    ///
574    /// Not cancel safe, like [`query`](Self::query).
575    pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
576        at_most_one_row(self.query(sql, params).await?)
577    }
578}
579
580/// The one row of a result, or [`ErrorKind::RowCount`].
581pub(crate) fn one_row(mut rows: Vec<Row>) -> Result<Row, Error> {
582    match rows.len() {
583        1 => Ok(rows.pop().expect("one row")),
584        n => Err(Error::new(
585            ErrorKind::RowCount,
586            format!(
587                "the statement returned {n} rows where exactly one was expected; use \
588                     query_opt for zero or one, or query for any number"
589            ),
590        )),
591    }
592}
593
594/// The row of a result of at most one, or [`ErrorKind::RowCount`].
595pub(crate) fn at_most_one_row(mut rows: Vec<Row>) -> Result<Option<Row>, Error> {
596    match rows.len() {
597        0 | 1 => Ok(rows.pop()),
598        n => Err(Error::new(
599            ErrorKind::RowCount,
600            format!(
601                "the statement returned {n} rows where at most one was expected; add a \
602                     LIMIT, or use query"
603            ),
604        )),
605    }
606}
607
608impl Client {
609    /// Runs a statement and returns the number of rows it inserted, updated
610    /// or deleted (or returned, for a `SELECT`).
611    ///
612    /// Not cancel safe, like [`query`](Self::query).
613    pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
614        let (_, tag) = self.run(sql, params, false).await?;
615        Ok(tag.map_or(0, |t| t.rows))
616    }
617
618    /// Runs SQL that may hold several statements separated by `;`, with no
619    /// parameters, such as a schema migration. Rows they return are thrown
620    /// away.
621    ///
622    /// The statements run in one implicit transaction unless the SQL has its
623    /// own `BEGIN` and `COMMIT`: if one fails, the earlier ones are rolled
624    /// back.
625    ///
626    /// Not cancel safe: if the future is dropped, the statements may still run
627    /// on the server, and what they change stays.
628    pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
629        let _wait = giong::observe::wait(giong::observe::Wait::Query, "postgres");
630        let slot = self
631            .conn
632            .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
633        Wait { slot }.await.map(|_| ())
634    }
635
636    /// Starts a transaction.
637    ///
638    /// It is committed by [`Transaction::commit`]; dropping it without a
639    /// commit rolls it back. While it is open, it holds the client mutably,
640    /// so no other statement can run on the connection outside it.
641    ///
642    /// ```no_run
643    /// # async fn f(client: &mut giong_postgres::Client) -> Result<(), giong_postgres::Error> {
644    /// let tx = client.transaction().await?;
645    /// tx.execute("UPDATE accounts SET balance = balance - $1 WHERE id = $2", &[&100i64, &1i64]).await?;
646    /// tx.execute("UPDATE accounts SET balance = balance + $1 WHERE id = $2", &[&100i64, &2i64]).await?;
647    /// tx.commit().await?;
648    /// # Ok(()) }
649    /// ```
650    ///
651    /// Cancel safe: if the future is dropped, a transaction it began is rolled
652    /// back.
653    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
654        // The guard exists before BEGIN is sent: if this future is dropped
655        // while waiting, the guard's drop rolls the transaction back.
656        let tx = Transaction {
657            client: self,
658            done: false,
659        };
660        tx.client.conn.tx.set(Tx::Open);
661        tx.client.batch_execute("BEGIN").await?;
662        Ok(tx)
663    }
664
665    /// A handle that asks the server to cancel whatever this connection is
666    /// running, from any thread.
667    ///
668    /// A token taken from a [`PooledClient`](crate::PooledClient) stops
669    /// working when the connection goes back to the pool, so that it cannot
670    /// cancel the statements of the tasks that use the connection next; and
671    /// a connection that goes back while a request from such a token is on
672    /// its way is closed rather than lent to another task.
673    pub fn cancel_token(&self) -> CancelToken {
674        CancelToken {
675            config: self.conn.config.without_password(),
676            key: self.conn.key,
677            lease: self.conn.lease.borrow().clone(),
678        }
679    }
680
681    /// A setting the server reported, such as `server_version`, `TimeZone`
682    /// or `integer_datetimes`.
683    pub fn parameter(&self, name: &str) -> Option<String> {
684        let st = self.conn.state.borrow();
685        st.server_params
686            .iter()
687            .find(|(n, _)| n == name)
688            .map(|(_, v)| v.clone())
689    }
690
691    /// Whether the connection has stopped working. A closed client fails
692    /// every statement with [`ErrorKind::Closed`].
693    pub fn is_closed(&self) -> bool {
694        self.conn.state.borrow().broken.is_some()
695    }
696
697    /// How many requests have been sent and not answered yet.
698    pub fn in_flight(&self) -> usize {
699        let st = self.conn.state.borrow();
700        st.queue.len() - st.extra + st.held.len()
701    }
702
703    /// How long the oldest unanswered request has been waiting for its
704    /// answer; zero with nothing in flight.
705    pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
706        self.conn
707            .head_since
708            .get()
709            .map_or(std::time::Duration::ZERO, |t| {
710                now.saturating_duration_since(t)
711            })
712    }
713
714    /// Whether the last answer from the server said a transaction was open.
715    pub(crate) fn in_transaction(&self) -> bool {
716        self.conn.state.borrow().status != b'I'
717    }
718
719    /// Marks the connection as shared between tasks, or as one task's own.
720    /// Statements sent while it is shared must not leave a transaction open:
721    /// if one does, the connection is closed, which rolls the transaction
722    /// back, rather than let the statements of other tasks run inside it.
723    pub(crate) fn set_shared(&self, shared: bool) {
724        self.conn.shared.set(shared);
725    }
726
727    /// Wakes `waker` once nothing is in flight, or the connection fails.
728    pub(crate) fn wake_when_idle(&self, waker: &Waker) {
729        let mut wakers = self.conn.idle_wakers.borrow_mut();
730        if !wakers.iter().any(|w| w.will_wake(waker)) {
731            wakers.push(waker.clone());
732        }
733    }
734
735    /// How many requests have been sent on the connection since it opened.
736    pub(crate) fn requests(&self) -> u64 {
737        self.conn.requests.get()
738    }
739
740    /// Starts lending the connection to one task: cancel tokens taken from
741    /// now on work until [`end_lease`](Self::end_lease).
742    pub(crate) fn begin_lease(&self) {
743        *self.conn.lease.borrow_mut() = Some(Arc::new(Lease::default()));
744    }
745
746    /// Ends the lease: the cancel tokens taken during it stop working.
747    /// Returns whether a cancel request taken during it may still be on its
748    /// way to the server, in which case the connection must not be lent to
749    /// another task: the request would stop that task's statement.
750    pub(crate) fn end_lease(&self) -> bool {
751        self.conn
752            .lease
753            .borrow_mut()
754            .take()
755            .is_some_and(|lease| lease.end())
756    }
757
758    /// Whether the connection should not be used any more although it works:
759    /// the server refused a write because it is a standby.
760    pub(crate) fn should_retire(&self) -> bool {
761        self.conn.retire.get()
762    }
763
764    /// Queues the pool's session reset ([`RESET`]), and `DEALLOCATE ALL` if a
765    /// statement ran SQL-level `PREPARE` (the statement cache is emptied with
766    /// it). Nobody waits for the result; if it fails, the connection is
767    /// closed.
768    pub(crate) fn reset_session(&self) {
769        let deallocate = self.conn.user_prepared.replace(false);
770        let sql = if deallocate {
771            let mut st = self.conn.state.borrow_mut();
772            st.cache.clear();
773            st.read_only_prepared = false;
774            format!("{RESET}; DEALLOCATE ALL")
775        } else {
776            RESET.to_owned()
777        };
778        if let Ok(slot) = self
779            .conn
780            .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
781        {
782            slot.inner.borrow_mut().abandoned = true;
783        }
784    }
785
786    /// Queues a statement whose result nobody waits for.
787    pub(crate) fn send_and_forget(&self, sql: &str) {
788        if let Ok(slot) = self
789            .conn
790            .enqueue(Kind::Simple, |out| protocol::query(out, sql))
791        {
792            slot.inner.borrow_mut().abandoned = true;
793        }
794    }
795
796    async fn run(
797        &self,
798        sql: &str,
799        params: &[&dyn ToSql],
800        batch: bool,
801    ) -> Result<(ResultSet, Option<Tag>), Error> {
802        let _wait = giong::observe::wait(giong::observe::Wait::Query, "postgres");
803        if params.len() > MAX_PARAMS {
804            return Err(Error::conversion(format!(
805                "{} parameters were given; a statement can have at most {MAX_PARAMS}",
806                params.len()
807            )));
808        }
809        // A cached statement the schema changed under fails before running
810        // and is dropped from the cache: it is prepared again and run once
811        // more, unless that happened inside a transaction, which the error
812        // aborted.
813        let mut retried = false;
814        // A statement a batch skipped, or that writes, is sent again alone.
815        let mut alone = !batch;
816        loop {
817            let slot = self.send(sql, params, !alone).await?;
818            let result = Wait { slot: slot.clone() }.await;
819            if result.is_err() {
820                let (skipped, stale) = {
821                    let inner = slot.inner.borrow();
822                    (inner.alone, inner.retry)
823                };
824                if skipped && !alone {
825                    alone = true;
826                    continue;
827                }
828                if stale && !retried {
829                    retried = true;
830                    continue;
831                }
832            }
833            return match result? {
834                Response::Rows(set, tag) => Ok((set, tag)),
835                _ => unreachable!("an execute slot ends with rows"),
836            };
837        }
838    }
839
840    /// Prepares the statement if needed and sends a Bind and Execute for it.
841    async fn send(&self, sql: &str, params: &[&dyn ToSql], batch: bool) -> Result<Rc<Slot>, Error> {
842        let stmt = self.conn.statement(sql).await?;
843        if stmt.params.len() != params.len() {
844            return Err(Error::conversion(format!(
845                "the statement has {} parameters but {} values were given",
846                stmt.params.len(),
847                params.len()
848            )));
849        }
850        let cached = stmt.conn.is_none();
851        let encode = |out: &mut Vec<u8>| {
852            protocol::bind(
853                out,
854                &stmt.name,
855                params.len(),
856                |i, out| {
857                    params[i].to_sql(stmt.params[i], out).map_err(|e| {
858                        e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
859                    })
860                },
861                stmt.columns.iter().map(|c| c.ty().binary_result()),
862            )?;
863            protocol::execute(out)
864        };
865        let kind = Kind::Execute { stmt: stmt.clone() };
866        let slot = if batch
867            && cached
868            && !stmt.writes.get()
869            && self.conn.shared.get()
870            && self.conn.tx.get() == Tx::None
871        {
872            self.conn.enqueue_batched(kind, encode)?
873        } else {
874            self.conn.enqueue(kind, |out| {
875                encode(out)?;
876                protocol::sync(out);
877                Ok(())
878            })?
879        };
880        if !cached {
881            // In a request of its own: after an error the server skips the
882            // rest of a request, and the statement must go either way.
883            let close = self.conn.enqueue(Kind::Simple, |out| {
884                protocol::close_statement(out, &stmt.name)?;
885                protocol::sync(out);
886                Ok(())
887            });
888            if let Ok(close) = close {
889                close.inner.borrow_mut().abandoned = true;
890                stmt.closed.set(true);
891            }
892        }
893        Ok(slot)
894    }
895}
896
897impl Drop for Client {
898    fn drop(&mut self) {
899        let mut st = self.conn.state.borrow_mut();
900        st.closing = true;
901        if st.broken.is_none() {
902            protocol::terminate(&mut st.out);
903            st.batch = None;
904        }
905        if let Some(w) = st.writer.take() {
906            w.wake();
907        }
908    }
909}
910
911impl std::fmt::Debug for Client {
912    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
913        f.debug_struct("Client")
914            .field("server", &self.conn.config.target())
915            .field("in_flight", &self.in_flight())
916            .field("closed", &self.is_closed())
917            .finish()
918    }
919}
920
921impl Conn {
922    /// Appends a request's messages and queues its slot, or fails without
923    /// sending anything.
924    fn enqueue(
925        &self,
926        kind: Kind,
927        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
928    ) -> Result<Rc<Slot>, Error> {
929        self.enqueue_with(kind, false, encode)
930    }
931
932    /// The link a request sent in the open transaction keeps, or the error
933    /// if the transaction can no longer be committed.
934    #[cold]
935    #[inline(never)]
936    fn in_tx(&self) -> Result<Weak<Conn>, Error> {
937        match self.tx.get() {
938            Tx::Abandoned => Err(abandoned()),
939            _ => Ok(self.weak.clone()),
940        }
941    }
942
943    fn enqueue_with(
944        &self,
945        kind: Kind,
946        close_on_error: bool,
947        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
948    ) -> Result<Rc<Slot>, Error> {
949        let mut st = self.state.borrow_mut();
950        if let Some(e) = &st.broken {
951            return Err(e.clone());
952        }
953        let in_tx = if self.tx.get() == Tx::None {
954            None
955        } else {
956            Some(self.in_tx()?)
957        };
958        // Anything else written after a batch ends it.
959        st.batch = None;
960        let start = st.out.len();
961        if let Err(e) = encode(&mut st.out) {
962            st.out.truncate(start);
963            return Err(e);
964        }
965        let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
966        self.requests.set(self.requests.get() + 1);
967        if st.queue.is_empty() {
968            self.head_since.set(Some(giong::time::Instant::now()));
969        }
970        st.queue.push_back(slot.clone());
971        if let Some(w) = st.writer.take() {
972            w.wake();
973        }
974        Ok(slot)
975    }
976
977    /// Appends a statement's Bind and Execute (`encode`) and a `Sync`, and
978    /// queues its slot: the statement joins the batch that ends `out` when
979    /// there is one with room, or may start one; its `Sync` is then taken
980    /// off and the statement's messages go before it (see
981    /// [`Config::batch_reads`]). On a shared connection outside a
982    /// transaction only.
983    #[inline(never)]
984    fn enqueue_batched(
985        &self,
986        kind: Kind,
987        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
988    ) -> Result<Rc<Slot>, Error> {
989        let mut st = self.state.borrow_mut();
990        if let Some(e) = &st.broken {
991            return Err(e.clone());
992        }
993        let joins = st.batch.as_ref().is_some_and(|b| b.members < BATCH_MAX);
994        if !joins {
995            let start = st.out.len();
996            if let Err(e) = encode(&mut st.out) {
997                st.out.truncate(start);
998                return Err(e);
999            }
1000            protocol::sync(&mut st.out);
1001            st.batch = Some(OpenBatch { start, members: 1 });
1002            return Ok(self.queue_slot(&mut st, Slot::new(kind, true, false, None)));
1003        }
1004        // Encoded apart first: a value that cannot be encoded leaves the
1005        // batch as it was.
1006        let mut messages = Vec::new();
1007        encode(&mut messages)?;
1008        let sync_at = st.out.len() - SYNC_LEN;
1009        st.out.truncate(sync_at);
1010        let b = st.batch.as_mut().expect("joins");
1011        if b.members == 1 {
1012            // The request alone so far becomes the batch's first statement,
1013            // behind the one that makes the transaction read-only.
1014            let start = b.start;
1015            let mut guard = Vec::new();
1016            read_only_guard(&mut guard, st.read_only_prepared);
1017            st.read_only_prepared = true;
1018            st.out.splice(start..start, guard);
1019            let first = st.queue.pop_back().expect("the batch's first statement");
1020            first.batch.set(Role::Member);
1021            let guard = Slot::new(Kind::Simple, true, false, None);
1022            guard.batch.set(Role::Guard);
1023            st.extra += 2; // The guard, and the end queued below.
1024            guard.inner.borrow_mut().abandoned = true;
1025            st.queue.push_back(guard);
1026            st.queue.push_back(first);
1027        } else {
1028            let end = st.queue.pop_back().expect("the batch's end");
1029            debug_assert_eq!(end.batch.get(), Role::End);
1030        }
1031        st.batch.as_mut().expect("joins").members += 1;
1032        st.out.extend_from_slice(&messages);
1033        protocol::sync(&mut st.out);
1034        let slot = Slot::new(kind, true, false, None);
1035        slot.batch.set(Role::Member);
1036        st.queue.push_back(slot.clone());
1037        let end = Slot::new(Kind::Simple, true, false, None);
1038        end.batch.set(Role::End);
1039        end.inner.borrow_mut().abandoned = true;
1040        self.queue_slot(&mut st, end);
1041        Ok(slot)
1042    }
1043
1044    /// Queues `slot` behind the requests in flight and wakes the writer.
1045    fn queue_slot(&self, st: &mut State, slot: Rc<Slot>) -> Rc<Slot> {
1046        self.requests.set(self.requests.get() + 1);
1047        if st.queue.is_empty() {
1048            self.head_since.set(Some(giong::time::Instant::now()));
1049        }
1050        st.queue.push_back(slot.clone());
1051        if let Some(w) = st.writer.take() {
1052            w.wake();
1053        }
1054        slot
1055    }
1056
1057    /// A statement of a batch is done: its `CommandComplete` or its error
1058    /// arrived, or the batch ended without running it.
1059    /// Its result is held until the batch's end, when it is known whether
1060    /// the batch's transaction committed.
1061    fn finish_member(&self, slot: &Rc<Slot>) {
1062        // The batch's transaction ends with its `Sync`: the outcome is as
1063        // outside a transaction.
1064        slot.inner.borrow_mut().status = b'I';
1065        let mut st = self.state.borrow_mut();
1066        st.queue.pop_front();
1067        if slot.batch.get() == Role::Guard {
1068            st.extra -= 1;
1069        } else {
1070            st.held.push(slot.clone());
1071        }
1072        self.head_since
1073            .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1074    }
1075
1076    /// The prepared statement for `sql`: from the cache, from a prepare
1077    /// already in flight, or prepared now.
1078    async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1079        let mut again = true;
1080        loop {
1081            let pending = {
1082                let mut st = self.state.borrow_mut();
1083                st.clock += 1;
1084                let now = st.clock;
1085                match st.cache.get_mut(sql) {
1086                    Some(Entry::Ready { stmt, used }) => {
1087                        *used = now;
1088                        return Ok(stmt.clone());
1089                    }
1090                    Some(Entry::Preparing(slot)) => Some(slot.clone()),
1091                    None => None,
1092                }
1093            };
1094            let Some(slot) = pending else {
1095                return self.prepare(sql).await;
1096            };
1097            match (Wait { slot }).await {
1098                Ok(Response::Statement(stmt)) => return Ok(stmt),
1099                Ok(_) => unreachable!("a prepare slot ends with a statement"),
1100                // The task that sent this prepare tries another name (see
1101                // `prepare`); look in the cache again.
1102                Err(e) if again && e.server_code() == Some("42P05") => again = false,
1103                Err(e) => return Err(e),
1104            }
1105        }
1106    }
1107
1108    async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1109        match self.prepare_once(sql).await {
1110            // A statement of that name exists already: prepared by the
1111            // application with SQL-level PREPARE, or by another client behind
1112            // a connection pooler. The next name will do.
1113            Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
1114            result => result,
1115        }
1116    }
1117
1118    async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1119        let cached = self.config.statement_cache > 0;
1120        let (name, key) = {
1121            let mut st = self.state.borrow_mut();
1122            st.next_name += 1;
1123            (
1124                format!("{NAME_PREFIX}{}", st.next_name),
1125                Rc::<str>::from(sql),
1126            )
1127        };
1128        let slot = self.enqueue(
1129            Kind::Prepare {
1130                sql: key.clone(),
1131                name: name.as_str().into(),
1132                cached,
1133            },
1134            |out| {
1135                protocol::parse(out, &name, sql)?;
1136                protocol::describe_statement(out, &name)?;
1137                protocol::sync(out);
1138                Ok(())
1139            },
1140        )?;
1141        if cached {
1142            self.state
1143                .borrow_mut()
1144                .cache
1145                .insert(key, Entry::Preparing(slot.clone()));
1146        }
1147        match (Wait { slot }).await? {
1148            Response::Statement(stmt) => Ok(stmt),
1149            _ => unreachable!("a prepare slot ends with a statement"),
1150        }
1151    }
1152
1153    /// Stops the connection: every request waiting gets `err` (or the
1154    /// server's own error for it), and both tasks finish.
1155    fn fail(&self, err: Error) {
1156        let slots = {
1157            let mut st = self.state.borrow_mut();
1158            if st.broken.is_none() {
1159                st.broken = Some(err.clone());
1160            }
1161            st.cache.clear();
1162            st.out.clear();
1163            self.head_since.set(None);
1164            if let Some(w) = st.writer.take() {
1165                w.wake();
1166            }
1167            st.extra = 0;
1168            st.read_only_prepared = false;
1169            st.batch_failed = false;
1170            let mut slots = std::mem::take(&mut st.held);
1171            slots.extend(std::mem::take(&mut st.queue));
1172            slots
1173        };
1174        for slot in slots {
1175            let mut inner = slot.inner.borrow_mut();
1176            let e = inner.error.take().unwrap_or_else(|| err.clone());
1177            inner.outcome = Some(Err(e));
1178            inner.wakers.wake_all();
1179        }
1180        self.wake_idle();
1181        self.stream.shutdown(Shutdown::Both);
1182    }
1183
1184    fn wake_idle(&self) {
1185        let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
1186        for w in wakers {
1187            w.wake();
1188        }
1189    }
1190
1191    /// Takes apart and handles every whole message in `buf`.
1192    fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
1193        let limit = self.config.max_result_size.max(1 << 20);
1194        while let Some((tag, len)) = buf.peek()? {
1195            if len > limit {
1196                match tag {
1197                    // One row larger than the limit: skip it as it arrives,
1198                    // and fail the statement once it completes.
1199                    b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
1200                    // A notice or a notification (nobody reads them), or
1201                    // COPY TO STDOUT output (thrown away, and the statement
1202                    // fails anyway).
1203                    b'N' | b'A' | b'd' => {}
1204                    // The statement's error: it fails with this one instead,
1205                    // and the connection stays usable.
1206                    b'E' => {
1207                        let slot = self.front()?;
1208                        let mut inner = slot.inner.borrow_mut();
1209                        if inner.error.is_none() {
1210                            inner.error = Some(Error::new(
1211                                ErrorKind::TooLarge,
1212                                format!(
1213                                    "the server's error for this statement was a {len}-byte \
1214                                     message, more than max_result_size allows, so it was \
1215                                     thrown away; raise Config::max_result_size to read it"
1216                                ),
1217                            ));
1218                        }
1219                    }
1220                    _ => {
1221                        return Err(Error::new(
1222                            ErrorKind::Protocol,
1223                            format!(
1224                                "the server sent a {:?} message of {len} bytes, more than \
1225                                 max_result_size allows, so the connection was closed; raise \
1226                                 Config::max_result_size if the server's messages are this large",
1227                                tag as char
1228                            ),
1229                        ))
1230                    }
1231                }
1232                buf.skip(len);
1233                continue;
1234            }
1235            let Some(body) = buf.body(len) else {
1236                return Ok(());
1237            };
1238            self.handle(tag, buf.bytes(body))?;
1239            buf.consume(len);
1240        }
1241        Ok(())
1242    }
1243
1244    fn front(&self) -> Result<Rc<Slot>, Error> {
1245        self.state.borrow().queue.front().cloned().ok_or_else(|| {
1246            Error::protocol("the server sent a reply to a request that was never made")
1247        })
1248    }
1249
1250    fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
1251        let msg = parse_backend(tag, body)?;
1252        match msg {
1253            Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
1254            Backend::ParameterStatus { name, value } => {
1255                if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
1256                    return Err(Error::closed(format!(
1257                        "the session's client_encoding was changed to {value}; giong-postgres \
1258                         reads and writes UTF-8 only, so the connection was closed"
1259                    )));
1260                }
1261                let mut st = self.state.borrow_mut();
1262                match st.server_params.iter_mut().find(|(n, _)| n == name) {
1263                    Some(entry) => entry.1 = value.to_owned(),
1264                    None => st.server_params.push((name.to_owned(), value.to_owned())),
1265                }
1266                return Ok(());
1267            }
1268            Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
1269                // A FATAL error outside any request: the server is closing
1270                // the connection (an administrator's command, a shutdown).
1271                let db = DbError::parse(fields)?;
1272                return Err(Error::with_db(
1273                    ErrorKind::Closed,
1274                    "the server closed the connection",
1275                    db,
1276                ));
1277            }
1278            _ => {}
1279        }
1280        let slot = loop {
1281            let slot = self.front()?;
1282            if slot.batch.get() != Role::Alone
1283                && matches!(
1284                    msg,
1285                    Backend::CommandComplete(_)
1286                        | Backend::ErrorResponse(_)
1287                        | Backend::ReadyForQuery(_)
1288                )
1289            {
1290                if self.handle_batched(slot, &msg)? {
1291                    // A skipped statement's slot is done; the message is
1292                    // the next slot's.
1293                    continue;
1294                }
1295                return Ok(());
1296            }
1297            break slot;
1298        };
1299        let mut inner = slot.inner.borrow_mut();
1300        match msg {
1301            Backend::BindComplete => inner.bound = true,
1302            Backend::ParseComplete
1303            | Backend::CloseComplete
1304            | Backend::NoData
1305            | Backend::PortalSuspended
1306            | Backend::EmptyQueryResponse => {}
1307            Backend::ParameterDescription(types) => inner.params = Some(types),
1308            Backend::RowDescription(fields) => {
1309                if matches!(slot.kind, Kind::Prepare { .. }) {
1310                    inner.columns = Some(
1311                        fields
1312                            .iter()
1313                            .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
1314                            .collect(),
1315                    );
1316                }
1317            }
1318            Backend::DataRow(body) => match &slot.kind {
1319                Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
1320                    let limit = self.config.max_result_size;
1321                    inner.rows.push(body, stmt.columns.len(), limit)?;
1322                }
1323                _ => {}
1324            },
1325            Backend::CommandComplete(tag) => {
1326                if tag == "PREPARE" {
1327                    self.user_prepared.set(true);
1328                }
1329                inner.tag = Some(Tag::of(tag));
1330            }
1331            Backend::ErrorResponse(fields) => {
1332                if inner.error.is_none() {
1333                    inner.error = Some(self.db_error(fields, true)?);
1334                }
1335            }
1336            Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
1337                if inner.error.is_none() {
1338                    inner.error = Some(Error::conversion(
1339                        "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
1340                         was thrown away",
1341                    ));
1342                }
1343            }
1344            Backend::CopyInResponse | Backend::CopyBothResponse => {
1345                return Err(Error::closed(
1346                    "the statement started COPY FROM STDIN or replication, which giong-postgres \
1347                     does not support yet; the connection was closed",
1348                ));
1349            }
1350            Backend::ReadyForQuery(status) => {
1351                // A statement sent on a shared connection opened a
1352                // transaction (or left a failed one): the statements other
1353                // tasks send next would run inside it, and be lost with it.
1354                let left_open = slot.shared && status != b'I';
1355                if left_open {
1356                    inner.error = Some(Error::closed(LEFT_OPEN));
1357                }
1358                let reset_failed = match &inner.error {
1359                    Some(e) if slot.close_on_error => Some(Error::closed(format!(
1360                        "resetting the session of a connection that went back to the pool \
1361                         failed, so it was closed rather than reused: {e}"
1362                    ))),
1363                    _ => None,
1364                };
1365                inner.status = status;
1366                drop(inner);
1367                let idle = {
1368                    let mut st = self.state.borrow_mut();
1369                    st.status = status;
1370                    st.queue.pop_front();
1371                    self.head_since
1372                        .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1373                    st.queue.is_empty()
1374                };
1375                self.complete(&slot);
1376                if left_open {
1377                    // Closing the connection makes the server roll back.
1378                    return Err(Error::closed(LEFT_OPEN));
1379                }
1380                if let Some(e) = reset_failed {
1381                    return Err(e);
1382                }
1383                if idle {
1384                    self.wake_idle();
1385                }
1386            }
1387            other => {
1388                return Err(Error::protocol(format!(
1389                    "the server sent an unexpected {:?} message ({other:?})",
1390                    tag as char
1391                )))
1392            }
1393        }
1394        Ok(())
1395    }
1396
1397    /// The request's error from an `ErrorResponse`.
1398    fn db_error(&self, fields: &[u8], may_retire: bool) -> Result<Error, Error> {
1399        let db = DbError::parse(fields)?;
1400        if may_retire && db.code() == "25006" && self.on_standby() {
1401            self.retire.set(true);
1402        }
1403        // Only a note: the message is translated on servers whose
1404        // lc_messages is not English, and then there is none.
1405        let note = (db.code() == "57014" && db.message().contains("statement timeout")).then(
1406            || match self.config.statement_timeout {
1407                Some(limit) => format!(
1408                    "the statement ran longer than the statement timeout ({limit:?}; \
1409                     Config::statement_timeout)"
1410                ),
1411                None => "the statement ran longer than the server's statement_timeout".to_owned(),
1412            },
1413        );
1414        Ok(Error::from_db(db, note))
1415    }
1416
1417    /// The `CommandComplete`, `ErrorResponse` or `ReadyForQuery` of a slot
1418    /// of a batch ([`Config::batch_reads`]). Apart from [`handle`](Self::handle),
1419    /// which every request goes through, so that it stays as small as it was.
1420    #[cold]
1421    #[inline(never)]
1422    ///
1423    /// Returns whether the message is still to be handled, by the next slot.
1424    fn handle_batched(&self, slot: Rc<Slot>, msg: &Backend<'_>) -> Result<bool, Error> {
1425        let mut inner = slot.inner.borrow_mut();
1426        match *msg {
1427            Backend::CommandComplete(command) => {
1428                inner.tag = Some(Tag::of(command));
1429            }
1430            Backend::ErrorResponse(fields) => {
1431                // Not a sign of a standby: the batch is read-only on purpose.
1432                let error = self.db_error(fields, false)?;
1433                self.state.borrow_mut().batch_failed = true;
1434                match slot.batch.get() {
1435                    // At the `Sync`: the commit failed (a deferred
1436                    // constraint, say). The `ReadyForQuery` follows.
1437                    Role::End => return Ok(false),
1438                    // The guard's statement is gone (a `DEALLOCATE`): it is
1439                    // prepared again with the next batch. Its other errors
1440                    // (a cancel, a timeout) leave it prepared.
1441                    Role::Guard if error.server_code() == Some("26000") => {
1442                        self.state.borrow_mut().read_only_prepared = false;
1443                    }
1444                    _ => {}
1445                }
1446                if matches!(error.server_code(), Some("55P03" | "40P01" | "40001"))
1447                    && slot.batch.get() == Role::Member
1448                {
1449                    // A lock waited for, a deadlock or a serialization
1450                    // failure the batch may have caused by holding its
1451                    // locks: run again alone, where it is as without
1452                    // batches.
1453                    if let Kind::Execute { .. } = &slot.kind {
1454                        inner.alone = true;
1455                    }
1456                }
1457                if error.server_code() == Some("25006") {
1458                    // It would have run alone: send it alone.
1459                    if let Kind::Execute { stmt } = &slot.kind {
1460                        stmt.writes.set(true);
1461                        inner.alone = true;
1462                    }
1463                }
1464                inner.error = Some(error);
1465            }
1466            Backend::ReadyForQuery(status) if slot.batch.get() == Role::End => {
1467                // The batch's transaction ended, committed or rolled back:
1468                // the outcome is as outside a transaction.
1469                inner.status = status;
1470                drop(inner);
1471                let (idle, held, failed) = {
1472                    let mut st = self.state.borrow_mut();
1473                    st.status = status;
1474                    st.queue.pop_front();
1475                    st.extra -= 1;
1476                    self.head_since
1477                        .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1478                    let failed = std::mem::take(&mut st.batch_failed);
1479                    (st.queue.is_empty(), std::mem::take(&mut st.held), failed)
1480                };
1481                for member in &held {
1482                    if failed {
1483                        let mut inner = member.inner.borrow_mut();
1484                        if inner.error.is_none() {
1485                            // It ran, but what it did was rolled back with
1486                            // the batch: it runs again, alone.
1487                            inner.error = Some(Error::new(
1488                                ErrorKind::Closed,
1489                                "another statement of this one's batch failed, so the batch \
1490                                 was rolled back",
1491                            ));
1492                            inner.alone = matches!(member.kind, Kind::Execute { .. });
1493                        }
1494                    }
1495                    self.complete(member);
1496                }
1497                self.complete(&slot);
1498                if idle {
1499                    self.wake_idle();
1500                }
1501                return Ok(false);
1502            }
1503            Backend::ReadyForQuery(_) => {
1504                // The batch ended before this statement ran: a statement
1505                // before it failed, and the server skipped the rest.
1506                inner.error = Some(Error::new(
1507                    ErrorKind::Closed,
1508                    "a statement before this one in its batch failed, so the server skipped it",
1509                ));
1510                inner.alone = matches!(slot.kind, Kind::Execute { .. });
1511                drop(inner);
1512                self.finish_member(&slot);
1513                return Ok(true);
1514            }
1515            _ => unreachable!("only these three come here"),
1516        }
1517        drop(inner);
1518        self.finish_member(&slot);
1519        Ok(false)
1520    }
1521
1522    /// Works out a finished request's outcome and wakes whoever waits.
1523    fn complete(&self, slot: &Rc<Slot>) {
1524        let mut inner = slot.inner.borrow_mut();
1525        let error = inner.error.take();
1526        let outcome = match &slot.kind {
1527            Kind::Prepare { sql, name, cached } => {
1528                let result = match error {
1529                    Some(e) => Err(e),
1530                    None => match inner.params.take() {
1531                        Some(params) => Ok(Rc::new(Statement {
1532                            sql: sql.clone(),
1533                            name: name.clone(),
1534                            params,
1535                            columns: inner.columns.take().unwrap_or_default().into(),
1536                            conn: (!*cached).then(|| self.weak.clone()),
1537                            closed: Cell::new(false),
1538                            writes: Cell::new(false),
1539                        })),
1540                        None => Err(Error::protocol("the server did not describe the statement")),
1541                    },
1542                };
1543                if *cached {
1544                    self.settle_cache(sql, slot, &result);
1545                }
1546                result.map(Response::Statement)
1547            }
1548            Kind::Execute { stmt } => match error {
1549                Some(e) => {
1550                    let stale = self.forget_if_stale(stmt, &e);
1551                    // Failed in Bind (nothing ran) and outside a transaction
1552                    // (none was aborted): safe to run again.
1553                    inner.retry = stale && !inner.bound && inner.status == b'I';
1554                    Err(e)
1555                }
1556                None if inner.rows.overflow => Err(Error::new(
1557                    ErrorKind::TooLarge,
1558                    format!(
1559                        "the result is larger than max_result_size ({} bytes); add a LIMIT or \
1560                         select fewer columns, or raise Config::max_result_size",
1561                        self.config.max_result_size
1562                    ),
1563                )),
1564                None => {
1565                    let rows = std::mem::take(&mut inner.rows);
1566                    Ok(Response::Rows(
1567                        rows.finish(stmt.columns.clone()),
1568                        inner.tag.take(),
1569                    ))
1570                }
1571            },
1572            Kind::Simple => match error {
1573                Some(e) => Err(e),
1574                None => Ok(Response::Done(inner.tag.take())),
1575            },
1576        };
1577        inner.outcome = Some(outcome);
1578        inner.wakers.wake_all();
1579    }
1580
1581    /// Takes a cached statement out of the cache when the server says it no
1582    /// longer fits: the schema changed under it, or something deallocated it.
1583    /// The next run prepares it afresh. Returns whether the error was one of
1584    /// those.
1585    fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
1586        if !e.db().is_some_and(is_stale) {
1587            return false;
1588        }
1589        let mut st = self.state.borrow_mut();
1590        if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
1591        {
1592            st.cache.remove(&stmt.sql);
1593        }
1594        true
1595    }
1596
1597    /// Whether the server says it is a standby, or does not say (servers
1598    /// before PostgreSQL 14 do not report `in_hot_standby`).
1599    fn on_standby(&self) -> bool {
1600        let st = self.state.borrow();
1601        st.server_params
1602            .iter()
1603            .find(|(n, _)| n == "in_hot_standby")
1604            .map_or(true, |(_, v)| v != "off")
1605    }
1606
1607    /// Puts a prepared statement in the cache (or takes out a failed one),
1608    /// closing the least recently used statements when it is full.
1609    fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
1610        let mut st = self.state.borrow_mut();
1611        let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
1612        if !ours {
1613            return;
1614        }
1615        let Ok(stmt) = result else {
1616            st.cache.remove(sql);
1617            return;
1618        };
1619        st.clock += 1;
1620        let used = st.clock;
1621        st.cache.insert(
1622            sql.clone(),
1623            Entry::Ready {
1624                stmt: stmt.clone(),
1625                used,
1626            },
1627        );
1628        while st.cache.len() > self.config.statement_cache {
1629            // Only statements nobody is about to use can go.
1630            let victim = st
1631                .cache
1632                .iter()
1633                .filter_map(|(k, e)| match e {
1634                    Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
1635                        Some((*used, k.clone()))
1636                    }
1637                    _ => None,
1638                })
1639                .min();
1640            let Some((_, key)) = victim else { break };
1641            if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
1642                // No Sync: the close travels with the next request, whose
1643                // reply includes the CloseComplete.
1644                let _ = protocol::close_statement(&mut st.out, &stmt.name);
1645                // A batch must end `out` to take more statements.
1646                st.batch = None;
1647            }
1648        }
1649    }
1650}
1651
1652async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
1653    let err = loop {
1654        if let Err(e) = conn.process(&mut buf) {
1655            break e;
1656        }
1657        match conn.stream.read_into(&mut buf).await {
1658            Ok(0) => {
1659                let closing = conn.state.borrow().closing;
1660                break Error::closed(if closing {
1661                    "the connection was closed"
1662                } else {
1663                    "the server closed the connection"
1664                });
1665            }
1666            Ok(_) => {}
1667            Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
1668        }
1669    };
1670    conn.fail(err);
1671}
1672
1673async fn write_loop(conn: Rc<Conn>) {
1674    let mut spare = Vec::new();
1675    loop {
1676        let next = poll_fn(|cx| {
1677            let mut st = conn.state.borrow_mut();
1678            if st.broken.is_some() {
1679                return Poll::Ready(None);
1680            }
1681            if !st.out.is_empty() {
1682                // What is written cannot grow: a batch ends here.
1683                st.batch = None;
1684                return Poll::Ready(Some(std::mem::replace(
1685                    &mut st.out,
1686                    std::mem::take(&mut spare),
1687                )));
1688            }
1689            if st.closing {
1690                return Poll::Ready(None);
1691            }
1692            st.writer = Some(cx.waker().clone());
1693            Poll::Pending
1694        })
1695        .await;
1696        let Some(data) = next else { break };
1697        let (written, mut data) = conn.stream.write_all(data).await;
1698        if let Err(e) = written {
1699            conn.fail(Error::io(
1700                ErrorKind::Closed,
1701                "writing to the server failed",
1702                e,
1703            ));
1704            return;
1705        }
1706        data.clear();
1707        spare = data;
1708    }
1709    if conn.state.borrow().closing {
1710        conn.stream.shutdown(Shutdown::Write);
1711    }
1712}
1713
1714/// An open transaction. Statements run through it with the same methods as
1715/// on [`Client`] (it dereferences to the client).
1716///
1717/// Commit it with [`commit`](Self::commit). Dropping it otherwise rolls it
1718/// back: the `ROLLBACK` is queued at once, ahead of anything the connection
1719/// runs afterwards.
1720///
1721/// A statement given up before its answer came (its future dropped, by a
1722/// timeout or a `select` say) may still run on the server, so the
1723/// transaction can no longer be committed: from then on every statement
1724/// sent through it, [`commit`](Self::commit) included, fails with an
1725/// [`ErrorKind::Db`] error that says so, and nothing more is sent. Drop the
1726/// transaction or [`rollback`](Self::rollback) it, and run it again from the
1727/// start. A statement whose answer had arrived before its future was
1728/// dropped does not count: its outcome is known.
1729pub struct Transaction<'a> {
1730    client: &'a mut Client,
1731    done: bool,
1732}
1733
1734impl Transaction<'_> {
1735    /// Commits the transaction.
1736    ///
1737    /// When a statement in the transaction failed earlier, PostgreSQL rolls
1738    /// the transaction back instead; this is reported as an error, never as
1739    /// a successful commit. When a statement in it was given up before its
1740    /// answer came, `COMMIT` is not sent: the transaction is rolled back and
1741    /// the error says why (see [`Transaction`]).
1742    ///
1743    /// Not cancel safe: if the future is dropped, the transaction may have been
1744    /// committed or rolled back, and the caller does not learn which.
1745    pub async fn commit(mut self) -> Result<(), Error> {
1746        if self.client.conn.tx.get() == Tx::Abandoned {
1747            // Dropping `self` rolls it back.
1748            return Err(abandoned());
1749        }
1750        self.end();
1751        let slot = self
1752            .client
1753            .conn
1754            .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
1755        match (Wait { slot }).await? {
1756            Response::Done(Some(tag)) if tag.rollback => Err(Error::with_sqlstate(
1757                "25P02",
1758                "the transaction was rolled back instead of committed, because a statement in \
1759                 it failed earlier",
1760            )),
1761            _ => Ok(()),
1762        }
1763    }
1764
1765    /// Rolls the transaction back and waits for the server to confirm.
1766    ///
1767    /// Cancel safe: if the future is dropped, the transaction is rolled back
1768    /// all the same.
1769    pub async fn rollback(mut self) -> Result<(), Error> {
1770        self.end();
1771        self.client.batch_execute("ROLLBACK").await
1772    }
1773
1774    /// The transaction ends here: what is sent next is outside it.
1775    fn end(&mut self) {
1776        self.done = true;
1777        self.client.conn.tx.set(Tx::None);
1778    }
1779}
1780
1781impl Deref for Transaction<'_> {
1782    type Target = Client;
1783
1784    fn deref(&self) -> &Client {
1785        self.client
1786    }
1787}
1788
1789impl Drop for Transaction<'_> {
1790    fn drop(&mut self) {
1791        if !self.done {
1792            self.end();
1793            self.client.send_and_forget("ROLLBACK");
1794        }
1795    }
1796}
1797
1798impl std::fmt::Debug for Transaction<'_> {
1799    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1800        f.debug_struct("Transaction")
1801            .field("client", &self.client)
1802            .finish()
1803    }
1804}
1805
1806/// Asks the server to cancel what a connection is running.
1807///
1808/// It can be sent to another thread. The request goes over a new connection,
1809/// as the protocol requires; the statement being cancelled fails with SQLSTATE
1810/// `57014`. With several tasks sharing the connection, the statement running
1811/// when the request arrives is the one cancelled.
1812#[derive(Clone)]
1813pub struct CancelToken {
1814    /// Where to send the request; without the password, which it does not
1815    /// need.
1816    config: Config,
1817    key: Option<(i32, i32)>,
1818    /// Set for a token taken from a pooled connection: ended when the
1819    /// connection goes back to the pool.
1820    lease: Option<Arc<Lease>>,
1821}
1822
1823/// A pooled connection's time with one task, shared with the cancel tokens
1824/// taken during it: whether it has ended, and how many cancel requests are
1825/// on their way.
1826#[derive(Default)]
1827pub(crate) struct Lease(AtomicU32);
1828
1829impl Lease {
1830    /// Set once the connection has gone back to its pool.
1831    const ENDED: u32 = 1 << 31;
1832
1833    /// Counts a cancel request on its way, unless the lease has ended.
1834    fn start_cancel(&self) -> bool {
1835        let mut v = self.0.load(Ordering::Acquire);
1836        while v & Self::ENDED == 0 {
1837            match self
1838                .0
1839                .compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire)
1840            {
1841                Ok(_) => return true,
1842                Err(now) => v = now,
1843            }
1844        }
1845        false
1846    }
1847
1848    /// A cancel request that `start_cancel` counted got its answer.
1849    fn finish_cancel(&self) {
1850        self.0.fetch_sub(1, Ordering::AcqRel);
1851    }
1852
1853    fn is_ended(&self) -> bool {
1854        self.0.load(Ordering::Acquire) & Self::ENDED != 0
1855    }
1856
1857    /// Ends the lease; returns whether a cancel request is still on its way
1858    /// (or was given up on the way, which counts the same).
1859    fn end(&self) -> bool {
1860        self.0.fetch_or(Self::ENDED, Ordering::AcqRel) & !Self::ENDED != 0
1861    }
1862}
1863
1864impl CancelToken {
1865    /// Sends the cancel request. Success means the server received it, not
1866    /// that something was cancelled: the statement may have finished first.
1867    ///
1868    /// Fails with [`ErrorKind::Closed`], sending nothing, when the token was
1869    /// taken from a [`PooledClient`](crate::PooledClient) that has gone back
1870    /// to its pool since.
1871    ///
1872    /// Not cancel safe: if the future is dropped, the request may still reach
1873    /// the server and stop whatever the connection runs then.
1874    pub async fn cancel(&self) -> Result<(), Error> {
1875        let gone = || {
1876            Error::closed(
1877                "the connection this cancel token was taken from has gone back to its pool, \
1878                 where other tasks use it, so nothing was sent; take a new token from the next \
1879                 connection",
1880            )
1881        };
1882        if self.lease.as_ref().is_some_and(|lease| lease.is_ended()) {
1883            return Err(gone());
1884        }
1885        let key = self.key.ok_or_else(|| {
1886            Error::new(
1887                ErrorKind::Connect,
1888                "the server gave this connection no cancel key (a connection pooler may be in \
1889                 between), so it cannot be cancelled",
1890            )
1891        })?;
1892        let Some(lease) = &self.lease else {
1893            return connect::cancel(&self.config, key).await;
1894        };
1895        // Counted until the answer comes: a connection that goes back to the
1896        // pool meanwhile is closed rather than lent to a task whose
1897        // statement the request would stop. A request given up on the way
1898        // stays counted, for the same reason.
1899        if !lease.start_cancel() {
1900            return Err(gone());
1901        }
1902        let sent = connect::cancel(&self.config, key).await;
1903        lease.finish_cancel();
1904        sent
1905    }
1906}
1907
1908impl std::fmt::Debug for CancelToken {
1909    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1910        f.debug_struct("CancelToken")
1911            .field("server", &self.config.target())
1912            .finish_non_exhaustive()
1913    }
1914}
1915
1916#[cfg(test)]
1917mod tests {
1918    use super::{is_stale, Tag};
1919    use crate::error::DbError;
1920
1921    fn db_error(fields: &[(u8, &str)]) -> DbError {
1922        let mut body = Vec::new();
1923        for (field, value) in fields {
1924            body.push(*field);
1925            body.extend_from_slice(value.as_bytes());
1926            body.push(0);
1927        }
1928        body.push(0);
1929        DbError::parse(&body).unwrap()
1930    }
1931
1932    #[test]
1933    fn a_stale_plan_is_recognised_in_any_language() {
1934        let german = db_error(&[
1935            (b'S', "FEHLER"),
1936            (b'V', "ERROR"),
1937            (b'C', "0A000"),
1938            (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
1939            (b'R', "RevalidateCachedQuery"),
1940        ]);
1941        assert!(is_stale(&german));
1942        assert_eq!(german.severity(), "ERROR");
1943        // A server that sends no routine, in English.
1944        let english = db_error(&[
1945            (b'C', "0A000"),
1946            (b'M', "cached plan must not change result type"),
1947        ]);
1948        assert!(is_stale(&english));
1949        // Another "feature not supported" error.
1950        let other = db_error(&[
1951            (b'C', "0A000"),
1952            (b'M', "nicht unterstützt"),
1953            (b'R', "transformSelectStmt"),
1954        ]);
1955        assert!(!is_stale(&other));
1956        assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
1957    }
1958
1959    #[test]
1960    fn command_tags_give_row_counts() {
1961        assert_eq!(Tag::of("INSERT 0 5").rows, 5);
1962        assert_eq!(Tag::of("UPDATE 3").rows, 3);
1963        assert_eq!(Tag::of("SELECT 12").rows, 12);
1964        assert_eq!(Tag::of("CREATE TABLE").rows, 0);
1965        assert!(Tag::of("ROLLBACK").rollback && !Tag::of("COMMIT").rollback);
1966    }
1967}