| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::collections::HashMap; |
| 8 | |
| 9 | use crate::database::{Database, tx_with_retry}; |
| 10 | use crate::db::page::PagedList; |
| 11 | use crate::domain::note_file::FileContentType; |
| 12 | use crate::domain::pool_question::PoolQuestionId; |
| 13 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; |
| 14 | use crate::domain::timestamp::Timestamp; |
| 15 | use crate::domain::user::UserId; |
| 16 | use crate::error::AppError; |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> { |
| 30 | match sqlx::query_as!( |
| 31 | Solution, |
| 32 | r#"INSERT INTO solution (id, question, author, body, offered_at) |
| 33 | VALUES ($1, $2, $3, $4, $5) |
| 34 | RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 35 | author AS "author: UserId", body AS "body: SolutionBody", |
| 36 | offered_at AS "offered_at: Timestamp", image_file, |
| 37 | image_content_type AS "image_content_type: FileContentType", |
| 38 | image_size"#, |
| 39 | solution.id.uuid(), |
| 40 | solution.question.uuid(), |
| 41 | solution.author.uuid(), |
| 42 | solution.body.as_str(), |
| 43 | solution.offered_at.as_millis(), |
| 44 | ) |
| 45 | .fetch_one(db) |
| 46 | .await |
| 47 | { |
| 48 | Ok(row) => Ok(row), |
| 49 | Err(err) if is_question_gone(&err) => Err(AppError::NotFound), |
| 50 | Err(err) => Err(err.into()), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | |
| 55 | |
| 56 | fn is_question_gone(err: &sqlx::Error) -> bool { |
| 57 | err.as_database_error().and_then(|db| db.constraint()) == Some("solution_question_fkey") |
| 58 | } |
| 59 | |
| 60 | |
| 61 | |
| 62 | pub async fn read_for( |
| 63 | db: &Database, |
| 64 | id: &SolutionId, |
| 65 | question: &PoolQuestionId, |
| 66 | ) -> Result<Option<Solution>, AppError> { |
| 67 | let row = sqlx::query_as!( |
| 68 | Solution, |
| 69 | r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 70 | author AS "author: UserId", body AS "body: SolutionBody", |
| 71 | offered_at AS "offered_at: Timestamp", image_file, |
| 72 | image_content_type AS "image_content_type: FileContentType", |
| 73 | image_size |
| 74 | FROM solution WHERE id = $1 AND question = $2"#, |
| 75 | id.uuid(), |
| 76 | question.uuid() |
| 77 | ) |
| 78 | .fetch_optional(db) |
| 79 | .await?; |
| 80 | Ok(row) |
| 81 | } |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | pub async fn list_for( |
| 88 | db: &Database, |
| 89 | question: &PoolQuestionId, |
| 90 | limit: Option<i64>, |
| 91 | offset: i64, |
| 92 | ) -> Result<(Vec<Solution>, i64), AppError> { |
| 93 | |
| 94 | PagedList::new( |
| 95 | "solution WHERE question = $1", |
| 96 | "ORDER BY offered_at ASC, id ASC", |
| 97 | ) |
| 98 | .bind(question.uuid()) |
| 99 | .run(limit, offset, db) |
| 100 | .await |
| 101 | } |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | pub async fn counts_for( |
| 108 | db: &Database, |
| 109 | questions: &[PoolQuestionId], |
| 110 | ) -> Result<HashMap<String, i64>, AppError> { |
| 111 | if questions.is_empty() { |
| 112 | return Ok(HashMap::new()); |
| 113 | } |
| 114 | let ids: Vec<uuid::Uuid> = questions.iter().map(|id| id.uuid()).collect(); |
| 115 | let rows = sqlx::query!( |
| 116 | r#"SELECT question AS "question: PoolQuestionId", count(*) AS n |
| 117 | FROM solution |
| 118 | WHERE question = ANY($1) |
| 119 | GROUP BY question"#, |
| 120 | &ids, |
| 121 | ) |
| 122 | .fetch_all(db) |
| 123 | .await?; |
| 124 | Ok(rows |
| 125 | .into_iter() |
| 126 | .map(|row| (row.question.key(), row.n.unwrap_or(0))) |
| 127 | .collect()) |
| 128 | } |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | pub async fn set_body( |
| 134 | db: &Database, |
| 135 | id: &SolutionId, |
| 136 | body: &SolutionBody, |
| 137 | ) -> Result<Option<Solution>, AppError> { |
| 138 | let row = sqlx::query_as!( |
| 139 | Solution, |
| 140 | r#"UPDATE solution SET body = $2 WHERE id = $1 |
| 141 | RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 142 | author AS "author: UserId", body AS "body: SolutionBody", |
| 143 | offered_at AS "offered_at: Timestamp", image_file, |
| 144 | image_content_type AS "image_content_type: FileContentType", |
| 145 | image_size"#, |
| 146 | id.uuid(), |
| 147 | body.as_str() |
| 148 | ) |
| 149 | .fetch_optional(db) |
| 150 | .await?; |
| 151 | Ok(row) |
| 152 | } |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | pub async fn set_image( |
| 163 | db: &Database, |
| 164 | id: &SolutionId, |
| 165 | file: &str, |
| 166 | content_type: &FileContentType, |
| 167 | size: i64, |
| 168 | ) -> Result<Option<Solution>, AppError> { |
| 169 | |
| 170 | let id = *id; |
| 171 | let file = file.to_owned(); |
| 172 | let content_type = content_type.clone(); |
| 173 | tx_with_retry(db, false, async move |tx| { |
| 174 | let before = sqlx::query_as!( |
| 175 | Solution, |
| 176 | r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 177 | author AS "author: UserId", body AS "body: SolutionBody", |
| 178 | offered_at AS "offered_at: Timestamp", image_file, |
| 179 | image_content_type AS "image_content_type: FileContentType", |
| 180 | image_size |
| 181 | FROM solution WHERE id = $1 FOR UPDATE"#, |
| 182 | id.uuid() |
| 183 | ) |
| 184 | .fetch_optional(&mut *tx) |
| 185 | .await?; |
| 186 | let Some(before) = before else { |
| 187 | return Ok(None); |
| 188 | }; |
| 189 | sqlx::query!( |
| 190 | r#"UPDATE solution |
| 191 | SET image_file = $2, image_content_type = $3, image_size = $4 |
| 192 | WHERE id = $1"#, |
| 193 | id.uuid(), |
| 194 | file.as_str(), |
| 195 | content_type.as_str(), |
| 196 | size, |
| 197 | ) |
| 198 | .execute(&mut *tx) |
| 199 | .await?; |
| 200 | Ok(Some(before)) |
| 201 | }) |
| 202 | .await |
| 203 | } |
| 204 | |
| 205 | |
| 206 | |
| 207 | pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> { |
| 208 | |
| 209 | let id = *id; |
| 210 | tx_with_retry(db, false, async move |tx| { |
| 211 | let before = sqlx::query_as!( |
| 212 | Solution, |
| 213 | r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 214 | author AS "author: UserId", body AS "body: SolutionBody", |
| 215 | offered_at AS "offered_at: Timestamp", image_file, |
| 216 | image_content_type AS "image_content_type: FileContentType", |
| 217 | image_size |
| 218 | FROM solution WHERE id = $1 FOR UPDATE"#, |
| 219 | id.uuid() |
| 220 | ) |
| 221 | .fetch_optional(&mut *tx) |
| 222 | .await?; |
| 223 | let Some(before) = before else { |
| 224 | return Ok(None); |
| 225 | }; |
| 226 | sqlx::query!( |
| 227 | r#"UPDATE solution |
| 228 | SET image_file = NULL, image_content_type = NULL, image_size = NULL |
| 229 | WHERE id = $1"#, |
| 230 | id.uuid(), |
| 231 | ) |
| 232 | .execute(&mut *tx) |
| 233 | .await?; |
| 234 | Ok(Some(before)) |
| 235 | }) |
| 236 | .await |
| 237 | } |
| 238 | |
| 239 | pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> { |
| 240 | let deleted = sqlx::query_as!( |
| 241 | Solution, |
| 242 | r#"DELETE FROM solution WHERE id = $1 |
| 243 | RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 244 | author AS "author: UserId", body AS "body: SolutionBody", |
| 245 | offered_at AS "offered_at: Timestamp", image_file, |
| 246 | image_content_type AS "image_content_type: FileContentType", |
| 247 | image_size"#, |
| 248 | solution.id.uuid() |
| 249 | ) |
| 250 | .fetch_optional(db) |
| 251 | .await?; |
| 252 | deleted.ok_or(AppError::NotFound) |
| 253 | } |
| 254 | |
| 255 | #[cfg(test)] |
| 256 | mod tests { |
| 257 | use ulid::Ulid; |
| 258 | |
| 259 | use super::*; |
| 260 | use crate::database; |
| 261 | use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; |
| 262 | use crate::domain::timestamp::Timestamp; |
| 263 | use crate::domain::user::UserId; |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | async fn question_row(db: &Database) -> PoolQuestionId { |
| 269 | crate::db::pool_question::insert( |
| 270 | db, |
| 271 | PoolQuestion::new( |
| 272 | &UserId::from_key(&Ulid::generate().to_string()), |
| 273 | PoolQuestionTitle::try_new("soru").unwrap(), |
| 274 | PoolQuestionBody::try_new("neden").unwrap(), |
| 275 | ), |
| 276 | ) |
| 277 | .await |
| 278 | .unwrap() |
| 279 | .get_id() |
| 280 | .clone() |
| 281 | } |
| 282 | |
| 283 | #[tokio::test] |
| 284 | async fn rows_scope_to_their_question_and_list_oldest_first() { |
| 285 | let db = database::init_mem().await.unwrap(); |
| 286 | let question_a = question_row(&db).await; |
| 287 | let question_b = question_row(&db).await; |
| 288 | let author = UserId::from_key(&Ulid::generate().to_string()); |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | let mut first = Solution::new( |
| 295 | &question_a, |
| 296 | &author, |
| 297 | SolutionBody::try_new("Önce türevi al.").unwrap(), |
| 298 | ); |
| 299 | first.offered_at = Timestamp::from_millis(1); |
| 300 | let first = insert(&db, first).await.unwrap(); |
| 301 | let mut second = Solution::new( |
| 302 | &question_a, |
| 303 | &author, |
| 304 | SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), |
| 305 | ); |
| 306 | second.offered_at = Timestamp::from_millis(2); |
| 307 | let second = insert(&db, second).await.unwrap(); |
| 308 | |
| 309 | let (listed, _) = list_for(&db, &question_a, None, 0).await.unwrap(); |
| 310 | assert_eq!(listed.len(), 2); |
| 311 | assert_eq!(listed[0].get_id(), first.get_id()); |
| 312 | assert_eq!(listed[1].get_id(), second.get_id()); |
| 313 | assert!( |
| 314 | list_for(&db, &question_b, None, 0) |
| 315 | .await |
| 316 | .unwrap() |
| 317 | .0 |
| 318 | .is_empty() |
| 319 | ); |
| 320 | |
| 321 | |
| 322 | assert!( |
| 323 | read_for(&db, first.get_id(), &question_a) |
| 324 | .await |
| 325 | .unwrap() |
| 326 | .is_some() |
| 327 | ); |
| 328 | assert!( |
| 329 | read_for(&db, first.get_id(), &question_b) |
| 330 | .await |
| 331 | .unwrap() |
| 332 | .is_none() |
| 333 | ); |
| 334 | |
| 335 | delete(&db, first).await.unwrap(); |
| 336 | assert_eq!( |
| 337 | list_for(&db, &question_a, None, 0).await.unwrap().0.len(), |
| 338 | 1 |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | #[tokio::test] |
| 343 | async fn image_set_replace_clear_report_the_replaced_blob() { |
| 344 | let db = database::init_mem().await.unwrap(); |
| 345 | let question = question_row(&db).await; |
| 346 | let author = UserId::from_key(&Ulid::generate().to_string()); |
| 347 | let png = FileContentType::try_new("image/png").unwrap(); |
| 348 | |
| 349 | let solution = insert( |
| 350 | &db, |
| 351 | Solution::new( |
| 352 | &question, |
| 353 | &author, |
| 354 | SolutionBody::try_new("Grafiği çiz.").unwrap(), |
| 355 | ), |
| 356 | ) |
| 357 | .await |
| 358 | .unwrap(); |
| 359 | |
| 360 | let before = set_image(&db, solution.get_id(), "blob_a", &png, 3) |
| 361 | .await |
| 362 | .unwrap() |
| 363 | .unwrap(); |
| 364 | assert!(before.get_image_file().is_none()); |
| 365 | |
| 366 | |
| 367 | let before = set_image(&db, solution.get_id(), "blob_b", &png, 5) |
| 368 | .await |
| 369 | .unwrap() |
| 370 | .unwrap(); |
| 371 | assert_eq!(before.get_image_file(), Some("blob_a")); |
| 372 | let stored = read_for(&db, solution.get_id(), &question) |
| 373 | .await |
| 374 | .unwrap() |
| 375 | .unwrap(); |
| 376 | assert_eq!(stored.get_image_file(), Some("blob_b")); |
| 377 | assert_eq!(stored.get_image_size(), Some(5)); |
| 378 | |
| 379 | |
| 380 | let before = clear_image(&db, solution.get_id()).await.unwrap().unwrap(); |
| 381 | assert_eq!(before.get_image_file(), Some("blob_b")); |
| 382 | assert!( |
| 383 | read_for(&db, solution.get_id(), &question) |
| 384 | .await |
| 385 | .unwrap() |
| 386 | .unwrap() |
| 387 | .get_image_file() |
| 388 | .is_none() |
| 389 | ); |
| 390 | |
| 391 | |
| 392 | let deleted = delete(&db, solution.clone()).await.unwrap(); |
| 393 | assert_eq!(deleted.get_id(), solution.get_id()); |
| 394 | assert!( |
| 395 | set_image(&db, solution.get_id(), "blob_c", &png, 7) |
| 396 | .await |
| 397 | .unwrap() |
| 398 | .is_none() |
| 399 | ); |
| 400 | assert!(clear_image(&db, solution.get_id()).await.unwrap().is_none()); |
| 401 | } |
| 402 | |
| 403 | #[tokio::test] |
| 404 | async fn set_body_edits_in_place() { |
| 405 | let db = database::init_mem().await.unwrap(); |
| 406 | let question = question_row(&db).await; |
| 407 | let author = UserId::from_key(&Ulid::generate().to_string()); |
| 408 | |
| 409 | let solution = insert( |
| 410 | &db, |
| 411 | Solution::new( |
| 412 | &question, |
| 413 | &author, |
| 414 | SolutionBody::try_new("İlk deneme.").unwrap(), |
| 415 | ), |
| 416 | ) |
| 417 | .await |
| 418 | .unwrap(); |
| 419 | |
| 420 | let edited = set_body( |
| 421 | &db, |
| 422 | solution.get_id(), |
| 423 | &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), |
| 424 | ) |
| 425 | .await |
| 426 | .unwrap() |
| 427 | .unwrap(); |
| 428 | assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); |
| 429 | assert_eq!(edited.get_id(), solution.get_id()); |
| 430 | |
| 431 | |
| 432 | assert!( |
| 433 | set_body( |
| 434 | &db, |
| 435 | &SolutionId::from_key(&Ulid::generate().to_string()), |
| 436 | &SolutionBody::try_new("boş").unwrap(), |
| 437 | ) |
| 438 | .await |
| 439 | .unwrap() |
| 440 | .is_none() |
| 441 | ); |
| 442 | } |
| 443 | |
| 444 | #[tokio::test] |
| 445 | async fn counts_for_groups_per_question() { |
| 446 | let db = database::init_mem().await.unwrap(); |
| 447 | let two = question_row(&db).await; |
| 448 | let one = question_row(&db).await; |
| 449 | let none = question_row(&db).await; |
| 450 | let author = UserId::from_key(&Ulid::generate().to_string()); |
| 451 | |
| 452 | for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { |
| 453 | for body in bodies { |
| 454 | insert( |
| 455 | &db, |
| 456 | Solution::new(question, &author, SolutionBody::try_new(body).unwrap()), |
| 457 | ) |
| 458 | .await |
| 459 | .unwrap(); |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()]) |
| 464 | .await |
| 465 | .unwrap(); |
| 466 | assert_eq!(counts.get(two.key()), Some(&2)); |
| 467 | assert_eq!(counts.get(one.key()), Some(&1)); |
| 468 | |
| 469 | assert_eq!(counts.get(none.key()), None); |
| 470 | assert!(counts_for(&db, &[]).await.unwrap().is_empty()); |
| 471 | } |
| 472 | } |