use sqlx::{ database::Database, database::HasValueRef, sqlite::{Sqlite, SqliteRow}, Decode, Row, }; use std::convert; use std::error; use std::fmt; use std::str::FromStr; use uuid::Uuid; use sqlx::sqlite::SqlitePoolOptions; use futures::TryFutureExt; use futures::TryStreamExt; pub enum Error { SqlError { description: String }, UuidError { description: String }, NotFoundError { description: String }, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::SqlError { description } => { write!(f, "SQL error: {description}") } Self::UuidError { description } => { write!(f, "UUID error: {description}") } Self::NotFoundError { description } => { write!(f, "Not found: {description}") } } } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // defer to Display write!(f, "SQL error: {self}") } } impl convert::From for Error { fn from(value: uuid::Error) -> Self { Error::UuidError { description: value.to_string(), } } } impl convert::From for Error { fn from(value: sqlx::Error) -> Self { Error::SqlError { description: value.to_string(), } } } impl error::Error for Error {} #[derive(sqlx::Type)] pub enum TripState { Planning, Planned, Active, Review, Done, } impl fmt::Display for TripState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { Self::Planning => "Planning", Self::Planned => "Planned", Self::Active => "Active", Self::Review => "Review", Self::Done => "Done", }, ) } } pub struct Trip { pub id: Uuid, pub name: String, pub start_date: time::Date, pub end_date: time::Date, pub state: TripState, pub location: String, pub temp_min: i32, pub temp_max: i32, types: Option>, } impl TryFrom for Trip { type Error = Error; fn try_from(row: SqliteRow) -> Result { let name: &str = row.try_get("name")?; let id: &str = row.try_get("id")?; let start_date: time::Date = row.try_get("start_date")?; let end_date: time::Date = row.try_get("end_date")?; let state: TripState = row.try_get("state")?; let location = row.try_get("location")?; let temp_min = row.try_get("temp_min")?; let temp_max = row.try_get("temp_max")?; let id: Uuid = Uuid::try_parse(id)?; Ok(Trip { id, name: name.to_string(), start_date, end_date, state, location, temp_min, temp_max, types: None, }) } } impl<'a> Trip { pub fn types(&'a self) -> &Vec { self.types .as_ref() .expect("you need to call load_triptypes()") } } impl<'a> Trip { pub async fn load_triptypes( &'a mut self, pool: &sqlx::Pool, ) -> Result<(), Error> { let types = sqlx::query( " SELECT type.id as id, type.name as name, CASE WHEN inner.id IS NOT NULL THEN true ELSE false END AS active FROM triptypes AS type LEFT JOIN ( SELECT type.id as id, type.name as name FROM trips as trip INNER JOIN trips_to_triptypes as ttt ON ttt.trip_id = trip.id INNER JOIN triptypes AS type ON type.id == ttt.trip_type_id WHERE trip.id = ? ) AS inner ON inner.id = type.id ", ) .bind(self.id.to_string()) .fetch(pool) .map_ok(std::convert::TryInto::try_into) .try_collect::>>() .await? .into_iter() .collect::, Error>>()?; self.types = Some(types); Ok(()) } } pub struct TripType { pub id: Uuid, pub name: String, pub active: bool, } impl TryFrom for TripType { type Error = Error; fn try_from(row: SqliteRow) -> Result { let id: Uuid = Uuid::try_parse(row.try_get("id")?)?; let name: String = row.try_get::<&str, _>("name")?.to_string(); let active: bool = row.try_get("active")?; Ok(Self { id, name, active }) } } #[derive(Debug)] pub struct Category { pub id: Uuid, pub name: String, pub description: String, items: Option>, } impl TryFrom for Category { type Error = Error; fn try_from(row: SqliteRow) -> Result { let name: &str = row.try_get("name")?; let description: &str = row.try_get("description")?; let id: Uuid = Uuid::try_parse(row.try_get("id")?)?; Ok(Category { id, name: name.to_string(), description: description.to_string(), items: None, }) } } impl<'a> Category { pub fn items(&'a self) -> &'a Vec { self.items .as_ref() .expect("you need to call populate_items()") } pub fn total_weight(&self) -> u32 { self.items().iter().map(|item| item.weight).sum() } pub async fn populate_items( &'a mut self, pool: &sqlx::Pool, ) -> Result<(), Error> { let items = sqlx::query(&format!( "SELECT id,name,weight,description,category_id FROM inventoryitems WHERE category_id = '{id}'", id = self.id )) .fetch(pool) .map_ok(std::convert::TryInto::try_into) .try_collect::>>() .await? .into_iter() .collect::, Error>>()?; self.items = Some(items); Ok(()) } } #[derive(Debug)] pub struct Item { pub id: Uuid, pub name: String, pub description: String, pub weight: u32, pub category_id: Uuid, } impl TryFrom for Item { type Error = Error; fn try_from(row: SqliteRow) -> Result { let name: &str = row.try_get("name")?; let description: &str = row.try_get("description")?; let weight: u32 = row.try_get("weight")?; let id: Uuid = Uuid::try_parse(row.try_get("id")?)?; let category_id: Uuid = Uuid::try_parse(row.try_get("category_id")?)?; Ok(Item { id, name: name.to_string(), weight, description: description.to_string(), category_id, }) } } impl Item { pub async fn find(pool: &sqlx::Pool, id: Uuid) -> Result, Error> { let item: Result, sqlx::Error> = sqlx::query( "SELECT * FROM inventoryitems AS item WHERE item.id = ?", ) .bind(id.to_string()) .fetch_one(pool) .map_ok(std::convert::TryInto::try_into) .await; match item { Err(e) => match e { sqlx::Error::RowNotFound => Ok(None), _ => Err(e.into()), }, Ok(v) => Ok(Some(v?)), } } pub async fn update( pool: &sqlx::Pool, id: Uuid, name: &str, weight: u32, ) -> Result, Error> { let id: Result, sqlx::Error> = sqlx::query( "UPDATE inventoryitems AS item SET name = ?, weight = ? WHERE item.id = ? RETURNING inventoryitems.category_id AS id ", ) .bind(name) .bind(weight) .bind(id.to_string()) .fetch_one(pool) .map_ok(|row| { let id: &str = row.try_get("id")?; let uuid: Result = Uuid::try_parse(id); let uuid: Result = uuid.map_err(|e| e.into()); uuid }) .await; match id { Err(e) => match e { sqlx::Error::RowNotFound => Ok(None), _ => Err(e.into()), }, Ok(v) => Ok(Some(v?)), } } }