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::{AtomicU32, 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<Lease>>>,
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)]
285struct Wakers {
286 first: Option<Waker>,
287 more: Vec<Waker>,
288}
289
290impl Wakers {
291 fn register(&mut self, waker: &Waker) {
293 match &self.first {
294 None => self.first = Some(waker.clone()),
295 Some(w) if w.will_wake(waker) => {}
296 Some(_) => {
297 if !self.more.iter().any(|w| w.will_wake(waker)) {
298 self.more.push(waker.clone());
299 }
300 }
301 }
302 }
303
304 fn wake_all(&mut self) {
305 if let Some(w) = self.first.take() {
306 w.wake();
307 }
308 for w in self.more.drain(..) {
309 w.wake();
310 }
311 }
312}
313
314#[derive(Default)]
315struct SlotInner {
316 wakers: Wakers,
317 abandoned: bool,
319 delivered: bool,
321 error: Option<Error>,
322 params: Option<Vec<Type>>,
323 columns: Option<Vec<Column>>,
324 rows: RowsBuilder,
325 tag: Option<Tag>,
326 bound: bool,
328 status: u8,
330 retry: bool,
333 alone: bool,
337 outcome: Option<Result<Response, Error>>,
338}
339
340enum Response {
341 Statement(Rc<Statement>),
342 Rows(ResultSet, Option<Tag>),
343 Done(Option<Tag>),
344}
345
346impl Slot {
347 fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
348 Rc::new(Slot {
349 kind,
350 shared,
351 close_on_error,
352 in_tx,
353 batch: Cell::new(Role::Alone),
354 inner: RefCell::default(),
355 })
356 }
357}
358
359struct Wait {
362 slot: Rc<Slot>,
363}
364
365impl Future for Wait {
366 type Output = Result<Response, Error>;
367
368 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
369 let mut inner = self.slot.inner.borrow_mut();
370 let shared = matches!(self.slot.kind, Kind::Prepare { .. });
371 match &inner.outcome {
372 Some(Ok(Response::Statement(stmt))) if shared => {
373 return Poll::Ready(Ok(Response::Statement(stmt.clone())))
374 }
375 Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
376 Some(_) => {
377 inner.delivered = true;
378 return Poll::Ready(inner.outcome.take().expect("checked"));
379 }
380 None => {}
381 }
382 inner.wakers.register(cx.waker());
383 Poll::Pending
384 }
385}
386
387impl Drop for Wait {
388 fn drop(&mut self) {
389 if matches!(self.slot.kind, Kind::Prepare { .. }) {
390 return;
391 }
392 let known = {
394 let mut inner = self.slot.inner.borrow_mut();
395 inner.abandoned = true;
396 inner.rows = RowsBuilder::default();
397 inner.delivered || inner.outcome.is_some()
398 };
399 if !known && self.slot.in_tx.is_some() {
402 abandon_tx(&self.slot);
403 }
404 }
405}
406
407#[cold]
409#[inline(never)]
410fn abandon_tx(slot: &Slot) {
411 if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
412 if conn.tx.get() == Tx::Open {
413 conn.tx.set(Tx::Abandoned);
414 }
415 }
416}
417
418fn is_stale(db: &DbError) -> bool {
424 match db.code() {
425 "26000" => true,
426 "0A000" => {
427 db.routine() == Some("RevalidateCachedQuery")
428 || db.message().contains("cached plan must not change")
429 }
430 _ => false,
431 }
432}
433
434#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
437struct Tag {
438 rows: u64,
441 rollback: bool,
443}
444
445impl Tag {
446 fn of(tag: &str) -> Self {
447 Self {
448 rows: tag
449 .rsplit(' ')
450 .next()
451 .and_then(|n| n.parse().ok())
452 .unwrap_or(0),
453 rollback: tag == "ROLLBACK",
454 }
455 }
456}
457
458impl Client {
459 pub async fn connect(config: &Config) -> Result<Client, Error> {
473 let startup = connect::connect(config).await?;
474 Ok(Self::start(startup, config.clone()))
475 }
476
477 pub(crate) fn start(startup: Startup, config: Config) -> Client {
478 let Startup {
479 stream,
480 buf,
481 params,
482 key,
483 status,
484 } = startup;
485 let conn = Rc::new_cyclic(|weak| Conn {
486 weak: weak.clone(),
487 head_since: Cell::new(None),
488 stream,
489 config,
490 key,
491 shared: Cell::new(false),
492 idle_wakers: RefCell::new(Vec::new()),
493 requests: Cell::new(0),
494 lease: RefCell::new(None),
495 retire: Cell::new(false),
496 user_prepared: Cell::new(false),
497 tx: Cell::new(Tx::None),
498 state: RefCell::new(State {
499 out: Vec::new(),
500 writer: None,
501 queue: VecDeque::new(),
502 extra: 0,
503 read_only_prepared: false,
504 held: Vec::new(),
505 batch_failed: false,
506 broken: None,
507 closing: false,
508 status,
509 cache: HashMap::new(),
510 clock: 0,
511 next_name: 0,
512 server_params: params,
513 batch: None,
514 }),
515 });
516 giong::spawn(read_loop(conn.clone(), buf));
517 giong::spawn(write_loop(conn.clone()));
518 Client { conn }
519 }
520
521 pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
545 let (set, _) = self.run(sql, params, false).await?;
546 Ok(set.into_rows())
547 }
548
549 pub(crate) async fn query_shared(
552 &self,
553 sql: &str,
554 params: &[&dyn ToSql],
555 batch: bool,
556 ) -> Result<Vec<Row>, Error> {
557 let (set, _) = self.run(sql, params, batch).await?;
558 Ok(set.into_rows())
559 }
560
561 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
567 one_row(self.query(sql, params).await?)
568 }
569
570 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
576 at_most_one_row(self.query(sql, params).await?)
577 }
578}
579
580pub(crate) fn one_row(mut rows: Vec<Row>) -> Result<Row, Error> {
582 match rows.len() {
583 1 => Ok(rows.pop().expect("one row")),
584 n => Err(Error::new(
585 ErrorKind::RowCount,
586 format!(
587 "the statement returned {n} rows where exactly one was expected; use \
588 query_opt for zero or one, or query for any number"
589 ),
590 )),
591 }
592}
593
594pub(crate) fn at_most_one_row(mut rows: Vec<Row>) -> Result<Option<Row>, Error> {
596 match rows.len() {
597 0 | 1 => Ok(rows.pop()),
598 n => Err(Error::new(
599 ErrorKind::RowCount,
600 format!(
601 "the statement returned {n} rows where at most one was expected; add a \
602 LIMIT, or use query"
603 ),
604 )),
605 }
606}
607
608impl Client {
609 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
614 let (_, tag) = self.run(sql, params, false).await?;
615 Ok(tag.map_or(0, |t| t.rows))
616 }
617
618 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
629 let slot = self
630 .conn
631 .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
632 Wait { slot }.await.map(|_| ())
633 }
634
635 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
653 let tx = Transaction {
656 client: self,
657 done: false,
658 };
659 tx.client.conn.tx.set(Tx::Open);
660 tx.client.batch_execute("BEGIN").await?;
661 Ok(tx)
662 }
663
664 pub fn cancel_token(&self) -> CancelToken {
673 CancelToken {
674 config: self.conn.config.without_password(),
675 key: self.conn.key,
676 lease: self.conn.lease.borrow().clone(),
677 }
678 }
679
680 pub fn parameter(&self, name: &str) -> Option<String> {
683 let st = self.conn.state.borrow();
684 st.server_params
685 .iter()
686 .find(|(n, _)| n == name)
687 .map(|(_, v)| v.clone())
688 }
689
690 pub fn is_closed(&self) -> bool {
693 self.conn.state.borrow().broken.is_some()
694 }
695
696 pub fn in_flight(&self) -> usize {
698 let st = self.conn.state.borrow();
699 st.queue.len() - st.extra + st.held.len()
700 }
701
702 pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
705 self.conn
706 .head_since
707 .get()
708 .map_or(std::time::Duration::ZERO, |t| {
709 now.saturating_duration_since(t)
710 })
711 }
712
713 pub(crate) fn in_transaction(&self) -> bool {
715 self.conn.state.borrow().status != b'I'
716 }
717
718 pub(crate) fn set_shared(&self, shared: bool) {
723 self.conn.shared.set(shared);
724 }
725
726 pub(crate) fn wake_when_idle(&self, waker: &Waker) {
728 let mut wakers = self.conn.idle_wakers.borrow_mut();
729 if !wakers.iter().any(|w| w.will_wake(waker)) {
730 wakers.push(waker.clone());
731 }
732 }
733
734 pub(crate) fn requests(&self) -> u64 {
736 self.conn.requests.get()
737 }
738
739 pub(crate) fn begin_lease(&self) {
742 *self.conn.lease.borrow_mut() = Some(Arc::new(Lease::default()));
743 }
744
745 pub(crate) fn end_lease(&self) -> bool {
750 self.conn
751 .lease
752 .borrow_mut()
753 .take()
754 .is_some_and(|lease| lease.end())
755 }
756
757 pub(crate) fn should_retire(&self) -> bool {
760 self.conn.retire.get()
761 }
762
763 pub(crate) fn reset_session(&self) {
768 let deallocate = self.conn.user_prepared.replace(false);
769 let sql = if deallocate {
770 let mut st = self.conn.state.borrow_mut();
771 st.cache.clear();
772 st.read_only_prepared = false;
773 format!("{RESET}; DEALLOCATE ALL")
774 } else {
775 RESET.to_owned()
776 };
777 if let Ok(slot) = self
778 .conn
779 .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
780 {
781 slot.inner.borrow_mut().abandoned = true;
782 }
783 }
784
785 pub(crate) fn send_and_forget(&self, sql: &str) {
787 if let Ok(slot) = self
788 .conn
789 .enqueue(Kind::Simple, |out| protocol::query(out, sql))
790 {
791 slot.inner.borrow_mut().abandoned = true;
792 }
793 }
794
795 async fn run(
796 &self,
797 sql: &str,
798 params: &[&dyn ToSql],
799 batch: bool,
800 ) -> Result<(ResultSet, Option<Tag>), Error> {
801 if params.len() > MAX_PARAMS {
802 return Err(Error::conversion(format!(
803 "{} parameters were given; a statement can have at most {MAX_PARAMS}",
804 params.len()
805 )));
806 }
807 let mut retried = false;
812 let mut alone = !batch;
814 loop {
815 let slot = self.send(sql, params, !alone).await?;
816 let result = Wait { slot: slot.clone() }.await;
817 if result.is_err() {
818 let (skipped, stale) = {
819 let inner = slot.inner.borrow();
820 (inner.alone, inner.retry)
821 };
822 if skipped && !alone {
823 alone = true;
824 continue;
825 }
826 if stale && !retried {
827 retried = true;
828 continue;
829 }
830 }
831 return match result? {
832 Response::Rows(set, tag) => Ok((set, tag)),
833 _ => unreachable!("an execute slot ends with rows"),
834 };
835 }
836 }
837
838 async fn send(&self, sql: &str, params: &[&dyn ToSql], batch: bool) -> Result<Rc<Slot>, Error> {
840 let stmt = self.conn.statement(sql).await?;
841 if stmt.params.len() != params.len() {
842 return Err(Error::conversion(format!(
843 "the statement has {} parameters but {} values were given",
844 stmt.params.len(),
845 params.len()
846 )));
847 }
848 let cached = stmt.conn.is_none();
849 let encode = |out: &mut Vec<u8>| {
850 protocol::bind(
851 out,
852 &stmt.name,
853 params.len(),
854 |i, out| {
855 params[i].to_sql(stmt.params[i], out).map_err(|e| {
856 e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
857 })
858 },
859 stmt.columns.iter().map(|c| c.ty().binary_result()),
860 )?;
861 protocol::execute(out)
862 };
863 let kind = Kind::Execute { stmt: stmt.clone() };
864 let slot = if batch
865 && cached
866 && !stmt.writes.get()
867 && self.conn.shared.get()
868 && self.conn.tx.get() == Tx::None
869 {
870 self.conn.enqueue_batched(kind, encode)?
871 } else {
872 self.conn.enqueue(kind, |out| {
873 encode(out)?;
874 protocol::sync(out);
875 Ok(())
876 })?
877 };
878 if !cached {
879 let close = self.conn.enqueue(Kind::Simple, |out| {
882 protocol::close_statement(out, &stmt.name)?;
883 protocol::sync(out);
884 Ok(())
885 });
886 if let Ok(close) = close {
887 close.inner.borrow_mut().abandoned = true;
888 stmt.closed.set(true);
889 }
890 }
891 Ok(slot)
892 }
893}
894
895impl Drop for Client {
896 fn drop(&mut self) {
897 let mut st = self.conn.state.borrow_mut();
898 st.closing = true;
899 if st.broken.is_none() {
900 protocol::terminate(&mut st.out);
901 st.batch = None;
902 }
903 if let Some(w) = st.writer.take() {
904 w.wake();
905 }
906 }
907}
908
909impl std::fmt::Debug for Client {
910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
911 f.debug_struct("Client")
912 .field("server", &self.conn.config.target())
913 .field("in_flight", &self.in_flight())
914 .field("closed", &self.is_closed())
915 .finish()
916 }
917}
918
919impl Conn {
920 fn enqueue(
923 &self,
924 kind: Kind,
925 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
926 ) -> Result<Rc<Slot>, Error> {
927 self.enqueue_with(kind, false, encode)
928 }
929
930 #[cold]
933 #[inline(never)]
934 fn in_tx(&self) -> Result<Weak<Conn>, Error> {
935 match self.tx.get() {
936 Tx::Abandoned => Err(abandoned()),
937 _ => Ok(self.weak.clone()),
938 }
939 }
940
941 fn enqueue_with(
942 &self,
943 kind: Kind,
944 close_on_error: bool,
945 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
946 ) -> Result<Rc<Slot>, Error> {
947 let mut st = self.state.borrow_mut();
948 if let Some(e) = &st.broken {
949 return Err(e.clone());
950 }
951 let in_tx = if self.tx.get() == Tx::None {
952 None
953 } else {
954 Some(self.in_tx()?)
955 };
956 st.batch = None;
958 let start = st.out.len();
959 if let Err(e) = encode(&mut st.out) {
960 st.out.truncate(start);
961 return Err(e);
962 }
963 let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
964 self.requests.set(self.requests.get() + 1);
965 if st.queue.is_empty() {
966 self.head_since.set(Some(giong::time::Instant::now()));
967 }
968 st.queue.push_back(slot.clone());
969 if let Some(w) = st.writer.take() {
970 w.wake();
971 }
972 Ok(slot)
973 }
974
975 #[inline(never)]
982 fn enqueue_batched(
983 &self,
984 kind: Kind,
985 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
986 ) -> Result<Rc<Slot>, Error> {
987 let mut st = self.state.borrow_mut();
988 if let Some(e) = &st.broken {
989 return Err(e.clone());
990 }
991 let joins = st.batch.as_ref().is_some_and(|b| b.members < BATCH_MAX);
992 if !joins {
993 let start = st.out.len();
994 if let Err(e) = encode(&mut st.out) {
995 st.out.truncate(start);
996 return Err(e);
997 }
998 protocol::sync(&mut st.out);
999 st.batch = Some(OpenBatch { start, members: 1 });
1000 return Ok(self.queue_slot(&mut st, Slot::new(kind, true, false, None)));
1001 }
1002 let mut messages = Vec::new();
1005 encode(&mut messages)?;
1006 let sync_at = st.out.len() - SYNC_LEN;
1007 st.out.truncate(sync_at);
1008 let b = st.batch.as_mut().expect("joins");
1009 if b.members == 1 {
1010 let start = b.start;
1013 let mut guard = Vec::new();
1014 read_only_guard(&mut guard, st.read_only_prepared);
1015 st.read_only_prepared = true;
1016 st.out.splice(start..start, guard);
1017 let first = st.queue.pop_back().expect("the batch's first statement");
1018 first.batch.set(Role::Member);
1019 let guard = Slot::new(Kind::Simple, true, false, None);
1020 guard.batch.set(Role::Guard);
1021 st.extra += 2; guard.inner.borrow_mut().abandoned = true;
1023 st.queue.push_back(guard);
1024 st.queue.push_back(first);
1025 } else {
1026 let end = st.queue.pop_back().expect("the batch's end");
1027 debug_assert_eq!(end.batch.get(), Role::End);
1028 }
1029 st.batch.as_mut().expect("joins").members += 1;
1030 st.out.extend_from_slice(&messages);
1031 protocol::sync(&mut st.out);
1032 let slot = Slot::new(kind, true, false, None);
1033 slot.batch.set(Role::Member);
1034 st.queue.push_back(slot.clone());
1035 let end = Slot::new(Kind::Simple, true, false, None);
1036 end.batch.set(Role::End);
1037 end.inner.borrow_mut().abandoned = true;
1038 self.queue_slot(&mut st, end);
1039 Ok(slot)
1040 }
1041
1042 fn queue_slot(&self, st: &mut State, slot: Rc<Slot>) -> Rc<Slot> {
1044 self.requests.set(self.requests.get() + 1);
1045 if st.queue.is_empty() {
1046 self.head_since.set(Some(giong::time::Instant::now()));
1047 }
1048 st.queue.push_back(slot.clone());
1049 if let Some(w) = st.writer.take() {
1050 w.wake();
1051 }
1052 slot
1053 }
1054
1055 fn finish_member(&self, slot: &Rc<Slot>) {
1060 slot.inner.borrow_mut().status = b'I';
1063 let mut st = self.state.borrow_mut();
1064 st.queue.pop_front();
1065 if slot.batch.get() == Role::Guard {
1066 st.extra -= 1;
1067 } else {
1068 st.held.push(slot.clone());
1069 }
1070 self.head_since
1071 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1072 }
1073
1074 async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1077 let mut again = true;
1078 loop {
1079 let pending = {
1080 let mut st = self.state.borrow_mut();
1081 st.clock += 1;
1082 let now = st.clock;
1083 match st.cache.get_mut(sql) {
1084 Some(Entry::Ready { stmt, used }) => {
1085 *used = now;
1086 return Ok(stmt.clone());
1087 }
1088 Some(Entry::Preparing(slot)) => Some(slot.clone()),
1089 None => None,
1090 }
1091 };
1092 let Some(slot) = pending else {
1093 return self.prepare(sql).await;
1094 };
1095 match (Wait { slot }).await {
1096 Ok(Response::Statement(stmt)) => return Ok(stmt),
1097 Ok(_) => unreachable!("a prepare slot ends with a statement"),
1098 Err(e) if again && e.server_code() == Some("42P05") => again = false,
1101 Err(e) => return Err(e),
1102 }
1103 }
1104 }
1105
1106 async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1107 match self.prepare_once(sql).await {
1108 Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
1112 result => result,
1113 }
1114 }
1115
1116 async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1117 let cached = self.config.statement_cache > 0;
1118 let (name, key) = {
1119 let mut st = self.state.borrow_mut();
1120 st.next_name += 1;
1121 (
1122 format!("{NAME_PREFIX}{}", st.next_name),
1123 Rc::<str>::from(sql),
1124 )
1125 };
1126 let slot = self.enqueue(
1127 Kind::Prepare {
1128 sql: key.clone(),
1129 name: name.as_str().into(),
1130 cached,
1131 },
1132 |out| {
1133 protocol::parse(out, &name, sql)?;
1134 protocol::describe_statement(out, &name)?;
1135 protocol::sync(out);
1136 Ok(())
1137 },
1138 )?;
1139 if cached {
1140 self.state
1141 .borrow_mut()
1142 .cache
1143 .insert(key, Entry::Preparing(slot.clone()));
1144 }
1145 match (Wait { slot }).await? {
1146 Response::Statement(stmt) => Ok(stmt),
1147 _ => unreachable!("a prepare slot ends with a statement"),
1148 }
1149 }
1150
1151 fn fail(&self, err: Error) {
1154 let slots = {
1155 let mut st = self.state.borrow_mut();
1156 if st.broken.is_none() {
1157 st.broken = Some(err.clone());
1158 }
1159 st.cache.clear();
1160 st.out.clear();
1161 self.head_since.set(None);
1162 if let Some(w) = st.writer.take() {
1163 w.wake();
1164 }
1165 st.extra = 0;
1166 st.read_only_prepared = false;
1167 st.batch_failed = false;
1168 let mut slots = std::mem::take(&mut st.held);
1169 slots.extend(std::mem::take(&mut st.queue));
1170 slots
1171 };
1172 for slot in slots {
1173 let mut inner = slot.inner.borrow_mut();
1174 let e = inner.error.take().unwrap_or_else(|| err.clone());
1175 inner.outcome = Some(Err(e));
1176 inner.wakers.wake_all();
1177 }
1178 self.wake_idle();
1179 self.stream.shutdown(Shutdown::Both);
1180 }
1181
1182 fn wake_idle(&self) {
1183 let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
1184 for w in wakers {
1185 w.wake();
1186 }
1187 }
1188
1189 fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
1191 let limit = self.config.max_result_size.max(1 << 20);
1192 while let Some((tag, len)) = buf.peek()? {
1193 if len > limit {
1194 match tag {
1195 b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
1198 b'N' | b'A' | b'd' => {}
1202 b'E' => {
1205 let slot = self.front()?;
1206 let mut inner = slot.inner.borrow_mut();
1207 if inner.error.is_none() {
1208 inner.error = Some(Error::new(
1209 ErrorKind::TooLarge,
1210 format!(
1211 "the server's error for this statement was a {len}-byte \
1212 message, more than max_result_size allows, so it was \
1213 thrown away; raise Config::max_result_size to read it"
1214 ),
1215 ));
1216 }
1217 }
1218 _ => {
1219 return Err(Error::new(
1220 ErrorKind::Protocol,
1221 format!(
1222 "the server sent a {:?} message of {len} bytes, more than \
1223 max_result_size allows, so the connection was closed; raise \
1224 Config::max_result_size if the server's messages are this large",
1225 tag as char
1226 ),
1227 ))
1228 }
1229 }
1230 buf.skip(len);
1231 continue;
1232 }
1233 let Some(body) = buf.body(len) else {
1234 return Ok(());
1235 };
1236 self.handle(tag, buf.bytes(body))?;
1237 buf.consume(len);
1238 }
1239 Ok(())
1240 }
1241
1242 fn front(&self) -> Result<Rc<Slot>, Error> {
1243 self.state.borrow().queue.front().cloned().ok_or_else(|| {
1244 Error::protocol("the server sent a reply to a request that was never made")
1245 })
1246 }
1247
1248 fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
1249 let msg = parse_backend(tag, body)?;
1250 match msg {
1251 Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
1252 Backend::ParameterStatus { name, value } => {
1253 if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
1254 return Err(Error::closed(format!(
1255 "the session's client_encoding was changed to {value}; giong-postgres \
1256 reads and writes UTF-8 only, so the connection was closed"
1257 )));
1258 }
1259 let mut st = self.state.borrow_mut();
1260 match st.server_params.iter_mut().find(|(n, _)| n == name) {
1261 Some(entry) => entry.1 = value.to_owned(),
1262 None => st.server_params.push((name.to_owned(), value.to_owned())),
1263 }
1264 return Ok(());
1265 }
1266 Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
1267 let db = DbError::parse(fields)?;
1270 return Err(Error::with_db(
1271 ErrorKind::Closed,
1272 "the server closed the connection",
1273 db,
1274 ));
1275 }
1276 _ => {}
1277 }
1278 let slot = loop {
1279 let slot = self.front()?;
1280 if slot.batch.get() != Role::Alone
1281 && matches!(
1282 msg,
1283 Backend::CommandComplete(_)
1284 | Backend::ErrorResponse(_)
1285 | Backend::ReadyForQuery(_)
1286 )
1287 {
1288 if self.handle_batched(slot, &msg)? {
1289 continue;
1292 }
1293 return Ok(());
1294 }
1295 break slot;
1296 };
1297 let mut inner = slot.inner.borrow_mut();
1298 match msg {
1299 Backend::BindComplete => inner.bound = true,
1300 Backend::ParseComplete
1301 | Backend::CloseComplete
1302 | Backend::NoData
1303 | Backend::PortalSuspended
1304 | Backend::EmptyQueryResponse => {}
1305 Backend::ParameterDescription(types) => inner.params = Some(types),
1306 Backend::RowDescription(fields) => {
1307 if matches!(slot.kind, Kind::Prepare { .. }) {
1308 inner.columns = Some(
1309 fields
1310 .iter()
1311 .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
1312 .collect(),
1313 );
1314 }
1315 }
1316 Backend::DataRow(body) => match &slot.kind {
1317 Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
1318 let limit = self.config.max_result_size;
1319 inner.rows.push(body, stmt.columns.len(), limit)?;
1320 }
1321 _ => {}
1322 },
1323 Backend::CommandComplete(tag) => {
1324 if tag == "PREPARE" {
1325 self.user_prepared.set(true);
1326 }
1327 inner.tag = Some(Tag::of(tag));
1328 }
1329 Backend::ErrorResponse(fields) => {
1330 if inner.error.is_none() {
1331 inner.error = Some(self.db_error(fields, true)?);
1332 }
1333 }
1334 Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
1335 if inner.error.is_none() {
1336 inner.error = Some(Error::conversion(
1337 "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
1338 was thrown away",
1339 ));
1340 }
1341 }
1342 Backend::CopyInResponse | Backend::CopyBothResponse => {
1343 return Err(Error::closed(
1344 "the statement started COPY FROM STDIN or replication, which giong-postgres \
1345 does not support yet; the connection was closed",
1346 ));
1347 }
1348 Backend::ReadyForQuery(status) => {
1349 let left_open = slot.shared && status != b'I';
1353 if left_open {
1354 inner.error = Some(Error::closed(LEFT_OPEN));
1355 }
1356 let reset_failed = match &inner.error {
1357 Some(e) if slot.close_on_error => Some(Error::closed(format!(
1358 "resetting the session of a connection that went back to the pool \
1359 failed, so it was closed rather than reused: {e}"
1360 ))),
1361 _ => None,
1362 };
1363 inner.status = status;
1364 drop(inner);
1365 let idle = {
1366 let mut st = self.state.borrow_mut();
1367 st.status = status;
1368 st.queue.pop_front();
1369 self.head_since
1370 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1371 st.queue.is_empty()
1372 };
1373 self.complete(&slot);
1374 if left_open {
1375 return Err(Error::closed(LEFT_OPEN));
1377 }
1378 if let Some(e) = reset_failed {
1379 return Err(e);
1380 }
1381 if idle {
1382 self.wake_idle();
1383 }
1384 }
1385 other => {
1386 return Err(Error::protocol(format!(
1387 "the server sent an unexpected {:?} message ({other:?})",
1388 tag as char
1389 )))
1390 }
1391 }
1392 Ok(())
1393 }
1394
1395 fn db_error(&self, fields: &[u8], may_retire: bool) -> Result<Error, Error> {
1397 let db = DbError::parse(fields)?;
1398 if may_retire && db.code() == "25006" && self.on_standby() {
1399 self.retire.set(true);
1400 }
1401 let note = (db.code() == "57014" && db.message().contains("statement timeout")).then(
1404 || match self.config.statement_timeout {
1405 Some(limit) => format!(
1406 "the statement ran longer than the statement timeout ({limit:?}; \
1407 Config::statement_timeout)"
1408 ),
1409 None => "the statement ran longer than the server's statement_timeout".to_owned(),
1410 },
1411 );
1412 Ok(Error::from_db(db, note))
1413 }
1414
1415 #[cold]
1419 #[inline(never)]
1420 fn handle_batched(&self, slot: Rc<Slot>, msg: &Backend<'_>) -> Result<bool, Error> {
1423 let mut inner = slot.inner.borrow_mut();
1424 match *msg {
1425 Backend::CommandComplete(command) => {
1426 inner.tag = Some(Tag::of(command));
1427 }
1428 Backend::ErrorResponse(fields) => {
1429 let error = self.db_error(fields, false)?;
1431 self.state.borrow_mut().batch_failed = true;
1432 match slot.batch.get() {
1433 Role::End => return Ok(false),
1436 Role::Guard if error.server_code() == Some("26000") => {
1440 self.state.borrow_mut().read_only_prepared = false;
1441 }
1442 _ => {}
1443 }
1444 if matches!(error.server_code(), Some("55P03" | "40P01" | "40001"))
1445 && slot.batch.get() == Role::Member
1446 {
1447 if let Kind::Execute { .. } = &slot.kind {
1452 inner.alone = true;
1453 }
1454 }
1455 if error.server_code() == Some("25006") {
1456 if let Kind::Execute { stmt } = &slot.kind {
1458 stmt.writes.set(true);
1459 inner.alone = true;
1460 }
1461 }
1462 inner.error = Some(error);
1463 }
1464 Backend::ReadyForQuery(status) if slot.batch.get() == Role::End => {
1465 inner.status = status;
1468 drop(inner);
1469 let (idle, held, failed) = {
1470 let mut st = self.state.borrow_mut();
1471 st.status = status;
1472 st.queue.pop_front();
1473 st.extra -= 1;
1474 self.head_since
1475 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1476 let failed = std::mem::take(&mut st.batch_failed);
1477 (st.queue.is_empty(), std::mem::take(&mut st.held), failed)
1478 };
1479 for member in &held {
1480 if failed {
1481 let mut inner = member.inner.borrow_mut();
1482 if inner.error.is_none() {
1483 inner.error = Some(Error::new(
1486 ErrorKind::Closed,
1487 "another statement of this one's batch failed, so the batch \
1488 was rolled back",
1489 ));
1490 inner.alone = matches!(member.kind, Kind::Execute { .. });
1491 }
1492 }
1493 self.complete(member);
1494 }
1495 self.complete(&slot);
1496 if idle {
1497 self.wake_idle();
1498 }
1499 return Ok(false);
1500 }
1501 Backend::ReadyForQuery(_) => {
1502 inner.error = Some(Error::new(
1505 ErrorKind::Closed,
1506 "a statement before this one in its batch failed, so the server skipped it",
1507 ));
1508 inner.alone = matches!(slot.kind, Kind::Execute { .. });
1509 drop(inner);
1510 self.finish_member(&slot);
1511 return Ok(true);
1512 }
1513 _ => unreachable!("only these three come here"),
1514 }
1515 drop(inner);
1516 self.finish_member(&slot);
1517 Ok(false)
1518 }
1519
1520 fn complete(&self, slot: &Rc<Slot>) {
1522 let mut inner = slot.inner.borrow_mut();
1523 let error = inner.error.take();
1524 let outcome = match &slot.kind {
1525 Kind::Prepare { sql, name, cached } => {
1526 let result = match error {
1527 Some(e) => Err(e),
1528 None => match inner.params.take() {
1529 Some(params) => Ok(Rc::new(Statement {
1530 sql: sql.clone(),
1531 name: name.clone(),
1532 params,
1533 columns: inner.columns.take().unwrap_or_default().into(),
1534 conn: (!*cached).then(|| self.weak.clone()),
1535 closed: Cell::new(false),
1536 writes: Cell::new(false),
1537 })),
1538 None => Err(Error::protocol("the server did not describe the statement")),
1539 },
1540 };
1541 if *cached {
1542 self.settle_cache(sql, slot, &result);
1543 }
1544 result.map(Response::Statement)
1545 }
1546 Kind::Execute { stmt } => match error {
1547 Some(e) => {
1548 let stale = self.forget_if_stale(stmt, &e);
1549 inner.retry = stale && !inner.bound && inner.status == b'I';
1552 Err(e)
1553 }
1554 None if inner.rows.overflow => Err(Error::new(
1555 ErrorKind::TooLarge,
1556 format!(
1557 "the result is larger than max_result_size ({} bytes); add a LIMIT or \
1558 select fewer columns, or raise Config::max_result_size",
1559 self.config.max_result_size
1560 ),
1561 )),
1562 None => {
1563 let rows = std::mem::take(&mut inner.rows);
1564 Ok(Response::Rows(
1565 rows.finish(stmt.columns.clone()),
1566 inner.tag.take(),
1567 ))
1568 }
1569 },
1570 Kind::Simple => match error {
1571 Some(e) => Err(e),
1572 None => Ok(Response::Done(inner.tag.take())),
1573 },
1574 };
1575 inner.outcome = Some(outcome);
1576 inner.wakers.wake_all();
1577 }
1578
1579 fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
1584 if !e.db().is_some_and(is_stale) {
1585 return false;
1586 }
1587 let mut st = self.state.borrow_mut();
1588 if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
1589 {
1590 st.cache.remove(&stmt.sql);
1591 }
1592 true
1593 }
1594
1595 fn on_standby(&self) -> bool {
1598 let st = self.state.borrow();
1599 st.server_params
1600 .iter()
1601 .find(|(n, _)| n == "in_hot_standby")
1602 .map_or(true, |(_, v)| v != "off")
1603 }
1604
1605 fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
1608 let mut st = self.state.borrow_mut();
1609 let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
1610 if !ours {
1611 return;
1612 }
1613 let Ok(stmt) = result else {
1614 st.cache.remove(sql);
1615 return;
1616 };
1617 st.clock += 1;
1618 let used = st.clock;
1619 st.cache.insert(
1620 sql.clone(),
1621 Entry::Ready {
1622 stmt: stmt.clone(),
1623 used,
1624 },
1625 );
1626 while st.cache.len() > self.config.statement_cache {
1627 let victim = st
1629 .cache
1630 .iter()
1631 .filter_map(|(k, e)| match e {
1632 Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
1633 Some((*used, k.clone()))
1634 }
1635 _ => None,
1636 })
1637 .min();
1638 let Some((_, key)) = victim else { break };
1639 if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
1640 let _ = protocol::close_statement(&mut st.out, &stmt.name);
1643 st.batch = None;
1645 }
1646 }
1647 }
1648}
1649
1650async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
1651 let err = loop {
1652 if let Err(e) = conn.process(&mut buf) {
1653 break e;
1654 }
1655 match conn.stream.read_into(&mut buf).await {
1656 Ok(0) => {
1657 let closing = conn.state.borrow().closing;
1658 break Error::closed(if closing {
1659 "the connection was closed"
1660 } else {
1661 "the server closed the connection"
1662 });
1663 }
1664 Ok(_) => {}
1665 Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
1666 }
1667 };
1668 conn.fail(err);
1669}
1670
1671async fn write_loop(conn: Rc<Conn>) {
1672 let mut spare = Vec::new();
1673 loop {
1674 let next = poll_fn(|cx| {
1675 let mut st = conn.state.borrow_mut();
1676 if st.broken.is_some() {
1677 return Poll::Ready(None);
1678 }
1679 if !st.out.is_empty() {
1680 st.batch = None;
1682 return Poll::Ready(Some(std::mem::replace(
1683 &mut st.out,
1684 std::mem::take(&mut spare),
1685 )));
1686 }
1687 if st.closing {
1688 return Poll::Ready(None);
1689 }
1690 st.writer = Some(cx.waker().clone());
1691 Poll::Pending
1692 })
1693 .await;
1694 let Some(data) = next else { break };
1695 let (written, mut data) = conn.stream.write_all(data).await;
1696 if let Err(e) = written {
1697 conn.fail(Error::io(
1698 ErrorKind::Closed,
1699 "writing to the server failed",
1700 e,
1701 ));
1702 return;
1703 }
1704 data.clear();
1705 spare = data;
1706 }
1707 if conn.state.borrow().closing {
1708 conn.stream.shutdown(Shutdown::Write);
1709 }
1710}
1711
1712pub struct Transaction<'a> {
1728 client: &'a mut Client,
1729 done: bool,
1730}
1731
1732impl Transaction<'_> {
1733 pub async fn commit(mut self) -> Result<(), Error> {
1744 if self.client.conn.tx.get() == Tx::Abandoned {
1745 return Err(abandoned());
1747 }
1748 self.end();
1749 let slot = self
1750 .client
1751 .conn
1752 .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
1753 match (Wait { slot }).await? {
1754 Response::Done(Some(tag)) if tag.rollback => Err(Error::with_sqlstate(
1755 "25P02",
1756 "the transaction was rolled back instead of committed, because a statement in \
1757 it failed earlier",
1758 )),
1759 _ => Ok(()),
1760 }
1761 }
1762
1763 pub async fn rollback(mut self) -> Result<(), Error> {
1768 self.end();
1769 self.client.batch_execute("ROLLBACK").await
1770 }
1771
1772 fn end(&mut self) {
1774 self.done = true;
1775 self.client.conn.tx.set(Tx::None);
1776 }
1777}
1778
1779impl Deref for Transaction<'_> {
1780 type Target = Client;
1781
1782 fn deref(&self) -> &Client {
1783 self.client
1784 }
1785}
1786
1787impl Drop for Transaction<'_> {
1788 fn drop(&mut self) {
1789 if !self.done {
1790 self.end();
1791 self.client.send_and_forget("ROLLBACK");
1792 }
1793 }
1794}
1795
1796impl std::fmt::Debug for Transaction<'_> {
1797 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1798 f.debug_struct("Transaction")
1799 .field("client", &self.client)
1800 .finish()
1801 }
1802}
1803
1804#[derive(Clone)]
1811pub struct CancelToken {
1812 config: Config,
1815 key: Option<(i32, i32)>,
1816 lease: Option<Arc<Lease>>,
1819}
1820
1821#[derive(Default)]
1825pub(crate) struct Lease(AtomicU32);
1826
1827impl Lease {
1828 const ENDED: u32 = 1 << 31;
1830
1831 fn start_cancel(&self) -> bool {
1833 let mut v = self.0.load(Ordering::Acquire);
1834 while v & Self::ENDED == 0 {
1835 match self
1836 .0
1837 .compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire)
1838 {
1839 Ok(_) => return true,
1840 Err(now) => v = now,
1841 }
1842 }
1843 false
1844 }
1845
1846 fn finish_cancel(&self) {
1848 self.0.fetch_sub(1, Ordering::AcqRel);
1849 }
1850
1851 fn is_ended(&self) -> bool {
1852 self.0.load(Ordering::Acquire) & Self::ENDED != 0
1853 }
1854
1855 fn end(&self) -> bool {
1858 self.0.fetch_or(Self::ENDED, Ordering::AcqRel) & !Self::ENDED != 0
1859 }
1860}
1861
1862impl CancelToken {
1863 pub async fn cancel(&self) -> Result<(), Error> {
1873 let gone = || {
1874 Error::closed(
1875 "the connection this cancel token was taken from has gone back to its pool, \
1876 where other tasks use it, so nothing was sent; take a new token from the next \
1877 connection",
1878 )
1879 };
1880 if self.lease.as_ref().is_some_and(|lease| lease.is_ended()) {
1881 return Err(gone());
1882 }
1883 let key = self.key.ok_or_else(|| {
1884 Error::new(
1885 ErrorKind::Connect,
1886 "the server gave this connection no cancel key (a connection pooler may be in \
1887 between), so it cannot be cancelled",
1888 )
1889 })?;
1890 let Some(lease) = &self.lease else {
1891 return connect::cancel(&self.config, key).await;
1892 };
1893 if !lease.start_cancel() {
1898 return Err(gone());
1899 }
1900 let sent = connect::cancel(&self.config, key).await;
1901 lease.finish_cancel();
1902 sent
1903 }
1904}
1905
1906impl std::fmt::Debug for CancelToken {
1907 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1908 f.debug_struct("CancelToken")
1909 .field("server", &self.config.target())
1910 .finish_non_exhaustive()
1911 }
1912}
1913
1914#[cfg(test)]
1915mod tests {
1916 use super::{is_stale, Tag};
1917 use crate::error::DbError;
1918
1919 fn db_error(fields: &[(u8, &str)]) -> DbError {
1920 let mut body = Vec::new();
1921 for (field, value) in fields {
1922 body.push(*field);
1923 body.extend_from_slice(value.as_bytes());
1924 body.push(0);
1925 }
1926 body.push(0);
1927 DbError::parse(&body).unwrap()
1928 }
1929
1930 #[test]
1931 fn a_stale_plan_is_recognised_in_any_language() {
1932 let german = db_error(&[
1933 (b'S', "FEHLER"),
1934 (b'V', "ERROR"),
1935 (b'C', "0A000"),
1936 (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
1937 (b'R', "RevalidateCachedQuery"),
1938 ]);
1939 assert!(is_stale(&german));
1940 assert_eq!(german.severity(), "ERROR");
1941 let english = db_error(&[
1943 (b'C', "0A000"),
1944 (b'M', "cached plan must not change result type"),
1945 ]);
1946 assert!(is_stale(&english));
1947 let other = db_error(&[
1949 (b'C', "0A000"),
1950 (b'M', "nicht unterstützt"),
1951 (b'R', "transformSelectStmt"),
1952 ]);
1953 assert!(!is_stale(&other));
1954 assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
1955 }
1956
1957 #[test]
1958 fn command_tags_give_row_counts() {
1959 assert_eq!(Tag::of("INSERT 0 5").rows, 5);
1960 assert_eq!(Tag::of("UPDATE 3").rows, 3);
1961 assert_eq!(Tag::of("SELECT 12").rows, 12);
1962 assert_eq!(Tag::of("CREATE TABLE").rows, 0);
1963 assert!(Tag::of("ROLLBACK").rollback && !Tag::of("COMMIT").rollback);
1964 }
1965}