2018-07-21 22:11:08 +00:00
|
|
|
use diesel::{self, prelude::*};
|
2017-02-03 01:38:36 +00:00
|
|
|
|
2017-02-02 08:41:47 +00:00
|
|
|
mod schema {
|
2017-12-29 23:03:06 +00:00
|
|
|
table! {
|
|
|
|
tasks {
|
|
|
|
id -> Nullable<Integer>,
|
|
|
|
description -> Text,
|
|
|
|
completed -> Bool,
|
|
|
|
}
|
|
|
|
}
|
2017-02-02 08:41:47 +00:00
|
|
|
}
|
|
|
|
|
2017-12-29 23:03:06 +00:00
|
|
|
use self::schema::tasks;
|
|
|
|
use self::schema::tasks::dsl::{tasks as all_tasks, completed as task_completed};
|
|
|
|
|
|
|
|
#[table_name="tasks"]
|
2017-05-26 23:44:53 +00:00
|
|
|
#[derive(Serialize, Queryable, Insertable, Debug, Clone)]
|
2016-08-02 02:07:36 +00:00
|
|
|
pub struct Task {
|
2017-05-26 23:44:53 +00:00
|
|
|
pub id: Option<i32>,
|
|
|
|
pub description: String,
|
|
|
|
pub completed: bool
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(FromForm)]
|
|
|
|
pub struct Todo {
|
2016-08-02 02:07:36 +00:00
|
|
|
pub description: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Task {
|
2017-02-03 01:38:36 +00:00
|
|
|
pub fn all(conn: &SqliteConnection) -> Vec<Task> {
|
|
|
|
all_tasks.order(tasks::id.desc()).load::<Task>(conn).unwrap()
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
|
|
|
|
2017-05-26 23:44:53 +00:00
|
|
|
pub fn insert(todo: Todo, conn: &SqliteConnection) -> bool {
|
|
|
|
let t = Task { id: None, description: todo.description, completed: false };
|
2017-12-29 23:03:06 +00:00
|
|
|
diesel::insert_into(tasks::table).values(&t).execute(conn).is_ok()
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
|
|
|
|
2017-02-03 01:38:36 +00:00
|
|
|
pub fn toggle_with_id(id: i32, conn: &SqliteConnection) -> bool {
|
|
|
|
let task = all_tasks.find(id).get_result::<Task>(conn);
|
2016-08-02 02:07:36 +00:00
|
|
|
if task.is_err() {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2017-05-26 23:44:53 +00:00
|
|
|
let new_status = !task.unwrap().completed;
|
2016-09-12 01:57:04 +00:00
|
|
|
let updated_task = diesel::update(all_tasks.find(id));
|
2017-02-03 01:38:36 +00:00
|
|
|
updated_task.set(task_completed.eq(new_status)).execute(conn).is_ok()
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
|
|
|
|
2017-02-03 01:38:36 +00:00
|
|
|
pub fn delete_with_id(id: i32, conn: &SqliteConnection) -> bool {
|
|
|
|
diesel::delete(all_tasks.find(id)).execute(conn).is_ok()
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
2018-12-30 21:52:08 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
pub fn delete_all(conn: &SqliteConnection) -> bool {
|
|
|
|
diesel::delete(all_tasks).execute(conn).is_ok()
|
|
|
|
}
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|