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
70#[cold]
73#[inline(never)]
74fn abandoned() -> Error {
75 Error::new(
76 ErrorKind::Db,
77 "a statement of this transaction was given up before its answer came (its future was \
78 dropped, by a timeout say), and it may have run, so the transaction cannot be \
79 committed; this statement was not sent. Drop the transaction (which rolls it back) and \
80 run it again from the start",
81 )
82}
83
84const LEFT_OPEN: &str = "a statement sent through the pool's shared methods (Pool::batch_execute) \
86 left a transaction open on a connection other tasks share, so the connection was closed and \
87 the transaction rolled back, with every statement sent on it since BEGIN, this one included. \
88 Run transactions on a connection of the task's own: pool.get().await?.transaction()";
89
90const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
97 SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";
98
99const NAME_PREFIX: &str = "__giong_";
102
103struct Conn {
105 weak: Weak<Conn>,
106 stream: Stream,
107 state: RefCell<State>,
108 head_since: Cell<Option<giong::time::Instant>>,
111 config: Config,
112 key: Option<(i32, i32)>,
113 shared: Cell<bool>,
117 idle_wakers: RefCell<Vec<Waker>>,
119 requests: Cell<u64>,
122 lease: RefCell<Option<Arc<AtomicBool>>>,
125 retire: Cell<bool>,
129 user_prepared: Cell<bool>,
132 tx: Cell<Tx>,
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138enum Tx {
139 None,
141 Open,
142 Abandoned,
146}
147
148struct State {
149 out: Vec<u8>,
151 writer: Option<Waker>,
152 queue: VecDeque<Rc<Slot>>,
154 broken: Option<Error>,
156 closing: bool,
158 status: u8,
160 cache: HashMap<Rc<str>, Entry>,
161 clock: u64,
162 next_name: u64,
163 server_params: Vec<(String, String)>,
164}
165
166enum Entry {
167 Ready { stmt: Rc<Statement>, used: u64 },
168 Preparing(Rc<Slot>),
169}
170
171struct Slot {
173 kind: Kind,
174 shared: bool,
176 close_on_error: bool,
179 in_tx: Option<Weak<Conn>>,
182 inner: RefCell<SlotInner>,
183}
184
185enum Kind {
186 Prepare {
187 sql: Rc<str>,
188 name: Box<str>,
189 cached: bool,
190 },
191 Execute {
192 stmt: Rc<Statement>,
193 },
194 Simple,
195}
196
197#[derive(Default)]
198struct SlotInner {
199 wakers: Vec<Waker>,
200 abandoned: bool,
202 delivered: bool,
204 error: Option<Error>,
205 params: Option<Vec<Type>>,
206 columns: Option<Vec<Column>>,
207 rows: RowsBuilder,
208 tag: Option<String>,
209 bound: bool,
211 status: u8,
213 retry: bool,
216 outcome: Option<Result<Response, Error>>,
217}
218
219enum Response {
220 Statement(Rc<Statement>),
221 Rows(ResultSet, Option<String>),
222 Done(Option<String>),
223}
224
225impl Slot {
226 fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
227 Rc::new(Slot {
228 kind,
229 shared,
230 close_on_error,
231 in_tx,
232 inner: RefCell::default(),
233 })
234 }
235}
236
237struct Wait {
240 slot: Rc<Slot>,
241}
242
243impl Future for Wait {
244 type Output = Result<Response, Error>;
245
246 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
247 let mut inner = self.slot.inner.borrow_mut();
248 let shared = matches!(self.slot.kind, Kind::Prepare { .. });
249 match &inner.outcome {
250 Some(Ok(Response::Statement(stmt))) if shared => {
251 return Poll::Ready(Ok(Response::Statement(stmt.clone())))
252 }
253 Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
254 Some(_) => {
255 inner.delivered = true;
256 return Poll::Ready(inner.outcome.take().expect("checked"));
257 }
258 None => {}
259 }
260 if !inner.wakers.iter().any(|w| w.will_wake(cx.waker())) {
261 inner.wakers.push(cx.waker().clone());
262 }
263 Poll::Pending
264 }
265}
266
267impl Drop for Wait {
268 fn drop(&mut self) {
269 if matches!(self.slot.kind, Kind::Prepare { .. }) {
270 return;
271 }
272 let known = {
274 let mut inner = self.slot.inner.borrow_mut();
275 inner.abandoned = true;
276 inner.rows = RowsBuilder::default();
277 inner.delivered || inner.outcome.is_some()
278 };
279 if !known && self.slot.in_tx.is_some() {
282 abandon_tx(&self.slot);
283 }
284 }
285}
286
287#[cold]
289#[inline(never)]
290fn abandon_tx(slot: &Slot) {
291 if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
292 if conn.tx.get() == Tx::Open {
293 conn.tx.set(Tx::Abandoned);
294 }
295 }
296}
297
298fn is_stale(db: &DbError) -> bool {
304 match db.code() {
305 "26000" => true,
306 "0A000" => {
307 db.routine() == Some("RevalidateCachedQuery")
308 || db.message().contains("cached plan must not change")
309 }
310 _ => false,
311 }
312}
313
314fn rows_affected(tag: Option<&str>) -> u64 {
317 tag.and_then(|t| t.rsplit(' ').next())
318 .and_then(|n| n.parse().ok())
319 .unwrap_or(0)
320}
321
322impl Client {
323 pub async fn connect(config: &Config) -> Result<Client, Error> {
337 let startup = connect::connect(config).await?;
338 Ok(Self::start(startup, config.clone()))
339 }
340
341 pub(crate) fn start(startup: Startup, config: Config) -> Client {
342 let Startup {
343 stream,
344 buf,
345 params,
346 key,
347 status,
348 } = startup;
349 let conn = Rc::new_cyclic(|weak| Conn {
350 weak: weak.clone(),
351 head_since: Cell::new(None),
352 stream,
353 config,
354 key,
355 shared: Cell::new(false),
356 idle_wakers: RefCell::new(Vec::new()),
357 requests: Cell::new(0),
358 lease: RefCell::new(None),
359 retire: Cell::new(false),
360 user_prepared: Cell::new(false),
361 tx: Cell::new(Tx::None),
362 state: RefCell::new(State {
363 out: Vec::new(),
364 writer: None,
365 queue: VecDeque::new(),
366 broken: None,
367 closing: false,
368 status,
369 cache: HashMap::new(),
370 clock: 0,
371 next_name: 0,
372 server_params: params,
373 }),
374 });
375 giong::spawn(read_loop(conn.clone(), buf));
376 giong::spawn(write_loop(conn.clone()));
377 Client { conn }
378 }
379
380 pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
404 let (set, _) = self.run(sql, params).await?;
405 Ok(set.into_rows())
406 }
407
408 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
414 let mut rows = self.query(sql, params).await?;
415 match rows.len() {
416 1 => Ok(rows.pop().expect("one row")),
417 n => Err(Error::new(
418 ErrorKind::RowCount,
419 format!(
420 "the statement returned {n} rows where exactly one was expected; use \
421 query_opt for zero or one, or query for any number"
422 ),
423 )),
424 }
425 }
426
427 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
433 let mut rows = self.query(sql, params).await?;
434 match rows.len() {
435 0 | 1 => Ok(rows.pop()),
436 n => Err(Error::new(
437 ErrorKind::RowCount,
438 format!(
439 "the statement returned {n} rows where at most one was expected; add a \
440 LIMIT, or use query"
441 ),
442 )),
443 }
444 }
445
446 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
451 let (_, tag) = self.run(sql, params).await?;
452 Ok(rows_affected(tag.as_deref()))
453 }
454
455 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
466 let slot = self
467 .conn
468 .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
469 Wait { slot }.await.map(|_| ())
470 }
471
472 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
490 let tx = Transaction {
493 client: self,
494 done: false,
495 };
496 tx.client.conn.tx.set(Tx::Open);
497 tx.client.batch_execute("BEGIN").await?;
498 Ok(tx)
499 }
500
501 pub fn cancel_token(&self) -> CancelToken {
508 CancelToken {
509 config: self.conn.config.without_password(),
510 key: self.conn.key,
511 lease: self.conn.lease.borrow().clone(),
512 }
513 }
514
515 pub fn parameter(&self, name: &str) -> Option<String> {
518 let st = self.conn.state.borrow();
519 st.server_params
520 .iter()
521 .find(|(n, _)| n == name)
522 .map(|(_, v)| v.clone())
523 }
524
525 pub fn is_closed(&self) -> bool {
528 self.conn.state.borrow().broken.is_some()
529 }
530
531 pub fn in_flight(&self) -> usize {
533 self.conn.state.borrow().queue.len()
534 }
535
536 pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
539 self.conn
540 .head_since
541 .get()
542 .map_or(std::time::Duration::ZERO, |t| {
543 now.saturating_duration_since(t)
544 })
545 }
546
547 pub(crate) fn in_transaction(&self) -> bool {
549 self.conn.state.borrow().status != b'I'
550 }
551
552 pub(crate) fn set_shared(&self, shared: bool) {
557 self.conn.shared.set(shared);
558 }
559
560 pub(crate) fn wake_when_idle(&self, waker: &Waker) {
562 let mut wakers = self.conn.idle_wakers.borrow_mut();
563 if !wakers.iter().any(|w| w.will_wake(waker)) {
564 wakers.push(waker.clone());
565 }
566 }
567
568 pub(crate) fn requests(&self) -> u64 {
570 self.conn.requests.get()
571 }
572
573 pub(crate) fn begin_lease(&self) {
576 *self.conn.lease.borrow_mut() = Some(Arc::new(AtomicBool::new(true)));
577 }
578
579 pub(crate) fn end_lease(&self) {
581 if let Some(lease) = self.conn.lease.borrow_mut().take() {
582 lease.store(false, Ordering::Release);
583 }
584 }
585
586 pub(crate) fn should_retire(&self) -> bool {
589 self.conn.retire.get()
590 }
591
592 pub(crate) fn reset_session(&self) {
597 let deallocate = self.conn.user_prepared.replace(false);
598 let sql = if deallocate {
599 self.conn.state.borrow_mut().cache.clear();
600 format!("{RESET}; DEALLOCATE ALL")
601 } else {
602 RESET.to_owned()
603 };
604 if let Ok(slot) = self
605 .conn
606 .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
607 {
608 slot.inner.borrow_mut().abandoned = true;
609 }
610 }
611
612 pub(crate) fn send_and_forget(&self, sql: &str) {
614 if let Ok(slot) = self
615 .conn
616 .enqueue(Kind::Simple, |out| protocol::query(out, sql))
617 {
618 slot.inner.borrow_mut().abandoned = true;
619 }
620 }
621
622 async fn run(
623 &self,
624 sql: &str,
625 params: &[&dyn ToSql],
626 ) -> Result<(ResultSet, Option<String>), Error> {
627 if params.len() > MAX_PARAMS {
628 return Err(Error::conversion(format!(
629 "{} parameters were given; a statement can have at most {MAX_PARAMS}",
630 params.len()
631 )));
632 }
633 let mut retried = false;
638 loop {
639 let slot = self.send(sql, params).await?;
640 let result = Wait { slot: slot.clone() }.await;
641 if result.is_err() && !retried && slot.inner.borrow().retry {
642 retried = true;
643 continue;
644 }
645 return match result? {
646 Response::Rows(set, tag) => Ok((set, tag)),
647 _ => unreachable!("an execute slot ends with rows"),
648 };
649 }
650 }
651
652 async fn send(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Rc<Slot>, Error> {
654 let stmt = self.conn.statement(sql).await?;
655 if stmt.params.len() != params.len() {
656 return Err(Error::conversion(format!(
657 "the statement has {} parameters but {} values were given",
658 stmt.params.len(),
659 params.len()
660 )));
661 }
662 let cached = stmt.conn.is_none();
663 let slot = self
664 .conn
665 .enqueue(Kind::Execute { stmt: stmt.clone() }, |out| {
666 protocol::bind(
667 out,
668 &stmt.name,
669 params.len(),
670 |i, out| {
671 params[i].to_sql(stmt.params[i], out).map_err(|e| {
672 e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
673 })
674 },
675 stmt.columns.iter().map(|c| c.ty().binary_result()),
676 )?;
677 protocol::execute(out)?;
678 protocol::sync(out);
679 Ok(())
680 })?;
681 if !cached {
682 let close = self.conn.enqueue(Kind::Simple, |out| {
685 protocol::close_statement(out, &stmt.name)?;
686 protocol::sync(out);
687 Ok(())
688 });
689 if let Ok(close) = close {
690 close.inner.borrow_mut().abandoned = true;
691 stmt.closed.set(true);
692 }
693 }
694 Ok(slot)
695 }
696}
697
698impl Drop for Client {
699 fn drop(&mut self) {
700 let mut st = self.conn.state.borrow_mut();
701 st.closing = true;
702 if st.broken.is_none() {
703 protocol::terminate(&mut st.out);
704 }
705 if let Some(w) = st.writer.take() {
706 w.wake();
707 }
708 }
709}
710
711impl std::fmt::Debug for Client {
712 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713 f.debug_struct("Client")
714 .field("server", &self.conn.config.target())
715 .field("in_flight", &self.in_flight())
716 .field("closed", &self.is_closed())
717 .finish()
718 }
719}
720
721impl Conn {
722 fn enqueue(
725 &self,
726 kind: Kind,
727 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
728 ) -> Result<Rc<Slot>, Error> {
729 self.enqueue_with(kind, false, encode)
730 }
731
732 #[cold]
735 #[inline(never)]
736 fn in_tx(&self) -> Result<Weak<Conn>, Error> {
737 match self.tx.get() {
738 Tx::Abandoned => Err(abandoned()),
739 _ => Ok(self.weak.clone()),
740 }
741 }
742
743 fn enqueue_with(
744 &self,
745 kind: Kind,
746 close_on_error: bool,
747 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
748 ) -> Result<Rc<Slot>, Error> {
749 let mut st = self.state.borrow_mut();
750 if let Some(e) = &st.broken {
751 return Err(e.clone());
752 }
753 let in_tx = if self.tx.get() == Tx::None {
754 None
755 } else {
756 Some(self.in_tx()?)
757 };
758 let start = st.out.len();
759 if let Err(e) = encode(&mut st.out) {
760 st.out.truncate(start);
761 return Err(e);
762 }
763 let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
764 self.requests.set(self.requests.get() + 1);
765 if st.queue.is_empty() {
766 self.head_since.set(Some(giong::time::Instant::now()));
767 }
768 st.queue.push_back(slot.clone());
769 if let Some(w) = st.writer.take() {
770 w.wake();
771 }
772 Ok(slot)
773 }
774
775 async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
778 let mut again = true;
779 loop {
780 let pending = {
781 let mut st = self.state.borrow_mut();
782 st.clock += 1;
783 let now = st.clock;
784 match st.cache.get_mut(sql) {
785 Some(Entry::Ready { stmt, used }) => {
786 *used = now;
787 return Ok(stmt.clone());
788 }
789 Some(Entry::Preparing(slot)) => Some(slot.clone()),
790 None => None,
791 }
792 };
793 let Some(slot) = pending else {
794 return self.prepare(sql).await;
795 };
796 match (Wait { slot }).await {
797 Ok(Response::Statement(stmt)) => return Ok(stmt),
798 Ok(_) => unreachable!("a prepare slot ends with a statement"),
799 Err(e) if again && e.server_code() == Some("42P05") => again = false,
802 Err(e) => return Err(e),
803 }
804 }
805 }
806
807 async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
808 match self.prepare_once(sql).await {
809 Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
813 result => result,
814 }
815 }
816
817 async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
818 let cached = self.config.statement_cache > 0;
819 let (name, key) = {
820 let mut st = self.state.borrow_mut();
821 st.next_name += 1;
822 (
823 format!("{NAME_PREFIX}{}", st.next_name),
824 Rc::<str>::from(sql),
825 )
826 };
827 let slot = self.enqueue(
828 Kind::Prepare {
829 sql: key.clone(),
830 name: name.as_str().into(),
831 cached,
832 },
833 |out| {
834 protocol::parse(out, &name, sql)?;
835 protocol::describe_statement(out, &name)?;
836 protocol::sync(out);
837 Ok(())
838 },
839 )?;
840 if cached {
841 self.state
842 .borrow_mut()
843 .cache
844 .insert(key, Entry::Preparing(slot.clone()));
845 }
846 match (Wait { slot }).await? {
847 Response::Statement(stmt) => Ok(stmt),
848 _ => unreachable!("a prepare slot ends with a statement"),
849 }
850 }
851
852 fn fail(&self, err: Error) {
855 let slots = {
856 let mut st = self.state.borrow_mut();
857 if st.broken.is_none() {
858 st.broken = Some(err.clone());
859 }
860 st.cache.clear();
861 st.out.clear();
862 self.head_since.set(None);
863 if let Some(w) = st.writer.take() {
864 w.wake();
865 }
866 std::mem::take(&mut st.queue)
867 };
868 for slot in slots {
869 let mut inner = slot.inner.borrow_mut();
870 let e = inner.error.take().unwrap_or_else(|| err.clone());
871 inner.outcome = Some(Err(e));
872 for w in inner.wakers.drain(..) {
873 w.wake();
874 }
875 }
876 self.wake_idle();
877 self.stream.shutdown(Shutdown::Both);
878 }
879
880 fn wake_idle(&self) {
881 let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
882 for w in wakers {
883 w.wake();
884 }
885 }
886
887 fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
889 let limit = self.config.max_result_size.max(1 << 20);
890 while let Some((tag, len)) = buf.peek()? {
891 if len > limit {
892 match tag {
893 b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
896 b'N' | b'A' | b'd' => {}
900 b'E' => {
903 let slot = self.front()?;
904 let mut inner = slot.inner.borrow_mut();
905 if inner.error.is_none() {
906 inner.error = Some(Error::new(
907 ErrorKind::TooLarge,
908 format!(
909 "the server's error for this statement was a {len}-byte \
910 message, more than max_result_size allows, so it was \
911 thrown away; raise Config::max_result_size to read it"
912 ),
913 ));
914 }
915 }
916 _ => {
917 return Err(Error::new(
918 ErrorKind::Protocol,
919 format!(
920 "the server sent a {:?} message of {len} bytes, more than \
921 max_result_size allows, so the connection was closed; raise \
922 Config::max_result_size if the server's messages are this large",
923 tag as char
924 ),
925 ))
926 }
927 }
928 buf.skip(len);
929 continue;
930 }
931 let Some(body) = buf.body(len) else {
932 return Ok(());
933 };
934 self.handle(tag, buf.bytes(body))?;
935 buf.consume(len);
936 }
937 Ok(())
938 }
939
940 fn front(&self) -> Result<Rc<Slot>, Error> {
941 self.state.borrow().queue.front().cloned().ok_or_else(|| {
942 Error::protocol("the server sent a reply to a request that was never made")
943 })
944 }
945
946 fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
947 let msg = parse_backend(tag, body)?;
948 match msg {
949 Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
950 Backend::ParameterStatus { name, value } => {
951 if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
952 return Err(Error::closed(format!(
953 "the session's client_encoding was changed to {value}; giong-postgres \
954 reads and writes UTF-8 only, so the connection was closed"
955 )));
956 }
957 let mut st = self.state.borrow_mut();
958 match st.server_params.iter_mut().find(|(n, _)| n == name) {
959 Some(entry) => entry.1 = value.to_owned(),
960 None => st.server_params.push((name.to_owned(), value.to_owned())),
961 }
962 return Ok(());
963 }
964 Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
965 let db = DbError::parse(fields)?;
968 return Err(Error::with_db(
969 ErrorKind::Closed,
970 "the server closed the connection",
971 db,
972 ));
973 }
974 _ => {}
975 }
976 let slot = self.front()?;
977 let mut inner = slot.inner.borrow_mut();
978 match msg {
979 Backend::BindComplete => inner.bound = true,
980 Backend::ParseComplete
981 | Backend::CloseComplete
982 | Backend::NoData
983 | Backend::PortalSuspended
984 | Backend::EmptyQueryResponse => {}
985 Backend::ParameterDescription(types) => inner.params = Some(types),
986 Backend::RowDescription(fields) => {
987 if matches!(slot.kind, Kind::Prepare { .. }) {
988 inner.columns = Some(
989 fields
990 .iter()
991 .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
992 .collect(),
993 );
994 }
995 }
996 Backend::DataRow(body) => match &slot.kind {
997 Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
998 let limit = self.config.max_result_size;
999 inner.rows.push(body, stmt.columns.len(), limit)?;
1000 }
1001 _ => {}
1002 },
1003 Backend::CommandComplete(tag) => {
1004 if tag == "PREPARE" {
1005 self.user_prepared.set(true);
1006 }
1007 inner.tag = Some(tag.to_owned());
1008 }
1009 Backend::ErrorResponse(fields) => {
1010 if inner.error.is_none() {
1011 let db = DbError::parse(fields)?;
1012 if db.code() == "25006" && self.on_standby() {
1013 self.retire.set(true);
1014 }
1015 let note = (db.code() == "57014" && db.message().contains("statement timeout"))
1018 .then(|| match self.config.statement_timeout {
1019 Some(limit) => format!(
1020 "the statement ran longer than the statement timeout ({limit:?}; \
1021 Config::statement_timeout)"
1022 ),
1023 None => "the statement ran longer than the server's statement_timeout"
1024 .to_owned(),
1025 });
1026 inner.error = Some(Error::from_db(db, note));
1027 }
1028 }
1029 Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
1030 if inner.error.is_none() {
1031 inner.error = Some(Error::conversion(
1032 "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
1033 was thrown away",
1034 ));
1035 }
1036 }
1037 Backend::CopyInResponse | Backend::CopyBothResponse => {
1038 return Err(Error::closed(
1039 "the statement started COPY FROM STDIN or replication, which giong-postgres \
1040 does not support yet; the connection was closed",
1041 ));
1042 }
1043 Backend::ReadyForQuery(status) => {
1044 let left_open = slot.shared && status != b'I';
1048 if left_open {
1049 inner.error = Some(Error::closed(LEFT_OPEN));
1050 }
1051 let reset_failed = match &inner.error {
1052 Some(e) if slot.close_on_error => Some(Error::closed(format!(
1053 "resetting the session of a connection that went back to the pool \
1054 failed, so it was closed rather than reused: {e}"
1055 ))),
1056 _ => None,
1057 };
1058 inner.status = status;
1059 drop(inner);
1060 let idle = {
1061 let mut st = self.state.borrow_mut();
1062 st.status = status;
1063 st.queue.pop_front();
1064 self.head_since
1065 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1066 st.queue.is_empty()
1067 };
1068 self.complete(&slot);
1069 if left_open {
1070 return Err(Error::closed(LEFT_OPEN));
1072 }
1073 if let Some(e) = reset_failed {
1074 return Err(e);
1075 }
1076 if idle {
1077 self.wake_idle();
1078 }
1079 }
1080 other => {
1081 return Err(Error::protocol(format!(
1082 "the server sent an unexpected {:?} message ({other:?})",
1083 tag as char
1084 )))
1085 }
1086 }
1087 Ok(())
1088 }
1089
1090 fn complete(&self, slot: &Rc<Slot>) {
1092 let mut inner = slot.inner.borrow_mut();
1093 let error = inner.error.take();
1094 let outcome = match &slot.kind {
1095 Kind::Prepare { sql, name, cached } => {
1096 let result = match error {
1097 Some(e) => Err(e),
1098 None => match inner.params.take() {
1099 Some(params) => Ok(Rc::new(Statement {
1100 sql: sql.clone(),
1101 name: name.clone(),
1102 params,
1103 columns: inner.columns.take().unwrap_or_default().into(),
1104 conn: (!*cached).then(|| self.weak.clone()),
1105 closed: Cell::new(false),
1106 })),
1107 None => Err(Error::protocol("the server did not describe the statement")),
1108 },
1109 };
1110 if *cached {
1111 self.settle_cache(sql, slot, &result);
1112 }
1113 result.map(Response::Statement)
1114 }
1115 Kind::Execute { stmt } => match error {
1116 Some(e) => {
1117 let stale = self.forget_if_stale(stmt, &e);
1118 inner.retry = stale && !inner.bound && inner.status == b'I';
1121 Err(e)
1122 }
1123 None if inner.rows.overflow => Err(Error::new(
1124 ErrorKind::TooLarge,
1125 format!(
1126 "the result is larger than max_result_size ({} bytes); add a LIMIT or \
1127 select fewer columns, or raise Config::max_result_size",
1128 self.config.max_result_size
1129 ),
1130 )),
1131 None => {
1132 let rows = std::mem::take(&mut inner.rows);
1133 Ok(Response::Rows(
1134 rows.finish(stmt.columns.clone()),
1135 inner.tag.take(),
1136 ))
1137 }
1138 },
1139 Kind::Simple => match error {
1140 Some(e) => Err(e),
1141 None => Ok(Response::Done(inner.tag.take())),
1142 },
1143 };
1144 inner.outcome = Some(outcome);
1145 for w in inner.wakers.drain(..) {
1146 w.wake();
1147 }
1148 }
1149
1150 fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
1155 if !e.db().is_some_and(is_stale) {
1156 return false;
1157 }
1158 let mut st = self.state.borrow_mut();
1159 if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
1160 {
1161 st.cache.remove(&stmt.sql);
1162 }
1163 true
1164 }
1165
1166 fn on_standby(&self) -> bool {
1169 let st = self.state.borrow();
1170 st.server_params
1171 .iter()
1172 .find(|(n, _)| n == "in_hot_standby")
1173 .map_or(true, |(_, v)| v != "off")
1174 }
1175
1176 fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
1179 let mut st = self.state.borrow_mut();
1180 let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
1181 if !ours {
1182 return;
1183 }
1184 let Ok(stmt) = result else {
1185 st.cache.remove(sql);
1186 return;
1187 };
1188 st.clock += 1;
1189 let used = st.clock;
1190 st.cache.insert(
1191 sql.clone(),
1192 Entry::Ready {
1193 stmt: stmt.clone(),
1194 used,
1195 },
1196 );
1197 while st.cache.len() > self.config.statement_cache {
1198 let victim = st
1200 .cache
1201 .iter()
1202 .filter_map(|(k, e)| match e {
1203 Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
1204 Some((*used, k.clone()))
1205 }
1206 _ => None,
1207 })
1208 .min();
1209 let Some((_, key)) = victim else { break };
1210 if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
1211 let _ = protocol::close_statement(&mut st.out, &stmt.name);
1214 }
1215 }
1216 }
1217}
1218
1219async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
1220 let err = loop {
1221 if let Err(e) = conn.process(&mut buf) {
1222 break e;
1223 }
1224 match conn.stream.read_into(&mut buf).await {
1225 Ok(0) => {
1226 let closing = conn.state.borrow().closing;
1227 break Error::closed(if closing {
1228 "the connection was closed"
1229 } else {
1230 "the server closed the connection"
1231 });
1232 }
1233 Ok(_) => {}
1234 Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
1235 }
1236 };
1237 conn.fail(err);
1238}
1239
1240async fn write_loop(conn: Rc<Conn>) {
1241 let mut spare = Vec::new();
1242 loop {
1243 let next = poll_fn(|cx| {
1244 let mut st = conn.state.borrow_mut();
1245 if st.broken.is_some() {
1246 return Poll::Ready(None);
1247 }
1248 if !st.out.is_empty() {
1249 return Poll::Ready(Some(std::mem::replace(
1250 &mut st.out,
1251 std::mem::take(&mut spare),
1252 )));
1253 }
1254 if st.closing {
1255 return Poll::Ready(None);
1256 }
1257 st.writer = Some(cx.waker().clone());
1258 Poll::Pending
1259 })
1260 .await;
1261 let Some(data) = next else { break };
1262 let (written, mut data) = conn.stream.write_all(data).await;
1263 if let Err(e) = written {
1264 conn.fail(Error::io(
1265 ErrorKind::Closed,
1266 "writing to the server failed",
1267 e,
1268 ));
1269 return;
1270 }
1271 data.clear();
1272 spare = data;
1273 }
1274 if conn.state.borrow().closing {
1275 conn.stream.shutdown(Shutdown::Write);
1276 }
1277}
1278
1279pub struct Transaction<'a> {
1295 client: &'a mut Client,
1296 done: bool,
1297}
1298
1299impl Transaction<'_> {
1300 pub async fn commit(mut self) -> Result<(), Error> {
1311 if self.client.conn.tx.get() == Tx::Abandoned {
1312 return Err(abandoned());
1314 }
1315 self.end();
1316 let slot = self
1317 .client
1318 .conn
1319 .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
1320 match (Wait { slot }).await? {
1321 Response::Done(Some(tag)) if tag == "ROLLBACK" => Err(Error::with_sqlstate(
1322 "25P02",
1323 "the transaction was rolled back instead of committed, because a statement in \
1324 it failed earlier",
1325 )),
1326 _ => Ok(()),
1327 }
1328 }
1329
1330 pub async fn rollback(mut self) -> Result<(), Error> {
1335 self.end();
1336 self.client.batch_execute("ROLLBACK").await
1337 }
1338
1339 fn end(&mut self) {
1341 self.done = true;
1342 self.client.conn.tx.set(Tx::None);
1343 }
1344}
1345
1346impl Deref for Transaction<'_> {
1347 type Target = Client;
1348
1349 fn deref(&self) -> &Client {
1350 self.client
1351 }
1352}
1353
1354impl Drop for Transaction<'_> {
1355 fn drop(&mut self) {
1356 if !self.done {
1357 self.end();
1358 self.client.send_and_forget("ROLLBACK");
1359 }
1360 }
1361}
1362
1363impl std::fmt::Debug for Transaction<'_> {
1364 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1365 f.debug_struct("Transaction")
1366 .field("client", &self.client)
1367 .finish()
1368 }
1369}
1370
1371#[derive(Clone)]
1378pub struct CancelToken {
1379 config: Config,
1382 key: Option<(i32, i32)>,
1383 lease: Option<Arc<AtomicBool>>,
1386}
1387
1388impl CancelToken {
1389 pub async fn cancel(&self) -> Result<(), Error> {
1399 if self
1400 .lease
1401 .as_ref()
1402 .is_some_and(|lease| !lease.load(Ordering::Acquire))
1403 {
1404 return Err(Error::closed(
1405 "the connection this cancel token was taken from has gone back to its pool, \
1406 where other tasks use it, so nothing was sent; take a new token from the next \
1407 connection",
1408 ));
1409 }
1410 let key = self.key.ok_or_else(|| {
1411 Error::new(
1412 ErrorKind::Connect,
1413 "the server gave this connection no cancel key (a connection pooler may be in \
1414 between), so it cannot be cancelled",
1415 )
1416 })?;
1417 connect::cancel(&self.config, key).await
1418 }
1419}
1420
1421impl std::fmt::Debug for CancelToken {
1422 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1423 f.debug_struct("CancelToken")
1424 .field("server", &self.config.target())
1425 .finish_non_exhaustive()
1426 }
1427}
1428
1429#[cfg(test)]
1430mod tests {
1431 use super::{is_stale, rows_affected};
1432 use crate::error::DbError;
1433
1434 fn db_error(fields: &[(u8, &str)]) -> DbError {
1435 let mut body = Vec::new();
1436 for (field, value) in fields {
1437 body.push(*field);
1438 body.extend_from_slice(value.as_bytes());
1439 body.push(0);
1440 }
1441 body.push(0);
1442 DbError::parse(&body).unwrap()
1443 }
1444
1445 #[test]
1446 fn a_stale_plan_is_recognised_in_any_language() {
1447 let german = db_error(&[
1448 (b'S', "FEHLER"),
1449 (b'V', "ERROR"),
1450 (b'C', "0A000"),
1451 (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
1452 (b'R', "RevalidateCachedQuery"),
1453 ]);
1454 assert!(is_stale(&german));
1455 assert_eq!(german.severity(), "ERROR");
1456 let english = db_error(&[
1458 (b'C', "0A000"),
1459 (b'M', "cached plan must not change result type"),
1460 ]);
1461 assert!(is_stale(&english));
1462 let other = db_error(&[
1464 (b'C', "0A000"),
1465 (b'M', "nicht unterstützt"),
1466 (b'R', "transformSelectStmt"),
1467 ]);
1468 assert!(!is_stale(&other));
1469 assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
1470 }
1471
1472 #[test]
1473 fn command_tags_give_row_counts() {
1474 assert_eq!(rows_affected(Some("INSERT 0 5")), 5);
1475 assert_eq!(rows_affected(Some("UPDATE 3")), 3);
1476 assert_eq!(rows_affected(Some("SELECT 12")), 12);
1477 assert_eq!(rows_affected(Some("CREATE TABLE")), 0);
1478 assert_eq!(rows_affected(None), 0);
1479 }
1480}