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