1
0
mirror of https://github.com/actix/examples synced 2025-02-13 14:02:19 +01:00
examples/basics/todo/src/model.rs

74 lines
1.5 KiB
Rust
Raw Normal View History

2022-02-06 07:55:51 +00:00
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;
2018-08-27 10:56:26 +01:00
2022-02-05 17:34:43 +00:00
#[derive(Debug)]
2018-08-27 10:56:26 +01:00
pub struct NewTask {
pub description: String,
}
2022-02-06 07:55:51 +00:00
#[derive(Debug, Deserialize, Serialize)]
2018-08-27 10:56:26 +01:00
pub struct Task {
2022-02-06 07:55:51 +00:00
pub id: i64,
2018-08-27 10:56:26 +01:00
pub description: String,
pub completed: bool,
}
impl Task {
2022-02-06 07:55:51 +00:00
pub async fn all(connection: &SqlitePool) -> Result<Vec<Task>, sqlx::Error> {
2022-02-05 17:34:43 +00:00
let tasks = sqlx::query_as!(
Task,
r#"
SELECT *
FROM tasks
"#
)
.fetch_all(connection)
.await?;
2022-02-06 07:55:51 +00:00
2022-02-05 17:34:43 +00:00
Ok(tasks)
2018-08-27 10:56:26 +01:00
}
2022-02-18 02:44:02 +00:00
pub async fn insert(todo: NewTask, connection: &SqlitePool) -> Result<(), sqlx::Error> {
2022-02-05 17:34:43 +00:00
sqlx::query!(
r#"
INSERT INTO tasks (description)
VALUES ($1)
"#,
todo.description,
)
.execute(connection)
.await?;
2022-02-06 07:55:51 +00:00
2022-02-05 17:34:43 +00:00
Ok(())
2018-08-27 10:56:26 +01:00
}
2022-02-18 02:44:02 +00:00
pub async fn toggle_with_id(id: i32, connection: &SqlitePool) -> Result<(), sqlx::Error> {
2022-02-05 17:34:43 +00:00
sqlx::query!(
r#"
UPDATE tasks
SET completed = NOT completed
WHERE id = $1
2022-02-06 07:55:51 +00:00
"#,
2022-02-05 17:34:43 +00:00
id
)
.execute(connection)
.await?;
2022-02-06 07:55:51 +00:00
2022-02-05 17:34:43 +00:00
Ok(())
2018-08-27 10:56:26 +01:00
}
2022-02-18 02:44:02 +00:00
pub async fn delete_with_id(id: i32, connection: &SqlitePool) -> Result<(), sqlx::Error> {
2022-02-05 17:34:43 +00:00
sqlx::query!(
r#"
DELETE FROM tasks
WHERE id = $1
"#,
id
)
.execute(connection)
.await?;
2022-02-06 07:55:51 +00:00
2022-02-05 17:34:43 +00:00
Ok(())
2018-08-27 10:56:26 +01:00
}
}