4 extern crate strum_macros;
6 extern crate lazy_static;
7 // this is used in tests
8 #[allow(unused_imports)]
10 extern crate diesel_migrations;
13 extern crate serial_test;
15 use diesel::{result::Error, *};
16 use lemmy_db_schema::{CommunityId, DbUrl, PersonId};
17 use lemmy_utils::ApiError;
19 use serde::{Deserialize, Serialize};
20 use std::{env, env::VarError};
26 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
28 pub trait Crud<Form, IdType> {
29 fn create(conn: &PgConnection, form: &Form) -> Result<Self, Error>
32 fn read(conn: &PgConnection, id: IdType) -> Result<Self, Error>
35 fn update(conn: &PgConnection, id: IdType, form: &Form) -> Result<Self, Error>
38 fn delete(_conn: &PgConnection, _id: IdType) -> Result<usize, Error>
46 pub trait Followable<Form> {
47 fn follow(conn: &PgConnection, form: &Form) -> Result<Self, Error>
52 community_id: CommunityId,
54 ) -> Result<Self, Error>
57 fn unfollow(conn: &PgConnection, form: &Form) -> Result<usize, Error>
60 fn has_local_followers(conn: &PgConnection, community_id: CommunityId) -> Result<bool, Error>;
63 pub trait Joinable<Form> {
64 fn join(conn: &PgConnection, form: &Form) -> Result<Self, Error>
67 fn leave(conn: &PgConnection, form: &Form) -> Result<usize, Error>
72 pub trait Likeable<Form, IdType> {
73 fn like(conn: &PgConnection, form: &Form) -> Result<Self, Error>
76 fn remove(conn: &PgConnection, person_id: PersonId, item_id: IdType) -> Result<usize, Error>
81 pub trait Bannable<Form> {
82 fn ban(conn: &PgConnection, form: &Form) -> Result<Self, Error>
85 fn unban(conn: &PgConnection, form: &Form) -> Result<usize, Error>
90 pub trait Saveable<Form> {
91 fn save(conn: &PgConnection, form: &Form) -> Result<Self, Error>
94 fn unsave(conn: &PgConnection, form: &Form) -> Result<usize, Error>
99 pub trait Readable<Form> {
100 fn mark_as_read(conn: &PgConnection, form: &Form) -> Result<Self, Error>
103 fn mark_as_unread(conn: &PgConnection, form: &Form) -> Result<usize, Error>
108 pub trait Reportable<Form> {
109 fn report(conn: &PgConnection, form: &Form) -> Result<Self, Error>
112 fn resolve(conn: &PgConnection, report_id: i32, resolver_id: PersonId) -> Result<usize, Error>
115 fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: PersonId) -> Result<usize, Error>
120 pub trait ApubObject<Form> {
121 fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error>
124 fn upsert(conn: &PgConnection, user_form: &Form) -> Result<Self, Error>
129 pub trait MaybeOptional<T> {
130 fn get_optional(self) -> Option<T>;
133 impl<T> MaybeOptional<T> for T {
134 fn get_optional(self) -> Option<T> {
139 impl<T> MaybeOptional<T> for Option<T> {
140 fn get_optional(self) -> Option<T> {
147 fn safe_columns_tuple() -> Self::SafeColumns;
150 pub trait ToSafeSettings {
151 type SafeSettingsColumns;
152 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
155 pub trait ViewToVec {
157 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
162 pub fn get_database_url_from_env() -> Result<String, VarError> {
163 env::var("LEMMY_DATABASE_URL")
166 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
180 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
181 pub enum ListingType {
188 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
189 pub enum SearchType {
198 pub fn from_opt_str_to_opt_enum<T: std::str::FromStr>(opt: &Option<String>) -> Option<T> {
199 opt.as_ref().map(|t| T::from_str(t).ok()).flatten()
202 pub fn fuzzy_search(q: &str) -> String {
203 let replaced = q.replace(" ", "%");
204 format!("%{}%", replaced)
207 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
208 let page = page.unwrap_or(1);
209 let limit = limit.unwrap_or(10);
210 let offset = limit * (page - 1);
214 pub fn is_email_regex(test: &str) -> bool {
215 EMAIL_REGEX.is_match(test)
218 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
220 // An empty string is an erase
222 if !unwrapped.eq("") {
223 Some(Some(unwrapped.to_owned()))
232 pub fn diesel_option_overwrite_to_url(
233 opt: &Option<String>,
234 ) -> Result<Option<Option<DbUrl>>, ApiError> {
235 match opt.as_ref().map(|s| s.as_str()) {
236 // An empty string is an erase
237 Some("") => Ok(Some(None)),
238 Some(str_url) => match Url::parse(str_url) {
239 Ok(url) => Ok(Some(Some(url.into()))),
240 Err(_) => Err(ApiError::err("invalid_url")),
248 pub fn establish_unpooled_connection() -> PgConnection {
249 let db_url = match get_database_url_from_env() {
252 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
257 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
258 embedded_migrations::run(&conn).expect("load migrations");
263 static ref EMAIL_REGEX: Regex =
264 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
265 .expect("compile email regex");
269 use diesel::sql_types::*;
272 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
278 use super::{fuzzy_search, *};
279 use crate::is_email_regex;
282 fn test_fuzzy_search() {
283 let test = "This is a fuzzy search";
284 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
289 assert!(is_email_regex("gush@gmail.com"));
290 assert!(!is_email_regex("nada_neutho"));
294 fn test_diesel_option_overwrite() {
295 assert_eq!(diesel_option_overwrite(&None), None);
296 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
298 diesel_option_overwrite(&Some("test".to_string())),
299 Some(Some("test".to_string()))
304 fn test_diesel_option_overwrite_to_url() {
305 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
307 diesel_option_overwrite_to_url(&Some("".to_string())),
311 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
314 let example_url = "https://example.com";
316 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
317 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()