forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

note.rs216 lines, 7.6 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,
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 // Links before rows: the outputs' citation links are their children
112 // (`ON DELETE NO ACTION`).
113 sqlx::query!(
114 "DELETE FROM rag_output_source WHERE output IN
115 (SELECT id FROM rag_output WHERE course_note = $1)",
116 note.id.uuid()
117 )
118 .execute(&mut *conn)
119 .await?;
120 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())
121 .execute(&mut *conn)
122 .await?;
123 let files = sqlx::query_as!(
124 NoteFile,
125 r#"DELETE FROM note_file WHERE note = $1
126 RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName",
127 content_type AS "content_type: FileContentType", size"#,
128 note.id.uuid()
129 )
130 .fetch_all(&mut *conn)
131 .await?;
132 let gone = sqlx::query_as!(
133 Note,
134 r#"DELETE FROM note WHERE id = $1 RETURNING id AS "id: NoteId", app_user AS "user: UserId",
135 title AS "title: NoteTitle", content AS "content: NoteContent""#,
136 note.id.uuid()
137 )
138 .fetch_optional(&mut *conn)
139 .await?;
140 let note = gone.ok_or(AppError::NotFound)?;
141 Ok((note, files))
142 })
143 .await
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149 use crate::domain::note_file::{FileContentType, FileName};
150
151 /// The blobs the handler unlinks are exactly the rows this transaction
152 /// removed — including one uploaded after any pre-read snapshot would have
153 /// been taken, which is the row whose blob used to leak.
154 #[tokio::test]
155 async fn delete_returns_the_attachment_rows_it_removed() {
156 let (db, _leases) = crate::database::init_test_db().await;
157 let owner = crate::db::class_member::tests::fixture_user(&db, "note-owner").await;
158 let note = create(
159 &db,
160 &owner,
161 NoteTitle::try_new("a").unwrap(),
162 NoteContent::try_new("body").unwrap(),
163 )
164 .await
165 .unwrap();
166 // What a handler snapshot would have seen...
167 let early = crate::db::note_file::insert(
168 &db,
169 NoteFile::new(
170 note.get_id(),
171 FileName::try_new("early.pdf").unwrap(),
172 FileContentType::try_new("application/pdf").unwrap(),
173 3,
174 ),
175 )
176 .await
177 .unwrap();
178 let (snapshot, _) = crate::db::note_file::list_for(&db, note.get_id(), None, 0)
179 .await
180 .unwrap();
181 assert_eq!(snapshot.len(), 1);
182 // ...and the upload that races in after it.
183 let late = crate::db::note_file::insert(
184 &db,
185 NoteFile::new(
186 note.get_id(),
187 FileName::try_new("late.pdf").unwrap(),
188 FileContentType::try_new("application/pdf").unwrap(),
189 3,
190 ),
191 )
192 .await
193 .unwrap();
194
195 let (gone, files) = delete(&db, note).await.unwrap();
196 assert_eq!(gone.get_title().as_str(), "a");
197 let mut keys: Vec<_> = files
198 .iter()
199 .map(|file| file.get_id().key().to_string())
200 .collect();
201 keys.sort();
202 let mut want = vec![
203 early.get_id().key().to_string(),
204 late.get_id().key().to_string(),
205 ];
206 want.sort();
207 assert_eq!(keys, want);
208 assert!(
209 crate::db::note_file::list_for(&db, gone.get_id(), None, 0)
210 .await
211 .unwrap()
212 .0
213 .is_empty()
214 );
215 }
216}