yb_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    pub(crate) fn get_socket_config(&self) -> Option<SocketConfig> {
218        self.socket_config.clone()
219    }
220
221    /// Creates a new prepared statement.
222    ///
223    /// Prepared statements can be executed repeatedly, and may contain query parameters (indicated by `$1`, `$2`, etc),
224    /// which are set when executed. Prepared statements can only be used with the connection that created them.
225    pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
226        self.prepare_typed(query, &[]).await
227    }
228
229    /// Like `prepare`, but allows the types of query parameters to be explicitly specified.
230    ///
231    /// The list of types may be smaller than the number of parameters - the types of the remaining parameters will be
232    /// inferred. For example, `client.prepare_typed(query, &[])` is equivalent to `client.prepare(query)`.
233    pub async fn prepare_typed(
234        &self,
235        query: &str,
236        parameter_types: &[Type],
237    ) -> Result<Statement, Error> {
238        prepare::prepare(&self.inner, query, parameter_types).await
239    }
240
241    /// Executes a statement, returning a vector of the resulting rows.
242    ///
243    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
244    /// provided, 1-indexed.
245    ///
246    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
247    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
248    /// with the `prepare` method.
249    pub async fn query<T>(
250        &self,
251        statement: &T,
252        params: &[&(dyn ToSql + Sync)],
253    ) -> Result<Vec<Row>, Error>
254    where
255        T: ?Sized + ToStatement,
256    {
257        self.query_raw(statement, slice_iter(params))
258            .await?
259            .try_collect()
260            .await
261    }
262
263    /// Executes a statement which returns a single row, returning it.
264    ///
265    /// Returns an error if the query does not return exactly one row.
266    ///
267    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
268    /// provided, 1-indexed.
269    ///
270    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
271    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
272    /// with the `prepare` method.
273    pub async fn query_one<T>(
274        &self,
275        statement: &T,
276        params: &[&(dyn ToSql + Sync)],
277    ) -> Result<Row, Error>
278    where
279        T: ?Sized + ToStatement,
280    {
281        let stream = self.query_raw(statement, slice_iter(params)).await?;
282        pin_mut!(stream);
283
284        let row = match stream.try_next().await? {
285            Some(row) => row,
286            None => return Err(Error::row_count()),
287        };
288
289        if stream.try_next().await?.is_some() {
290            return Err(Error::row_count());
291        }
292
293        Ok(row)
294    }
295
296    /// Executes a statements which returns zero or one rows, returning it.
297    ///
298    /// Returns an error if the query returns more than one row.
299    ///
300    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
301    /// provided, 1-indexed.
302    ///
303    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
304    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
305    /// with the `prepare` method.
306    pub async fn query_opt<T>(
307        &self,
308        statement: &T,
309        params: &[&(dyn ToSql + Sync)],
310    ) -> Result<Option<Row>, Error>
311    where
312        T: ?Sized + ToStatement,
313    {
314        let stream = self.query_raw(statement, slice_iter(params)).await?;
315        pin_mut!(stream);
316
317        let row = match stream.try_next().await? {
318            Some(row) => row,
319            None => return Ok(None),
320        };
321
322        if stream.try_next().await?.is_some() {
323            return Err(Error::row_count());
324        }
325
326        Ok(Some(row))
327    }
328
329    /// The maximally flexible version of [`query`].
330    ///
331    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
332    /// provided, 1-indexed.
333    ///
334    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
335    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
336    /// with the `prepare` method.
337    ///
338    /// [`query`]: #method.query
339    ///
340    /// # Examples
341    ///
342    /// ```no_run
343    /// # async fn async_main(client: &yb_tokio_postgres::Client) -> Result<(), yb_tokio_postgres::Error> {
344    /// use yb_tokio_postgres::types::ToSql;
345    /// use futures_util::{pin_mut, TryStreamExt};
346    ///
347    /// let params: Vec<String> = vec![
348    ///     "first param".into(),
349    ///     "second param".into(),
350    /// ];
351    /// let mut it = client.query_raw(
352    ///     "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
353    ///     params,
354    /// ).await?;
355    ///
356    /// pin_mut!(it);
357    /// while let Some(row) = it.try_next().await? {
358    ///     let foo: i32 = row.get("foo");
359    ///     println!("foo: {}", foo);
360    /// }
361    /// # Ok(())
362    /// # }
363    /// ```
364    pub async fn query_raw<T, P, I>(&self, statement: &T, params: I) -> Result<RowStream, Error>
365    where
366        T: ?Sized + ToStatement,
367        P: BorrowToSql,
368        I: IntoIterator<Item = P>,
369        I::IntoIter: ExactSizeIterator,
370    {
371        let statement = statement.__convert().into_statement(self).await?;
372        query::query(&self.inner, statement, params).await
373    }
374
375    /// Executes a statement, returning the number of rows modified.
376    ///
377    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
378    /// provided, 1-indexed.
379    ///
380    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
381    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
382    /// with the `prepare` method.
383    ///
384    /// If the statement does not modify any rows (e.g. `SELECT`), 0 is returned.
385    pub async fn execute<T>(
386        &self,
387        statement: &T,
388        params: &[&(dyn ToSql + Sync)],
389    ) -> Result<u64, Error>
390    where
391        T: ?Sized + ToStatement,
392    {
393        self.execute_raw(statement, slice_iter(params)).await
394    }
395
396    /// The maximally flexible version of [`execute`].
397    ///
398    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
399    /// provided, 1-indexed.
400    ///
401    /// The `statement` argument can either be a `Statement`, or a raw query string. If the same statement will be
402    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
403    /// with the `prepare` method.
404    ///
405    /// [`execute`]: #method.execute
406    pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
407    where
408        T: ?Sized + ToStatement,
409        P: BorrowToSql,
410        I: IntoIterator<Item = P>,
411        I::IntoIter: ExactSizeIterator,
412    {
413        let statement = statement.__convert().into_statement(self).await?;
414        query::execute(self.inner(), statement, params).await
415    }
416
417    /// Executes a `COPY FROM STDIN` statement, returning a sink used to write the copy data.
418    ///
419    /// PostgreSQL does not support parameters in `COPY` statements, so this method does not take any. The copy *must*
420    /// be explicitly completed via the `Sink::close` or `finish` methods. If it is not, the copy will be aborted.
421    pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
422    where
423        T: ?Sized + ToStatement,
424        U: Buf + 'static + Send,
425    {
426        let statement = statement.__convert().into_statement(self).await?;
427        copy_in::copy_in(self.inner(), statement).await
428    }
429
430    /// Executes a `COPY TO STDOUT` statement, returning a stream of the resulting data.
431    ///
432    /// PostgreSQL does not support parameters in `COPY` statements, so this method does not take any.
433    pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
434    where
435        T: ?Sized + ToStatement,
436    {
437        let statement = statement.__convert().into_statement(self).await?;
438        copy_out::copy_out(self.inner(), statement).await
439    }
440
441    /// Executes a sequence of SQL statements using the simple query protocol, returning the resulting rows.
442    ///
443    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
444    /// point. The simple query protocol returns the values in rows as strings rather than in their binary encodings,
445    /// so the associated row type doesn't work with the `FromSql` trait. Rather than simply returning a list of the
446    /// rows, this method returns a list of an enum which indicates either the completion of one of the commands,
447    /// or a row of data. This preserves the framing between the separate statements in the request.
448    ///
449    /// # Warning
450    ///
451    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
452    /// functionality to safely embed that data in the request. Do not form statements via string concatenation and pass
453    /// them to this method!
454    pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
455        self.simple_query_raw(query).await?.try_collect().await
456    }
457
458    pub(crate) async fn simple_query_raw(&self, query: &str) -> Result<SimpleQueryStream, Error> {
459        simple_query::simple_query(self.inner(), query).await
460    }
461
462    /// Executes a sequence of SQL statements using the simple query protocol.
463    ///
464    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
465    /// point. This is intended for use when, for example, initializing a database schema.
466    ///
467    /// # Warning
468    ///
469    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
470    /// functionality to safely embed that data in the request. Do not form statements via string concatenation and pass
471    /// them to this method!
472    pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
473        simple_query::batch_execute(self.inner(), query).await
474    }
475
476    /// Begins a new database transaction.
477    ///
478    /// The transaction will roll back by default - use the `commit` method to commit it.
479    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
480        struct RollbackIfNotDone<'me> {
481            client: &'me Client,
482            done: bool,
483        }
484
485        impl<'a> Drop for RollbackIfNotDone<'a> {
486            fn drop(&mut self) {
487                if self.done {
488                    return;
489                }
490
491                let buf = self.client.inner().with_buf(|buf| {
492                    frontend::query("ROLLBACK", buf).unwrap();
493                    buf.split().freeze()
494                });
495                let _ = self
496                    .client
497                    .inner()
498                    .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
499            }
500        }
501
502        // This is done, as `Future` created by this method can be dropped after
503        // `RequestMessages` is synchronously send to the `Connection` by
504        // `batch_execute()`, but before `Responses` is asynchronously polled to
505        // completion. In that case `Transaction` won't be created and thus
506        // won't be rolled back.
507        {
508            let mut cleaner = RollbackIfNotDone {
509                client: self,
510                done: false,
511            };
512            self.batch_execute("BEGIN").await?;
513            cleaner.done = true;
514        }
515
516        Ok(Transaction::new(self))
517    }
518
519    /// Returns a builder for a transaction with custom settings.
520    ///
521    /// Unlike the `transaction` method, the builder can be used to control the transaction's isolation level and other
522    /// attributes.
523    pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
524        TransactionBuilder::new(self)
525    }
526
527    /// Constructs a cancellation token that can later be used to request cancellation of a query running on the
528    /// connection associated with this client.
529    pub fn cancel_token(&self) -> CancelToken {
530        CancelToken {
531            #[cfg(feature = "runtime")]
532            socket_config: self.socket_config.clone(),
533            ssl_mode: self.ssl_mode,
534            process_id: self.process_id,
535            secret_key: self.secret_key,
536        }
537    }
538
539    /// Attempts to cancel an in-progress query.
540    ///
541    /// The server provides no information about whether a cancellation attempt was successful or not. An error will
542    /// only be returned if the client was unable to connect to the database.
543    ///
544    /// Requires the `runtime` Cargo feature (enabled by default).
545    #[cfg(feature = "runtime")]
546    #[deprecated(since = "0.6.0", note = "use Client::cancel_token() instead")]
547    pub async fn cancel_query<T>(&self, tls: T) -> Result<(), Error>
548    where
549        T: MakeTlsConnect<Socket>,
550    {
551        self.cancel_token().cancel_query(tls).await
552    }
553
554    /// Like `cancel_query`, but uses a stream which is already connected to the server rather than opening a new
555    /// connection itself.
556    #[deprecated(since = "0.6.0", note = "use Client::cancel_token() instead")]
557    pub async fn cancel_query_raw<S, T>(&self, stream: S, tls: T) -> Result<(), Error>
558    where
559        S: AsyncRead + AsyncWrite + Unpin,
560        T: TlsConnect<S>,
561    {
562        self.cancel_token().cancel_query_raw(stream, tls).await
563    }
564
565    /// Clears the client's type information cache.
566    ///
567    /// When user-defined types are used in a query, the client loads their definitions from the database and caches
568    /// them for the lifetime of the client. If those definitions are changed in the database, this method can be used
569    /// to flush the local cache and allow the new, updated definitions to be loaded.
570    pub fn clear_type_cache(&self) {
571        self.inner().clear_type_cache();
572    }
573
574    /// Determines if the connection to the server has already closed.
575    ///
576    /// In that case, all future queries will fail.
577    pub fn is_closed(&self) -> bool {
578        self.inner.sender.is_closed()
579    }
580
581    #[doc(hidden)]
582    pub fn __private_api_close(&mut self) {
583        self.inner.sender.close_channel()
584    }
585}
586
587impl fmt::Debug for Client {
588    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589        f.debug_struct("Client").finish()
590    }
591}