studium/src/services/database/tasks.rs
Antoine Pelletier ce985ef784
Some checks failed
build / image (push) Failing after 31s
wip
2026-10-24 12:55:18 +02:00

272 lines
8.4 KiB
Rust

//! Tasks and their tags. A task is always written together with its tags, inside a
//! transaction.
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sqlx::{Postgres, Transaction, query, query_as};
use crate::{
core::{
models::{
course::CourseId,
tag::TagId,
task::{Task, TaskData, TaskId},
},
repositories::{RepositoryError, tasks_repository::TasksRepository},
},
services::database::SqlxDatabase,
};
struct TaskDB {
pub id: i32,
pub course_id: i32,
pub parent_id: Option<i32>,
pub name: String,
pub description: Option<String>,
pub links: Vec<String>,
pub deadline: Option<DateTime<Utc>>,
pub done: bool,
pub time_spent: i32,
pub tag_ids: Vec<i32>,
}
impl From<TaskDB> for Task {
fn from(value: TaskDB) -> Self {
Task {
id: value.id,
course_id: value.course_id,
parent_id: value.parent_id,
name: value.name,
description: value.description,
links: value.links,
deadline: value.deadline,
done: value.done,
tag_ids: value.tag_ids,
time_spent: value.time_spent,
subtasks: Vec::new(),
}
}
}
fn not_found(id: TaskId) -> RepositoryError {
RepositoryError::NotFound(format!("task {id}"))
}
async fn insert_tags(
tx: &mut Transaction<'_, Postgres>,
task_id: TaskId,
tag_ids: &[TagId],
) -> Result<(), RepositoryError> {
query!(
r#"INSERT INTO task_tags (task_id, tag_id)
SELECT $1, tag_id FROM UNNEST($2::INTEGER[]) AS tag_id
ON CONFLICT DO NOTHING"#,
task_id,
tag_ids,
)
.execute(&mut **tx)
.await?;
Ok(())
}
#[async_trait]
impl TasksRepository for SqlxDatabase {
async fn get_tasks(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<Task>, RepositoryError> {
Ok(query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
t.deadline, t.done, t.time_spent,
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $2
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE t.course_id = $1
GROUP BY t.id
ORDER BY t.id"#,
course_id,
owner,
)
.fetch_all(&self.pool)
.await?
.into_iter()
.map(Into::into)
.collect())
}
async fn get_dated_tasks(
&self,
owner: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<Task>, RepositoryError> {
Ok(query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
t.deadline, t.done, t.time_spent,
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $3
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE (t.deadline >= $1 AND t.deadline < $2)
OR t.id IN (SELECT parent_id FROM tasks
WHERE deadline >= $1 AND deadline < $2 AND parent_id IS NOT NULL)
GROUP BY t.id
ORDER BY t.id"#,
from,
to,
owner,
)
.fetch_all(&self.pool)
.await?
.into_iter()
.map(Into::into)
.collect())
}
async fn get_todo_tasks(&self, owner: &str) -> Result<Vec<Task>, RepositoryError> {
Ok(query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
t.deadline, t.done, t.time_spent,
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $1
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE t.id IN (SELECT id FROM tasks WHERE parent_id IS NULL AND NOT done)
OR t.parent_id IN (SELECT id FROM tasks WHERE parent_id IS NULL AND NOT done)
GROUP BY t.id
ORDER BY t.id"#,
owner,
)
.fetch_all(&self.pool)
.await?
.into_iter()
.map(Into::into)
.collect())
}
async fn get_task(&self, owner: &str, id: TaskId) -> Result<Task, RepositoryError> {
query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
t.deadline, t.done, t.time_spent,
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $2
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE t.id = $1
GROUP BY t.id"#,
id,
owner,
)
.fetch_optional(&self.pool)
.await?
.map(Into::into)
.ok_or_else(|| not_found(id))
}
async fn create_task(
&self,
owner: &str,
course_id: CourseId,
parent_id: Option<TaskId>,
task: TaskData,
) -> Result<(), RepositoryError> {
let mut tx = self.pool.begin().await?;
let id = query!(
r#"INSERT INTO tasks (course_id, parent_id, name, description, links, deadline, done)
SELECT id, $2, $3, $4, $5, $6, $7 FROM courses WHERE id = $1 AND owner = $8
RETURNING id"#,
course_id,
parent_id,
task.name,
task.description,
&task.links,
task.deadline,
task.done,
owner,
)
.fetch_optional(&mut *tx)
.await?
.ok_or_else(|| RepositoryError::NotFound(format!("course {course_id}")))?
.id;
insert_tags(&mut tx, id, &task.tag_ids).await?;
tx.commit().await?;
Ok(())
}
async fn update_task(
&self,
owner: &str,
id: TaskId,
task: TaskData,
) -> Result<(), RepositoryError> {
let mut tx = self.pool.begin().await?;
let result = query!(
r#"UPDATE tasks SET name = $2, description = $3, links = $4, deadline = $5, done = $6
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $7)"#,
id,
task.name,
task.description,
&task.links,
task.deadline,
task.done,
owner,
)
.execute(&mut *tx)
.await?;
if result.rows_affected() == 0 {
return Err(not_found(id));
}
query!("DELETE FROM task_tags WHERE task_id = $1", id)
.execute(&mut *tx)
.await?;
insert_tags(&mut tx, id, &task.tag_ids).await?;
tx.commit().await?;
Ok(())
}
async fn add_time_spent(
&self,
owner: &str,
id: TaskId,
seconds: i32,
) -> Result<i32, RepositoryError> {
query!(
r#"UPDATE tasks SET time_spent = time_spent + $2
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $3)
RETURNING time_spent"#,
id,
seconds,
owner,
)
.fetch_optional(&self.pool)
.await?
.map(|row| row.time_spent)
.ok_or_else(|| not_found(id))
}
async fn delete_task(&self, owner: &str, id: TaskId) -> Result<(), RepositoryError> {
// The subtasks and the tags are removed by the `ON DELETE CASCADE`
let result = query!(
r#"DELETE FROM tasks
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)"#,
id,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(not_found(id));
}
Ok(())
}
}