Last active
March 8, 2022 01:33
-
-
Save markazmierczak/f408ac8f5b4f3ca37bfdd5cc22fc3fe4 to your computer and use it in GitHub Desktop.
Sqlx - Sqlite Pool
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 = "sqlx-pool-sqlite" | |
version = "0.1.0" | |
edition = "2018" | |
[dependencies] | |
sqlx = { version = "0.4", default-features = false, features = [ "runtime-tokio-native-tls", "macros", "sqlite" ] } | |
tokio = { version = "0.2", features = ["full"] } |
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
#[tokio::main] | |
async fn main() { | |
let db = sqlx::pool::PoolOptions::<sqlx::Sqlite>::new() | |
.max_connections(16) | |
.connect_with(sqlx::sqlite::SqliteConnectOptions::new().filename("/tmp/test-sqlx.db")) | |
.await | |
.unwrap(); | |
{ | |
let mut handles = vec![]; | |
for _ in 0usize..16 { | |
let mut h = db.acquire().await.unwrap(); | |
sqlx::query("PRAGMA synchronous=NORMAL") | |
.execute(&mut h) | |
.await | |
.unwrap(); | |
handles.push(h); | |
} | |
} | |
sqlx::query!( | |
"CREATE TABLE IF NOT EXISTS users ( | |
name TEXT PRIMARY KEY NOT NULL | |
); | |
DELETE FROM users; | |
", | |
) | |
.execute(&db) | |
.await | |
.unwrap(); | |
let mut guards = vec![]; | |
for i in 0..16 { | |
let db = db.clone(); | |
let guard = tokio::spawn(async move { | |
for j in 0..10000i32 { | |
drop( | |
sqlx::query!("SELECT * FROM users") | |
.fetch_optional(&db) | |
.await | |
.unwrap(), | |
); | |
let name = format!("John{}a{}", i, j * 2); | |
let name = &name; | |
sqlx::query!("INSERT INTO users VALUES(?)", name) | |
.execute(&db) | |
.await | |
.unwrap(); | |
} | |
}); | |
guards.push(guard); | |
} | |
for guard in guards { | |
guard.await.unwrap(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment