1 year ago

#379247

test-img

discodowney

Generic query function

Im not sure if what im asking for here is even possible in Rust but ill give it an ask anyway. So thanks to some helpful people on here I am able to use the sqlx::query_as! macro to query data from a mysql database and return it as the passed in type. Im wondering if this could be placed in a generic function.

So I have a DB struct that holds all the database information. Currently its just the pool that gets created. I would like to add a query function to that and any time someone wants to query the data they use that function instead of an explicit call to sqlx.

So im thinking it would look something like:

use sqlx::mysql::MySqlPoolOptions;
use sqlx::mysql::MySqlPool;
use core::any::Any;


pub struct DB {
    pub pool: MySqlPool

}
impl DB {
    #[tokio::main]
    pub async fn query<T> (&self) -> Result<Vec<T>, sqlx::Error>  {
        let recs = sqlx::query_as!(T,
            "
                SELECT name
                FROM rooms
            "
        )
            .fetch_all(&self.pool)
            .await?;

        Ok(recs)
    }
}
#[tokio::main]
pub async fn initializeSqlx(url: &str) -> Result<DB, sqlx::Error>{
    println!("Initializing!");
    let pool = MySqlPoolOptions::new()
        .max_connections(5)
        .connect(url).await?;
    //let conn = pool.get_conn().unwrap();
    let db = DB {
        pool
    };
    return Ok(db);
}

the query function as presented above is obviously incorrect. But is there a way to indicate I want to be able to query for any object type and the return should return an array of that type?

rust

rust-sqlx

0 Answers

Your Answer

Accepted video resources