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 writes: Cell<bool>,
55}
56
57impl Drop for Statement {
58 fn drop(&mut self) {
59 let Some(conn) = self.conn.as_ref().and_then(Weak::upgrade) else {
60 return;
61 };
62 if !self.closed.get() {
63 if let Ok(mut st) = conn.state.try_borrow_mut() {
65 if st.broken.is_none() {
66 let _ = protocol::close_statement(&mut st.out, &self.name);
67 st.batch = None;
69 }
70 }
71 }
72 }
73}
74
75#[cold]
78#[inline(never)]
79fn abandoned() -> Error {
80 Error::new(
81 ErrorKind::Db,
82 "a statement of this transaction was given up before its answer came (its future was \
83 dropped, by a timeout say), and it may have run, so the transaction cannot be \
84 committed; this statement was not sent. Drop the transaction (which rolls it back) and \
85 run it again from the start",
86 )
87}
88
89const LEFT_OPEN: &str = "a statement sent through the pool's shared methods (Pool::batch_execute) \
91 left a transaction open on a connection other tasks share, so the connection was closed and \
92 the transaction rolled back, with every statement sent on it since BEGIN, this one included. \
93 Run transactions on a connection of the task's own: pool.get().await?.transaction()";
94
95const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
102 SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";
103
104const NAME_PREFIX: &str = "__giong_";
107
108struct Conn {
110 weak: Weak<Conn>,
111 stream: Stream,
112 state: RefCell<State>,
113 head_since: Cell<Option<giong::time::Instant>>,
116 config: Config,
117 key: Option<(i32, i32)>,
118 shared: Cell<bool>,
122 idle_wakers: RefCell<Vec<Waker>>,
124 requests: Cell<u64>,
127 lease: RefCell<Option<Arc<AtomicBool>>>,
130 retire: Cell<bool>,
134 user_prepared: Cell<bool>,
137 tx: Cell<Tx>,
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143enum Tx {
144 None,
146 Open,
147 Abandoned,
151}
152
153struct State {
154 out: Vec<u8>,
156 writer: Option<Waker>,
157 queue: VecDeque<Rc<Slot>>,
159 broken: Option<Error>,
161 closing: bool,
163 status: u8,
165 cache: HashMap<Rc<str>, Entry>,
166 clock: u64,
167 next_name: u64,
168 server_params: Vec<(String, String)>,
169 batch: Option<OpenBatch>,
172 extra: usize,
174 read_only_prepared: bool,
176 held: Vec<Rc<Slot>>,
180 batch_failed: bool,
182}
183
184struct OpenBatch {
186 start: usize,
188 members: usize,
190}
191
192const BATCH_MAX: usize = 16;
194const SYNC_LEN: usize = 5;
196const READ_ONLY: &str =
210 "SELECT set_config('transaction_read_only', 'on', true), set_config('lock_timeout', '50ms', true)";
211
212const READ_ONLY_NAME: &str = "__giong_read_only";
214
215fn read_only_guard(out: &mut Vec<u8>, prepared: bool) {
217 let parsed = if prepared {
218 Ok(())
219 } else {
220 protocol::parse(out, READ_ONLY_NAME, READ_ONLY)
221 };
222 let encoded = parsed
223 .and_then(|()| {
224 protocol::bind(
225 out,
226 READ_ONLY_NAME,
227 0,
228 |_, _| unreachable!("no parameters"),
229 [].into_iter(),
230 )
231 })
232 .and_then(|()| protocol::execute(out));
233 debug_assert!(encoded.is_ok(), "a constant statement encodes");
234}
235
236enum Entry {
237 Ready { stmt: Rc<Statement>, used: u64 },
238 Preparing(Rc<Slot>),
239}
240
241struct Slot {
243 kind: Kind,
244 shared: bool,
246 close_on_error: bool,
249 in_tx: Option<Weak<Conn>>,
252 batch: Cell<Role>,
255 inner: RefCell<SlotInner>,
256}
257
258#[derive(Clone, Copy, PartialEq, Eq, Debug)]
259enum Role {
260 Alone,
262 Member,
264 Guard,
266 End,
268}
269
270enum Kind {
271 Prepare {
272 sql: Rc<str>,
273 name: Box<str>,
274 cached: bool,
275 },
276 Execute {
277 stmt: Rc<Statement>,
278 },
279 Simple,
280}
281
282#[derive(Default)]
283struct SlotInner {
284 wakers: Vec<Waker>,
285 abandoned: bool,
287 delivered: bool,
289 error: Option<Error>,
290 params: Option<Vec<Type>>,
291 columns: Option<Vec<Column>>,
292 rows: RowsBuilder,
293 tag: Option<String>,
294 bound: bool,
296 status: u8,
298 retry: bool,
301 alone: bool,
305 outcome: Option<Result<Response, Error>>,
306}
307
308enum Response {
309 Statement(Rc<Statement>),
310 Rows(ResultSet, Option<String>),
311 Done(Option<String>),
312}
313
314impl Slot {
315 fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
316 Rc::new(Slot {
317 kind,
318 shared,
319 close_on_error,
320 in_tx,
321 batch: Cell::new(Role::Alone),
322 inner: RefCell::default(),
323 })
324 }
325}
326
327struct Wait {
330 slot: Rc<Slot>,
331}
332
333impl Future for Wait {
334 type Output = Result<Response, Error>;
335
336 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
337 let mut inner = self.slot.inner.borrow_mut();
338 let shared = matches!(self.slot.kind, Kind::Prepare { .. });
339 match &inner.outcome {
340 Some(Ok(Response::Statement(stmt))) if shared => {
341 return Poll::Ready(Ok(Response::Statement(stmt.clone())))
342 }
343 Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
344 Some(_) => {
345 inner.delivered = true;
346 return Poll::Ready(inner.outcome.take().expect("checked"));
347 }
348 None => {}
349 }
350 if !inner.wakers.iter().any(|w| w.will_wake(cx.waker())) {
351 inner.wakers.push(cx.waker().clone());
352 }
353 Poll::Pending
354 }
355}
356
357impl Drop for Wait {
358 fn drop(&mut self) {
359 if matches!(self.slot.kind, Kind::Prepare { .. }) {
360 return;
361 }
362 let known = {
364 let mut inner = self.slot.inner.borrow_mut();
365 inner.abandoned = true;
366 inner.rows = RowsBuilder::default();
367 inner.delivered || inner.outcome.is_some()
368 };
369 if !known && self.slot.in_tx.is_some() {
372 abandon_tx(&self.slot);
373 }
374 }
375}
376
377#[cold]
379#[inline(never)]
380fn abandon_tx(slot: &Slot) {
381 if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
382 if conn.tx.get() == Tx::Open {
383 conn.tx.set(Tx::Abandoned);
384 }
385 }
386}
387
388fn is_stale(db: &DbError) -> bool {
394 match db.code() {
395 "26000" => true,
396 "0A000" => {
397 db.routine() == Some("RevalidateCachedQuery")
398 || db.message().contains("cached plan must not change")
399 }
400 _ => false,
401 }
402}
403
404fn rows_affected(tag: Option<&str>) -> u64 {
407 tag.and_then(|t| t.rsplit(' ').next())
408 .and_then(|n| n.parse().ok())
409 .unwrap_or(0)
410}
411
412impl Client {
413 pub async fn connect(config: &Config) -> Result<Client, Error> {
427 let startup = connect::connect(config).await?;
428 Ok(Self::start(startup, config.clone()))
429 }
430
431 pub(crate) fn start(startup: Startup, config: Config) -> Client {
432 let Startup {
433 stream,
434 buf,
435 params,
436 key,
437 status,
438 } = startup;
439 let conn = Rc::new_cyclic(|weak| Conn {
440 weak: weak.clone(),
441 head_since: Cell::new(None),
442 stream,
443 config,
444 key,
445 shared: Cell::new(false),
446 idle_wakers: RefCell::new(Vec::new()),
447 requests: Cell::new(0),
448 lease: RefCell::new(None),
449 retire: Cell::new(false),
450 user_prepared: Cell::new(false),
451 tx: Cell::new(Tx::None),
452 state: RefCell::new(State {
453 out: Vec::new(),
454 writer: None,
455 queue: VecDeque::new(),
456 extra: 0,
457 read_only_prepared: false,
458 held: Vec::new(),
459 batch_failed: false,
460 broken: None,
461 closing: false,
462 status,
463 cache: HashMap::new(),
464 clock: 0,
465 next_name: 0,
466 server_params: params,
467 batch: None,
468 }),
469 });
470 giong::spawn(read_loop(conn.clone(), buf));
471 giong::spawn(write_loop(conn.clone()));
472 Client { conn }
473 }
474
475 pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
499 let (set, _) = self.run(sql, params, false).await?;
500 Ok(set.into_rows())
501 }
502
503 pub(crate) async fn query_shared(
506 &self,
507 sql: &str,
508 params: &[&dyn ToSql],
509 batch: bool,
510 ) -> Result<Vec<Row>, Error> {
511 let (set, _) = self.run(sql, params, batch).await?;
512 Ok(set.into_rows())
513 }
514
515 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
521 one_row(self.query(sql, params).await?)
522 }
523
524 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
530 at_most_one_row(self.query(sql, params).await?)
531 }
532}
533
534pub(crate) fn one_row(mut rows: Vec<Row>) -> Result<Row, Error> {
536 match rows.len() {
537 1 => Ok(rows.pop().expect("one row")),
538 n => Err(Error::new(
539 ErrorKind::RowCount,
540 format!(
541 "the statement returned {n} rows where exactly one was expected; use \
542 query_opt for zero or one, or query for any number"
543 ),
544 )),
545 }
546}
547
548pub(crate) fn at_most_one_row(mut rows: Vec<Row>) -> Result<Option<Row>, Error> {
550 match rows.len() {
551 0 | 1 => Ok(rows.pop()),
552 n => Err(Error::new(
553 ErrorKind::RowCount,
554 format!(
555 "the statement returned {n} rows where at most one was expected; add a \
556 LIMIT, or use query"
557 ),
558 )),
559 }
560}
561
562impl Client {
563 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
568 let (_, tag) = self.run(sql, params, false).await?;
569 Ok(rows_affected(tag.as_deref()))
570 }
571
572 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
583 let slot = self
584 .conn
585 .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
586 Wait { slot }.await.map(|_| ())
587 }
588
589 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
607 let tx = Transaction {
610 client: self,
611 done: false,
612 };
613 tx.client.conn.tx.set(Tx::Open);
614 tx.client.batch_execute("BEGIN").await?;
615 Ok(tx)
616 }
617
618 pub fn cancel_token(&self) -> CancelToken {
625 CancelToken {
626 config: self.conn.config.without_password(),
627 key: self.conn.key,
628 lease: self.conn.lease.borrow().clone(),
629 }
630 }
631
632 pub fn parameter(&self, name: &str) -> Option<String> {
635 let st = self.conn.state.borrow();
636 st.server_params
637 .iter()
638 .find(|(n, _)| n == name)
639 .map(|(_, v)| v.clone())
640 }
641
642 pub fn is_closed(&self) -> bool {
645 self.conn.state.borrow().broken.is_some()
646 }
647
648 pub fn in_flight(&self) -> usize {
650 let st = self.conn.state.borrow();
651 st.queue.len() - st.extra + st.held.len()
652 }
653
654 pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
657 self.conn
658 .head_since
659 .get()
660 .map_or(std::time::Duration::ZERO, |t| {
661 now.saturating_duration_since(t)
662 })
663 }
664
665 pub(crate) fn in_transaction(&self) -> bool {
667 self.conn.state.borrow().status != b'I'
668 }
669
670 pub(crate) fn set_shared(&self, shared: bool) {
675 self.conn.shared.set(shared);
676 }
677
678 pub(crate) fn wake_when_idle(&self, waker: &Waker) {
680 let mut wakers = self.conn.idle_wakers.borrow_mut();
681 if !wakers.iter().any(|w| w.will_wake(waker)) {
682 wakers.push(waker.clone());
683 }
684 }
685
686 pub(crate) fn requests(&self) -> u64 {
688 self.conn.requests.get()
689 }
690
691 pub(crate) fn begin_lease(&self) {
694 *self.conn.lease.borrow_mut() = Some(Arc::new(AtomicBool::new(true)));
695 }
696
697 pub(crate) fn end_lease(&self) {
699 if let Some(lease) = self.conn.lease.borrow_mut().take() {
700 lease.store(false, Ordering::Release);
701 }
702 }
703
704 pub(crate) fn should_retire(&self) -> bool {
707 self.conn.retire.get()
708 }
709
710 pub(crate) fn reset_session(&self) {
715 let deallocate = self.conn.user_prepared.replace(false);
716 let sql = if deallocate {
717 let mut st = self.conn.state.borrow_mut();
718 st.cache.clear();
719 st.read_only_prepared = false;
720 format!("{RESET}; DEALLOCATE ALL")
721 } else {
722 RESET.to_owned()
723 };
724 if let Ok(slot) = self
725 .conn
726 .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
727 {
728 slot.inner.borrow_mut().abandoned = true;
729 }
730 }
731
732 pub(crate) fn send_and_forget(&self, sql: &str) {
734 if let Ok(slot) = self
735 .conn
736 .enqueue(Kind::Simple, |out| protocol::query(out, sql))
737 {
738 slot.inner.borrow_mut().abandoned = true;
739 }
740 }
741
742 async fn run(
743 &self,
744 sql: &str,
745 params: &[&dyn ToSql],
746 batch: bool,
747 ) -> Result<(ResultSet, Option<String>), Error> {
748 if params.len() > MAX_PARAMS {
749 return Err(Error::conversion(format!(
750 "{} parameters were given; a statement can have at most {MAX_PARAMS}",
751 params.len()
752 )));
753 }
754 let mut retried = false;
759 let mut alone = !batch;
761 loop {
762 let slot = self.send(sql, params, !alone).await?;
763 let result = Wait { slot: slot.clone() }.await;
764 if result.is_err() {
765 let (skipped, stale) = {
766 let inner = slot.inner.borrow();
767 (inner.alone, inner.retry)
768 };
769 if skipped && !alone {
770 alone = true;
771 continue;
772 }
773 if stale && !retried {
774 retried = true;
775 continue;
776 }
777 }
778 return match result? {
779 Response::Rows(set, tag) => Ok((set, tag)),
780 _ => unreachable!("an execute slot ends with rows"),
781 };
782 }
783 }
784
785 async fn send(&self, sql: &str, params: &[&dyn ToSql], batch: bool) -> Result<Rc<Slot>, Error> {
787 let stmt = self.conn.statement(sql).await?;
788 if stmt.params.len() != params.len() {
789 return Err(Error::conversion(format!(
790 "the statement has {} parameters but {} values were given",
791 stmt.params.len(),
792 params.len()
793 )));
794 }
795 let cached = stmt.conn.is_none();
796 let encode = |out: &mut Vec<u8>| {
797 protocol::bind(
798 out,
799 &stmt.name,
800 params.len(),
801 |i, out| {
802 params[i].to_sql(stmt.params[i], out).map_err(|e| {
803 e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
804 })
805 },
806 stmt.columns.iter().map(|c| c.ty().binary_result()),
807 )?;
808 protocol::execute(out)
809 };
810 let kind = Kind::Execute { stmt: stmt.clone() };
811 let slot = if batch
812 && cached
813 && !stmt.writes.get()
814 && self.conn.shared.get()
815 && self.conn.tx.get() == Tx::None
816 {
817 self.conn.enqueue_batched(kind, encode)?
818 } else {
819 self.conn.enqueue(kind, |out| {
820 encode(out)?;
821 protocol::sync(out);
822 Ok(())
823 })?
824 };
825 if !cached {
826 let close = self.conn.enqueue(Kind::Simple, |out| {
829 protocol::close_statement(out, &stmt.name)?;
830 protocol::sync(out);
831 Ok(())
832 });
833 if let Ok(close) = close {
834 close.inner.borrow_mut().abandoned = true;
835 stmt.closed.set(true);
836 }
837 }
838 Ok(slot)
839 }
840}
841
842impl Drop for Client {
843 fn drop(&mut self) {
844 let mut st = self.conn.state.borrow_mut();
845 st.closing = true;
846 if st.broken.is_none() {
847 protocol::terminate(&mut st.out);
848 st.batch = None;
849 }
850 if let Some(w) = st.writer.take() {
851 w.wake();
852 }
853 }
854}
855
856impl std::fmt::Debug for Client {
857 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
858 f.debug_struct("Client")
859 .field("server", &self.conn.config.target())
860 .field("in_flight", &self.in_flight())
861 .field("closed", &self.is_closed())
862 .finish()
863 }
864}
865
866impl Conn {
867 fn enqueue(
870 &self,
871 kind: Kind,
872 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
873 ) -> Result<Rc<Slot>, Error> {
874 self.enqueue_with(kind, false, encode)
875 }
876
877 #[cold]
880 #[inline(never)]
881 fn in_tx(&self) -> Result<Weak<Conn>, Error> {
882 match self.tx.get() {
883 Tx::Abandoned => Err(abandoned()),
884 _ => Ok(self.weak.clone()),
885 }
886 }
887
888 fn enqueue_with(
889 &self,
890 kind: Kind,
891 close_on_error: bool,
892 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
893 ) -> Result<Rc<Slot>, Error> {
894 let mut st = self.state.borrow_mut();
895 if let Some(e) = &st.broken {
896 return Err(e.clone());
897 }
898 let in_tx = if self.tx.get() == Tx::None {
899 None
900 } else {
901 Some(self.in_tx()?)
902 };
903 st.batch = None;
905 let start = st.out.len();
906 if let Err(e) = encode(&mut st.out) {
907 st.out.truncate(start);
908 return Err(e);
909 }
910 let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
911 self.requests.set(self.requests.get() + 1);
912 if st.queue.is_empty() {
913 self.head_since.set(Some(giong::time::Instant::now()));
914 }
915 st.queue.push_back(slot.clone());
916 if let Some(w) = st.writer.take() {
917 w.wake();
918 }
919 Ok(slot)
920 }
921
922 #[inline(never)]
929 fn enqueue_batched(
930 &self,
931 kind: Kind,
932 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
933 ) -> Result<Rc<Slot>, Error> {
934 let mut st = self.state.borrow_mut();
935 if let Some(e) = &st.broken {
936 return Err(e.clone());
937 }
938 let joins = st.batch.as_ref().is_some_and(|b| b.members < BATCH_MAX);
939 if !joins {
940 let start = st.out.len();
941 if let Err(e) = encode(&mut st.out) {
942 st.out.truncate(start);
943 return Err(e);
944 }
945 protocol::sync(&mut st.out);
946 st.batch = Some(OpenBatch { start, members: 1 });
947 return Ok(self.queue_slot(&mut st, Slot::new(kind, true, false, None)));
948 }
949 let mut messages = Vec::new();
952 encode(&mut messages)?;
953 let sync_at = st.out.len() - SYNC_LEN;
954 st.out.truncate(sync_at);
955 let b = st.batch.as_mut().expect("joins");
956 if b.members == 1 {
957 let start = b.start;
960 let mut guard = Vec::new();
961 read_only_guard(&mut guard, st.read_only_prepared);
962 st.read_only_prepared = true;
963 st.out.splice(start..start, guard);
964 let first = st.queue.pop_back().expect("the batch's first statement");
965 first.batch.set(Role::Member);
966 let guard = Slot::new(Kind::Simple, true, false, None);
967 guard.batch.set(Role::Guard);
968 st.extra += 2; guard.inner.borrow_mut().abandoned = true;
970 st.queue.push_back(guard);
971 st.queue.push_back(first);
972 } else {
973 let end = st.queue.pop_back().expect("the batch's end");
974 debug_assert_eq!(end.batch.get(), Role::End);
975 }
976 st.batch.as_mut().expect("joins").members += 1;
977 st.out.extend_from_slice(&messages);
978 protocol::sync(&mut st.out);
979 let slot = Slot::new(kind, true, false, None);
980 slot.batch.set(Role::Member);
981 st.queue.push_back(slot.clone());
982 let end = Slot::new(Kind::Simple, true, false, None);
983 end.batch.set(Role::End);
984 end.inner.borrow_mut().abandoned = true;
985 self.queue_slot(&mut st, end);
986 Ok(slot)
987 }
988
989 fn queue_slot(&self, st: &mut State, slot: Rc<Slot>) -> Rc<Slot> {
991 self.requests.set(self.requests.get() + 1);
992 if st.queue.is_empty() {
993 self.head_since.set(Some(giong::time::Instant::now()));
994 }
995 st.queue.push_back(slot.clone());
996 if let Some(w) = st.writer.take() {
997 w.wake();
998 }
999 slot
1000 }
1001
1002 fn finish_member(&self, slot: &Rc<Slot>) {
1007 slot.inner.borrow_mut().status = b'I';
1010 let mut st = self.state.borrow_mut();
1011 st.queue.pop_front();
1012 if slot.batch.get() == Role::Guard {
1013 st.extra -= 1;
1014 } else {
1015 st.held.push(slot.clone());
1016 }
1017 self.head_since
1018 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1019 }
1020
1021 async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1024 let mut again = true;
1025 loop {
1026 let pending = {
1027 let mut st = self.state.borrow_mut();
1028 st.clock += 1;
1029 let now = st.clock;
1030 match st.cache.get_mut(sql) {
1031 Some(Entry::Ready { stmt, used }) => {
1032 *used = now;
1033 return Ok(stmt.clone());
1034 }
1035 Some(Entry::Preparing(slot)) => Some(slot.clone()),
1036 None => None,
1037 }
1038 };
1039 let Some(slot) = pending else {
1040 return self.prepare(sql).await;
1041 };
1042 match (Wait { slot }).await {
1043 Ok(Response::Statement(stmt)) => return Ok(stmt),
1044 Ok(_) => unreachable!("a prepare slot ends with a statement"),
1045 Err(e) if again && e.server_code() == Some("42P05") => again = false,
1048 Err(e) => return Err(e),
1049 }
1050 }
1051 }
1052
1053 async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1054 match self.prepare_once(sql).await {
1055 Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
1059 result => result,
1060 }
1061 }
1062
1063 async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1064 let cached = self.config.statement_cache > 0;
1065 let (name, key) = {
1066 let mut st = self.state.borrow_mut();
1067 st.next_name += 1;
1068 (
1069 format!("{NAME_PREFIX}{}", st.next_name),
1070 Rc::<str>::from(sql),
1071 )
1072 };
1073 let slot = self.enqueue(
1074 Kind::Prepare {
1075 sql: key.clone(),
1076 name: name.as_str().into(),
1077 cached,
1078 },
1079 |out| {
1080 protocol::parse(out, &name, sql)?;
1081 protocol::describe_statement(out, &name)?;
1082 protocol::sync(out);
1083 Ok(())
1084 },
1085 )?;
1086 if cached {
1087 self.state
1088 .borrow_mut()
1089 .cache
1090 .insert(key, Entry::Preparing(slot.clone()));
1091 }
1092 match (Wait { slot }).await? {
1093 Response::Statement(stmt) => Ok(stmt),
1094 _ => unreachable!("a prepare slot ends with a statement"),
1095 }
1096 }
1097
1098 fn fail(&self, err: Error) {
1101 let slots = {
1102 let mut st = self.state.borrow_mut();
1103 if st.broken.is_none() {
1104 st.broken = Some(err.clone());
1105 }
1106 st.cache.clear();
1107 st.out.clear();
1108 self.head_since.set(None);
1109 if let Some(w) = st.writer.take() {
1110 w.wake();
1111 }
1112 st.extra = 0;
1113 st.read_only_prepared = false;
1114 st.batch_failed = false;
1115 let mut slots = std::mem::take(&mut st.held);
1116 slots.extend(std::mem::take(&mut st.queue));
1117 slots
1118 };
1119 for slot in slots {
1120 let mut inner = slot.inner.borrow_mut();
1121 let e = inner.error.take().unwrap_or_else(|| err.clone());
1122 inner.outcome = Some(Err(e));
1123 for w in inner.wakers.drain(..) {
1124 w.wake();
1125 }
1126 }
1127 self.wake_idle();
1128 self.stream.shutdown(Shutdown::Both);
1129 }
1130
1131 fn wake_idle(&self) {
1132 let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
1133 for w in wakers {
1134 w.wake();
1135 }
1136 }
1137
1138 fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
1140 let limit = self.config.max_result_size.max(1 << 20);
1141 while let Some((tag, len)) = buf.peek()? {
1142 if len > limit {
1143 match tag {
1144 b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
1147 b'N' | b'A' | b'd' => {}
1151 b'E' => {
1154 let slot = self.front()?;
1155 let mut inner = slot.inner.borrow_mut();
1156 if inner.error.is_none() {
1157 inner.error = Some(Error::new(
1158 ErrorKind::TooLarge,
1159 format!(
1160 "the server's error for this statement was a {len}-byte \
1161 message, more than max_result_size allows, so it was \
1162 thrown away; raise Config::max_result_size to read it"
1163 ),
1164 ));
1165 }
1166 }
1167 _ => {
1168 return Err(Error::new(
1169 ErrorKind::Protocol,
1170 format!(
1171 "the server sent a {:?} message of {len} bytes, more than \
1172 max_result_size allows, so the connection was closed; raise \
1173 Config::max_result_size if the server's messages are this large",
1174 tag as char
1175 ),
1176 ))
1177 }
1178 }
1179 buf.skip(len);
1180 continue;
1181 }
1182 let Some(body) = buf.body(len) else {
1183 return Ok(());
1184 };
1185 self.handle(tag, buf.bytes(body))?;
1186 buf.consume(len);
1187 }
1188 Ok(())
1189 }
1190
1191 fn front(&self) -> Result<Rc<Slot>, Error> {
1192 self.state.borrow().queue.front().cloned().ok_or_else(|| {
1193 Error::protocol("the server sent a reply to a request that was never made")
1194 })
1195 }
1196
1197 fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
1198 let msg = parse_backend(tag, body)?;
1199 match msg {
1200 Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
1201 Backend::ParameterStatus { name, value } => {
1202 if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
1203 return Err(Error::closed(format!(
1204 "the session's client_encoding was changed to {value}; giong-postgres \
1205 reads and writes UTF-8 only, so the connection was closed"
1206 )));
1207 }
1208 let mut st = self.state.borrow_mut();
1209 match st.server_params.iter_mut().find(|(n, _)| n == name) {
1210 Some(entry) => entry.1 = value.to_owned(),
1211 None => st.server_params.push((name.to_owned(), value.to_owned())),
1212 }
1213 return Ok(());
1214 }
1215 Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
1216 let db = DbError::parse(fields)?;
1219 return Err(Error::with_db(
1220 ErrorKind::Closed,
1221 "the server closed the connection",
1222 db,
1223 ));
1224 }
1225 _ => {}
1226 }
1227 let slot = loop {
1228 let slot = self.front()?;
1229 if slot.batch.get() != Role::Alone
1230 && matches!(
1231 msg,
1232 Backend::CommandComplete(_)
1233 | Backend::ErrorResponse(_)
1234 | Backend::ReadyForQuery(_)
1235 )
1236 {
1237 if self.handle_batched(slot, &msg)? {
1238 continue;
1241 }
1242 return Ok(());
1243 }
1244 break slot;
1245 };
1246 let mut inner = slot.inner.borrow_mut();
1247 match msg {
1248 Backend::BindComplete => inner.bound = true,
1249 Backend::ParseComplete
1250 | Backend::CloseComplete
1251 | Backend::NoData
1252 | Backend::PortalSuspended
1253 | Backend::EmptyQueryResponse => {}
1254 Backend::ParameterDescription(types) => inner.params = Some(types),
1255 Backend::RowDescription(fields) => {
1256 if matches!(slot.kind, Kind::Prepare { .. }) {
1257 inner.columns = Some(
1258 fields
1259 .iter()
1260 .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
1261 .collect(),
1262 );
1263 }
1264 }
1265 Backend::DataRow(body) => match &slot.kind {
1266 Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
1267 let limit = self.config.max_result_size;
1268 inner.rows.push(body, stmt.columns.len(), limit)?;
1269 }
1270 _ => {}
1271 },
1272 Backend::CommandComplete(tag) => {
1273 if tag == "PREPARE" {
1274 self.user_prepared.set(true);
1275 }
1276 inner.tag = Some(tag.to_owned());
1277 }
1278 Backend::ErrorResponse(fields) => {
1279 if inner.error.is_none() {
1280 inner.error = Some(self.db_error(fields, true)?);
1281 }
1282 }
1283 Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
1284 if inner.error.is_none() {
1285 inner.error = Some(Error::conversion(
1286 "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
1287 was thrown away",
1288 ));
1289 }
1290 }
1291 Backend::CopyInResponse | Backend::CopyBothResponse => {
1292 return Err(Error::closed(
1293 "the statement started COPY FROM STDIN or replication, which giong-postgres \
1294 does not support yet; the connection was closed",
1295 ));
1296 }
1297 Backend::ReadyForQuery(status) => {
1298 let left_open = slot.shared && status != b'I';
1302 if left_open {
1303 inner.error = Some(Error::closed(LEFT_OPEN));
1304 }
1305 let reset_failed = match &inner.error {
1306 Some(e) if slot.close_on_error => Some(Error::closed(format!(
1307 "resetting the session of a connection that went back to the pool \
1308 failed, so it was closed rather than reused: {e}"
1309 ))),
1310 _ => None,
1311 };
1312 inner.status = status;
1313 drop(inner);
1314 let idle = {
1315 let mut st = self.state.borrow_mut();
1316 st.status = status;
1317 st.queue.pop_front();
1318 self.head_since
1319 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1320 st.queue.is_empty()
1321 };
1322 self.complete(&slot);
1323 if left_open {
1324 return Err(Error::closed(LEFT_OPEN));
1326 }
1327 if let Some(e) = reset_failed {
1328 return Err(e);
1329 }
1330 if idle {
1331 self.wake_idle();
1332 }
1333 }
1334 other => {
1335 return Err(Error::protocol(format!(
1336 "the server sent an unexpected {:?} message ({other:?})",
1337 tag as char
1338 )))
1339 }
1340 }
1341 Ok(())
1342 }
1343
1344 fn db_error(&self, fields: &[u8], may_retire: bool) -> Result<Error, Error> {
1346 let db = DbError::parse(fields)?;
1347 if may_retire && db.code() == "25006" && self.on_standby() {
1348 self.retire.set(true);
1349 }
1350 let note = (db.code() == "57014" && db.message().contains("statement timeout")).then(
1353 || match self.config.statement_timeout {
1354 Some(limit) => format!(
1355 "the statement ran longer than the statement timeout ({limit:?}; \
1356 Config::statement_timeout)"
1357 ),
1358 None => "the statement ran longer than the server's statement_timeout".to_owned(),
1359 },
1360 );
1361 Ok(Error::from_db(db, note))
1362 }
1363
1364 #[cold]
1368 #[inline(never)]
1369 fn handle_batched(&self, slot: Rc<Slot>, msg: &Backend<'_>) -> Result<bool, Error> {
1372 let mut inner = slot.inner.borrow_mut();
1373 match *msg {
1374 Backend::CommandComplete(command) => {
1375 inner.tag = Some(command.to_owned());
1376 }
1377 Backend::ErrorResponse(fields) => {
1378 let error = self.db_error(fields, false)?;
1380 self.state.borrow_mut().batch_failed = true;
1381 match slot.batch.get() {
1382 Role::End => return Ok(false),
1385 Role::Guard if error.server_code() == Some("26000") => {
1389 self.state.borrow_mut().read_only_prepared = false;
1390 }
1391 _ => {}
1392 }
1393 if matches!(error.server_code(), Some("55P03" | "40P01" | "40001"))
1394 && slot.batch.get() == Role::Member
1395 {
1396 if let Kind::Execute { .. } = &slot.kind {
1401 inner.alone = true;
1402 }
1403 }
1404 if error.server_code() == Some("25006") {
1405 if let Kind::Execute { stmt } = &slot.kind {
1407 stmt.writes.set(true);
1408 inner.alone = true;
1409 }
1410 }
1411 inner.error = Some(error);
1412 }
1413 Backend::ReadyForQuery(status) if slot.batch.get() == Role::End => {
1414 inner.status = status;
1417 drop(inner);
1418 let (idle, held, failed) = {
1419 let mut st = self.state.borrow_mut();
1420 st.status = status;
1421 st.queue.pop_front();
1422 st.extra -= 1;
1423 self.head_since
1424 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1425 let failed = std::mem::take(&mut st.batch_failed);
1426 (st.queue.is_empty(), std::mem::take(&mut st.held), failed)
1427 };
1428 for member in &held {
1429 if failed {
1430 let mut inner = member.inner.borrow_mut();
1431 if inner.error.is_none() {
1432 inner.error = Some(Error::new(
1435 ErrorKind::Closed,
1436 "another statement of this one's batch failed, so the batch \
1437 was rolled back",
1438 ));
1439 inner.alone = matches!(member.kind, Kind::Execute { .. });
1440 }
1441 }
1442 self.complete(member);
1443 }
1444 self.complete(&slot);
1445 if idle {
1446 self.wake_idle();
1447 }
1448 return Ok(false);
1449 }
1450 Backend::ReadyForQuery(_) => {
1451 inner.error = Some(Error::new(
1454 ErrorKind::Closed,
1455 "a statement before this one in its batch failed, so the server skipped it",
1456 ));
1457 inner.alone = matches!(slot.kind, Kind::Execute { .. });
1458 drop(inner);
1459 self.finish_member(&slot);
1460 return Ok(true);
1461 }
1462 _ => unreachable!("only these three come here"),
1463 }
1464 drop(inner);
1465 self.finish_member(&slot);
1466 Ok(false)
1467 }
1468
1469 fn complete(&self, slot: &Rc<Slot>) {
1471 let mut inner = slot.inner.borrow_mut();
1472 let error = inner.error.take();
1473 let outcome = match &slot.kind {
1474 Kind::Prepare { sql, name, cached } => {
1475 let result = match error {
1476 Some(e) => Err(e),
1477 None => match inner.params.take() {
1478 Some(params) => Ok(Rc::new(Statement {
1479 sql: sql.clone(),
1480 name: name.clone(),
1481 params,
1482 columns: inner.columns.take().unwrap_or_default().into(),
1483 conn: (!*cached).then(|| self.weak.clone()),
1484 closed: Cell::new(false),
1485 writes: Cell::new(false),
1486 })),
1487 None => Err(Error::protocol("the server did not describe the statement")),
1488 },
1489 };
1490 if *cached {
1491 self.settle_cache(sql, slot, &result);
1492 }
1493 result.map(Response::Statement)
1494 }
1495 Kind::Execute { stmt } => match error {
1496 Some(e) => {
1497 let stale = self.forget_if_stale(stmt, &e);
1498 inner.retry = stale && !inner.bound && inner.status == b'I';
1501 Err(e)
1502 }
1503 None if inner.rows.overflow => Err(Error::new(
1504 ErrorKind::TooLarge,
1505 format!(
1506 "the result is larger than max_result_size ({} bytes); add a LIMIT or \
1507 select fewer columns, or raise Config::max_result_size",
1508 self.config.max_result_size
1509 ),
1510 )),
1511 None => {
1512 let rows = std::mem::take(&mut inner.rows);
1513 Ok(Response::Rows(
1514 rows.finish(stmt.columns.clone()),
1515 inner.tag.take(),
1516 ))
1517 }
1518 },
1519 Kind::Simple => match error {
1520 Some(e) => Err(e),
1521 None => Ok(Response::Done(inner.tag.take())),
1522 },
1523 };
1524 inner.outcome = Some(outcome);
1525 for w in inner.wakers.drain(..) {
1526 w.wake();
1527 }
1528 }
1529
1530 fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
1535 if !e.db().is_some_and(is_stale) {
1536 return false;
1537 }
1538 let mut st = self.state.borrow_mut();
1539 if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
1540 {
1541 st.cache.remove(&stmt.sql);
1542 }
1543 true
1544 }
1545
1546 fn on_standby(&self) -> bool {
1549 let st = self.state.borrow();
1550 st.server_params
1551 .iter()
1552 .find(|(n, _)| n == "in_hot_standby")
1553 .map_or(true, |(_, v)| v != "off")
1554 }
1555
1556 fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
1559 let mut st = self.state.borrow_mut();
1560 let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
1561 if !ours {
1562 return;
1563 }
1564 let Ok(stmt) = result else {
1565 st.cache.remove(sql);
1566 return;
1567 };
1568 st.clock += 1;
1569 let used = st.clock;
1570 st.cache.insert(
1571 sql.clone(),
1572 Entry::Ready {
1573 stmt: stmt.clone(),
1574 used,
1575 },
1576 );
1577 while st.cache.len() > self.config.statement_cache {
1578 let victim = st
1580 .cache
1581 .iter()
1582 .filter_map(|(k, e)| match e {
1583 Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
1584 Some((*used, k.clone()))
1585 }
1586 _ => None,
1587 })
1588 .min();
1589 let Some((_, key)) = victim else { break };
1590 if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
1591 let _ = protocol::close_statement(&mut st.out, &stmt.name);
1594 st.batch = None;
1596 }
1597 }
1598 }
1599}
1600
1601async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
1602 let err = loop {
1603 if let Err(e) = conn.process(&mut buf) {
1604 break e;
1605 }
1606 match conn.stream.read_into(&mut buf).await {
1607 Ok(0) => {
1608 let closing = conn.state.borrow().closing;
1609 break Error::closed(if closing {
1610 "the connection was closed"
1611 } else {
1612 "the server closed the connection"
1613 });
1614 }
1615 Ok(_) => {}
1616 Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
1617 }
1618 };
1619 conn.fail(err);
1620}
1621
1622async fn write_loop(conn: Rc<Conn>) {
1623 let mut spare = Vec::new();
1624 loop {
1625 let next = poll_fn(|cx| {
1626 let mut st = conn.state.borrow_mut();
1627 if st.broken.is_some() {
1628 return Poll::Ready(None);
1629 }
1630 if !st.out.is_empty() {
1631 st.batch = None;
1633 return Poll::Ready(Some(std::mem::replace(
1634 &mut st.out,
1635 std::mem::take(&mut spare),
1636 )));
1637 }
1638 if st.closing {
1639 return Poll::Ready(None);
1640 }
1641 st.writer = Some(cx.waker().clone());
1642 Poll::Pending
1643 })
1644 .await;
1645 let Some(data) = next else { break };
1646 let (written, mut data) = conn.stream.write_all(data).await;
1647 if let Err(e) = written {
1648 conn.fail(Error::io(
1649 ErrorKind::Closed,
1650 "writing to the server failed",
1651 e,
1652 ));
1653 return;
1654 }
1655 data.clear();
1656 spare = data;
1657 }
1658 if conn.state.borrow().closing {
1659 conn.stream.shutdown(Shutdown::Write);
1660 }
1661}
1662
1663pub struct Transaction<'a> {
1679 client: &'a mut Client,
1680 done: bool,
1681}
1682
1683impl Transaction<'_> {
1684 pub async fn commit(mut self) -> Result<(), Error> {
1695 if self.client.conn.tx.get() == Tx::Abandoned {
1696 return Err(abandoned());
1698 }
1699 self.end();
1700 let slot = self
1701 .client
1702 .conn
1703 .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
1704 match (Wait { slot }).await? {
1705 Response::Done(Some(tag)) if tag == "ROLLBACK" => Err(Error::with_sqlstate(
1706 "25P02",
1707 "the transaction was rolled back instead of committed, because a statement in \
1708 it failed earlier",
1709 )),
1710 _ => Ok(()),
1711 }
1712 }
1713
1714 pub async fn rollback(mut self) -> Result<(), Error> {
1719 self.end();
1720 self.client.batch_execute("ROLLBACK").await
1721 }
1722
1723 fn end(&mut self) {
1725 self.done = true;
1726 self.client.conn.tx.set(Tx::None);
1727 }
1728}
1729
1730impl Deref for Transaction<'_> {
1731 type Target = Client;
1732
1733 fn deref(&self) -> &Client {
1734 self.client
1735 }
1736}
1737
1738impl Drop for Transaction<'_> {
1739 fn drop(&mut self) {
1740 if !self.done {
1741 self.end();
1742 self.client.send_and_forget("ROLLBACK");
1743 }
1744 }
1745}
1746
1747impl std::fmt::Debug for Transaction<'_> {
1748 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1749 f.debug_struct("Transaction")
1750 .field("client", &self.client)
1751 .finish()
1752 }
1753}
1754
1755#[derive(Clone)]
1762pub struct CancelToken {
1763 config: Config,
1766 key: Option<(i32, i32)>,
1767 lease: Option<Arc<AtomicBool>>,
1770}
1771
1772impl CancelToken {
1773 pub async fn cancel(&self) -> Result<(), Error> {
1783 if self
1784 .lease
1785 .as_ref()
1786 .is_some_and(|lease| !lease.load(Ordering::Acquire))
1787 {
1788 return Err(Error::closed(
1789 "the connection this cancel token was taken from has gone back to its pool, \
1790 where other tasks use it, so nothing was sent; take a new token from the next \
1791 connection",
1792 ));
1793 }
1794 let key = self.key.ok_or_else(|| {
1795 Error::new(
1796 ErrorKind::Connect,
1797 "the server gave this connection no cancel key (a connection pooler may be in \
1798 between), so it cannot be cancelled",
1799 )
1800 })?;
1801 connect::cancel(&self.config, key).await
1802 }
1803}
1804
1805impl std::fmt::Debug for CancelToken {
1806 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1807 f.debug_struct("CancelToken")
1808 .field("server", &self.config.target())
1809 .finish_non_exhaustive()
1810 }
1811}
1812
1813#[cfg(test)]
1814mod tests {
1815 use super::{is_stale, rows_affected};
1816 use crate::error::DbError;
1817
1818 fn db_error(fields: &[(u8, &str)]) -> DbError {
1819 let mut body = Vec::new();
1820 for (field, value) in fields {
1821 body.push(*field);
1822 body.extend_from_slice(value.as_bytes());
1823 body.push(0);
1824 }
1825 body.push(0);
1826 DbError::parse(&body).unwrap()
1827 }
1828
1829 #[test]
1830 fn a_stale_plan_is_recognised_in_any_language() {
1831 let german = db_error(&[
1832 (b'S', "FEHLER"),
1833 (b'V', "ERROR"),
1834 (b'C', "0A000"),
1835 (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
1836 (b'R', "RevalidateCachedQuery"),
1837 ]);
1838 assert!(is_stale(&german));
1839 assert_eq!(german.severity(), "ERROR");
1840 let english = db_error(&[
1842 (b'C', "0A000"),
1843 (b'M', "cached plan must not change result type"),
1844 ]);
1845 assert!(is_stale(&english));
1846 let other = db_error(&[
1848 (b'C', "0A000"),
1849 (b'M', "nicht unterstützt"),
1850 (b'R', "transformSelectStmt"),
1851 ]);
1852 assert!(!is_stale(&other));
1853 assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
1854 }
1855
1856 #[test]
1857 fn command_tags_give_row_counts() {
1858 assert_eq!(rows_affected(Some("INSERT 0 5")), 5);
1859 assert_eq!(rows_affected(Some("UPDATE 3")), 3);
1860 assert_eq!(rows_affected(Some("SELECT 12")), 12);
1861 assert_eq!(rows_affected(Some("CREATE TABLE")), 0);
1862 assert_eq!(rows_affected(None), 0);
1863 }
1864}