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

75 lines
1.5 KiB
Rust
Raw Normal View History

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