xxai_tokio_postgres/
client.rs

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