Last active
March 2, 2024 12:03
-
-
Save fancellu/2a19a184bffb7b71201e439a3a464acc to your computer and use it in GitHub Desktop.
Rust sqlx example
This file contains hidden or 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 futures::TryStreamExt; | |
use sqlx::postgres::{PgPoolOptions, PgRow}; | |
use sqlx::{Error, PgPool, Row}; | |
use uuid::Uuid; | |
#[derive(sqlx::FromRow, Debug)] | |
struct People { | |
id: i32, | |
name: String, | |
} | |
#[derive(Debug, sqlx::FromRow)] | |
struct GeneratedId { | |
id: i32, | |
} | |
async fn insert_person(pool: &PgPool, name: String) -> Result<GeneratedId, Error> { | |
let sql = "INSERT INTO dino.People (name) VALUES ($1) returning id"; | |
let id = sqlx::query_as::<_, GeneratedId>(sql) | |
.bind(name) | |
.fetch_one(pool) | |
.await?; | |
Ok(id) | |
} | |
#[tokio::main] | |
async fn main() -> Result<(), sqlx::Error> { | |
let pool = PgPoolOptions::new() | |
.max_connections(3) | |
.connect("postgres://postgres:pw@localhost/postgres") | |
.await?; | |
let uuid = Uuid::new_v4(); | |
let id = insert_person(&pool, format!("person {}", uuid)).await?; | |
println!("inserted id: {}", id.id); | |
// I could have used fetch_all to get a Vec and not a stream | |
let mut stream = sqlx::query_as::<_, People>("SELECT * FROM dino.People").fetch(&pool); | |
// iterate on stream | |
while let Some(people) = stream.try_next().await? { | |
println!("{} {}", people.id, people.name); | |
} | |
let count_row: PgRow = sqlx::query("SELECT COUNT(*) FROM dino.People") | |
.fetch_one(&pool) | |
.await?; | |
let count: i64 = count_row.get(0); | |
println!("Count: {}", count); | |
Ok(()) | |
} |
Output
inserted id: 4
1 Dino
2 Jenny
3 person 22fdc09e-7a89-42b8-bcf2-6e82ffded0d8
4 person 88203d90-6a7b-428e-88e6-6b7a8efbc77b
Count: 4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cargo.toml
[package]
name = "sqlx_stuff"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1.36.0", features = ["rt", "rt-multi-thread", "macros", "time","sync"] }
sqlx = { version = "0.7.3", features = [ "runtime-tokio","postgres" ] }
futures = "0.3.30"
uuid= { version = "1.7.0", features = ["v4", "fast-rng"] }