rvault/src/storage.rs
2025-06-17 10:11:50 -07:00

41 lines
1.2 KiB
Rust

pub mod sealing;
use std::{fs::File, path::Path};
use log::*;
use sqlx::{Pool, Sqlite, sqlite::SqlitePoolOptions};
pub(crate) type DbType = Sqlite;
pub(crate) type DbPool = Pool<DbType>;
/// Creates a SQLx SQLite database pool.
/// If nonexistent, it creates a new SQLite file.
///
/// Note: rvault uses compile-time queries.
/// Hence, during development a migrated SQLite file is required.
/// Use `cargo sqlx database reset` if required.
/// Otherwise, set the env var `SQLX_OFFLINE=true` during compilation (not helpful for development).
pub async fn create_pool(db_url: String) -> DbPool {
// Create SQLite database file if it does not exist
if db_url.starts_with("sqlite:") && db_url != ("sqlite::memory:") {
let path = db_url.replace("sqlite:", "");
if !Path::new(&path).exists() {
warn!("Sqlite database does not exist, creating file {path}");
File::create(&path).expect("Failed to create database file");
}
}
let pool = SqlitePoolOptions::new()
.max_connections(5)
.test_before_acquire(true)
.connect(&db_url)
.await
.expect(&db_url);
sqlx::migrate!()
.run(&pool)
.await
.expect("Failed to apply migrations");
pool
}