db/models/
assignment_task.rs1use chrono::{DateTime, Utc};
2use sea_orm::entity::prelude::*;
3use sea_orm::{
4 ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, IntoActiveModel, QueryFilter, Set,
5};
6use strum::EnumIter;
7
8#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
10#[sea_orm(table_name = "assignment_tasks")]
11pub struct Model {
12 #[sea_orm(primary_key)]
13 pub id: i64,
14 pub assignment_id: i64,
15 pub task_number: i64,
16 pub name: String,
17 pub command: String,
18 pub created_at: DateTime<Utc>,
19 pub updated_at: DateTime<Utc>,
20}
21
22#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
23pub enum Relation {
24 #[sea_orm(
25 belongs_to = "super::assignment::Entity",
26 from = "Column::AssignmentId",
27 to = "super::assignment::Column::Id"
28 )]
29 Assignment,
30}
31
32impl ActiveModelBehavior for ActiveModel {}
33
34impl Model {
35 pub async fn create(
37 db: &DatabaseConnection,
38 assignment_id: i64,
39 task_number: i64,
40 name: &str,
41 command: &str,
42 ) -> Result<Self, DbErr> {
43 let active = ActiveModel {
44 assignment_id: Set(assignment_id),
45 task_number: Set(task_number),
46 name: Set(name.to_string()),
47 command: Set(command.to_string()),
48 created_at: Set(Utc::now()),
49 updated_at: Set(Utc::now()),
50 ..Default::default()
51 };
52 active.insert(db).await
53 }
54
55 pub async fn get_by_id(db: &DatabaseConnection, id: i64) -> Result<Option<Self>, DbErr> {
57 Entity::find_by_id(id).one(db).await
58 }
59
60 pub async fn get_by_assignment_id(
62 db: &DatabaseConnection,
63 assignment_id: i64,
64 ) -> Result<Vec<Self>, DbErr> {
65 Entity::find()
66 .filter(Column::AssignmentId.eq(assignment_id))
67 .all(db)
68 .await
69 }
70
71 pub async fn edit_command_and_name(
73 db: &DatabaseConnection,
74 id: i64,
75 new_name: &str,
76 new_command: &str,
77 ) -> Result<Self, DbErr> {
78 if let Some(task) = Self::get_by_id(db, id).await? {
79 let mut active = task.into_active_model();
80 active.name = Set(new_name.to_string());
81 active.command = Set(new_command.to_string());
82 active.updated_at = Set(Utc::now());
83 active.update(db).await
84 } else {
85 Err(DbErr::RecordNotFound("Task not found".into()))
86 }
87 }
88
89 pub async fn delete(db: &DatabaseConnection, id: i64) -> Result<(), DbErr> {
91 if let Some(task) = Self::get_by_id(db, id).await? {
92 task.delete(db).await.map(|_| ())
93 } else {
94 Err(DbErr::RecordNotFound("Task not found".into()))
95 }
96 }
97}