giong_postgres/pool.rs
1//! A pool of connections for one worker thread.
2
3use 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
20/// How long a connection's oldest statement may have been running before
21/// shared statements avoid that connection.
22const STALLED: Duration = Duration::from_millis(5);
23
24/// The most statements the pool's statement methods keep on one connection
25/// at a time; past it they use another connection, or wait.
26const MAX_PIPELINE: usize = 1024;
27
28/// Connections to one server, for the tasks of one worker thread.
29///
30/// Make one pool per worker, inside [`giong::Runtime::run`]: nothing is
31/// shared between threads, so nothing is locked.
32///
33/// ```no_run
34/// use giong_postgres::{Config, Pool};
35///
36/// fn main() -> std::io::Result<()> {
37/// let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
38/// giong::Builder::new().build()?.run(move |_worker| {
39/// let pool = Pool::new(config.clone(), 4);
40/// async move {
41/// let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
42/// let n: i64 = row.get(0).unwrap();
43/// println!("{n} orders");
44/// }
45/// })
46/// }
47/// ```
48///
49/// [`query`](Self::query) and the other statement methods do not take a
50/// connection for themselves: they run on the least busy connection, beside
51/// statements from other tasks (pipelining), and the pool opens another
52/// connection, up to its maximum, when every open one is busy. That is the
53/// fast path for statements that stand alone. On one connection the server
54/// answers in order, so a statement waits for those sent before it; the pool
55/// steers new statements away from a connection whose oldest statement has
56/// been running for more than 5 ms. Run statements known to be slow (reports,
57/// migrations) on a connection of their own, from [`get`](Self::get). At most
58/// 1024 statements run on one connection at a time; past that, statements
59/// use another connection or wait for room.
60///
61/// **How many connections.** Because statements pipeline, a few connections
62/// keep the server busy: start with the server's cores, shared among the
63/// workers' pools. More than that adds no throughput and raises tail latency,
64/// since a backend waiting for a core holds up every statement queued on its
65/// connection. Statements that wait on disk or on locks need more.
66///
67/// [`get`](Self::get) takes a connection for one task alone: for a
68/// transaction, for session settings (`SET`, `SET ROLE`, temporary tables,
69/// advisory locks, `LISTEN`), or for a slow statement. While it is out, no
70/// shared statement runs on it. Tasks waiting in `get` are served in the
71/// order they came, and shared statements stop using a connection while a
72/// `get` waits for it, so `get` is served even when shared statements keep
73/// every connection busy; shared statements always keep at least one
74/// connection when the pool has room for two. The connection comes back when
75/// the [`PooledClient`] is dropped, and its session is reset before anything
76/// else runs on it: a transaction left open is rolled back, and if anything
77/// was sent on it, `SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL;
78/// UNLISTEN *; SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD
79/// SEQUENCES` follows (plus `DEALLOCATE ALL` after an SQL-level `PREPARE`).
80/// Settings given to [`Config`] survive the reset; settings made with `SET`
81/// do not. These requests are pipelined in front of the next statement, so
82/// nobody waits a round trip for them; if they fail, the connection is closed
83/// instead of reused.
84///
85/// **Transactions and session changes never run on the shared
86/// connections**, since the statements of other tasks would run inside them
87/// or under them. `query`, `query_one`, `query_opt` and `execute` refuse
88/// `BEGIN`, `COMMIT`, `ROLLBACK` and the other transaction statements, and
89/// all the statement methods refuse statements that change the session
90/// (`SET` without `LOCAL`, `RESET`, `DISCARD`, `LISTEN`, `UNLISTEN`,
91/// `PREPARE`, `DEALLOCATE`, `DECLARE`, `LOAD`, `CREATE TEMP ...`) and
92/// `COPY ... FROM STDIN`, before sending anything ([`ErrorKind::Statement`]).
93/// Functions that change the session (`set_config(.., false)`,
94/// `pg_advisory_lock`) cannot be recognised this way: call them on a
95/// connection from `get`. [`batch_execute`](Self::batch_execute) may carry a
96/// whole transaction (`BEGIN; ...; COMMIT`); if a batch leaves one open, its
97/// connection is closed, which rolls it back, and the batch and every
98/// statement sent on that connection after it fail with
99/// [`ErrorKind::Closed`].
100///
101/// Connections the server closed, or that broke, are left behind as soon as
102/// that is noticed, which is when it happens: each connection is read
103/// continuously. A connection unused for the [idle
104/// timeout](Self::idle_timeout) is closed, and so is one older than the
105/// [maximum lifetime](Self::max_lifetime) or whose server refused a write
106/// because it is a standby (after a failover), once no statement uses it.
107#[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 /// The pool as `giong::observe` sees it; registered by a weak reference,
120 /// so it leaves snapshots when the pool is dropped.
121 _observed: Rc<Observed>,
122}
123
124impl Drop for Inner {
125 fn drop(&mut self) {
126 // The task that closes idle connections ends with the pool.
127 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
138/// Reports the pool's state in `giong::observe` snapshots (and so to
139/// giong-mcp).
140struct 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 /// Open connections that are not taken.
190 shared: Vec<Member>,
191 taken: usize,
192 connecting: usize,
193 waiting: usize,
194 /// Tasks of the statement methods waiting for room, woken one at a time:
195 /// a statement that finishes frees room for one more.
196 shared_waiters: VecDeque<Waker>,
197 /// Tasks waiting in `get`, all woken when a connection may have become
198 /// free (there are few of them).
199 get_waiters: Vec<Waker>,
200 /// The tickets of the `get` calls waiting, oldest first: only the oldest
201 /// may take a connection.
202 queue: VecDeque<u64>,
203 next_ticket: u64,
204 /// Wakers to wake once the state is no longer borrowed.
205 to_wake: Vec<Waker>,
206 /// The task that closes idle and old connections is running.
207 reaper: bool,
208 reaper_waker: Option<Waker>,
209 /// The pool was dropped.
210 stopped: bool,
211 opened: u64,
212 connect_errors: u64,
213 timeouts: u64,
214 recycled: u64,
215}
216
217/// A connection among the shared ones.
218struct Member {
219 client: Rc<Client>,
220 /// Kept free for a task waiting in `get`: shared statements do not use it.
221 draining: bool,
222 /// When it was last lent or came back.
223 used: Instant,
224 /// When it is to be closed, however busy it is.
225 expires: Instant,
226}
227
228impl Member {
229 /// No statement method is using it: nobody else holds it.
230 fn is_free(&self) -> bool {
231 Rc::strong_count(&self.client) == 1
232 }
233
234 /// To be closed once free: too old, or its server is a standby.
235 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 /// Wakes every waiting task (later, see `to_wake`), to look again.
246 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 /// Wakes the tasks waiting in `get`.
253 fn wake_gets(&mut self) {
254 let gets = std::mem::take(&mut self.get_waiters);
255 self.to_wake.extend(gets);
256 }
257
258 /// Wakes one task of the statement methods.
259 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 /// Closes the shared connections that broke, and the free ones that are
266 /// idle, too old, or on a standby.
267 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 // Room for a new connection, or fewer to drain.
284 self.wake_all();
285 }
286 }
287
288 /// Marks as many shared connections draining as tasks wait in `get`,
289 /// leaving at least one to the statement methods when the pool has room
290 /// for two.
291 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 // The least used one, so that it drains soonest.
300 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/// What a pool is doing, from [`Pool::stats`].
329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330#[non_exhaustive]
331pub struct PoolStats {
332 /// Open connections, taken or not.
333 pub connections: usize,
334 /// Connections taken with [`Pool::get`].
335 pub taken: usize,
336 /// Connections being opened.
337 pub connecting: usize,
338 /// Requests sent on the shared connections and not answered yet.
339 pub in_flight: usize,
340 /// Tasks waiting for a connection.
341 pub waiting: usize,
342 /// Connections opened since the pool was made.
343 pub opened: u64,
344 /// Attempts to open a connection that failed.
345 pub connect_errors: u64,
346 /// Waits that ended with [`ErrorKind::PoolTimeout`].
347 pub timeouts: u64,
348 /// Connections the pool closed although they worked: idle longer than
349 /// the [idle timeout](Pool::idle_timeout), older than the [maximum
350 /// lifetime](Pool::max_lifetime), or on a server that turned out to be a
351 /// standby.
352 pub recycled: u64,
353}
354
355enum Decision<T> {
356 Ready(T),
357 Connect,
358 Wait,
359}
360
361/// Which list a waiting task is in.
362#[derive(Clone, Copy, PartialEq, Eq)]
363enum Waiter {
364 Shared,
365 Get,
366}
367
368/// Undoes the `connecting` count however the attempt ends.
369struct 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
381/// Counts a task as waiting from its first wait until it gets a connection
382/// or gives up. A task of the statement methods that gives up passes its
383/// turn on: it may have been woken for room it will not use.
384struct 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
402/// A `get` call's place in the queue, given up however the call ends.
403struct 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 // The next one in the queue may go now.
415 st.wake_gets();
416 drop(st);
417 self.pool.flush_wakes();
418 }
419 }
420}
421
422impl Pool {
423 /// A pool of at most `max_size` connections to the server in `config`.
424 /// Connections are opened when needed, not here.
425 ///
426 /// Size it from the server's `max_connections`: the pools of all workers
427 /// of all processes together must stay below it.
428 ///
429 /// # Panics
430 ///
431 /// Panics if `max_size` is 0.
432 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 /// The longest a task waits for a connection when all `max_size` are
464 /// taken or busy: 5 seconds by default. A longer wait fails with
465 /// [`ErrorKind::PoolTimeout`]. A task that opens a new connection waits
466 /// for it up to [`Config::connect_timeout`] instead.
467 ///
468 /// # Panics
469 ///
470 /// Panics if other clones of this pool exist; set it right after
471 /// [`new`](Self::new).
472 pub fn wait_timeout(mut self, timeout: Duration) -> Self {
473 self.settings("wait timeout").wait_timeout = timeout;
474 self
475 }
476
477 /// How long a connection may sit unused before the pool closes it: 10
478 /// minutes by default. The pool opens connections again when it needs
479 /// them, so a burst does not hold the server's connections forever.
480 ///
481 /// # Panics
482 ///
483 /// Panics if other clones of this pool exist; set it right after
484 /// [`new`](Self::new).
485 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
486 self.settings("idle timeout").idle_timeout = timeout;
487 self
488 }
489
490 /// How long a connection may live: 30 minutes by default, less up to a
491 /// tenth at random so that the connections of a pool do not all close at
492 /// once. An older connection is closed as soon as no statement uses it,
493 /// and replaced when needed, so that connections follow DNS changes and
494 /// failovers, and the server's per-connection memory is given back.
495 ///
496 /// # Panics
497 ///
498 /// Panics if other clones of this pool exist; set it right after
499 /// [`new`](Self::new).
500 pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
501 self.settings("maximum lifetime").max_lifetime = lifetime;
502 self
503 }
504
505 /// Runs a statement on a shared connection and returns its rows; see
506 /// [`Client::query`]. Statements that control a transaction or change
507 /// the session are refused ([`ErrorKind::Statement`]): run them on a
508 /// connection from [`get`](Self::get).
509 ///
510 /// Not cancel safe: if the future is dropped, the statement may still run
511 /// on the server, and what it changes stays; the pool and its connections
512 /// stay usable.
513 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 client.query(sql, params).await
517 }
518
519 /// Runs a statement that returns exactly one row; see
520 /// [`Client::query_one`]. Refuses the statements [`query`](Self::query)
521 /// refuses.
522 ///
523 /// Not cancel safe, like [`query`](Self::query).
524 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
525 refuse_on_shared(sql, false)?;
526 let client = self.shared().await?;
527 client.query_one(sql, params).await
528 }
529
530 /// Runs a statement that returns at most one row; see
531 /// [`Client::query_opt`]. Refuses the statements [`query`](Self::query)
532 /// refuses.
533 ///
534 /// Not cancel safe, like [`query`](Self::query).
535 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
536 refuse_on_shared(sql, false)?;
537 let client = self.shared().await?;
538 client.query_opt(sql, params).await
539 }
540
541 /// Runs a statement and returns the number of rows it changed; see
542 /// [`Client::execute`]. Refuses the statements [`query`](Self::query)
543 /// refuses.
544 ///
545 /// Not cancel safe, like [`query`](Self::query).
546 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
547 refuse_on_shared(sql, false)?;
548 let client = self.shared().await?;
549 client.execute(sql, params).await
550 }
551
552 /// Runs several statements without parameters; see
553 /// [`Client::batch_execute`].
554 ///
555 /// The batch may hold a whole transaction, `BEGIN; ...; COMMIT`. If it
556 /// leaves one open, the connection is closed, which rolls the
557 /// transaction back, and the batch fails with [`ErrorKind::Closed`], as
558 /// do the statements other tasks sent on that connection after it: they
559 /// would otherwise have run inside the transaction. Statements that
560 /// change the session (`SET` without `LOCAL`, `LISTEN`,
561 /// `COPY ... FROM STDIN` and the others listed on [`Pool`]) are refused
562 /// before anything is sent ([`ErrorKind::Statement`]).
563 ///
564 /// Not cancel safe, like [`query`](Self::query).
565 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
566 refuse_on_shared(sql, true)?;
567 let client = self.shared().await?;
568 client.batch_execute(sql).await
569 }
570
571 /// Takes a connection for this task alone, for a transaction, session
572 /// settings or a slow statement:
573 ///
574 /// ```no_run
575 /// # async fn f(pool: &giong_postgres::Pool) -> Result<(), giong_postgres::Error> {
576 /// let mut conn = pool.get().await?;
577 /// let tx = conn.transaction().await?;
578 /// tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
579 /// tx.commit().await?;
580 /// # Ok(()) }
581 /// ```
582 ///
583 /// Waits up to the [wait timeout](Self::wait_timeout) when every
584 /// connection is taken or busy and the pool is full. Tasks waiting here
585 /// are served in the order they came. The session is reset when the
586 /// connection comes back (see [`Pool`]).
587 ///
588 /// Cancel safe: if the future is dropped, no connection is taken, and the
589 /// place in line goes to the next task.
590 pub async fn get(&self) -> Result<PooledClient, Error> {
591 let ticket = Ticket {
592 pool: self,
593 id: Cell::new(None),
594 };
595 let max = self.inner.max_size;
596 let taken = self
597 .acquire(Waiter::Get, |st, now| {
598 let mine = ticket.id.get();
599 let turn = st.queue.front().map_or(true, |&t| Some(t) == mine);
600 if turn {
601 // A connection nobody else holds, busy at most with
602 // requests whose tasks stopped waiting (and only
603 // briefly), draining ones first.
604 let free = st
605 .shared
606 .iter()
607 .enumerate()
608 .filter(|(_, m)| {
609 m.is_free()
610 && !m.is_retiring(now)
611 && (m.client.in_flight() == 0
612 || m.client.waiting_for(now) <= STALLED)
613 })
614 .min_by_key(|(_, m)| (m.client.in_flight() > 0, !m.draining))
615 .map(|(i, _)| i);
616 let decision = if let Some(i) = free {
617 let m = st.shared.swap_remove(i);
618 st.taken += 1;
619 let Ok(client) = Rc::try_unwrap(m.client) else {
620 unreachable!("checked: nobody else holds it")
621 };
622 Some(Decision::Ready((client, m.expires)))
623 } else if st.room(max) {
624 st.connecting += 1;
625 Some(Decision::Connect)
626 } else {
627 None
628 };
629 if let Some(decision) = decision {
630 if let Some(id) = ticket.id.take() {
631 st.remove_ticket(id);
632 }
633 st.rebalance(max);
634 // The next in the queue may find a connection too.
635 st.wake_gets();
636 return decision;
637 }
638 }
639 if mine.is_none() {
640 let id = st.next_ticket;
641 st.next_ticket += 1;
642 st.queue.push_back(id);
643 ticket.id.set(Some(id));
644 }
645 st.rebalance(max);
646 Decision::Wait
647 })
648 .await?;
649 let (client, expires) = match taken {
650 Ok(taken) => taken,
651 Err(new) => {
652 self.inner.state.borrow_mut().taken += 1;
653 (new, self.expiry())
654 }
655 };
656 client.set_shared(false);
657 client.begin_lease();
658 Ok(PooledClient {
659 requests: client.requests(),
660 client: Some(client),
661 expires,
662 pool: self.clone(),
663 })
664 }
665
666 /// The pool's current state and counters.
667 pub fn stats(&self) -> PoolStats {
668 stats_of(&self.inner.state.borrow())
669 }
670
671 /// When a connection opened now is to be closed: the maximum lifetime,
672 /// less up to a tenth of it.
673 fn expiry(&self) -> Instant {
674 use std::hash::{BuildHasher, Hasher};
675 let life = self.inner.max_lifetime;
676 // Not for secrets: only spreads the closing times. The standard
677 // library seeds each RandomState differently.
678 let seed = std::collections::hash_map::RandomState::new()
679 .build_hasher()
680 .finish();
681 let jitter = life / 10_000 * u32::try_from(seed % 1000).unwrap_or(0);
682 // A lifetime too long for the clock (`Duration::MAX`) means none.
683 Instant::now()
684 .checked_add(life - jitter)
685 .unwrap_or_else(|| Instant::now() + Duration::from_secs(100 * 365 * 24 * 3600))
686 }
687
688 /// The least busy shared connection, or a new one if every open one is
689 /// busy and there is room.
690 ///
691 /// A connection whose oldest statement has been running for more than
692 /// [`STALLED`] is passed over while another will do: statements queue
693 /// behind it in order, so a slow one would hold up everything sent after
694 /// it on that connection. Connections kept for a task waiting in `get`
695 /// and connections about to be closed are not used.
696 async fn shared(&self) -> Result<Lent<'_>, Error> {
697 let max = self.inner.max_size;
698 let client = self
699 .acquire(Waiter::Shared, |st, now| {
700 let room = st.room(max);
701 // The tasks holding the connection count, not only the
702 // requests sent: tasks waiting for a statement to be
703 // prepared have sent nothing yet. Abandoned requests count
704 // too, though nobody holds them.
705 let usable = |m: &Member| {
706 let users = Rc::strong_count(&m.client) - 1;
707 !m.draining
708 && !m.is_retiring(now)
709 && users.max(m.client.in_flight()) < MAX_PIPELINE
710 };
711 // Busy means used by other tasks right now.
712 let best = st
713 .shared
714 .iter()
715 .enumerate()
716 .filter(|(_, m)| usable(m) && m.client.waiting_for(now) <= STALLED)
717 .min_by_key(|(_, m)| Rc::strong_count(&m.client))
718 .map(|(i, m)| (i, m.is_free()));
719 let pick = match best {
720 Some((i, free)) if free || !room => Some(i),
721 _ if room => {
722 st.connecting += 1;
723 return Decision::Connect;
724 }
725 // Every usable connection is stalled and the pool is
726 // full: the one whose oldest statement has waited least,
727 // which is the one most likely to be moving.
728 _ => st
729 .shared
730 .iter()
731 .enumerate()
732 .filter(|(_, m)| usable(m))
733 .min_by_key(|(_, m)| m.client.waiting_for(now))
734 .map(|(i, _)| i),
735 };
736 match pick {
737 Some(i) => {
738 let m = &mut st.shared[i];
739 m.used = now;
740 Decision::Ready(m.client.clone())
741 }
742 None => Decision::Wait,
743 }
744 })
745 .await?;
746 let client = match client {
747 Ok(c) => c,
748 Err(new) => {
749 new.set_shared(true);
750 let c = Rc::new(new);
751 let member = Member {
752 client: c.clone(),
753 draining: false,
754 used: Instant::now(),
755 expires: self.expiry(),
756 };
757 let mut st = self.inner.state.borrow_mut();
758 st.shared.push(member);
759 // Room for other waiting statements too.
760 st.wake_all();
761 drop(st);
762 self.flush_wakes();
763 c
764 }
765 };
766 Ok(Lent {
767 pool: self,
768 client: Some(client),
769 })
770 }
771
772 /// Wakes the tasks the state says to wake. Called with the state not
773 /// borrowed.
774 fn flush_wakes(&self) {
775 let wakers = std::mem::take(&mut self.inner.state.borrow_mut().to_wake);
776 for w in wakers {
777 w.wake();
778 }
779 }
780
781 /// Starts the task that closes idle and old connections, once.
782 fn start_reaper(&self, st: &mut State) {
783 if st.reaper {
784 return;
785 }
786 st.reaper = true;
787 let state = Rc::downgrade(&self.inner.state);
788 let idle_timeout = self.inner.idle_timeout;
789 let period = (self.inner.idle_timeout.min(self.inner.max_lifetime) / 4)
790 .clamp(Duration::from_millis(50), Duration::from_secs(30));
791 giong::spawn(reap(state, idle_timeout, period));
792 }
793
794 /// Runs `decide` until it hands out a connection (`Ok`), or a new one is
795 /// opened for the caller (`Err(client)`), or the wait times out.
796 async fn acquire<T>(
797 &self,
798 kind: Waiter,
799 mut decide: impl FnMut(&mut State, Instant) -> Decision<T>,
800 ) -> Result<Result<T, Client>, Error> {
801 let deadline = Instant::now() + self.inner.wait_timeout;
802 let mut waiting: Option<Waiting<'_>> = None;
803 loop {
804 let decision = {
805 let mut st = self.inner.state.borrow_mut();
806 let now = Instant::now();
807 st.sweep(now, self.inner.idle_timeout);
808 let d = decide(&mut st, now);
809 if matches!(d, Decision::Wait) && waiting.is_none() {
810 st.waiting += 1;
811 }
812 d
813 };
814 self.flush_wakes();
815 match decision {
816 Decision::Ready(c) => {
817 if let Some(w) = &mut waiting {
818 w.served = true;
819 }
820 return Ok(Ok(c));
821 }
822 Decision::Connect => {
823 if let Some(w) = &mut waiting {
824 w.served = true;
825 }
826 drop(waiting);
827 let _connecting = Connecting(self);
828 let result = Client::connect(&self.inner.config).await;
829 let mut st = self.inner.state.borrow_mut();
830 return match result {
831 Ok(client) => {
832 st.opened += 1;
833 self.start_reaper(&mut st);
834 Ok(Err(client))
835 }
836 Err(e) => {
837 st.connect_errors += 1;
838 Err(e)
839 }
840 };
841 }
842 Decision::Wait => {
843 if waiting.is_none() {
844 waiting = Some(Waiting {
845 pool: self,
846 kind,
847 served: false,
848 });
849 }
850 let mut registered = false;
851 let woken = poll_fn(|cx| {
852 if registered {
853 return Poll::Ready(());
854 }
855 registered = true;
856 let mut st = self.inner.state.borrow_mut();
857 match kind {
858 Waiter::Shared => st.shared_waiters.push_back(cx.waker().clone()),
859 Waiter::Get => st.get_waiters.push(cx.waker().clone()),
860 }
861 // A connection kept busy only by requests whose tasks
862 // stopped waiting (a timeout dropped them) frees up
863 // once they are answered, which nothing else would
864 // announce.
865 for m in &st.shared {
866 if m.is_free() && m.client.in_flight() > 0 {
867 m.client.wake_when_idle(cx.waker());
868 }
869 }
870 Poll::Pending
871 });
872 let left = deadline.saturating_duration_since(Instant::now());
873 if giong::time::timeout(left, woken).await.is_err() {
874 let mut st = self.inner.state.borrow_mut();
875 st.timeouts += 1;
876 let (taken, max) = (st.taken, self.inner.max_size);
877 drop(st);
878 let why = if taken == max {
879 format!("all {max} are taken with Pool::get")
880 } else {
881 format!("all {max} are taken or busy ({taken} taken with Pool::get)")
882 };
883 return Err(Error::new(
884 ErrorKind::PoolTimeout,
885 format!(
886 "no connection to {} became free within {:?}: {why}. Raise the \
887 pool's max_size (the server's max_connections allowing), look \
888 for transactions or connections from Pool::get held too long, \
889 or raise Pool::wait_timeout",
890 self.inner.config.target(),
891 self.inner.wait_timeout,
892 ),
893 ));
894 }
895 }
896 }
897 }
898 }
899}
900
901/// Closes idle and old connections now and then, until the pool is dropped.
902async fn reap(state: Weak<RefCell<State>>, idle_timeout: Duration, period: Duration) {
903 loop {
904 let mut sleep = pin!(giong::time::sleep(period));
905 let stopped = poll_fn(|cx| {
906 let Some(state) = state.upgrade() else {
907 return Poll::Ready(true);
908 };
909 let mut st = state.borrow_mut();
910 if st.stopped {
911 return Poll::Ready(true);
912 }
913 st.reaper_waker = Some(cx.waker().clone());
914 drop(st);
915 sleep.as_mut().poll(cx).map(|()| false)
916 })
917 .await;
918 if stopped {
919 return;
920 }
921 let Some(state) = state.upgrade() else { return };
922 let wakers = {
923 let mut st = state.borrow_mut();
924 st.sweep(Instant::now(), idle_timeout);
925 std::mem::take(&mut st.to_wake)
926 };
927 for w in wakers {
928 w.wake();
929 }
930 }
931}
932
933/// A shared connection lent to one statement. Dropping it, when the
934/// statement is answered or its future is dropped, tells waiting tasks to
935/// look again: there is room for one more statement, and the connection may
936/// have become free.
937struct Lent<'a> {
938 pool: &'a Pool,
939 client: Option<Rc<Client>>,
940}
941
942impl Deref for Lent<'_> {
943 type Target = Client;
944
945 fn deref(&self) -> &Client {
946 self.client.as_ref().expect("present until dropped")
947 }
948}
949
950impl Drop for Lent<'_> {
951 fn drop(&mut self) {
952 let client = self.client.take().expect("present until dropped");
953 // The pool's reference and this one.
954 let free = Rc::strong_count(&client) == 2;
955 drop(client);
956 let mut st = self.pool.inner.state.borrow_mut();
957 st.wake_one_shared();
958 if free {
959 if st
960 .shared
961 .iter()
962 .any(|m| m.is_free() && m.client.should_retire())
963 {
964 st.sweep(Instant::now(), self.pool.inner.idle_timeout);
965 }
966 st.wake_gets();
967 }
968 drop(st);
969 self.pool.flush_wakes();
970 }
971}
972
973/// Refuses, before anything is sent, a statement that must not run on a
974/// shared connection: one that controls a transaction (unless in a `batch`),
975/// changes the session, or starts `COPY ... FROM STDIN`. It is on the path of
976/// every shared statement, so it reads no further than the first word or
977/// three that decide.
978fn refuse_on_shared(sql: &str, batch: bool) -> Result<(), Error> {
979 // Through the extended protocol the server refuses more than one
980 // statement, so only a batch needs looking at past its first.
981 let mut statements = Statements {
982 sql,
983 i: 0,
984 first_only: !batch,
985 };
986 while let Some(words) = statements.next() {
987 let word = |i: usize| words.get(i);
988 let is = |i: usize, any: &[&str]| any.iter().any(|w| word(i).eq_ignore_ascii_case(w));
989 let transaction = match words.lead {
990 Lead::Transaction => true,
991 // Two-phase commit's second phase may run on any connection.
992 Lead::CommitOrRollback => !is(1, &["PREPARED"]),
993 Lead::Prepare => is(1, &["TRANSACTION"]),
994 _ => false,
995 };
996 if transaction && !batch {
997 return Err(Error::new(
998 ErrorKind::Statement,
999 format!(
1000 "{} controls a transaction, and the pool's own methods run statements on \
1001 connections that other tasks share, whose statements would run inside it; \
1002 nothing was sent. Run the transaction on a connection of this task's own: \
1003 let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
1004 tx.commit().await?",
1005 word(0).to_ascii_uppercase()
1006 ),
1007 ));
1008 }
1009 if transaction {
1010 continue;
1011 }
1012 let session = match words.lead {
1013 // SET LOCAL and the transaction's own settings end with it.
1014 Lead::Set => !is(1, &["LOCAL", "TRANSACTION", "CONSTRAINTS"]),
1015 Lead::Create => {
1016 is(1, &["TEMP", "TEMPORARY"])
1017 || (is(1, &["LOCAL", "GLOBAL"]) && is(2, &["TEMP", "TEMPORARY"]))
1018 }
1019 Lead::Prepare | Lead::Session => true,
1020 _ => false,
1021 };
1022 if session {
1023 let what = match words.lead {
1024 Lead::Create => "CREATE TEMP".to_owned(),
1025 Lead::Set => format!("SET {}", word(1).to_ascii_uppercase()),
1026 _ => word(0).to_ascii_uppercase(),
1027 };
1028 return Err(Error::new(
1029 ErrorKind::Statement,
1030 format!(
1031 "{what} changes the session, and the pool's own methods run statements on \
1032 connections that other tasks share, which would then run under it; nothing \
1033 was sent. Run it on a connection of this task's own, from pool.get(): its \
1034 session is reset when it goes back to the pool. For a setting that every \
1035 connection needs, use Config::param"
1036 ),
1037 ));
1038 }
1039 if words.lead == Lead::Copy && words.from_stdin {
1040 return Err(Error::new(
1041 ErrorKind::Statement,
1042 "COPY ... FROM STDIN is not supported by giong-postgres yet, and on a connection \
1043 that other tasks share it would fail their statements too; nothing was sent. \
1044 Insert the rows with INSERT, several per statement",
1045 ));
1046 }
1047 }
1048 Ok(())
1049}
1050
1051/// What the first word of a statement says about it, for
1052/// [`refuse_on_shared`].
1053#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1054enum Lead {
1055 /// Anything else (`SELECT`, `INSERT`, `WITH`...): the rest of the
1056 /// statement does not matter.
1057 #[default]
1058 Other,
1059 /// `BEGIN`, `START`, `END`, `ABORT`, `SAVEPOINT`, `RELEASE`.
1060 Transaction,
1061 /// `COMMIT` or `ROLLBACK`, unless `PREPARED` follows.
1062 CommitOrRollback,
1063 /// `PREPARE`, or `PREPARE TRANSACTION`.
1064 Prepare,
1065 /// `SET`, unless `LOCAL`, `TRANSACTION` or `CONSTRAINTS` follows.
1066 Set,
1067 /// `CREATE`, which matters when a temporary object follows.
1068 Create,
1069 /// `RESET`, `DISCARD`, `LISTEN`, `UNLISTEN`, `DEALLOCATE`, `DECLARE`,
1070 /// `LOAD`.
1071 Session,
1072 /// `COPY`, which matters when `FROM STDIN` appears in it.
1073 Copy,
1074}
1075
1076impl Lead {
1077 fn of(word: &str) -> Lead {
1078 let mut upper = [0u8; 10];
1079 let Some(upper) = upper.get_mut(..word.len()) else {
1080 return Lead::Other;
1081 };
1082 for (u, b) in upper.iter_mut().zip(word.bytes()) {
1083 *u = b.to_ascii_uppercase();
1084 }
1085 match &*upper {
1086 b"BEGIN" | b"START" | b"END" | b"ABORT" | b"SAVEPOINT" | b"RELEASE" => {
1087 Lead::Transaction
1088 }
1089 b"COMMIT" | b"ROLLBACK" => Lead::CommitOrRollback,
1090 b"PREPARE" => Lead::Prepare,
1091 b"SET" => Lead::Set,
1092 b"CREATE" => Lead::Create,
1093 b"RESET" | b"DISCARD" | b"LISTEN" | b"UNLISTEN" | b"DEALLOCATE" | b"DECLARE"
1094 | b"LOAD" => Lead::Session,
1095 b"COPY" => Lead::Copy,
1096 _ => Lead::Other,
1097 }
1098 }
1099
1100 /// How many words decide the statement (the whole of it for `COPY`).
1101 fn words(self) -> usize {
1102 match self {
1103 Lead::Other | Lead::Transaction | Lead::Session => 1,
1104 Lead::CommitOrRollback | Lead::Prepare | Lead::Set => 2,
1105 Lead::Create => 3,
1106 Lead::Copy => usize::MAX,
1107 }
1108 }
1109}
1110
1111/// The first words of one statement, as they are written, and whether
1112/// `FROM STDIN` appears in it. A quoted identifier counts as the word `"`.
1113#[derive(Default)]
1114struct Words<'a> {
1115 lead: Lead,
1116 first: [&'a str; 3],
1117 len: usize,
1118 from_stdin: bool,
1119 after_from: bool,
1120}
1121
1122impl<'a> Words<'a> {
1123 /// Word `i`, or `""` past the last one kept.
1124 fn get(&self, i: usize) -> &'a str {
1125 if i < self.len {
1126 self.first[i]
1127 } else {
1128 ""
1129 }
1130 }
1131
1132 fn push(&mut self, word: &'a str) {
1133 if self.len == 0 {
1134 self.lead = Lead::of(word);
1135 }
1136 if self.len < self.first.len() {
1137 self.first[self.len] = word;
1138 self.len += 1;
1139 }
1140 if self.lead == Lead::Copy {
1141 self.from_stdin |= self.after_from && word.eq_ignore_ascii_case("STDIN");
1142 self.after_from = word.eq_ignore_ascii_case("FROM");
1143 }
1144 }
1145
1146 /// Whether the rest of the statement can change nothing that
1147 /// [`refuse_on_shared`] decides.
1148 fn settled(&self) -> bool {
1149 self.len > 0 && self.len >= self.lead.words()
1150 }
1151}
1152
1153/// The statements of `sql`, split at `;` outside comments, string
1154/// constants, quoted identifiers and dollar-quoted bodies; empty ones are
1155/// skipped. With `first_only`, only the first statement, and only as far as
1156/// it needs reading.
1157struct Statements<'a> {
1158 sql: &'a str,
1159 i: usize,
1160 first_only: bool,
1161}
1162
1163impl<'a> Statements<'a> {
1164 fn next(&mut self) -> Option<Words<'a>> {
1165 let (sql, b) = (self.sql, self.sql.as_bytes());
1166 let mut i = self.i;
1167 let mut words = Words::default();
1168 while i < b.len() {
1169 if self.first_only && words.settled() {
1170 i = b.len();
1171 break;
1172 }
1173 match b[i] {
1174 b';' => {
1175 i += 1;
1176 if words.len > 0 {
1177 break;
1178 }
1179 }
1180 b'-' if b.get(i + 1) == Some(&b'-') => {
1181 while i < b.len() && b[i] != b'\n' {
1182 i += 1;
1183 }
1184 }
1185 b'/' if b.get(i + 1) == Some(&b'*') => {
1186 // PostgreSQL's block comments nest.
1187 let mut depth = 0;
1188 while i < b.len() {
1189 if b[i..].starts_with(b"/*") {
1190 depth += 1;
1191 i += 2;
1192 } else if b[i..].starts_with(b"*/") {
1193 depth -= 1;
1194 i += 2;
1195 if depth == 0 {
1196 break;
1197 }
1198 } else {
1199 i += 1;
1200 }
1201 }
1202 }
1203 q @ (b'\'' | b'"') => {
1204 i = skip_quoted(b, i + 1, q, false);
1205 if q == b'"' {
1206 words.push("\"");
1207 }
1208 }
1209 b'$' => match dollar_tag(b, i) {
1210 Some(tag_len) => {
1211 let tag = &b[i..i + tag_len];
1212 i += tag_len;
1213 while i < b.len() && !b[i..].starts_with(tag) {
1214 i += 1;
1215 }
1216 i = (i + tag_len).min(b.len());
1217 }
1218 // A parameter, $1.
1219 None => i += 1,
1220 },
1221 c if c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 => {
1222 let start = i;
1223 while i < b.len()
1224 && (b[i].is_ascii_alphanumeric()
1225 || matches!(b[i], b'_' | b'$')
1226 || b[i] >= 0x80)
1227 {
1228 i += 1;
1229 }
1230 let word = &sql[start..i];
1231 // E'...' takes backslash escapes; U&'...', B'...', X'...'
1232 // and N'...' are ordinary string constants after their
1233 // prefix.
1234 if b.get(i) == Some(&b'\'') {
1235 let escapes = word.eq_ignore_ascii_case("e");
1236 if escapes || ["b", "x", "n"].iter().any(|p| word.eq_ignore_ascii_case(p)) {
1237 i = skip_quoted(b, i + 1, b'\'', escapes);
1238 continue;
1239 }
1240 }
1241 if word.eq_ignore_ascii_case("u") && b[i..].starts_with(b"&'") {
1242 i = skip_quoted(b, i + 2, b'\'', false);
1243 continue;
1244 }
1245 words.push(word);
1246 }
1247 _ => i += 1,
1248 }
1249 }
1250 self.i = if self.first_only { b.len() } else { i };
1251 (words.len > 0).then_some(words)
1252 }
1253}
1254
1255/// The position after the quote that closes the one before `i`; a doubled
1256/// quote stands for itself, and with `escapes` so does a backslash and the
1257/// byte after it.
1258fn skip_quoted(b: &[u8], mut i: usize, quote: u8, escapes: bool) -> usize {
1259 while i < b.len() {
1260 if escapes && b[i] == b'\\' {
1261 i += 2;
1262 } else if b[i] == quote {
1263 if b.get(i + 1) == Some("e) {
1264 i += 2;
1265 } else {
1266 return i + 1;
1267 }
1268 } else {
1269 i += 1;
1270 }
1271 }
1272 b.len()
1273}
1274
1275/// The length of the dollar-quote tag at `i` (`$$` or `$name$`), if one
1276/// starts there.
1277fn dollar_tag(b: &[u8], i: usize) -> Option<usize> {
1278 let mut j = i + 1;
1279 if b.get(j).is_some_and(|c| c.is_ascii_digit()) {
1280 return None;
1281 }
1282 while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] >= 0x80) {
1283 j += 1;
1284 }
1285 (b.get(j) == Some(&b'$')).then_some(j + 1 - i)
1286}
1287
1288impl std::fmt::Debug for Pool {
1289 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1290 f.debug_struct("Pool")
1291 .field("server", &self.inner.config.target())
1292 .field("max_size", &self.inner.max_size)
1293 .field("stats", &self.stats())
1294 .finish()
1295 }
1296}
1297
1298/// A connection taken from a [`Pool`] with [`Pool::get`]. It dereferences to
1299/// the [`Client`], and goes back to the pool when dropped, where its session
1300/// is reset (see [`Pool`]).
1301pub struct PooledClient {
1302 client: Option<Client>,
1303 pool: Pool,
1304 /// When the connection is to be closed rather than go back.
1305 expires: Instant,
1306 /// The connection's request count when it was taken.
1307 requests: u64,
1308}
1309
1310impl PooledClient {
1311 /// Starts a transaction; see [`Client::transaction`].
1312 ///
1313 /// Cancel safe, like [`Client::transaction`].
1314 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
1315 self.deref_mut().transaction().await
1316 }
1317}
1318
1319impl Deref for PooledClient {
1320 type Target = Client;
1321
1322 fn deref(&self) -> &Client {
1323 self.client.as_ref().expect("present until dropped")
1324 }
1325}
1326
1327impl DerefMut for PooledClient {
1328 fn deref_mut(&mut self) -> &mut Client {
1329 self.client.as_mut().expect("present until dropped")
1330 }
1331}
1332
1333impl Drop for PooledClient {
1334 fn drop(&mut self) {
1335 let client = self.client.take().expect("present until dropped");
1336 client.end_lease();
1337 let now = Instant::now();
1338 let mut st = self.pool.inner.state.borrow_mut();
1339 st.taken -= 1;
1340 let retire = now >= self.expires || client.should_retire();
1341 if retire && !client.is_closed() {
1342 // Closing rolls back whatever was left open.
1343 st.recycled += 1;
1344 }
1345 if !client.is_closed() && !retire {
1346 let used = client.requests() != self.requests;
1347 // A statement still on its way (its future was dropped, by a
1348 // timeout say) may be a BEGIN: the last answer cannot tell.
1349 // Queued ahead of anything a shared statement sends next.
1350 if client.in_flight() > 0 || client.in_transaction() {
1351 client.send_and_forget("ROLLBACK");
1352 }
1353 if used {
1354 client.reset_session();
1355 }
1356 client.set_shared(true);
1357 st.shared.push(Member {
1358 client: Rc::new(client),
1359 draining: false,
1360 used: now,
1361 expires: self.expires,
1362 });
1363 st.rebalance(self.pool.inner.max_size);
1364 }
1365 st.wake_all();
1366 drop(st);
1367 self.pool.flush_wakes();
1368 }
1369}
1370
1371impl std::fmt::Debug for PooledClient {
1372 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1373 f.debug_tuple("PooledClient").field(&**self).finish()
1374 }
1375}
1376
1377#[cfg(test)]
1378mod tests {
1379 use super::*;
1380
1381 fn refused(sql: &str) -> bool {
1382 refuse_on_shared(sql, false).is_err()
1383 }
1384
1385 fn refused_in_batch(sql: &str) -> bool {
1386 refuse_on_shared(sql, true).is_err()
1387 }
1388
1389 #[test]
1390 fn transaction_statements_are_refused_outside_batches() {
1391 for sql in [
1392 "BEGIN",
1393 " begin isolation level serializable",
1394 "/* x /* nested */ */ COMMIT",
1395 "-- c\nROLLBACK",
1396 "start transaction",
1397 "PREPARE TRANSACTION 'x'",
1398 "savepoint a",
1399 ] {
1400 assert!(refused(sql), "{sql}");
1401 assert!(!refused_in_batch(sql), "{sql}");
1402 }
1403 for sql in ["COMMIT PREPARED 'x'", "ROLLBACK PREPARED 'x'", "SELECT 1"] {
1404 assert!(!refused(sql), "{sql}");
1405 }
1406 }
1407
1408 #[test]
1409 fn session_changes_are_refused_everywhere() {
1410 for sql in [
1411 "SET search_path = tenant_a",
1412 "set session authorization app",
1413 "SET ROLE tenant",
1414 "SET statement_timeout = 0",
1415 "RESET ALL",
1416 "DISCARD ALL",
1417 "LISTEN jobs",
1418 "UNLISTEN *",
1419 "PREPARE q AS SELECT 1",
1420 "DEALLOCATE ALL",
1421 "DECLARE c CURSOR WITH HOLD FOR SELECT 1",
1422 "LOAD 'auto_explain'",
1423 "CREATE TEMP TABLE t (a int)",
1424 "create temporary table t (a int)",
1425 "CREATE LOCAL TEMPORARY TABLE t (a int)",
1426 "COPY t FROM STDIN",
1427 "copy t (a, b) from stdin with (format csv)",
1428 "BEGIN; SET work_mem = '1GB'; COMMIT",
1429 ] {
1430 assert!(refused(sql), "{sql}");
1431 assert!(refused_in_batch(sql), "{sql}");
1432 }
1433 // Statements after the first matter in a batch only: through the
1434 // extended protocol, the server refuses more than one.
1435 assert!(refused_in_batch("SELECT 1; SET search_path = x"));
1436 assert!(!refused("SELECT 1; SET search_path = x"));
1437 for sql in [
1438 "SET LOCAL work_mem = '1GB'",
1439 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
1440 "SET CONSTRAINTS ALL DEFERRED",
1441 "CREATE TABLE t (a int)",
1442 "COPY t TO STDOUT",
1443 "COPY t FROM '/tmp/x'",
1444 "SELECT 'SET x = 1; LISTEN y'",
1445 "SELECT E'it\\'s; SET x = 1'",
1446 "SELECT $$; SET x = 1$$, $f$ ; LISTEN y $f$",
1447 "SELECT \"set\" FROM t",
1448 "SELECT $1::text; SELECT 2",
1449 "SELECT 1 -- ; SET x = 1",
1450 "SELECT /* ; SET x = 1 */ 1",
1451 "UPDATE t SET a = 1",
1452 "INSERT INTO t SELECT 'from stdin'",
1453 ] {
1454 assert!(!refused_in_batch(sql), "{sql}");
1455 }
1456 assert!(refused_in_batch("BEGIN; SET LOCAL a = 1; COMMIT; LISTEN x"));
1457 }
1458
1459 #[test]
1460 fn statements_are_split_outside_quotes() {
1461 let all = |sql| {
1462 let mut s = Statements {
1463 sql,
1464 i: 0,
1465 first_only: false,
1466 };
1467 let mut all = Vec::new();
1468 while let Some(w) = s.next() {
1469 all.push((0..w.len).map(|i| w.get(i).to_owned()).collect::<Vec<_>>());
1470 }
1471 all
1472 };
1473 let s = all("SELECT 'a;b'; SELECT \"x;y\" ; ; /* ; */ -- ;\n VALUES (1)");
1474 assert_eq!(s.len(), 3);
1475 assert_eq!(s[1], ["SELECT", "\""]);
1476 assert_eq!(s[2], ["VALUES"]);
1477 // An unterminated quote swallows the rest, as the server would.
1478 assert_eq!(all("SELECT 'a; SET x = 1").len(), 1);
1479 assert_eq!(all("SELECT $q$ a; SET x $q").len(), 1);
1480 assert_eq!(all("SELECT a$b; SET x = 1")[1], ["SET", "x"]);
1481 // Only the first three words are kept, and FROM STDIN is seen anywhere.
1482 let mut s = Statements {
1483 sql: "copy t (a, b, c, d) from stdin; select 1",
1484 i: 0,
1485 first_only: true,
1486 };
1487 let w = s.next().unwrap();
1488 assert_eq!((w.lead, w.len, w.from_stdin), (Lead::Copy, 3, true));
1489 assert!(s.next().is_none());
1490 }
1491}