Yoda/src/profile/database.rs

68 lines
1.4 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 bookmark::Bookmark;
2024-11-12 17:07:00 +02:00
use history::History;
2024-11-12 12:30:12 +02:00
use identity::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
match connection.try_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
}
}
2024-11-12 12:30:12 +02:00
// Tools
fn init(mut connection: RwLockWriteGuard<'_, Connection>) -> Result<(), Error> {
// Create transaction
let transaction = connection.transaction()?;
// Init profile components
Bookmark::init(&transaction)?;
2024-11-12 17:07:00 +02:00
History::init(&transaction)?;
2024-11-12 12:30:12 +02:00
Identity::init(&transaction)?;
// Apply changes
transaction.commit()?;
Ok(())
}