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; mod bookmark;
use std::{path::Path, rc::Rc, sync::RwLock}; mod identity;
use bookmark::Bookmark;
use identity::Identity;
use sqlite::{Connection, Error};
use std::{
path::Path,
rc::Rc,
sync::{RwLock, RwLockWriteGuard},
};
pub struct Database { pub struct Database {
connection: Rc<RwLock<Connection>>, connection: Rc<RwLock<Connection>>,
@ -8,13 +18,26 @@ pub struct Database {
impl Database { impl Database {
// Constructors // Constructors
/// Create new connected `Self`
pub fn new(path: &Path) -> Self { pub fn new(path: &Path) -> Self {
Self { // Init database connection
connection: match Connection::open(path) { let connection = match Connection::open(path) {
Ok(connection) => Rc::new(RwLock::new(connection)), Ok(connection) => Rc::new(RwLock::new(connection)),
Err(reason) => panic!("{reason}"), 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 // Getters
@ -23,3 +46,19 @@ impl Database {
&self.connection &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(())
}

View File

@ -0,0 +1,24 @@
use sqlite::{Error, Transaction};
pub struct Table {
pub id: i64,
// pub app_id: i64, not in use
}
pub struct Bookmark {
// nothing yet..
}
impl Bookmark {
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `bookmark`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`time` INTEGER NOT NULL,
`data` TEXT
)",
[],
)
}
}

View File

@ -0,0 +1,26 @@
use sqlite::{Error, Transaction};
pub struct Table {
pub id: i64,
// pub app_id: i64, not in use
}
pub struct Identity {
// nothing yet..
}
impl Identity {
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `identity`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`time` INTEGER NOT NULL,
`name` VARCHAR(255),
`crt` TEXT NOT NULL,
`key` TEXT NOT NULL
)",
[],
)
}
}