Skip to content

Conversation

smiera
Copy link

@smiera smiera commented Apr 15, 2025

I need to create Pool and/or Conn wrapper. Wrapper I use for limit or extend some functionality.
It would be great to be able implement, for example, ToConnection for my wrapper.

Example

impl<'a> ToConnection<'a, 'static> for &'a MyPoolWrapper {
    fn to_connection(self) -> ToConnectionResult<'a, 'static> {
        // ... get conn logic
        ToConnectionResult::Mediate(fut)
    }
}
// ...
#[tokio::test]
async fn test_pool() {
    let pool = MyPoolWrapper::new("mysql://localhost:3306");
    let result: Option<u32> = "SELECT 1".first(&pool).await.unwrap();
    assert_eq!(1, result.unwrap());
}

UPD: After testing my wrapper, I concluded that in addition to the proposed changes, it would be great to implement the DerefMut trait for Transaction.

For example, I create a trait to extend the Conn:

pub trait Administration {
    fn get_connection(&mut self) -> &mut Conn;

    fn create_database<'a>(&'a mut self, db_name: &'a str) -> BoxFuture<'a, Result<()>>
    where
        Self: Send + Sync,
    {
        async move {
            format!("CREATE SCHEMA IF NOT EXISTS `{}`", db_name)
                .ignore(self.get_connection()).await?;
            Ok(())
        }.boxed()
    }
}

impl Administration for Conn {
    fn get_connection(&mut self) -> &mut Conn {
        self
    }
}

But I can't get a &mut Conn from a Transaction instance, as Transaction does not implement the DerefMut trait.

#[tokio::test]
async fn test_transaction() {
    let mut conn = Conn::from_url("mysql://root:@localhost:3306").await.unwrap();
    // Work!
    conn.create_database("db_1").await.unwrap();
    // Not work!
    let mut trx = conn.start_transaction(Default::default()).await.unwrap();
    trx.database_exists("db_2").await.unwrap();
}
   |
77 |         trx.database_exists("db_2").await.unwrap();
   |         ^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Transaction<'_>`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants