Skip to main content

tokio_postgres/
client.rs

1#[cfg(feature = "runtime")]
2use crate::Socket;
3use crate::codec::{BackendMessages, FrontendMessage};
4use crate::config::{SslMode, SslNegotiation};
5use crate::connection::{Request, RequestMessages};
6use crate::copy_out::CopyOutStream;
7#[cfg(feature = "runtime")]
8use crate::keepalive::KeepaliveConfig;
9use crate::query::RowStream;
10use crate::simple_query::SimpleQueryStream;
11#[cfg(feature = "runtime")]
12use crate::tls::MakeTlsConnect;
13use crate::tls::TlsConnect;
14use crate::types::{Oid, ToSql, Type};
15use crate::{
16    CancelToken, CopyInSink, Error, Row, SimpleQueryMessage, Statement, ToStatement, Transaction,
17    TransactionBuilder, copy_in, copy_out, prepare, query, simple_query, slice_iter,
18};
19use bytes::{Buf, BytesMut};
20use fallible_iterator::FallibleIterator;
21use futures_channel::mpsc;
22use futures_util::{StreamExt, TryStreamExt, future, pin_mut, ready};
23use parking_lot::Mutex;
24use postgres_protocol::message::backend::Message;
25use postgres_protocol::message::frontend;
26use postgres_types::BorrowToSql;
27use std::collections::HashMap;
28use std::fmt;
29#[cfg(feature = "runtime")]
30use std::net::IpAddr;
31#[cfg(feature = "runtime")]
32use std::path::PathBuf;
33use std::sync::Arc;
34use std::task::{Context, Poll};
35#[cfg(feature = "runtime")]
36use std::time::Duration;
37use tokio::io::{AsyncRead, AsyncWrite};
38
39pub struct Responses {
40    receiver: mpsc::Receiver<BackendMessages>,
41    cur: BackendMessages,
42}
43
44impl Responses {
45    pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Result<Message, Error>> {
46        loop {
47            match self.cur.next().map_err(Error::parse)? {
48                Some(Message::ErrorResponse(body)) => return Poll::Ready(Err(Error::db(body))),
49                Some(message) => return Poll::Ready(Ok(message)),
50                None => {}
51            }
52
53            match ready!(self.receiver.poll_next_unpin(cx)) {
54                Some(messages) => self.cur = messages,
55                None => return Poll::Ready(Err(Error::closed())),
56            }
57        }
58    }
59
60    pub async fn next(&mut self) -> Result<Message, Error> {
61        future::poll_fn(|cx| self.poll_next(cx)).await
62    }
63}
64
65/// A cache of type info and prepared statements for fetching type info
66/// (corresponding to the queries in the [prepare](prepare) module).
67#[derive(Default)]
68struct CachedTypeInfo {
69    /// A statement for basic information for a type from its
70    /// OID. Corresponds to [TYPEINFO_QUERY](prepare::TYPEINFO_QUERY) (or its
71    /// fallback).
72    typeinfo: Option<Statement>,
73    /// A statement for getting information for a composite type from its OID.
74    /// Corresponds to [TYPEINFO_QUERY](prepare::TYPEINFO_COMPOSITE_QUERY).
75    typeinfo_composite: Option<Statement>,
76    /// A statement for getting information for a composite type from its OID.
77    /// Corresponds to [TYPEINFO_QUERY](prepare::TYPEINFO_COMPOSITE_QUERY) (or
78    /// its fallback).
79    typeinfo_enum: Option<Statement>,
80
81    /// Cache of types already looked up.
82    types: HashMap<Oid, Type>,
83}
84
85pub struct InnerClient {
86    sender: mpsc::UnboundedSender<Request>,
87    /// Set for a connection its client's calls drive: see
88    /// [`Connection::driven_by`](crate::Connection::driven_by).
89    driver: std::sync::OnceLock<Arc<dyn crate::driven::Drive>>,
90    cached_typeinfo: Mutex<CachedTypeInfo>,
91
92    /// A buffer to use when writing out postgres commands.
93    buffer: Mutex<BytesMut>,
94}
95
96impl InnerClient {
97    pub fn send(&self, messages: RequestMessages) -> Result<Responses, Error> {
98        let (sender, receiver) = mpsc::channel(1);
99        let request = Request { messages, sender };
100        match self.driver.get() {
101            None => self
102                .sender
103                .unbounded_send(request)
104                .map_err(|_| Error::closed())?,
105            Some(driver) => {
106                let mut request = Some(request);
107                driver.queue_and_drive(&mut || {
108                    let request = request.take().expect("queued once");
109                    self.sender
110                        .unbounded_send(request)
111                        .map_err(|_| Error::closed())
112                })?;
113            }
114        }
115
116        Ok(Responses {
117            receiver,
118            cur: BackendMessages::empty(),
119        })
120    }
121
122    pub(crate) fn set_driver(this: &Arc<Self>, driver: Arc<dyn crate::driven::Drive>) {
123        let _ = this.driver.set(driver);
124    }
125
126    pub fn typeinfo(&self) -> Option<Statement> {
127        self.cached_typeinfo.lock().typeinfo.clone()
128    }
129
130    pub fn set_typeinfo(&self, statement: &Statement) {
131        self.cached_typeinfo.lock().typeinfo = Some(statement.clone());
132    }
133
134    pub fn typeinfo_composite(&self) -> Option<Statement> {
135        self.cached_typeinfo.lock().typeinfo_composite.clone()
136    }
137
138    pub fn set_typeinfo_composite(&self, statement: &Statement) {
139        self.cached_typeinfo.lock().typeinfo_composite = Some(statement.clone());
140    }
141
142    pub fn typeinfo_enum(&self) -> Option<Statement> {
143        self.cached_typeinfo.lock().typeinfo_enum.clone()
144    }
145
146    pub fn set_typeinfo_enum(&self, statement: &Statement) {
147        self.cached_typeinfo.lock().typeinfo_enum = Some(statement.clone());
148    }
149
150    pub fn type_(&self, oid: Oid) -> Option<Type> {
151        self.cached_typeinfo.lock().types.get(&oid).cloned()
152    }
153
154    pub fn set_type(&self, oid: Oid, type_: &Type) {
155        self.cached_typeinfo.lock().types.insert(oid, type_.clone());
156    }
157
158    pub fn clear_type_cache(&self) {
159        self.cached_typeinfo.lock().types.clear();
160    }
161
162    /// Call the given function with a buffer to be used when writing out
163    /// postgres commands.
164    pub fn with_buf<F, R>(&self, f: F) -> R
165    where
166        F: FnOnce(&mut BytesMut) -> R,
167    {
168        let mut buffer = self.buffer.lock();
169        let r = f(&mut buffer);
170        buffer.clear();
171        r
172    }
173}
174
175#[cfg(feature = "runtime")]
176#[derive(Clone)]
177pub(crate) struct SocketConfig {
178    pub addr: Addr,
179    pub hostname: Option<String>,
180    pub port: u16,
181    pub connect_timeout: Option<Duration>,
182    pub tcp_user_timeout: Option<Duration>,
183    pub keepalive: Option<KeepaliveConfig>,
184}
185
186#[cfg(feature = "runtime")]
187#[derive(Clone)]
188pub(crate) enum Addr {
189    Tcp(IpAddr),
190    #[cfg(unix)]
191    Unix(PathBuf),
192}
193
194/// An asynchronous PostgreSQL client.
195///
196/// The client is one half of what is returned when a connection is established. Users interact with the database
197/// through this client object.
198pub struct Client {
199    inner: Arc<InnerClient>,
200    #[cfg(feature = "runtime")]
201    socket_config: Option<SocketConfig>,
202    ssl_mode: SslMode,
203    ssl_negotiation: SslNegotiation,
204    process_id: i32,
205    secret_key: i32,
206}
207
208impl Client {
209    pub(crate) fn new(
210        sender: mpsc::UnboundedSender<Request>,
211        ssl_mode: SslMode,
212        ssl_negotiation: SslNegotiation,
213        process_id: i32,
214        secret_key: i32,
215    ) -> Client {
216        Client {
217            inner: Arc::new(InnerClient {
218                sender,
219                driver: Default::default(),
220                cached_typeinfo: Default::default(),
221                buffer: Default::default(),
222            }),
223            #[cfg(feature = "runtime")]
224            socket_config: None,
225            ssl_mode,
226            ssl_negotiation,
227            process_id,
228            secret_key,
229        }
230    }
231
232    pub(crate) fn inner(&self) -> &Arc<InnerClient> {
233        &self.inner
234    }
235
236    #[cfg(feature = "runtime")]
237    pub(crate) fn set_socket_config(&mut self, socket_config: SocketConfig) {
238        self.socket_config = Some(socket_config);
239    }
240
241    /// Creates a new prepared statement.
242    ///
243    /// Prepared statements can be executed repeatedly, and may contain query parameters (indicated by `$1`, `$2`, etc),
244    /// which are set when executed. Prepared statements can only be used with the connection that created them.
245    pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
246        self.prepare_typed(query, &[]).await
247    }
248
249    /// Like `prepare`, but allows the types of query parameters to be explicitly specified.
250    ///
251    /// The list of types may be smaller than the number of parameters - the types of the remaining parameters will be
252    /// inferred. For example, `client.prepare_typed(query, &[])` is equivalent to `client.prepare(query)`.
253    pub async fn prepare_typed(
254        &self,
255        query: &str,
256        parameter_types: &[Type],
257    ) -> Result<Statement, Error> {
258        prepare::prepare(&self.inner, query, parameter_types).await
259    }
260
261    /// Executes a statement, returning a vector of the resulting rows.
262    ///
263    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
264    /// provided, 1-indexed.
265    ///
266    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
267    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
268    /// with the `prepare` method.
269    pub async fn query<T>(
270        &self,
271        statement: &T,
272        params: &[&(dyn ToSql + Sync)],
273    ) -> Result<Vec<Row>, Error>
274    where
275        T: ?Sized + ToStatement,
276    {
277        self.query_raw(statement, slice_iter(params))
278            .await?
279            .try_collect()
280            .await
281    }
282
283    /// Executes a statement which returns a single row, returning it.
284    ///
285    /// Returns an error if the query does not return exactly one row.
286    ///
287    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
288    /// provided, 1-indexed.
289    ///
290    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
291    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
292    /// with the `prepare` method.
293    pub async fn query_one<T>(
294        &self,
295        statement: &T,
296        params: &[&(dyn ToSql + Sync)],
297    ) -> Result<Row, Error>
298    where
299        T: ?Sized + ToStatement,
300    {
301        self.query_opt(statement, params)
302            .await
303            .and_then(|res| res.ok_or_else(Error::row_count))
304    }
305
306    /// Executes a statements which returns zero or one rows, returning it.
307    ///
308    /// Returns an error if the query returns more than one row.
309    ///
310    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
311    /// provided, 1-indexed.
312    ///
313    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
314    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
315    /// with the `prepare` method.
316    pub async fn query_opt<T>(
317        &self,
318        statement: &T,
319        params: &[&(dyn ToSql + Sync)],
320    ) -> Result<Option<Row>, Error>
321    where
322        T: ?Sized + ToStatement,
323    {
324        let stream = self.query_raw(statement, slice_iter(params)).await?;
325        pin_mut!(stream);
326
327        let mut first = None;
328
329        // Originally this was two calls to `try_next().await?`,
330        // once for the first element, and second to error if more than one.
331        //
332        // However, this new form with only one .await in a loop generates
333        // slightly smaller codegen/stack usage for the resulting future.
334        while let Some(row) = stream.try_next().await? {
335            if first.is_some() {
336                return Err(Error::row_count());
337            }
338
339            first = Some(row);
340        }
341
342        Ok(first)
343    }
344
345    /// The maximally flexible version of [`query`].
346    ///
347    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
348    /// provided, 1-indexed.
349    ///
350    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
351    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
352    /// with the `prepare` method.
353    ///
354    /// [`query`]: #method.query
355    ///
356    /// # Examples
357    ///
358    /// ```no_run
359    /// # async fn async_main(client: &tokio_postgres::Client) -> Result<(), tokio_postgres::Error> {
360    /// use futures_util::{pin_mut, TryStreamExt};
361    ///
362    /// let params: Vec<String> = vec![
363    ///     "first param".into(),
364    ///     "second param".into(),
365    /// ];
366    /// let mut it = client.query_raw(
367    ///     "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
368    ///     params,
369    /// ).await?;
370    ///
371    /// pin_mut!(it);
372    /// while let Some(row) = it.try_next().await? {
373    ///     let foo: i32 = row.get("foo");
374    ///     println!("foo: {}", foo);
375    /// }
376    /// # Ok(())
377    /// # }
378    /// ```
379    pub async fn query_raw<T, P, I>(&self, statement: &T, params: I) -> Result<RowStream, Error>
380    where
381        T: ?Sized + ToStatement,
382        P: BorrowToSql,
383        I: IntoIterator<Item = P>,
384        I::IntoIter: ExactSizeIterator,
385    {
386        let statement = statement.__convert().into_statement(self).await?;
387        query::query(&self.inner, statement, params).await
388    }
389
390    /// Like `query_raw`, but allows specifying the result format (text or binary).
391    ///
392    /// With `ResultFormat::Text`, PostgreSQL returns column values as UTF-8 strings —
393    /// the same format the pg Node.js library receives. This is useful for building
394    /// driver adapters for ORMs that apply their own type parsing.
395    pub async fn query_raw_with_format<T, P, I>(
396        &self,
397        statement: &T,
398        params: I,
399        result_format: crate::ResultFormat,
400    ) -> Result<RowStream, Error>
401    where
402        T: ?Sized + ToStatement,
403        P: BorrowToSql,
404        I: IntoIterator<Item = P>,
405        I::IntoIter: ExactSizeIterator,
406    {
407        let statement = statement.__convert().into_statement(self).await?;
408        query::query_with_format(&self.inner, statement, params, result_format).await
409    }
410
411    /// Like `query_raw_with_format`, with each result column in its own format:
412    /// `formats` holds one per column of `statement`, in order. Each row says
413    /// which format a column is in (`Row::format`).
414    ///
415    /// A caller that decodes some types itself and wants the server's text for
416    /// the rest prepares the statement, picks a format for each of its
417    /// `columns()`, and runs it with this: the statement is described once,
418    /// with no round trip beyond what `query_raw` makes for a query string.
419    ///
420    /// Fails without sending anything if `formats` does not have one format
421    /// per column.
422    pub async fn query_raw_with_formats<P, I>(
423        &self,
424        statement: &Statement,
425        params: I,
426        formats: &[crate::ResultFormat],
427    ) -> Result<RowStream, Error>
428    where
429        P: BorrowToSql,
430        I: IntoIterator<Item = P>,
431        I::IntoIter: ExactSizeIterator,
432    {
433        query::query_with_column_formats(&self.inner, statement.clone(), params, formats).await
434    }
435
436    /// Like `query`, but requires the types of query parameters to be explicitly specified.
437    ///
438    /// Compared to `query`, this method allows performing queries without three round trips (for
439    /// prepare, execute, and close) by requiring the caller to specify parameter values along with
440    /// their Postgres type. Thus, this is suitable in environments where prepared statements aren't
441    /// supported (such as Cloudflare Workers with Hyperdrive).
442    ///
443    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the
444    /// parameter of the list provided, 1-indexed.
445    pub async fn query_typed(
446        &self,
447        query: &str,
448        params: &[(&(dyn ToSql + Sync), Type)],
449    ) -> Result<Vec<Row>, Error> {
450        self.query_typed_raw(query, params.iter().map(|(v, t)| (*v, t.clone())))
451            .await?
452            .try_collect()
453            .await
454    }
455
456    /// The maximally flexible version of [`query_typed`].
457    ///
458    /// Compared to `query`, this method allows performing queries without three round trips (for
459    /// prepare, execute, and close) by requiring the caller to specify parameter values along with
460    /// their Postgres type. Thus, this is suitable in environments where prepared statements aren't
461    /// supported (such as Cloudflare Workers with Hyperdrive).
462    ///
463    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the
464    /// parameter of the list provided, 1-indexed.
465    ///
466    /// [`query_typed`]: #method.query_typed
467    ///
468    /// # Examples
469    ///
470    /// ```no_run
471    /// # async fn async_main(client: &tokio_postgres::Client) -> Result<(), tokio_postgres::Error> {
472    /// use futures_util::{pin_mut, TryStreamExt};
473    /// use tokio_postgres::types::Type;
474    ///
475    /// let params: Vec<(String, Type)> = vec![
476    ///     ("first param".into(), Type::TEXT),
477    ///     ("second param".into(), Type::TEXT),
478    /// ];
479    /// let mut it = client.query_typed_raw(
480    ///     "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
481    ///     params,
482    /// ).await?;
483    ///
484    /// pin_mut!(it);
485    /// while let Some(row) = it.try_next().await? {
486    ///     let foo: i32 = row.get("foo");
487    ///     println!("foo: {}", foo);
488    /// }
489    /// # Ok(())
490    /// # }
491    /// ```
492    pub async fn query_typed_raw<P, I>(&self, query: &str, params: I) -> Result<RowStream, Error>
493    where
494        P: BorrowToSql,
495        I: IntoIterator<Item = (P, Type)>,
496    {
497        query::query_typed(&self.inner, query, params).await
498    }
499
500    /// Executes a statement, returning the number of rows modified.
501    ///
502    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
503    /// provided, 1-indexed.
504    ///
505    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
506    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
507    /// with the `prepare` method.
508    ///
509    /// If the statement does not modify any rows (e.g. `SELECT`), 0 is returned.
510    pub async fn execute<T>(
511        &self,
512        statement: &T,
513        params: &[&(dyn ToSql + Sync)],
514    ) -> Result<u64, Error>
515    where
516        T: ?Sized + ToStatement,
517    {
518        self.execute_raw(statement, slice_iter(params)).await
519    }
520
521    /// The maximally flexible version of [`execute`].
522    ///
523    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
524    /// provided, 1-indexed.
525    ///
526    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
527    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
528    /// with the `prepare` method.
529    ///
530    /// [`execute`]: #method.execute
531    pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
532    where
533        T: ?Sized + ToStatement,
534        P: BorrowToSql,
535        I: IntoIterator<Item = P>,
536        I::IntoIter: ExactSizeIterator,
537    {
538        let statement = statement.__convert().into_statement(self).await?;
539        query::execute(self.inner(), statement, params).await
540    }
541
542    /// Executes a `COPY FROM STDIN` statement, returning a sink used to write the copy data.
543    ///
544    /// PostgreSQL does not support parameters in `COPY` statements, so this method does not take any. The copy *must*
545    /// be explicitly completed via the `Sink::close` or `finish` methods. If it is not, the copy will be aborted.
546    pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
547    where
548        T: ?Sized + ToStatement,
549        U: Buf + 'static + Send,
550    {
551        let statement = statement.__convert().into_statement(self).await?;
552        copy_in::copy_in(self.inner(), statement).await
553    }
554
555    /// Executes a `COPY TO STDOUT` statement, returning a stream of the resulting data.
556    ///
557    /// PostgreSQL does not support parameters in `COPY` statements, so this method does not take any.
558    pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
559    where
560        T: ?Sized + ToStatement,
561    {
562        let statement = statement.__convert().into_statement(self).await?;
563        copy_out::copy_out(self.inner(), statement).await
564    }
565
566    /// Executes a sequence of SQL statements using the simple query protocol, returning the resulting rows.
567    ///
568    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
569    /// point. The simple query protocol returns the values in rows as strings rather than in their binary encodings,
570    /// so the associated row type doesn't work with the `FromSql` trait. Rather than simply returning a list of the
571    /// rows, this method returns a list of an enum which indicates either the completion of one of the commands,
572    /// or a row of data. This preserves the framing between the separate statements in the request.
573    ///
574    /// # Warning
575    ///
576    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
577    /// functionality to safely embed that data in the request. Do not form statements via string concatenation and pass
578    /// them to this method!
579    pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
580        self.simple_query_raw(query).await?.try_collect().await
581    }
582
583    pub(crate) async fn simple_query_raw(&self, query: &str) -> Result<SimpleQueryStream, Error> {
584        simple_query::simple_query(self.inner(), query).await
585    }
586
587    /// Executes a sequence of SQL statements using the simple query protocol.
588    ///
589    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
590    /// point. This is intended for use when, for example, initializing a database schema.
591    ///
592    /// # Warning
593    ///
594    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
595    /// functionality to safely embed that data in the request. Do not form statements via string concatenation and pass
596    /// them to this method!
597    pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
598        simple_query::batch_execute(self.inner(), query).await
599    }
600
601    /// Begins a new database transaction.
602    ///
603    /// The transaction will roll back by default - use the `commit` method to commit it.
604    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
605        self.build_transaction().start().await
606    }
607
608    /// Returns a builder for a transaction with custom settings.
609    ///
610    /// Unlike the `transaction` method, the builder can be used to control the transaction's isolation level and other
611    /// attributes.
612    pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
613        TransactionBuilder::new(self)
614    }
615
616    /// Constructs a cancellation token that can later be used to request cancellation of a query running on the
617    /// connection associated with this client.
618    pub fn cancel_token(&self) -> CancelToken {
619        CancelToken {
620            #[cfg(feature = "runtime")]
621            socket_config: self.socket_config.clone(),
622            ssl_mode: self.ssl_mode,
623            ssl_negotiation: self.ssl_negotiation,
624            process_id: self.process_id,
625            secret_key: self.secret_key,
626        }
627    }
628
629    /// Attempts to cancel an in-progress query.
630    ///
631    /// The server provides no information about whether a cancellation attempt was successful or not. An error will
632    /// only be returned if the client was unable to connect to the database.
633    ///
634    /// Requires the `runtime` Cargo feature (enabled by default).
635    #[cfg(feature = "runtime")]
636    #[deprecated(since = "0.6.0", note = "use Client::cancel_token() instead")]
637    pub async fn cancel_query<T>(&self, tls: T) -> Result<(), Error>
638    where
639        T: MakeTlsConnect<Socket>,
640    {
641        self.cancel_token().cancel_query(tls).await
642    }
643
644    /// Like `cancel_query`, but uses a stream which is already connected to the server rather than opening a new
645    /// connection itself.
646    #[deprecated(since = "0.6.0", note = "use Client::cancel_token() instead")]
647    pub async fn cancel_query_raw<S, T>(&self, stream: S, tls: T) -> Result<(), Error>
648    where
649        S: AsyncRead + AsyncWrite + Unpin,
650        T: TlsConnect<S>,
651    {
652        self.cancel_token().cancel_query_raw(stream, tls).await
653    }
654
655    /// Clears the client's type information cache.
656    ///
657    /// When user-defined types are used in a query, the client loads their definitions from the database and caches
658    /// them for the lifetime of the client. If those definitions are changed in the database, this method can be used
659    /// to flush the local cache and allow the new, updated definitions to be loaded.
660    pub fn clear_type_cache(&self) {
661        self.inner().clear_type_cache();
662    }
663
664    /// Determines if the connection to the server has already closed.
665    ///
666    /// In that case, all future queries will fail.
667    pub fn is_closed(&self) -> bool {
668        self.inner.sender.is_closed()
669    }
670
671    #[doc(hidden)]
672    pub fn __private_api_close(&mut self) {
673        self.inner.sender.close_channel()
674    }
675
676    #[doc(hidden)]
677    pub fn __private_api_rollback(&self, name: Option<&str>) {
678        let buf = self.inner().with_buf(|buf| {
679            if let Some(name) = name {
680                frontend::query(&format!("ROLLBACK TO {}", name), buf).unwrap();
681            } else {
682                frontend::query("ROLLBACK", buf).unwrap();
683            }
684            buf.split().freeze()
685        });
686        let _ = self
687            .inner()
688            .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
689    }
690}
691
692impl fmt::Debug for Client {
693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
694        f.debug_struct("Client").finish()
695    }
696}