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::task::{Context, Poll, Waker};
13
14use crate::config::Config;
15use crate::connect::{self, ReadBuf, Startup, Stream};
16use crate::error::{DbError, Error, ErrorKind};
17use crate::protocol::{self, parse_backend, Backend, MAX_PARAMS};
18use crate::row::{Column, ResultSet, Row, RowsBuilder};
19use crate::types::{ToSql, Type};
20
21/// A connection to a PostgreSQL server.
22///
23/// Every method takes `&self`, so tasks can share a client (through an `Rc`)
24/// and run statements at the same time: their messages go out together and
25/// the server answers them in order, one round trip for all of them
26/// (pipelining). A [`Transaction`] needs `&mut self`, so that no other task
27/// can slip a statement into it.
28///
29/// Statements are prepared on the server the first time the connection runs
30/// them and kept (see
31/// [`Config::statement_cache_capacity`](crate::Config::statement_cache_capacity)),
32/// so a statement that ran before takes a single round trip.
33///
34/// A client lives on the worker thread that opened it. Dropping it closes the
35/// connection once the statements already sent have been written.
36pub struct Client {
37    conn: Rc<Conn>,
38}
39
40/// A prepared statement on one connection.
41pub(crate) struct Statement {
42    sql: Rc<str>,
43    name: Box<str>,
44    params: Vec<Type>,
45    columns: Rc<[Column]>,
46    /// Set for a statement that is not cached: the connection, so that the
47    /// statement can be closed if it was never run.
48    conn: Option<Weak<Conn>>,
49    closed: Cell<bool>,
50}
51
52impl Drop for Statement {
53    fn drop(&mut self) {
54        let Some(conn) = self.conn.as_ref().and_then(Weak::upgrade) else {
55            return;
56        };
57        if !self.closed.get() {
58            // No Sync: the close travels with the next request.
59            if let Ok(mut st) = conn.state.try_borrow_mut() {
60                if st.broken.is_none() {
61                    let _ = protocol::close_statement(&mut st.out, &self.name);
62                }
63            }
64        }
65    }
66}
67
68/// The state shared by a client and its two tasks.
69struct Conn {
70    weak: Weak<Conn>,
71    stream: Stream,
72    state: RefCell<State>,
73    /// When the oldest unanswered request became the oldest; `None` with
74    /// nothing in flight.
75    head_since: Cell<Option<giong::time::Instant>>,
76    config: Config,
77    key: Option<(i32, i32)>,
78}
79
80struct State {
81    /// Messages waiting to be written.
82    out: Vec<u8>,
83    writer: Option<Waker>,
84    /// One entry per `Sync` or simple query sent, answered in order.
85    queue: VecDeque<Rc<Slot>>,
86    /// Why the connection stopped working, once it has.
87    broken: Option<Error>,
88    /// The client was dropped: write what is queued, then `Terminate`.
89    closing: bool,
90    /// The transaction status from the last `ReadyForQuery`.
91    status: u8,
92    cache: HashMap<Rc<str>, Entry>,
93    clock: u64,
94    next_name: u64,
95    server_params: Vec<(String, String)>,
96}
97
98enum Entry {
99    Ready { stmt: Rc<Statement>, used: u64 },
100    Preparing(Rc<Slot>),
101}
102
103/// A request in flight and what has arrived for it.
104struct Slot {
105    kind: Kind,
106    inner: RefCell<SlotInner>,
107}
108
109enum Kind {
110    Prepare {
111        sql: Rc<str>,
112        name: Box<str>,
113        cached: bool,
114    },
115    Execute {
116        stmt: Rc<Statement>,
117    },
118    Simple,
119}
120
121#[derive(Default)]
122struct SlotInner {
123    wakers: Vec<Waker>,
124    /// Nobody is waiting for the result any more: rows are not kept.
125    abandoned: bool,
126    error: Option<Error>,
127    params: Option<Vec<Type>>,
128    columns: Option<Vec<Column>>,
129    rows: RowsBuilder,
130    tag: Option<String>,
131    outcome: Option<Result<Response, Error>>,
132}
133
134enum Response {
135    Statement(Rc<Statement>),
136    Rows(ResultSet, Option<String>),
137    Done(Option<String>),
138}
139
140impl Slot {
141    fn new(kind: Kind) -> Rc<Self> {
142        Rc::new(Slot {
143            kind,
144            inner: RefCell::default(),
145        })
146    }
147}
148
149/// Waits for a slot's outcome. Dropping it lets the reader throw the rows
150/// away; the statement still runs.
151struct Wait {
152    slot: Rc<Slot>,
153}
154
155impl Future for Wait {
156    type Output = Result<Response, Error>;
157
158    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
159        let mut inner = self.slot.inner.borrow_mut();
160        let shared = matches!(self.slot.kind, Kind::Prepare { .. });
161        match &inner.outcome {
162            Some(Ok(Response::Statement(stmt))) if shared => {
163                return Poll::Ready(Ok(Response::Statement(stmt.clone())))
164            }
165            Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
166            Some(_) => return Poll::Ready(inner.outcome.take().expect("checked")),
167            None => {}
168        }
169        if !inner.wakers.iter().any(|w| w.will_wake(cx.waker())) {
170            inner.wakers.push(cx.waker().clone());
171        }
172        Poll::Pending
173    }
174}
175
176impl Drop for Wait {
177    fn drop(&mut self) {
178        if !matches!(self.slot.kind, Kind::Prepare { .. }) {
179            let mut inner = self.slot.inner.borrow_mut();
180            inner.abandoned = true;
181            inner.rows = RowsBuilder::default();
182        }
183    }
184}
185
186/// The number of rows a command tag reports: `INSERT 0 5`, `UPDATE 3`,
187/// `SELECT 7`.
188fn rows_affected(tag: Option<&str>) -> u64 {
189    tag.and_then(|t| t.rsplit(' ').next())
190        .and_then(|n| n.parse().ok())
191        .unwrap_or(0)
192}
193
194impl Client {
195    /// Opens a connection and logs in.
196    ///
197    /// Fails with [`ErrorKind::Connect`] when the server cannot be reached
198    /// within [`Config::connect_timeout`](crate::Config::connect_timeout),
199    /// [`ErrorKind::Auth`] when it refuses the credentials, and
200    /// [`ErrorKind::Config`] when the configuration is incomplete.
201    ///
202    /// # Panics
203    ///
204    /// Panics when called outside of a giong runtime.
205    pub async fn connect(config: &Config) -> Result<Client, Error> {
206        let startup = connect::connect(config).await?;
207        Ok(Self::start(startup, config.clone()))
208    }
209
210    fn start(startup: Startup, config: Config) -> Client {
211        let Startup {
212            stream,
213            buf,
214            params,
215            key,
216            status,
217        } = startup;
218        let conn = Rc::new_cyclic(|weak| Conn {
219            weak: weak.clone(),
220            head_since: Cell::new(None),
221            stream,
222            config,
223            key,
224            state: RefCell::new(State {
225                out: Vec::new(),
226                writer: None,
227                queue: VecDeque::new(),
228                broken: None,
229                closing: false,
230                status,
231                cache: HashMap::new(),
232                clock: 0,
233                next_name: 0,
234                server_params: params,
235            }),
236        });
237        giong::spawn(read_loop(conn.clone(), buf));
238        giong::spawn(write_loop(conn.clone()));
239        Client { conn }
240    }
241
242    /// Runs a statement and returns its rows.
243    ///
244    /// Parameters are written `$1`, `$2`... in the SQL and passed in order:
245    ///
246    /// ```no_run
247    /// # async fn f(client: &giong_postgres::Client) -> Result<(), giong_postgres::Error> {
248    /// let rows = client
249    ///     .query("SELECT id, email FROM users WHERE created_at > now() - $1::interval", &[&"7 days"])
250    ///     .await?;
251    /// for row in &rows {
252    ///     let id: i64 = row.get("id")?;
253    ///     let email: &str = row.get("email")?;
254    /// }
255    /// # Ok(()) }
256    /// ```
257    ///
258    /// The server decides each parameter's type from the SQL; see the
259    /// [`types`](crate::types) module for which Rust types fit which.
260    ///
261    /// Cancel safe in the sense that matters: dropping the future leaves the
262    /// connection usable. The statement may still run on the server.
263    pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
264        let (set, _) = self.run(sql, params).await?;
265        Ok(set.into_rows())
266    }
267
268    /// Runs a statement that must return exactly one row, and returns it.
269    ///
270    /// No row or several rows fail with [`ErrorKind::RowCount`].
271    pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
272        let mut rows = self.query(sql, params).await?;
273        match rows.len() {
274            1 => Ok(rows.pop().expect("one row")),
275            n => Err(Error::new(
276                ErrorKind::RowCount,
277                format!(
278                    "the statement returned {n} rows where exactly one was expected; use \
279                     query_opt for zero or one, or query for any number"
280                ),
281            )),
282        }
283    }
284
285    /// Runs a statement that returns at most one row.
286    ///
287    /// Several rows fail with [`ErrorKind::RowCount`].
288    pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
289        let mut rows = self.query(sql, params).await?;
290        match rows.len() {
291            0 | 1 => Ok(rows.pop()),
292            n => Err(Error::new(
293                ErrorKind::RowCount,
294                format!(
295                    "the statement returned {n} rows where at most one was expected; add a \
296                     LIMIT, or use query"
297                ),
298            )),
299        }
300    }
301
302    /// Runs a statement and returns the number of rows it inserted, updated
303    /// or deleted (or returned, for a `SELECT`).
304    pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
305        let (_, tag) = self.run(sql, params).await?;
306        Ok(rows_affected(tag.as_deref()))
307    }
308
309    /// Runs SQL that may hold several statements separated by `;`, with no
310    /// parameters, such as a schema migration. Rows they return are thrown
311    /// away.
312    ///
313    /// The statements run in one implicit transaction unless the SQL has its
314    /// own `BEGIN` and `COMMIT`: if one fails, the earlier ones are rolled
315    /// back.
316    pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
317        let slot = self
318            .conn
319            .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
320        Wait { slot }.await.map(|_| ())
321    }
322
323    /// Starts a transaction.
324    ///
325    /// It is committed by [`Transaction::commit`]; dropping it without a
326    /// commit rolls it back. While it is open, it holds the client mutably,
327    /// so no other statement can run on the connection outside it.
328    ///
329    /// ```no_run
330    /// # async fn f(client: &mut giong_postgres::Client) -> Result<(), giong_postgres::Error> {
331    /// let tx = client.transaction().await?;
332    /// tx.execute("UPDATE accounts SET balance = balance - $1 WHERE id = $2", &[&100i64, &1i64]).await?;
333    /// tx.execute("UPDATE accounts SET balance = balance + $1 WHERE id = $2", &[&100i64, &2i64]).await?;
334    /// tx.commit().await?;
335    /// # Ok(()) }
336    /// ```
337    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
338        // The guard exists before BEGIN is sent: if this future is dropped
339        // while waiting, the guard's drop rolls the transaction back.
340        let tx = Transaction {
341            client: self,
342            done: false,
343        };
344        tx.client.batch_execute("BEGIN").await?;
345        Ok(tx)
346    }
347
348    /// A handle that asks the server to cancel whatever this connection is
349    /// running, from any thread.
350    pub fn cancel_token(&self) -> CancelToken {
351        CancelToken {
352            config: self.conn.config.clone(),
353            key: self.conn.key,
354        }
355    }
356
357    /// A setting the server reported, such as `server_version`, `TimeZone`
358    /// or `integer_datetimes`.
359    pub fn parameter(&self, name: &str) -> Option<String> {
360        let st = self.conn.state.borrow();
361        st.server_params
362            .iter()
363            .find(|(n, _)| n == name)
364            .map(|(_, v)| v.clone())
365    }
366
367    /// Whether the connection has stopped working. A closed client fails
368    /// every statement with [`ErrorKind::Closed`].
369    pub fn is_closed(&self) -> bool {
370        self.conn.state.borrow().broken.is_some()
371    }
372
373    /// How many requests have been sent and not answered yet.
374    pub fn in_flight(&self) -> usize {
375        self.conn.state.borrow().queue.len()
376    }
377
378    /// How long the oldest unanswered request has been waiting for its
379    /// answer; zero with nothing in flight.
380    pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
381        self.conn
382            .head_since
383            .get()
384            .map_or(std::time::Duration::ZERO, |t| {
385                now.saturating_duration_since(t)
386            })
387    }
388
389    /// Whether the last answer from the server said a transaction was open.
390    pub(crate) fn in_transaction(&self) -> bool {
391        self.conn.state.borrow().status != b'I'
392    }
393
394    /// Queues a statement whose result nobody waits for.
395    pub(crate) fn send_and_forget(&self, sql: &str) {
396        if let Ok(slot) = self
397            .conn
398            .enqueue(Kind::Simple, |out| protocol::query(out, sql))
399        {
400            slot.inner.borrow_mut().abandoned = true;
401        }
402    }
403
404    async fn run(
405        &self,
406        sql: &str,
407        params: &[&dyn ToSql],
408    ) -> Result<(ResultSet, Option<String>), Error> {
409        if params.len() > MAX_PARAMS {
410            return Err(Error::conversion(format!(
411                "{} parameters were given; a statement can have at most {MAX_PARAMS}",
412                params.len()
413            )));
414        }
415        let stmt = self.conn.statement(sql).await?;
416        if stmt.params.len() != params.len() {
417            return Err(Error::conversion(format!(
418                "the statement has {} parameters but {} values were given",
419                stmt.params.len(),
420                params.len()
421            )));
422        }
423        let cached = stmt.conn.is_none();
424        let slot = self
425            .conn
426            .enqueue(Kind::Execute { stmt: stmt.clone() }, |out| {
427                protocol::bind(
428                    out,
429                    &stmt.name,
430                    params.len(),
431                    |i, out| {
432                        params[i].to_sql(stmt.params[i], out).map_err(|e| {
433                            e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
434                        })
435                    },
436                    stmt.columns.iter().map(|c| c.ty().binary_result()),
437                )?;
438                protocol::execute(out)?;
439                protocol::sync(out);
440                Ok(())
441            })?;
442        if !cached {
443            // In a request of its own: after an error the server skips the
444            // rest of a request, and the statement must go either way.
445            let close = self.conn.enqueue(Kind::Simple, |out| {
446                protocol::close_statement(out, &stmt.name)?;
447                protocol::sync(out);
448                Ok(())
449            });
450            if let Ok(close) = close {
451                close.inner.borrow_mut().abandoned = true;
452                stmt.closed.set(true);
453            }
454        }
455        drop(stmt);
456        match (Wait { slot }).await? {
457            Response::Rows(set, tag) => Ok((set, tag)),
458            _ => unreachable!("an execute slot ends with rows"),
459        }
460    }
461}
462
463impl Drop for Client {
464    fn drop(&mut self) {
465        let mut st = self.conn.state.borrow_mut();
466        st.closing = true;
467        if st.broken.is_none() {
468            protocol::terminate(&mut st.out);
469        }
470        if let Some(w) = st.writer.take() {
471            w.wake();
472        }
473    }
474}
475
476impl std::fmt::Debug for Client {
477    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478        f.debug_struct("Client")
479            .field("server", &self.conn.config.target())
480            .field("in_flight", &self.in_flight())
481            .field("closed", &self.is_closed())
482            .finish()
483    }
484}
485
486impl Conn {
487    /// Appends a request's messages and queues its slot, or fails without
488    /// sending anything.
489    fn enqueue(
490        &self,
491        kind: Kind,
492        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
493    ) -> Result<Rc<Slot>, Error> {
494        let mut st = self.state.borrow_mut();
495        if let Some(e) = &st.broken {
496            return Err(e.clone());
497        }
498        let start = st.out.len();
499        if let Err(e) = encode(&mut st.out) {
500            st.out.truncate(start);
501            return Err(e);
502        }
503        let slot = Slot::new(kind);
504        if st.queue.is_empty() {
505            self.head_since.set(Some(giong::time::Instant::now()));
506        }
507        st.queue.push_back(slot.clone());
508        if let Some(w) = st.writer.take() {
509            w.wake();
510        }
511        Ok(slot)
512    }
513
514    /// The prepared statement for `sql`: from the cache, from a prepare
515    /// already in flight, or prepared now.
516    async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
517        let pending = {
518            let mut st = self.state.borrow_mut();
519            st.clock += 1;
520            let now = st.clock;
521            match st.cache.get_mut(sql) {
522                Some(Entry::Ready { stmt, used }) => {
523                    *used = now;
524                    return Ok(stmt.clone());
525                }
526                Some(Entry::Preparing(slot)) => Some(slot.clone()),
527                None => None,
528            }
529        };
530        let Some(slot) = pending else {
531            return self.prepare(sql).await;
532        };
533        match (Wait { slot }).await? {
534            Response::Statement(stmt) => Ok(stmt),
535            _ => unreachable!("a prepare slot ends with a statement"),
536        }
537    }
538
539    async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
540        let cached = self.config.statement_cache > 0;
541        let (name, key) = {
542            let mut st = self.state.borrow_mut();
543            st.next_name += 1;
544            (format!("g{}", st.next_name), Rc::<str>::from(sql))
545        };
546        let slot = self.enqueue(
547            Kind::Prepare {
548                sql: key.clone(),
549                name: name.as_str().into(),
550                cached,
551            },
552            |out| {
553                protocol::parse(out, &name, sql)?;
554                protocol::describe_statement(out, &name)?;
555                protocol::sync(out);
556                Ok(())
557            },
558        )?;
559        if cached {
560            self.state
561                .borrow_mut()
562                .cache
563                .insert(key, Entry::Preparing(slot.clone()));
564        }
565        match (Wait { slot }).await? {
566            Response::Statement(stmt) => Ok(stmt),
567            _ => unreachable!("a prepare slot ends with a statement"),
568        }
569    }
570
571    /// Stops the connection: every request waiting gets `err` (or the
572    /// server's own error for it), and both tasks finish.
573    fn fail(&self, err: Error) {
574        let slots = {
575            let mut st = self.state.borrow_mut();
576            if st.broken.is_none() {
577                st.broken = Some(err.clone());
578            }
579            st.cache.clear();
580            st.out.clear();
581            self.head_since.set(None);
582            if let Some(w) = st.writer.take() {
583                w.wake();
584            }
585            std::mem::take(&mut st.queue)
586        };
587        for slot in slots {
588            let mut inner = slot.inner.borrow_mut();
589            let e = inner.error.take().unwrap_or_else(|| err.clone());
590            inner.outcome = Some(Err(e));
591            for w in inner.wakers.drain(..) {
592                w.wake();
593            }
594        }
595        self.stream.shutdown(Shutdown::Both);
596    }
597
598    /// Takes apart and handles every whole message in `buf`.
599    fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
600        let limit = self.config.max_result_size.max(1 << 20);
601        while let Some((tag, len)) = buf.peek()? {
602            if len > limit {
603                if tag != b'D' {
604                    return Err(Error::protocol(format!(
605                        "the server sent a {:?} message of {len} bytes, more than \
606                         max_result_size allows",
607                        tag as char
608                    )));
609                }
610                // One row larger than the limit: skip it as it arrives, and
611                // fail the statement once it completes.
612                self.front()?.inner.borrow_mut().rows.set_overflow();
613                buf.skip(len);
614                continue;
615            }
616            let Some(body) = buf.body(len) else {
617                return Ok(());
618            };
619            self.handle(tag, buf.bytes(body))?;
620            buf.consume(len);
621        }
622        Ok(())
623    }
624
625    fn front(&self) -> Result<Rc<Slot>, Error> {
626        self.state.borrow().queue.front().cloned().ok_or_else(|| {
627            Error::protocol("the server sent a reply to a request that was never made")
628        })
629    }
630
631    fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
632        let msg = parse_backend(tag, body)?;
633        match msg {
634            Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
635            Backend::ParameterStatus { name, value } => {
636                if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
637                    return Err(Error::closed(format!(
638                        "the session's client_encoding was changed to {value}; giong-postgres \
639                         reads and writes UTF-8 only, so the connection was closed"
640                    )));
641                }
642                let mut st = self.state.borrow_mut();
643                match st.server_params.iter_mut().find(|(n, _)| n == name) {
644                    Some(entry) => entry.1 = value.to_owned(),
645                    None => st.server_params.push((name.to_owned(), value.to_owned())),
646                }
647                return Ok(());
648            }
649            Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
650                // A FATAL error outside any request: the server is closing
651                // the connection (an administrator's command, a shutdown).
652                let db = DbError::parse(fields)?;
653                return Err(Error::with_db(
654                    ErrorKind::Closed,
655                    "the server closed the connection",
656                    db,
657                ));
658            }
659            _ => {}
660        }
661        let slot = self.front()?;
662        let mut inner = slot.inner.borrow_mut();
663        match msg {
664            Backend::ParseComplete
665            | Backend::BindComplete
666            | Backend::CloseComplete
667            | Backend::NoData
668            | Backend::PortalSuspended
669            | Backend::EmptyQueryResponse => {}
670            Backend::ParameterDescription(types) => inner.params = Some(types),
671            Backend::RowDescription(fields) => {
672                if matches!(slot.kind, Kind::Prepare { .. }) {
673                    inner.columns = Some(
674                        fields
675                            .iter()
676                            .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
677                            .collect(),
678                    );
679                }
680            }
681            Backend::DataRow(body) => match &slot.kind {
682                Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
683                    let limit = self.config.max_result_size;
684                    inner.rows.push(body, stmt.columns.len(), limit)?;
685                }
686                _ => {}
687            },
688            Backend::CommandComplete(tag) => inner.tag = Some(tag.to_owned()),
689            Backend::ErrorResponse(fields) => {
690                if inner.error.is_none() {
691                    let db = DbError::parse(fields)?;
692                    let note = (db.code() == "57014" && db.message().contains("statement timeout"))
693                        .then(|| {
694                            format!(
695                                "the statement ran longer than the statement timeout ({:?}; \
696                                 Config::statement_timeout)",
697                                self.config.statement_timeout
698                            )
699                        });
700                    inner.error = Some(Error::from_db(db, note));
701                }
702            }
703            Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
704                if inner.error.is_none() {
705                    inner.error = Some(Error::conversion(
706                        "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
707                         was thrown away",
708                    ));
709                }
710            }
711            Backend::CopyInResponse | Backend::CopyBothResponse => {
712                return Err(Error::closed(
713                    "the statement started COPY FROM STDIN or replication, which giong-postgres \
714                     does not support yet; the connection was closed",
715                ));
716            }
717            Backend::ReadyForQuery(status) => {
718                drop(inner);
719                {
720                    let mut st = self.state.borrow_mut();
721                    st.status = status;
722                    st.queue.pop_front();
723                    self.head_since
724                        .set((!st.queue.is_empty()).then(giong::time::Instant::now));
725                }
726                self.complete(&slot);
727            }
728            other => {
729                return Err(Error::protocol(format!(
730                    "the server sent an unexpected {:?} message ({other:?})",
731                    tag as char
732                )))
733            }
734        }
735        Ok(())
736    }
737
738    /// Works out a finished request's outcome and wakes whoever waits.
739    fn complete(&self, slot: &Rc<Slot>) {
740        let mut inner = slot.inner.borrow_mut();
741        let error = inner.error.take();
742        let outcome = match &slot.kind {
743            Kind::Prepare { sql, name, cached } => {
744                let result = match error {
745                    Some(e) => Err(e),
746                    None => match inner.params.take() {
747                        Some(params) => Ok(Rc::new(Statement {
748                            sql: sql.clone(),
749                            name: name.clone(),
750                            params,
751                            columns: inner.columns.take().unwrap_or_default().into(),
752                            conn: (!*cached).then(|| self.weak.clone()),
753                            closed: Cell::new(false),
754                        })),
755                        None => Err(Error::protocol("the server did not describe the statement")),
756                    },
757                };
758                if *cached {
759                    self.settle_cache(sql, slot, &result);
760                }
761                result.map(Response::Statement)
762            }
763            Kind::Execute { stmt } => match error {
764                Some(e) => {
765                    self.forget_if_stale(stmt, &e);
766                    Err(e)
767                }
768                None if inner.rows.overflow => Err(Error::new(
769                    ErrorKind::TooLarge,
770                    format!(
771                        "the result is larger than max_result_size ({} bytes); add a LIMIT or \
772                         select fewer columns, or raise Config::max_result_size",
773                        self.config.max_result_size
774                    ),
775                )),
776                None => {
777                    let rows = std::mem::take(&mut inner.rows);
778                    Ok(Response::Rows(
779                        rows.finish(stmt.columns.clone()),
780                        inner.tag.take(),
781                    ))
782                }
783            },
784            Kind::Simple => match error {
785                Some(e) => Err(e),
786                None => Ok(Response::Done(inner.tag.take())),
787            },
788        };
789        inner.outcome = Some(outcome);
790        for w in inner.wakers.drain(..) {
791            w.wake();
792        }
793    }
794
795    /// Takes a cached statement out of the cache when the server says it no
796    /// longer fits: the schema changed under it, or something deallocated it.
797    /// The next run prepares it afresh.
798    fn forget_if_stale(&self, stmt: &Statement, e: &Error) {
799        let stale = match e.db() {
800            Some(db) => {
801                (db.code() == "0A000" && db.message().contains("cached plan must not change"))
802                    || db.code() == "26000"
803            }
804            None => false,
805        };
806        if !stale {
807            return;
808        }
809        let mut st = self.state.borrow_mut();
810        if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
811        {
812            st.cache.remove(&stmt.sql);
813        }
814    }
815
816    /// Puts a prepared statement in the cache (or takes out a failed one),
817    /// closing the least recently used statements when it is full.
818    fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
819        let mut st = self.state.borrow_mut();
820        let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
821        if !ours {
822            return;
823        }
824        let Ok(stmt) = result else {
825            st.cache.remove(sql);
826            return;
827        };
828        st.clock += 1;
829        let used = st.clock;
830        st.cache.insert(
831            sql.clone(),
832            Entry::Ready {
833                stmt: stmt.clone(),
834                used,
835            },
836        );
837        while st.cache.len() > self.config.statement_cache {
838            // Only statements nobody is about to use can go.
839            let victim = st
840                .cache
841                .iter()
842                .filter_map(|(k, e)| match e {
843                    Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
844                        Some((*used, k.clone()))
845                    }
846                    _ => None,
847                })
848                .min();
849            let Some((_, key)) = victim else { break };
850            if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
851                // No Sync: the close travels with the next request, whose
852                // reply includes the CloseComplete.
853                let _ = protocol::close_statement(&mut st.out, &stmt.name);
854            }
855        }
856    }
857}
858
859async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
860    let err = loop {
861        if let Err(e) = conn.process(&mut buf) {
862            break e;
863        }
864        match conn.stream.recv().await {
865            Ok(chunk) if chunk.is_empty() => {
866                let closing = conn.state.borrow().closing;
867                break Error::closed(if closing {
868                    "the connection was closed"
869                } else {
870                    "the server closed the connection"
871                });
872            }
873            Ok(chunk) => buf.extend(&chunk),
874            Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
875        }
876    };
877    conn.fail(err);
878}
879
880async fn write_loop(conn: Rc<Conn>) {
881    let mut spare = Vec::new();
882    loop {
883        let next = poll_fn(|cx| {
884            let mut st = conn.state.borrow_mut();
885            if st.broken.is_some() {
886                return Poll::Ready(None);
887            }
888            if !st.out.is_empty() {
889                return Poll::Ready(Some(std::mem::replace(
890                    &mut st.out,
891                    std::mem::take(&mut spare),
892                )));
893            }
894            if st.closing {
895                return Poll::Ready(None);
896            }
897            st.writer = Some(cx.waker().clone());
898            Poll::Pending
899        })
900        .await;
901        let Some(data) = next else { break };
902        let (written, mut data) = conn.stream.write_all(data).await;
903        if let Err(e) = written {
904            conn.fail(Error::io(
905                ErrorKind::Closed,
906                "writing to the server failed",
907                e,
908            ));
909            return;
910        }
911        data.clear();
912        spare = data;
913    }
914    if conn.state.borrow().closing {
915        conn.stream.shutdown(Shutdown::Write);
916    }
917}
918
919/// An open transaction. Statements run through it with the same methods as
920/// on [`Client`] (it dereferences to the client).
921///
922/// Commit it with [`commit`](Self::commit). Dropping it otherwise rolls it
923/// back: the `ROLLBACK` is queued at once, ahead of anything the connection
924/// runs afterwards.
925pub struct Transaction<'a> {
926    client: &'a mut Client,
927    done: bool,
928}
929
930impl Transaction<'_> {
931    /// Commits the transaction.
932    ///
933    /// When a statement in the transaction failed earlier, PostgreSQL rolls
934    /// the transaction back instead; this is reported as an error, never as
935    /// a successful commit.
936    pub async fn commit(mut self) -> Result<(), Error> {
937        self.done = true;
938        let slot = self
939            .client
940            .conn
941            .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
942        match (Wait { slot }).await? {
943            Response::Done(Some(tag)) if tag == "ROLLBACK" => Err(Error::new(
944                ErrorKind::Db,
945                "the transaction was rolled back instead of committed, because a statement in \
946                 it failed earlier",
947            )),
948            _ => Ok(()),
949        }
950    }
951
952    /// Rolls the transaction back and waits for the server to confirm.
953    pub async fn rollback(mut self) -> Result<(), Error> {
954        self.done = true;
955        self.client.batch_execute("ROLLBACK").await
956    }
957}
958
959impl Deref for Transaction<'_> {
960    type Target = Client;
961
962    fn deref(&self) -> &Client {
963        self.client
964    }
965}
966
967impl Drop for Transaction<'_> {
968    fn drop(&mut self) {
969        if !self.done {
970            self.client.send_and_forget("ROLLBACK");
971        }
972    }
973}
974
975impl std::fmt::Debug for Transaction<'_> {
976    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
977        f.debug_struct("Transaction")
978            .field("client", &self.client)
979            .finish()
980    }
981}
982
983/// Asks the server to cancel what a connection is running.
984///
985/// It can be sent to another thread. The request goes over a new connection,
986/// as the protocol requires; the statement being cancelled fails with SQLSTATE
987/// `57014`. With several tasks sharing the connection, the statement running
988/// when the request arrives is the one cancelled.
989#[derive(Clone)]
990pub struct CancelToken {
991    config: Config,
992    key: Option<(i32, i32)>,
993}
994
995impl CancelToken {
996    /// Sends the cancel request. Success means the server received it, not
997    /// that something was cancelled: the statement may have finished first.
998    pub async fn cancel(&self) -> Result<(), Error> {
999        let key = self.key.ok_or_else(|| {
1000            Error::new(
1001                ErrorKind::Connect,
1002                "the server gave this connection no cancel key (a connection pooler may be in \
1003                 between), so it cannot be cancelled",
1004            )
1005        })?;
1006        connect::cancel(&self.config, key).await
1007    }
1008}
1009
1010impl std::fmt::Debug for CancelToken {
1011    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1012        f.debug_struct("CancelToken")
1013            .field("server", &self.config.target())
1014            .finish_non_exhaustive()
1015    }
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020    use super::rows_affected;
1021
1022    #[test]
1023    fn command_tags_give_row_counts() {
1024        assert_eq!(rows_affected(Some("INSERT 0 5")), 5);
1025        assert_eq!(rows_affected(Some("UPDATE 3")), 3);
1026        assert_eq!(rows_affected(Some("SELECT 12")), 12);
1027        assert_eq!(rows_affected(Some("CREATE TABLE")), 0);
1028        assert_eq!(rows_affected(None), 0);
1029    }
1030}