1use std::cell::{Cell, RefCell};
4use std::collections::VecDeque;
5use std::future::{poll_fn, Future};
6use std::ops::{Deref, DerefMut};
7use std::pin::pin;
8use std::rc::{Rc, Weak};
9use std::task::{Poll, Waker};
10use std::time::Duration;
11
12use giong::time::Instant;
13
14use crate::client::{Client, Transaction};
15use crate::config::Config;
16use crate::error::{Error, ErrorKind};
17use crate::row::Row;
18use crate::types::ToSql;
19
20const STALLED: Duration = Duration::from_millis(5);
23
24const MAX_PIPELINE: usize = 1024;
27
28#[derive(Clone)]
108pub struct Pool {
109 inner: Rc<Inner>,
110}
111
112struct Inner {
113 config: Config,
114 max_size: usize,
115 wait_timeout: Duration,
116 idle_timeout: Duration,
117 max_lifetime: Duration,
118 state: Rc<RefCell<State>>,
119 _observed: Rc<Observed>,
122}
123
124impl Drop for Inner {
125 fn drop(&mut self) {
126 let reaper = {
128 let mut st = self.state.borrow_mut();
129 st.stopped = true;
130 st.reaper_waker.take()
131 };
132 if let Some(w) = reaper {
133 w.wake();
134 }
135 }
136}
137
138struct Observed {
141 name: String,
142 max_size: usize,
143 state: Rc<RefCell<State>>,
144}
145
146impl giong::observe::Source for Observed {
147 fn kind(&self) -> &'static str {
148 "postgres pool"
149 }
150
151 fn name(&self) -> String {
152 self.name.clone()
153 }
154
155 fn stats(&self) -> Vec<(&'static str, u64)> {
156 let s = stats_of(&self.state.borrow());
157 let n = |v: usize| v as u64;
158 vec![
159 ("max_size", n(self.max_size)),
160 ("connections", n(s.connections)),
161 ("taken", n(s.taken)),
162 ("connecting", n(s.connecting)),
163 ("in_flight", n(s.in_flight)),
164 ("waiting", n(s.waiting)),
165 ("opened", s.opened),
166 ("connect_errors", s.connect_errors),
167 ("timeouts", s.timeouts),
168 ("recycled", s.recycled),
169 ]
170 }
171}
172
173fn stats_of(st: &State) -> PoolStats {
174 PoolStats {
175 connections: st.shared.len() + st.taken,
176 taken: st.taken,
177 connecting: st.connecting,
178 in_flight: st.shared.iter().map(|m| m.client.in_flight()).sum(),
179 waiting: st.waiting,
180 opened: st.opened,
181 connect_errors: st.connect_errors,
182 timeouts: st.timeouts,
183 recycled: st.recycled,
184 }
185}
186
187#[derive(Default)]
188struct State {
189 shared: Vec<Member>,
191 taken: usize,
192 connecting: usize,
193 waiting: usize,
194 shared_waiters: VecDeque<Waker>,
197 get_waiters: Vec<Waker>,
200 queue: VecDeque<u64>,
203 next_ticket: u64,
204 to_wake: Vec<Waker>,
206 reaper: bool,
208 reaper_waker: Option<Waker>,
209 stopped: bool,
211 opened: u64,
212 connect_errors: u64,
213 timeouts: u64,
214 recycled: u64,
215}
216
217struct Member {
219 client: Rc<Client>,
220 draining: bool,
222 used: Instant,
224 expires: Instant,
226}
227
228impl Member {
229 fn is_free(&self) -> bool {
231 Rc::strong_count(&self.client) == 1
232 }
233
234 fn is_retiring(&self, now: Instant) -> bool {
236 now >= self.expires || self.client.should_retire()
237 }
238}
239
240impl State {
241 fn room(&self, max: usize) -> bool {
242 self.shared.len() + self.taken + self.connecting < max
243 }
244
245 fn wake_all(&mut self) {
247 let shared = std::mem::take(&mut self.shared_waiters);
248 self.to_wake.extend(shared);
249 self.to_wake.append(&mut self.get_waiters);
250 }
251
252 fn wake_gets(&mut self) {
254 let gets = std::mem::take(&mut self.get_waiters);
255 self.to_wake.extend(gets);
256 }
257
258 fn wake_one_shared(&mut self) {
260 if let Some(w) = self.shared_waiters.pop_front() {
261 self.to_wake.push(w);
262 }
263 }
264
265 fn sweep(&mut self, now: Instant, idle_timeout: Duration) {
268 let before = self.shared.len();
269 let mut recycled = 0;
270 self.shared.retain(|m| {
271 if m.client.is_closed() {
272 return false;
273 }
274 let stale = m.is_free()
275 && (m.is_retiring(now)
276 || (m.client.in_flight() == 0
277 && now.saturating_duration_since(m.used) >= idle_timeout));
278 recycled += u64::from(stale);
279 !stale
280 });
281 self.recycled += recycled;
282 if self.shared.len() != before {
283 self.wake_all();
285 }
286 }
287
288 fn rebalance(&mut self, max: usize) {
292 let target = match self.queue.len() {
293 0 => 0,
294 n if max == 1 => n.min(self.shared.len()),
295 n => n.min(self.shared.len().saturating_sub(1)),
296 };
297 let mut draining = self.shared.iter().filter(|m| m.draining).count();
298 while draining < target {
299 let next = self
301 .shared
302 .iter_mut()
303 .filter(|m| !m.draining)
304 .min_by_key(|m| (Rc::strong_count(&m.client), m.client.in_flight()));
305 let Some(m) = next else { break };
306 m.draining = true;
307 draining += 1;
308 }
309 if draining > target {
310 for m in self.shared.iter_mut().filter(|m| m.draining) {
311 if draining == target {
312 break;
313 }
314 m.draining = false;
315 draining -= 1;
316 }
317 self.wake_all();
318 }
319 }
320
321 fn remove_ticket(&mut self, ticket: u64) {
322 if let Some(i) = self.queue.iter().position(|&t| t == ticket) {
323 self.queue.remove(i);
324 }
325 }
326}
327
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330#[non_exhaustive]
331pub struct PoolStats {
332 pub connections: usize,
334 pub taken: usize,
336 pub connecting: usize,
338 pub in_flight: usize,
340 pub waiting: usize,
342 pub opened: u64,
344 pub connect_errors: u64,
346 pub timeouts: u64,
348 pub recycled: u64,
353}
354
355enum Decision<T> {
356 Ready(T),
357 Connect,
358 Wait,
359}
360
361#[derive(Clone, Copy, PartialEq, Eq)]
363enum Waiter {
364 Shared,
365 Get,
366}
367
368struct Connecting<'a>(&'a Pool);
370
371impl Drop for Connecting<'_> {
372 fn drop(&mut self) {
373 let mut st = self.0.inner.state.borrow_mut();
374 st.connecting -= 1;
375 st.wake_all();
376 drop(st);
377 self.0.flush_wakes();
378 }
379}
380
381struct Waiting<'a> {
385 pool: &'a Pool,
386 kind: Waiter,
387 served: bool,
388}
389
390impl Drop for Waiting<'_> {
391 fn drop(&mut self) {
392 let mut st = self.pool.inner.state.borrow_mut();
393 st.waiting -= 1;
394 if !self.served && self.kind == Waiter::Shared {
395 st.wake_one_shared();
396 }
397 drop(st);
398 self.pool.flush_wakes();
399 }
400}
401
402struct Ticket<'a> {
404 pool: &'a Pool,
405 id: Cell<Option<u64>>,
406}
407
408impl Drop for Ticket<'_> {
409 fn drop(&mut self) {
410 if let Some(id) = self.id.take() {
411 let mut st = self.pool.inner.state.borrow_mut();
412 st.remove_ticket(id);
413 st.rebalance(self.pool.inner.max_size);
414 st.wake_gets();
416 drop(st);
417 self.pool.flush_wakes();
418 }
419 }
420}
421
422impl Pool {
423 pub fn new(config: Config, max_size: usize) -> Self {
433 assert!(
434 max_size > 0,
435 "a pool needs room for at least one connection"
436 );
437 let state = Rc::new(RefCell::default());
438 let observed = Rc::new(Observed {
439 name: config.describe(),
440 max_size,
441 state: Rc::clone(&state),
442 });
443 giong::observe::register_rc(&observed);
444 Self {
445 inner: Rc::new(Inner {
446 config,
447 max_size,
448 wait_timeout: Duration::from_secs(5),
449 idle_timeout: Duration::from_secs(10 * 60),
450 max_lifetime: Duration::from_secs(30 * 60),
451 state,
452 _observed: observed,
453 }),
454 }
455 }
456
457 fn settings(&mut self, what: &str) -> &mut Inner {
458 Rc::get_mut(&mut self.inner)
459 .unwrap_or_else(|| panic!("set the {what} before cloning the pool"))
460 }
461
462 pub fn wait_timeout(mut self, timeout: Duration) -> Self {
472 self.settings("wait timeout").wait_timeout = timeout;
473 self
474 }
475
476 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
485 self.settings("idle timeout").idle_timeout = timeout;
486 self
487 }
488
489 pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
500 self.settings("maximum lifetime").max_lifetime = lifetime;
501 self
502 }
503
504 pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
509 refuse_on_shared(sql, false)?;
510 let client = self.shared().await?;
511 client.query(sql, params).await
512 }
513
514 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
518 refuse_on_shared(sql, false)?;
519 let client = self.shared().await?;
520 client.query_one(sql, params).await
521 }
522
523 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
527 refuse_on_shared(sql, false)?;
528 let client = self.shared().await?;
529 client.query_opt(sql, params).await
530 }
531
532 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
536 refuse_on_shared(sql, false)?;
537 let client = self.shared().await?;
538 client.execute(sql, params).await
539 }
540
541 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
553 refuse_on_shared(sql, true)?;
554 let client = self.shared().await?;
555 client.batch_execute(sql).await
556 }
557
558 pub async fn get(&self) -> Result<PooledClient, Error> {
575 let ticket = Ticket {
576 pool: self,
577 id: Cell::new(None),
578 };
579 let max = self.inner.max_size;
580 let taken = self
581 .acquire(Waiter::Get, |st, now| {
582 let mine = ticket.id.get();
583 let turn = st.queue.front().map_or(true, |&t| Some(t) == mine);
584 if turn {
585 let free = st
589 .shared
590 .iter()
591 .enumerate()
592 .filter(|(_, m)| {
593 m.is_free()
594 && !m.is_retiring(now)
595 && (m.client.in_flight() == 0
596 || m.client.waiting_for(now) <= STALLED)
597 })
598 .min_by_key(|(_, m)| (m.client.in_flight() > 0, !m.draining))
599 .map(|(i, _)| i);
600 let decision = if let Some(i) = free {
601 let m = st.shared.swap_remove(i);
602 st.taken += 1;
603 let Ok(client) = Rc::try_unwrap(m.client) else {
604 unreachable!("checked: nobody else holds it")
605 };
606 Some(Decision::Ready((client, m.expires)))
607 } else if st.room(max) {
608 st.connecting += 1;
609 Some(Decision::Connect)
610 } else {
611 None
612 };
613 if let Some(decision) = decision {
614 if let Some(id) = ticket.id.take() {
615 st.remove_ticket(id);
616 }
617 st.rebalance(max);
618 st.wake_gets();
620 return decision;
621 }
622 }
623 if mine.is_none() {
624 let id = st.next_ticket;
625 st.next_ticket += 1;
626 st.queue.push_back(id);
627 ticket.id.set(Some(id));
628 }
629 st.rebalance(max);
630 Decision::Wait
631 })
632 .await?;
633 let (client, expires) = match taken {
634 Ok(taken) => taken,
635 Err(new) => {
636 self.inner.state.borrow_mut().taken += 1;
637 (new, self.expiry())
638 }
639 };
640 client.set_shared(false);
641 client.begin_lease();
642 Ok(PooledClient {
643 requests: client.requests(),
644 client: Some(client),
645 expires,
646 pool: self.clone(),
647 })
648 }
649
650 pub fn stats(&self) -> PoolStats {
652 stats_of(&self.inner.state.borrow())
653 }
654
655 fn expiry(&self) -> Instant {
658 use std::hash::{BuildHasher, Hasher};
659 let life = self.inner.max_lifetime;
660 let seed = std::collections::hash_map::RandomState::new()
663 .build_hasher()
664 .finish();
665 let jitter = life / 10 * u32::try_from(seed % 1000).unwrap_or(0) / 1000;
666 Instant::now() + (life - jitter)
667 }
668
669 async fn shared(&self) -> Result<Lent<'_>, Error> {
678 let max = self.inner.max_size;
679 let client = self
680 .acquire(Waiter::Shared, |st, now| {
681 let room = st.room(max);
682 let usable = |m: &Member| {
687 let users = Rc::strong_count(&m.client) - 1;
688 !m.draining
689 && !m.is_retiring(now)
690 && users.max(m.client.in_flight()) < MAX_PIPELINE
691 };
692 let best = st
694 .shared
695 .iter()
696 .enumerate()
697 .filter(|(_, m)| usable(m) && m.client.waiting_for(now) <= STALLED)
698 .min_by_key(|(_, m)| Rc::strong_count(&m.client))
699 .map(|(i, m)| (i, m.is_free()));
700 let pick = match best {
701 Some((i, free)) if free || !room => Some(i),
702 _ if room => {
703 st.connecting += 1;
704 return Decision::Connect;
705 }
706 _ => st
710 .shared
711 .iter()
712 .enumerate()
713 .filter(|(_, m)| usable(m))
714 .min_by_key(|(_, m)| m.client.waiting_for(now))
715 .map(|(i, _)| i),
716 };
717 match pick {
718 Some(i) => {
719 let m = &mut st.shared[i];
720 m.used = now;
721 Decision::Ready(m.client.clone())
722 }
723 None => Decision::Wait,
724 }
725 })
726 .await?;
727 let client = match client {
728 Ok(c) => c,
729 Err(new) => {
730 new.set_shared(true);
731 let c = Rc::new(new);
732 let member = Member {
733 client: c.clone(),
734 draining: false,
735 used: Instant::now(),
736 expires: self.expiry(),
737 };
738 let mut st = self.inner.state.borrow_mut();
739 st.shared.push(member);
740 st.wake_all();
742 drop(st);
743 self.flush_wakes();
744 c
745 }
746 };
747 Ok(Lent {
748 pool: self,
749 client: Some(client),
750 })
751 }
752
753 fn flush_wakes(&self) {
756 let wakers = std::mem::take(&mut self.inner.state.borrow_mut().to_wake);
757 for w in wakers {
758 w.wake();
759 }
760 }
761
762 fn start_reaper(&self, st: &mut State) {
764 if st.reaper {
765 return;
766 }
767 st.reaper = true;
768 let state = Rc::downgrade(&self.inner.state);
769 let idle_timeout = self.inner.idle_timeout;
770 let period = (self.inner.idle_timeout.min(self.inner.max_lifetime) / 4)
771 .clamp(Duration::from_millis(50), Duration::from_secs(30));
772 giong::spawn(reap(state, idle_timeout, period));
773 }
774
775 async fn acquire<T>(
778 &self,
779 kind: Waiter,
780 mut decide: impl FnMut(&mut State, Instant) -> Decision<T>,
781 ) -> Result<Result<T, Client>, Error> {
782 let deadline = Instant::now() + self.inner.wait_timeout;
783 let mut waiting: Option<Waiting<'_>> = None;
784 loop {
785 let decision = {
786 let mut st = self.inner.state.borrow_mut();
787 let now = Instant::now();
788 st.sweep(now, self.inner.idle_timeout);
789 let d = decide(&mut st, now);
790 if matches!(d, Decision::Wait) && waiting.is_none() {
791 st.waiting += 1;
792 }
793 d
794 };
795 self.flush_wakes();
796 match decision {
797 Decision::Ready(c) => {
798 if let Some(w) = &mut waiting {
799 w.served = true;
800 }
801 return Ok(Ok(c));
802 }
803 Decision::Connect => {
804 if let Some(w) = &mut waiting {
805 w.served = true;
806 }
807 drop(waiting);
808 let _connecting = Connecting(self);
809 let result = Client::connect(&self.inner.config).await;
810 let mut st = self.inner.state.borrow_mut();
811 return match result {
812 Ok(client) => {
813 st.opened += 1;
814 self.start_reaper(&mut st);
815 Ok(Err(client))
816 }
817 Err(e) => {
818 st.connect_errors += 1;
819 Err(e)
820 }
821 };
822 }
823 Decision::Wait => {
824 if waiting.is_none() {
825 waiting = Some(Waiting {
826 pool: self,
827 kind,
828 served: false,
829 });
830 }
831 let mut registered = false;
832 let woken = poll_fn(|cx| {
833 if registered {
834 return Poll::Ready(());
835 }
836 registered = true;
837 let mut st = self.inner.state.borrow_mut();
838 match kind {
839 Waiter::Shared => st.shared_waiters.push_back(cx.waker().clone()),
840 Waiter::Get => st.get_waiters.push(cx.waker().clone()),
841 }
842 for m in &st.shared {
847 if m.is_free() && m.client.in_flight() > 0 {
848 m.client.wake_when_idle(cx.waker());
849 }
850 }
851 Poll::Pending
852 });
853 let left = deadline.saturating_duration_since(Instant::now());
854 if giong::time::timeout(left, woken).await.is_err() {
855 let mut st = self.inner.state.borrow_mut();
856 st.timeouts += 1;
857 let (taken, max) = (st.taken, self.inner.max_size);
858 drop(st);
859 let why = if taken == max {
860 format!("all {max} are taken with Pool::get")
861 } else {
862 format!("all {max} are taken or busy ({taken} taken with Pool::get)")
863 };
864 return Err(Error::new(
865 ErrorKind::PoolTimeout,
866 format!(
867 "no connection to {} became free within {:?}: {why}. Raise the \
868 pool's max_size (the server's max_connections allowing), look \
869 for transactions or connections from Pool::get held too long, \
870 or raise Pool::wait_timeout",
871 self.inner.config.target(),
872 self.inner.wait_timeout,
873 ),
874 ));
875 }
876 }
877 }
878 }
879 }
880}
881
882async fn reap(state: Weak<RefCell<State>>, idle_timeout: Duration, period: Duration) {
884 loop {
885 let mut sleep = pin!(giong::time::sleep(period));
886 let stopped = poll_fn(|cx| {
887 let Some(state) = state.upgrade() else {
888 return Poll::Ready(true);
889 };
890 let mut st = state.borrow_mut();
891 if st.stopped {
892 return Poll::Ready(true);
893 }
894 st.reaper_waker = Some(cx.waker().clone());
895 drop(st);
896 sleep.as_mut().poll(cx).map(|()| false)
897 })
898 .await;
899 if stopped {
900 return;
901 }
902 let Some(state) = state.upgrade() else { return };
903 let wakers = {
904 let mut st = state.borrow_mut();
905 st.sweep(Instant::now(), idle_timeout);
906 std::mem::take(&mut st.to_wake)
907 };
908 for w in wakers {
909 w.wake();
910 }
911 }
912}
913
914struct Lent<'a> {
919 pool: &'a Pool,
920 client: Option<Rc<Client>>,
921}
922
923impl Deref for Lent<'_> {
924 type Target = Client;
925
926 fn deref(&self) -> &Client {
927 self.client.as_ref().expect("present until dropped")
928 }
929}
930
931impl Drop for Lent<'_> {
932 fn drop(&mut self) {
933 let client = self.client.take().expect("present until dropped");
934 let free = Rc::strong_count(&client) == 2;
936 drop(client);
937 let mut st = self.pool.inner.state.borrow_mut();
938 st.wake_one_shared();
939 if free {
940 if st
941 .shared
942 .iter()
943 .any(|m| m.is_free() && m.client.should_retire())
944 {
945 st.sweep(Instant::now(), self.pool.inner.idle_timeout);
946 }
947 st.wake_gets();
948 }
949 drop(st);
950 self.pool.flush_wakes();
951 }
952}
953
954fn refuse_on_shared(sql: &str, batch: bool) -> Result<(), Error> {
960 let mut statements = Statements {
963 sql,
964 i: 0,
965 first_only: !batch,
966 };
967 while let Some(words) = statements.next() {
968 let word = |i: usize| words.get(i);
969 let is = |i: usize, any: &[&str]| any.iter().any(|w| word(i).eq_ignore_ascii_case(w));
970 let transaction = match words.lead {
971 Lead::Transaction => true,
972 Lead::CommitOrRollback => !is(1, &["PREPARED"]),
974 Lead::Prepare => is(1, &["TRANSACTION"]),
975 _ => false,
976 };
977 if transaction && !batch {
978 return Err(Error::new(
979 ErrorKind::Statement,
980 format!(
981 "{} controls a transaction, and the pool's own methods run statements on \
982 connections that other tasks share, whose statements would run inside it; \
983 nothing was sent. Run the transaction on a connection of this task's own: \
984 let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
985 tx.commit().await?",
986 word(0).to_ascii_uppercase()
987 ),
988 ));
989 }
990 if transaction {
991 continue;
992 }
993 let session = match words.lead {
994 Lead::Set => !is(1, &["LOCAL", "TRANSACTION", "CONSTRAINTS"]),
996 Lead::Create => {
997 is(1, &["TEMP", "TEMPORARY"])
998 || (is(1, &["LOCAL", "GLOBAL"]) && is(2, &["TEMP", "TEMPORARY"]))
999 }
1000 Lead::Prepare | Lead::Session => true,
1001 _ => false,
1002 };
1003 if session {
1004 let what = match words.lead {
1005 Lead::Create => "CREATE TEMP".to_owned(),
1006 Lead::Set => format!("SET {}", word(1).to_ascii_uppercase()),
1007 _ => word(0).to_ascii_uppercase(),
1008 };
1009 return Err(Error::new(
1010 ErrorKind::Statement,
1011 format!(
1012 "{what} changes the session, and the pool's own methods run statements on \
1013 connections that other tasks share, which would then run under it; nothing \
1014 was sent. Run it on a connection of this task's own, from pool.get(): its \
1015 session is reset when it goes back to the pool. For a setting that every \
1016 connection needs, use Config::param"
1017 ),
1018 ));
1019 }
1020 if words.lead == Lead::Copy && words.from_stdin {
1021 return Err(Error::new(
1022 ErrorKind::Statement,
1023 "COPY ... FROM STDIN is not supported by giong-postgres yet, and on a connection \
1024 that other tasks share it would fail their statements too; nothing was sent. \
1025 Insert the rows with INSERT, several per statement",
1026 ));
1027 }
1028 }
1029 Ok(())
1030}
1031
1032#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1035enum Lead {
1036 #[default]
1039 Other,
1040 Transaction,
1042 CommitOrRollback,
1044 Prepare,
1046 Set,
1048 Create,
1050 Session,
1053 Copy,
1055}
1056
1057impl Lead {
1058 fn of(word: &str) -> Lead {
1059 let mut upper = [0u8; 10];
1060 let Some(upper) = upper.get_mut(..word.len()) else {
1061 return Lead::Other;
1062 };
1063 for (u, b) in upper.iter_mut().zip(word.bytes()) {
1064 *u = b.to_ascii_uppercase();
1065 }
1066 match &*upper {
1067 b"BEGIN" | b"START" | b"END" | b"ABORT" | b"SAVEPOINT" | b"RELEASE" => {
1068 Lead::Transaction
1069 }
1070 b"COMMIT" | b"ROLLBACK" => Lead::CommitOrRollback,
1071 b"PREPARE" => Lead::Prepare,
1072 b"SET" => Lead::Set,
1073 b"CREATE" => Lead::Create,
1074 b"RESET" | b"DISCARD" | b"LISTEN" | b"UNLISTEN" | b"DEALLOCATE" | b"DECLARE"
1075 | b"LOAD" => Lead::Session,
1076 b"COPY" => Lead::Copy,
1077 _ => Lead::Other,
1078 }
1079 }
1080
1081 fn words(self) -> usize {
1083 match self {
1084 Lead::Other | Lead::Transaction | Lead::Session => 1,
1085 Lead::CommitOrRollback | Lead::Prepare | Lead::Set => 2,
1086 Lead::Create => 3,
1087 Lead::Copy => usize::MAX,
1088 }
1089 }
1090}
1091
1092#[derive(Default)]
1095struct Words<'a> {
1096 lead: Lead,
1097 first: [&'a str; 3],
1098 len: usize,
1099 from_stdin: bool,
1100 after_from: bool,
1101}
1102
1103impl<'a> Words<'a> {
1104 fn get(&self, i: usize) -> &'a str {
1106 if i < self.len {
1107 self.first[i]
1108 } else {
1109 ""
1110 }
1111 }
1112
1113 fn push(&mut self, word: &'a str) {
1114 if self.len == 0 {
1115 self.lead = Lead::of(word);
1116 }
1117 if self.len < self.first.len() {
1118 self.first[self.len] = word;
1119 self.len += 1;
1120 }
1121 if self.lead == Lead::Copy {
1122 self.from_stdin |= self.after_from && word.eq_ignore_ascii_case("STDIN");
1123 self.after_from = word.eq_ignore_ascii_case("FROM");
1124 }
1125 }
1126
1127 fn settled(&self) -> bool {
1130 self.len > 0 && self.len >= self.lead.words()
1131 }
1132}
1133
1134struct Statements<'a> {
1139 sql: &'a str,
1140 i: usize,
1141 first_only: bool,
1142}
1143
1144impl<'a> Statements<'a> {
1145 fn next(&mut self) -> Option<Words<'a>> {
1146 let (sql, b) = (self.sql, self.sql.as_bytes());
1147 let mut i = self.i;
1148 let mut words = Words::default();
1149 while i < b.len() {
1150 if self.first_only && words.settled() {
1151 i = b.len();
1152 break;
1153 }
1154 match b[i] {
1155 b';' => {
1156 i += 1;
1157 if words.len > 0 {
1158 break;
1159 }
1160 }
1161 b'-' if b.get(i + 1) == Some(&b'-') => {
1162 while i < b.len() && b[i] != b'\n' {
1163 i += 1;
1164 }
1165 }
1166 b'/' if b.get(i + 1) == Some(&b'*') => {
1167 let mut depth = 0;
1169 while i < b.len() {
1170 if b[i..].starts_with(b"/*") {
1171 depth += 1;
1172 i += 2;
1173 } else if b[i..].starts_with(b"*/") {
1174 depth -= 1;
1175 i += 2;
1176 if depth == 0 {
1177 break;
1178 }
1179 } else {
1180 i += 1;
1181 }
1182 }
1183 }
1184 q @ (b'\'' | b'"') => {
1185 i = skip_quoted(b, i + 1, q, false);
1186 if q == b'"' {
1187 words.push("\"");
1188 }
1189 }
1190 b'$' => match dollar_tag(b, i) {
1191 Some(tag_len) => {
1192 let tag = &b[i..i + tag_len];
1193 i += tag_len;
1194 while i < b.len() && !b[i..].starts_with(tag) {
1195 i += 1;
1196 }
1197 i = (i + tag_len).min(b.len());
1198 }
1199 None => i += 1,
1201 },
1202 c if c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 => {
1203 let start = i;
1204 while i < b.len()
1205 && (b[i].is_ascii_alphanumeric()
1206 || matches!(b[i], b'_' | b'$')
1207 || b[i] >= 0x80)
1208 {
1209 i += 1;
1210 }
1211 let word = &sql[start..i];
1212 if b.get(i) == Some(&b'\'') {
1216 let escapes = word.eq_ignore_ascii_case("e");
1217 if escapes || ["b", "x", "n"].iter().any(|p| word.eq_ignore_ascii_case(p)) {
1218 i = skip_quoted(b, i + 1, b'\'', escapes);
1219 continue;
1220 }
1221 }
1222 if word.eq_ignore_ascii_case("u") && b[i..].starts_with(b"&'") {
1223 i = skip_quoted(b, i + 2, b'\'', false);
1224 continue;
1225 }
1226 words.push(word);
1227 }
1228 _ => i += 1,
1229 }
1230 }
1231 self.i = if self.first_only { b.len() } else { i };
1232 (words.len > 0).then_some(words)
1233 }
1234}
1235
1236fn skip_quoted(b: &[u8], mut i: usize, quote: u8, escapes: bool) -> usize {
1240 while i < b.len() {
1241 if escapes && b[i] == b'\\' {
1242 i += 2;
1243 } else if b[i] == quote {
1244 if b.get(i + 1) == Some("e) {
1245 i += 2;
1246 } else {
1247 return i + 1;
1248 }
1249 } else {
1250 i += 1;
1251 }
1252 }
1253 b.len()
1254}
1255
1256fn dollar_tag(b: &[u8], i: usize) -> Option<usize> {
1259 let mut j = i + 1;
1260 if b.get(j).is_some_and(|c| c.is_ascii_digit()) {
1261 return None;
1262 }
1263 while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] >= 0x80) {
1264 j += 1;
1265 }
1266 (b.get(j) == Some(&b'$')).then_some(j + 1 - i)
1267}
1268
1269impl std::fmt::Debug for Pool {
1270 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1271 f.debug_struct("Pool")
1272 .field("server", &self.inner.config.target())
1273 .field("max_size", &self.inner.max_size)
1274 .field("stats", &self.stats())
1275 .finish()
1276 }
1277}
1278
1279pub struct PooledClient {
1283 client: Option<Client>,
1284 pool: Pool,
1285 expires: Instant,
1287 requests: u64,
1289}
1290
1291impl PooledClient {
1292 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
1294 self.deref_mut().transaction().await
1295 }
1296}
1297
1298impl Deref for PooledClient {
1299 type Target = Client;
1300
1301 fn deref(&self) -> &Client {
1302 self.client.as_ref().expect("present until dropped")
1303 }
1304}
1305
1306impl DerefMut for PooledClient {
1307 fn deref_mut(&mut self) -> &mut Client {
1308 self.client.as_mut().expect("present until dropped")
1309 }
1310}
1311
1312impl Drop for PooledClient {
1313 fn drop(&mut self) {
1314 let client = self.client.take().expect("present until dropped");
1315 client.end_lease();
1316 let now = Instant::now();
1317 let mut st = self.pool.inner.state.borrow_mut();
1318 st.taken -= 1;
1319 let retire = now >= self.expires || client.should_retire();
1320 if retire && !client.is_closed() {
1321 st.recycled += 1;
1323 }
1324 if !client.is_closed() && !retire {
1325 let used = client.requests() != self.requests;
1326 if client.in_flight() > 0 || client.in_transaction() {
1330 client.send_and_forget("ROLLBACK");
1331 }
1332 if used {
1333 client.reset_session();
1334 }
1335 client.set_shared(true);
1336 st.shared.push(Member {
1337 client: Rc::new(client),
1338 draining: false,
1339 used: now,
1340 expires: self.expires,
1341 });
1342 st.rebalance(self.pool.inner.max_size);
1343 }
1344 st.wake_all();
1345 drop(st);
1346 self.pool.flush_wakes();
1347 }
1348}
1349
1350impl std::fmt::Debug for PooledClient {
1351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1352 f.debug_tuple("PooledClient").field(&**self).finish()
1353 }
1354}
1355
1356#[cfg(test)]
1357mod tests {
1358 use super::*;
1359
1360 fn refused(sql: &str) -> bool {
1361 refuse_on_shared(sql, false).is_err()
1362 }
1363
1364 fn refused_in_batch(sql: &str) -> bool {
1365 refuse_on_shared(sql, true).is_err()
1366 }
1367
1368 #[test]
1369 fn transaction_statements_are_refused_outside_batches() {
1370 for sql in [
1371 "BEGIN",
1372 " begin isolation level serializable",
1373 "/* x /* nested */ */ COMMIT",
1374 "-- c\nROLLBACK",
1375 "start transaction",
1376 "PREPARE TRANSACTION 'x'",
1377 "savepoint a",
1378 ] {
1379 assert!(refused(sql), "{sql}");
1380 assert!(!refused_in_batch(sql), "{sql}");
1381 }
1382 for sql in ["COMMIT PREPARED 'x'", "ROLLBACK PREPARED 'x'", "SELECT 1"] {
1383 assert!(!refused(sql), "{sql}");
1384 }
1385 }
1386
1387 #[test]
1388 fn session_changes_are_refused_everywhere() {
1389 for sql in [
1390 "SET search_path = tenant_a",
1391 "set session authorization app",
1392 "SET ROLE tenant",
1393 "SET statement_timeout = 0",
1394 "RESET ALL",
1395 "DISCARD ALL",
1396 "LISTEN jobs",
1397 "UNLISTEN *",
1398 "PREPARE q AS SELECT 1",
1399 "DEALLOCATE ALL",
1400 "DECLARE c CURSOR WITH HOLD FOR SELECT 1",
1401 "LOAD 'auto_explain'",
1402 "CREATE TEMP TABLE t (a int)",
1403 "create temporary table t (a int)",
1404 "CREATE LOCAL TEMPORARY TABLE t (a int)",
1405 "COPY t FROM STDIN",
1406 "copy t (a, b) from stdin with (format csv)",
1407 "BEGIN; SET work_mem = '1GB'; COMMIT",
1408 ] {
1409 assert!(refused(sql), "{sql}");
1410 assert!(refused_in_batch(sql), "{sql}");
1411 }
1412 assert!(refused_in_batch("SELECT 1; SET search_path = x"));
1415 assert!(!refused("SELECT 1; SET search_path = x"));
1416 for sql in [
1417 "SET LOCAL work_mem = '1GB'",
1418 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
1419 "SET CONSTRAINTS ALL DEFERRED",
1420 "CREATE TABLE t (a int)",
1421 "COPY t TO STDOUT",
1422 "COPY t FROM '/tmp/x'",
1423 "SELECT 'SET x = 1; LISTEN y'",
1424 "SELECT E'it\\'s; SET x = 1'",
1425 "SELECT $$; SET x = 1$$, $f$ ; LISTEN y $f$",
1426 "SELECT \"set\" FROM t",
1427 "SELECT $1::text; SELECT 2",
1428 "SELECT 1 -- ; SET x = 1",
1429 "SELECT /* ; SET x = 1 */ 1",
1430 "UPDATE t SET a = 1",
1431 "INSERT INTO t SELECT 'from stdin'",
1432 ] {
1433 assert!(!refused_in_batch(sql), "{sql}");
1434 }
1435 assert!(refused_in_batch("BEGIN; SET LOCAL a = 1; COMMIT; LISTEN x"));
1436 }
1437
1438 #[test]
1439 fn statements_are_split_outside_quotes() {
1440 let all = |sql| {
1441 let mut s = Statements {
1442 sql,
1443 i: 0,
1444 first_only: false,
1445 };
1446 let mut all = Vec::new();
1447 while let Some(w) = s.next() {
1448 all.push((0..w.len).map(|i| w.get(i).to_owned()).collect::<Vec<_>>());
1449 }
1450 all
1451 };
1452 let s = all("SELECT 'a;b'; SELECT \"x;y\" ; ; /* ; */ -- ;\n VALUES (1)");
1453 assert_eq!(s.len(), 3);
1454 assert_eq!(s[1], ["SELECT", "\""]);
1455 assert_eq!(s[2], ["VALUES"]);
1456 assert_eq!(all("SELECT 'a; SET x = 1").len(), 1);
1458 assert_eq!(all("SELECT $q$ a; SET x $q").len(), 1);
1459 assert_eq!(all("SELECT a$b; SET x = 1")[1], ["SET", "x"]);
1460 let mut s = Statements {
1462 sql: "copy t (a, b, c, d) from stdin; select 1",
1463 i: 0,
1464 first_only: true,
1465 };
1466 let w = s.next().unwrap();
1467 assert_eq!((w.lead, w.len, w.from_stdin), (Lead::Copy, 3, true));
1468 assert!(s.next().is_none());
1469 }
1470}