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 let source: Weak<dyn giong::observe::Source> = Rc::downgrade(&observed) as _;
444 giong::observe::register(source);
445 Self {
446 inner: Rc::new(Inner {
447 config,
448 max_size,
449 wait_timeout: Duration::from_secs(5),
450 idle_timeout: Duration::from_secs(10 * 60),
451 max_lifetime: Duration::from_secs(30 * 60),
452 state,
453 _observed: observed,
454 }),
455 }
456 }
457
458 fn settings(&mut self, what: &str) -> &mut Inner {
459 Rc::get_mut(&mut self.inner)
460 .unwrap_or_else(|| panic!("set the {what} before cloning the pool"))
461 }
462
463 pub fn wait_timeout(mut self, timeout: Duration) -> Self {
473 self.settings("wait timeout").wait_timeout = timeout;
474 self
475 }
476
477 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
486 self.settings("idle timeout").idle_timeout = timeout;
487 self
488 }
489
490 pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
501 self.settings("maximum lifetime").max_lifetime = lifetime;
502 self
503 }
504
505 pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
514 refuse_on_shared(sql, false)?;
515 let client = self.shared().await?;
516 let batch = self.inner.config.batch_reads && is_select(sql);
517 client.query_shared(sql, params, batch).await
518 }
519
520 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
526 refuse_on_shared(sql, false)?;
527 let client = self.shared().await?;
528 let batch = self.inner.config.batch_reads && is_select(sql);
529 crate::client::one_row(client.query_shared(sql, params, batch).await?)
530 }
531
532 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
538 refuse_on_shared(sql, false)?;
539 let client = self.shared().await?;
540 let batch = self.inner.config.batch_reads && is_select(sql);
541 crate::client::at_most_one_row(client.query_shared(sql, params, batch).await?)
542 }
543
544 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
550 refuse_on_shared(sql, false)?;
551 let client = self.shared().await?;
552 client.execute(sql, params).await
553 }
554
555 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
569 refuse_on_shared(sql, true)?;
570 let client = self.shared().await?;
571 client.batch_execute(sql).await
572 }
573
574 pub async fn get(&self) -> Result<PooledClient, Error> {
594 let ticket = Ticket {
595 pool: self,
596 id: Cell::new(None),
597 };
598 let max = self.inner.max_size;
599 let taken = self
600 .acquire(Waiter::Get, |st, now| {
601 let mine = ticket.id.get();
602 let turn = st.queue.front().map_or(true, |&t| Some(t) == mine);
603 if turn {
604 let free = st
608 .shared
609 .iter()
610 .enumerate()
611 .filter(|(_, m)| {
612 m.is_free()
613 && !m.is_retiring(now)
614 && (m.client.in_flight() == 0
615 || m.client.waiting_for(now) <= STALLED)
616 })
617 .min_by_key(|(_, m)| (m.client.in_flight() > 0, !m.draining))
618 .map(|(i, _)| i);
619 let decision = if let Some(i) = free {
620 let m = st.shared.swap_remove(i);
621 st.taken += 1;
622 let Ok(client) = Rc::try_unwrap(m.client) else {
623 unreachable!("checked: nobody else holds it")
624 };
625 Some(Decision::Ready((client, m.expires)))
626 } else if st.room(max) {
627 st.connecting += 1;
628 Some(Decision::Connect)
629 } else {
630 None
631 };
632 if let Some(decision) = decision {
633 if let Some(id) = ticket.id.take() {
634 st.remove_ticket(id);
635 }
636 st.rebalance(max);
637 st.wake_gets();
639 return decision;
640 }
641 }
642 if mine.is_none() {
643 let id = st.next_ticket;
644 st.next_ticket += 1;
645 st.queue.push_back(id);
646 ticket.id.set(Some(id));
647 }
648 st.rebalance(max);
649 Decision::Wait
650 })
651 .await?;
652 let (client, expires) = match taken {
653 Ok(taken) => taken,
654 Err(new) => {
655 self.inner.state.borrow_mut().taken += 1;
656 (new, self.expiry())
657 }
658 };
659 client.set_shared(false);
660 client.begin_lease();
661 Ok(PooledClient {
662 requests: client.requests(),
663 client: Some(client),
664 expires,
665 pool: self.clone(),
666 })
667 }
668
669 pub fn stats(&self) -> PoolStats {
671 stats_of(&self.inner.state.borrow())
672 }
673
674 fn expiry(&self) -> Instant {
677 use std::hash::{BuildHasher, Hasher};
678 let life = self.inner.max_lifetime;
679 let seed = std::collections::hash_map::RandomState::new()
682 .build_hasher()
683 .finish();
684 let jitter = life / 10_000 * u32::try_from(seed % 1000).unwrap_or(0);
685 Instant::now()
687 .checked_add(life - jitter)
688 .unwrap_or_else(|| Instant::now() + Duration::from_secs(100 * 365 * 24 * 3600))
689 }
690
691 async fn shared(&self) -> Result<Lent<'_>, Error> {
700 let max = self.inner.max_size;
701 let client = self
702 .acquire(Waiter::Shared, |st, now| {
703 let room = st.room(max);
704 let usable = |m: &Member| {
709 let users = Rc::strong_count(&m.client) - 1;
710 !m.draining
711 && !m.is_retiring(now)
712 && users.max(m.client.in_flight()) < MAX_PIPELINE
713 };
714 let best = st
716 .shared
717 .iter()
718 .enumerate()
719 .filter(|(_, m)| usable(m) && m.client.waiting_for(now) <= STALLED)
720 .min_by_key(|(_, m)| Rc::strong_count(&m.client))
721 .map(|(i, m)| (i, m.is_free()));
722 let pick = match best {
723 Some((i, free)) if free || !room => Some(i),
724 _ if room => {
725 st.connecting += 1;
726 return Decision::Connect;
727 }
728 _ => st
732 .shared
733 .iter()
734 .enumerate()
735 .filter(|(_, m)| usable(m))
736 .min_by_key(|(_, m)| m.client.waiting_for(now))
737 .map(|(i, _)| i),
738 };
739 match pick {
740 Some(i) => {
741 let m = &mut st.shared[i];
742 m.used = now;
743 Decision::Ready(m.client.clone())
744 }
745 None => Decision::Wait,
746 }
747 })
748 .await?;
749 let client = match client {
750 Ok(c) => c,
751 Err(new) => {
752 new.set_shared(true);
753 let c = Rc::new(new);
754 let member = Member {
755 client: c.clone(),
756 draining: false,
757 used: Instant::now(),
758 expires: self.expiry(),
759 };
760 let mut st = self.inner.state.borrow_mut();
761 st.shared.push(member);
762 st.wake_all();
764 drop(st);
765 self.flush_wakes();
766 c
767 }
768 };
769 Ok(Lent {
770 pool: self,
771 client: Some(client),
772 })
773 }
774
775 fn flush_wakes(&self) {
778 let wakers = std::mem::take(&mut self.inner.state.borrow_mut().to_wake);
779 for w in wakers {
780 w.wake();
781 }
782 }
783
784 fn start_reaper(&self, st: &mut State) {
786 if st.reaper {
787 return;
788 }
789 st.reaper = true;
790 let state = Rc::downgrade(&self.inner.state);
791 let idle_timeout = self.inner.idle_timeout;
792 let period = (self.inner.idle_timeout.min(self.inner.max_lifetime) / 4)
793 .clamp(Duration::from_millis(50), Duration::from_secs(30));
794 giong::spawn(reap(state, idle_timeout, period));
795 }
796
797 async fn acquire<T>(
800 &self,
801 kind: Waiter,
802 mut decide: impl FnMut(&mut State, Instant) -> Decision<T>,
803 ) -> Result<Result<T, Client>, Error> {
804 let deadline = Instant::now() + self.inner.wait_timeout;
805 let mut waiting: Option<Waiting<'_>> = None;
806 loop {
807 let decision = {
808 let mut st = self.inner.state.borrow_mut();
809 let now = Instant::now();
810 st.sweep(now, self.inner.idle_timeout);
811 let d = decide(&mut st, now);
812 if matches!(d, Decision::Wait) && waiting.is_none() {
813 st.waiting += 1;
814 }
815 d
816 };
817 self.flush_wakes();
818 match decision {
819 Decision::Ready(c) => {
820 if let Some(w) = &mut waiting {
821 w.served = true;
822 }
823 return Ok(Ok(c));
824 }
825 Decision::Connect => {
826 if let Some(w) = &mut waiting {
827 w.served = true;
828 }
829 drop(waiting);
830 let _connecting = Connecting(self);
831 let result = Client::connect(&self.inner.config).await;
832 let mut st = self.inner.state.borrow_mut();
833 return match result {
834 Ok(client) => {
835 st.opened += 1;
836 self.start_reaper(&mut st);
837 Ok(Err(client))
838 }
839 Err(e) => {
840 st.connect_errors += 1;
841 Err(e)
842 }
843 };
844 }
845 Decision::Wait => {
846 if waiting.is_none() {
847 waiting = Some(Waiting {
848 pool: self,
849 kind,
850 served: false,
851 });
852 }
853 let mut registered = false;
854 let woken = poll_fn(|cx| {
855 if registered {
856 return Poll::Ready(());
857 }
858 registered = true;
859 let mut st = self.inner.state.borrow_mut();
860 match kind {
861 Waiter::Shared => st.shared_waiters.push_back(cx.waker().clone()),
862 Waiter::Get => st.get_waiters.push(cx.waker().clone()),
863 }
864 for m in &st.shared {
869 if m.is_free() && m.client.in_flight() > 0 {
870 m.client.wake_when_idle(cx.waker());
871 }
872 }
873 Poll::Pending
874 });
875 let left = deadline.saturating_duration_since(Instant::now());
876 if giong::time::timeout(left, woken).await.is_err() {
877 let mut st = self.inner.state.borrow_mut();
878 st.timeouts += 1;
879 let (taken, max) = (st.taken, self.inner.max_size);
880 drop(st);
881 let why = if taken == max {
882 format!("all {max} are taken with Pool::get")
883 } else {
884 format!("all {max} are taken or busy ({taken} taken with Pool::get)")
885 };
886 return Err(Error::new(
887 ErrorKind::PoolTimeout,
888 format!(
889 "no connection to {} became free within {:?}: {why}. Raise the \
890 pool's max_size (the server's max_connections allowing), look \
891 for transactions or connections from Pool::get held too long, \
892 or raise Pool::wait_timeout",
893 self.inner.config.target(),
894 self.inner.wait_timeout,
895 ),
896 ));
897 }
898 }
899 }
900 }
901 }
902}
903
904async fn reap(state: Weak<RefCell<State>>, idle_timeout: Duration, period: Duration) {
906 loop {
907 let mut sleep = pin!(giong::time::sleep(period));
908 let stopped = poll_fn(|cx| {
909 let Some(state) = state.upgrade() else {
910 return Poll::Ready(true);
911 };
912 let mut st = state.borrow_mut();
913 if st.stopped {
914 return Poll::Ready(true);
915 }
916 st.reaper_waker = Some(cx.waker().clone());
917 drop(st);
918 sleep.as_mut().poll(cx).map(|()| false)
919 })
920 .await;
921 if stopped {
922 return;
923 }
924 let Some(state) = state.upgrade() else { return };
925 let wakers = {
926 let mut st = state.borrow_mut();
927 st.sweep(Instant::now(), idle_timeout);
928 std::mem::take(&mut st.to_wake)
929 };
930 for w in wakers {
931 w.wake();
932 }
933 }
934}
935
936struct Lent<'a> {
941 pool: &'a Pool,
942 client: Option<Rc<Client>>,
943}
944
945impl Deref for Lent<'_> {
946 type Target = Client;
947
948 fn deref(&self) -> &Client {
949 self.client.as_ref().expect("present until dropped")
950 }
951}
952
953impl Drop for Lent<'_> {
954 fn drop(&mut self) {
955 let client = self.client.take().expect("present until dropped");
956 let free = Rc::strong_count(&client) == 2;
958 drop(client);
959 let mut st = self.pool.inner.state.borrow_mut();
960 st.wake_one_shared();
961 if free {
962 if st
963 .shared
964 .iter()
965 .any(|m| m.is_free() && m.client.should_retire())
966 {
967 st.sweep(Instant::now(), self.pool.inner.idle_timeout);
968 }
969 st.wake_gets();
970 }
971 drop(st);
972 self.pool.flush_wakes();
973 }
974}
975
976fn is_select(sql: &str) -> bool {
984 let sql = sql.trim_start();
985 sql.get(..6)
986 .is_some_and(|w| w.eq_ignore_ascii_case("select"))
987 && !sql[6..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')
988 && !sql
989 .as_bytes()
990 .windows(10)
991 .any(|w| w.eq_ignore_ascii_case(b"set_config"))
992}
993
994fn refuse_on_shared(sql: &str, batch: bool) -> Result<(), Error> {
1000 let mut statements = Statements {
1003 sql,
1004 i: 0,
1005 first_only: !batch,
1006 };
1007 while let Some(words) = statements.next() {
1008 let word = |i: usize| words.get(i);
1009 let is = |i: usize, any: &[&str]| any.iter().any(|w| word(i).eq_ignore_ascii_case(w));
1010 let transaction = match words.lead {
1011 Lead::Transaction => true,
1012 Lead::CommitOrRollback => !is(1, &["PREPARED"]),
1014 Lead::Prepare => is(1, &["TRANSACTION"]),
1015 _ => false,
1016 };
1017 if transaction && !batch {
1018 return Err(Error::new(
1019 ErrorKind::Statement,
1020 format!(
1021 "{} controls a transaction, and the pool's own methods run statements on \
1022 connections that other tasks share, whose statements would run inside it; \
1023 nothing was sent. Run the transaction on a connection of this task's own: \
1024 let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
1025 tx.commit().await?",
1026 word(0).to_ascii_uppercase()
1027 ),
1028 ));
1029 }
1030 if transaction {
1031 continue;
1032 }
1033 let session = match words.lead {
1034 Lead::Set => !is(1, &["LOCAL", "TRANSACTION", "CONSTRAINTS"]),
1036 Lead::Create => {
1037 is(1, &["TEMP", "TEMPORARY"])
1038 || (is(1, &["LOCAL", "GLOBAL"]) && is(2, &["TEMP", "TEMPORARY"]))
1039 }
1040 Lead::Prepare | Lead::Session => true,
1041 _ => false,
1042 };
1043 if session {
1044 let what = match words.lead {
1045 Lead::Create => "CREATE TEMP".to_owned(),
1046 Lead::Set => format!("SET {}", word(1).to_ascii_uppercase()),
1047 _ => word(0).to_ascii_uppercase(),
1048 };
1049 return Err(Error::new(
1050 ErrorKind::Statement,
1051 format!(
1052 "{what} changes the session, and the pool's own methods run statements on \
1053 connections that other tasks share, which would then run under it; nothing \
1054 was sent. Run it on a connection of this task's own, from pool.get(): its \
1055 session is reset when it goes back to the pool. For a setting that every \
1056 connection needs, use Config::param"
1057 ),
1058 ));
1059 }
1060 if words.lead == Lead::Copy && words.from_stdin {
1061 return Err(Error::new(
1062 ErrorKind::Statement,
1063 "COPY ... FROM STDIN is not supported by giong-postgres yet, and on a connection \
1064 that other tasks share it would fail their statements too; nothing was sent. \
1065 Insert the rows with INSERT, several per statement",
1066 ));
1067 }
1068 }
1069 Ok(())
1070}
1071
1072#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1075enum Lead {
1076 #[default]
1079 Other,
1080 Transaction,
1082 CommitOrRollback,
1084 Prepare,
1086 Set,
1088 Create,
1090 Session,
1093 Copy,
1095}
1096
1097impl Lead {
1098 fn of(word: &str) -> Lead {
1099 let mut upper = [0u8; 10];
1100 let Some(upper) = upper.get_mut(..word.len()) else {
1101 return Lead::Other;
1102 };
1103 for (u, b) in upper.iter_mut().zip(word.bytes()) {
1104 *u = b.to_ascii_uppercase();
1105 }
1106 match &*upper {
1107 b"BEGIN" | b"START" | b"END" | b"ABORT" | b"SAVEPOINT" | b"RELEASE" => {
1108 Lead::Transaction
1109 }
1110 b"COMMIT" | b"ROLLBACK" => Lead::CommitOrRollback,
1111 b"PREPARE" => Lead::Prepare,
1112 b"SET" => Lead::Set,
1113 b"CREATE" => Lead::Create,
1114 b"RESET" | b"DISCARD" | b"LISTEN" | b"UNLISTEN" | b"DEALLOCATE" | b"DECLARE"
1115 | b"LOAD" => Lead::Session,
1116 b"COPY" => Lead::Copy,
1117 _ => Lead::Other,
1118 }
1119 }
1120
1121 fn words(self) -> usize {
1123 match self {
1124 Lead::Other | Lead::Transaction | Lead::Session => 1,
1125 Lead::CommitOrRollback | Lead::Prepare | Lead::Set => 2,
1126 Lead::Create => 3,
1127 Lead::Copy => usize::MAX,
1128 }
1129 }
1130}
1131
1132#[derive(Default)]
1135struct Words<'a> {
1136 lead: Lead,
1137 first: [&'a str; 3],
1138 len: usize,
1139 from_stdin: bool,
1140 after_from: bool,
1141}
1142
1143impl<'a> Words<'a> {
1144 fn get(&self, i: usize) -> &'a str {
1146 if i < self.len {
1147 self.first[i]
1148 } else {
1149 ""
1150 }
1151 }
1152
1153 fn push(&mut self, word: &'a str) {
1154 if self.len == 0 {
1155 self.lead = Lead::of(word);
1156 }
1157 if self.len < self.first.len() {
1158 self.first[self.len] = word;
1159 self.len += 1;
1160 }
1161 if self.lead == Lead::Copy {
1162 self.from_stdin |= self.after_from && word.eq_ignore_ascii_case("STDIN");
1163 self.after_from = word.eq_ignore_ascii_case("FROM");
1164 }
1165 }
1166
1167 fn settled(&self) -> bool {
1170 self.len > 0 && self.len >= self.lead.words()
1171 }
1172}
1173
1174struct Statements<'a> {
1179 sql: &'a str,
1180 i: usize,
1181 first_only: bool,
1182}
1183
1184impl<'a> Statements<'a> {
1185 fn next(&mut self) -> Option<Words<'a>> {
1186 let (sql, b) = (self.sql, self.sql.as_bytes());
1187 let mut i = self.i;
1188 let mut words = Words::default();
1189 while i < b.len() {
1190 if self.first_only && words.settled() {
1191 i = b.len();
1192 break;
1193 }
1194 match b[i] {
1195 b';' => {
1196 i += 1;
1197 if words.len > 0 {
1198 break;
1199 }
1200 }
1201 b'-' if b.get(i + 1) == Some(&b'-') => {
1202 while i < b.len() && b[i] != b'\n' {
1203 i += 1;
1204 }
1205 }
1206 b'/' if b.get(i + 1) == Some(&b'*') => {
1207 let mut depth = 0;
1209 while i < b.len() {
1210 if b[i..].starts_with(b"/*") {
1211 depth += 1;
1212 i += 2;
1213 } else if b[i..].starts_with(b"*/") {
1214 depth -= 1;
1215 i += 2;
1216 if depth == 0 {
1217 break;
1218 }
1219 } else {
1220 i += 1;
1221 }
1222 }
1223 }
1224 q @ (b'\'' | b'"') => {
1225 i = skip_quoted(b, i + 1, q, false);
1226 if q == b'"' {
1227 words.push("\"");
1228 }
1229 }
1230 b'$' => match dollar_tag(b, i) {
1231 Some(tag_len) => {
1232 let tag = &b[i..i + tag_len];
1233 i += tag_len;
1234 while i < b.len() && !b[i..].starts_with(tag) {
1235 i += 1;
1236 }
1237 i = (i + tag_len).min(b.len());
1238 }
1239 None => i += 1,
1241 },
1242 c if c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 => {
1243 let start = i;
1244 while i < b.len()
1245 && (b[i].is_ascii_alphanumeric()
1246 || matches!(b[i], b'_' | b'$')
1247 || b[i] >= 0x80)
1248 {
1249 i += 1;
1250 }
1251 let word = &sql[start..i];
1252 if b.get(i) == Some(&b'\'') {
1256 let escapes = word.eq_ignore_ascii_case("e");
1257 if escapes || ["b", "x", "n"].iter().any(|p| word.eq_ignore_ascii_case(p)) {
1258 i = skip_quoted(b, i + 1, b'\'', escapes);
1259 continue;
1260 }
1261 }
1262 if word.eq_ignore_ascii_case("u") && b[i..].starts_with(b"&'") {
1263 i = skip_quoted(b, i + 2, b'\'', false);
1264 continue;
1265 }
1266 words.push(word);
1267 }
1268 _ => i += 1,
1269 }
1270 }
1271 self.i = if self.first_only { b.len() } else { i };
1272 (words.len > 0).then_some(words)
1273 }
1274}
1275
1276fn skip_quoted(b: &[u8], mut i: usize, quote: u8, escapes: bool) -> usize {
1280 while i < b.len() {
1281 if escapes && b[i] == b'\\' {
1282 i += 2;
1283 } else if b[i] == quote {
1284 if b.get(i + 1) == Some("e) {
1285 i += 2;
1286 } else {
1287 return i + 1;
1288 }
1289 } else {
1290 i += 1;
1291 }
1292 }
1293 b.len()
1294}
1295
1296fn dollar_tag(b: &[u8], i: usize) -> Option<usize> {
1299 let mut j = i + 1;
1300 if b.get(j).is_some_and(|c| c.is_ascii_digit()) {
1301 return None;
1302 }
1303 while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] >= 0x80) {
1304 j += 1;
1305 }
1306 (b.get(j) == Some(&b'$')).then_some(j + 1 - i)
1307}
1308
1309impl std::fmt::Debug for Pool {
1310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1311 f.debug_struct("Pool")
1312 .field("server", &self.inner.config.target())
1313 .field("max_size", &self.inner.max_size)
1314 .field("stats", &self.stats())
1315 .finish()
1316 }
1317}
1318
1319pub struct PooledClient {
1323 client: Option<Client>,
1324 pool: Pool,
1325 expires: Instant,
1327 requests: u64,
1329}
1330
1331impl PooledClient {
1332 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
1336 self.deref_mut().transaction().await
1337 }
1338}
1339
1340impl Deref for PooledClient {
1341 type Target = Client;
1342
1343 fn deref(&self) -> &Client {
1344 self.client.as_ref().expect("present until dropped")
1345 }
1346}
1347
1348impl DerefMut for PooledClient {
1349 fn deref_mut(&mut self) -> &mut Client {
1350 self.client.as_mut().expect("present until dropped")
1351 }
1352}
1353
1354impl Drop for PooledClient {
1355 fn drop(&mut self) {
1356 let client = self.client.take().expect("present until dropped");
1357 let cancelling = client.end_lease();
1360 let now = Instant::now();
1361 let mut st = self.pool.inner.state.borrow_mut();
1362 st.taken -= 1;
1363 let old = now >= self.expires || client.should_retire();
1364 let retire = old || cancelling;
1365 if old && !client.is_closed() {
1366 st.recycled += 1;
1368 }
1369 if !client.is_closed() && !retire {
1370 let used = client.requests() != self.requests;
1371 if client.in_flight() > 0 || client.in_transaction() {
1375 client.send_and_forget("ROLLBACK");
1376 }
1377 if used {
1378 client.reset_session();
1379 }
1380 client.set_shared(true);
1381 st.shared.push(Member {
1382 client: Rc::new(client),
1383 draining: false,
1384 used: now,
1385 expires: self.expires,
1386 });
1387 st.rebalance(self.pool.inner.max_size);
1388 }
1389 st.wake_all();
1390 drop(st);
1391 self.pool.flush_wakes();
1392 }
1393}
1394
1395impl std::fmt::Debug for PooledClient {
1396 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1397 f.debug_tuple("PooledClient").field(&**self).finish()
1398 }
1399}
1400
1401#[cfg(test)]
1402mod tests {
1403 use super::*;
1404
1405 fn refused(sql: &str) -> bool {
1406 refuse_on_shared(sql, false).is_err()
1407 }
1408
1409 fn refused_in_batch(sql: &str) -> bool {
1410 refuse_on_shared(sql, true).is_err()
1411 }
1412
1413 #[test]
1414 fn only_select_statements_may_join_a_batch() {
1415 for sql in ["SELECT 1", " select\n1", "Select(1)", "SELECT"] {
1416 assert!(is_select(sql), "{sql}");
1417 }
1418 for sql in [
1419 "SELECTED",
1420 "select_x()",
1421 "WITH a AS (SELECT 1) SELECT 1",
1422 "INSERT 1",
1423 "sel",
1424 "",
1425 "SELECT set_config('app.user', $1, true)",
1426 "select 1 from t where pg_catalog.SET_CONFIG('a', 'b', true) is not null",
1427 ] {
1428 assert!(!is_select(sql), "{sql}");
1429 }
1430 }
1431
1432 #[test]
1433 fn transaction_statements_are_refused_outside_batches() {
1434 for sql in [
1435 "BEGIN",
1436 " begin isolation level serializable",
1437 "/* x /* nested */ */ COMMIT",
1438 "-- c\nROLLBACK",
1439 "start transaction",
1440 "PREPARE TRANSACTION 'x'",
1441 "savepoint a",
1442 ] {
1443 assert!(refused(sql), "{sql}");
1444 assert!(!refused_in_batch(sql), "{sql}");
1445 }
1446 for sql in ["COMMIT PREPARED 'x'", "ROLLBACK PREPARED 'x'", "SELECT 1"] {
1447 assert!(!refused(sql), "{sql}");
1448 }
1449 }
1450
1451 #[test]
1452 fn session_changes_are_refused_everywhere() {
1453 for sql in [
1454 "SET search_path = tenant_a",
1455 "set session authorization app",
1456 "SET ROLE tenant",
1457 "SET statement_timeout = 0",
1458 "RESET ALL",
1459 "DISCARD ALL",
1460 "LISTEN jobs",
1461 "UNLISTEN *",
1462 "PREPARE q AS SELECT 1",
1463 "DEALLOCATE ALL",
1464 "DECLARE c CURSOR WITH HOLD FOR SELECT 1",
1465 "LOAD 'auto_explain'",
1466 "CREATE TEMP TABLE t (a int)",
1467 "create temporary table t (a int)",
1468 "CREATE LOCAL TEMPORARY TABLE t (a int)",
1469 "COPY t FROM STDIN",
1470 "copy t (a, b) from stdin with (format csv)",
1471 "BEGIN; SET work_mem = '1GB'; COMMIT",
1472 ] {
1473 assert!(refused(sql), "{sql}");
1474 assert!(refused_in_batch(sql), "{sql}");
1475 }
1476 assert!(refused_in_batch("SELECT 1; SET search_path = x"));
1479 assert!(!refused("SELECT 1; SET search_path = x"));
1480 for sql in [
1481 "SET LOCAL work_mem = '1GB'",
1482 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
1483 "SET CONSTRAINTS ALL DEFERRED",
1484 "CREATE TABLE t (a int)",
1485 "COPY t TO STDOUT",
1486 "COPY t FROM '/tmp/x'",
1487 "SELECT 'SET x = 1; LISTEN y'",
1488 "SELECT E'it\\'s; SET x = 1'",
1489 "SELECT $$; SET x = 1$$, $f$ ; LISTEN y $f$",
1490 "SELECT \"set\" FROM t",
1491 "SELECT $1::text; SELECT 2",
1492 "SELECT 1 -- ; SET x = 1",
1493 "SELECT /* ; SET x = 1 */ 1",
1494 "UPDATE t SET a = 1",
1495 "INSERT INTO t SELECT 'from stdin'",
1496 ] {
1497 assert!(!refused_in_batch(sql), "{sql}");
1498 }
1499 assert!(refused_in_batch("BEGIN; SET LOCAL a = 1; COMMIT; LISTEN x"));
1500 }
1501
1502 #[test]
1503 fn statements_are_split_outside_quotes() {
1504 let all = |sql| {
1505 let mut s = Statements {
1506 sql,
1507 i: 0,
1508 first_only: false,
1509 };
1510 let mut all = Vec::new();
1511 while let Some(w) = s.next() {
1512 all.push((0..w.len).map(|i| w.get(i).to_owned()).collect::<Vec<_>>());
1513 }
1514 all
1515 };
1516 let s = all("SELECT 'a;b'; SELECT \"x;y\" ; ; /* ; */ -- ;\n VALUES (1)");
1517 assert_eq!(s.len(), 3);
1518 assert_eq!(s[1], ["SELECT", "\""]);
1519 assert_eq!(s[2], ["VALUES"]);
1520 assert_eq!(all("SELECT 'a; SET x = 1").len(), 1);
1522 assert_eq!(all("SELECT $q$ a; SET x $q").len(), 1);
1523 assert_eq!(all("SELECT a$b; SET x = 1")[1], ["SET", "x"]);
1524 let mut s = Statements {
1526 sql: "copy t (a, b, c, d) from stdin; select 1",
1527 i: 0,
1528 first_only: true,
1529 };
1530 let w = s.next().unwrap();
1531 assert_eq!((w.lead, w.len, w.from_stdin), (Lead::Copy, 3, true));
1532 assert!(s.next().is_none());
1533 }
1534}