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

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