move error handle outside

This commit is contained in:
yggverse 2024-10-04 02:57:50 +03:00
parent caee762103
commit 73ab25efdf
2 changed files with 13 additions and 34 deletions

View File

@ -31,8 +31,11 @@ pub struct App {
impl App { impl App {
// Construct // Construct
pub fn new(profile_database_connection: Arc<Connection>) -> Self { pub fn new(profile_database_connection: Arc<Connection>) -> Self {
// Init app database model // Init database model
let database = Arc::new(Database::init(profile_database_connection)); let database = match Database::init(profile_database_connection) {
Ok(database) => Arc::new(database),
Err(e) => panic!("{e}"), // @TODO
};
// Init actions // Init actions
let action_debug = Action::new("win", true); let action_debug = Action::new("win", true);

View File

@ -1,8 +1,6 @@
use sqlite::{Connection, Error}; use sqlite::{Connection, Error};
use std::sync::Arc; use std::sync::Arc;
const DEBUG: bool = true; // @TODO
pub struct Table { pub struct Table {
pub id: i64, pub id: i64,
pub time: i64, pub time: i64,
@ -13,33 +11,21 @@ pub struct Database {
} }
impl Database { impl Database {
pub fn init(connection: Arc<Connection>) -> Database { pub fn init(connection: Arc<Connection>) -> Result<Database, Error> {
// Init app table connection.execute(
if let Err(error) = connection.execute(
"CREATE TABLE IF NOT EXISTS `app` "CREATE TABLE IF NOT EXISTS `app`
( (
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`time` INTEGER NOT NULL DEFAULT CURRENT_TIMESTAMP `time` INTEGER NOT NULL DEFAULT CURRENT_TIMESTAMP
)", )",
[], [],
) { )?;
panic!("{error}"); // @TODO
Ok(Self { connection })
} }
// Return struct pub fn add(&self) -> Result<usize, Error> {
Self { connection } self.connection.execute("INSERT INTO `app`", [])
}
pub fn add(&self) -> Result<usize, String> {
return match self.connection.execute("INSERT INTO `app`", []) {
Ok(total) => {
if DEBUG {
println!("Inserted {total} row to `app` table");
}
Ok(total)
}
Err(error) => Err(error.to_string()),
};
} }
pub fn records(&self) -> Result<Vec<Table>, Error> { pub fn records(&self) -> Result<Vec<Table>, Error> {
@ -57,19 +43,9 @@ impl Database {
Ok(records) Ok(records)
} }
pub fn delete(&self, id: i64) -> Result<usize, String> { pub fn delete(&self, id: i64) -> Result<usize, Error> {
return match self self.connection
.connection
.execute("DELETE FROM `app` WHERE `id` = ?", [id]) .execute("DELETE FROM `app` WHERE `id` = ?", [id])
{
Ok(total) => {
if DEBUG {
println!("Deleted {total} row(s) from `app` table");
}
Ok(total)
}
Err(error) => Err(error.to_string()),
};
} }
pub fn last_insert_id(&self) -> i64 { pub fn last_insert_id(&self) -> i64 {