1use 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
23pub struct Client {
39 conn: Rc<Conn>,
40}
41
42pub(crate) struct Statement {
44 sql: Rc<str>,
45 name: Box<str>,
46 params: Vec<Type>,
47 columns: Rc<[Column]>,
48 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 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
70const 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
76const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
83 SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";
84
85const NAME_PREFIX: &str = "__giong_";
88
89struct Conn {
91 weak: Weak<Conn>,
92 stream: Stream,
93 state: RefCell<State>,
94 head_since: Cell<Option<giong::time::Instant>>,
97 config: Config,
98 key: Option<(i32, i32)>,
99 shared: Cell<bool>,
103 idle_wakers: RefCell<Vec<Waker>>,
105 requests: Cell<u64>,
108 lease: RefCell<Option<Arc<AtomicBool>>>,
111 retire: Cell<bool>,
115 user_prepared: Cell<bool>,
118}
119
120struct State {
121 out: Vec<u8>,
123 writer: Option<Waker>,
124 queue: VecDeque<Rc<Slot>>,
126 broken: Option<Error>,
128 closing: bool,
130 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
143struct Slot {
145 kind: Kind,
146 shared: bool,
148 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 abandoned: bool,
171 error: Option<Error>,
172 params: Option<Vec<Type>>,
173 columns: Option<Vec<Column>>,
174 rows: RowsBuilder,
175 tag: Option<String>,
176 bound: bool,
178 status: u8,
180 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
203struct 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
240fn 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
256fn 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 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 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 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 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 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 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 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
414 let tx = Transaction {
417 client: self,
418 done: false,
419 };
420 tx.client.batch_execute("BEGIN").await?;
421 Ok(tx)
422 }
423
424 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 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 pub fn is_closed(&self) -> bool {
451 self.conn.state.borrow().broken.is_some()
452 }
453
454 pub fn in_flight(&self) -> usize {
456 self.conn.state.borrow().queue.len()
457 }
458
459 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 pub(crate) fn in_transaction(&self) -> bool {
472 self.conn.state.borrow().status != b'I'
473 }
474
475 pub(crate) fn set_shared(&self, shared: bool) {
480 self.conn.shared.set(shared);
481 }
482
483 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 pub(crate) fn requests(&self) -> u64 {
493 self.conn.requests.get()
494 }
495
496 pub(crate) fn begin_lease(&self) {
499 *self.conn.lease.borrow_mut() = Some(Arc::new(AtomicBool::new(true)));
500 }
501
502 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 pub(crate) fn should_retire(&self) -> bool {
512 self.conn.retire.get()
513 }
514
515 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 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 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 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 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 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 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 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 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 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 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 b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
803 b'N' | b'A' | b'd' => {}
807 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 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 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 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 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 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 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 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 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 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 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 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
1186pub struct Transaction<'a> {
1193 client: &'a mut Client,
1194 done: bool,
1195}
1196
1197impl Transaction<'_> {
1198 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 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#[derive(Clone)]
1257pub struct CancelToken {
1258 config: Config,
1261 key: Option<(i32, i32)>,
1262 lease: Option<Arc<AtomicBool>>,
1265}
1266
1267impl CancelToken {
1268 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 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 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}