-- Version 1 is the initial structure.
-CREATE TABLE Version (
- id INTEGER PRIMARY KEY,
- version INTEGER NOT NULL UNIQUE,
- datetime DATETIME
+CREATE TABLE [Version] (
+ [id] INTEGER PRIMARY KEY,
+ [version] INTEGER NOT NULL UNIQUE,
+ [datetime] DATETIME
);
-CREATE TABLE User (
- id INTEGER PRIMARY KEY,
- email TEXT NOT NULL,
- password TEXT NOT NULL, -- Hashed and salted.
- name TEXT NOT NULL
+CREATE TABLE [User] (
+ [id] INTEGER PRIMARY KEY,
+ [email] TEXT NOT NULL,
+ [password] TEXT NOT NULL, -- Hashed and salted.
+ [name] TEXT NOT NULL
);
-CREATE TABLE Recipe (
- id INTEGER PRIMARY KEY,
- user_id INTEGER NOT NULL,
- title TEXT NOT NULL,
- estimate_time INTEGER,
- description DATETIME,
+CREATE TABLE [Recipe] (
+ [id] INTEGER PRIMARY KEY,
+ [user_id] INTEGER NOT NULL,
+ [title] TEXT NOT NULL,
+ [estimate_time] INTEGER,
+ [description] TEXT,
- FOREIGN KEY(user_id) REFERENCES User(id)
+ FOREIGN KEY([user_id]) REFERENCES [User]([id])
);
-CREATE TABLE Quantity (
- id INTEGER PRIMARY KEY,
- value REAL,
- unit TEXT
+CREATE TABLE [Quantity] (
+ [id] INTEGER PRIMARY KEY,
+ [value] REAL,
+ [unit] TEXT
);
-CREATE TABLE Ingredient (
- id INTEGER PRIMARY KEY,
- name TEXT NOT NULL,
- quantity_id INTEGER,
- input_step_id INTEGER NOT NULL,
+CREATE TABLE [Ingredient] (
+ [id] INTEGER PRIMARY KEY,
+ [name] TEXT NOT NULL,
+ [quantity_id] INTEGER,
+ [input_step_id] INTEGER NOT NULL,
- FOREIGN KEY(quantity_id) REFERENCES Quantity(id),
- FOREIGN KEY(input_step_id) REFERENCES Step(id)
+ FOREIGN KEY([quantity_id]) REFERENCES Quantity([id]),
+ FOREIGN KEY([input_step_id]) REFERENCES Step([id])
);
CREATE TABLE [Group] (
- id INTEGER PRIMARY KEY,
- name TEXT
+ [id] INTEGER PRIMARY KEY,
+ [order] INTEGER NOT NULL DEFAULT 0,
+ [recipe_id] INTEGER,
+ name TEXT,
+
+ FOREIGN KEY([recipe_id]) REFERENCES [Recipe]([id])
);
-CREATE TABLE Step (
- id INTEGER PRIMARY KEY,
- action TEXT NOT NULL,
- group_id INTEGER NOT NULL,
+CREATE INDEX [Group_order_index] ON [Group] ([order]);
+
+CREATE TABLE [Step] (
+ [id] INTEGER PRIMARY KEY,
+ [order] INTEGER NOT NULL DEFAULT 0,
+ [action] TEXT NOT NULL,
+ [group_id] INTEGER NOT NULL,
FOREIGN KEY(group_id) REFERENCES [Group](id)
);
-CREATE TABLE IntermediateSubstance (
- id INTEGER PRIMARY KEY,
- name TEXT NOT NULL,
- quantity_id INTEGER,
- output_step_id INTEGER NOT NULL,
- input_step_id INTEGER NOT NULL,
+CREATE INDEX [Step_order_index] ON [Group] ([order]);
- FOREIGN KEY(quantity_id) REFERENCES Quantity(id),
- FOREIGN KEY(output_step_id) REFERENCES Step(id),
- FOREIGN KEY(input_step_id) REFERENCES Step(id)
-);
\ No newline at end of file
+CREATE TABLE [IntermediateSubstance] (
+ [id] INTEGER PRIMARY KEY,
+ [name] TEXT NOT NULL,
+ [quantity_id] INTEGER,
+ [output_step_id] INTEGER NOT NULL,
+ [input_step_id] INTEGER NOT NULL,
+
+ FOREIGN KEY([quantity_id]) REFERENCES [Quantity]([id]),
+ FOREIGN KEY([output_step_id]) REFERENCES [Step]([id]),
+ FOREIGN KEY([input_step_id]) REFERENCES [Step]([id])
+);
-use crate::consts::SQL_FILENAME;\r
-\r
-use super::consts;\r
-\r
use std::{fs::{self, File}, path::Path, io::Read};\r
\r
+use itertools::Itertools;\r
//use rusqlite::types::ToSql;\r
//use rusqlite::{Connection, Result, NO_PARAMS};\r
use r2d2::Pool;\r
use r2d2_sqlite::SqliteConnectionManager;\r
\r
+use crate::consts;\r
+use crate::model;\r
+\r
const CURRENT_DB_VERSION: u32 = 1;\r
\r
#[derive(Debug)]\r
Other(String),\r
}\r
\r
-pub struct Connection {\r
- //con: rusqlite::Connection\r
- pool: Pool<SqliteConnectionManager>\r
-}\r
-\r
-pub struct Recipe {\r
- pub title: String,\r
- pub id: i32,\r
-}\r
-\r
-impl std::convert::From<rusqlite::Error> for DBError {\r
+impl From<rusqlite::Error> for DBError {\r
fn from(error: rusqlite::Error) -> Self {\r
DBError::SqliteError(error)\r
}\r
}\r
\r
-impl std::convert::From<r2d2::Error> for DBError {\r
+impl From<r2d2::Error> for DBError {\r
fn from(error: r2d2::Error) -> Self {\r
DBError::R2d2Error(error)\r
}\r
}\r
\r
+type Result<T> = std::result::Result<T, DBError>;\r
+\r
+#[derive(Clone)]\r
+pub struct Connection {\r
+ //con: rusqlite::Connection\r
+ pool: Pool<SqliteConnectionManager>\r
+}\r
+\r
impl Connection {\r
- pub fn new() -> Result<Connection, DBError> {\r
+ pub fn new() -> Result<Connection> {\r
\r
let data_dir = Path::new(consts::DB_DIRECTORY);\r
\r
* Called after the connection has been established for creating or updating the database.\r
* The 'Version' table tracks the current state of the database.\r
*/\r
- fn create_or_update(self: &Self) -> Result<(), DBError> {\r
- // let connection = Connection::new();\r
- // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap();\r
- // let mut stmt = connection.sqlite_con.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap();\r
-\r
+ fn create_or_update(&self) -> Result<()> {\r
// Check the Database version.\r
let mut con = self.pool.get()?;\r
let tx = con.transaction()?;\r
[],\r
|row| row.get::<usize, String>(0)\r
) {\r
- Ok(_) => tx.query_row("SELECT [version] FROM [Version]", [], |row| row.get(0)).unwrap_or_default(),\r
+ Ok(_) => tx.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row| row.get(0)).unwrap_or_default(),\r
Err(_) => 0\r
}\r
};\r
Ok(())\r
}\r
\r
- fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result<bool, DBError> {\r
+ fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result<bool> {\r
let next_version = current_version + 1;\r
\r
if next_version <= CURRENT_DB_VERSION {\r
println!("Update to version {}...", next_version);\r
}\r
\r
- fn ok(updated: bool) -> Result<bool, DBError> {\r
+ fn update_version(to_version: u32, tx: &rusqlite::Transaction) -> Result<()> {\r
+ tx.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version]).map(|_| ()).map_err(DBError::from)\r
+ }\r
+\r
+ fn ok(updated: bool) -> Result<bool> {\r
if updated {\r
println!("Version updated");\r
}\r
match next_version {\r
1 => {\r
tx.execute_batch(&load_sql_file(next_version)?)?;\r
+ update_version(next_version, tx)?;\r
\r
ok(true)\r
}\r
}\r
}\r
\r
- pub fn get_all_recipes() {\r
+ pub fn get_all_recipe_titles(&self) -> Result<Vec<(i32, String)>> {\r
+ let con = self.pool.get()?;\r
+ let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;\r
+ let titles =\r
+ stmt.query_map([], |row| {\r
+ Ok((row.get(0)?, row.get(1)?))\r
+ })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.\r
+ Ok(titles)\r
+ }\r
+\r
+ pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {\r
+ let con = self.pool.get()?;\r
+ let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;\r
+ let recipes =\r
+ stmt.query_map([], |row| {\r
+ Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
+ })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.\r
+ Ok(recipes)\r
+ }\r
\r
+ pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {\r
+ let con = self.pool.get()?;\r
+ con.query_row("SELECT [id], [title] FROM [Recipe] WHERE [id] = ?1", [id], |row| {\r
+ Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
+ }).map_err(DBError::from)\r
}\r
}\r
\r
-fn load_sql_file(version: u32) -> Result<String, DBError> {\r
- let sql_file = SQL_FILENAME.replace("{VERSION}", &version.to_string());\r
+fn load_sql_file(version: u32) -> Result<String> {\r
+ let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &version.to_string());\r
let mut file = File::open(&sql_file).map_err(|err| DBError::Other(format!("Cannot open SQL file ({}): {}", &sql_file, err.to_string())))?;\r
let mut sql = String::new();\r
file.read_to_string(&mut sql).map_err(|err| DBError::Other(format!("Cannot read SQL file ({}) : {}", &sql_file, err.to_string())))?;\r
-use std::io::prelude::*;
-use std::{fs::File, env::args};
+use std::fs::File;
+use std::sync::Mutex;
use actix_files as fs;
-use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpResponse, HttpRequest, web::Query};
-
+use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpRequest};
use askama_actix::Template;
+use clap::Parser;
use ron::de::from_reader;
use serde::Deserialize;
-use itertools::Itertools;
-
mod consts;
mod model;
mod db;
#[derive(Template)]
#[template(path = "home.html")]
struct HomeTemplate {
- recipes: Vec<db::Recipe>
+ recipes: Vec<(i32, String)>,
}
#[derive(Template)]
#[template(path = "view_recipe.html")]
struct ViewRecipeTemplate {
- recipes: Vec<db::Recipe>,
- current_recipe: db::Recipe
+ recipes: Vec<(i32, String)>,
+ current_recipe: model::Recipe,
}
#[derive(Deserialize)]
}
#[get("/")]
-async fn home_page(req: HttpRequest) -> impl Responder {
- HomeTemplate { recipes: vec![ db::Recipe { title: String::from("Saumon en croûte feuilletée"), id: 1 }, db::Recipe { title: String::from("Croissant au jambon"), id: 2 } ] }
+async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
+ HomeTemplate { recipes: connection.get_all_recipe_titles().unwrap() } // TODO: unwrap.
}
#[get("/recipe/view/{id}")]
-async fn view_page(req: HttpRequest, path: web::Path<(i32,)>) -> impl Responder {
- ViewRecipeTemplate { recipes: vec![ db::Recipe { title: String::from("Saumon en croûte feuilletée"), id: 1 }, db::Recipe { title: String::from("Croissant au jambon"), id: 2 } ], current_recipe: db::Recipe { title: String::from("Saumon en croûte feuilletée"), id: 1 } }
+async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data<db::Connection>) -> impl Responder {
+ ViewRecipeTemplate {
+ recipes: connection.get_all_recipe_titles().unwrap(),
+ current_recipe: connection.get_recipe(path.0).unwrap(),
+ }
}
#[derive(Debug, Deserialize)]
println!("Configuration: {:?}", config);
- // let database_connection = db::create_or_update();
+ let db_connection = web::Data::new(db::Connection::new().unwrap()); // TODO: remove unwrap.
std::env::set_var("RUST_LOG", "actix_web=info");
let mut server =
HttpServer::new(
- || {
+ move || {
App::new()
.wrap(middleware::Logger::default())
.wrap(middleware::Compress::default())
+ .app_data(db_connection.clone())
.service(home_page)
- .service(view_page)
+ .service(view_recipe)
.service(fs::Files::new("/static", "static").show_files_listing())
}
);
server.run().await
}
+#[derive(Parser, Debug)]
+struct Args {
+ #[arg(long)]
+ test: bool
+}
+
fn process_args() -> bool {
+ let args = Args::parse();
+
+ if args.test {
+ if let Err(error) = db::Connection::new() {
+ println!("Error: {:?}", error)
+ }
+ return true;
+ }
+
+ false
+
+ /*
+
+
fn print_usage() {
println!("Usage:");
println!(" {} [--help] [--test]", get_exe_name());
}
return true
}
-
false
+ */
}
-struct Recipe {\r
- title: String,\r
- estimate_time: Option<i32>, // [min].\r
- difficulty: Option<Difficulty>,\r
+pub struct Recipe {\r
+ pub id: i32,\r
+ pub title: String,\r
+ pub estimate_time: Option<i32>, // [min].\r
+ pub difficulty: Option<Difficulty>,\r
\r
//ingredients: Vec<Ingredient>, // For four people.\r
- process: Vec<Group>,\r
+ pub process: Vec<Group>,\r
}\r
\r
-struct Ingredient {\r
- quantity: Option<Quantity>,\r
- name: String,\r
+impl Recipe {\r
+ pub fn new(id: i32, title: String) -> Recipe {\r
+ Recipe {\r
+ id,\r
+ title,\r
+ estimate_time: None,\r
+ difficulty: None,\r
+ process: Vec::new(),\r
+ }\r
+ }\r
}\r
\r
-struct Quantity {\r
- value: f32,\r
- unit: String,\r
+pub struct Ingredient {\r
+ pub quantity: Option<Quantity>,\r
+ pub name: String,\r
}\r
\r
-struct Group {\r
- name: Option<String>,\r
- steps: Vec<Step>,\r
+pub struct Quantity {\r
+ pub value: f32,\r
+ pub unit: String,\r
}\r
\r
-struct Step {\r
- action: String,\r
- input: Vec<StepInput>,\r
- output: Vec<IntermediateSubstance>,\r
+pub struct Group {\r
+ pub name: Option<String>,\r
+ pub steps: Vec<Step>,\r
}\r
\r
-struct IntermediateSubstance {\r
- name: String,\r
- quantity: Option<Quantity>,\r
+pub struct Step {\r
+ pub action: String,\r
+ pub input: Vec<StepInput>,\r
+ pub output: Vec<IntermediateSubstance>,\r
}\r
\r
-enum StepInput {\r
+pub struct IntermediateSubstance {\r
+ pub name: String,\r
+ pub quantity: Option<Quantity>,\r
+}\r
+\r
+pub enum StepInput {\r
Ingredient(Ingredient),\r
IntermediateSubstance(IntermediateSubstance),\r
}\r
\r
-enum Difficulty {\r
+pub enum Difficulty {\r
Unknown,\r
Easy,\r
Medium,\r
{% block main_container %}
<div class="list">
<ul>
- {% for recipe in recipes %}
- <li><a href="/recipe/view/{{ recipe.id }}">{{ recipe.title|escape }}</a></li>
+ {% for (id, title) in recipes %}
+ <li><a href="/recipe/view/{{ id }}">{{ title|escape }}</a></li>
{% endfor %}
</ul>
</div>
{% block content %}
-*** HOME - PUT SOMETHING HERE ***
+HOME: TODO
{% endblock %}
\ No newline at end of file