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,14 +6,10 @@ use self::models::*;
use self::diesel::prelude::*;
fn main() {
use cookbook::schema::recipes::dsl::*;
let conn = establish_connection();
let result = recipes
.load::<Recipe>(&conn)
.expect("Error loading recipes");
println!("Here are {} recipes :", result.len());
let result = recipes::load_all(&conn);
println!("Here are {} recipes [{}]:", result.len(), result.len() * std::mem::size_of::<Recipe>());
for rec in result {
println!("*************\n{}\n({:?})", rec.title, rec.category);
println!("-------------\n");

View File

@@ -27,6 +27,10 @@ impl<'a> CreateRecipe<'a> {
self.title = title;
}
fn set_category(&mut self, id: i16) {
self.category = RecipeCategory::from_id(id);
}
fn add_ingredient(&mut self, name: String) {
use crate::ingredients::*;
@@ -43,7 +47,11 @@ impl<'a> CreateRecipe<'a> {
/// Builds a NewRecipe instance from current data and insert it.
fn insert(self) {
let new_recipe = NewRecipe::new(self.title, 0, &self.ingredients, "");
let new_recipe = NewRecipe::new(
self.title,
self.category.unwrap_or(RecipeCategory::Breakfast),
&self.ingredients,
"");
match new_recipe.insert(self.connection) {
Ok(new) => println!("Added {}", new.title),
Err(e) => println!("Error: {}", e),
@@ -62,6 +70,15 @@ fn main() {
let title = &title[..(title.len() - 1)];
builder.set_title(title);
println!("Category : ");
for cat in &RecipeCategory::all() {
println!("{} - {}", cat.id(), cat.name());
}
let mut category_id = String::new();
stdin().read_line(&mut category_id).unwrap();
let category_id = category_id.trim().parse::<i16>().expect("Could not parse id");
builder.set_category(category_id);
println!("Ingredients (empty line to finish): ");
loop {
let mut ingdts = String::new();
@@ -69,7 +86,7 @@ fn main() {
if &ingdts == "\r\n" {
break;
}
builder.add_ingredient(ingdts.clone());
builder.add_ingredient(ingdts);
}
builder.insert();

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,