Works on ingredients

This commit is contained in:
2019-02-03 15:17:43 +01:00
parent 28afe8ece0
commit d3259c82b3
10 changed files with 151 additions and 61 deletions

View File

@@ -57,8 +57,7 @@ pub mod fields {
}
impl<DB: Backend> FromSql<SmallInt, DB> for RecipeCategory
where
i16: FromSql<SmallInt, DB>
where i16: FromSql<SmallInt, DB>
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
let v = i16::from_sql(bytes)?;
@@ -68,13 +67,70 @@ pub mod fields {
}
impl<DB: Backend> ToSql<SmallInt, DB> for RecipeCategory
where
i16: ToSql<SmallInt, DB>{
where i16: ToSql<SmallInt, DB>
{
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
i16::to_sql(&(*self as i16), out)
}
}
pub type IngredientId = i32;
#[derive(Debug, Clone, FromSqlRow, AsExpression)]
#[sql_type = "Text"]
pub struct IngredientList(Vec<IngredientId>);
/// Just a basic method for now
impl IngredientList {
pub fn new() -> Self {
IngredientList(Vec::new())
}
pub fn as_string(&self) -> String {
self.0.iter()
.map(|i| format!("{}", i))
.collect::<Vec<String>>()
.join(" ")
}
}
impl std::ops::Deref for IngredientList {
type Target = Vec<IngredientId>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for IngredientList {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<DB: Backend> FromSql<Text, DB> for IngredientList
where String: FromSql<Text, DB>
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
let data = String::from_sql(bytes)?;
Ok(
IngredientList(
data.split(" ")
.map(|i| i.parse::<IngredientId>().unwrap())
.collect()
))
}
}
impl<DB: Backend> ToSql<Text, DB> for IngredientList
where String: ToSql<Text, DB>
{
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
String::to_sql(&self.as_string(), out)
}
}
}
@@ -84,7 +140,7 @@ pub struct Recipe {
pub id: i32,
pub title: String,
pub category: fields::RecipeCategory,
pub ingredients: String,
pub ingredients: fields::IngredientList,
pub preparation: String,
}
@@ -93,20 +149,11 @@ pub struct Recipe {
pub struct NewRecipe<'a> {
pub title: &'a str,
pub category: fields::RecipeCategory,
pub ingredients: &'a str,
pub ingredients: fields::IngredientList,
pub preparation: &'a str,
}
impl<'a> NewRecipe<'a> {
pub fn new(title: &'a str, category: fields::RecipeCategory, ingredients: &'a str, preparation: &'a str) -> Self {
NewRecipe{
title,
category,
ingredients,
preparation,
}
}
pub fn insert(self, conn: &SqliteConnection) -> Result<Self, String> {
diesel::insert_into(recipes::table)
.values(&self)