]> Untitled Git - lemmy.git/blob - crates/db_schema/src/utils.rs
f6accb60c29f483a24f5f58a2e49ae726a390729
[lemmy.git] / crates / db_schema / src / utils.rs
1 use crate::{
2   diesel::Connection,
3   diesel_migrations::MigrationHarness,
4   newtypes::DbUrl,
5   CommentSortType,
6   SortType,
7 };
8 use activitypub_federation::{core::object_id::ObjectId, traits::ApubObject};
9 use bb8::PooledConnection;
10 use chrono::NaiveDateTime;
11 use diesel::{
12   backend::Backend,
13   deserialize::FromSql,
14   pg::Pg,
15   result::{Error as DieselError, Error::QueryBuilderError},
16   serialize::{Output, ToSql},
17   sql_types::Text,
18   PgConnection,
19 };
20 use diesel_async::{
21   pg::AsyncPgConnection,
22   pooled_connection::{bb8::Pool, AsyncDieselConnectionManager},
23 };
24 use diesel_migrations::EmbeddedMigrations;
25 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
26 use once_cell::sync::Lazy;
27 use regex::Regex;
28 use std::{env, env::VarError};
29 use url::Url;
30
31 const FETCH_LIMIT_DEFAULT: i64 = 10;
32 pub const FETCH_LIMIT_MAX: i64 = 50;
33
34 pub type DbPool = Pool<AsyncPgConnection>;
35
36 pub async fn get_conn(
37   pool: &DbPool,
38 ) -> Result<PooledConnection<AsyncDieselConnectionManager<AsyncPgConnection>>, DieselError> {
39   pool.get().await.map_err(|e| QueryBuilderError(e.into()))
40 }
41
42 pub fn get_database_url_from_env() -> Result<String, VarError> {
43   env::var("LEMMY_DATABASE_URL")
44 }
45
46 pub fn fuzzy_search(q: &str) -> String {
47   let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
48   format!("%{}%", replaced)
49 }
50
51 pub fn limit_and_offset(
52   page: Option<i64>,
53   limit: Option<i64>,
54 ) -> Result<(i64, i64), diesel::result::Error> {
55   let page = match page {
56     Some(page) => {
57       if page < 1 {
58         return Err(QueryBuilderError("Page is < 1".into()));
59       } else {
60         page
61       }
62     }
63     None => 1,
64   };
65   let limit = match limit {
66     Some(limit) => {
67       if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
68         return Err(QueryBuilderError(
69           format!("Fetch limit is > {}", FETCH_LIMIT_MAX).into(),
70         ));
71       } else {
72         limit
73       }
74     }
75     None => FETCH_LIMIT_DEFAULT,
76   };
77   let offset = limit * (page - 1);
78   Ok((limit, offset))
79 }
80
81 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
82   let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
83   let offset = limit * (page.unwrap_or(1) - 1);
84   (limit, offset)
85 }
86
87 pub fn is_email_regex(test: &str) -> bool {
88   EMAIL_REGEX.is_match(test)
89 }
90
91 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
92   match opt {
93     // An empty string is an erase
94     Some(unwrapped) => {
95       if !unwrapped.eq("") {
96         Some(Some(unwrapped.clone()))
97       } else {
98         Some(None)
99       }
100     }
101     None => None,
102   }
103 }
104
105 pub fn diesel_option_overwrite_to_url(
106   opt: &Option<String>,
107 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
108   match opt.as_ref().map(std::string::String::as_str) {
109     // An empty string is an erase
110     Some("") => Ok(Some(None)),
111     Some(str_url) => match Url::parse(str_url) {
112       Ok(url) => Ok(Some(Some(url.into()))),
113       Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
114     },
115     None => Ok(None),
116   }
117 }
118
119 pub fn diesel_option_overwrite_to_url_create(
120   opt: &Option<String>,
121 ) -> Result<Option<DbUrl>, LemmyError> {
122   match opt.as_ref().map(std::string::String::as_str) {
123     // An empty string is nothing
124     Some("") => Ok(None),
125     Some(str_url) => match Url::parse(str_url) {
126       Ok(url) => Ok(Some(url.into())),
127       Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
128     },
129     None => Ok(None),
130   }
131 }
132
133 async fn build_db_pool_settings_opt(settings: Option<&Settings>) -> Result<DbPool, LemmyError> {
134   let db_url = get_database_url(settings);
135   let pool_size = settings.map(|s| s.database.pool_size).unwrap_or(5);
136   let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new(&db_url);
137   let pool = Pool::builder()
138     .max_size(pool_size)
139     .min_idle(Some(1))
140     .build(manager)
141     .await?;
142
143   // If there's no settings, that means its a unit test, and migrations need to be run
144   if settings.is_none() {
145     run_migrations(&db_url);
146   }
147
148   Ok(pool)
149 }
150
151 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
152
153 pub fn run_migrations(db_url: &str) {
154   // Needs to be a sync connection
155   let mut conn =
156     PgConnection::establish(db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
157   let _ = &mut conn
158     .run_pending_migrations(MIGRATIONS)
159     .unwrap_or_else(|_| panic!("Couldn't run DB Migrations"));
160 }
161
162 pub async fn build_db_pool(settings: &Settings) -> Result<DbPool, LemmyError> {
163   build_db_pool_settings_opt(Some(settings)).await
164 }
165
166 pub async fn build_db_pool_for_tests() -> DbPool {
167   build_db_pool_settings_opt(None)
168     .await
169     .expect("db pool missing")
170 }
171
172 pub fn get_database_url(settings: Option<&Settings>) -> String {
173   // The env var should override anything in the settings config
174   match get_database_url_from_env() {
175     Ok(url) => url,
176     Err(e) => match settings {
177       Some(settings) => settings.get_database_url(),
178       None => panic!(
179         "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
180         e
181       ),
182     },
183   }
184 }
185
186 pub fn naive_now() -> NaiveDateTime {
187   chrono::prelude::Utc::now().naive_utc()
188 }
189
190 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
191   match sort {
192     SortType::Active | SortType::Hot => CommentSortType::Hot,
193     SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
194     SortType::Old => CommentSortType::Old,
195     SortType::TopDay
196     | SortType::TopAll
197     | SortType::TopWeek
198     | SortType::TopYear
199     | SortType::TopMonth => CommentSortType::Top,
200   }
201 }
202
203 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
204   Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
205     .expect("compile email regex")
206 });
207
208 pub mod functions {
209   use diesel::sql_types::{BigInt, Text, Timestamp};
210
211   sql_function! {
212     fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
213   }
214
215   sql_function!(fn lower(x: Text) -> Text);
216 }
217
218 impl ToSql<Text, Pg> for DbUrl {
219   fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
220     <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
221   }
222 }
223
224 impl<DB: Backend> FromSql<Text, DB> for DbUrl
225 where
226   String: FromSql<Text, DB>,
227 {
228   fn from_sql(value: diesel::backend::RawValue<'_, DB>) -> diesel::deserialize::Result<Self> {
229     let str = String::from_sql(value)?;
230     Ok(DbUrl(Url::parse(&str)?))
231   }
232 }
233
234 impl<Kind> From<ObjectId<Kind>> for DbUrl
235 where
236   Kind: ApubObject + Send + 'static,
237   for<'de2> <Kind as ApubObject>::ApubType: serde::Deserialize<'de2>,
238 {
239   fn from(id: ObjectId<Kind>) -> Self {
240     DbUrl(id.into())
241   }
242 }
243
244 #[cfg(test)]
245 mod tests {
246   use super::{fuzzy_search, *};
247   use crate::utils::is_email_regex;
248
249   #[test]
250   fn test_fuzzy_search() {
251     let test = "This %is% _a_ fuzzy search";
252     assert_eq!(
253       fuzzy_search(test),
254       "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
255     );
256   }
257
258   #[test]
259   fn test_email() {
260     assert!(is_email_regex("gush@gmail.com"));
261     assert!(!is_email_regex("nada_neutho"));
262   }
263
264   #[test]
265   fn test_diesel_option_overwrite() {
266     assert_eq!(diesel_option_overwrite(&None), None);
267     assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
268     assert_eq!(
269       diesel_option_overwrite(&Some("test".to_string())),
270       Some(Some("test".to_string()))
271     );
272   }
273
274   #[test]
275   fn test_diesel_option_overwrite_to_url() {
276     assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
277     assert!(matches!(
278       diesel_option_overwrite_to_url(&Some(String::new())),
279       Ok(Some(None))
280     ));
281     assert!(matches!(
282       diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
283       Err(_)
284     ));
285     let example_url = "https://example.com";
286     assert!(matches!(
287       diesel_option_overwrite_to_url(&Some(example_url.to_string())),
288       Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()
289     ));
290   }
291 }