Yoda/src/profile/database.rs
2024-11-12 17:37:47 +02:00

64 lines
1.3 KiB
Rust

mod bookmark;
mod history;
mod identity;
use sqlite::{Connection, Error};
use std::{
path::Path,
rc::Rc,
sync::{RwLock, RwLockWriteGuard},
};
pub struct Database {
connection: Rc<RwLock<Connection>>,
}
impl Database {
// Constructors
/// Create new connected `Self`
pub fn new(path: &Path) -> Self {
// Init database connection
let connection = match Connection::open(path) {
Ok(connection) => Rc::new(RwLock::new(connection)),
Err(reason) => panic!("{reason}"),
};
// Init profile components
match connection.write() {
Ok(writable) => {
if let Err(reason) = init(writable) {
panic!("{reason}")
}
}
Err(reason) => panic!("{reason}"),
};
// Result
Self { connection }
}
// Getters
pub fn connection(&self) -> &Rc<RwLock<Connection>> {
&self.connection
}
}
// Tools
fn init(mut connection: RwLockWriteGuard<'_, Connection>) -> Result<(), Error> {
// Begin transaction
let transaction = connection.transaction()?;
// Init profile components
bookmark::init(&transaction)?;
history::init(&transaction)?;
identity::init(&transaction)?;
// Apply changes
transaction.commit()?;
Ok(())
}