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},
|
|
|
|
};
|
2024-11-08 07:46:25 +02:00
|
|
|
|
|
|
|
pub struct Database {
|
|
|
|
connection: Rc<RwLock<Connection>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Database {
|
|
|
|
// Constructors
|
|
|
|
|
2024-11-12 12:30:12 +02:00
|
|
|
/// Create new connected `Self`
|
2024-11-08 07:46:25 +02:00
|
|
|
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 }
|
2024-11-08 07:46:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
2024-11-12 17:22:07 +02:00
|
|
|
bookmark::init(&transaction)?;
|
|
|
|
history::init(&transaction)?;
|
|
|
|
identity::init(&transaction)?;
|
2024-11-12 12:30:12 +02:00
|
|
|
|
|
|
|
// Apply changes
|
|
|
|
transaction.commit()?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|