Search code examples
rustrust-sqlx

Is there a more concise way to get single column results from (Rust) SQLx?


Currently I have:

/// The format which SQLx will use to return our rows.
#[derive(sqlx::FromRow, Debug)]
struct FooRow {
    foo: String,
}

pub async fn page(
    Extension(pool): Extension<PgPool>,
    ...
) -> PageTemplate {
    // find the available callsigns
    let rows = sqlx::query_as::<_, FooRow>(r#"SELECT foo FROM bar GROUP BY foo"#)
    .fetch_all(&pool)
    .await
    .unwrap();

    let foos: Vec<String> = rows.into_iter().map(|foo_row| foo_row.callsign).collect();

String does not implement FromRow and so I always need a wrapper struct.

Is there a more concise way of getting a column of Strings from SQLx, without needing a wrapper struct and iteration mapping?


Solution

  • Use query_scalar, which is the function for this exact purpose:

    let rows: Vec<String> = sqlx::query_scalar::<_, String>(r#"SELECT foo FROM bar GROUP BY foo"#)
        .fetch_all(&pool)
        .await?;