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::{AtomicBool, 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}
53
54impl Drop for Statement {
55    fn drop(&mut self) {
56        let Some(conn) = self.conn.as_ref().and_then(Weak::upgrade) else {
57            return;
58        };
59        if !self.closed.get() {
60            // No Sync: the close travels with the next request.
61            if let Ok(mut st) = conn.state.try_borrow_mut() {
62                if st.broken.is_none() {
63                    let _ = protocol::close_statement(&mut st.out, &self.name);
64                }
65            }
66        }
67    }
68}
69
70/// The error for a statement sent in a transaction that can no longer be
71/// committed.
72#[cold]
73#[inline(never)]
74fn abandoned() -> Error {
75    Error::new(
76        ErrorKind::Db,
77        "a statement of this transaction was given up before its answer came (its future was \
78         dropped, by a timeout say), and it may have run, so the transaction cannot be \
79         committed; this statement was not sent. Drop the transaction (which rolls it back) and \
80         run it again from the start",
81    )
82}
83
84/// Why a shared connection was closed under its statements.
85const LEFT_OPEN: &str = "a statement sent through the pool's shared methods (Pool::batch_execute) \
86     left a transaction open on a connection other tasks share, so the connection was closed and \
87     the transaction rolled back, with every statement sent on it since BEGIN, this one included. \
88     Run transactions on a connection of the task's own: pool.get().await?.transaction()";
89
90/// What a pool sends when a connection taken with `get()` comes back, so
91/// that the next task finds a clean session: `DISCARD ALL` without
92/// `DEALLOCATE ALL` (which would also drop the statement cache) and without
93/// `DISCARD PLANS` (plans are not session state). `RESET ALL` returns the
94/// settings sent when connecting (`statement_timeout`, `Config::param`) to
95/// those values, not to the server's defaults.
96const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
97     SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";
98
99/// The prefix of the names of the statements this crate prepares, chosen to
100/// stay clear of names an application would give its own.
101const NAME_PREFIX: &str = "__giong_";
102
103/// The state shared by a client and its two tasks.
104struct Conn {
105    weak: Weak<Conn>,
106    stream: Stream,
107    state: RefCell<State>,
108    /// When the oldest unanswered request became the oldest; `None` with
109    /// nothing in flight.
110    head_since: Cell<Option<giong::time::Instant>>,
111    config: Config,
112    key: Option<(i32, i32)>,
113    /// Several tasks send statements on this connection at once (it is among
114    /// a pool's shared connections): none of them may leave a transaction
115    /// open, which would take in the statements of the others.
116    shared: Cell<bool>,
117    /// Woken when nothing is in flight any more, or the connection fails.
118    idle_wakers: RefCell<Vec<Waker>>,
119    /// Requests sent since the connection opened: a pool compares the count
120    /// before and after lending it, to know whether it was used.
121    requests: Cell<u64>,
122    /// While a pool lends the connection to one task: the flag its cancel
123    /// tokens check, cleared when the connection goes back.
124    lease: RefCell<Option<Arc<AtomicBool>>>,
125    /// The server refused a write because it is a standby (it was a primary
126    /// once, or DNS still points at it): a pool closes the connection rather
127    /// than keep sending writes there.
128    retire: Cell<bool>,
129    /// A statement ran SQL-level `PREPARE`, whose prepared statement outlives
130    /// the task that made it.
131    user_prepared: Cell<bool>,
132    /// The state of the [`Transaction`] open on this connection.
133    tx: Cell<Tx>,
134}
135
136/// Where a [`Transaction`] stands, as the client sees it.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138enum Tx {
139    /// No `Transaction` is open.
140    None,
141    Open,
142    /// A statement in it was given up before its answer came (its future
143    /// was dropped): it may have run, so committing would commit work the
144    /// application believes undone. Nothing more is sent until it ends.
145    Abandoned,
146}
147
148struct State {
149    /// Messages waiting to be written.
150    out: Vec<u8>,
151    writer: Option<Waker>,
152    /// One entry per `Sync` or simple query sent, answered in order.
153    queue: VecDeque<Rc<Slot>>,
154    /// Why the connection stopped working, once it has.
155    broken: Option<Error>,
156    /// The client was dropped: write what is queued, then `Terminate`.
157    closing: bool,
158    /// The transaction status from the last `ReadyForQuery`.
159    status: u8,
160    cache: HashMap<Rc<str>, Entry>,
161    clock: u64,
162    next_name: u64,
163    server_params: Vec<(String, String)>,
164}
165
166enum Entry {
167    Ready { stmt: Rc<Statement>, used: u64 },
168    Preparing(Rc<Slot>),
169}
170
171/// A request in flight and what has arrived for it.
172struct Slot {
173    kind: Kind,
174    /// Sent while the connection was shared.
175    shared: bool,
176    /// The pool's session reset: if it fails, the session is in an unknown
177    /// state, so the connection is closed rather than reused.
178    close_on_error: bool,
179    /// A statement of an open transaction: giving it up before its answer
180    /// marks the transaction [`Tx::Abandoned`].
181    in_tx: Option<Weak<Conn>>,
182    inner: RefCell<SlotInner>,
183}
184
185enum Kind {
186    Prepare {
187        sql: Rc<str>,
188        name: Box<str>,
189        cached: bool,
190    },
191    Execute {
192        stmt: Rc<Statement>,
193    },
194    Simple,
195}
196
197#[derive(Default)]
198struct SlotInner {
199    wakers: Vec<Waker>,
200    /// Nobody is waiting for the result any more: rows are not kept.
201    abandoned: bool,
202    /// The outcome was handed to the caller.
203    delivered: bool,
204    error: Option<Error>,
205    params: Option<Vec<Type>>,
206    columns: Option<Vec<Column>>,
207    rows: RowsBuilder,
208    tag: Option<String>,
209    /// The server confirmed the Bind: the statement started running.
210    bound: bool,
211    /// The transaction status in the `ReadyForQuery` that ended the request.
212    status: u8,
213    /// The request failed on a stale cached statement before running, outside
214    /// a transaction: running it again is safe.
215    retry: bool,
216    outcome: Option<Result<Response, Error>>,
217}
218
219enum Response {
220    Statement(Rc<Statement>),
221    Rows(ResultSet, Option<String>),
222    Done(Option<String>),
223}
224
225impl Slot {
226    fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
227        Rc::new(Slot {
228            kind,
229            shared,
230            close_on_error,
231            in_tx,
232            inner: RefCell::default(),
233        })
234    }
235}
236
237/// Waits for a slot's outcome. Dropping it lets the reader throw the rows
238/// away; the statement still runs.
239struct Wait {
240    slot: Rc<Slot>,
241}
242
243impl Future for Wait {
244    type Output = Result<Response, Error>;
245
246    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
247        let mut inner = self.slot.inner.borrow_mut();
248        let shared = matches!(self.slot.kind, Kind::Prepare { .. });
249        match &inner.outcome {
250            Some(Ok(Response::Statement(stmt))) if shared => {
251                return Poll::Ready(Ok(Response::Statement(stmt.clone())))
252            }
253            Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
254            Some(_) => {
255                inner.delivered = true;
256                return Poll::Ready(inner.outcome.take().expect("checked"));
257            }
258            None => {}
259        }
260        if !inner.wakers.iter().any(|w| w.will_wake(cx.waker())) {
261            inner.wakers.push(cx.waker().clone());
262        }
263        Poll::Pending
264    }
265}
266
267impl Drop for Wait {
268    fn drop(&mut self) {
269        if matches!(self.slot.kind, Kind::Prepare { .. }) {
270            return;
271        }
272        // Its answer arrived (handed over or not): its outcome is known.
273        let known = {
274            let mut inner = self.slot.inner.borrow_mut();
275            inner.abandoned = true;
276            inner.rows = RowsBuilder::default();
277            inner.delivered || inner.outcome.is_some()
278        };
279        // The application gave up on a statement of its transaction, which
280        // may run all the same: the transaction must not commit it unseen.
281        if !known && self.slot.in_tx.is_some() {
282            abandon_tx(&self.slot);
283        }
284    }
285}
286
287/// Marks the transaction `slot` was sent in as abandoned (see [`Tx::Abandoned`]).
288#[cold]
289#[inline(never)]
290fn abandon_tx(slot: &Slot) {
291    if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
292        if conn.tx.get() == Tx::Open {
293            conn.tx.set(Tx::Abandoned);
294        }
295    }
296}
297
298/// Whether the server's error says a prepared statement no longer fits: the
299/// schema changed under its cached plan (`0A000` from
300/// `RevalidateCachedQuery`; the message is matched too, for servers that send
301/// no routine, but it is translated when `lc_messages` is not English), or it
302/// does not exist any more (`26000`, after `DEALLOCATE` or `DISCARD ALL`).
303fn is_stale(db: &DbError) -> bool {
304    match db.code() {
305        "26000" => true,
306        "0A000" => {
307            db.routine() == Some("RevalidateCachedQuery")
308                || db.message().contains("cached plan must not change")
309        }
310        _ => false,
311    }
312}
313
314/// The number of rows a command tag reports: `INSERT 0 5`, `UPDATE 3`,
315/// `SELECT 7`.
316fn rows_affected(tag: Option<&str>) -> u64 {
317    tag.and_then(|t| t.rsplit(' ').next())
318        .and_then(|n| n.parse().ok())
319        .unwrap_or(0)
320}
321
322impl Client {
323    /// Opens a connection and logs in.
324    ///
325    /// Fails with [`ErrorKind::Connect`] when the server cannot be reached
326    /// within [`Config::connect_timeout`](crate::Config::connect_timeout),
327    /// [`ErrorKind::Auth`] when it refuses the credentials, and
328    /// [`ErrorKind::Config`] when the configuration is incomplete.
329    ///
330    /// # Panics
331    ///
332    /// Panics when called outside of a giong runtime.
333    ///
334    /// Cancel safe: if the future is dropped, the connection being opened is
335    /// closed.
336    pub async fn connect(config: &Config) -> Result<Client, Error> {
337        let startup = connect::connect(config).await?;
338        Ok(Self::start(startup, config.clone()))
339    }
340
341    pub(crate) fn start(startup: Startup, config: Config) -> Client {
342        let Startup {
343            stream,
344            buf,
345            params,
346            key,
347            status,
348        } = startup;
349        let conn = Rc::new_cyclic(|weak| Conn {
350            weak: weak.clone(),
351            head_since: Cell::new(None),
352            stream,
353            config,
354            key,
355            shared: Cell::new(false),
356            idle_wakers: RefCell::new(Vec::new()),
357            requests: Cell::new(0),
358            lease: RefCell::new(None),
359            retire: Cell::new(false),
360            user_prepared: Cell::new(false),
361            tx: Cell::new(Tx::None),
362            state: RefCell::new(State {
363                out: Vec::new(),
364                writer: None,
365                queue: VecDeque::new(),
366                broken: None,
367                closing: false,
368                status,
369                cache: HashMap::new(),
370                clock: 0,
371                next_name: 0,
372                server_params: params,
373            }),
374        });
375        giong::spawn(read_loop(conn.clone(), buf));
376        giong::spawn(write_loop(conn.clone()));
377        Client { conn }
378    }
379
380    /// Runs a statement and returns its rows.
381    ///
382    /// Parameters are written `$1`, `$2`... in the SQL and passed in order:
383    ///
384    /// ```no_run
385    /// # async fn f(client: &giong_postgres::Client) -> Result<(), giong_postgres::Error> {
386    /// let rows = client
387    ///     .query("SELECT id, email FROM users WHERE created_at > now() - $1::interval", &[&"7 days"])
388    ///     .await?;
389    /// for row in &rows {
390    ///     let id: i64 = row.get("id")?;
391    ///     let email: &str = row.get("email")?;
392    /// }
393    /// # Ok(()) }
394    /// ```
395    ///
396    /// The server decides each parameter's type from the SQL; see the
397    /// [`types`](crate::types) module for which Rust types fit which.
398    ///
399    /// Not cancel safe: if the future is dropped, the statement may still run
400    /// on the server, and what it changes stays; the connection stays usable.
401    /// Inside a [`Transaction`], a later [`commit`](Transaction::commit)
402    /// commits it.
403    pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
404        let (set, _) = self.run(sql, params).await?;
405        Ok(set.into_rows())
406    }
407
408    /// Runs a statement that must return exactly one row, and returns it.
409    ///
410    /// No row or several rows fail with [`ErrorKind::RowCount`].
411    ///
412    /// Not cancel safe, like [`query`](Self::query).
413    pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
414        let mut rows = self.query(sql, params).await?;
415        match rows.len() {
416            1 => Ok(rows.pop().expect("one row")),
417            n => Err(Error::new(
418                ErrorKind::RowCount,
419                format!(
420                    "the statement returned {n} rows where exactly one was expected; use \
421                     query_opt for zero or one, or query for any number"
422                ),
423            )),
424        }
425    }
426
427    /// Runs a statement that returns at most one row.
428    ///
429    /// Several rows fail with [`ErrorKind::RowCount`].
430    ///
431    /// Not cancel safe, like [`query`](Self::query).
432    pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
433        let mut rows = self.query(sql, params).await?;
434        match rows.len() {
435            0 | 1 => Ok(rows.pop()),
436            n => Err(Error::new(
437                ErrorKind::RowCount,
438                format!(
439                    "the statement returned {n} rows where at most one was expected; add a \
440                     LIMIT, or use query"
441                ),
442            )),
443        }
444    }
445
446    /// Runs a statement and returns the number of rows it inserted, updated
447    /// or deleted (or returned, for a `SELECT`).
448    ///
449    /// Not cancel safe, like [`query`](Self::query).
450    pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
451        let (_, tag) = self.run(sql, params).await?;
452        Ok(rows_affected(tag.as_deref()))
453    }
454
455    /// Runs SQL that may hold several statements separated by `;`, with no
456    /// parameters, such as a schema migration. Rows they return are thrown
457    /// away.
458    ///
459    /// The statements run in one implicit transaction unless the SQL has its
460    /// own `BEGIN` and `COMMIT`: if one fails, the earlier ones are rolled
461    /// back.
462    ///
463    /// Not cancel safe: if the future is dropped, the statements may still run
464    /// on the server, and what they change stays.
465    pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
466        let slot = self
467            .conn
468            .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
469        Wait { slot }.await.map(|_| ())
470    }
471
472    /// Starts a transaction.
473    ///
474    /// It is committed by [`Transaction::commit`]; dropping it without a
475    /// commit rolls it back. While it is open, it holds the client mutably,
476    /// so no other statement can run on the connection outside it.
477    ///
478    /// ```no_run
479    /// # async fn f(client: &mut giong_postgres::Client) -> Result<(), giong_postgres::Error> {
480    /// let tx = client.transaction().await?;
481    /// tx.execute("UPDATE accounts SET balance = balance - $1 WHERE id = $2", &[&100i64, &1i64]).await?;
482    /// tx.execute("UPDATE accounts SET balance = balance + $1 WHERE id = $2", &[&100i64, &2i64]).await?;
483    /// tx.commit().await?;
484    /// # Ok(()) }
485    /// ```
486    ///
487    /// Cancel safe: if the future is dropped, a transaction it began is rolled
488    /// back.
489    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
490        // The guard exists before BEGIN is sent: if this future is dropped
491        // while waiting, the guard's drop rolls the transaction back.
492        let tx = Transaction {
493            client: self,
494            done: false,
495        };
496        tx.client.conn.tx.set(Tx::Open);
497        tx.client.batch_execute("BEGIN").await?;
498        Ok(tx)
499    }
500
501    /// A handle that asks the server to cancel whatever this connection is
502    /// running, from any thread.
503    ///
504    /// A token taken from a [`PooledClient`](crate::PooledClient) stops
505    /// working when the connection goes back to the pool, so that it cannot
506    /// cancel the statements of the tasks that use the connection next.
507    pub fn cancel_token(&self) -> CancelToken {
508        CancelToken {
509            config: self.conn.config.without_password(),
510            key: self.conn.key,
511            lease: self.conn.lease.borrow().clone(),
512        }
513    }
514
515    /// A setting the server reported, such as `server_version`, `TimeZone`
516    /// or `integer_datetimes`.
517    pub fn parameter(&self, name: &str) -> Option<String> {
518        let st = self.conn.state.borrow();
519        st.server_params
520            .iter()
521            .find(|(n, _)| n == name)
522            .map(|(_, v)| v.clone())
523    }
524
525    /// Whether the connection has stopped working. A closed client fails
526    /// every statement with [`ErrorKind::Closed`].
527    pub fn is_closed(&self) -> bool {
528        self.conn.state.borrow().broken.is_some()
529    }
530
531    /// How many requests have been sent and not answered yet.
532    pub fn in_flight(&self) -> usize {
533        self.conn.state.borrow().queue.len()
534    }
535
536    /// How long the oldest unanswered request has been waiting for its
537    /// answer; zero with nothing in flight.
538    pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
539        self.conn
540            .head_since
541            .get()
542            .map_or(std::time::Duration::ZERO, |t| {
543                now.saturating_duration_since(t)
544            })
545    }
546
547    /// Whether the last answer from the server said a transaction was open.
548    pub(crate) fn in_transaction(&self) -> bool {
549        self.conn.state.borrow().status != b'I'
550    }
551
552    /// Marks the connection as shared between tasks, or as one task's own.
553    /// Statements sent while it is shared must not leave a transaction open:
554    /// if one does, the connection is closed, which rolls the transaction
555    /// back, rather than let the statements of other tasks run inside it.
556    pub(crate) fn set_shared(&self, shared: bool) {
557        self.conn.shared.set(shared);
558    }
559
560    /// Wakes `waker` once nothing is in flight, or the connection fails.
561    pub(crate) fn wake_when_idle(&self, waker: &Waker) {
562        let mut wakers = self.conn.idle_wakers.borrow_mut();
563        if !wakers.iter().any(|w| w.will_wake(waker)) {
564            wakers.push(waker.clone());
565        }
566    }
567
568    /// How many requests have been sent on the connection since it opened.
569    pub(crate) fn requests(&self) -> u64 {
570        self.conn.requests.get()
571    }
572
573    /// Starts lending the connection to one task: cancel tokens taken from
574    /// now on work until [`end_lease`](Self::end_lease).
575    pub(crate) fn begin_lease(&self) {
576        *self.conn.lease.borrow_mut() = Some(Arc::new(AtomicBool::new(true)));
577    }
578
579    /// Ends the lease: the cancel tokens taken during it stop working.
580    pub(crate) fn end_lease(&self) {
581        if let Some(lease) = self.conn.lease.borrow_mut().take() {
582            lease.store(false, Ordering::Release);
583        }
584    }
585
586    /// Whether the connection should not be used any more although it works:
587    /// the server refused a write because it is a standby.
588    pub(crate) fn should_retire(&self) -> bool {
589        self.conn.retire.get()
590    }
591
592    /// Queues the pool's session reset ([`RESET`]), and `DEALLOCATE ALL` if a
593    /// statement ran SQL-level `PREPARE` (the statement cache is emptied with
594    /// it). Nobody waits for the result; if it fails, the connection is
595    /// closed.
596    pub(crate) fn reset_session(&self) {
597        let deallocate = self.conn.user_prepared.replace(false);
598        let sql = if deallocate {
599            self.conn.state.borrow_mut().cache.clear();
600            format!("{RESET}; DEALLOCATE ALL")
601        } else {
602            RESET.to_owned()
603        };
604        if let Ok(slot) = self
605            .conn
606            .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
607        {
608            slot.inner.borrow_mut().abandoned = true;
609        }
610    }
611
612    /// Queues a statement whose result nobody waits for.
613    pub(crate) fn send_and_forget(&self, sql: &str) {
614        if let Ok(slot) = self
615            .conn
616            .enqueue(Kind::Simple, |out| protocol::query(out, sql))
617        {
618            slot.inner.borrow_mut().abandoned = true;
619        }
620    }
621
622    async fn run(
623        &self,
624        sql: &str,
625        params: &[&dyn ToSql],
626    ) -> Result<(ResultSet, Option<String>), Error> {
627        if params.len() > MAX_PARAMS {
628            return Err(Error::conversion(format!(
629                "{} parameters were given; a statement can have at most {MAX_PARAMS}",
630                params.len()
631            )));
632        }
633        // A cached statement the schema changed under fails before running
634        // and is dropped from the cache: it is prepared again and run once
635        // more, unless that happened inside a transaction, which the error
636        // aborted.
637        let mut retried = false;
638        loop {
639            let slot = self.send(sql, params).await?;
640            let result = Wait { slot: slot.clone() }.await;
641            if result.is_err() && !retried && slot.inner.borrow().retry {
642                retried = true;
643                continue;
644            }
645            return match result? {
646                Response::Rows(set, tag) => Ok((set, tag)),
647                _ => unreachable!("an execute slot ends with rows"),
648            };
649        }
650    }
651
652    /// Prepares the statement if needed and sends a Bind and Execute for it.
653    async fn send(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Rc<Slot>, Error> {
654        let stmt = self.conn.statement(sql).await?;
655        if stmt.params.len() != params.len() {
656            return Err(Error::conversion(format!(
657                "the statement has {} parameters but {} values were given",
658                stmt.params.len(),
659                params.len()
660            )));
661        }
662        let cached = stmt.conn.is_none();
663        let slot = self
664            .conn
665            .enqueue(Kind::Execute { stmt: stmt.clone() }, |out| {
666                protocol::bind(
667                    out,
668                    &stmt.name,
669                    params.len(),
670                    |i, out| {
671                        params[i].to_sql(stmt.params[i], out).map_err(|e| {
672                            e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
673                        })
674                    },
675                    stmt.columns.iter().map(|c| c.ty().binary_result()),
676                )?;
677                protocol::execute(out)?;
678                protocol::sync(out);
679                Ok(())
680            })?;
681        if !cached {
682            // In a request of its own: after an error the server skips the
683            // rest of a request, and the statement must go either way.
684            let close = self.conn.enqueue(Kind::Simple, |out| {
685                protocol::close_statement(out, &stmt.name)?;
686                protocol::sync(out);
687                Ok(())
688            });
689            if let Ok(close) = close {
690                close.inner.borrow_mut().abandoned = true;
691                stmt.closed.set(true);
692            }
693        }
694        Ok(slot)
695    }
696}
697
698impl Drop for Client {
699    fn drop(&mut self) {
700        let mut st = self.conn.state.borrow_mut();
701        st.closing = true;
702        if st.broken.is_none() {
703            protocol::terminate(&mut st.out);
704        }
705        if let Some(w) = st.writer.take() {
706            w.wake();
707        }
708    }
709}
710
711impl std::fmt::Debug for Client {
712    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713        f.debug_struct("Client")
714            .field("server", &self.conn.config.target())
715            .field("in_flight", &self.in_flight())
716            .field("closed", &self.is_closed())
717            .finish()
718    }
719}
720
721impl Conn {
722    /// Appends a request's messages and queues its slot, or fails without
723    /// sending anything.
724    fn enqueue(
725        &self,
726        kind: Kind,
727        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
728    ) -> Result<Rc<Slot>, Error> {
729        self.enqueue_with(kind, false, encode)
730    }
731
732    /// The link a request sent in the open transaction keeps, or the error
733    /// if the transaction can no longer be committed.
734    #[cold]
735    #[inline(never)]
736    fn in_tx(&self) -> Result<Weak<Conn>, Error> {
737        match self.tx.get() {
738            Tx::Abandoned => Err(abandoned()),
739            _ => Ok(self.weak.clone()),
740        }
741    }
742
743    fn enqueue_with(
744        &self,
745        kind: Kind,
746        close_on_error: bool,
747        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
748    ) -> Result<Rc<Slot>, Error> {
749        let mut st = self.state.borrow_mut();
750        if let Some(e) = &st.broken {
751            return Err(e.clone());
752        }
753        let in_tx = if self.tx.get() == Tx::None {
754            None
755        } else {
756            Some(self.in_tx()?)
757        };
758        let start = st.out.len();
759        if let Err(e) = encode(&mut st.out) {
760            st.out.truncate(start);
761            return Err(e);
762        }
763        let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
764        self.requests.set(self.requests.get() + 1);
765        if st.queue.is_empty() {
766            self.head_since.set(Some(giong::time::Instant::now()));
767        }
768        st.queue.push_back(slot.clone());
769        if let Some(w) = st.writer.take() {
770            w.wake();
771        }
772        Ok(slot)
773    }
774
775    /// The prepared statement for `sql`: from the cache, from a prepare
776    /// already in flight, or prepared now.
777    async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
778        let mut again = true;
779        loop {
780            let pending = {
781                let mut st = self.state.borrow_mut();
782                st.clock += 1;
783                let now = st.clock;
784                match st.cache.get_mut(sql) {
785                    Some(Entry::Ready { stmt, used }) => {
786                        *used = now;
787                        return Ok(stmt.clone());
788                    }
789                    Some(Entry::Preparing(slot)) => Some(slot.clone()),
790                    None => None,
791                }
792            };
793            let Some(slot) = pending else {
794                return self.prepare(sql).await;
795            };
796            match (Wait { slot }).await {
797                Ok(Response::Statement(stmt)) => return Ok(stmt),
798                Ok(_) => unreachable!("a prepare slot ends with a statement"),
799                // The task that sent this prepare tries another name (see
800                // `prepare`); look in the cache again.
801                Err(e) if again && e.server_code() == Some("42P05") => again = false,
802                Err(e) => return Err(e),
803            }
804        }
805    }
806
807    async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
808        match self.prepare_once(sql).await {
809            // A statement of that name exists already: prepared by the
810            // application with SQL-level PREPARE, or by another client behind
811            // a connection pooler. The next name will do.
812            Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
813            result => result,
814        }
815    }
816
817    async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
818        let cached = self.config.statement_cache > 0;
819        let (name, key) = {
820            let mut st = self.state.borrow_mut();
821            st.next_name += 1;
822            (
823                format!("{NAME_PREFIX}{}", st.next_name),
824                Rc::<str>::from(sql),
825            )
826        };
827        let slot = self.enqueue(
828            Kind::Prepare {
829                sql: key.clone(),
830                name: name.as_str().into(),
831                cached,
832            },
833            |out| {
834                protocol::parse(out, &name, sql)?;
835                protocol::describe_statement(out, &name)?;
836                protocol::sync(out);
837                Ok(())
838            },
839        )?;
840        if cached {
841            self.state
842                .borrow_mut()
843                .cache
844                .insert(key, Entry::Preparing(slot.clone()));
845        }
846        match (Wait { slot }).await? {
847            Response::Statement(stmt) => Ok(stmt),
848            _ => unreachable!("a prepare slot ends with a statement"),
849        }
850    }
851
852    /// Stops the connection: every request waiting gets `err` (or the
853    /// server's own error for it), and both tasks finish.
854    fn fail(&self, err: Error) {
855        let slots = {
856            let mut st = self.state.borrow_mut();
857            if st.broken.is_none() {
858                st.broken = Some(err.clone());
859            }
860            st.cache.clear();
861            st.out.clear();
862            self.head_since.set(None);
863            if let Some(w) = st.writer.take() {
864                w.wake();
865            }
866            std::mem::take(&mut st.queue)
867        };
868        for slot in slots {
869            let mut inner = slot.inner.borrow_mut();
870            let e = inner.error.take().unwrap_or_else(|| err.clone());
871            inner.outcome = Some(Err(e));
872            for w in inner.wakers.drain(..) {
873                w.wake();
874            }
875        }
876        self.wake_idle();
877        self.stream.shutdown(Shutdown::Both);
878    }
879
880    fn wake_idle(&self) {
881        let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
882        for w in wakers {
883            w.wake();
884        }
885    }
886
887    /// Takes apart and handles every whole message in `buf`.
888    fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
889        let limit = self.config.max_result_size.max(1 << 20);
890        while let Some((tag, len)) = buf.peek()? {
891            if len > limit {
892                match tag {
893                    // One row larger than the limit: skip it as it arrives,
894                    // and fail the statement once it completes.
895                    b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
896                    // A notice or a notification (nobody reads them), or
897                    // COPY TO STDOUT output (thrown away, and the statement
898                    // fails anyway).
899                    b'N' | b'A' | b'd' => {}
900                    // The statement's error: it fails with this one instead,
901                    // and the connection stays usable.
902                    b'E' => {
903                        let slot = self.front()?;
904                        let mut inner = slot.inner.borrow_mut();
905                        if inner.error.is_none() {
906                            inner.error = Some(Error::new(
907                                ErrorKind::TooLarge,
908                                format!(
909                                    "the server's error for this statement was a {len}-byte \
910                                     message, more than max_result_size allows, so it was \
911                                     thrown away; raise Config::max_result_size to read it"
912                                ),
913                            ));
914                        }
915                    }
916                    _ => {
917                        return Err(Error::new(
918                            ErrorKind::Protocol,
919                            format!(
920                                "the server sent a {:?} message of {len} bytes, more than \
921                                 max_result_size allows, so the connection was closed; raise \
922                                 Config::max_result_size if the server's messages are this large",
923                                tag as char
924                            ),
925                        ))
926                    }
927                }
928                buf.skip(len);
929                continue;
930            }
931            let Some(body) = buf.body(len) else {
932                return Ok(());
933            };
934            self.handle(tag, buf.bytes(body))?;
935            buf.consume(len);
936        }
937        Ok(())
938    }
939
940    fn front(&self) -> Result<Rc<Slot>, Error> {
941        self.state.borrow().queue.front().cloned().ok_or_else(|| {
942            Error::protocol("the server sent a reply to a request that was never made")
943        })
944    }
945
946    fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
947        let msg = parse_backend(tag, body)?;
948        match msg {
949            Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
950            Backend::ParameterStatus { name, value } => {
951                if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
952                    return Err(Error::closed(format!(
953                        "the session's client_encoding was changed to {value}; giong-postgres \
954                         reads and writes UTF-8 only, so the connection was closed"
955                    )));
956                }
957                let mut st = self.state.borrow_mut();
958                match st.server_params.iter_mut().find(|(n, _)| n == name) {
959                    Some(entry) => entry.1 = value.to_owned(),
960                    None => st.server_params.push((name.to_owned(), value.to_owned())),
961                }
962                return Ok(());
963            }
964            Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
965                // A FATAL error outside any request: the server is closing
966                // the connection (an administrator's command, a shutdown).
967                let db = DbError::parse(fields)?;
968                return Err(Error::with_db(
969                    ErrorKind::Closed,
970                    "the server closed the connection",
971                    db,
972                ));
973            }
974            _ => {}
975        }
976        let slot = self.front()?;
977        let mut inner = slot.inner.borrow_mut();
978        match msg {
979            Backend::BindComplete => inner.bound = true,
980            Backend::ParseComplete
981            | Backend::CloseComplete
982            | Backend::NoData
983            | Backend::PortalSuspended
984            | Backend::EmptyQueryResponse => {}
985            Backend::ParameterDescription(types) => inner.params = Some(types),
986            Backend::RowDescription(fields) => {
987                if matches!(slot.kind, Kind::Prepare { .. }) {
988                    inner.columns = Some(
989                        fields
990                            .iter()
991                            .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
992                            .collect(),
993                    );
994                }
995            }
996            Backend::DataRow(body) => match &slot.kind {
997                Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
998                    let limit = self.config.max_result_size;
999                    inner.rows.push(body, stmt.columns.len(), limit)?;
1000                }
1001                _ => {}
1002            },
1003            Backend::CommandComplete(tag) => {
1004                if tag == "PREPARE" {
1005                    self.user_prepared.set(true);
1006                }
1007                inner.tag = Some(tag.to_owned());
1008            }
1009            Backend::ErrorResponse(fields) => {
1010                if inner.error.is_none() {
1011                    let db = DbError::parse(fields)?;
1012                    if db.code() == "25006" && self.on_standby() {
1013                        self.retire.set(true);
1014                    }
1015                    // Only a note: the message is translated on servers whose
1016                    // lc_messages is not English, and then there is none.
1017                    let note = (db.code() == "57014" && db.message().contains("statement timeout"))
1018                        .then(|| match self.config.statement_timeout {
1019                            Some(limit) => format!(
1020                                "the statement ran longer than the statement timeout ({limit:?}; \
1021                                 Config::statement_timeout)"
1022                            ),
1023                            None => "the statement ran longer than the server's statement_timeout"
1024                                .to_owned(),
1025                        });
1026                    inner.error = Some(Error::from_db(db, note));
1027                }
1028            }
1029            Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
1030                if inner.error.is_none() {
1031                    inner.error = Some(Error::conversion(
1032                        "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
1033                         was thrown away",
1034                    ));
1035                }
1036            }
1037            Backend::CopyInResponse | Backend::CopyBothResponse => {
1038                return Err(Error::closed(
1039                    "the statement started COPY FROM STDIN or replication, which giong-postgres \
1040                     does not support yet; the connection was closed",
1041                ));
1042            }
1043            Backend::ReadyForQuery(status) => {
1044                // A statement sent on a shared connection opened a
1045                // transaction (or left a failed one): the statements other
1046                // tasks send next would run inside it, and be lost with it.
1047                let left_open = slot.shared && status != b'I';
1048                if left_open {
1049                    inner.error = Some(Error::closed(LEFT_OPEN));
1050                }
1051                let reset_failed = match &inner.error {
1052                    Some(e) if slot.close_on_error => Some(Error::closed(format!(
1053                        "resetting the session of a connection that went back to the pool \
1054                         failed, so it was closed rather than reused: {e}"
1055                    ))),
1056                    _ => None,
1057                };
1058                inner.status = status;
1059                drop(inner);
1060                let idle = {
1061                    let mut st = self.state.borrow_mut();
1062                    st.status = status;
1063                    st.queue.pop_front();
1064                    self.head_since
1065                        .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1066                    st.queue.is_empty()
1067                };
1068                self.complete(&slot);
1069                if left_open {
1070                    // Closing the connection makes the server roll back.
1071                    return Err(Error::closed(LEFT_OPEN));
1072                }
1073                if let Some(e) = reset_failed {
1074                    return Err(e);
1075                }
1076                if idle {
1077                    self.wake_idle();
1078                }
1079            }
1080            other => {
1081                return Err(Error::protocol(format!(
1082                    "the server sent an unexpected {:?} message ({other:?})",
1083                    tag as char
1084                )))
1085            }
1086        }
1087        Ok(())
1088    }
1089
1090    /// Works out a finished request's outcome and wakes whoever waits.
1091    fn complete(&self, slot: &Rc<Slot>) {
1092        let mut inner = slot.inner.borrow_mut();
1093        let error = inner.error.take();
1094        let outcome = match &slot.kind {
1095            Kind::Prepare { sql, name, cached } => {
1096                let result = match error {
1097                    Some(e) => Err(e),
1098                    None => match inner.params.take() {
1099                        Some(params) => Ok(Rc::new(Statement {
1100                            sql: sql.clone(),
1101                            name: name.clone(),
1102                            params,
1103                            columns: inner.columns.take().unwrap_or_default().into(),
1104                            conn: (!*cached).then(|| self.weak.clone()),
1105                            closed: Cell::new(false),
1106                        })),
1107                        None => Err(Error::protocol("the server did not describe the statement")),
1108                    },
1109                };
1110                if *cached {
1111                    self.settle_cache(sql, slot, &result);
1112                }
1113                result.map(Response::Statement)
1114            }
1115            Kind::Execute { stmt } => match error {
1116                Some(e) => {
1117                    let stale = self.forget_if_stale(stmt, &e);
1118                    // Failed in Bind (nothing ran) and outside a transaction
1119                    // (none was aborted): safe to run again.
1120                    inner.retry = stale && !inner.bound && inner.status == b'I';
1121                    Err(e)
1122                }
1123                None if inner.rows.overflow => Err(Error::new(
1124                    ErrorKind::TooLarge,
1125                    format!(
1126                        "the result is larger than max_result_size ({} bytes); add a LIMIT or \
1127                         select fewer columns, or raise Config::max_result_size",
1128                        self.config.max_result_size
1129                    ),
1130                )),
1131                None => {
1132                    let rows = std::mem::take(&mut inner.rows);
1133                    Ok(Response::Rows(
1134                        rows.finish(stmt.columns.clone()),
1135                        inner.tag.take(),
1136                    ))
1137                }
1138            },
1139            Kind::Simple => match error {
1140                Some(e) => Err(e),
1141                None => Ok(Response::Done(inner.tag.take())),
1142            },
1143        };
1144        inner.outcome = Some(outcome);
1145        for w in inner.wakers.drain(..) {
1146            w.wake();
1147        }
1148    }
1149
1150    /// Takes a cached statement out of the cache when the server says it no
1151    /// longer fits: the schema changed under it, or something deallocated it.
1152    /// The next run prepares it afresh. Returns whether the error was one of
1153    /// those.
1154    fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
1155        if !e.db().is_some_and(is_stale) {
1156            return false;
1157        }
1158        let mut st = self.state.borrow_mut();
1159        if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
1160        {
1161            st.cache.remove(&stmt.sql);
1162        }
1163        true
1164    }
1165
1166    /// Whether the server says it is a standby, or does not say (servers
1167    /// before PostgreSQL 14 do not report `in_hot_standby`).
1168    fn on_standby(&self) -> bool {
1169        let st = self.state.borrow();
1170        st.server_params
1171            .iter()
1172            .find(|(n, _)| n == "in_hot_standby")
1173            .map_or(true, |(_, v)| v != "off")
1174    }
1175
1176    /// Puts a prepared statement in the cache (or takes out a failed one),
1177    /// closing the least recently used statements when it is full.
1178    fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
1179        let mut st = self.state.borrow_mut();
1180        let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
1181        if !ours {
1182            return;
1183        }
1184        let Ok(stmt) = result else {
1185            st.cache.remove(sql);
1186            return;
1187        };
1188        st.clock += 1;
1189        let used = st.clock;
1190        st.cache.insert(
1191            sql.clone(),
1192            Entry::Ready {
1193                stmt: stmt.clone(),
1194                used,
1195            },
1196        );
1197        while st.cache.len() > self.config.statement_cache {
1198            // Only statements nobody is about to use can go.
1199            let victim = st
1200                .cache
1201                .iter()
1202                .filter_map(|(k, e)| match e {
1203                    Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
1204                        Some((*used, k.clone()))
1205                    }
1206                    _ => None,
1207                })
1208                .min();
1209            let Some((_, key)) = victim else { break };
1210            if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
1211                // No Sync: the close travels with the next request, whose
1212                // reply includes the CloseComplete.
1213                let _ = protocol::close_statement(&mut st.out, &stmt.name);
1214            }
1215        }
1216    }
1217}
1218
1219async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
1220    let err = loop {
1221        if let Err(e) = conn.process(&mut buf) {
1222            break e;
1223        }
1224        match conn.stream.read_into(&mut buf).await {
1225            Ok(0) => {
1226                let closing = conn.state.borrow().closing;
1227                break Error::closed(if closing {
1228                    "the connection was closed"
1229                } else {
1230                    "the server closed the connection"
1231                });
1232            }
1233            Ok(_) => {}
1234            Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
1235        }
1236    };
1237    conn.fail(err);
1238}
1239
1240async fn write_loop(conn: Rc<Conn>) {
1241    let mut spare = Vec::new();
1242    loop {
1243        let next = poll_fn(|cx| {
1244            let mut st = conn.state.borrow_mut();
1245            if st.broken.is_some() {
1246                return Poll::Ready(None);
1247            }
1248            if !st.out.is_empty() {
1249                return Poll::Ready(Some(std::mem::replace(
1250                    &mut st.out,
1251                    std::mem::take(&mut spare),
1252                )));
1253            }
1254            if st.closing {
1255                return Poll::Ready(None);
1256            }
1257            st.writer = Some(cx.waker().clone());
1258            Poll::Pending
1259        })
1260        .await;
1261        let Some(data) = next else { break };
1262        let (written, mut data) = conn.stream.write_all(data).await;
1263        if let Err(e) = written {
1264            conn.fail(Error::io(
1265                ErrorKind::Closed,
1266                "writing to the server failed",
1267                e,
1268            ));
1269            return;
1270        }
1271        data.clear();
1272        spare = data;
1273    }
1274    if conn.state.borrow().closing {
1275        conn.stream.shutdown(Shutdown::Write);
1276    }
1277}
1278
1279/// An open transaction. Statements run through it with the same methods as
1280/// on [`Client`] (it dereferences to the client).
1281///
1282/// Commit it with [`commit`](Self::commit). Dropping it otherwise rolls it
1283/// back: the `ROLLBACK` is queued at once, ahead of anything the connection
1284/// runs afterwards.
1285///
1286/// A statement given up before its answer came (its future dropped, by a
1287/// timeout or a `select` say) may still run on the server, so the
1288/// transaction can no longer be committed: from then on every statement
1289/// sent through it, [`commit`](Self::commit) included, fails with an
1290/// [`ErrorKind::Db`] error that says so, and nothing more is sent. Drop the
1291/// transaction or [`rollback`](Self::rollback) it, and run it again from the
1292/// start. A statement whose answer had arrived before its future was
1293/// dropped does not count: its outcome is known.
1294pub struct Transaction<'a> {
1295    client: &'a mut Client,
1296    done: bool,
1297}
1298
1299impl Transaction<'_> {
1300    /// Commits the transaction.
1301    ///
1302    /// When a statement in the transaction failed earlier, PostgreSQL rolls
1303    /// the transaction back instead; this is reported as an error, never as
1304    /// a successful commit. When a statement in it was given up before its
1305    /// answer came, `COMMIT` is not sent: the transaction is rolled back and
1306    /// the error says why (see [`Transaction`]).
1307    ///
1308    /// Not cancel safe: if the future is dropped, the transaction may have been
1309    /// committed or rolled back, and the caller does not learn which.
1310    pub async fn commit(mut self) -> Result<(), Error> {
1311        if self.client.conn.tx.get() == Tx::Abandoned {
1312            // Dropping `self` rolls it back.
1313            return Err(abandoned());
1314        }
1315        self.end();
1316        let slot = self
1317            .client
1318            .conn
1319            .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
1320        match (Wait { slot }).await? {
1321            Response::Done(Some(tag)) if tag == "ROLLBACK" => Err(Error::with_sqlstate(
1322                "25P02",
1323                "the transaction was rolled back instead of committed, because a statement in \
1324                 it failed earlier",
1325            )),
1326            _ => Ok(()),
1327        }
1328    }
1329
1330    /// Rolls the transaction back and waits for the server to confirm.
1331    ///
1332    /// Cancel safe: if the future is dropped, the transaction is rolled back
1333    /// all the same.
1334    pub async fn rollback(mut self) -> Result<(), Error> {
1335        self.end();
1336        self.client.batch_execute("ROLLBACK").await
1337    }
1338
1339    /// The transaction ends here: what is sent next is outside it.
1340    fn end(&mut self) {
1341        self.done = true;
1342        self.client.conn.tx.set(Tx::None);
1343    }
1344}
1345
1346impl Deref for Transaction<'_> {
1347    type Target = Client;
1348
1349    fn deref(&self) -> &Client {
1350        self.client
1351    }
1352}
1353
1354impl Drop for Transaction<'_> {
1355    fn drop(&mut self) {
1356        if !self.done {
1357            self.end();
1358            self.client.send_and_forget("ROLLBACK");
1359        }
1360    }
1361}
1362
1363impl std::fmt::Debug for Transaction<'_> {
1364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1365        f.debug_struct("Transaction")
1366            .field("client", &self.client)
1367            .finish()
1368    }
1369}
1370
1371/// Asks the server to cancel what a connection is running.
1372///
1373/// It can be sent to another thread. The request goes over a new connection,
1374/// as the protocol requires; the statement being cancelled fails with SQLSTATE
1375/// `57014`. With several tasks sharing the connection, the statement running
1376/// when the request arrives is the one cancelled.
1377#[derive(Clone)]
1378pub struct CancelToken {
1379    /// Where to send the request; without the password, which it does not
1380    /// need.
1381    config: Config,
1382    key: Option<(i32, i32)>,
1383    /// Set for a token taken from a pooled connection: cleared when the
1384    /// connection goes back to the pool.
1385    lease: Option<Arc<AtomicBool>>,
1386}
1387
1388impl CancelToken {
1389    /// Sends the cancel request. Success means the server received it, not
1390    /// that something was cancelled: the statement may have finished first.
1391    ///
1392    /// Fails with [`ErrorKind::Closed`], sending nothing, when the token was
1393    /// taken from a [`PooledClient`](crate::PooledClient) that has gone back
1394    /// to its pool since.
1395    ///
1396    /// Not cancel safe: if the future is dropped, the request may still reach
1397    /// the server and stop whatever the connection runs then.
1398    pub async fn cancel(&self) -> Result<(), Error> {
1399        if self
1400            .lease
1401            .as_ref()
1402            .is_some_and(|lease| !lease.load(Ordering::Acquire))
1403        {
1404            return Err(Error::closed(
1405                "the connection this cancel token was taken from has gone back to its pool, \
1406                 where other tasks use it, so nothing was sent; take a new token from the next \
1407                 connection",
1408            ));
1409        }
1410        let key = self.key.ok_or_else(|| {
1411            Error::new(
1412                ErrorKind::Connect,
1413                "the server gave this connection no cancel key (a connection pooler may be in \
1414                 between), so it cannot be cancelled",
1415            )
1416        })?;
1417        connect::cancel(&self.config, key).await
1418    }
1419}
1420
1421impl std::fmt::Debug for CancelToken {
1422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1423        f.debug_struct("CancelToken")
1424            .field("server", &self.config.target())
1425            .finish_non_exhaustive()
1426    }
1427}
1428
1429#[cfg(test)]
1430mod tests {
1431    use super::{is_stale, rows_affected};
1432    use crate::error::DbError;
1433
1434    fn db_error(fields: &[(u8, &str)]) -> DbError {
1435        let mut body = Vec::new();
1436        for (field, value) in fields {
1437            body.push(*field);
1438            body.extend_from_slice(value.as_bytes());
1439            body.push(0);
1440        }
1441        body.push(0);
1442        DbError::parse(&body).unwrap()
1443    }
1444
1445    #[test]
1446    fn a_stale_plan_is_recognised_in_any_language() {
1447        let german = db_error(&[
1448            (b'S', "FEHLER"),
1449            (b'V', "ERROR"),
1450            (b'C', "0A000"),
1451            (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
1452            (b'R', "RevalidateCachedQuery"),
1453        ]);
1454        assert!(is_stale(&german));
1455        assert_eq!(german.severity(), "ERROR");
1456        // A server that sends no routine, in English.
1457        let english = db_error(&[
1458            (b'C', "0A000"),
1459            (b'M', "cached plan must not change result type"),
1460        ]);
1461        assert!(is_stale(&english));
1462        // Another "feature not supported" error.
1463        let other = db_error(&[
1464            (b'C', "0A000"),
1465            (b'M', "nicht unterstützt"),
1466            (b'R', "transformSelectStmt"),
1467        ]);
1468        assert!(!is_stale(&other));
1469        assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
1470    }
1471
1472    #[test]
1473    fn command_tags_give_row_counts() {
1474        assert_eq!(rows_affected(Some("INSERT 0 5")), 5);
1475        assert_eq!(rows_affected(Some("UPDATE 3")), 3);
1476        assert_eq!(rows_affected(Some("SELECT 12")), 12);
1477        assert_eq!(rows_affected(Some("CREATE TABLE")), 0);
1478        assert_eq!(rows_affected(None), 0);
1479    }
1480}