1use 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
48pub 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 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 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
241impl<'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 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 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 pub fn build_transaction(&mut self) -> TransactionBuilder<'_, Self> {
459 TransactionBuilder::new(self)
460 }
461
462 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 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 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 let mut query_builder = PgQueryBuilder::default();
567
568 let bind_data = construct_bind_data(&query);
569
570 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 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 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 (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 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 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 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 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 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 if metadata_lookup_0.custom_oid {
809 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 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 (&[] 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 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 .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
912struct 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 Either::Right((Ok(e), _)) => Err(self::error_helper::from_tokio_postgres_error(e)),
1005 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}