Created
March 16, 2024 04:38
-
-
Save jcbellido/96747902ff4ad97317a5714d868dc8af to your computer and use it in GitHub Desktop.
jcbellido.info: sqlite test utility in rust
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 std::process::Command; | |
use anyhow::Result; | |
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite}; | |
async fn sqlite_migrate_as(migration_dir: &str, path_new_db: &str) -> Result<String> { | |
let cs = format!("sqlite:{}?mode=rwc", path_new_db); | |
let output = Command::new("cargo") | |
.arg("sqlx") | |
.arg("migrate") | |
.arg("run") | |
.arg("--source") | |
.arg(migration_dir) | |
.arg("--database-url") | |
.arg(&cs) | |
.output()?; | |
if !output.status.success() { | |
let stderr = std::str::from_utf8(output.stderr.as_slice())?.to_string(); | |
return Err(anyhow::anyhow!(stderr)); | |
} | |
Ok(cs) | |
} | |
pub async fn sqlite_create( | |
migration_dir: &str, | |
path_new_db: &str, | |
max_connections: u32, | |
) -> Result<Pool<Sqlite>> { | |
let p_output_db = std::path::Path::new(path_new_db); | |
if p_output_db.exists() && p_output_db.is_file() { | |
std::fs::remove_file(p_output_db)?; | |
} | |
let p_migration_dir = std::path::Path::new(migration_dir); | |
if !p_migration_dir.exists() || !p_migration_dir.is_dir() { | |
panic!("Specified migration dir: `{}` not found", migration_dir); | |
} | |
let cs = sqlite_migrate_as(migration_dir, path_new_db).await?; | |
Ok(SqlitePoolOptions::new() | |
.max_connections(max_connections) | |
.connect(&cs) | |
.await?) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment