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

course_note.rs263 lines, 9.7 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,
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/// Every course note that has at least one attachment, newest first.
83///
84/// One statement: the attachment table is filtered in the `EXISTS`, not
85/// queried once per note. A note with no files is absent — a `rag.index`
86/// replay has nothing to send for it. `file_count` is not the predicate:
87/// the file rows are the ground truth, and the counter is only a cap.
88pub async fn list_with_files(db: &Database) -> Result<Vec<CourseNote>, AppError> {
89 let notes = sqlx::query_as!(
90 CourseNote,
91 r#"SELECT id AS "id: CourseNoteId", course AS "course: CourseId",
92 author AS "author: UserId", title AS "title: CourseNoteTitle",
93 content AS "content: CourseNoteContent"
94 FROM course_note
95 WHERE EXISTS (
96 SELECT 1 FROM course_note_file
97 WHERE course_note_file.course_note = course_note.id
98 )
99 ORDER BY id DESC"#,
100 )
101 .fetch_all(db)
102 .await?;
103 Ok(notes)
104}
105
106/// Request-scoped: no lock spans the handler's read and this write, so an
107/// omitted field (`None`) is not written at all. Passing the snapshot's
108/// value back instead would revert a concurrent edit of that field —
109/// scoping the `SET` alone does not prevent that, the values have to come
110/// from the request. Neither column is nullable, so plain `Option` per
111/// field says everything there is to say.
112pub async fn update(
113 db: &Database,
114 note: CourseNote,
115 title: Option<CourseNoteTitle>,
116 content: Option<CourseNoteContent>,
117) -> Result<CourseNote, AppError> {
118 FieldUpdate::new("course_note", note.id.uuid())
119 .set("title", title.map(|title| title.as_str().to_string()))
120 .set(
121 "content",
122 content.map(|content| content.as_str().to_string()),
123 )
124 .run::<CourseNote>(db)
125 .await
126}
127
128/// Delete the note and cascade-remove its attachment rows, returning both:
129/// the note, and the attachment rows this transaction actually removed.
130/// Blob files on disk are the web layer's to remove, but only for *these*
131/// rows — a row uploaded after the caller listed the note's files is
132/// deleted here too, and a pre-read snapshot would strand its blob.
133///
134/// The `rag_output` sweep rides in the same transaction: `rag_output`
135/// references this table through a real foreign key (`ON DELETE NO
136/// ACTION`), so a derived row left behind would refuse the delete — and a
137/// derived row outliving its note is exactly what the cascade exists to
138/// prevent. The web layer's separate `delete_for_note` call stays, as a
139/// harmless idempotent repeat.
140pub async fn delete(
141 db: &Database,
142 note: CourseNote,
143) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {
144 tx_with_retry(db, true, async move |conn| {
145 // Links before rows: the outputs' citation links are their children
146 // (`ON DELETE NO ACTION`).
147 sqlx::query!(
148 "DELETE FROM rag_output_source WHERE output IN
149 (SELECT id FROM rag_output WHERE course_note = $1)",
150 note.id.uuid()
151 )
152 .execute(&mut *conn)
153 .await?;
154 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())
155 .execute(&mut *conn)
156 .await?;
157 let files = sqlx::query_as!(
158 CourseNoteFile,
159 r#"DELETE FROM course_note_file WHERE course_note = $1
160 RETURNING id AS "id: CourseNoteFileId",
161 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
162 content_type AS "content_type: FileContentType", size"#,
163 note.id.uuid()
164 )
165 .fetch_all(&mut *conn)
166 .await?;
167 let gone = sqlx::query_as!(
168 CourseNote,
169 r#"DELETE FROM course_note WHERE id = $1 RETURNING id AS "id: CourseNoteId", course AS "course: CourseId",
170 author AS "author: UserId", title AS "title: CourseNoteTitle",
171 content AS "content: CourseNoteContent""#,
172 note.id.uuid()
173 )
174 .fetch_optional(&mut *conn)
175 .await?;
176 let note = gone.ok_or(AppError::NotFound)?;
177 Ok((note, files))
178 })
179 .await
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
186 use crate::domain::course_note_file::{FileContentType, FileName};
187
188 /// The blobs the handler unlinks are exactly the rows this transaction
189 /// removed — including one uploaded after any pre-read snapshot would have
190 /// been taken, which is the row whose blob used to leak.
191 #[tokio::test]
192 async fn delete_returns_the_attachment_rows_it_removed() {
193 let (db, _leases) = crate::database::init_test_db().await;
194 let creator = crate::db::class_member::tests::fixture_user(&db, "course-note-author").await;
195 let course = crate::db::course::create(
196 &db,
197 &creator,
198 CourseTitle::try_new("Math").unwrap(),
199 CourseDescription::try_new("").unwrap(),
200 CourseKind::try_new("course").unwrap(),
201 )
202 .await
203 .unwrap();
204 let note = create(
205 &db,
206 course.get_id(),
207 &creator,
208 CourseNoteTitle::try_new("a").unwrap(),
209 CourseNoteContent::try_new("body").unwrap(),
210 )
211 .await
212 .unwrap();
213 // What a handler snapshot would have seen...
214 let early = crate::db::course_note_file::insert(
215 &db,
216 CourseNoteFile::new(
217 note.get_id(),
218 FileName::try_new("early.pdf").unwrap(),
219 FileContentType::try_new("application/pdf").unwrap(),
220 3,
221 ),
222 )
223 .await
224 .unwrap();
225 let (snapshot, _) = crate::db::course_note_file::list_for(&db, note.get_id(), None, 0)
226 .await
227 .unwrap();
228 assert_eq!(snapshot.len(), 1);
229 // ...and the upload that races in after it.
230 let late = crate::db::course_note_file::insert(
231 &db,
232 CourseNoteFile::new(
233 note.get_id(),
234 FileName::try_new("late.pdf").unwrap(),
235 FileContentType::try_new("application/pdf").unwrap(),
236 3,
237 ),
238 )
239 .await
240 .unwrap();
241
242 let (gone, files) = delete(&db, note).await.unwrap();
243 assert_eq!(gone.get_title().as_str(), "a");
244 let mut keys: Vec<_> = files
245 .iter()
246 .map(|file| file.get_id().key().to_string())
247 .collect();
248 keys.sort();
249 let mut want = vec![
250 early.get_id().key().to_string(),
251 late.get_id().key().to_string(),
252 ];
253 want.sort();
254 assert_eq!(keys, want);
255 assert!(
256 crate::db::course_note_file::list_for(&db, gone.get_id(), None, 0)
257 .await
258 .unwrap()
259 .0
260 .is_empty()
261 );
262 }
263}