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 DeleteableOrRemoveable {
121 fn blank_out_deleted_or_removed_info(self) -> Self;
124 pub trait ApubObject<Form> {
125 fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error>
128 fn upsert(conn: &PgConnection, user_form: &Form) -> Result<Self, Error>
133 pub trait MaybeOptional<T> {
134 fn get_optional(self) -> Option<T>;
137 impl<T> MaybeOptional<T> for T {
138 fn get_optional(self) -> Option<T> {
143 impl<T> MaybeOptional<T> for Option<T> {
144 fn get_optional(self) -> Option<T> {
151 fn safe_columns_tuple() -> Self::SafeColumns;
154 pub trait ToSafeSettings {
155 type SafeSettingsColumns;
156 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
159 pub trait ViewToVec {
161 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
166 pub fn get_database_url_from_env() -> Result<String, VarError> {
167 env::var("LEMMY_DATABASE_URL")
170 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
184 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
185 pub enum ListingType {
192 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
193 pub enum SearchType {
202 pub fn from_opt_str_to_opt_enum<T: std::str::FromStr>(opt: &Option<String>) -> Option<T> {
203 opt.as_ref().map(|t| T::from_str(t).ok()).flatten()
206 pub fn fuzzy_search(q: &str) -> String {
207 let replaced = q.replace(" ", "%");
208 format!("%{}%", replaced)
211 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
212 let page = page.unwrap_or(1);
213 let limit = limit.unwrap_or(10);
214 let offset = limit * (page - 1);
218 pub fn is_email_regex(test: &str) -> bool {
219 EMAIL_REGEX.is_match(test)
222 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
224 // An empty string is an erase
226 if !unwrapped.eq("") {
227 Some(Some(unwrapped.to_owned()))
236 pub fn diesel_option_overwrite_to_url(
237 opt: &Option<String>,
238 ) -> Result<Option<Option<DbUrl>>, ApiError> {
239 match opt.as_ref().map(|s| s.as_str()) {
240 // An empty string is an erase
241 Some("") => Ok(Some(None)),
242 Some(str_url) => match Url::parse(str_url) {
243 Ok(url) => Ok(Some(Some(url.into()))),
244 Err(_) => Err(ApiError::err("invalid_url")),
252 pub fn establish_unpooled_connection() -> PgConnection {
253 let db_url = match get_database_url_from_env() {
256 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
261 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
262 embedded_migrations::run(&conn).expect("load migrations");
267 static ref EMAIL_REGEX: Regex =
268 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
269 .expect("compile email regex");
273 use diesel::sql_types::*;
276 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
282 use super::{fuzzy_search, *};
283 use crate::is_email_regex;
286 fn test_fuzzy_search() {
287 let test = "This is a fuzzy search";
288 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
293 assert!(is_email_regex("gush@gmail.com"));
294 assert!(!is_email_regex("nada_neutho"));
298 fn test_diesel_option_overwrite() {
299 assert_eq!(diesel_option_overwrite(&None), None);
300 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
302 diesel_option_overwrite(&Some("test".to_string())),
303 Some(Some("test".to_string()))
308 fn test_diesel_option_overwrite_to_url() {
309 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
311 diesel_option_overwrite_to_url(&Some("".to_string())),
315 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
318 let example_url = "https://example.com";
320 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
321 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()