move profile components to separated namespace

This commit is contained in:
yggverse 2024-11-13 03:40:29 +02:00
parent 61010e0a42
commit b12f5e8b8f
13 changed files with 332 additions and 214 deletions

View file

@ -1,63 +1,41 @@
mod bookmark;
mod history;
mod identity;
use sqlite::{Error, Transaction};
use sqlite::{Connection, Error};
use std::{
path::Path,
rc::Rc,
sync::{RwLock, RwLockWriteGuard},
};
pub struct Database {
connection: Rc<RwLock<Connection>>,
pub struct Table {
pub id: i64,
}
impl Database {
// Constructors
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `profile`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
)",
[],
)
}
/// 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}"),
};
pub fn add(tx: &Transaction) -> Result<usize, Error> {
tx.execute("INSERT INTO `profile` DEFAULT VALUES", [])
}
// Init profile components
match connection.write() {
Ok(writable) => {
if let Err(reason) = init(writable) {
panic!("{reason}")
}
}
Err(reason) => panic!("{reason}"),
};
pub fn records(tx: &Transaction) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare("SELECT `profile_id` FROM `profile`")?;
let result = stmt.query_map([], |row| Ok(Table { id: row.get(0)? }))?;
// Result
Self { connection }
let mut records = Vec::new();
for record in result {
let table = record?;
records.push(table);
}
// Getters
pub fn connection(&self) -> &Rc<RwLock<Connection>> {
&self.connection
}
Ok(records)
}
// 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(())
pub fn delete(tx: &Transaction, id: &i64) -> Result<usize, Error> {
tx.execute("DELETE FROM `profile` WHERE `id` = ?", [id])
}
pub fn last_insert_id(tx: &Transaction) -> i64 {
tx.last_insert_rowid()
}