From 666dec74df05d1a82ad35e029f159accb304a71e Mon Sep 17 00:00:00 2001 From: Tobias Bieniek Date: Mon, 28 Oct 2024 23:47:15 +0100 Subject: [PATCH] AsyncConnectionWrapper: Implement `Deref` This allows us to use an `AsyncConnectionWrapper` instance with sync **and** async queries, which should slightly ease the migration from sync to async. --- src/async_connection_wrapper.rs | 15 +++++++++++++++ tests/sync_wrapper.rs | 20 +++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/async_connection_wrapper.rs b/src/async_connection_wrapper.rs index 29bc428..427db0a 100644 --- a/src/async_connection_wrapper.rs +++ b/src/async_connection_wrapper.rs @@ -101,6 +101,7 @@ pub use self::implementation::AsyncConnectionWrapper; mod implementation { use diesel::connection::{Instrumentation, SimpleConnection}; + use std::ops::{Deref, DerefMut}; use super::*; @@ -122,6 +123,20 @@ mod implementation { } } + impl Deref for AsyncConnectionWrapper { + type Target = C; + + fn deref(&self) -> &Self::Target { + &self.inner + } + } + + impl DerefMut for AsyncConnectionWrapper { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } + } + impl diesel::connection::SimpleConnection for AsyncConnectionWrapper where C: crate::SimpleAsyncConnection, diff --git a/tests/sync_wrapper.rs b/tests/sync_wrapper.rs index 309a9f4..9a5373b 100644 --- a/tests/sync_wrapper.rs +++ b/tests/sync_wrapper.rs @@ -1,9 +1,11 @@ use diesel::migration::Migration; -use diesel::prelude::*; +use diesel::{Connection, IntoSql}; use diesel_async::async_connection_wrapper::AsyncConnectionWrapper; #[test] fn test_sync_wrapper() { + use diesel::RunQueryDsl; + let db_url = std::env::var("DATABASE_URL").unwrap(); let mut conn = AsyncConnectionWrapper::::establish(&db_url).unwrap(); @@ -12,8 +14,24 @@ fn test_sync_wrapper() { assert_eq!(Ok(1), res); } +#[tokio::test] +async fn test_sync_wrapper_async_query() { + use diesel_async::{AsyncConnection, RunQueryDsl}; + + let db_url = std::env::var("DATABASE_URL").unwrap(); + let conn = crate::TestConnection::establish(&db_url).await.unwrap(); + let mut conn = AsyncConnectionWrapper::<_>::from(conn); + + let res = diesel::select(1.into_sql::()) + .get_result::(&mut conn) + .await; + assert_eq!(Ok(1), res); +} + #[tokio::test] async fn test_sync_wrapper_under_runtime() { + use diesel::RunQueryDsl; + let db_url = std::env::var("DATABASE_URL").unwrap(); tokio::task::spawn_blocking(move || { let mut conn = AsyncConnectionWrapper::::establish(&db_url).unwrap();