1use chrono::Utc;
2
3use super::*;
4use crate::db::tables::shared_thread;
5
6impl Database {
7 pub async fn upsert_shared_thread(
8 &self,
9 id: SharedThreadId,
10 user_id: UserId,
11 title: &str,
12 data: Vec<u8>,
13 ) -> Result<()> {
14 let title = title.to_string();
15 self.transaction(|tx| {
16 let title = title.clone();
17 let data = data.clone();
18 async move {
19 let now = Utc::now().naive_utc();
20
21 let existing = shared_thread::Entity::find_by_id(id).one(&*tx).await?;
22
23 match existing {
24 Some(existing) => {
25 if existing.user_id != user_id {
26 Err(anyhow!("Cannot update shared thread owned by another user"))?;
27 }
28
29 let mut active: shared_thread::ActiveModel = existing.into();
30 active.title = ActiveValue::Set(title);
31 active.data = ActiveValue::Set(data);
32 active.updated_at = ActiveValue::Set(now);
33 active.update(&*tx).await?;
34 }
35 None => {
36 shared_thread::ActiveModel {
37 id: ActiveValue::Set(id),
38 user_id: ActiveValue::Set(user_id),
39 title: ActiveValue::Set(title),
40 data: ActiveValue::Set(data),
41 created_at: ActiveValue::Set(now),
42 updated_at: ActiveValue::Set(now),
43 }
44 .insert(&*tx)
45 .await?;
46 }
47 }
48
49 Ok(())
50 }
51 })
52 .await
53 }
54
55 pub async fn get_shared_thread(
56 &self,
57 share_id: SharedThreadId,
58 ) -> Result<Option<(shared_thread::Model, String)>> {
59 self.transaction(|tx| async move {
60 let Some(thread) = shared_thread::Entity::find_by_id(share_id)
61 .one(&*tx)
62 .await?
63 else {
64 return Ok(None);
65 };
66
67 let user = user::Entity::find_by_id(thread.user_id).one(&*tx).await?;
68
69 let username = user
70 .map(|u| u.github_login)
71 .unwrap_or_else(|| "Unknown".to_string());
72
73 Ok(Some((thread, username)))
74 })
75 .await
76 }
77}