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