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