Skip to content

Instantly share code, notes, and snippets.

@markazmierczak
Last active March 8, 2022 01:33
Show Gist options
  • Save markazmierczak/f408ac8f5b4f3ca37bfdd5cc22fc3fe4 to your computer and use it in GitHub Desktop.
Save markazmierczak/f408ac8f5b4f3ca37bfdd5cc22fc3fe4 to your computer and use it in GitHub Desktop.
Sqlx - Sqlite Pool
[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"] }
#[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