]> Untitled Git - lemmy.git/blob - crates/db_queries/src/lib.rs
Use URL type in most outstanding struct fields (#1468)
[lemmy.git] / crates / db_queries / src / lib.rs
1 #[macro_use]
2 extern crate diesel;
3 #[macro_use]
4 extern crate strum_macros;
5 #[macro_use]
6 extern crate lazy_static;
7 // this is used in tests
8 #[allow(unused_imports)]
9 #[macro_use]
10 extern crate diesel_migrations;
11
12 #[cfg(test)]
13 extern crate serial_test;
14
15 use diesel::{result::Error, *};
16 use lemmy_db_schema::DbUrl;
17 use lemmy_utils::ApiError;
18 use regex::Regex;
19 use serde::{Deserialize, Serialize};
20 use std::{env, env::VarError};
21 use url::Url;
22
23 pub mod aggregates;
24 pub mod source;
25
26 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
27
28 pub trait Crud<T> {
29   fn create(conn: &PgConnection, form: &T) -> Result<Self, Error>
30   where
31     Self: Sized;
32   fn read(conn: &PgConnection, id: i32) -> Result<Self, Error>
33   where
34     Self: Sized;
35   fn update(conn: &PgConnection, id: i32, form: &T) -> Result<Self, Error>
36   where
37     Self: Sized;
38   fn delete(_conn: &PgConnection, _id: i32) -> Result<usize, Error>
39   where
40     Self: Sized,
41   {
42     unimplemented!()
43   }
44 }
45
46 pub trait Followable<T> {
47   fn follow(conn: &PgConnection, form: &T) -> Result<Self, Error>
48   where
49     Self: Sized;
50   fn follow_accepted(conn: &PgConnection, community_id: i32, user_id: i32) -> Result<Self, Error>
51   where
52     Self: Sized;
53   fn unfollow(conn: &PgConnection, form: &T) -> Result<usize, Error>
54   where
55     Self: Sized;
56   fn has_local_followers(conn: &PgConnection, community_id: i32) -> Result<bool, Error>;
57 }
58
59 pub trait Joinable<T> {
60   fn join(conn: &PgConnection, form: &T) -> Result<Self, Error>
61   where
62     Self: Sized;
63   fn leave(conn: &PgConnection, form: &T) -> Result<usize, Error>
64   where
65     Self: Sized;
66 }
67
68 pub trait Likeable<T> {
69   fn like(conn: &PgConnection, form: &T) -> Result<Self, Error>
70   where
71     Self: Sized;
72   fn remove(conn: &PgConnection, user_id: i32, item_id: i32) -> Result<usize, Error>
73   where
74     Self: Sized;
75 }
76
77 pub trait Bannable<T> {
78   fn ban(conn: &PgConnection, form: &T) -> Result<Self, Error>
79   where
80     Self: Sized;
81   fn unban(conn: &PgConnection, form: &T) -> Result<usize, Error>
82   where
83     Self: Sized;
84 }
85
86 pub trait Saveable<T> {
87   fn save(conn: &PgConnection, form: &T) -> Result<Self, Error>
88   where
89     Self: Sized;
90   fn unsave(conn: &PgConnection, form: &T) -> Result<usize, Error>
91   where
92     Self: Sized;
93 }
94
95 pub trait Readable<T> {
96   fn mark_as_read(conn: &PgConnection, form: &T) -> Result<Self, Error>
97   where
98     Self: Sized;
99   fn mark_as_unread(conn: &PgConnection, form: &T) -> Result<usize, Error>
100   where
101     Self: Sized;
102 }
103
104 pub trait Reportable<T> {
105   fn report(conn: &PgConnection, form: &T) -> Result<Self, Error>
106   where
107     Self: Sized;
108   fn resolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error>
109   where
110     Self: Sized;
111   fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error>
112   where
113     Self: Sized;
114 }
115
116 pub trait ApubObject<T> {
117   fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error>
118   where
119     Self: Sized;
120   fn upsert(conn: &PgConnection, user_form: &T) -> Result<Self, Error>
121   where
122     Self: Sized;
123 }
124
125 pub trait MaybeOptional<T> {
126   fn get_optional(self) -> Option<T>;
127 }
128
129 impl<T> MaybeOptional<T> for T {
130   fn get_optional(self) -> Option<T> {
131     Some(self)
132   }
133 }
134
135 impl<T> MaybeOptional<T> for Option<T> {
136   fn get_optional(self) -> Option<T> {
137     self
138   }
139 }
140
141 pub trait ToSafe {
142   type SafeColumns;
143   fn safe_columns_tuple() -> Self::SafeColumns;
144 }
145
146 pub trait ToSafeSettings {
147   type SafeSettingsColumns;
148   fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
149 }
150
151 pub trait ViewToVec {
152   type DbTuple;
153   fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
154   where
155     Self: Sized;
156 }
157
158 pub fn get_database_url_from_env() -> Result<String, VarError> {
159   env::var("LEMMY_DATABASE_URL")
160 }
161
162 #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]
163 pub enum SortType {
164   Active,
165   Hot,
166   New,
167   TopDay,
168   TopWeek,
169   TopMonth,
170   TopYear,
171   TopAll,
172   MostComments,
173   NewComments,
174 }
175
176 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone)]
177 pub enum ListingType {
178   All,
179   Local,
180   Subscribed,
181   Community,
182 }
183
184 #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]
185 pub enum SearchType {
186   All,
187   Comments,
188   Posts,
189   Communities,
190   Users,
191   Url,
192 }
193
194 pub fn fuzzy_search(q: &str) -> String {
195   let replaced = q.replace(" ", "%");
196   format!("%{}%", replaced)
197 }
198
199 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
200   let page = page.unwrap_or(1);
201   let limit = limit.unwrap_or(10);
202   let offset = limit * (page - 1);
203   (limit, offset)
204 }
205
206 pub fn is_email_regex(test: &str) -> bool {
207   EMAIL_REGEX.is_match(test)
208 }
209
210 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
211   match opt {
212     // An empty string is an erase
213     Some(unwrapped) => {
214       if !unwrapped.eq("") {
215         Some(Some(unwrapped.to_owned()))
216       } else {
217         Some(None)
218       }
219     }
220     None => None,
221   }
222 }
223
224 pub fn diesel_option_overwrite_to_url(
225   opt: &Option<String>,
226 ) -> Result<Option<Option<DbUrl>>, ApiError> {
227   match opt.as_ref().map(|s| s.as_str()) {
228     // An empty string is an erase
229     Some("") => Ok(Some(None)),
230     Some(str_url) => match Url::parse(str_url) {
231       Ok(url) => Ok(Some(Some(url.into()))),
232       Err(_) => Err(ApiError::err("invalid_url")),
233     },
234     None => Ok(None),
235   }
236 }
237
238 embed_migrations!();
239
240 pub fn establish_unpooled_connection() -> PgConnection {
241   let db_url = match get_database_url_from_env() {
242     Ok(url) => url,
243     Err(e) => panic!(
244       "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
245       e
246     ),
247   };
248   let conn =
249     PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
250   embedded_migrations::run(&conn).unwrap();
251   conn
252 }
253
254 lazy_static! {
255   static ref EMAIL_REGEX: Regex =
256     Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
257 }
258
259 pub mod functions {
260   use diesel::sql_types::*;
261
262   sql_function! {
263     fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
264   }
265 }
266
267 #[cfg(test)]
268 mod tests {
269   use super::{fuzzy_search, *};
270   use crate::is_email_regex;
271
272   #[test]
273   fn test_fuzzy_search() {
274     let test = "This is a fuzzy search";
275     assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
276   }
277
278   #[test]
279   fn test_email() {
280     assert!(is_email_regex("gush@gmail.com"));
281     assert!(!is_email_regex("nada_neutho"));
282   }
283
284   #[test]
285   fn test_diesel_option_overwrite() {
286     assert_eq!(diesel_option_overwrite(&None), None);
287     assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
288     assert_eq!(
289       diesel_option_overwrite(&Some("test".to_string())),
290       Some(Some("test".to_string()))
291     );
292   }
293
294   #[test]
295   fn test_diesel_option_overwrite_to_url() {
296     assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
297     assert!(matches!(
298       diesel_option_overwrite_to_url(&Some("".to_string())),
299       Ok(Some(None))
300     ));
301     assert!(matches!(
302       diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
303       Err(_)
304     ));
305     let example_url = "https://example.com";
306     assert!(matches!(
307       diesel_option_overwrite_to_url(&Some(example_url.to_string())),
308       Ok(Some(Some(url))) if url == Url::parse(&example_url).unwrap().into()
309     ));
310   }
311 }