Yoda/src/profile/database.rs

162 lines
4.1 KiB
Rust
Raw Normal View History

use gtk::glib::DateTime;
use sqlite::{Connection, Error, Transaction};
use std::{rc::Rc, sync::RwLock};
pub struct Table {
pub id: i64,
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> {
2024-11-13 08:10:54 +02:00
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction().unwrap();
2024-11-13 11:36:48 +02:00
select(&tx).unwrap()
}
/// Get active profile record if exist
pub fn active(&self) -> Option<Table> {
self.records().into_iter().find(|record| record.is_active)
}
2024-11-13 08:32:49 +02:00
// Setters
2024-11-13 12:55:36 +02:00
/// Create new record in `Self` database connected
2024-11-14 04:24:32 +02:00
pub fn add(&self, is_active: bool, time: DateTime, name: Option<String>) -> Result<i64, ()> {
2024-11-13 11:36:48 +02:00
// Begin new transaction
2024-11-13 08:32:49 +02:00
let mut writable = self.connection.write().unwrap();
let tx = writable.transaction().unwrap();
2024-11-13 11:36:48 +02:00
// New record has active status
if is_active {
// Deactivate other records as only one profile should be active
for record in select(&tx).unwrap() {
2024-11-14 04:24:32 +02:00
let _ = update(&tx, record.id, false, record.time, record.name);
2024-11-13 11:36:48 +02:00
}
}
2024-11-13 08:32:49 +02:00
2024-11-13 11:36:48 +02:00
// Create new record
insert(&tx, is_active, time, name).unwrap();
// Hold insert ID for result
2024-11-13 08:32:49 +02:00
let id = last_insert_id(&tx);
2024-11-13 11:36:48 +02:00
// Done
2024-11-13 08:32:49 +02:00
match tx.commit() {
Ok(_) => Ok(id),
Err(_) => Err(()), // @TODO
}
}
2024-11-13 12:55:36 +02:00
/* @TODO not in use
2024-11-13 12:55:36 +02:00
/// Set `is_active` status `true` for the record with given profile ID
/// * reset other records to `false`
pub fn activate(&self, id: i64) -> Result<(), ()> {
// Begin new transaction
let mut writable = self.connection.write().unwrap();
let tx = writable.transaction().unwrap();
// Deactivate other records as only one profile should be active
for record in select(&tx).unwrap() {
let _ = update(
&tx,
record.id,
if record.id == id { true } else { false },
record.time,
2024-11-14 04:24:32 +02:00
record.name,
2024-11-13 12:55:36 +02:00
);
}
// Done
match tx.commit() {
Ok(_) => Ok(()),
Err(_) => Err(()),
} // @TODO make sure ID exist and was changed
} */
}
2024-11-13 08:08:54 +02:00
// Low-level DB API
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `profile`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`is_active` INTEGER NOT NULL,
`time` INTEGER NOT NULL,
`name` VARCHAR(255)
)",
[],
)
}
2024-11-13 11:36:48 +02:00
pub fn insert(
tx: &Transaction,
is_active: bool,
2024-11-13 12:55:36 +02:00
time: DateTime,
2024-11-14 04:24:32 +02:00
name: Option<String>,
2024-11-13 11:36:48 +02:00
) -> Result<usize, Error> {
tx.execute(
"INSERT INTO `profile` (
`is_active`,
`time`,
`name`
) VALUES (?, ?, ?)",
(is_active, time.to_unix(), name),
)
}
pub fn update(
2024-11-13 04:48:13 +02:00
tx: &Transaction,
2024-11-13 11:36:48 +02:00
id: i64,
is_active: bool,
2024-11-13 12:55:36 +02:00
time: DateTime,
2024-11-14 04:24:32 +02:00
name: Option<String>,
2024-11-13 04:48:13 +02:00
) -> Result<usize, Error> {
2024-11-13 11:36:48 +02:00
tx.execute(
2024-11-13 12:55:36 +02:00
"UPDATE `profile` SET `is_active` = ?, `time` = ?, `name` = ? WHERE `id` = ?",
2024-11-13 11:36:48 +02:00
(is_active, time.to_unix(), name, id),
)
}
2024-11-12 12:30:12 +02:00
2024-11-13 11:36:48 +02:00
pub fn select(tx: &Transaction) -> Result<Vec<Table>, Error> {
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)?,
is_active: row.get(1)?,
2024-11-13 04:48:13 +02:00
time: DateTime::from_unix_local(row.get(2)?).unwrap(),
name: row.get(3)?,
})
})?;
2024-11-12 12:30:12 +02:00
let mut records = Vec::new();
2024-11-12 12:30:12 +02:00
for record in result {
let table = record?;
records.push(table);
}
Ok(records)
}
2024-11-12 12:30:12 +02:00
pub fn last_insert_id(tx: &Transaction) -> i64 {
tx.last_insert_rowid()
2024-11-12 12:30:12 +02:00
}