Asnim P Ansari
Asnim P Ansari

Reputation: 2487

How do I load SQLX records to Vec of structs in Rust

I have a table named instruments with the following fields:

I have defined a Rust struct as below

pub struct Instrument {
    pub id: i64,
    pub instrument_token: i32,
    pub tradingsymbol: Option<String>,
}

I query and create a Vec<Instrument> inside a function as follows using SQLX

     let records = sqlx::query!(r"select * from instruments").fetch_all(&app_context.db_connection).await?;


        let mut all_instruments: Vec<Instrument> = Vec::new();
        for rec in records {
            all_instruments.push(Instrument {
                id: rec.id,
                instrument_token: rec.instrument_token,
                tradingsymbol: rec.tradingsymbol,
            });
        }

Here &app_context.db_connection is &pool instance.

Is this there a better way to load records to a struct using SQLX. If yes how?

Upvotes: 4

Views: 6390

Answers (1)

Freyja
Freyja

Reputation: 40884

If your record and data type have the same field names and types, you can use query_as! instead:

let records: Vec<Instrument> =
    sqlx::query_as!(Instrument, r"select * from instruments")
        .fetch_all(&app_context.db_connection)
        .await?;

Upvotes: 6

Related Questions