draft profile database implementation, make members public, run initial dialog, rename field from active to is_active

This commit is contained in:
yggverse 2024-11-13 08:03:48 +02:00
parent b0ee52c3f4
commit 4d7b61ef59
4 changed files with 81 additions and 54 deletions

View file

@ -1,22 +1,60 @@
use sqlite::{Error, Transaction};
use gtk::glib::DateTime;
use sqlite::{Connection, Error, Transaction};
use std::{rc::Rc, sync::RwLock};
#[derive(Debug)]
pub struct Table {
pub id: i64,
pub active: bool,
pub is_active: bool,
pub time: DateTime,
pub name: Option<String>,
}
pub struct Database {
pub connection: Rc<RwLock<Connection>>,
}
impl Database {
// Constructors
/// Create new `Self`
pub fn new(connection: Rc<RwLock<Connection>>) -> Self {
Self { connection }
}
// Getters
/// Get all records
pub fn records(&self) -> Vec<Table> {
let binding = self.connection.read().unwrap();
let tx = binding.unchecked_transaction().unwrap();
records(&tx).unwrap()
}
/// Get selected profile record if exist
pub fn selected(&self) -> Option<Table> {
let binding = self.connection.read().unwrap();
let tx = binding.unchecked_transaction().unwrap();
for record in records(&tx).unwrap() {
if record.is_active {
return Some(record);
}
}
None
}
}
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `profile`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`active` INTEGER NOT NULL,
`time` INTEGER NOT NULL,
`name` VARCHAR(255)
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`is_active` INTEGER NOT NULL,
`time` INTEGER NOT NULL,
`name` VARCHAR(255)
)",
[],
)
@ -24,19 +62,19 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
pub fn add(
tx: &Transaction,
active: bool,
is_active: bool,
time: &DateTime,
name: Option<&str>,
) -> Result<usize, Error> {
tx.execute("INSERT INTO `profile`", (active, time.to_unix(), name))
tx.execute("INSERT INTO `profile`", (is_active, time.to_unix(), name))
}
pub fn records(tx: &Transaction) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare("SELECT `id`, `active`, `time`, `name` FROM `profile`")?;
let mut stmt = tx.prepare("SELECT `id`, `is_active`, `time`, `name` FROM `profile`")?;
let result = stmt.query_map([], |row| {
Ok(Table {
id: row.get(0)?,
active: row.get(1)?,
is_active: row.get(1)?,
time: DateTime::from_unix_local(row.get(2)?).unwrap(),
name: row.get(3)?,
})