1

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?

Herohtar
  • 5,347
  • 4
  • 31
  • 41
discodowney
  • 1,475
  • 6
  • 28
  • 58
  • What does it even mean to query for generic type? The SQL table has some shape. You need to conform to this shape. So you need a specific type. – Chayim Friedman Apr 05 '22 at 21:57
  • I'm wanting to do a similar thing, and in my case the common feature of query rows is that they can be displayed (implements Display). – philwalk Jul 25 '22 at 17:06

0 Answers0