Improves fields::RecipeCategory

This commit is contained in:
2019-02-01 21:35:47 +01:00
parent 616f8095e2
commit ee3271f772
4 changed files with 60 additions and 24 deletions

View File

@@ -6,7 +6,7 @@ pub mod fields {
use diesel::{
backend::Backend,
sqlite::Sqlite,
sql_types::SmallInt,
sql_types::*,
deserialize::{self, FromSql},
serialize::{self, Output, ToSql},
};
@@ -16,8 +16,8 @@ pub mod fields {
/// representing the main use of the resulting preparation.
///
/// It is stored as Integer
#[derive(Debug, Clone, FromSqlRow, AsExpression)]
#[repr(i16)]
#[derive(Debug, Copy, Clone, FromSqlRow, AsExpression)]
#[sql_type = "SmallInt"]
pub enum RecipeCategory {
Breakfast = 0,
Starter = 1,
@@ -26,7 +26,27 @@ pub mod fields {
}
impl RecipeCategory {
fn from_id(id: i16) -> Option<RecipeCategory> {
pub fn id(&self) -> i16 {
*self as i16
}
pub fn name(&self) -> &str {
match *self {
RecipeCategory::Breakfast => "Petit-déjeuner",
RecipeCategory::Starter => "Entrée",
RecipeCategory::MainCourse => "Plat principal",
RecipeCategory::Dessert => "Dessert"
}
}
pub fn all() -> [Self; 4] {
[RecipeCategory::Breakfast,
RecipeCategory::Starter,
RecipeCategory::MainCourse,
RecipeCategory::Dessert]
}
pub fn from_id(id: i16) -> Option<RecipeCategory> {
match id {
0 => Some(RecipeCategory::Breakfast),
1 => Some(RecipeCategory::Starter),
@@ -37,19 +57,22 @@ pub mod fields {
}
}
impl FromSql<SmallInt, Sqlite> for RecipeCategory {
fn from_sql(bytes: Option<&<Sqlite as Backend>::RawValue>) -> deserialize::Result<Self> {
if let Some(result) = RecipeCategory::from_id(
<i16 as FromSql<SmallInt,Sqlite>>::from_sql(bytes)?)
{ Ok(result) }
impl<DB: Backend> FromSql<SmallInt, DB> for RecipeCategory
where
i16: FromSql<SmallInt, DB>
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
let v = i16::from_sql(bytes)?;
if let Some(result) = RecipeCategory::from_id(v){ Ok(result) }
else { Err("Invalid RecipeCategory id".into()) }
}
}
impl ToSql<SmallInt, Sqlite> for RecipeCategory {
fn to_sql<W: Write>(&self, out: &mut Output<W, Sqlite>) -> serialize::Result {
let as_int = self.clone() as i16;
<i16 as ToSql<SmallInt, Sqlite>>::to_sql(&as_int, out)
impl<DB: Backend> ToSql<SmallInt, DB> for RecipeCategory
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)
}
}
@@ -66,17 +89,17 @@ pub struct Recipe {
pub preparation: String,
}
#[derive(Insertable)]
#[derive(Insertable, Debug)]
#[table_name="recipes"]
pub struct NewRecipe<'a> {
pub title: &'a str,
pub category: i16,
pub category: fields::RecipeCategory,
pub ingredients: &'a str,
pub preparation: &'a str,
}
impl<'a> NewRecipe<'a> {
pub fn new(title: &'a str, category: i16, ingredients: &'a str, preparation: &'a str) -> Self {
pub fn new(title: &'a str, category: fields::RecipeCategory, ingredients: &'a str, preparation: &'a str) -> Self {
NewRecipe{
title,
category,