draft profile db components

This commit is contained in:
yggverse 2024-11-12 12:30:12 +02:00
parent 0dee053e36
commit e84b9d4fb1
3 changed files with 97 additions and 8 deletions

View file

@ -1,5 +1,15 @@
use sqlite::Connection;
use std::{path::Path, rc::Rc, sync::RwLock};
mod bookmark;
mod identity;
use bookmark::Bookmark;
use identity::Identity;
use sqlite::{Connection, Error};
use std::{
path::Path,
rc::Rc,
sync::{RwLock, RwLockWriteGuard},
};
pub struct Database {
connection: Rc<RwLock<Connection>>,
@ -8,13 +18,26 @@ pub struct Database {
impl Database {
// Constructors
/// Create new connected `Self`
pub fn new(path: &Path) -> Self {
Self {
connection: match Connection::open(path) {
Ok(connection) => Rc::new(RwLock::new(connection)),
Err(reason) => panic!("{reason}"),
},
}
// 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
@ -23,3 +46,19 @@ impl Database {
&self.connection
}
}
// Tools
fn init(mut connection: RwLockWriteGuard<'_, Connection>) -> Result<(), Error> {
// Create transaction
let transaction = connection.transaction()?;
// Init profile components
Bookmark::init(&transaction)?;
Identity::init(&transaction)?;
// Apply changes
transaction.commit()?;
Ok(())
}