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