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)]
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 {
627 CancelToken {
628 config: self.conn.config.without_password(),
629 key: self.conn.key,
630 lease: self.conn.lease.borrow().clone(),
631 }
632 }
633
634 pub fn parameter(&self, name: &str) -> Option<String> {
637 let st = self.conn.state.borrow();
638 st.server_params
639 .iter()
640 .find(|(n, _)| n == name)
641 .map(|(_, v)| v.clone())
642 }
643
644 pub fn is_closed(&self) -> bool {
647 self.conn.state.borrow().broken.is_some()
648 }
649
650 pub fn in_flight(&self) -> usize {
652 let st = self.conn.state.borrow();
653 st.queue.len() - st.extra + st.held.len()
654 }
655
656 pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
659 self.conn
660 .head_since
661 .get()
662 .map_or(std::time::Duration::ZERO, |t| {
663 now.saturating_duration_since(t)
664 })
665 }
666
667 pub(crate) fn in_transaction(&self) -> bool {
669 self.conn.state.borrow().status != b'I'
670 }
671
672 pub(crate) fn set_shared(&self, shared: bool) {
677 self.conn.shared.set(shared);
678 }
679
680 pub(crate) fn wake_when_idle(&self, waker: &Waker) {
682 let mut wakers = self.conn.idle_wakers.borrow_mut();
683 if !wakers.iter().any(|w| w.will_wake(waker)) {
684 wakers.push(waker.clone());
685 }
686 }
687
688 pub(crate) fn requests(&self) -> u64 {
690 self.conn.requests.get()
691 }
692
693 pub(crate) fn begin_lease(&self) {
696 *self.conn.lease.borrow_mut() = Some(Arc::new(Lease::default()));
697 }
698
699 pub(crate) fn end_lease(&self) -> bool {
704 self.conn
705 .lease
706 .borrow_mut()
707 .take()
708 .is_some_and(|lease| lease.end())
709 }
710
711 pub(crate) fn should_retire(&self) -> bool {
714 self.conn.retire.get()
715 }
716
717 pub(crate) fn reset_session(&self) {
722 let deallocate = self.conn.user_prepared.replace(false);
723 let sql = if deallocate {
724 let mut st = self.conn.state.borrow_mut();
725 st.cache.clear();
726 st.read_only_prepared = false;
727 format!("{RESET}; DEALLOCATE ALL")
728 } else {
729 RESET.to_owned()
730 };
731 if let Ok(slot) = self
732 .conn
733 .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
734 {
735 slot.inner.borrow_mut().abandoned = true;
736 }
737 }
738
739 pub(crate) fn send_and_forget(&self, sql: &str) {
741 if let Ok(slot) = self
742 .conn
743 .enqueue(Kind::Simple, |out| protocol::query(out, sql))
744 {
745 slot.inner.borrow_mut().abandoned = true;
746 }
747 }
748
749 async fn run(
750 &self,
751 sql: &str,
752 params: &[&dyn ToSql],
753 batch: bool,
754 ) -> Result<(ResultSet, Option<String>), Error> {
755 if params.len() > MAX_PARAMS {
756 return Err(Error::conversion(format!(
757 "{} parameters were given; a statement can have at most {MAX_PARAMS}",
758 params.len()
759 )));
760 }
761 let mut retried = false;
766 let mut alone = !batch;
768 loop {
769 let slot = self.send(sql, params, !alone).await?;
770 let result = Wait { slot: slot.clone() }.await;
771 if result.is_err() {
772 let (skipped, stale) = {
773 let inner = slot.inner.borrow();
774 (inner.alone, inner.retry)
775 };
776 if skipped && !alone {
777 alone = true;
778 continue;
779 }
780 if stale && !retried {
781 retried = true;
782 continue;
783 }
784 }
785 return match result? {
786 Response::Rows(set, tag) => Ok((set, tag)),
787 _ => unreachable!("an execute slot ends with rows"),
788 };
789 }
790 }
791
792 async fn send(&self, sql: &str, params: &[&dyn ToSql], batch: bool) -> Result<Rc<Slot>, Error> {
794 let stmt = self.conn.statement(sql).await?;
795 if stmt.params.len() != params.len() {
796 return Err(Error::conversion(format!(
797 "the statement has {} parameters but {} values were given",
798 stmt.params.len(),
799 params.len()
800 )));
801 }
802 let cached = stmt.conn.is_none();
803 let encode = |out: &mut Vec<u8>| {
804 protocol::bind(
805 out,
806 &stmt.name,
807 params.len(),
808 |i, out| {
809 params[i].to_sql(stmt.params[i], out).map_err(|e| {
810 e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
811 })
812 },
813 stmt.columns.iter().map(|c| c.ty().binary_result()),
814 )?;
815 protocol::execute(out)
816 };
817 let kind = Kind::Execute { stmt: stmt.clone() };
818 let slot = if batch
819 && cached
820 && !stmt.writes.get()
821 && self.conn.shared.get()
822 && self.conn.tx.get() == Tx::None
823 {
824 self.conn.enqueue_batched(kind, encode)?
825 } else {
826 self.conn.enqueue(kind, |out| {
827 encode(out)?;
828 protocol::sync(out);
829 Ok(())
830 })?
831 };
832 if !cached {
833 let close = self.conn.enqueue(Kind::Simple, |out| {
836 protocol::close_statement(out, &stmt.name)?;
837 protocol::sync(out);
838 Ok(())
839 });
840 if let Ok(close) = close {
841 close.inner.borrow_mut().abandoned = true;
842 stmt.closed.set(true);
843 }
844 }
845 Ok(slot)
846 }
847}
848
849impl Drop for Client {
850 fn drop(&mut self) {
851 let mut st = self.conn.state.borrow_mut();
852 st.closing = true;
853 if st.broken.is_none() {
854 protocol::terminate(&mut st.out);
855 st.batch = None;
856 }
857 if let Some(w) = st.writer.take() {
858 w.wake();
859 }
860 }
861}
862
863impl std::fmt::Debug for Client {
864 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865 f.debug_struct("Client")
866 .field("server", &self.conn.config.target())
867 .field("in_flight", &self.in_flight())
868 .field("closed", &self.is_closed())
869 .finish()
870 }
871}
872
873impl Conn {
874 fn enqueue(
877 &self,
878 kind: Kind,
879 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
880 ) -> Result<Rc<Slot>, Error> {
881 self.enqueue_with(kind, false, encode)
882 }
883
884 #[cold]
887 #[inline(never)]
888 fn in_tx(&self) -> Result<Weak<Conn>, Error> {
889 match self.tx.get() {
890 Tx::Abandoned => Err(abandoned()),
891 _ => Ok(self.weak.clone()),
892 }
893 }
894
895 fn enqueue_with(
896 &self,
897 kind: Kind,
898 close_on_error: bool,
899 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
900 ) -> Result<Rc<Slot>, Error> {
901 let mut st = self.state.borrow_mut();
902 if let Some(e) = &st.broken {
903 return Err(e.clone());
904 }
905 let in_tx = if self.tx.get() == Tx::None {
906 None
907 } else {
908 Some(self.in_tx()?)
909 };
910 st.batch = None;
912 let start = st.out.len();
913 if let Err(e) = encode(&mut st.out) {
914 st.out.truncate(start);
915 return Err(e);
916 }
917 let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
918 self.requests.set(self.requests.get() + 1);
919 if st.queue.is_empty() {
920 self.head_since.set(Some(giong::time::Instant::now()));
921 }
922 st.queue.push_back(slot.clone());
923 if let Some(w) = st.writer.take() {
924 w.wake();
925 }
926 Ok(slot)
927 }
928
929 #[inline(never)]
936 fn enqueue_batched(
937 &self,
938 kind: Kind,
939 encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
940 ) -> Result<Rc<Slot>, Error> {
941 let mut st = self.state.borrow_mut();
942 if let Some(e) = &st.broken {
943 return Err(e.clone());
944 }
945 let joins = st.batch.as_ref().is_some_and(|b| b.members < BATCH_MAX);
946 if !joins {
947 let start = st.out.len();
948 if let Err(e) = encode(&mut st.out) {
949 st.out.truncate(start);
950 return Err(e);
951 }
952 protocol::sync(&mut st.out);
953 st.batch = Some(OpenBatch { start, members: 1 });
954 return Ok(self.queue_slot(&mut st, Slot::new(kind, true, false, None)));
955 }
956 let mut messages = Vec::new();
959 encode(&mut messages)?;
960 let sync_at = st.out.len() - SYNC_LEN;
961 st.out.truncate(sync_at);
962 let b = st.batch.as_mut().expect("joins");
963 if b.members == 1 {
964 let start = b.start;
967 let mut guard = Vec::new();
968 read_only_guard(&mut guard, st.read_only_prepared);
969 st.read_only_prepared = true;
970 st.out.splice(start..start, guard);
971 let first = st.queue.pop_back().expect("the batch's first statement");
972 first.batch.set(Role::Member);
973 let guard = Slot::new(Kind::Simple, true, false, None);
974 guard.batch.set(Role::Guard);
975 st.extra += 2; guard.inner.borrow_mut().abandoned = true;
977 st.queue.push_back(guard);
978 st.queue.push_back(first);
979 } else {
980 let end = st.queue.pop_back().expect("the batch's end");
981 debug_assert_eq!(end.batch.get(), Role::End);
982 }
983 st.batch.as_mut().expect("joins").members += 1;
984 st.out.extend_from_slice(&messages);
985 protocol::sync(&mut st.out);
986 let slot = Slot::new(kind, true, false, None);
987 slot.batch.set(Role::Member);
988 st.queue.push_back(slot.clone());
989 let end = Slot::new(Kind::Simple, true, false, None);
990 end.batch.set(Role::End);
991 end.inner.borrow_mut().abandoned = true;
992 self.queue_slot(&mut st, end);
993 Ok(slot)
994 }
995
996 fn queue_slot(&self, st: &mut State, slot: Rc<Slot>) -> Rc<Slot> {
998 self.requests.set(self.requests.get() + 1);
999 if st.queue.is_empty() {
1000 self.head_since.set(Some(giong::time::Instant::now()));
1001 }
1002 st.queue.push_back(slot.clone());
1003 if let Some(w) = st.writer.take() {
1004 w.wake();
1005 }
1006 slot
1007 }
1008
1009 fn finish_member(&self, slot: &Rc<Slot>) {
1014 slot.inner.borrow_mut().status = b'I';
1017 let mut st = self.state.borrow_mut();
1018 st.queue.pop_front();
1019 if slot.batch.get() == Role::Guard {
1020 st.extra -= 1;
1021 } else {
1022 st.held.push(slot.clone());
1023 }
1024 self.head_since
1025 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1026 }
1027
1028 async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1031 let mut again = true;
1032 loop {
1033 let pending = {
1034 let mut st = self.state.borrow_mut();
1035 st.clock += 1;
1036 let now = st.clock;
1037 match st.cache.get_mut(sql) {
1038 Some(Entry::Ready { stmt, used }) => {
1039 *used = now;
1040 return Ok(stmt.clone());
1041 }
1042 Some(Entry::Preparing(slot)) => Some(slot.clone()),
1043 None => None,
1044 }
1045 };
1046 let Some(slot) = pending else {
1047 return self.prepare(sql).await;
1048 };
1049 match (Wait { slot }).await {
1050 Ok(Response::Statement(stmt)) => return Ok(stmt),
1051 Ok(_) => unreachable!("a prepare slot ends with a statement"),
1052 Err(e) if again && e.server_code() == Some("42P05") => again = false,
1055 Err(e) => return Err(e),
1056 }
1057 }
1058 }
1059
1060 async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1061 match self.prepare_once(sql).await {
1062 Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
1066 result => result,
1067 }
1068 }
1069
1070 async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
1071 let cached = self.config.statement_cache > 0;
1072 let (name, key) = {
1073 let mut st = self.state.borrow_mut();
1074 st.next_name += 1;
1075 (
1076 format!("{NAME_PREFIX}{}", st.next_name),
1077 Rc::<str>::from(sql),
1078 )
1079 };
1080 let slot = self.enqueue(
1081 Kind::Prepare {
1082 sql: key.clone(),
1083 name: name.as_str().into(),
1084 cached,
1085 },
1086 |out| {
1087 protocol::parse(out, &name, sql)?;
1088 protocol::describe_statement(out, &name)?;
1089 protocol::sync(out);
1090 Ok(())
1091 },
1092 )?;
1093 if cached {
1094 self.state
1095 .borrow_mut()
1096 .cache
1097 .insert(key, Entry::Preparing(slot.clone()));
1098 }
1099 match (Wait { slot }).await? {
1100 Response::Statement(stmt) => Ok(stmt),
1101 _ => unreachable!("a prepare slot ends with a statement"),
1102 }
1103 }
1104
1105 fn fail(&self, err: Error) {
1108 let slots = {
1109 let mut st = self.state.borrow_mut();
1110 if st.broken.is_none() {
1111 st.broken = Some(err.clone());
1112 }
1113 st.cache.clear();
1114 st.out.clear();
1115 self.head_since.set(None);
1116 if let Some(w) = st.writer.take() {
1117 w.wake();
1118 }
1119 st.extra = 0;
1120 st.read_only_prepared = false;
1121 st.batch_failed = false;
1122 let mut slots = std::mem::take(&mut st.held);
1123 slots.extend(std::mem::take(&mut st.queue));
1124 slots
1125 };
1126 for slot in slots {
1127 let mut inner = slot.inner.borrow_mut();
1128 let e = inner.error.take().unwrap_or_else(|| err.clone());
1129 inner.outcome = Some(Err(e));
1130 for w in inner.wakers.drain(..) {
1131 w.wake();
1132 }
1133 }
1134 self.wake_idle();
1135 self.stream.shutdown(Shutdown::Both);
1136 }
1137
1138 fn wake_idle(&self) {
1139 let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
1140 for w in wakers {
1141 w.wake();
1142 }
1143 }
1144
1145 fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
1147 let limit = self.config.max_result_size.max(1 << 20);
1148 while let Some((tag, len)) = buf.peek()? {
1149 if len > limit {
1150 match tag {
1151 b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
1154 b'N' | b'A' | b'd' => {}
1158 b'E' => {
1161 let slot = self.front()?;
1162 let mut inner = slot.inner.borrow_mut();
1163 if inner.error.is_none() {
1164 inner.error = Some(Error::new(
1165 ErrorKind::TooLarge,
1166 format!(
1167 "the server's error for this statement was a {len}-byte \
1168 message, more than max_result_size allows, so it was \
1169 thrown away; raise Config::max_result_size to read it"
1170 ),
1171 ));
1172 }
1173 }
1174 _ => {
1175 return Err(Error::new(
1176 ErrorKind::Protocol,
1177 format!(
1178 "the server sent a {:?} message of {len} bytes, more than \
1179 max_result_size allows, so the connection was closed; raise \
1180 Config::max_result_size if the server's messages are this large",
1181 tag as char
1182 ),
1183 ))
1184 }
1185 }
1186 buf.skip(len);
1187 continue;
1188 }
1189 let Some(body) = buf.body(len) else {
1190 return Ok(());
1191 };
1192 self.handle(tag, buf.bytes(body))?;
1193 buf.consume(len);
1194 }
1195 Ok(())
1196 }
1197
1198 fn front(&self) -> Result<Rc<Slot>, Error> {
1199 self.state.borrow().queue.front().cloned().ok_or_else(|| {
1200 Error::protocol("the server sent a reply to a request that was never made")
1201 })
1202 }
1203
1204 fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
1205 let msg = parse_backend(tag, body)?;
1206 match msg {
1207 Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
1208 Backend::ParameterStatus { name, value } => {
1209 if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
1210 return Err(Error::closed(format!(
1211 "the session's client_encoding was changed to {value}; giong-postgres \
1212 reads and writes UTF-8 only, so the connection was closed"
1213 )));
1214 }
1215 let mut st = self.state.borrow_mut();
1216 match st.server_params.iter_mut().find(|(n, _)| n == name) {
1217 Some(entry) => entry.1 = value.to_owned(),
1218 None => st.server_params.push((name.to_owned(), value.to_owned())),
1219 }
1220 return Ok(());
1221 }
1222 Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
1223 let db = DbError::parse(fields)?;
1226 return Err(Error::with_db(
1227 ErrorKind::Closed,
1228 "the server closed the connection",
1229 db,
1230 ));
1231 }
1232 _ => {}
1233 }
1234 let slot = loop {
1235 let slot = self.front()?;
1236 if slot.batch.get() != Role::Alone
1237 && matches!(
1238 msg,
1239 Backend::CommandComplete(_)
1240 | Backend::ErrorResponse(_)
1241 | Backend::ReadyForQuery(_)
1242 )
1243 {
1244 if self.handle_batched(slot, &msg)? {
1245 continue;
1248 }
1249 return Ok(());
1250 }
1251 break slot;
1252 };
1253 let mut inner = slot.inner.borrow_mut();
1254 match msg {
1255 Backend::BindComplete => inner.bound = true,
1256 Backend::ParseComplete
1257 | Backend::CloseComplete
1258 | Backend::NoData
1259 | Backend::PortalSuspended
1260 | Backend::EmptyQueryResponse => {}
1261 Backend::ParameterDescription(types) => inner.params = Some(types),
1262 Backend::RowDescription(fields) => {
1263 if matches!(slot.kind, Kind::Prepare { .. }) {
1264 inner.columns = Some(
1265 fields
1266 .iter()
1267 .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
1268 .collect(),
1269 );
1270 }
1271 }
1272 Backend::DataRow(body) => match &slot.kind {
1273 Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
1274 let limit = self.config.max_result_size;
1275 inner.rows.push(body, stmt.columns.len(), limit)?;
1276 }
1277 _ => {}
1278 },
1279 Backend::CommandComplete(tag) => {
1280 if tag == "PREPARE" {
1281 self.user_prepared.set(true);
1282 }
1283 inner.tag = Some(tag.to_owned());
1284 }
1285 Backend::ErrorResponse(fields) => {
1286 if inner.error.is_none() {
1287 inner.error = Some(self.db_error(fields, true)?);
1288 }
1289 }
1290 Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
1291 if inner.error.is_none() {
1292 inner.error = Some(Error::conversion(
1293 "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
1294 was thrown away",
1295 ));
1296 }
1297 }
1298 Backend::CopyInResponse | Backend::CopyBothResponse => {
1299 return Err(Error::closed(
1300 "the statement started COPY FROM STDIN or replication, which giong-postgres \
1301 does not support yet; the connection was closed",
1302 ));
1303 }
1304 Backend::ReadyForQuery(status) => {
1305 let left_open = slot.shared && status != b'I';
1309 if left_open {
1310 inner.error = Some(Error::closed(LEFT_OPEN));
1311 }
1312 let reset_failed = match &inner.error {
1313 Some(e) if slot.close_on_error => Some(Error::closed(format!(
1314 "resetting the session of a connection that went back to the pool \
1315 failed, so it was closed rather than reused: {e}"
1316 ))),
1317 _ => None,
1318 };
1319 inner.status = status;
1320 drop(inner);
1321 let idle = {
1322 let mut st = self.state.borrow_mut();
1323 st.status = status;
1324 st.queue.pop_front();
1325 self.head_since
1326 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1327 st.queue.is_empty()
1328 };
1329 self.complete(&slot);
1330 if left_open {
1331 return Err(Error::closed(LEFT_OPEN));
1333 }
1334 if let Some(e) = reset_failed {
1335 return Err(e);
1336 }
1337 if idle {
1338 self.wake_idle();
1339 }
1340 }
1341 other => {
1342 return Err(Error::protocol(format!(
1343 "the server sent an unexpected {:?} message ({other:?})",
1344 tag as char
1345 )))
1346 }
1347 }
1348 Ok(())
1349 }
1350
1351 fn db_error(&self, fields: &[u8], may_retire: bool) -> Result<Error, Error> {
1353 let db = DbError::parse(fields)?;
1354 if may_retire && db.code() == "25006" && self.on_standby() {
1355 self.retire.set(true);
1356 }
1357 let note = (db.code() == "57014" && db.message().contains("statement timeout")).then(
1360 || match self.config.statement_timeout {
1361 Some(limit) => format!(
1362 "the statement ran longer than the statement timeout ({limit:?}; \
1363 Config::statement_timeout)"
1364 ),
1365 None => "the statement ran longer than the server's statement_timeout".to_owned(),
1366 },
1367 );
1368 Ok(Error::from_db(db, note))
1369 }
1370
1371 #[cold]
1375 #[inline(never)]
1376 fn handle_batched(&self, slot: Rc<Slot>, msg: &Backend<'_>) -> Result<bool, Error> {
1379 let mut inner = slot.inner.borrow_mut();
1380 match *msg {
1381 Backend::CommandComplete(command) => {
1382 inner.tag = Some(command.to_owned());
1383 }
1384 Backend::ErrorResponse(fields) => {
1385 let error = self.db_error(fields, false)?;
1387 self.state.borrow_mut().batch_failed = true;
1388 match slot.batch.get() {
1389 Role::End => return Ok(false),
1392 Role::Guard if error.server_code() == Some("26000") => {
1396 self.state.borrow_mut().read_only_prepared = false;
1397 }
1398 _ => {}
1399 }
1400 if matches!(error.server_code(), Some("55P03" | "40P01" | "40001"))
1401 && slot.batch.get() == Role::Member
1402 {
1403 if let Kind::Execute { .. } = &slot.kind {
1408 inner.alone = true;
1409 }
1410 }
1411 if error.server_code() == Some("25006") {
1412 if let Kind::Execute { stmt } = &slot.kind {
1414 stmt.writes.set(true);
1415 inner.alone = true;
1416 }
1417 }
1418 inner.error = Some(error);
1419 }
1420 Backend::ReadyForQuery(status) if slot.batch.get() == Role::End => {
1421 inner.status = status;
1424 drop(inner);
1425 let (idle, held, failed) = {
1426 let mut st = self.state.borrow_mut();
1427 st.status = status;
1428 st.queue.pop_front();
1429 st.extra -= 1;
1430 self.head_since
1431 .set((!st.queue.is_empty()).then(giong::time::Instant::now));
1432 let failed = std::mem::take(&mut st.batch_failed);
1433 (st.queue.is_empty(), std::mem::take(&mut st.held), failed)
1434 };
1435 for member in &held {
1436 if failed {
1437 let mut inner = member.inner.borrow_mut();
1438 if inner.error.is_none() {
1439 inner.error = Some(Error::new(
1442 ErrorKind::Closed,
1443 "another statement of this one's batch failed, so the batch \
1444 was rolled back",
1445 ));
1446 inner.alone = matches!(member.kind, Kind::Execute { .. });
1447 }
1448 }
1449 self.complete(member);
1450 }
1451 self.complete(&slot);
1452 if idle {
1453 self.wake_idle();
1454 }
1455 return Ok(false);
1456 }
1457 Backend::ReadyForQuery(_) => {
1458 inner.error = Some(Error::new(
1461 ErrorKind::Closed,
1462 "a statement before this one in its batch failed, so the server skipped it",
1463 ));
1464 inner.alone = matches!(slot.kind, Kind::Execute { .. });
1465 drop(inner);
1466 self.finish_member(&slot);
1467 return Ok(true);
1468 }
1469 _ => unreachable!("only these three come here"),
1470 }
1471 drop(inner);
1472 self.finish_member(&slot);
1473 Ok(false)
1474 }
1475
1476 fn complete(&self, slot: &Rc<Slot>) {
1478 let mut inner = slot.inner.borrow_mut();
1479 let error = inner.error.take();
1480 let outcome = match &slot.kind {
1481 Kind::Prepare { sql, name, cached } => {
1482 let result = match error {
1483 Some(e) => Err(e),
1484 None => match inner.params.take() {
1485 Some(params) => Ok(Rc::new(Statement {
1486 sql: sql.clone(),
1487 name: name.clone(),
1488 params,
1489 columns: inner.columns.take().unwrap_or_default().into(),
1490 conn: (!*cached).then(|| self.weak.clone()),
1491 closed: Cell::new(false),
1492 writes: Cell::new(false),
1493 })),
1494 None => Err(Error::protocol("the server did not describe the statement")),
1495 },
1496 };
1497 if *cached {
1498 self.settle_cache(sql, slot, &result);
1499 }
1500 result.map(Response::Statement)
1501 }
1502 Kind::Execute { stmt } => match error {
1503 Some(e) => {
1504 let stale = self.forget_if_stale(stmt, &e);
1505 inner.retry = stale && !inner.bound && inner.status == b'I';
1508 Err(e)
1509 }
1510 None if inner.rows.overflow => Err(Error::new(
1511 ErrorKind::TooLarge,
1512 format!(
1513 "the result is larger than max_result_size ({} bytes); add a LIMIT or \
1514 select fewer columns, or raise Config::max_result_size",
1515 self.config.max_result_size
1516 ),
1517 )),
1518 None => {
1519 let rows = std::mem::take(&mut inner.rows);
1520 Ok(Response::Rows(
1521 rows.finish(stmt.columns.clone()),
1522 inner.tag.take(),
1523 ))
1524 }
1525 },
1526 Kind::Simple => match error {
1527 Some(e) => Err(e),
1528 None => Ok(Response::Done(inner.tag.take())),
1529 },
1530 };
1531 inner.outcome = Some(outcome);
1532 for w in inner.wakers.drain(..) {
1533 w.wake();
1534 }
1535 }
1536
1537 fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
1542 if !e.db().is_some_and(is_stale) {
1543 return false;
1544 }
1545 let mut st = self.state.borrow_mut();
1546 if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
1547 {
1548 st.cache.remove(&stmt.sql);
1549 }
1550 true
1551 }
1552
1553 fn on_standby(&self) -> bool {
1556 let st = self.state.borrow();
1557 st.server_params
1558 .iter()
1559 .find(|(n, _)| n == "in_hot_standby")
1560 .map_or(true, |(_, v)| v != "off")
1561 }
1562
1563 fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
1566 let mut st = self.state.borrow_mut();
1567 let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
1568 if !ours {
1569 return;
1570 }
1571 let Ok(stmt) = result else {
1572 st.cache.remove(sql);
1573 return;
1574 };
1575 st.clock += 1;
1576 let used = st.clock;
1577 st.cache.insert(
1578 sql.clone(),
1579 Entry::Ready {
1580 stmt: stmt.clone(),
1581 used,
1582 },
1583 );
1584 while st.cache.len() > self.config.statement_cache {
1585 let victim = st
1587 .cache
1588 .iter()
1589 .filter_map(|(k, e)| match e {
1590 Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
1591 Some((*used, k.clone()))
1592 }
1593 _ => None,
1594 })
1595 .min();
1596 let Some((_, key)) = victim else { break };
1597 if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
1598 let _ = protocol::close_statement(&mut st.out, &stmt.name);
1601 st.batch = None;
1603 }
1604 }
1605 }
1606}
1607
1608async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
1609 let err = loop {
1610 if let Err(e) = conn.process(&mut buf) {
1611 break e;
1612 }
1613 match conn.stream.read_into(&mut buf).await {
1614 Ok(0) => {
1615 let closing = conn.state.borrow().closing;
1616 break Error::closed(if closing {
1617 "the connection was closed"
1618 } else {
1619 "the server closed the connection"
1620 });
1621 }
1622 Ok(_) => {}
1623 Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
1624 }
1625 };
1626 conn.fail(err);
1627}
1628
1629async fn write_loop(conn: Rc<Conn>) {
1630 let mut spare = Vec::new();
1631 loop {
1632 let next = poll_fn(|cx| {
1633 let mut st = conn.state.borrow_mut();
1634 if st.broken.is_some() {
1635 return Poll::Ready(None);
1636 }
1637 if !st.out.is_empty() {
1638 st.batch = None;
1640 return Poll::Ready(Some(std::mem::replace(
1641 &mut st.out,
1642 std::mem::take(&mut spare),
1643 )));
1644 }
1645 if st.closing {
1646 return Poll::Ready(None);
1647 }
1648 st.writer = Some(cx.waker().clone());
1649 Poll::Pending
1650 })
1651 .await;
1652 let Some(data) = next else { break };
1653 let (written, mut data) = conn.stream.write_all(data).await;
1654 if let Err(e) = written {
1655 conn.fail(Error::io(
1656 ErrorKind::Closed,
1657 "writing to the server failed",
1658 e,
1659 ));
1660 return;
1661 }
1662 data.clear();
1663 spare = data;
1664 }
1665 if conn.state.borrow().closing {
1666 conn.stream.shutdown(Shutdown::Write);
1667 }
1668}
1669
1670pub struct Transaction<'a> {
1686 client: &'a mut Client,
1687 done: bool,
1688}
1689
1690impl Transaction<'_> {
1691 pub async fn commit(mut self) -> Result<(), Error> {
1702 if self.client.conn.tx.get() == Tx::Abandoned {
1703 return Err(abandoned());
1705 }
1706 self.end();
1707 let slot = self
1708 .client
1709 .conn
1710 .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
1711 match (Wait { slot }).await? {
1712 Response::Done(Some(tag)) if tag == "ROLLBACK" => Err(Error::with_sqlstate(
1713 "25P02",
1714 "the transaction was rolled back instead of committed, because a statement in \
1715 it failed earlier",
1716 )),
1717 _ => Ok(()),
1718 }
1719 }
1720
1721 pub async fn rollback(mut self) -> Result<(), Error> {
1726 self.end();
1727 self.client.batch_execute("ROLLBACK").await
1728 }
1729
1730 fn end(&mut self) {
1732 self.done = true;
1733 self.client.conn.tx.set(Tx::None);
1734 }
1735}
1736
1737impl Deref for Transaction<'_> {
1738 type Target = Client;
1739
1740 fn deref(&self) -> &Client {
1741 self.client
1742 }
1743}
1744
1745impl Drop for Transaction<'_> {
1746 fn drop(&mut self) {
1747 if !self.done {
1748 self.end();
1749 self.client.send_and_forget("ROLLBACK");
1750 }
1751 }
1752}
1753
1754impl std::fmt::Debug for Transaction<'_> {
1755 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1756 f.debug_struct("Transaction")
1757 .field("client", &self.client)
1758 .finish()
1759 }
1760}
1761
1762#[derive(Clone)]
1769pub struct CancelToken {
1770 config: Config,
1773 key: Option<(i32, i32)>,
1774 lease: Option<Arc<Lease>>,
1777}
1778
1779#[derive(Default)]
1783pub(crate) struct Lease(AtomicU32);
1784
1785impl Lease {
1786 const ENDED: u32 = 1 << 31;
1788
1789 fn start_cancel(&self) -> bool {
1791 let mut v = self.0.load(Ordering::Acquire);
1792 while v & Self::ENDED == 0 {
1793 match self
1794 .0
1795 .compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire)
1796 {
1797 Ok(_) => return true,
1798 Err(now) => v = now,
1799 }
1800 }
1801 false
1802 }
1803
1804 fn finish_cancel(&self) {
1806 self.0.fetch_sub(1, Ordering::AcqRel);
1807 }
1808
1809 fn is_ended(&self) -> bool {
1810 self.0.load(Ordering::Acquire) & Self::ENDED != 0
1811 }
1812
1813 fn end(&self) -> bool {
1816 self.0.fetch_or(Self::ENDED, Ordering::AcqRel) & !Self::ENDED != 0
1817 }
1818}
1819
1820impl CancelToken {
1821 pub async fn cancel(&self) -> Result<(), Error> {
1831 let gone = || {
1832 Error::closed(
1833 "the connection this cancel token was taken from has gone back to its pool, \
1834 where other tasks use it, so nothing was sent; take a new token from the next \
1835 connection",
1836 )
1837 };
1838 if self.lease.as_ref().is_some_and(|lease| lease.is_ended()) {
1839 return Err(gone());
1840 }
1841 let key = self.key.ok_or_else(|| {
1842 Error::new(
1843 ErrorKind::Connect,
1844 "the server gave this connection no cancel key (a connection pooler may be in \
1845 between), so it cannot be cancelled",
1846 )
1847 })?;
1848 let Some(lease) = &self.lease else {
1849 return connect::cancel(&self.config, key).await;
1850 };
1851 if !lease.start_cancel() {
1856 return Err(gone());
1857 }
1858 let sent = connect::cancel(&self.config, key).await;
1859 lease.finish_cancel();
1860 sent
1861 }
1862}
1863
1864impl std::fmt::Debug for CancelToken {
1865 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1866 f.debug_struct("CancelToken")
1867 .field("server", &self.config.target())
1868 .finish_non_exhaustive()
1869 }
1870}
1871
1872#[cfg(test)]
1873mod tests {
1874 use super::{is_stale, rows_affected};
1875 use crate::error::DbError;
1876
1877 fn db_error(fields: &[(u8, &str)]) -> DbError {
1878 let mut body = Vec::new();
1879 for (field, value) in fields {
1880 body.push(*field);
1881 body.extend_from_slice(value.as_bytes());
1882 body.push(0);
1883 }
1884 body.push(0);
1885 DbError::parse(&body).unwrap()
1886 }
1887
1888 #[test]
1889 fn a_stale_plan_is_recognised_in_any_language() {
1890 let german = db_error(&[
1891 (b'S', "FEHLER"),
1892 (b'V', "ERROR"),
1893 (b'C', "0A000"),
1894 (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
1895 (b'R', "RevalidateCachedQuery"),
1896 ]);
1897 assert!(is_stale(&german));
1898 assert_eq!(german.severity(), "ERROR");
1899 let english = db_error(&[
1901 (b'C', "0A000"),
1902 (b'M', "cached plan must not change result type"),
1903 ]);
1904 assert!(is_stale(&english));
1905 let other = db_error(&[
1907 (b'C', "0A000"),
1908 (b'M', "nicht unterstützt"),
1909 (b'R', "transformSelectStmt"),
1910 ]);
1911 assert!(!is_stale(&other));
1912 assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
1913 }
1914
1915 #[test]
1916 fn command_tags_give_row_counts() {
1917 assert_eq!(rows_affected(Some("INSERT 0 5")), 5);
1918 assert_eq!(rows_affected(Some("UPDATE 3")), 3);
1919 assert_eq!(rows_affected(Some("SELECT 12")), 12);
1920 assert_eq!(rows_affected(Some("CREATE TABLE")), 0);
1921 assert_eq!(rows_affected(None), 0);
1922 }
1923}