]> Untitled Git - lemmy.git/blob - crates/db_schema/src/utils.rs
c05cd565d0dc487c61967f17376d54624959427c
[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 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::TopDay
200     | SortType::TopAll
201     | SortType::TopWeek
202     | SortType::TopYear
203     | SortType::TopMonth => CommentSortType::Top,
204   }
205 }
206
207 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
208   Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
209     .expect("compile email regex")
210 });
211
212 pub mod functions {
213   use diesel::sql_types::{BigInt, Text, Timestamp};
214
215   sql_function! {
216     fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
217   }
218
219   sql_function!(fn lower(x: Text) -> Text);
220 }
221
222 impl ToSql<Text, Pg> for DbUrl {
223   fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
224     <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
225   }
226 }
227
228 impl<DB: Backend> FromSql<Text, DB> for DbUrl
229 where
230   String: FromSql<Text, DB>,
231 {
232   fn from_sql(value: diesel::backend::RawValue<'_, DB>) -> diesel::deserialize::Result<Self> {
233     let str = String::from_sql(value)?;
234     Ok(DbUrl(Box::new(Url::parse(&str)?)))
235   }
236 }
237
238 impl<Kind> From<ObjectId<Kind>> for DbUrl
239 where
240   Kind: ApubObject + Send + 'static,
241   for<'de2> <Kind as ApubObject>::ApubType: serde::Deserialize<'de2>,
242 {
243   fn from(id: ObjectId<Kind>) -> Self {
244     DbUrl(Box::new(id.into()))
245   }
246 }
247
248 #[cfg(test)]
249 mod tests {
250   use super::{fuzzy_search, *};
251   use crate::utils::is_email_regex;
252
253   #[test]
254   fn test_fuzzy_search() {
255     let test = "This %is% _a_ fuzzy search";
256     assert_eq!(
257       fuzzy_search(test),
258       "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
259     );
260   }
261
262   #[test]
263   fn test_email() {
264     assert!(is_email_regex("gush@gmail.com"));
265     assert!(!is_email_regex("nada_neutho"));
266   }
267
268   #[test]
269   fn test_diesel_option_overwrite() {
270     assert_eq!(diesel_option_overwrite(&None), None);
271     assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
272     assert_eq!(
273       diesel_option_overwrite(&Some("test".to_string())),
274       Some(Some("test".to_string()))
275     );
276   }
277
278   #[test]
279   fn test_diesel_option_overwrite_to_url() {
280     assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
281     assert!(matches!(
282       diesel_option_overwrite_to_url(&Some(String::new())),
283       Ok(Some(None))
284     ));
285     assert!(matches!(
286       diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
287       Err(_)
288     ));
289     let example_url = "https://example.com";
290     assert!(matches!(
291       diesel_option_overwrite_to_url(&Some(example_url.to_string())),
292       Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()
293     ));
294   }
295 }