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