Last active
August 4, 2024 22:02
-
-
Save framp/f7a8c372bb470ef4e3a5602c051d8da0 to your computer and use it in GitHub Desktop.
SUM + IN in sqlx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "sqlxxx" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
anyhow = "1.0.86" | |
sqlx = { version = "0.7", features = ["runtime-tokio", "tls-rustls", "sqlite"] } | |
tokio = { version = "1", features = ["macros", "rt-multi-thread"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use sqlx::sqlite::SqlitePool; | |
use sqlx::QueryBuilder; | |
use std::env; | |
#[derive(sqlx::FromRow)] | |
struct SumResult { | |
sum: Option<i64> | |
} | |
#[tokio::main(flavor = "current_thread")] | |
async fn main() -> anyhow::Result<()> { | |
let ids = vec![1,2,3,4]; | |
let pool = SqlitePool::connect(&env::var("DATABASE_URL")?).await?; | |
let mut conn = pool.acquire().await?; | |
let mut query = QueryBuilder::new( | |
"SELECT SUM(n) as sum FROM alfa WHERE id IN ("); | |
let mut separated = query.separated(", "); | |
for id in ids.iter() { | |
separated.push_bind(id); | |
} | |
let q = query.push(")").build_query_as::<SumResult>(); | |
let r = q.fetch_one(&mut *conn).await?; | |
println!("{:?}", r.sum); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment