forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

course_note.rs232 lines, 8.4 KiBHistoryRawDownload
1//! The `course_note` table: a course's shared notes, newest first, deleted
2//! together with their attachment rows.
3
4use crate::database::{Database, foreign_key_violation, tx_with_retry};
5use crate::db::field_update::FieldUpdate;
6use crate::db::page::PagedList;
7use crate::domain::course::CourseId;
8use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle};
9use crate::domain::course_note_file::{
10 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
11};
12use crate::domain::user::UserId;
13use crate::error::AppError;
14
15pub async fn create(
16 db: &Database,
17 course: &CourseId,
18 author: &UserId,
19 title: CourseNoteTitle,
20 content: CourseNoteContent,
21) -> Result<CourseNote, AppError> {
22 let note = CourseNote {
23 id: CourseNoteId::generate(),
24 course: course.clone(),
25 author: author.clone(),
26 title,
27 content,
28 };
29 // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber.
30 // The course row is *referenced* (a real foreign key the store now
31 // enforces), so a note that races `Course::delete`'s cascade is refused
32 // as 23503 instead of outliving its course — a note whose course is gone
33 // is unreachable forever, every route to it going through the course.
34 // That refusal is the parent-gone 404 the touch trick used to produce.
35 let created = sqlx::query_as!(
36 CourseNote,
37 r#"INSERT INTO course_note (id, course, author, title, content)
38 VALUES ($1, $2, $3, $4, $5)
39 RETURNING id AS "id: CourseNoteId", course AS "course: CourseId",
40 author AS "author: UserId", title AS "title: CourseNoteTitle",
41 content AS "content: CourseNoteContent""#,
42 note.id.uuid(),
43 note.course.uuid(),
44 note.author.uuid(),
45 note.title.as_str(),
46 note.content.as_str()
47 )
48 .fetch_one(db)
49 .await;
50 match created {
51 Ok(row) => Ok(row),
52 Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
53 Err(err) => Err(err.into()),
54 }
55}
56
57pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> {
58 let note = sqlx::query_as!(
59 CourseNote,
60 r#"SELECT id AS "id: CourseNoteId", course AS "course: CourseId",
61 author AS "author: UserId", title AS "title: CourseNoteTitle",
62 content AS "content: CourseNoteContent" FROM course_note WHERE id = $1"#,
63 id.uuid()
64 )
65 .fetch_optional(db)
66 .await?;
67 Ok(note)
68}
69
70pub async fn list_for_course(
71 db: &Database,
72 course: &CourseId,
73 limit: Option<i64>,
74 offset: i64,
75) -> Result<(Vec<CourseNote>, i64), AppError> {
76 PagedList::new("course_note WHERE course = $1", "ORDER BY id DESC")
77 .bind(course.uuid())
78 .run::<CourseNote>(limit, offset, db)
79 .await
80}
81
82/// Request-scoped: no lock spans the handler's read and this write, so an
83/// omitted field (`None`) is not written at all. Passing the snapshot's
84/// value back instead would revert a concurrent edit of that field —
85/// scoping the `SET` alone does not prevent that, the values have to come
86/// from the request. Neither column is nullable, so plain `Option` per
87/// field says everything there is to say.
88pub async fn update(
89 db: &Database,
90 note: CourseNote,
91 title: Option<CourseNoteTitle>,
92 content: Option<CourseNoteContent>,
93) -> Result<CourseNote, AppError> {
94 FieldUpdate::new("course_note", note.id.uuid())
95 .set("title", title.map(|title| title.as_str().to_string()))
96 .set(
97 "content",
98 content.map(|content| content.as_str().to_string()),
99 )
100 .run::<CourseNote>(db)
101 .await
102}
103
104/// Delete the note and cascade-remove its attachment rows, returning both:
105/// the note, and the attachment rows this transaction actually removed.
106/// Blob files on disk are the web layer's to remove, but only for *these*
107/// rows — a row uploaded after the caller listed the note's files is
108/// deleted here too, and a pre-read snapshot would strand its blob.
109///
110/// The `rag_output` sweep rides in the same transaction: `rag_output`
111/// references this table through a real foreign key (`ON DELETE NO
112/// ACTION`), so a derived row left behind would refuse the delete — and a
113/// derived row outliving its note is exactly what the cascade exists to
114/// prevent. The web layer's separate `delete_for_note` call stays, as a
115/// harmless idempotent repeat.
116pub async fn delete(
117 db: &Database,
118 note: CourseNote,
119) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {
120 tx_with_retry(db, true, async move |conn| {
121 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())
122 .execute(&mut *conn)
123 .await?;
124 let files = sqlx::query_as!(
125 CourseNoteFile,
126 r#"DELETE FROM course_note_file WHERE course_note = $1
127 RETURNING id AS "id: CourseNoteFileId",
128 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
129 content_type AS "content_type: FileContentType", size"#,
130 note.id.uuid()
131 )
132 .fetch_all(&mut *conn)
133 .await?;
134 let gone = sqlx::query_as!(
135 CourseNote,
136 r#"DELETE FROM course_note WHERE id = $1 RETURNING id AS "id: CourseNoteId", course AS "course: CourseId",
137 author AS "author: UserId", title AS "title: CourseNoteTitle",
138 content AS "content: CourseNoteContent""#,
139 note.id.uuid()
140 )
141 .fetch_optional(&mut *conn)
142 .await?;
143 let note = gone.ok_or(AppError::NotFound)?;
144 Ok((note, files))
145 })
146 .await
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
153 use crate::domain::course_note_file::{FileContentType, FileName};
154
155 /// The blobs the handler unlinks are exactly the rows this transaction
156 /// removed — including one uploaded after any pre-read snapshot would have
157 /// been taken, which is the row whose blob used to leak.
158 #[tokio::test]
159 async fn delete_returns_the_attachment_rows_it_removed() {
160 let db = crate::database::init_mem().await.unwrap();
161 let creator = crate::domain::user::UserId::generate();
162 let course = crate::db::course::create(
163 &db,
164 &creator,
165 CourseTitle::try_new("Math").unwrap(),
166 CourseDescription::try_new("").unwrap(),
167 CourseKind::try_new("course").unwrap(),
168 None,
169 None,
170 )
171 .await
172 .unwrap();
173 let note = create(
174 &db,
175 course.get_id(),
176 &creator,
177 CourseNoteTitle::try_new("a").unwrap(),
178 CourseNoteContent::try_new("body").unwrap(),
179 )
180 .await
181 .unwrap();
182 // What a handler snapshot would have seen...
183 let early = crate::db::course_note_file::insert(
184 &db,
185 CourseNoteFile::new(
186 note.get_id(),
187 FileName::try_new("early.pdf").unwrap(),
188 FileContentType::try_new("application/pdf").unwrap(),
189 3,
190 ),
191 )
192 .await
193 .unwrap();
194 let (snapshot, _) = crate::db::course_note_file::list_for(&db, note.get_id(), None, 0)
195 .await
196 .unwrap();
197 assert_eq!(snapshot.len(), 1);
198 // ...and the upload that races in after it.
199 let late = crate::db::course_note_file::insert(
200 &db,
201 CourseNoteFile::new(
202 note.get_id(),
203 FileName::try_new("late.pdf").unwrap(),
204 FileContentType::try_new("application/pdf").unwrap(),
205 3,
206 ),
207 )
208 .await
209 .unwrap();
210
211 let (gone, files) = delete(&db, note).await.unwrap();
212 assert_eq!(gone.get_title().as_str(), "a");
213 let mut keys: Vec<_> = files
214 .iter()
215 .map(|file| file.get_id().key().to_string())
216 .collect();
217 keys.sort();
218 let mut want = vec![
219 early.get_id().key().to_string(),
220 late.get_id().key().to_string(),
221 ];
222 want.sort();
223 assert_eq!(keys, want);
224 assert!(
225 crate::db::course_note_file::list_for(&db, gone.get_id(), None, 0)
226 .await
227 .unwrap()
228 .0
229 .is_empty()
230 );
231 }
232}