Rocket/examples/todo/src/task.rs

59 lines
1.7 KiB
Rust
Raw Normal View History

2020-06-08 19:11:34 +00:00
use diesel::{self, result::QueryResult, prelude::*};
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"]
#[derive(serde::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
}
2020-06-08 19:11:34 +00:00
#[derive(Debug, FromForm)]
2017-05-26 23:44:53 +00:00
pub struct Todo {
pub description: String,
}
impl Task {
2020-06-08 19:11:34 +00:00
pub fn all(conn: &SqliteConnection) -> QueryResult<Vec<Task>> {
all_tasks.order(tasks::id.desc()).load::<Task>(conn)
}
2020-06-08 19:11:34 +00:00
/// Returns the number of affected rows: 1.
pub fn insert(todo: Todo, conn: &SqliteConnection) -> QueryResult<usize> {
2017-05-26 23:44:53 +00:00
let t = Task { id: None, description: todo.description, completed: false };
2020-06-08 19:11:34 +00:00
diesel::insert_into(tasks::table).values(&t).execute(conn)
}
2020-06-08 19:11:34 +00:00
/// Returns the number of affected rows: 1.
pub fn toggle_with_id(id: i32, conn: &SqliteConnection) -> QueryResult<usize> {
let task = all_tasks.find(id).get_result::<Task>(conn)?;
let new_status = !task.completed;
let updated_task = diesel::update(all_tasks.find(id));
2020-06-08 19:11:34 +00:00
updated_task.set(task_completed.eq(new_status)).execute(conn)
}
2020-06-08 19:11:34 +00:00
/// Returns the number of affected rows: 1.
pub fn delete_with_id(id: i32, conn: &SqliteConnection) -> QueryResult<usize> {
diesel::delete(all_tasks.find(id)).execute(conn)
}
2018-12-30 21:52:08 +00:00
2020-06-08 19:11:34 +00:00
/// Returns the number of affected rows.
2018-12-30 21:52:08 +00:00
#[cfg(test)]
2020-06-08 19:11:34 +00:00
pub fn delete_all(conn: &SqliteConnection) -> QueryResult<usize> {
diesel::delete(all_tasks).execute(conn)
2018-12-30 21:52:08 +00:00
}
}