Skip to main content

diesel_async/pg/
mod.rs

1//! Provides types and functions related to working with PostgreSQL
2//!
3//! Much of this module is re-exported from database agnostic locations.
4//! However, if you are writing code specifically to extend Diesel on
5//! PostgreSQL, you may need to work with this module directly.
6
7use self::error_helper::ErrorHelper;
8use self::row::PgRow;
9use self::serialize::ToSqlHelper;
10use crate::stmt_cache::{CallbackHelper, QueryFragmentHelper};
11use crate::{AnsiTransactionManager, AsyncConnection, AsyncConnectionCore, SimpleAsyncConnection};
12use diesel::connection::statement_cache::{
13    PrepareForCache, QueryFragmentForCachedStatement, StatementCache,
14};
15use diesel::connection::StrQueryHelper;
16use diesel::connection::{CacheSize, Instrumentation};
17use diesel::connection::{DynInstrumentation, InstrumentationEvent};
18use diesel::pg::{
19    Pg, PgMetadataCache, PgMetadataCacheKey, PgMetadataLookup, PgQueryBuilder, PgTypeMetadata,
20};
21use diesel::query_builder::bind_collector::RawBytesBindCollector;
22use diesel::query_builder::{AsQuery, QueryBuilder, QueryFragment, QueryId};
23use diesel::result::{DatabaseErrorKind, Error};
24use diesel::{ConnectionError, ConnectionResult, QueryResult};
25use futures_core::future::BoxFuture;
26use futures_core::stream::BoxStream;
27use futures_util::future::Either;
28use futures_util::stream::TryStreamExt;
29use futures_util::TryFutureExt;
30use futures_util::{FutureExt, StreamExt};
31use std::collections::{HashMap, HashSet};
32use std::future::Future;
33use std::sync::Arc;
34use tokio::sync::{broadcast, mpsc, oneshot, Mutex};
35use tokio_postgres::types::ToSql;
36use tokio_postgres::types::Type;
37use tokio_postgres::Statement;
38
39pub use self::transaction_builder::TransactionBuilder;
40
41mod error_helper;
42mod row;
43mod serialize;
44mod transaction_builder;
45
46const FAKE_OID: u32 = 0;
47
48/// A connection to a PostgreSQL database.
49///
50/// Connection URLs should be in the form
51/// `postgres://[user[:password]@]host/database_name`
52///
53/// Checkout the documentation of the [tokio_postgres]
54/// crate for details about the format
55///
56/// [tokio_postgres]: https://docs.rs/tokio-postgres/0.7.6/tokio_postgres/config/struct.Config.html#url
57///
58/// ## Pipelining
59///
60/// This connection supports *pipelined* requests. Pipelining can improve performance in use cases in which multiple,
61/// independent queries need to be executed. In a traditional workflow, each query is sent to the server after the
62/// previous query completes. In contrast, pipelining allows the client to send all of the queries to the server up
63/// front, minimizing time spent by one side waiting for the other to finish sending data:
64///
65/// ```not_rust
66///             Sequential                              Pipelined
67/// | Client         | Server          |    | Client         | Server          |
68/// |----------------|-----------------|    |----------------|-----------------|
69/// | send query 1   |                 |    | send query 1   |                 |
70/// |                | process query 1 |    | send query 2   | process query 1 |
71/// | receive rows 1 |                 |    | send query 3   | process query 2 |
72/// | send query 2   |                 |    | receive rows 1 | process query 3 |
73/// |                | process query 2 |    | receive rows 2 |                 |
74/// | receive rows 2 |                 |    | receive rows 3 |                 |
75/// | send query 3   |                 |
76/// |                | process query 3 |
77/// | receive rows 3 |                 |
78/// ```
79///
80/// In both cases, the PostgreSQL server is executing the queries **sequentially** - pipelining just allows both sides of
81/// the connection to work concurrently when possible.
82///
83/// Pipelining happens automatically when futures are polled concurrently (for example, by using the futures `join`
84/// combinator):
85///
86/// ```rust
87/// # include!("../doctest_setup.rs");
88/// use diesel_async::RunQueryDsl;
89///
90/// #
91/// # #[tokio::main(flavor = "current_thread")]
92/// # async fn main() {
93/// #     run_test().await.unwrap();
94/// # }
95/// #
96/// # async fn run_test() -> QueryResult<()> {
97/// #     use diesel::sql_types::{Text, Integer};
98/// #     let conn = establish_connection().await;
99///       let q1 = diesel::select(1_i32.into_sql::<Integer>());
100///       let q2 = diesel::select(2_i32.into_sql::<Integer>());
101///
102///       // construct multiple futures for different queries
103///       let f1 = q1.get_result::<i32>(&mut &conn);
104///       let f2 = q2.get_result::<i32>(&mut &conn);
105///
106///       // wait on both results
107///       let res = futures_util::try_join!(f1, f2)?;
108///
109///       assert_eq!(res.0, 1);
110///       assert_eq!(res.1, 2);
111///       # Ok(())
112/// # }
113/// ```
114///
115/// For more complex cases, an immutable reference to the connection need to be used:
116/// ```rust
117/// # include!("../doctest_setup.rs");
118/// use diesel_async::RunQueryDsl;
119///
120/// #
121/// # #[tokio::main(flavor = "current_thread")]
122/// # async fn main() {
123/// #     run_test().await.unwrap();
124/// # }
125/// #
126/// # async fn run_test() -> QueryResult<()> {
127/// #     use diesel::sql_types::{Text, Integer};
128/// #     let conn = &mut establish_connection().await;
129/// #
130///       async fn fn12(mut conn: &AsyncPgConnection) -> QueryResult<(i32, i32)> {
131///           let f1 = diesel::select(1_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
132///           let f2 = diesel::select(2_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
133///
134///           futures_util::try_join!(f1, f2)
135///       }
136///
137///       async fn fn34(mut conn: &AsyncPgConnection) -> QueryResult<(i32, i32)> {
138///           let f3 = diesel::select(3_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
139///           let f4 = diesel::select(4_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
140///
141///           futures_util::try_join!(f3, f4)
142///       }
143///
144///       let f12 = fn12(&conn);
145///       let f34 = fn34(&conn);
146///
147///       let ((r1, r2), (r3, r4)) = futures_util::try_join!(f12, f34).unwrap();
148///
149///       assert_eq!(r1, 1);
150///       assert_eq!(r2, 2);
151///       assert_eq!(r3, 3);
152///       assert_eq!(r4, 4);
153///       # Ok(())
154/// # }
155/// ```
156///
157/// ## TLS
158///
159/// Connections created by [`AsyncPgConnection::establish`] do not support TLS.
160///
161/// TLS support for tokio_postgres connections is implemented by external crates, e.g. [tokio_postgres_rustls].
162///
163/// [`AsyncPgConnection::try_from_client_and_connection`] can be used to construct a connection from an existing
164/// [`tokio_postgres::Connection`] with TLS enabled.
165///
166/// [tokio_postgres_rustls]: https://docs.rs/tokio-postgres-rustls/0.12.0/tokio_postgres_rustls/
167pub struct AsyncPgConnection {
168    conn: tokio_postgres::Client,
169    stmt_cache: Mutex<StatementCache<diesel::pg::Pg, Statement>>,
170    transaction_state: Mutex<AnsiTransactionManager>,
171    metadata_cache: Mutex<PgMetadataCache>,
172    connection_future: Option<broadcast::Receiver<Arc<tokio_postgres::Error>>>,
173    notification_rx: Option<mpsc::UnboundedReceiver<QueryResult<diesel::pg::PgNotification>>>,
174    shutdown_channel: Option<oneshot::Sender<()>>,
175    // a sync mutex is fine here as we only hold it for a really short time
176    instrumentation: Arc<std::sync::Mutex<DynInstrumentation>>,
177}
178
179impl SimpleAsyncConnection for AsyncPgConnection {
180    async fn batch_execute(&mut self, query: &str) -> QueryResult<()> {
181        SimpleAsyncConnection::batch_execute(&mut &*self, query).await
182    }
183}
184
185impl SimpleAsyncConnection for &AsyncPgConnection {
186    async fn batch_execute(&mut self, query: &str) -> QueryResult<()> {
187        self.record_instrumentation(InstrumentationEvent::start_query(&StrQueryHelper::new(
188            query,
189        )));
190        let connection_future = self.connection_future.as_ref().map(|rx| rx.resubscribe());
191        let batch_execute = self
192            .conn
193            .batch_execute(query)
194            .map_err(ErrorHelper)
195            .map_err(Into::into);
196
197        let r = drive_future(connection_future, batch_execute).await;
198        let r = {
199            let mut transaction_manager = self.transaction_state.lock().await;
200            update_transaction_manager_status(r, &mut transaction_manager)
201        };
202        self.record_instrumentation(InstrumentationEvent::finish_query(
203            &StrQueryHelper::new(query),
204            r.as_ref().err(),
205        ));
206        r
207    }
208}
209
210impl AsyncConnectionCore for AsyncPgConnection {
211    // The returned future must not outlive the connection it borrows.
212    type LoadFuture<'conn, 'query> = BoxFuture<'conn, QueryResult<Self::Stream<'conn, 'query>>>;
213    type ExecuteFuture<'conn, 'query> = BoxFuture<'conn, QueryResult<usize>>;
214    type Stream<'conn, 'query> = BoxStream<'static, QueryResult<PgRow>>;
215    type Row<'conn, 'query> = PgRow;
216    type Backend = diesel::pg::Pg;
217
218    fn load<'conn, 'query, T>(&'conn mut self, source: T) -> Self::LoadFuture<'conn, 'query>
219    where
220        T: AsQuery + 'query,
221        T::Query: QueryFragment<Self::Backend> + QueryId + 'query,
222    {
223        let query = source.as_query();
224        let load_future = self.with_prepared_statement(query, load_prepared);
225
226        self.run_with_connection_future(load_future)
227    }
228
229    fn execute_returning_count<'conn, 'query, T>(
230        &'conn mut self,
231        source: T,
232    ) -> Self::ExecuteFuture<'conn, 'query>
233    where
234        T: QueryFragment<Self::Backend> + QueryId + 'query,
235    {
236        let execute = self.with_prepared_statement(source, execute_prepared);
237        self.run_with_connection_future(execute)
238    }
239}
240
241// Enable query pipelining via shared references while binding futures
242// to the lifetime of the borrowed connection.
243impl<'a> AsyncConnectionCore for &'a AsyncPgConnection {
244    type LoadFuture<'conn, 'query> = BoxFuture<'a, QueryResult<Self::Stream<'conn, 'query>>>;
245    type ExecuteFuture<'conn, 'query> = BoxFuture<'a, QueryResult<usize>>;
246    type Stream<'conn, 'query> = BoxStream<'static, QueryResult<PgRow>>;
247    type Row<'conn, 'query> = PgRow;
248    type Backend = diesel::pg::Pg;
249
250    fn load<'conn, 'query, T>(&'conn mut self, source: T) -> Self::LoadFuture<'conn, 'query>
251    where
252        T: AsQuery + 'query,
253        T::Query: QueryFragment<Self::Backend> + QueryId + 'query,
254    {
255        let query = source.as_query();
256        let load_future = self.with_prepared_statement(query, load_prepared);
257
258        self.run_with_connection_future(load_future)
259    }
260
261    fn execute_returning_count<'conn, 'query, T>(
262        &'conn mut self,
263        source: T,
264    ) -> Self::ExecuteFuture<'conn, 'query>
265    where
266        T: QueryFragment<Self::Backend> + QueryId + 'query,
267    {
268        let execute = self.with_prepared_statement(source, execute_prepared);
269        self.run_with_connection_future(execute)
270    }
271}
272
273impl AsyncConnection for AsyncPgConnection {
274    type TransactionManager = AnsiTransactionManager;
275
276    async fn establish(database_url: &str) -> ConnectionResult<Self> {
277        let mut instrumentation = DynInstrumentation::default_instrumentation();
278        instrumentation.on_connection_event(InstrumentationEvent::start_establish_connection(
279            database_url,
280        ));
281        let instrumentation = Arc::new(std::sync::Mutex::new(instrumentation));
282        let (client, connection) = tokio_postgres::connect(database_url, tokio_postgres::NoTls)
283            .await
284            .map_err(ErrorHelper)?;
285
286        let (error_rx, notification_rx, shutdown_tx) = drive_connection(connection);
287
288        let r = Self::setup(
289            client,
290            Some(error_rx),
291            Some(notification_rx),
292            Some(shutdown_tx),
293            Arc::clone(&instrumentation),
294        )
295        .await;
296
297        instrumentation
298            .lock()
299            .unwrap_or_else(|e| e.into_inner())
300            .on_connection_event(InstrumentationEvent::finish_establish_connection(
301                database_url,
302                r.as_ref().err(),
303            ));
304        r
305    }
306
307    fn transaction_state(&mut self) -> &mut AnsiTransactionManager {
308        self.transaction_state.get_mut()
309    }
310
311    fn instrumentation(&mut self) -> &mut dyn Instrumentation {
312        // there should be no other pending future when this is called
313        // that means there is only one instance of this arc and
314        // we can simply access the inner data
315        if let Some(instrumentation) = Arc::get_mut(&mut self.instrumentation) {
316            &mut **(instrumentation.get_mut().unwrap_or_else(|p| p.into_inner()))
317        } else {
318            panic!("Cannot access shared instrumentation")
319        }
320    }
321
322    fn set_instrumentation(&mut self, instrumentation: impl Instrumentation) {
323        self.instrumentation = Arc::new(std::sync::Mutex::new(instrumentation.into()));
324    }
325
326    fn set_prepared_statement_cache_size(&mut self, size: CacheSize) {
327        self.stmt_cache.get_mut().set_cache_size(size)
328    }
329}
330
331impl Drop for AsyncPgConnection {
332    fn drop(&mut self) {
333        if let Some(tx) = self.shutdown_channel.take() {
334            let _ = tx.send(());
335        }
336    }
337}
338
339async fn load_prepared(
340    conn: &tokio_postgres::Client,
341    stmt: Statement,
342    binds: Vec<ToSqlHelper>,
343) -> QueryResult<BoxStream<'static, QueryResult<PgRow>>> {
344    let res = conn.query_raw(&stmt, binds).await.map_err(ErrorHelper)?;
345
346    Ok(res
347        .map_err(|e| diesel::result::Error::from(ErrorHelper(e)))
348        .map_ok(PgRow::new)
349        .boxed())
350}
351
352async fn execute_prepared(
353    conn: &tokio_postgres::Client,
354    stmt: Statement,
355    binds: Vec<ToSqlHelper>,
356) -> QueryResult<usize> {
357    let binds = binds
358        .iter()
359        .map(|b| b as &(dyn ToSql + Sync))
360        .collect::<Vec<_>>();
361
362    let res = tokio_postgres::Client::execute(conn, &stmt, &binds as &[_])
363        .await
364        .map_err(ErrorHelper)?;
365    res.try_into()
366        .map_err(|e| diesel::result::Error::DeserializationError(Box::new(e)))
367}
368
369#[inline(always)]
370fn update_transaction_manager_status<T>(
371    query_result: QueryResult<T>,
372    transaction_manager: &mut AnsiTransactionManager,
373) -> QueryResult<T> {
374    if let Err(diesel::result::Error::DatabaseError(DatabaseErrorKind::SerializationFailure, _)) =
375        query_result
376    {
377        if !transaction_manager.is_commit {
378            transaction_manager
379                .status
380                .set_requires_rollback_maybe_up_to_top_level(true);
381        }
382    }
383    query_result
384}
385
386fn prepare_statement_helper<'conn>(
387    conn: &'conn tokio_postgres::Client,
388    sql: &str,
389    _is_for_cache: PrepareForCache,
390    metadata: &[PgTypeMetadata],
391) -> CallbackHelper<
392    impl Future<Output = QueryResult<(Statement, &'conn tokio_postgres::Client)>> + Send,
393> {
394    let bind_types = metadata
395        .iter()
396        .map(type_from_oid)
397        .collect::<QueryResult<Vec<_>>>();
398    // ideally we wouldn't clone the SQL string here
399    // but as we usually cache statements anyway
400    // this is a fixed one time const
401    //
402    // The probleme with not cloning it is that we then cannot express
403    // the right result lifetime anymore (at least not easily)
404    let sql = sql.to_string();
405    CallbackHelper(async move {
406        let bind_types = bind_types?;
407        let stmt = conn
408            .prepare_typed(&sql, &bind_types)
409            .await
410            .map_err(ErrorHelper);
411        Ok((stmt?, conn))
412    })
413}
414
415fn type_from_oid(t: &PgTypeMetadata) -> QueryResult<Type> {
416    let oid = t
417        .oid()
418        .map_err(|e| diesel::result::Error::SerializationError(Box::new(e) as _))?;
419
420    if let Some(tpe) = Type::from_oid(oid) {
421        return Ok(tpe);
422    }
423
424    Ok(Type::new(
425        format!("diesel_custom_type_{oid}"),
426        oid,
427        tokio_postgres::types::Kind::Simple,
428        "public".into(),
429    ))
430}
431
432impl AsyncPgConnection {
433    /// Build a transaction, specifying additional details such as isolation level
434    ///
435    /// See [`TransactionBuilder`] for more examples.
436    ///
437    /// [`TransactionBuilder`]: crate::pg::TransactionBuilder
438    ///
439    /// ```rust
440    /// # include!("../doctest_setup.rs");
441    /// #
442    /// # #[tokio::main(flavor = "current_thread")]
443    /// # async fn main() {
444    /// #     run_test().await.unwrap();
445    /// # }
446    /// #
447    /// # async fn run_test() -> QueryResult<()> {
448    /// #     use schema::users::dsl::*;
449    /// #     let conn = &mut connection_no_transaction().await;
450    /// conn.build_transaction()
451    ///     .read_only()
452    ///     .serializable()
453    ///     .deferrable()
454    ///     .run(async |conn| Ok(()))
455    ///     .await
456    /// # }
457    /// ```
458    pub fn build_transaction(&mut self) -> TransactionBuilder<'_, Self> {
459        TransactionBuilder::new(self)
460    }
461
462    /// Construct a new `AsyncPgConnection` instance from an existing [`tokio_postgres::Client`]
463    pub async fn try_from(conn: tokio_postgres::Client) -> ConnectionResult<Self> {
464        Self::setup(
465            conn,
466            None,
467            None,
468            None,
469            Arc::new(std::sync::Mutex::new(
470                DynInstrumentation::default_instrumentation(),
471            )),
472        )
473        .await
474    }
475
476    /// Constructs a new `AsyncPgConnection` from an existing [`tokio_postgres::Client`] and
477    /// [`tokio_postgres::Connection`]
478    pub async fn try_from_client_and_connection<S>(
479        client: tokio_postgres::Client,
480        conn: tokio_postgres::Connection<tokio_postgres::Socket, S>,
481    ) -> ConnectionResult<Self>
482    where
483        S: tokio_postgres::tls::TlsStream + Unpin + Send + 'static,
484    {
485        let (error_rx, notification_rx, shutdown_tx) = drive_connection(conn);
486
487        Self::setup(
488            client,
489            Some(error_rx),
490            Some(notification_rx),
491            Some(shutdown_tx),
492            Arc::new(std::sync::Mutex::new(
493                DynInstrumentation::default_instrumentation(),
494            )),
495        )
496        .await
497    }
498
499    async fn setup(
500        conn: tokio_postgres::Client,
501        connection_future: Option<broadcast::Receiver<Arc<tokio_postgres::Error>>>,
502        notification_rx: Option<mpsc::UnboundedReceiver<QueryResult<diesel::pg::PgNotification>>>,
503        shutdown_channel: Option<oneshot::Sender<()>>,
504        instrumentation: Arc<std::sync::Mutex<DynInstrumentation>>,
505    ) -> ConnectionResult<Self> {
506        let mut conn = Self {
507            conn,
508            stmt_cache: Mutex::new(StatementCache::new()),
509            transaction_state: Mutex::new(AnsiTransactionManager::default()),
510            metadata_cache: Mutex::new(PgMetadataCache::new()),
511            connection_future,
512            notification_rx,
513            shutdown_channel,
514            instrumentation,
515        };
516        conn.set_config_options()
517            .await
518            .map_err(ConnectionError::CouldntSetupConfiguration)?;
519        Ok(conn)
520    }
521
522    /// Constructs a cancellation token that can later be used to request cancellation of a query running on the connection associated with this client.
523    pub fn cancel_token(&self) -> tokio_postgres::CancelToken {
524        self.conn.cancel_token()
525    }
526
527    async fn set_config_options(&mut self) -> QueryResult<()> {
528        use crate::run_query_dsl::RunQueryDsl;
529
530        futures_util::future::try_join(
531            diesel::sql_query("SET TIME ZONE 'UTC'").execute(&mut &*self),
532            diesel::sql_query("SET CLIENT_ENCODING TO 'UTF8'").execute(&mut &*self),
533        )
534        .await?;
535        Ok(())
536    }
537
538    fn run_with_connection_future<'a, R: 'a>(
539        &self,
540        future: impl Future<Output = QueryResult<R>> + Send + 'a,
541    ) -> BoxFuture<'a, QueryResult<R>> {
542        let connection_future = self.connection_future.as_ref().map(|rx| rx.resubscribe());
543        drive_future(connection_future, future).boxed()
544    }
545
546    fn with_prepared_statement<'a, T, F, R>(
547        &'a self,
548        query: T,
549        callback: fn(&'a tokio_postgres::Client, Statement, Vec<ToSqlHelper>) -> F,
550    ) -> BoxFuture<'a, QueryResult<R>>
551    where
552        T: QueryFragment<diesel::pg::Pg> + QueryId,
553        F: Future<Output = QueryResult<R>> + Send + 'a,
554        R: Send,
555    {
556        self.record_instrumentation(InstrumentationEvent::start_query(&diesel::debug_query(
557            &query,
558        )));
559        // we explicilty descruct the query here before going into the async block
560        //
561        // That's required to remove the send bound from `T` as we have translated
562        // the query type to just a string (for the SQL) and a bunch of bytes (for the binds)
563        // which both are `Send`.
564        // We also collect the query id (essentially an integer) and the safe_to_cache flag here
565        // so there is no need to even access the query in the async block below
566        let mut query_builder = PgQueryBuilder::default();
567
568        let bind_data = construct_bind_data(&query);
569
570        // The code that doesn't need the `T` generic parameter is in a separate function to reduce LLVM IR lines
571        self.with_prepared_statement_after_sql_built(
572            callback,
573            query.is_safe_to_cache_prepared(&Pg),
574            T::query_id(),
575            query.to_sql(&mut query_builder, &Pg),
576            query_builder,
577            bind_data,
578        )
579    }
580
581    fn with_prepared_statement_after_sql_built<'a, F, R>(
582        &'a self,
583        callback: fn(&'a tokio_postgres::Client, Statement, Vec<ToSqlHelper>) -> F,
584        is_safe_to_cache_prepared: QueryResult<bool>,
585        query_id: Option<std::any::TypeId>,
586        to_sql_result: QueryResult<()>,
587        query_builder: PgQueryBuilder,
588        bind_data: BindData,
589    ) -> BoxFuture<'a, QueryResult<R>>
590    where
591        F: Future<Output = QueryResult<R>> + Send + 'a,
592        R: Send,
593    {
594        let raw_connection = &self.conn;
595        let stmt_cache = &self.stmt_cache;
596        let metadata_cache = &self.metadata_cache;
597        let tm = &self.transaction_state;
598        let instrumentation = self.instrumentation.clone();
599        let BindData {
600            collect_bind_result,
601            fake_oid_locations,
602            generated_oids,
603            mut bind_collector,
604        } = bind_data;
605
606        async move {
607            let sql = to_sql_result.map(|_| query_builder.finish())?;
608            let res = async {
609            let is_safe_to_cache_prepared = is_safe_to_cache_prepared?;
610            collect_bind_result?;
611            // Check whether we need to resolve some types at all
612            //
613            // If the user doesn't use custom types there is no need
614            // to borther with that at all
615            if let Some(ref unresolved_types) = generated_oids {
616                let metadata_cache = &mut *metadata_cache.lock().await;
617                let mut real_oids = HashMap::new();
618
619                for ((schema, lookup_type_name), (fake_oid, fake_array_oid)) in
620                    unresolved_types
621                {
622                    // for each unresolved item
623                    // we check whether it's arleady in the cache
624                    // or perform a lookup and insert it into the cache
625                    let cache_key = PgMetadataCacheKey::new(
626                        schema.as_deref().map(Into::into),
627                        lookup_type_name.into(),
628                    );
629                    let real_metadata = if let Some(type_metadata) =
630                        metadata_cache.lookup_type(&cache_key)
631                    {
632                        type_metadata
633                    } else {
634                        let type_metadata =
635                            lookup_type(schema.clone(), lookup_type_name.clone(), raw_connection)
636                                .await?;
637                        metadata_cache.store_type(cache_key, type_metadata);
638
639                        PgTypeMetadata::from_result(Ok(type_metadata))
640                    };
641                    // let (fake_oid, fake_array_oid) = metadata_lookup.fake_oids(index);
642                    let (real_oid, real_array_oid) = unwrap_oids(&real_metadata);
643                    real_oids.extend([(*fake_oid, real_oid), (*fake_array_oid, real_array_oid)]);
644                }
645
646                // Replace fake OIDs with real OIDs in `bind_collector.metadata`
647                for m in &mut bind_collector.metadata {
648                    let (oid, array_oid) = unwrap_oids(m);
649                    *m = PgTypeMetadata::new(
650                        real_oids.get(&oid).copied().unwrap_or(oid),
651                        real_oids.get(&array_oid).copied().unwrap_or(array_oid)
652                    );
653                }
654                // Replace fake OIDs with real OIDs in `bind_collector.binds`
655                for (bind_index, byte_index) in fake_oid_locations {
656                    replace_fake_oid(&mut bind_collector.binds, &real_oids, bind_index, byte_index)
657                        .ok_or_else(|| {
658                            Error::SerializationError(
659                                format!("diesel_async failed to replace a type OID serialized in bind value {bind_index}").into(),
660                            )
661                        })?;
662                }
663            }
664            let stmt = {
665                let mut stmt_cache = stmt_cache.lock().await;
666                let helper = QueryFragmentHelper {
667                    sql: sql.clone(),
668                    safe_to_cache: is_safe_to_cache_prepared,
669                };
670                let instrumentation = Arc::clone(&instrumentation);
671                stmt_cache
672                    .cached_statement_non_generic(
673                        query_id,
674                        &helper,
675                        &Pg,
676                        &bind_collector.metadata,
677                        raw_connection,
678                        prepare_statement_helper,
679                        &mut move |event: InstrumentationEvent<'_>| {
680                            // we wrap this lock into another callback to prevent locking
681                            // the instrumentation longer than necessary
682                            instrumentation.lock().unwrap_or_else(|e| e.into_inner())
683                                .on_connection_event(event);
684                        },
685                    )
686                    .await?
687                    .0
688                    .clone()
689            };
690
691            let binds = bind_collector
692                .metadata
693                .into_iter()
694                .zip(bind_collector.binds)
695                .map(|(meta, bind)| ToSqlHelper(meta, bind))
696                .collect::<Vec<_>>();
697                callback(raw_connection, stmt.clone(), binds).await
698            };
699            let res = res.await;
700            let mut tm = tm.lock().await;
701            let r = update_transaction_manager_status(res, &mut tm);
702            instrumentation
703                .lock()
704                .unwrap_or_else(|p| p.into_inner())
705                .on_connection_event(InstrumentationEvent::finish_query(
706                    &StrQueryHelper::new(&sql),
707                    r.as_ref().err(),
708                ));
709
710            r
711        }
712        .boxed()
713    }
714
715    fn record_instrumentation(&self, event: InstrumentationEvent<'_>) {
716        self.instrumentation
717            .lock()
718            .unwrap_or_else(|p| p.into_inner())
719            .on_connection_event(event);
720    }
721
722    /// See Postgres documentation for SQL commands [NOTIFY][] and [LISTEN][]
723    ///
724    /// The returned stream yields all notifications received by the connection, not only notifications received
725    /// after calling the function. The returned stream will never close, so no notifications will just result
726    /// in a pending state.
727    ///
728    /// If there's no connection available to poll, the stream will yield no notifications and be pending forever.
729    /// This can happen if you created the [`AsyncPgConnection`] by the [`try_from`] constructor.
730    ///
731    /// [NOTIFY]: https://www.postgresql.org/docs/current/sql-notify.html
732    /// [LISTEN]: https://www.postgresql.org/docs/current/sql-listen.html
733    /// [`AsyncPgConnection`]: crate::pg::AsyncPgConnection
734    /// [`try_from`]: crate::pg::AsyncPgConnection::try_from
735    ///
736    /// ```rust
737    /// # include!("../doctest_setup.rs");
738    /// #
739    /// # #[tokio::main(flavor = "current_thread")]
740    /// # async fn main() {
741    /// #     run_test().await.unwrap();
742    /// # }
743    /// #
744    /// # async fn run_test() -> QueryResult<()> {
745    /// #     use diesel_async::RunQueryDsl;
746    /// #     use futures_util::StreamExt;
747    /// #     let conn = &mut connection_no_transaction().await;
748    /// // register the notifications channel we want to receive notifications for
749    /// diesel::sql_query("LISTEN example_channel").execute(conn).await?;
750    /// // send some notification (usually done from a different connection/thread/application)
751    /// diesel::sql_query("NOTIFY example_channel, 'additional data'").execute(conn).await?;
752    ///
753    /// let mut notifications = std::pin::pin!(conn.notifications_stream());
754    /// let mut notification = notifications.next().await.unwrap().unwrap();
755    ///
756    /// assert_eq!(notification.channel, "example_channel");
757    /// assert_eq!(notification.payload, "additional data");
758    /// println!("Notification received from process with id {}", notification.process_id);
759    /// # Ok(())
760    /// # }
761    /// ```
762    pub fn notifications_stream(
763        &mut self,
764    ) -> impl futures_core::Stream<Item = QueryResult<diesel::pg::PgNotification>> + '_ {
765        match &mut self.notification_rx {
766            None => Either::Left(futures_util::stream::pending()),
767            Some(rx) => Either::Right(futures_util::stream::unfold(rx, |rx| async {
768                rx.recv().await.map(move |item| (item, rx))
769            })),
770        }
771    }
772}
773
774struct BindData {
775    collect_bind_result: Result<(), Error>,
776    fake_oid_locations: Vec<(usize, usize)>,
777    generated_oids: GeneratedOidTypeMap,
778    bind_collector: RawBytesBindCollector<Pg>,
779}
780
781fn construct_bind_data(query: &dyn QueryFragment<diesel::pg::Pg>) -> BindData {
782    // we don't resolve custom types here yet, we do that later
783    // in the async block below as we might need to perform lookup
784    // queries for that.
785    //
786    // We apply this workaround to prevent requiring all the diesel
787    // serialization code to beeing async
788    //
789    // We give out constant fake oids here to optimize for the "happy" path
790    // without custom type lookup
791    let mut bind_collector_0 = RawBytesBindCollector::<diesel::pg::Pg>::new();
792    let mut metadata_lookup_0 = PgAsyncMetadataLookup {
793        custom_oid: false,
794        generated_oids: None,
795        oid_generator: |_, _| (FAKE_OID, FAKE_OID),
796    };
797    let collect_bind_result_0 =
798        query.collect_binds(&mut bind_collector_0, &mut metadata_lookup_0, &Pg);
799    // we have encountered a custom type oid, so we need to perform more work here.
800    // These oids can occure in two locations:
801    //
802    // * In the collected metadata -> relativly easy to resolve, just need to replace them below
803    // * As part of the seralized bind blob -> hard to replace
804    //
805    // To address the second case, we perform a second run of the bind collector
806    // with a different set of fake oids. Then we compare the output of the two runs
807    // and use that information to infer where to replace bytes in the serialized output
808    if metadata_lookup_0.custom_oid {
809        // we try to get the maxium oid we encountered here
810        // to be sure that we don't accidently give out a fake oid below that collides with
811        // something
812        let mut max_oid = bind_collector_0
813            .metadata
814            .iter()
815            .flat_map(|t| {
816                [
817                    t.oid().unwrap_or_default(),
818                    t.array_oid().unwrap_or_default(),
819                ]
820            })
821            .max()
822            .unwrap_or_default();
823        let mut bind_collector_1 = RawBytesBindCollector::<diesel::pg::Pg>::new();
824        let mut metadata_lookup_1 = PgAsyncMetadataLookup {
825            custom_oid: false,
826            generated_oids: Some(HashMap::new()),
827            oid_generator: move |_, _| {
828                max_oid += 2;
829                (max_oid, max_oid + 1)
830            },
831        };
832        let collect_bind_result_1 =
833            query.collect_binds(&mut bind_collector_1, &mut metadata_lookup_1, &Pg);
834
835        assert_eq!(
836            bind_collector_0.binds.len(),
837            bind_collector_0.metadata.len()
838        );
839        let fake_oid_locations = std::iter::zip(
840            bind_collector_0
841                .binds
842                .iter()
843                .zip(&bind_collector_0.metadata),
844            &bind_collector_1.binds,
845        )
846        .enumerate()
847        .flat_map(|(bind_index, ((bytes_0, metadata_0), bytes_1))| {
848            // custom oids might appear in the serialized bind arguments for arrays or composite (record) types
849            // in both cases the relevant buffer is a custom type on it's own
850            // so we only need to check the cases that contain a fake OID on their own
851            let (bytes_0, bytes_1) = if matches!(metadata_0.oid(), Ok(FAKE_OID)) {
852                (
853                    bytes_0.as_deref().unwrap_or_default(),
854                    bytes_1.as_deref().unwrap_or_default(),
855                )
856            } else {
857                // for all other cases, just return an empty
858                // list to make the iteration below a no-op
859                // and prevent the need of boxing
860                (&[] as &[_], &[] as &[_])
861            };
862            let lookup_map = metadata_lookup_1
863                .generated_oids
864                .as_ref()
865                .map(|map| {
866                    map.values()
867                        .flat_map(|(oid, array_oid)| [*oid, *array_oid])
868                        .collect::<HashSet<_>>()
869                })
870                .unwrap_or_default();
871            std::iter::zip(
872                bytes_0.windows(std::mem::size_of_val(&FAKE_OID)),
873                bytes_1.windows(std::mem::size_of_val(&FAKE_OID)),
874            )
875            .enumerate()
876            .filter_map(move |(byte_index, (l, r))| {
877                // here we infer if some byte sequence is a fake oid
878                // We use the following conditions for that:
879                //
880                // * The first byte sequence matches the constant FAKE_OID
881                // * The second sequence does not match the constant FAKE_OID
882                // * The second sequence is contained in the set of generated oid,
883                //   otherwise we get false positives around the boundary
884                //   of a to be replaced byte sequence
885                let r_val = u32::from_be_bytes(r.try_into().expect("That's the right size"));
886                (l == FAKE_OID.to_be_bytes()
887                    && r != FAKE_OID.to_be_bytes()
888                    && lookup_map.contains(&r_val))
889                .then_some((bind_index, byte_index))
890            })
891        })
892        // Avoid storing the bind collectors in the returned Future
893        .collect::<Vec<_>>();
894        BindData {
895            collect_bind_result: collect_bind_result_0.and(collect_bind_result_1),
896            fake_oid_locations,
897            generated_oids: metadata_lookup_1.generated_oids,
898            bind_collector: bind_collector_1,
899        }
900    } else {
901        BindData {
902            collect_bind_result: collect_bind_result_0,
903            fake_oid_locations: Vec::new(),
904            generated_oids: None,
905            bind_collector: bind_collector_0,
906        }
907    }
908}
909
910type GeneratedOidTypeMap = Option<HashMap<(Option<String>, String), (u32, u32)>>;
911
912/// Collects types that need to be looked up, and causes fake OIDs to be written into the bind collector
913/// so they can be replaced with asynchronously fetched OIDs after the original query is dropped
914struct PgAsyncMetadataLookup<F: FnMut(&str, Option<&str>) -> (u32, u32) + 'static> {
915    custom_oid: bool,
916    generated_oids: GeneratedOidTypeMap,
917    oid_generator: F,
918}
919
920impl<F> PgMetadataLookup for PgAsyncMetadataLookup<F>
921where
922    F: FnMut(&str, Option<&str>) -> (u32, u32) + 'static,
923{
924    fn lookup_type(&mut self, type_name: &str, schema: Option<&str>) -> PgTypeMetadata {
925        self.custom_oid = true;
926
927        let oid = if let Some(map) = &mut self.generated_oids {
928            *map.entry((schema.map(ToOwned::to_owned), type_name.to_owned()))
929                .or_insert_with(|| (self.oid_generator)(type_name, schema))
930        } else {
931            (self.oid_generator)(type_name, schema)
932        };
933
934        PgTypeMetadata::from_result(Ok(oid))
935    }
936}
937
938async fn lookup_type(
939    schema: Option<String>,
940    type_name: String,
941    raw_connection: &tokio_postgres::Client,
942) -> QueryResult<(u32, u32)> {
943    let r = if let Some(schema) = schema.as_ref() {
944        raw_connection
945            .query_one(
946                "SELECT pg_type.oid, pg_type.typarray FROM pg_type \
947             INNER JOIN pg_namespace ON pg_type.typnamespace = pg_namespace.oid \
948             WHERE pg_type.typname = $1 AND pg_namespace.nspname = $2 \
949             LIMIT 1",
950                &[&type_name, schema],
951            )
952            .await
953            .map_err(ErrorHelper)?
954    } else {
955        raw_connection
956            .query_one(
957                "SELECT pg_type.oid, pg_type.typarray FROM pg_type \
958             WHERE pg_type.oid = quote_ident($1)::regtype::oid \
959             LIMIT 1",
960                &[&type_name],
961            )
962            .await
963            .map_err(ErrorHelper)?
964    };
965    Ok((r.get(0), r.get(1)))
966}
967
968fn unwrap_oids(metadata: &PgTypeMetadata) -> (u32, u32) {
969    let err_msg = "PgTypeMetadata is supposed to always be Ok here";
970    (
971        metadata.oid().expect(err_msg),
972        metadata.array_oid().expect(err_msg),
973    )
974}
975
976fn replace_fake_oid(
977    binds: &mut [Option<Vec<u8>>],
978    real_oids: &HashMap<u32, u32>,
979    bind_index: usize,
980    byte_index: usize,
981) -> Option<()> {
982    let serialized_oid = binds
983        .get_mut(bind_index)?
984        .as_mut()?
985        .get_mut(byte_index..)?
986        .first_chunk_mut::<4>()?;
987    *serialized_oid = real_oids
988        .get(&u32::from_be_bytes(*serialized_oid))?
989        .to_be_bytes();
990    Some(())
991}
992
993async fn drive_future<R>(
994    connection_future: Option<broadcast::Receiver<Arc<tokio_postgres::Error>>>,
995    client_future: impl Future<Output = Result<R, diesel::result::Error>>,
996) -> Result<R, diesel::result::Error> {
997    if let Some(mut connection_future) = connection_future {
998        let client_future = std::pin::pin!(client_future);
999        let connection_future = std::pin::pin!(connection_future.recv());
1000        match futures_util::future::select(client_future, connection_future).await {
1001            Either::Left((res, _)) => res,
1002            // we got an error from the background task
1003            // return it to the user
1004            Either::Right((Ok(e), _)) => Err(self::error_helper::from_tokio_postgres_error(e)),
1005            // seems like the background thread died for whatever reason
1006            Either::Right((Err(e), _)) => Err(diesel::result::Error::DatabaseError(
1007                DatabaseErrorKind::UnableToSendCommand,
1008                Box::new(e.to_string()),
1009            )),
1010        }
1011    } else {
1012        client_future.await
1013    }
1014}
1015
1016fn drive_connection<S>(
1017    mut conn: tokio_postgres::Connection<tokio_postgres::Socket, S>,
1018) -> (
1019    broadcast::Receiver<Arc<tokio_postgres::Error>>,
1020    mpsc::UnboundedReceiver<QueryResult<diesel::pg::PgNotification>>,
1021    oneshot::Sender<()>,
1022)
1023where
1024    S: tokio_postgres::tls::TlsStream + Unpin + Send + 'static,
1025{
1026    let (error_tx, error_rx) = tokio::sync::broadcast::channel(1);
1027    let (notification_tx, notification_rx) = tokio::sync::mpsc::unbounded_channel();
1028    let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel();
1029    let mut conn = futures_util::stream::poll_fn(move |cx| conn.poll_message(cx));
1030
1031    tokio::spawn(async move {
1032        loop {
1033            match futures_util::future::select(&mut shutdown_rx, conn.next()).await {
1034                Either::Left(_) | Either::Right((None, _)) => break,
1035                Either::Right((Some(Ok(tokio_postgres::AsyncMessage::Notification(notif))), _)) => {
1036                    let _: Result<_, _> = notification_tx.send(Ok(diesel::pg::PgNotification {
1037                        process_id: notif.process_id(),
1038                        channel: notif.channel().to_owned(),
1039                        payload: notif.payload().to_owned(),
1040                    }));
1041                }
1042                Either::Right((Some(Ok(_)), _)) => {}
1043                Either::Right((Some(Err(e)), _)) => {
1044                    let e = Arc::new(e);
1045                    let _: Result<_, _> = error_tx.send(e.clone());
1046                    let _: Result<_, _> =
1047                        notification_tx.send(Err(error_helper::from_tokio_postgres_error(e)));
1048                    break;
1049                }
1050            }
1051        }
1052    });
1053
1054    (error_rx, notification_rx, shutdown_tx)
1055}
1056
1057#[cfg(any(
1058    feature = "deadpool",
1059    feature = "bb8",
1060    feature = "mobc",
1061    feature = "r2d2"
1062))]
1063impl crate::pooled_connection::PoolableConnection for AsyncPgConnection {
1064    fn is_broken(&mut self) -> bool {
1065        use crate::TransactionManager;
1066
1067        Self::TransactionManager::is_broken_transaction_manager(self) || self.conn.is_closed()
1068    }
1069}
1070
1071impl QueryFragmentForCachedStatement<Pg> for QueryFragmentHelper {
1072    fn construct_sql(&self, _backend: &Pg) -> QueryResult<String> {
1073        Ok(self.sql.clone())
1074    }
1075
1076    fn is_safe_to_cache_prepared(&self, _backend: &Pg) -> QueryResult<bool> {
1077        Ok(self.safe_to_cache)
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use super::*;
1084    use crate::run_query_dsl::RunQueryDsl;
1085    use diesel::sql_types::Integer;
1086    use diesel::IntoSql;
1087    use futures_util::future::try_join;
1088
1089    #[tokio::test]
1090    async fn pipelining() {
1091        let database_url =
1092            std::env::var("DATABASE_URL").expect("DATABASE_URL must be set in order to run tests");
1093
1094        let conn = crate::AsyncPgConnection::establish(&database_url)
1095            .await
1096            .unwrap();
1097
1098        let q1 = diesel::select(1_i32.into_sql::<Integer>());
1099        let q2 = diesel::select(2_i32.into_sql::<Integer>());
1100
1101        let f1 = q1.get_result::<i32>(&mut &conn);
1102        let f2 = q2.get_result::<i32>(&mut &conn);
1103
1104        let (r1, r2) = try_join(f1, f2).await.unwrap();
1105
1106        assert_eq!(r1, 1);
1107        assert_eq!(r2, 2);
1108    }
1109
1110    #[tokio::test]
1111    async fn pipelining_with_composed_futures() {
1112        let database_url =
1113            std::env::var("DATABASE_URL").expect("DATABASE_URL must be set in order to run tests");
1114
1115        let conn = crate::AsyncPgConnection::establish(&database_url)
1116            .await
1117            .unwrap();
1118
1119        async fn fn12(mut conn: &AsyncPgConnection) -> QueryResult<(i32, i32)> {
1120            let f1 = diesel::select(1_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1121            let f2 = diesel::select(2_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1122
1123            try_join(f1, f2).await
1124        }
1125
1126        async fn fn34(mut conn: &AsyncPgConnection) -> QueryResult<(i32, i32)> {
1127            let f3 = diesel::select(3_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1128            let f4 = diesel::select(4_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1129
1130            try_join(f3, f4).await
1131        }
1132
1133        let f12 = fn12(&conn);
1134        let f34 = fn34(&conn);
1135
1136        let ((r1, r2), (r3, r4)) = try_join(f12, f34).await.unwrap();
1137
1138        assert_eq!(r1, 1);
1139        assert_eq!(r2, 2);
1140        assert_eq!(r3, 3);
1141        assert_eq!(r4, 4);
1142    }
1143
1144    #[tokio::test]
1145    async fn pipelining_with_composed_futures_and_transaction() {
1146        let database_url =
1147            std::env::var("DATABASE_URL").expect("DATABASE_URL must be set in order to run tests");
1148
1149        let mut conn = crate::AsyncPgConnection::establish(&database_url)
1150            .await
1151            .unwrap();
1152
1153        async fn fn12(mut conn: &AsyncPgConnection) -> QueryResult<(i32, i32)> {
1154            let f1 = diesel::select(1_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1155            let f2 = diesel::select(2_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1156
1157            try_join(f1, f2).await
1158        }
1159
1160        async fn fn37(
1161            mut conn: &AsyncPgConnection,
1162        ) -> QueryResult<(usize, (Vec<i32>, (i32, (Vec<i32>, i32))))> {
1163            let f3 = diesel::select(0_i32.into_sql::<Integer>()).execute(&mut conn);
1164            let f4 = diesel::select(4_i32.into_sql::<Integer>()).load::<i32>(&mut conn);
1165            let f5 = diesel::select(5_i32.into_sql::<Integer>()).get_result::<i32>(&mut conn);
1166            let f6 = diesel::select(6_i32.into_sql::<Integer>()).get_results::<i32>(&mut conn);
1167            let f7 = diesel::select(7_i32.into_sql::<Integer>()).first::<i32>(&mut conn);
1168
1169            try_join(f3, try_join(f4, try_join(f5, try_join(f6, f7)))).await
1170        }
1171
1172        conn.transaction(async |conn| {
1173            let f12 = fn12(conn);
1174            let f37 = fn37(conn);
1175
1176            let ((r1, r2), (r3, (r4, (r5, (r6, r7))))) = try_join(f12, f37).await.unwrap();
1177
1178            assert_eq!(r1, 1);
1179            assert_eq!(r2, 2);
1180            assert_eq!(r3, 1);
1181            assert_eq!(r4, vec![4]);
1182            assert_eq!(r5, 5);
1183            assert_eq!(r6, vec![6]);
1184            assert_eq!(r7, 7);
1185
1186            fn12(conn).await?;
1187            fn37(conn).await?;
1188
1189            QueryResult::<_>::Ok(())
1190        })
1191        .await
1192        .unwrap();
1193    }
1194}