1 use crate::newtypes::DbUrl;
2 use chrono::NaiveDateTime;
6 serialize::{Output, ToSql},
11 use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject};
12 use lemmy_utils::LemmyError;
13 use once_cell::sync::Lazy;
15 use serde::{Deserialize, Serialize};
16 use std::{env, env::VarError, io::Write};
19 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
21 pub fn get_database_url_from_env() -> Result<String, VarError> {
22 env::var("LEMMY_DATABASE_URL")
25 #[derive(EnumString, Display, Debug, Serialize, Deserialize, Clone, Copy)]
39 #[derive(EnumString, Display, Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
40 pub enum ListingType {
47 #[derive(EnumString, Display, Debug, Serialize, Deserialize, Clone, Copy)]
57 pub fn from_opt_str_to_opt_enum<T: std::str::FromStr>(opt: &Option<String>) -> Option<T> {
58 opt.as_ref().and_then(|t| T::from_str(t).ok())
61 pub fn fuzzy_search(q: &str) -> String {
62 let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
63 format!("%{}%", replaced)
66 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
67 let page = page.unwrap_or(1);
68 let limit = limit.unwrap_or(10);
69 let offset = limit * (page - 1);
73 pub fn is_email_regex(test: &str) -> bool {
74 EMAIL_REGEX.is_match(test)
77 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
79 // An empty string is an erase
81 if !unwrapped.eq("") {
82 Some(Some(unwrapped.to_owned()))
91 pub fn diesel_option_overwrite_to_url(
93 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
94 match opt.as_ref().map(|s| s.as_str()) {
95 // An empty string is an erase
96 Some("") => Ok(Some(None)),
97 Some(str_url) => match Url::parse(str_url) {
98 Ok(url) => Ok(Some(Some(url.into()))),
99 Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
107 pub fn establish_unpooled_connection() -> PgConnection {
108 let db_url = match get_database_url_from_env() {
111 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
116 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
117 embedded_migrations::run(&conn).expect("load migrations");
121 pub fn naive_now() -> NaiveDateTime {
122 chrono::prelude::Utc::now().naive_utc()
125 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
126 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
127 .expect("compile email regex")
131 use diesel::sql_types::*;
134 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
137 sql_function!(fn lower(x: Text) -> Text);
140 impl<DB: Backend> ToSql<Text, DB> for DbUrl
142 String: ToSql<Text, DB>,
144 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> diesel::serialize::Result {
145 self.0.to_string().to_sql(out)
149 impl<DB: Backend> FromSql<Text, DB> for DbUrl
151 String: FromSql<Text, DB>,
153 fn from_sql(bytes: Option<&DB::RawValue>) -> diesel::deserialize::Result<Self> {
154 let str = String::from_sql(bytes)?;
155 Ok(DbUrl(Url::parse(&str)?))
159 impl<Kind> From<ObjectId<Kind>> for DbUrl
161 Kind: ApubObject + Send + 'static,
162 for<'de2> <Kind as ApubObject>::ApubType: serde::Deserialize<'de2>,
164 fn from(id: ObjectId<Kind>) -> Self {
171 use super::{fuzzy_search, *};
172 use crate::utils::is_email_regex;
175 fn test_fuzzy_search() {
176 let test = "This %is% _a_ fuzzy search";
179 "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
185 assert!(is_email_regex("gush@gmail.com"));
186 assert!(!is_email_regex("nada_neutho"));
190 fn test_diesel_option_overwrite() {
191 assert_eq!(diesel_option_overwrite(&None), None);
192 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
194 diesel_option_overwrite(&Some("test".to_string())),
195 Some(Some("test".to_string()))
200 fn test_diesel_option_overwrite_to_url() {
201 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
203 diesel_option_overwrite_to_url(&Some("".to_string())),
207 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
210 let example_url = "https://example.com";
212 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
213 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()