2020-02-13 04:11:51 +00:00
|
|
|
use diesel::{self, result::Error as DieselError, prelude::*};
|
|
|
|
type Result<T> = std::result::Result<T, DieselError>;
|
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 {
|
2020-02-13 04:11:51 +00:00
|
|
|
pub fn all(conn: &SqliteConnection) -> Result<Vec<Task>> {
|
|
|
|
all_tasks.order(tasks::id.desc()).load::<Task>(conn)
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 04:11:51 +00:00
|
|
|
pub fn insert(todo: Todo, conn: &SqliteConnection) -> Result<()> {
|
2017-05-26 23:44:53 +00:00
|
|
|
let t = Task { id: None, description: todo.description, completed: false };
|
2020-02-13 04:11:51 +00:00
|
|
|
diesel::insert_into(tasks::table).values(&t).execute(conn)?;
|
|
|
|
|
|
|
|
Ok(())
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 04:11:51 +00:00
|
|
|
pub fn toggle_with_id(id: i32, conn: &SqliteConnection) -> Result<()> {
|
|
|
|
let task = all_tasks.find(id).get_result::<Task>(conn)?;
|
2016-08-02 02:07:36 +00:00
|
|
|
|
2020-02-13 04:11:51 +00:00
|
|
|
let new_status = !task.completed;
|
2016-09-12 01:57:04 +00:00
|
|
|
let updated_task = diesel::update(all_tasks.find(id));
|
2020-02-13 04:11:51 +00:00
|
|
|
updated_task.set(task_completed.eq(new_status)).execute(conn)?;
|
|
|
|
|
|
|
|
Ok(())
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 04:11:51 +00:00
|
|
|
pub fn delete_with_id(id: i32, conn: &SqliteConnection) -> Result<()> {
|
|
|
|
// `.execute` returns a usize representing the number of
|
|
|
|
// database rows affected by this modification.
|
|
|
|
// In a larger app these metrics may be useful,
|
|
|
|
// but for a simple example we'll ignore them.
|
|
|
|
diesel::delete(all_tasks.find(id)).execute(conn).map(|_| ())
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|
2018-12-30 21:52:08 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
2020-02-13 04:11:51 +00:00
|
|
|
pub fn delete_all(conn: &SqliteConnection) -> Result<()> {
|
|
|
|
// see comment in `.delete_with_id`.
|
|
|
|
diesel::delete(all_tasks).execute(conn).map(|_| ())
|
2018-12-30 21:52:08 +00:00
|
|
|
}
|
2016-08-02 02:07:36 +00:00
|
|
|
}
|