| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use crate::constant::MAX_COURSE_NOTE_FILES; |
| 6 | use crate::database::{Database, tx_with_retry, unique_violation}; |
| 7 | use crate::db::page::PagedList; |
| 8 | use crate::domain::course::CourseId; |
| 9 | use crate::domain::course_note::CourseNoteId; |
| 10 | use crate::domain::course_note_file::{ |
| 11 | CourseNoteFile, CourseNoteFileId, FileContentType, FileName, |
| 12 | }; |
| 13 | use crate::error::AppError; |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { |
| 22 | |
| 23 | let created = sqlx::query_as!( |
| 24 | CourseNoteFile, |
| 25 | r#"WITH seat AS ( |
| 26 | UPDATE course_note SET file_count = file_count + 1 |
| 27 | WHERE id = $1 AND file_count < $2 |
| 28 | RETURNING 1) |
| 29 | INSERT INTO course_note_file (id, course_note, name, content_type, size) |
| 30 | SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 31 | RETURNING id AS "id: CourseNoteFileId", |
| 32 | course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 33 | content_type AS "content_type: FileContentType", size"#, |
| 34 | file.course_note.uuid(), |
| 35 | MAX_COURSE_NOTE_FILES as i64, |
| 36 | file.id.uuid(), |
| 37 | file.name.as_str(), |
| 38 | file.content_type.as_str(), |
| 39 | file.size |
| 40 | ) |
| 41 | .fetch_optional(db) |
| 42 | .await; |
| 43 | match created { |
| 44 | Ok(Some(row)) => Ok(row), |
| 45 | |
| 46 | Ok(None) => Err(AppError::Conflict( |
| 47 | "the course note already holds the maximum of 10 files — delete one first", |
| 48 | )), |
| 49 | |
| 50 | |
| 51 | Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal( |
| 52 | "failed to create course note file".into(), |
| 53 | )), |
| 54 | Err(err) => Err(err.into()), |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | pub async fn read( |
| 63 | db: &Database, |
| 64 | id: &CourseNoteFileId, |
| 65 | ) -> Result<Option<CourseNoteFile>, AppError> { |
| 66 | let file = sqlx::query_as!( |
| 67 | CourseNoteFile, |
| 68 | r#"SELECT id AS "id: CourseNoteFileId", |
| 69 | course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 70 | content_type AS "content_type: FileContentType", size FROM course_note_file WHERE id = $1"#, |
| 71 | id.uuid() |
| 72 | ) |
| 73 | .fetch_optional(db) |
| 74 | .await?; |
| 75 | Ok(file) |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | pub async fn read_for( |
| 81 | db: &Database, |
| 82 | id: &CourseNoteFileId, |
| 83 | note: &CourseNoteId, |
| 84 | ) -> Result<Option<CourseNoteFile>, AppError> { |
| 85 | let file = sqlx::query_as!( |
| 86 | CourseNoteFile, |
| 87 | r#"SELECT id AS "id: CourseNoteFileId", |
| 88 | course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 89 | content_type AS "content_type: FileContentType", size FROM course_note_file |
| 90 | WHERE id = $1 AND course_note = $2"#, |
| 91 | id.uuid(), |
| 92 | note.uuid() |
| 93 | ) |
| 94 | .fetch_optional(db) |
| 95 | .await?; |
| 96 | Ok(file) |
| 97 | } |
| 98 | |
| 99 | |
| 100 | pub async fn list_for( |
| 101 | db: &Database, |
| 102 | note: &CourseNoteId, |
| 103 | limit: Option<i64>, |
| 104 | offset: i64, |
| 105 | ) -> Result<(Vec<CourseNoteFile>, i64), AppError> { |
| 106 | PagedList::new( |
| 107 | "course_note_file WHERE course_note = $1", |
| 108 | "ORDER BY id DESC", |
| 109 | ) |
| 110 | .bind(note.uuid()) |
| 111 | .run::<CourseNoteFile>(limit, offset, db) |
| 112 | .await |
| 113 | } |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | pub async fn file_keys_for_course( |
| 119 | db: &Database, |
| 120 | course: &CourseId, |
| 121 | ) -> Result<Vec<String>, AppError> { |
| 122 | let rows = sqlx::query!( |
| 123 | r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file |
| 124 | WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, |
| 125 | course.uuid() |
| 126 | ) |
| 127 | .fetch_all(db) |
| 128 | .await?; |
| 129 | Ok(rows.into_iter().map(|row| row.id.key()).collect()) |
| 130 | } |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> { |
| 136 | tx_with_retry(db, true, async move |conn| { |
| 137 | let gone = sqlx::query_as!( |
| 138 | CourseNoteFile, |
| 139 | r#"DELETE FROM course_note_file WHERE id = $1 |
| 140 | RETURNING id AS "id: CourseNoteFileId", |
| 141 | course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 142 | content_type AS "content_type: FileContentType", size"#, |
| 143 | file.id.uuid() |
| 144 | ) |
| 145 | .fetch_optional(&mut *conn) |
| 146 | .await?; |
| 147 | let file = gone.ok_or(AppError::NotFound)?; |
| 148 | sqlx::query!( |
| 149 | "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", |
| 150 | file.course_note.uuid() |
| 151 | ) |
| 152 | .execute(&mut *conn) |
| 153 | .await?; |
| 154 | Ok(file) |
| 155 | }) |
| 156 | .await |
| 157 | } |
| 158 | |
| 159 | #[cfg(test)] |
| 160 | mod tests { |
| 161 | use super::*; |
| 162 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 163 | use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle}; |
| 164 | use crate::domain::course_note_file::FileContentType; |
| 165 | use crate::domain::course_note_file::FileName; |
| 166 | |
| 167 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 168 | let creator = crate::domain::user::UserId::generate(); |
| 169 | let course = crate::db::course::create( |
| 170 | db, |
| 171 | &creator, |
| 172 | CourseTitle::try_new("c").unwrap(), |
| 173 | CourseDescription::try_new("").unwrap(), |
| 174 | CourseKind::try_new("course").unwrap(), |
| 175 | None, |
| 176 | None, |
| 177 | ) |
| 178 | .await |
| 179 | .unwrap(); |
| 180 | crate::db::course_note::create( |
| 181 | db, |
| 182 | course.get_id(), |
| 183 | &creator, |
| 184 | CourseNoteTitle::try_new(title).unwrap(), |
| 185 | CourseNoteContent::try_new("body").unwrap(), |
| 186 | ) |
| 187 | .await |
| 188 | .unwrap() |
| 189 | } |
| 190 | |
| 191 | |
| 192 | |
| 193 | #[tokio::test] |
| 194 | async fn insert_refuses_at_the_cap() { |
| 195 | let db = crate::database::init_mem().await.unwrap(); |
| 196 | let note = note_of(&db, "n").await; |
| 197 | for index in 0..MAX_COURSE_NOTE_FILES { |
| 198 | let file = CourseNoteFile::new( |
| 199 | note.get_id(), |
| 200 | FileName::try_new(&format!("f{index}")).unwrap(), |
| 201 | FileContentType::try_new("text/plain").unwrap(), |
| 202 | 1, |
| 203 | ); |
| 204 | insert(&db, file).await.unwrap(); |
| 205 | } |
| 206 | let over = CourseNoteFile::new( |
| 207 | note.get_id(), |
| 208 | FileName::try_new("over").unwrap(), |
| 209 | FileContentType::try_new("text/plain").unwrap(), |
| 210 | 1, |
| 211 | ); |
| 212 | assert!(matches!( |
| 213 | insert(&db, over).await, |
| 214 | Err(AppError::Conflict(_)) |
| 215 | )); |
| 216 | let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); |
| 217 | assert_eq!(total, MAX_COURSE_NOTE_FILES as i64); |
| 218 | } |
| 219 | |
| 220 | |
| 221 | |
| 222 | #[tokio::test] |
| 223 | async fn file_keys_and_delete_slot_release() { |
| 224 | let db = crate::database::init_mem().await.unwrap(); |
| 225 | let note = note_of(&db, "n").await; |
| 226 | let course = note.get_course().clone(); |
| 227 | let file = CourseNoteFile::new( |
| 228 | note.get_id(), |
| 229 | FileName::try_new("f").unwrap(), |
| 230 | FileContentType::try_new("text/plain").unwrap(), |
| 231 | 1, |
| 232 | ); |
| 233 | let file = insert(&db, file).await.unwrap(); |
| 234 | let keys = file_keys_for_course(&db, &course).await.unwrap(); |
| 235 | assert_eq!(keys, vec![file.get_id().key().to_string()]); |
| 236 | let gone = delete(&db, file.clone()).await.unwrap(); |
| 237 | assert_eq!(gone.get_id(), file.get_id()); |
| 238 | assert!(matches!(delete(&db, file).await, Err(AppError::NotFound))); |
| 239 | assert!(file_keys_for_course(&db, &course).await.unwrap().is_empty()); |
| 240 | } |
| 241 | } |