Rocket/examples/todo/src/task.rs

56 lines
1.5 KiB
Rust
Raw Normal View History

use diesel;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
2017-02-03 01:38:36 +00:00
mod schema {
table! {
tasks {
id -> Nullable<Integer>,
description -> Text,
completed -> Bool,
}
}
}
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)]
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 {
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()
}
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 };
diesel::insert_into(tasks::table).values(&t).execute(conn).is_ok()
}
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);
if task.is_err() {
return false;
}
2017-05-26 23:44:53 +00:00
let new_status = !task.unwrap().completed;
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()
}
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()
}
}