1 use crate::{newtypes::DbUrl, CommentSortType, SortType};
2 use activitypub_federation::{core::object_id::ObjectId, traits::ApubObject};
3 use chrono::NaiveDateTime;
7 result::Error::QueryBuilderError,
8 serialize::{Output, ToSql},
13 use lemmy_utils::error::LemmyError;
14 use once_cell::sync::Lazy;
16 use std::{env, env::VarError, io::Write};
19 const FETCH_LIMIT_DEFAULT: i64 = 10;
20 pub const FETCH_LIMIT_MAX: i64 = 50;
22 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
24 pub fn get_database_url_from_env() -> Result<String, VarError> {
25 env::var("LEMMY_DATABASE_URL")
28 pub fn fuzzy_search(q: &str) -> String {
29 let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
30 format!("%{}%", replaced)
33 pub fn limit_and_offset(
36 ) -> Result<(i64, i64), diesel::result::Error> {
37 let page = match page {
40 return Err(QueryBuilderError("Page is < 1".into()));
47 let limit = match limit {
49 if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
50 return Err(QueryBuilderError(
51 format!("Fetch limit is > {}", FETCH_LIMIT_MAX).into(),
57 None => FETCH_LIMIT_DEFAULT,
59 let offset = limit * (page - 1);
63 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
64 let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
65 let offset = limit * (page.unwrap_or(1) - 1);
69 pub fn is_email_regex(test: &str) -> bool {
70 EMAIL_REGEX.is_match(test)
73 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
75 // An empty string is an erase
77 if !unwrapped.eq("") {
78 Some(Some(unwrapped.to_owned()))
87 pub fn diesel_option_overwrite_to_url(
89 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
90 match opt.as_ref().map(|s| s.as_str()) {
91 // An empty string is an erase
92 Some("") => Ok(Some(None)),
93 Some(str_url) => match Url::parse(str_url) {
94 Ok(url) => Ok(Some(Some(url.into()))),
95 Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
103 pub fn establish_unpooled_connection() -> PgConnection {
104 let db_url = match get_database_url_from_env() {
107 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
112 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
113 embedded_migrations::run(&conn).expect("load migrations");
117 pub fn naive_now() -> NaiveDateTime {
118 chrono::prelude::Utc::now().naive_utc()
121 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
123 SortType::Active | SortType::Hot => CommentSortType::Hot,
124 SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
125 SortType::Old => CommentSortType::Old,
130 | SortType::TopMonth => CommentSortType::Top,
134 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
135 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
136 .expect("compile email regex")
140 use diesel::sql_types::*;
143 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
146 sql_function!(fn lower(x: Text) -> Text);
149 impl<DB: Backend> ToSql<Text, DB> for DbUrl
151 String: ToSql<Text, DB>,
153 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> diesel::serialize::Result {
154 self.0.to_string().to_sql(out)
158 impl<DB: Backend> FromSql<Text, DB> for DbUrl
160 String: FromSql<Text, DB>,
162 fn from_sql(bytes: Option<&DB::RawValue>) -> diesel::deserialize::Result<Self> {
163 let str = String::from_sql(bytes)?;
164 Ok(DbUrl(Url::parse(&str)?))
168 impl<Kind> From<ObjectId<Kind>> for DbUrl
170 Kind: ApubObject + Send + 'static,
171 for<'de2> <Kind as ApubObject>::ApubType: serde::Deserialize<'de2>,
173 fn from(id: ObjectId<Kind>) -> Self {
180 use super::{fuzzy_search, *};
181 use crate::utils::is_email_regex;
184 fn test_fuzzy_search() {
185 let test = "This %is% _a_ fuzzy search";
188 "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
194 assert!(is_email_regex("gush@gmail.com"));
195 assert!(!is_email_regex("nada_neutho"));
199 fn test_diesel_option_overwrite() {
200 assert_eq!(diesel_option_overwrite(&None), None);
201 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
203 diesel_option_overwrite(&Some("test".to_string())),
204 Some(Some("test".to_string()))
209 fn test_diesel_option_overwrite_to_url() {
210 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
212 diesel_option_overwrite_to_url(&Some("".to_string())),
216 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
219 let example_url = "https://example.com";
221 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
222 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()