Yoda/src/profile/database.rs

64 lines
1.3 KiB
Rust
Raw Normal View History

2024-11-12 12:30:12 +02:00
mod bookmark;
2024-11-12 17:07:00 +02:00
mod history;
2024-11-12 12:30:12 +02:00
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
2024-11-12 12:30:12 +02:00
/// Create new connected `Self`
pub fn new(path: &Path) -> Self {
2024-11-12 12:30:12 +02:00
// Init database connection
let connection = match Connection::open(path) {
Ok(connection) => Rc::new(RwLock::new(connection)),
Err(reason) => panic!("{reason}"),
};
// Init profile components
2024-11-12 17:37:47 +02:00
match connection.write() {
2024-11-12 12:30:12 +02:00
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
}
}
2024-11-12 12:30:12 +02:00
// Tools
fn init(mut connection: RwLockWriteGuard<'_, Connection>) -> Result<(), Error> {
2024-11-12 17:24:46 +02:00
// Begin transaction
2024-11-12 12:30:12 +02:00
let transaction = connection.transaction()?;
// Init profile components
bookmark::init(&transaction)?;
history::init(&transaction)?;
identity::init(&transaction)?;
2024-11-12 12:30:12 +02:00
// Apply changes
transaction.commit()?;
Ok(())
}