| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use sqlx::PgConnection; |
| 8 | |
| 9 | use crate::database::{Database, tx_with_retry}; |
| 10 | use crate::db::exam_attempt::freeze_gate; |
| 11 | use crate::domain::course::CourseId; |
| 12 | use crate::domain::exam::ExamId; |
| 13 | use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; |
| 14 | use crate::domain::note_file::FileContentType; |
| 15 | use crate::domain::question_image::QuestionImage; |
| 16 | use crate::error::AppError; |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | pub async fn upsert( |
| 31 | db: &Database, |
| 32 | image: QuestionImage, |
| 33 | ) -> Result<(QuestionImage, Option<String>), AppError> { |
| 34 | tx_with_retry(db, false, async move |conn| { |
| 35 | upsert_in(conn, image.clone()).await |
| 36 | }) |
| 37 | .await |
| 38 | } |
| 39 | |
| 40 | |
| 41 | pub(crate) async fn upsert_in( |
| 42 | conn: &mut PgConnection, |
| 43 | image: QuestionImage, |
| 44 | ) -> Result<(QuestionImage, Option<String>), AppError> { |
| 45 | freeze_gate(conn, &image.exam).await?; |
| 46 | let replaced = replaced_file(conn, &image.question, image.slot.as_ref()).await?; |
| 47 | let stored = sqlx::query_as!( |
| 48 | QuestionImage, |
| 49 | r#"INSERT INTO question_image (exam, question, slot, file, content_type, size) |
| 50 | VALUES ($1, $2, $3, $4, $5, $6) |
| 51 | ON CONFLICT (question, slot) DO UPDATE |
| 52 | SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, |
| 53 | size = EXCLUDED.size |
| 54 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 55 | slot AS "slot: ChoiceId", file, |
| 56 | content_type AS "content_type: FileContentType", size"#, |
| 57 | image.exam.uuid(), |
| 58 | image.question.uuid(), |
| 59 | image.slot.as_ref().map(ChoiceId::as_str), |
| 60 | image.file, |
| 61 | image.content_type.as_str(), |
| 62 | image.size, |
| 63 | ) |
| 64 | .fetch_one(&mut *conn) |
| 65 | .await?; |
| 66 | Ok((stored, replaced)) |
| 67 | } |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | pub(crate) async fn replaced_file( |
| 73 | conn: &mut PgConnection, |
| 74 | question: &ExamQuestionId, |
| 75 | slot: Option<&ChoiceId>, |
| 76 | ) -> Result<Option<String>, AppError> { |
| 77 | let row = sqlx::query!( |
| 78 | r#"SELECT file FROM question_image |
| 79 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, |
| 80 | question.uuid(), |
| 81 | slot.map(ChoiceId::as_str), |
| 82 | ) |
| 83 | .fetch_optional(conn) |
| 84 | .await?; |
| 85 | Ok(row.map(|row| row.file)) |
| 86 | } |
| 87 | |
| 88 | pub async fn read_slot( |
| 89 | db: &Database, |
| 90 | question: &ExamQuestionId, |
| 91 | slot: Option<&ChoiceId>, |
| 92 | ) -> Result<Option<QuestionImage>, AppError> { |
| 93 | Ok(sqlx::query_as!( |
| 94 | QuestionImage, |
| 95 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 96 | slot AS "slot: ChoiceId", file, |
| 97 | content_type AS "content_type: FileContentType", size |
| 98 | FROM question_image |
| 99 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, |
| 100 | question.uuid(), |
| 101 | slot.map(ChoiceId::as_str), |
| 102 | ) |
| 103 | .fetch_optional(db) |
| 104 | .await?) |
| 105 | } |
| 106 | |
| 107 | |
| 108 | pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<QuestionImage>, AppError> { |
| 109 | Ok(sqlx::query_as!( |
| 110 | QuestionImage, |
| 111 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 112 | slot AS "slot: ChoiceId", file, |
| 113 | content_type AS "content_type: FileContentType", size |
| 114 | FROM question_image WHERE exam = $1"#, |
| 115 | exam.uuid(), |
| 116 | ) |
| 117 | .fetch_all(db) |
| 118 | .await?) |
| 119 | } |
| 120 | |
| 121 | pub async fn list_for_question( |
| 122 | db: &Database, |
| 123 | question: &ExamQuestionId, |
| 124 | ) -> Result<Vec<QuestionImage>, AppError> { |
| 125 | Ok(sqlx::query_as!( |
| 126 | QuestionImage, |
| 127 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 128 | slot AS "slot: ChoiceId", file, |
| 129 | content_type AS "content_type: FileContentType", size |
| 130 | FROM question_image WHERE question = $1"#, |
| 131 | question.uuid(), |
| 132 | ) |
| 133 | .fetch_all(db) |
| 134 | .await?) |
| 135 | } |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | pub async fn delete_choices_not_in( |
| 147 | db: &Database, |
| 148 | question: &ExamQuestionId, |
| 149 | keep: &[ChoiceId], |
| 150 | ) -> Result<Vec<QuestionImage>, AppError> { |
| 151 | let keep = keep |
| 152 | .iter() |
| 153 | .map(|id| id.as_str().to_string()) |
| 154 | .collect::<Vec<_>>(); |
| 155 | Ok(sqlx::query_as!( |
| 156 | QuestionImage, |
| 157 | r#"DELETE FROM question_image |
| 158 | WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2)) |
| 159 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 160 | slot AS "slot: ChoiceId", file, |
| 161 | content_type AS "content_type: FileContentType", size"#, |
| 162 | question.uuid(), |
| 163 | &keep, |
| 164 | ) |
| 165 | .fetch_all(db) |
| 166 | .await?) |
| 167 | } |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | pub async fn file_keys_for_course( |
| 173 | db: &Database, |
| 174 | course: &CourseId, |
| 175 | ) -> Result<Vec<String>, AppError> { |
| 176 | let rows = sqlx::query!( |
| 177 | r#"SELECT qi.file FROM question_image qi |
| 178 | JOIN exam e ON e.id = qi.exam |
| 179 | JOIN class_course cc ON cc.id = e.class_course |
| 180 | WHERE cc.course = $1"#, |
| 181 | course.uuid(), |
| 182 | ) |
| 183 | .fetch_all(db) |
| 184 | .await?; |
| 185 | Ok(rows.into_iter().map(|row| row.file).collect()) |
| 186 | } |
| 187 | |
| 188 | |
| 189 | |
| 190 | pub async fn delete(db: &Database, image: QuestionImage) -> Result<QuestionImage, AppError> { |
| 191 | tx_with_retry(db, false, async move |conn| { |
| 192 | freeze_gate(conn, &image.exam).await?; |
| 193 | let deleted = sqlx::query_as!( |
| 194 | QuestionImage, |
| 195 | r#"DELETE FROM question_image |
| 196 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2 |
| 197 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 198 | slot AS "slot: ChoiceId", file, |
| 199 | content_type AS "content_type: FileContentType", size"#, |
| 200 | image.question.uuid(), |
| 201 | image.slot.as_ref().map(ChoiceId::as_str), |
| 202 | ) |
| 203 | .fetch_optional(&mut *conn) |
| 204 | .await?; |
| 205 | deleted.ok_or(AppError::NotFound) |
| 206 | }) |
| 207 | .await |
| 208 | } |
| 209 | |
| 210 | #[cfg(test)] |
| 211 | mod tests { |
| 212 | use super::*; |
| 213 | use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; |
| 214 | use crate::domain::note_file::FileContentType; |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | async fn exam_row(db: &Database) -> ExamId { |
| 220 | crate::db::exam::published_exam(db).await.get_id().clone() |
| 221 | } |
| 222 | |
| 223 | fn png() -> FileContentType { |
| 224 | FileContentType::try_new("image/png").unwrap() |
| 225 | } |
| 226 | |
| 227 | |
| 228 | fn choice_ids() -> Vec<ChoiceId> { |
| 229 | QuestionSpec::try_new( |
| 230 | QuestionKind::try_new("choice").unwrap(), |
| 231 | Some( |
| 232 | ["a", "b", "c"] |
| 233 | .iter() |
| 234 | .map(|l| ChoiceInput { |
| 235 | id: Some((*l).into()), |
| 236 | text: (*l).into(), |
| 237 | }) |
| 238 | .collect(), |
| 239 | ), |
| 240 | Some("a".into()), |
| 241 | &[], |
| 242 | ) |
| 243 | .unwrap() |
| 244 | .into_parts() |
| 245 | .1 |
| 246 | .unwrap() |
| 247 | .iter() |
| 248 | .map(|c| c.get_id().clone()) |
| 249 | .collect() |
| 250 | } |
| 251 | |
| 252 | |
| 253 | |
| 254 | async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId { |
| 255 | use crate::domain::exam_question::{QuestionPoints, QuestionText}; |
| 256 | use crate::domain::subject::{SubjectDescription, SubjectName}; |
| 257 | let spec = QuestionSpec::try_new( |
| 258 | QuestionKind::try_new("choice").unwrap(), |
| 259 | Some( |
| 260 | ["a", "b", "c"] |
| 261 | .iter() |
| 262 | .map(|l| ChoiceInput { |
| 263 | id: Some((*l).into()), |
| 264 | text: (*l).into(), |
| 265 | }) |
| 266 | .collect(), |
| 267 | ), |
| 268 | Some("a".into()), |
| 269 | &[], |
| 270 | ) |
| 271 | .unwrap(); |
| 272 | let subject = crate::db::subject::create( |
| 273 | db, |
| 274 | &crate::db::course::a_test_course(db).await, |
| 275 | SubjectName::try_new("pictures").unwrap(), |
| 276 | SubjectDescription::try_new("").unwrap(), |
| 277 | ) |
| 278 | .await |
| 279 | .unwrap(); |
| 280 | crate::db::exam_question::create( |
| 281 | db, |
| 282 | exam, |
| 283 | *subject.get_id(), |
| 284 | QuestionText::try_new("pick one").unwrap(), |
| 285 | QuestionPoints::try_new(1).unwrap(), |
| 286 | spec, |
| 287 | ) |
| 288 | .await |
| 289 | .unwrap() |
| 290 | .get_id() |
| 291 | .clone() |
| 292 | } |
| 293 | |
| 294 | #[tokio::test] |
| 295 | async fn upsert_replaces_per_slot() { |
| 296 | let (db, _leases) = crate::database::init_test_db().await; |
| 297 | let exam = exam_row(&db).await; |
| 298 | let question = a_question(&db, &exam).await; |
| 299 | let ids = choice_ids(); |
| 300 | |
| 301 | let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3)) |
| 302 | .await |
| 303 | .unwrap(); |
| 304 | assert_eq!(retired, None, "a first upload retires no blob"); |
| 305 | let (second, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 5)) |
| 306 | .await |
| 307 | .unwrap(); |
| 308 | |
| 309 | |
| 310 | assert_ne!(first.get_file(), second.get_file()); |
| 311 | assert_eq!(retired.as_deref(), Some(first.get_file())); |
| 312 | let rows = list_for_question(&db, &question).await.unwrap(); |
| 313 | assert_eq!(rows.len(), 1); |
| 314 | assert_eq!(rows[0].get_size(), 5); |
| 315 | |
| 316 | |
| 317 | upsert( |
| 318 | &db, |
| 319 | QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7), |
| 320 | ) |
| 321 | .await |
| 322 | .unwrap(); |
| 323 | assert_eq!(list_for_question(&db, &question).await.unwrap().len(), 2); |
| 324 | let choice = read_slot(&db, &question, Some(&ids[0])) |
| 325 | .await |
| 326 | .unwrap() |
| 327 | .unwrap(); |
| 328 | assert_eq!(choice.get_slot(), Some(&ids[0])); |
| 329 | assert!( |
| 330 | read_slot(&db, &question, Some(&ids[1])) |
| 331 | .await |
| 332 | .unwrap() |
| 333 | .is_none() |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | #[tokio::test] |
| 340 | async fn only_the_dropped_options_lose_their_pictures() { |
| 341 | let (db, _leases) = crate::database::init_test_db().await; |
| 342 | let exam = exam_row(&db).await; |
| 343 | let question = a_question(&db, &exam).await; |
| 344 | let ids = choice_ids(); |
| 345 | upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) |
| 346 | .await |
| 347 | .unwrap(); |
| 348 | for id in &ids { |
| 349 | upsert( |
| 350 | &db, |
| 351 | QuestionImage::new(&exam, &question, Some(id), png(), 1), |
| 352 | ) |
| 353 | .await |
| 354 | .unwrap(); |
| 355 | } |
| 356 | |
| 357 | |
| 358 | let keep = vec![ids[2].clone(), ids[0].clone()]; |
| 359 | let dropped = delete_choices_not_in(&db, &question, &keep).await.unwrap(); |
| 360 | assert_eq!(dropped.len(), 1); |
| 361 | assert_eq!(dropped[0].get_slot(), Some(&ids[1])); |
| 362 | |
| 363 | let left = list_for_question(&db, &question).await.unwrap(); |
| 364 | |
| 365 | assert_eq!(left.len(), 3); |
| 366 | assert!( |
| 367 | read_slot(&db, &question, Some(&ids[0])) |
| 368 | .await |
| 369 | .unwrap() |
| 370 | .is_some() |
| 371 | ); |
| 372 | assert!( |
| 373 | read_slot(&db, &question, Some(&ids[2])) |
| 374 | .await |
| 375 | .unwrap() |
| 376 | .is_some() |
| 377 | ); |
| 378 | assert!(read_slot(&db, &question, None).await.unwrap().is_some()); |
| 379 | } |
| 380 | |
| 381 | #[tokio::test] |
| 382 | async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { |
| 383 | let (db, _leases) = crate::database::init_test_db().await; |
| 384 | let exam = exam_row(&db).await; |
| 385 | let question = a_question(&db, &exam).await; |
| 386 | let ids = choice_ids(); |
| 387 | upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) |
| 388 | .await |
| 389 | .unwrap(); |
| 390 | for id in &ids[..2] { |
| 391 | upsert( |
| 392 | &db, |
| 393 | QuestionImage::new(&exam, &question, Some(id), png(), 1), |
| 394 | ) |
| 395 | .await |
| 396 | .unwrap(); |
| 397 | } |
| 398 | |
| 399 | let dropped = delete_choices_not_in(&db, &question, &[]).await.unwrap(); |
| 400 | assert_eq!(dropped.len(), 2); |
| 401 | assert!(dropped.iter().all(|image| image.get_slot().is_some())); |
| 402 | |
| 403 | let left = list_for_question(&db, &question).await.unwrap(); |
| 404 | assert_eq!(left.len(), 1); |
| 405 | assert_eq!(left[0].get_slot(), None); |
| 406 | } |
| 407 | |
| 408 | #[tokio::test] |
| 409 | async fn exam_listing_scopes_by_exam() { |
| 410 | let (db, _leases) = crate::database::init_test_db().await; |
| 411 | let exam_a = exam_row(&db).await; |
| 412 | let exam_b = exam_row(&db).await; |
| 413 | upsert( |
| 414 | &db, |
| 415 | QuestionImage::new(&exam_a, &a_question(&db, &exam_a).await, None, png(), 1), |
| 416 | ) |
| 417 | .await |
| 418 | .unwrap(); |
| 419 | assert_eq!(list_for_exam(&db, &exam_a).await.unwrap().len(), 1); |
| 420 | assert!(list_for_exam(&db, &exam_b).await.unwrap().is_empty()); |
| 421 | } |
| 422 | } |