Skip to main content

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        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    /// The longest a task waits for a connection when all `max_size` are
463    /// taken or busy: 5 seconds by default. A longer wait fails with
464    /// [`ErrorKind::PoolTimeout`]. A task that opens a new connection waits
465    /// for it up to [`Config::connect_timeout`] instead.
466    ///
467    /// # Panics
468    ///
469    /// Panics if other clones of this pool exist; set it right after
470    /// [`new`](Self::new).
471    pub fn wait_timeout(mut self, timeout: Duration) -> Self {
472        self.settings("wait timeout").wait_timeout = timeout;
473        self
474    }
475
476    /// How long a connection may sit unused before the pool closes it: 10
477    /// minutes by default. The pool opens connections again when it needs
478    /// them, so a burst does not hold the server's connections forever.
479    ///
480    /// # Panics
481    ///
482    /// Panics if other clones of this pool exist; set it right after
483    /// [`new`](Self::new).
484    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
485        self.settings("idle timeout").idle_timeout = timeout;
486        self
487    }
488
489    /// How long a connection may live: 30 minutes by default, less up to a
490    /// tenth at random so that the connections of a pool do not all close at
491    /// once. An older connection is closed as soon as no statement uses it,
492    /// and replaced when needed, so that connections follow DNS changes and
493    /// failovers, and the server's per-connection memory is given back.
494    ///
495    /// # Panics
496    ///
497    /// Panics if other clones of this pool exist; set it right after
498    /// [`new`](Self::new).
499    pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
500        self.settings("maximum lifetime").max_lifetime = lifetime;
501        self
502    }
503
504    /// Runs a statement on a shared connection and returns its rows; see
505    /// [`Client::query`]. Statements that control a transaction or change
506    /// the session are refused ([`ErrorKind::Statement`]): run them on a
507    /// connection from [`get`](Self::get).
508    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    /// Runs a statement that returns exactly one row; see
515    /// [`Client::query_one`]. Refuses the statements [`query`](Self::query)
516    /// refuses.
517    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    /// Runs a statement that returns at most one row; see
524    /// [`Client::query_opt`]. Refuses the statements [`query`](Self::query)
525    /// refuses.
526    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    /// Runs a statement and returns the number of rows it changed; see
533    /// [`Client::execute`]. Refuses the statements [`query`](Self::query)
534    /// refuses.
535    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    /// Runs several statements without parameters; see
542    /// [`Client::batch_execute`].
543    ///
544    /// The batch may hold a whole transaction, `BEGIN; ...; COMMIT`. If it
545    /// leaves one open, the connection is closed, which rolls the
546    /// transaction back, and the batch fails with [`ErrorKind::Closed`], as
547    /// do the statements other tasks sent on that connection after it: they
548    /// would otherwise have run inside the transaction. Statements that
549    /// change the session (`SET` without `LOCAL`, `LISTEN`,
550    /// `COPY ... FROM STDIN` and the others listed on [`Pool`]) are refused
551    /// before anything is sent ([`ErrorKind::Statement`]).
552    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    /// Takes a connection for this task alone, for a transaction, session
559    /// settings or a slow statement:
560    ///
561    /// ```no_run
562    /// # async fn f(pool: &giong_postgres::Pool) -> Result<(), giong_postgres::Error> {
563    /// let mut conn = pool.get().await?;
564    /// let tx = conn.transaction().await?;
565    /// tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
566    /// tx.commit().await?;
567    /// # Ok(()) }
568    /// ```
569    ///
570    /// Waits up to the [wait timeout](Self::wait_timeout) when every
571    /// connection is taken or busy and the pool is full. Tasks waiting here
572    /// are served in the order they came. The session is reset when the
573    /// connection comes back (see [`Pool`]).
574    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                    // A connection nobody else holds, busy at most with
586                    // requests whose tasks stopped waiting (and only
587                    // briefly), draining ones first.
588                    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                        // The next in the queue may find a connection too.
619                        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    /// The pool's current state and counters.
651    pub fn stats(&self) -> PoolStats {
652        stats_of(&self.inner.state.borrow())
653    }
654
655    /// When a connection opened now is to be closed: the maximum lifetime,
656    /// less up to a tenth of it.
657    fn expiry(&self) -> Instant {
658        use std::hash::{BuildHasher, Hasher};
659        let life = self.inner.max_lifetime;
660        // Not for secrets: only spreads the closing times. The standard
661        // library seeds each RandomState differently.
662        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    /// The least busy shared connection, or a new one if every open one is
670    /// busy and there is room.
671    ///
672    /// A connection whose oldest statement has been running for more than
673    /// [`STALLED`] is passed over while another will do: statements queue
674    /// behind it in order, so a slow one would hold up everything sent after
675    /// it on that connection. Connections kept for a task waiting in `get`
676    /// and connections about to be closed are not used.
677    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                // The tasks holding the connection count, not only the
683                // requests sent: tasks waiting for a statement to be
684                // prepared have sent nothing yet. Abandoned requests count
685                // too, though nobody holds them.
686                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                // Busy means used by other tasks right now.
693                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                    // Every usable connection is stalled and the pool is
707                    // full: the one whose oldest statement has waited least,
708                    // which is the one most likely to be moving.
709                    _ => 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                // Room for other waiting statements too.
741                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    /// Wakes the tasks the state says to wake. Called with the state not
754    /// borrowed.
755    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    /// Starts the task that closes idle and old connections, once.
763    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    /// Runs `decide` until it hands out a connection (`Ok`), or a new one is
776    /// opened for the caller (`Err(client)`), or the wait times out.
777    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                        // A connection kept busy only by requests whose tasks
843                        // stopped waiting (a timeout dropped them) frees up
844                        // once they are answered, which nothing else would
845                        // announce.
846                        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
882/// Closes idle and old connections now and then, until the pool is dropped.
883async 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
914/// A shared connection lent to one statement. Dropping it, when the
915/// statement is answered or its future is dropped, tells waiting tasks to
916/// look again: there is room for one more statement, and the connection may
917/// have become free.
918struct 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        // The pool's reference and this one.
935        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
954/// Refuses, before anything is sent, a statement that must not run on a
955/// shared connection: one that controls a transaction (unless in a `batch`),
956/// changes the session, or starts `COPY ... FROM STDIN`. It is on the path of
957/// every shared statement, so it reads no further than the first word or
958/// three that decide.
959fn refuse_on_shared(sql: &str, batch: bool) -> Result<(), Error> {
960    // Through the extended protocol the server refuses more than one
961    // statement, so only a batch needs looking at past its first.
962    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            // Two-phase commit's second phase may run on any connection.
973            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            // SET LOCAL and the transaction's own settings end with it.
995            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/// What the first word of a statement says about it, for
1033/// [`refuse_on_shared`].
1034#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1035enum Lead {
1036    /// Anything else (`SELECT`, `INSERT`, `WITH`...): the rest of the
1037    /// statement does not matter.
1038    #[default]
1039    Other,
1040    /// `BEGIN`, `START`, `END`, `ABORT`, `SAVEPOINT`, `RELEASE`.
1041    Transaction,
1042    /// `COMMIT` or `ROLLBACK`, unless `PREPARED` follows.
1043    CommitOrRollback,
1044    /// `PREPARE`, or `PREPARE TRANSACTION`.
1045    Prepare,
1046    /// `SET`, unless `LOCAL`, `TRANSACTION` or `CONSTRAINTS` follows.
1047    Set,
1048    /// `CREATE`, which matters when a temporary object follows.
1049    Create,
1050    /// `RESET`, `DISCARD`, `LISTEN`, `UNLISTEN`, `DEALLOCATE`, `DECLARE`,
1051    /// `LOAD`.
1052    Session,
1053    /// `COPY`, which matters when `FROM STDIN` appears in it.
1054    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    /// How many words decide the statement (the whole of it for `COPY`).
1082    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/// The first words of one statement, as they are written, and whether
1093/// `FROM STDIN` appears in it. A quoted identifier counts as the word `"`.
1094#[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    /// Word `i`, or `""` past the last one kept.
1105    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    /// Whether the rest of the statement can change nothing that
1128    /// [`refuse_on_shared`] decides.
1129    fn settled(&self) -> bool {
1130        self.len > 0 && self.len >= self.lead.words()
1131    }
1132}
1133
1134/// The statements of `sql`, split at `;` outside comments, string
1135/// constants, quoted identifiers and dollar-quoted bodies; empty ones are
1136/// skipped. With `first_only`, only the first statement, and only as far as
1137/// it needs reading.
1138struct 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                    // PostgreSQL's block comments nest.
1168                    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                    // A parameter, $1.
1200                    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                    // E'...' takes backslash escapes; U&'...', B'...', X'...'
1213                    // and N'...' are ordinary string constants after their
1214                    // prefix.
1215                    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
1236/// The position after the quote that closes the one before `i`; a doubled
1237/// quote stands for itself, and with `escapes` so does a backslash and the
1238/// byte after it.
1239fn 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(&quote) {
1245                i += 2;
1246            } else {
1247                return i + 1;
1248            }
1249        } else {
1250            i += 1;
1251        }
1252    }
1253    b.len()
1254}
1255
1256/// The length of the dollar-quote tag at `i` (`$$` or `$name$`), if one
1257/// starts there.
1258fn 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
1279/// A connection taken from a [`Pool`] with [`Pool::get`]. It dereferences to
1280/// the [`Client`], and goes back to the pool when dropped, where its session
1281/// is reset (see [`Pool`]).
1282pub struct PooledClient {
1283    client: Option<Client>,
1284    pool: Pool,
1285    /// When the connection is to be closed rather than go back.
1286    expires: Instant,
1287    /// The connection's request count when it was taken.
1288    requests: u64,
1289}
1290
1291impl PooledClient {
1292    /// Starts a transaction; see [`Client::transaction`].
1293    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            // Closing rolls back whatever was left open.
1322            st.recycled += 1;
1323        }
1324        if !client.is_closed() && !retire {
1325            let used = client.requests() != self.requests;
1326            // A statement still on its way (its future was dropped, by a
1327            // timeout say) may be a BEGIN: the last answer cannot tell.
1328            // Queued ahead of anything a shared statement sends next.
1329            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        // Statements after the first matter in a batch only: through the
1413        // extended protocol, the server refuses more than one.
1414        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        // An unterminated quote swallows the rest, as the server would.
1457        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        // Only the first three words are kept, and FROM STDIN is seen anywhere.
1461        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}