From 811ff64dd08c8835d19c57fd959e42a28d800a53 Mon Sep 17 00:00:00 2001 From: cel 🌸 Date: Sun, 22 Sep 2024 17:35:32 +0100 Subject: WIP: db --- src/db.rs | 40 +++++++++++++++++++++++++++++++++++++--- src/task.rs | 21 +++++++++++++++++++-- 2 files changed, 56 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/db.rs b/src/db.rs index dd35e4d..db5534c 100644 --- a/src/db.rs +++ b/src/db.rs @@ -7,7 +7,7 @@ struct Db { } impl Db { - pub async fn create_task(&self, task: Task) -> Result { + pub async fn create_task(&self, task: Task) -> Result { let id = sqlx::query!( "insert into tasks ( name, cron, archived, description ) values ( ?1, ?2, ?3, ?4 )", task.name, @@ -19,10 +19,44 @@ impl Db { .await? .last_insert_rowid(); - Ok(id) + for category in task.categories.clone() { + let category_id = sqlx::query!( + "insert or ignore into categories ( name ) values ( ?1 )", + category + ) + .execute(&self.pool) + .await? + .last_insert_rowid(); + + sqlx::query!( + "insert into tasks_categories ( task_id, category_id ) values ( ?1, ?2 )", + id, + category_id + ) + .execute(&self.pool) + .await?; + } + + Ok(task.add_id(id)) } - pub async fn read_tasks(&self) -> Result> { + pub async fn read_tasks(&self, select: Vec) -> Result> { + Ok(sqlx::query!("select * from tasks") + .fetch_all(&self.pool) + .await?) + } + + pub async fn update_tasks(&self, select: Vec) -> Result<()> { todo!() } + + pub async fn delete_tasks(&self, select: Vec) -> Result<()> { + todo!() + } +} + +pub enum TaskSelect { + Name(String), + Archived(bool), + Category(String), } diff --git a/src/task.rs b/src/task.rs index dcfe776..59aa502 100644 --- a/src/task.rs +++ b/src/task.rs @@ -1,36 +1,52 @@ use std::{ borrow::{Borrow, Cow}, + collections::HashSet, str::FromStr, }; use chrono::{NaiveDateTime, TimeDelta}; use sqlx::{ encode::IsNull, + prelude::FromRow, sqlite::{SqliteArgumentValue, SqliteTypeInfo, SqliteValue}, Decode, Sqlite, Type, TypeInfo, Value, ValueRef, }; +#[derive(FromRow)] pub struct Task { + id: Option, pub name: String, pub cron: Option, pub archived: bool, pub description: Option, + pub categories: HashSet, } impl Task { pub fn new( name: String, cron: Option, - archived: bool, description: Option, + categories: Option>, ) -> Self { Self { + id: None, name, cron, - archived, + archived: false, description, + categories: categories.unwrap_or_else(|| HashSet::new()), } } + + pub fn id(&self) -> Option { + self.id + } + + pub fn add_id(mut self, id: i64) -> Self { + self.id = Some(id); + self + } } pub struct Schedule(cron::Schedule); @@ -64,6 +80,7 @@ impl Type for Schedule { } } +#[repr(transparent)] pub struct Category(String); impl Category { -- cgit