forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

bank_question.rs863 lines, 33.1 KiBHistoryRawDownload
1//! The `bank_question` table: template creates, the visibility-gated paged
2//! listing, the page-wide usage tally, the compare-and-set every PATCH writes
3//! through, and the delete that sweeps the slot table and clears both
4//! provenance links in one transaction. The PATCH re-derive lives in
5//! [`crate::service::bank_question`]; the pure entity and newtypes in
6//! [`crate::domain::bank_question`].
7
8use std::collections::HashMap;
9
10use sqlx::types::Json;
11
12use crate::database::{Database, tx_with_retry};
13use crate::db::page::{PagedList, Param};
14use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
15use crate::domain::bank_question_image::BankQuestionImage;
16use crate::domain::exam::ExamId;
17use crate::domain::exam_question::{
18 Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
19};
20use crate::domain::note_file::FileContentType;
21use crate::domain::subject::SubjectId;
22use crate::domain::text_fold::{search_fold, search_fold_sql};
23use crate::domain::timestamp::Timestamp;
24use crate::domain::user::UserId;
25use crate::error::AppError;
26
27/// The `choices` JSONB bind as the macros type the parameter — a
28/// `serde_json::Value`. A `Choice` is two plain strings: serializing one
29/// cannot fail.
30fn choices_as_value(choices: &[Choice]) -> serde_json::Value {
31 serde_json::to_value(choices).expect("Choice serialization cannot fail")
32}
33
34pub async fn create(
35 db: &Database,
36 owner: UserId,
37 subject: SubjectId,
38 text: QuestionText,
39 points: QuestionPoints,
40 spec: QuestionSpec,
41) -> Result<BankQuestion, AppError> {
42 insert(db, owner, subject, text, points, spec, None).await
43}
44
45/// Like [`create`], but records the origin exam the template was saved from
46/// (`POST …/questions/{qid}/to-bank`).
47pub async fn create_from_exam(
48 db: &Database,
49 owner: UserId,
50 subject: SubjectId,
51 text: QuestionText,
52 points: QuestionPoints,
53 spec: QuestionSpec,
54 source: ExamId,
55) -> Result<BankQuestion, AppError> {
56 insert(db, owner, subject, text, points, spec, Some(source)).await
57}
58
59#[allow(clippy::too_many_arguments)]
60async fn insert(
61 db: &Database,
62 owner: UserId,
63 subject: SubjectId,
64 text: QuestionText,
65 points: QuestionPoints,
66 spec: QuestionSpec,
67 source_exam: Option<ExamId>,
68) -> Result<BankQuestion, AppError> {
69 let question = BankQuestion::from_parts(
70 BankQuestionId::generate(),
71 owner,
72 // Creation always carries a validated subject; only a subject
73 // delete ever clears it.
74 Some(subject),
75 text,
76 points,
77 spec,
78 source_exam,
79 // Never published on creation — publishing is its own PATCH.
80 BankVisibility::default(),
81 Timestamp::now(),
82 );
83 let row = sqlx::query_as!(
84 BankQuestion,
85 r#"INSERT INTO bank_question
86 (id, owner, subject, text, kind, points, choices, correct,
87 source_exam, visibility, created_at)
88 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
89 RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId",
90 subject AS "subject: SubjectId", text AS "text: QuestionText",
91 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
92 choices AS "choices: Json<Vec<Choice>>",
93 correct AS "correct: ChoiceId",
94 source_exam AS "source_exam: ExamId",
95 visibility AS "visibility: BankVisibility",
96 created_at AS "created_at: Timestamp""#,
97 question.id.uuid(),
98 question.owner.uuid(),
99 question.subject.as_ref().map(SubjectId::uuid),
100 question.text.as_str(),
101 question.kind.as_str(),
102 question.points.as_i64(),
103 question
104 .choices
105 .as_ref()
106 .map(|json| choices_as_value(&json.0)),
107 question.correct.as_ref().map(ChoiceId::as_str),
108 question.source_exam.as_ref().map(ExamId::uuid),
109 question.visibility.as_str(),
110 question.created_at.as_millis(),
111 )
112 .fetch_one(db)
113 .await?;
114 Ok(row)
115}
116
117pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> {
118 let row = sqlx::query_as!(
119 BankQuestion,
120 r#"SELECT id AS "id: BankQuestionId", owner AS "owner: UserId",
121 subject AS "subject: SubjectId", text AS "text: QuestionText",
122 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
123 choices AS "choices: Json<Vec<Choice>>",
124 correct AS "correct: ChoiceId",
125 source_exam AS "source_exam: ExamId",
126 visibility AS "visibility: BankVisibility",
127 created_at AS "created_at: Timestamp"
128 FROM bank_question WHERE id = $1"#,
129 id.uuid()
130 )
131 .fetch_optional(db)
132 .await?;
133 Ok(row)
134}
135
136/// One page of the bank the caller may see, **newest first** (`id DESC` is
137/// mint order — the ids are write-ordered UUIDv7) — plus the total row count
138/// under the same filters, so a client can page past the window.
139///
140/// The window is a real `LIMIT`/`OFFSET` handed to the database (the
141/// [`PagedList`] builder: the filters are runtime-conditional, which is that
142/// builder's named exemption from the compile-time macros). `q` is a case-
143/// and diacritic-insensitive fragment of the question text (blank = no text
144/// filter): needle and column both go through [`crate::domain::text_fold`],
145/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE`
146/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises.
147///
148/// `visible_to` is the security filter, and it is a WHERE clause like every
149/// other one — never a post-filter, or `total` would count templates the
150/// caller can't have and paging would return short pages of them:
151/// `Some(me)` sees the school-published templates plus their own,
152/// `None` (admins only) sees everything.
153///
154/// `visibility` is the *user's* filter ("only mine" / "shared with the
155/// school") and is ANDed on top of that gate, so it can only ever narrow:
156/// `school` still hides another teacher's private rows, and `private`
157/// intersected with the gate leaves exactly the caller's own drafts. It is
158/// part of the same WHERE, so `total` honours it too — a count that ignored
159/// it would break paging.
160///
161/// The uuid filters bind raw through the id newtypes' [`crate::domain`]
162/// `uuid()` accessor — [`Param::Uuid`] keeps the comparison exact, typed
163/// rather than textual.
164#[allow(clippy::too_many_arguments)]
165pub async fn list(
166 db: &Database,
167 visible_to: Option<&UserId>,
168 owner: Option<&UserId>,
169 subject: Option<&SubjectId>,
170 visibility: Option<&BankVisibility>,
171 q: Option<&str>,
172 limit: Option<i64>,
173 offset: i64,
174) -> Result<(Vec<BankQuestion>, i64), AppError> {
175 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
176 let mut clauses: Vec<String> = Vec::new();
177 let mut binds: Vec<Param> = Vec::new();
178 if let Some(viewer) = visible_to {
179 binds.push(Param::Uuid(viewer.uuid()));
180 clauses.push(format!(
181 "(visibility = 'school' OR owner = ${})",
182 binds.len()
183 ));
184 }
185 if let Some(visibility) = visibility {
186 binds.push(Param::Text(visibility.as_str().to_string()));
187 clauses.push(format!("visibility = ${}", binds.len()));
188 }
189 if let Some(owner) = owner {
190 binds.push(Param::Uuid(owner.uuid()));
191 clauses.push(format!("owner = ${}", binds.len()));
192 }
193 if let Some(subject) = subject {
194 binds.push(Param::Uuid(subject.uuid()));
195 clauses.push(format!("subject = ${}", binds.len()));
196 }
197 if let Some(needle) = needle {
198 binds.push(Param::Text(needle));
199 clauses.push(format!(
200 "position(${} in {}) > 0",
201 binds.len(),
202 search_fold_sql("text")
203 ));
204 }
205 let from_where = if clauses.is_empty() {
206 "bank_question WHERE true".to_string()
207 } else {
208 format!("bank_question WHERE {}", clauses.join(" AND "))
209 };
210 // The count runs over the *same* WHERE, so `total` can never disagree
211 // with what paging through the list actually yields.
212 let mut page = PagedList::new(from_where, "ORDER BY id DESC");
213 for bind in binds {
214 page = page.bind(bind);
215 }
216 page.run(limit, offset, db).await
217}
218
219/// How many exam questions were instantiated from each of `ids` — the
220/// `from_bank` side of the provenance link, tallied for a whole page in
221/// **one** grouped query (a `count()` per row would be the N+1 this page
222/// already had removed once). Keys are the templates' wire keys; a template
223/// nobody ever used has no entry at all, so the caller reads a miss as
224/// zero — and the UI can stay quiet rather than print "0".
225///
226/// Counts *questions*, not distinct exams: one exam that inserted the same
227/// template twice counts twice, which is what "copies made from this
228/// template" means and what the divergence trap is actually about.
229pub async fn usage_counts(
230 db: &Database,
231 ids: &[&BankQuestionId],
232) -> Result<HashMap<String, i64>, AppError> {
233 if ids.is_empty() {
234 return Ok(HashMap::new());
235 }
236 let ids: Vec<uuid::Uuid> = ids.iter().map(|id| id.uuid()).collect();
237 let rows = sqlx::query!(
238 r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n
239 FROM exam_question
240 WHERE from_bank = ANY($1)
241 GROUP BY from_bank"#,
242 &ids,
243 )
244 .fetch_all(db)
245 .await?;
246 Ok(rows
247 .into_iter()
248 .filter_map(|row| {
249 let n = row.n.unwrap_or(0);
250 row.from_bank.map(|from_bank| (from_bank.key(), n))
251 })
252 .collect())
253}
254
255/// Write the editable fields of the template, but only while the row still
256/// reads as the snapshot `expected` was loaded from — `None` means a concurrent
257/// edit (or the subject-delete cascade that clears `subject`) landed inside
258/// the handler's read-merge window, so nothing was written: reload,
259/// re-merge, retry. This is a genuine read-modify-write — every editable
260/// field is re-stated from the snapshot, and the kind/choices/correct trio
261/// has to be (a text-only edit re-submits the stored options *with their
262/// ids* so each keeps its picture) — so without the compare-and-set the
263/// later writer silently reverts the earlier one.
264///
265/// Every field the merge re-states is in the guard, which is the same list
266/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an
267/// absent subject/correct/choices guards truthfully. Postgres needs no retry
268/// loop around this: the guard re-evaluates on the row lock at execution, so
269/// a rival write either predates this statement's snapshot or loses its own.
270pub async fn update_if_unchanged(
271 db: &Database,
272 expected: BankQuestion,
273 subject: Option<SubjectId>,
274 text: QuestionText,
275 points: QuestionPoints,
276 spec: QuestionSpec,
277 visibility: BankVisibility,
278) -> Result<Option<BankQuestion>, AppError> {
279 let (kind, choices, correct) = spec.into_parts();
280 let choices = choices.map(Json);
281 let row = sqlx::query_as!(
282 BankQuestion,
283 r#"UPDATE bank_question SET
284 subject = $2, text = $3, points = $4, kind = $5,
285 choices = $6, correct = $7, visibility = $8
286 WHERE id = $1
287 AND subject IS NOT DISTINCT FROM $9
288 AND text = $10
289 AND points = $11
290 AND kind = $12
291 AND choices IS NOT DISTINCT FROM $13
292 AND correct IS NOT DISTINCT FROM $14
293 AND visibility = $15
294 RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId",
295 subject AS "subject: SubjectId", text AS "text: QuestionText",
296 kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
297 choices AS "choices: Json<Vec<Choice>>",
298 correct AS "correct: ChoiceId",
299 source_exam AS "source_exam: ExamId",
300 visibility AS "visibility: BankVisibility",
301 created_at AS "created_at: Timestamp""#,
302 expected.id.uuid(),
303 subject.as_ref().map(SubjectId::uuid),
304 text.as_str(),
305 points.as_i64(),
306 kind.as_str(),
307 choices.as_ref().map(|json| choices_as_value(&json.0)),
308 correct.as_ref().map(ChoiceId::as_str),
309 visibility.as_str(),
310 expected.subject.as_ref().map(SubjectId::uuid),
311 expected.text.as_str(),
312 expected.points.as_i64(),
313 expected.kind.as_str(),
314 expected
315 .choices
316 .as_ref()
317 .map(|json| choices_as_value(&json.0)),
318 expected.correct.as_ref().map(ChoiceId::as_str),
319 expected.visibility.as_str(),
320 )
321 .fetch_optional(db)
322 .await?;
323 Ok(row)
324}
325
326/// Delete the template and cascade-remove its bank images, so none points
327/// at a missing template. Bank rows have no answers. The image rows this
328/// actually removed come back with it: the blobs are the web layer's to
329/// take off disk, but only for *these* rows — an upload that committed
330/// after the caller listed the template's images is swept here too, and a
331/// pre-read snapshot would strand its blob for good.
332///
333/// All four statements are one transaction, children before the parent so
334/// the foreign keys never refuse the parent delete: the provenance links
335/// clear first (exam questions tied to this template keep living — only the
336/// links go, field-scoped, in both directions: `from_bank` on the questions
337/// instantiated from it and `banked_as` on the question it was saved out
338/// of), then the image sweep, then the row. `cascade = true` because an
339/// image upsert committing inside this window makes the parent delete
340/// answer 23503 — a mid-cascade race the retry loop re-runs, sweeping the
341/// latecomer with it.
342pub async fn delete(
343 db: &Database,
344 target: BankQuestion,
345) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> {
346 tx_with_retry(db, true, async move |tx| {
347 let id = target.id.clone();
348 sqlx::query!(
349 "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1",
350 id.uuid()
351 )
352 .execute(&mut *tx)
353 .await?;
354 sqlx::query!(
355 "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1",
356 id.uuid()
357 )
358 .execute(&mut *tx)
359 .await?;
360 let images = sqlx::query_as!(
361 BankQuestionImage,
362 r#"DELETE FROM bank_question_image WHERE bank_question = $1
363 RETURNING bank_question AS "bank_question: BankQuestionId",
364 slot AS "slot: ChoiceId", file,
365 content_type AS "content_type: FileContentType", size"#,
366 id.uuid()
367 )
368 .fetch_all(&mut *tx)
369 .await?;
370 let question = sqlx::query_as!(
371 BankQuestion,
372 r#"DELETE FROM bank_question WHERE id = $1
373 RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId",
374 subject AS "subject: SubjectId",
375 text AS "text: QuestionText", kind AS "kind: QuestionKind",
376 points AS "points: QuestionPoints",
377 choices AS "choices: Json<Vec<Choice>>",
378 correct AS "correct: ChoiceId",
379 source_exam AS "source_exam: ExamId",
380 visibility AS "visibility: BankVisibility",
381 created_at AS "created_at: Timestamp""#,
382 id.uuid()
383 )
384 .fetch_optional(&mut *tx)
385 .await?
386 .ok_or(AppError::NotFound)?;
387 Ok((question, images))
388 })
389 .await
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL};
396
397 /// A real `app_user` row: template owners are foreign keys now. The id is
398 /// minted per call, so repeated calls are new people, not the same row.
399 async fn a_person(db: &Database, label: &str) -> UserId {
400 let user = UserId::generate();
401 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
402 .bind(user.uuid())
403 .bind(format!("{label}-{}", &user.key()[30..]))
404 .execute(db)
405 .await
406 .unwrap();
407 user
408 }
409
410 /// A real subject row: a template's subject reference is a foreign key
411 /// too (and the subject needs a real course under it).
412 async fn a_subject(db: &Database) -> SubjectId {
413 *crate::db::subject::create(
414 db,
415 &crate::db::course::a_test_course(db).await,
416 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
417 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
418 )
419 .await
420 .unwrap()
421 .get_id()
422 }
423
424 fn spec() -> QuestionSpec {
425 use crate::domain::exam_question::{ChoiceInput, QuestionKind};
426 QuestionSpec::try_new(
427 QuestionKind::try_new("choice").unwrap(),
428 Some(vec![
429 ChoiceInput {
430 id: Some("a".into()),
431 text: "yes".into(),
432 },
433 ChoiceInput {
434 id: Some("b".into()),
435 text: "no".into(),
436 },
437 ]),
438 Some("b".into()),
439 &[],
440 )
441 .unwrap()
442 }
443
444 /// A row without a visibility of its own must decode as `private`, the
445 /// safe value. The old engine could store a row with the field absent;
446 /// Postgres carries the same guarantee in the schema instead — the column
447 /// is `NOT NULL DEFAULT 'private'`, so a `school` default here would
448 /// publish every pre-existing template in the school at once. The insert
449 /// below is written exactly as a pre-visibility row arrives: no column.
450 #[tokio::test]
451 async fn a_row_without_the_field_decodes_private() {
452 let (db, _leases) = crate::database::init_test_db().await;
453 let owner = a_person(&db, "owner").await;
454 let id = BankQuestionId::generate();
455 sqlx::query(
456 "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \
457 VALUES ($1, $2, 'q', 'multiple_choice', 1, 0)",
458 )
459 .bind(id.uuid())
460 .bind(owner.uuid())
461 .execute(&db)
462 .await
463 .unwrap();
464
465 let old = read(&db, &id).await.unwrap().expect("the row is there");
466 assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
467 assert!(!old.get_visibility().is_school());
468 }
469
470 /// The visibility gate is a WHERE clause, so `total` counts exactly what the
471 /// page can contain — never someone else's private templates.
472 #[tokio::test]
473 async fn list_hides_private_templates_from_others() {
474 let (db, _leases) = crate::database::init_test_db().await;
475 let owner = a_person(&db, "owner").await;
476 let other = a_person(&db, "other").await;
477 let private = create(
478 &db,
479 owner,
480 a_subject(&db).await,
481 QuestionText::try_new("secret").unwrap(),
482 QuestionPoints::try_new(1).unwrap(),
483 spec(),
484 )
485 .await
486 .unwrap();
487 let published = create(
488 &db,
489 owner,
490 a_subject(&db).await,
491 QuestionText::try_new("shared").unwrap(),
492 QuestionPoints::try_new(1).unwrap(),
493 spec(),
494 )
495 .await
496 .unwrap();
497 let subject = published.get_subject().cloned();
498 update_if_unchanged(
499 &db,
500 published,
501 subject,
502 QuestionText::try_new("shared").unwrap(),
503 QuestionPoints::try_new(1).unwrap(),
504 spec(),
505 BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(),
506 )
507 .await
508 .unwrap();
509
510 // The stranger sees the published one alone, and `total` agrees.
511 let (items, total) = list(&db, Some(&other), None, None, None, None, None, 0)
512 .await
513 .unwrap();
514 assert_eq!((items.len(), total), (1, 1));
515 assert_eq!(items[0].get_text().as_str(), "shared");
516 // The owner sees both; an admin (`None`) too.
517 let (items, total) = list(&db, Some(&owner), None, None, None, None, None, 0)
518 .await
519 .unwrap();
520 assert_eq!((items.len(), total), (2, 2));
521 let (items, total) = list(&db, None, None, None, None, None, None, 0)
522 .await
523 .unwrap();
524 assert_eq!((items.len(), total), (2, 2));
525 // An explicit `owner=` filter can't widen the gate.
526 let (items, total) = list(&db, Some(&other), Some(&owner), None, None, None, None, 0)
527 .await
528 .unwrap();
529 assert_eq!((items.len(), total), (1, 1));
530 assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
531 }
532
533 /// The bite test for the compare-and-set that replaced the writer lease of
534 /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has
535 /// since moved past must be refused, not written — otherwise it reverts
536 /// whatever landed in between. Asserts the *stored* row, never a race
537 /// outcome: the in-memory engine can drop one of two concurrent writes and
538 /// still answer `Ok`.
539 #[tokio::test]
540 async fn a_merge_built_on_a_stale_snapshot_is_refused() {
541 let (db, _leases) = crate::database::init_test_db().await;
542 let owner = a_person(&db, "owner").await;
543 let stale = create(
544 &db,
545 owner,
546 a_subject(&db).await,
547 QuestionText::try_new("first").unwrap(),
548 QuestionPoints::try_new(1).unwrap(),
549 spec(),
550 )
551 .await
552 .unwrap();
553 // Somebody else's edit lands on the row this snapshot came from.
554 let landed = update_if_unchanged(
555 &db,
556 stale.clone(),
557 None,
558 QuestionText::try_new("theirs").unwrap(),
559 QuestionPoints::try_new(2).unwrap(),
560 spec(),
561 BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(),
562 )
563 .await
564 .unwrap();
565 assert!(landed.is_some(), "the first write is on a fresh snapshot");
566
567 let refused = update_if_unchanged(
568 &db,
569 stale,
570 None,
571 QuestionText::try_new("mine").unwrap(),
572 QuestionPoints::try_new(3).unwrap(),
573 spec(),
574 BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(),
575 )
576 .await
577 .unwrap();
578 assert!(refused.is_none(), "a stale merge must not be written");
579 let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap();
580 assert_eq!(stored.get_text().as_str(), "theirs");
581 assert_eq!(stored.get_points().as_i64(), 2);
582 }
583
584 /// The `visibility` filter ANDs onto the security gate, so it narrows and
585 /// never widens: a stranger asking for `school` still can't see a private
586 /// row, and `private` means "my own drafts" for everyone but an admin.
587 #[tokio::test]
588 async fn visibility_filter_narrows_never_widens() {
589 let (db, _leases) = crate::database::init_test_db().await;
590 let owner = a_person(&db, "owner").await;
591 let other = a_person(&db, "other").await;
592 async fn mine(db: &Database, owner: &UserId, text: &str) -> Result<BankQuestion, AppError> {
593 create(
594 db,
595 *owner,
596 a_subject(db).await,
597 QuestionText::try_new(text).unwrap(),
598 QuestionPoints::try_new(1).unwrap(),
599 spec(),
600 )
601 .await
602 }
603 mine(&db, &owner, "draft").await.unwrap();
604 let published = mine(&db, &owner, "shared").await.unwrap();
605 let subject = published.get_subject().cloned();
606 update_if_unchanged(
607 &db,
608 published,
609 subject,
610 QuestionText::try_new("shared").unwrap(),
611 QuestionPoints::try_new(1).unwrap(),
612 spec(),
613 BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(),
614 )
615 .await
616 .unwrap();
617 let private = BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap();
618 let school = BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap();
619
620 // Owner: `private` = their drafts, `school` = the published one.
621 let (items, total) = list(&db, Some(&owner), None, None, Some(&private), None, None, 0)
622 .await
623 .unwrap();
624 assert_eq!((items.len(), total), (1, 1));
625 assert_eq!(items[0].get_text().as_str(), "draft");
626 let (items, total) = list(&db, Some(&owner), None, None, Some(&school), None, None, 0)
627 .await
628 .unwrap();
629 assert_eq!((items.len(), total), (1, 1));
630 assert_eq!(items[0].get_text().as_str(), "shared");
631 // A stranger's `private` is empty — never someone else's draft.
632 let (items, total) = list(&db, Some(&other), None, None, Some(&private), None, None, 0)
633 .await
634 .unwrap();
635 assert!(items.is_empty());
636 assert_eq!(total, 0);
637 // …and their `school` stops at the published one, gate intact.
638 let (items, total) = list(&db, Some(&other), None, None, Some(&school), None, None, 0)
639 .await
640 .unwrap();
641 assert_eq!((items.len(), total), (1, 1));
642 // Composes with the other filters: right owner, wrong visibility.
643 let (items, total) = list(
644 &db,
645 Some(&owner),
646 Some(&owner),
647 None,
648 Some(&school),
649 Some("draft"),
650 None,
651 0,
652 )
653 .await
654 .unwrap();
655 assert!(items.is_empty());
656 assert_eq!(total, 0);
657 }
658
659 /// The whole page's tally in one grouped statement: right number per
660 /// template, unused templates absent (so the UI prints nothing rather than
661 /// "0"), and questions authored by hand never counted.
662 #[tokio::test]
663 async fn usage_counts_tallies_a_page_in_one_statement() {
664 // One statement, so a page costs one round trip: the tally is a single
665 // static `query!` (a `GROUP BY` with no loop around it), which the
666 // compiler now checks the way the old constant asserted.
667 let (db, _leases) = crate::database::init_test_db().await;
668 let owner = a_person(&db, "owner").await;
669 async fn template(
670 db: &Database,
671 owner: &UserId,
672 text: &str,
673 ) -> Result<BankQuestion, AppError> {
674 create(
675 db,
676 *owner,
677 a_subject(db).await,
678 QuestionText::try_new(text).unwrap(),
679 QuestionPoints::try_new(1).unwrap(),
680 spec(),
681 )
682 .await
683 }
684 let used_twice = template(&db, &owner, "twice").await.unwrap();
685 let used_once = template(&db, &owner, "once").await.unwrap();
686 let unused = template(&db, &owner, "never").await.unwrap();
687
688 // Real exam rows: instantiating a template moves the exam's counter
689 // (what keeps a question from outliving its exam), so a minted id
690 // nothing wrote is a 404.
691 let exam = crate::db::exam::published_exam(&db).await.get_id().clone();
692 let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone();
693 // A real subject row: an exam question claims a reference on its
694 // subject, so a minted id it never wrote would be refused.
695 let subject = crate::db::subject::create(
696 &db,
697 &crate::db::course::a_test_course(&db).await,
698 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
699 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
700 )
701 .await
702 .unwrap();
703 async fn instantiate(
704 exam: &ExamId,
705 subject: &SubjectId,
706 source: &BankQuestion,
707 db: &Database,
708 ) {
709 crate::db::exam_question::create_from_bank(
710 db,
711 exam,
712 *subject,
713 source.get_text().clone(),
714 source.get_points(),
715 source.spec(),
716 source.get_id().clone(),
717 )
718 .await
719 .unwrap();
720 }
721 // Two copies of the same template, in two different exams.
722 instantiate(&exam, subject.get_id(), &used_twice, &db).await;
723 instantiate(&other_exam, subject.get_id(), &used_twice, &db).await;
724 instantiate(&exam, subject.get_id(), &used_once, &db).await;
725 // A hand-authored question has no `from_bank` and must not be tallied.
726 crate::db::exam_question::create(
727 &db,
728 &exam,
729 *subject.get_id(),
730 QuestionText::try_new("mine").unwrap(),
731 QuestionPoints::try_new(1).unwrap(),
732 spec(),
733 )
734 .await
735 .unwrap();
736
737 let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()];
738 let counts = usage_counts(&db, &ids).await.unwrap();
739 assert_eq!(counts.get(&used_twice.get_id().key()).copied(), Some(2));
740 assert_eq!(counts.get(&used_once.get_id().key()).copied(), Some(1));
741 assert_eq!(
742 counts.get(&unused.get_id().key()),
743 None,
744 "unused stays absent"
745 );
746 assert_eq!(counts.len(), 2);
747
748 // A template outside the page is never counted into it.
749 let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap();
750 assert_eq!(narrow.len(), 1);
751 assert_eq!(narrow.get(&used_once.get_id().key()).copied(), Some(1));
752 // An empty page asks nothing at all.
753 assert!(usage_counts(&db, &[]).await.unwrap().is_empty());
754 }
755
756 #[tokio::test]
757 async fn list_is_school_wide() {
758 let (db, _leases) = crate::database::init_test_db().await;
759 for _ in 0..2 {
760 create(
761 &db,
762 a_person(&db, "owner").await,
763 a_subject(&db).await,
764 QuestionText::try_new("q").unwrap(),
765 QuestionPoints::try_new(1).unwrap(),
766 spec(),
767 )
768 .await
769 .unwrap();
770 }
771 // Different owners, yet both listed.
772 let (items, total) = list(&db, None, None, None, None, None, None, 0)
773 .await
774 .unwrap();
775 assert_eq!(items.len(), 2);
776 assert_eq!(total, 2);
777 }
778
779 /// The window is SQL, not an in-memory slice, and `total` ignores it.
780 #[tokio::test]
781 async fn list_pages_newest_first_and_filters_text() {
782 let (db, _leases) = crate::database::init_test_db().await;
783 let owner = a_person(&db, "owner").await;
784 for i in 0..5 {
785 create(
786 &db,
787 owner,
788 a_subject(&db).await,
789 QuestionText::try_new(&format!("question {i}")).unwrap(),
790 QuestionPoints::try_new(1).unwrap(),
791 spec(),
792 )
793 .await
794 .unwrap();
795 }
796 let (page, total) = list(&db, None, None, None, None, None, Some(2), 0)
797 .await
798 .unwrap();
799 assert_eq!(total, 5);
800 assert_eq!(page.len(), 2);
801 // Newest first: the last-created row leads.
802 assert_eq!(page[0].get_text().as_str(), "question 4");
803 // The tail is reachable by offset.
804 let (tail, _) = list(&db, None, None, None, None, None, Some(2), 4)
805 .await
806 .unwrap();
807 assert_eq!(tail[0].get_text().as_str(), "question 0");
808 // Text filter runs in SQL, case-insensitively, and narrows `total`.
809 let (hits, total) = list(&db, None, None, None, None, Some("QUESTION 3"), None, 0)
810 .await
811 .unwrap();
812 assert_eq!((hits.len(), total), (1, 1));
813 // Owner filter with nobody's templates.
814 let (none, total) = list(
815 &db,
816 None,
817 Some(&a_person(&db, "empty").await),
818 None,
819 None,
820 None,
821 None,
822 0,
823 )
824 .await
825 .unwrap();
826 assert!(none.is_empty());
827 assert_eq!(total, 0);
828 }
829
830 /// Turkish `İ`/`ı` must not split the search into two disjoint halves.
831 #[tokio::test]
832 async fn list_text_filter_folds_turkish_casing() {
833 let (db, _leases) = crate::database::init_test_db().await;
834 create(
835 &db,
836 a_person(&db, "owner").await,
837 a_subject(&db).await,
838 QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(),
839 QuestionPoints::try_new(1).unwrap(),
840 spec(),
841 )
842 .await
843 .unwrap();
844 for needle in [
845 "istanbul",
846 "İSTANBUL",
847 "İstanbul",
848 "ıstanbul",
849 "ilçe",
850 "ILCE",
851 ] {
852 let (hits, total) = list(&db, None, None, None, None, Some(needle), None, 0)
853 .await
854 .unwrap();
855 assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed");
856 }
857 let (miss, total) = list(&db, None, None, None, None, Some("ankara"), None, 0)
858 .await
859 .unwrap();
860 assert!(miss.is_empty());
861 assert_eq!(total, 0);
862 }
863}