]> Untitled Git - lemmy.git/blob - crates/db_schema/src/utils.rs
798786b06d1cd829b6199f294debba952dcbdd63
[lemmy.git] / crates / db_schema / src / utils.rs
1 use crate::{diesel_migrations::MigrationHarness, newtypes::DbUrl, CommentSortType, SortType};
2 use activitypub_federation::{core::object_id::ObjectId, traits::ApubObject};
3 use chrono::NaiveDateTime;
4 use diesel::{
5   backend::Backend,
6   deserialize::FromSql,
7   pg::Pg,
8   result::Error::QueryBuilderError,
9   serialize::{Output, ToSql},
10   sql_types::Text,
11   Connection,
12   PgConnection,
13 };
14 use diesel_migrations::EmbeddedMigrations;
15 use lemmy_utils::error::LemmyError;
16 use once_cell::sync::Lazy;
17 use regex::Regex;
18 use std::{env, env::VarError};
19 use url::Url;
20
21 const FETCH_LIMIT_DEFAULT: i64 = 10;
22 pub const FETCH_LIMIT_MAX: i64 = 50;
23
24 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
25
26 pub fn get_database_url_from_env() -> Result<String, VarError> {
27   env::var("LEMMY_DATABASE_URL")
28 }
29
30 pub fn fuzzy_search(q: &str) -> String {
31   let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
32   format!("%{}%", replaced)
33 }
34
35 pub fn limit_and_offset(
36   page: Option<i64>,
37   limit: Option<i64>,
38 ) -> Result<(i64, i64), diesel::result::Error> {
39   let page = match page {
40     Some(page) => {
41       if page < 1 {
42         return Err(QueryBuilderError("Page is < 1".into()));
43       } else {
44         page
45       }
46     }
47     None => 1,
48   };
49   let limit = match limit {
50     Some(limit) => {
51       if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
52         return Err(QueryBuilderError(
53           format!("Fetch limit is > {}", FETCH_LIMIT_MAX).into(),
54         ));
55       } else {
56         limit
57       }
58     }
59     None => FETCH_LIMIT_DEFAULT,
60   };
61   let offset = limit * (page - 1);
62   Ok((limit, offset))
63 }
64
65 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
66   let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
67   let offset = limit * (page.unwrap_or(1) - 1);
68   (limit, offset)
69 }
70
71 pub fn is_email_regex(test: &str) -> bool {
72   EMAIL_REGEX.is_match(test)
73 }
74
75 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
76   match opt {
77     // An empty string is an erase
78     Some(unwrapped) => {
79       if !unwrapped.eq("") {
80         Some(Some(unwrapped.to_owned()))
81       } else {
82         Some(None)
83       }
84     }
85     None => None,
86   }
87 }
88
89 pub fn diesel_option_overwrite_to_url(
90   opt: &Option<String>,
91 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
92   match opt.as_ref().map(|s| s.as_str()) {
93     // An empty string is an erase
94     Some("") => Ok(Some(None)),
95     Some(str_url) => match Url::parse(str_url) {
96       Ok(url) => Ok(Some(Some(url.into()))),
97       Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
98     },
99     None => Ok(None),
100   }
101 }
102
103 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
104
105 pub fn establish_unpooled_connection() -> PgConnection {
106   let db_url = match get_database_url_from_env() {
107     Ok(url) => url,
108     Err(e) => panic!(
109       "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
110       e
111     ),
112   };
113   let mut conn =
114     PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
115   let _ = &mut conn
116     .run_pending_migrations(MIGRATIONS)
117     .unwrap_or_else(|_| panic!("Couldn't run DB Migrations"));
118   conn
119 }
120
121 pub fn naive_now() -> NaiveDateTime {
122   chrono::prelude::Utc::now().naive_utc()
123 }
124
125 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
126   match sort {
127     SortType::Active | SortType::Hot => CommentSortType::Hot,
128     SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
129     SortType::Old => CommentSortType::Old,
130     SortType::TopDay
131     | SortType::TopAll
132     | SortType::TopWeek
133     | SortType::TopYear
134     | SortType::TopMonth => CommentSortType::Top,
135   }
136 }
137
138 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
139   Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
140     .expect("compile email regex")
141 });
142
143 pub mod functions {
144   use diesel::sql_types::*;
145
146   sql_function! {
147     fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
148   }
149
150   sql_function!(fn lower(x: Text) -> Text);
151 }
152
153 impl ToSql<Text, Pg> for DbUrl {
154   fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
155     <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
156   }
157 }
158
159 impl<DB: Backend> FromSql<Text, DB> for DbUrl
160 where
161   String: FromSql<Text, DB>,
162 {
163   fn from_sql(value: diesel::backend::RawValue<'_, DB>) -> diesel::deserialize::Result<Self> {
164     let str = String::from_sql(value)?;
165     Ok(DbUrl(Url::parse(&str)?))
166   }
167 }
168
169 impl<Kind> From<ObjectId<Kind>> for DbUrl
170 where
171   Kind: ApubObject + Send + 'static,
172   for<'de2> <Kind as ApubObject>::ApubType: serde::Deserialize<'de2>,
173 {
174   fn from(id: ObjectId<Kind>) -> Self {
175     DbUrl(id.into())
176   }
177 }
178
179 #[cfg(test)]
180 mod tests {
181   use super::{fuzzy_search, *};
182   use crate::utils::is_email_regex;
183
184   #[test]
185   fn test_fuzzy_search() {
186     let test = "This %is% _a_ fuzzy search";
187     assert_eq!(
188       fuzzy_search(test),
189       "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
190     );
191   }
192
193   #[test]
194   fn test_email() {
195     assert!(is_email_regex("gush@gmail.com"));
196     assert!(!is_email_regex("nada_neutho"));
197   }
198
199   #[test]
200   fn test_diesel_option_overwrite() {
201     assert_eq!(diesel_option_overwrite(&None), None);
202     assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
203     assert_eq!(
204       diesel_option_overwrite(&Some("test".to_string())),
205       Some(Some("test".to_string()))
206     );
207   }
208
209   #[test]
210   fn test_diesel_option_overwrite_to_url() {
211     assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
212     assert!(matches!(
213       diesel_option_overwrite_to_url(&Some("".to_string())),
214       Ok(Some(None))
215     ));
216     assert!(matches!(
217       diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
218       Err(_)
219     ));
220     let example_url = "https://example.com";
221     assert!(matches!(
222       diesel_option_overwrite_to_url(&Some(example_url.to_string())),
223       Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()
224     ));
225   }
226 }