]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/activity.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / db_schema / src / impls / activity.rs
1 use crate::{
2   newtypes::DbUrl,
3   schema::activity::dsl::*,
4   source::activity::*,
5   traits::Crud,
6   utils::{get_conn, DbPool},
7 };
8 use diesel::{
9   dsl::*,
10   result::{DatabaseErrorKind, Error},
11   ExpressionMethods,
12   QueryDsl,
13 };
14 use diesel_async::RunQueryDsl;
15 use serde_json::Value;
16
17 #[async_trait]
18 impl Crud for Activity {
19   type InsertForm = ActivityInsertForm;
20   type UpdateForm = ActivityUpdateForm;
21   type IdType = i32;
22   async fn read(pool: &DbPool, activity_id: i32) -> Result<Self, Error> {
23     let conn = &mut get_conn(pool).await?;
24     activity.find(activity_id).first::<Self>(conn).await
25   }
26
27   async fn create(pool: &DbPool, new_activity: &Self::InsertForm) -> Result<Self, Error> {
28     let conn = &mut get_conn(pool).await?;
29     insert_into(activity)
30       .values(new_activity)
31       .get_result::<Self>(conn)
32       .await
33   }
34
35   async fn update(
36     pool: &DbPool,
37     activity_id: i32,
38     new_activity: &Self::UpdateForm,
39   ) -> Result<Self, Error> {
40     let conn = &mut get_conn(pool).await?;
41     diesel::update(activity.find(activity_id))
42       .set(new_activity)
43       .get_result::<Self>(conn)
44       .await
45   }
46   async fn delete(pool: &DbPool, activity_id: i32) -> Result<usize, Error> {
47     let conn = &mut get_conn(pool).await?;
48     diesel::delete(activity.find(activity_id))
49       .execute(conn)
50       .await
51   }
52 }
53
54 impl Activity {
55   /// Returns true if the insert was successful
56   // TODO this should probably just be changed to an upsert on_conflict, rather than an error
57   pub async fn insert(
58     pool: &DbPool,
59     ap_id_: DbUrl,
60     data_: Value,
61     local_: bool,
62     sensitive_: Option<bool>,
63   ) -> Result<bool, Error> {
64     let activity_form = ActivityInsertForm {
65       ap_id: ap_id_,
66       data: data_,
67       local: Some(local_),
68       sensitive: sensitive_,
69       updated: None,
70     };
71     match Activity::create(pool, &activity_form).await {
72       Ok(_) => Ok(true),
73       Err(e) => {
74         if let Error::DatabaseError(DatabaseErrorKind::UniqueViolation, _) = e {
75           return Ok(false);
76         }
77         Err(e)
78       }
79     }
80   }
81
82   pub async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result<Activity, Error> {
83     let conn = &mut get_conn(pool).await?;
84     activity
85       .filter(ap_id.eq(object_id))
86       .first::<Self>(conn)
87       .await
88   }
89 }
90
91 #[cfg(test)]
92 mod tests {
93   use super::*;
94   use crate::{
95     newtypes::DbUrl,
96     source::{
97       activity::{Activity, ActivityInsertForm},
98       instance::Instance,
99       person::{Person, PersonInsertForm},
100     },
101     utils::build_db_pool_for_tests,
102   };
103   use serde_json::Value;
104   use serial_test::serial;
105   use url::Url;
106
107   #[tokio::test]
108   #[serial]
109   async fn test_crud() {
110     let pool = &build_db_pool_for_tests().await;
111
112     let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
113
114     let creator_form = PersonInsertForm::builder()
115       .name("activity_creator_ pm".into())
116       .public_key("pubkey".to_string())
117       .instance_id(inserted_instance.id)
118       .build();
119
120     let inserted_creator = Person::create(pool, &creator_form).await.unwrap();
121
122     let ap_id_: DbUrl = Url::parse(
123       "https://enterprise.lemmy.ml/activities/delete/f1b5d57c-80f8-4e03-a615-688d552e946c",
124     )
125     .unwrap()
126     .into();
127     let test_json: Value = serde_json::from_str(
128       r#"{
129     "@context": "https://www.w3.org/ns/activitystreams",
130     "id": "https://enterprise.lemmy.ml/activities/delete/f1b5d57c-80f8-4e03-a615-688d552e946c",
131     "type": "Delete",
132     "actor": "https://enterprise.lemmy.ml/u/riker",
133     "to": "https://www.w3.org/ns/activitystreams#Public",
134     "cc": [
135         "https://enterprise.lemmy.ml/c/main/"
136     ],
137     "object": "https://enterprise.lemmy.ml/post/32"
138     }"#,
139     )
140     .unwrap();
141     let activity_form = ActivityInsertForm {
142       ap_id: ap_id_.clone(),
143       data: test_json.to_owned(),
144       local: Some(true),
145       sensitive: Some(false),
146       updated: None,
147     };
148
149     let inserted_activity = Activity::create(pool, &activity_form).await.unwrap();
150
151     let expected_activity = Activity {
152       ap_id: ap_id_.clone(),
153       id: inserted_activity.id,
154       data: test_json,
155       local: true,
156       sensitive: Some(false),
157       published: inserted_activity.published,
158       updated: None,
159     };
160
161     let read_activity = Activity::read(pool, inserted_activity.id).await.unwrap();
162     let read_activity_by_apub_id = Activity::read_from_apub_id(pool, &ap_id_).await.unwrap();
163     Person::delete(pool, inserted_creator.id).await.unwrap();
164     Activity::delete(pool, inserted_activity.id).await.unwrap();
165
166     assert_eq!(expected_activity, read_activity);
167     assert_eq!(expected_activity, read_activity_by_apub_id);
168     assert_eq!(expected_activity, inserted_activity);
169   }
170 }