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>>;
31 fn create(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
34 fn read(conn: &PgConnection, id: Self::IdType) -> Result<Self, Error>
37 fn update(conn: &PgConnection, id: Self::IdType, form: &Self::Form) -> Result<Self, Error>
40 fn delete(_conn: &PgConnection, _id: Self::IdType) -> Result<usize, Error>
48 pub trait Followable {
50 fn follow(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
55 community_id: CommunityId,
57 ) -> Result<Self, Error>
60 fn unfollow(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
63 fn has_local_followers(conn: &PgConnection, community_id: CommunityId) -> Result<bool, Error>;
68 fn join(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
71 fn leave(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
79 fn like(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
85 item_id: Self::IdType,
86 ) -> Result<usize, Error>
93 fn ban(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
96 fn unban(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
103 fn save(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
106 fn unsave(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
111 pub trait Blockable {
113 fn block(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
116 fn unblock(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
123 fn mark_as_read(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
126 fn mark_as_unread(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
131 pub trait Reportable {
134 fn report(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
139 report_id: Self::IdType,
140 resolver_id: PersonId,
141 ) -> Result<usize, Error>
146 report_id: Self::IdType,
147 resolver_id: PersonId,
148 ) -> Result<usize, Error>
153 pub trait DeleteableOrRemoveable {
154 fn blank_out_deleted_or_removed_info(self) -> Self;
157 pub trait MaybeOptional<T> {
158 fn get_optional(self) -> Option<T>;
161 impl<T> MaybeOptional<T> for T {
162 fn get_optional(self) -> Option<T> {
167 impl<T> MaybeOptional<T> for Option<T> {
168 fn get_optional(self) -> Option<T> {
175 fn safe_columns_tuple() -> Self::SafeColumns;
178 pub trait ToSafeSettings {
179 type SafeSettingsColumns;
180 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
183 pub trait ViewToVec {
185 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
190 pub fn get_database_url_from_env() -> Result<String, VarError> {
191 env::var("LEMMY_DATABASE_URL")
194 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
208 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
209 pub enum ListingType {
216 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
217 pub enum SearchType {
226 pub fn from_opt_str_to_opt_enum<T: std::str::FromStr>(opt: &Option<String>) -> Option<T> {
227 opt.as_ref().map(|t| T::from_str(t).ok()).flatten()
230 pub fn fuzzy_search(q: &str) -> String {
231 let replaced = q.replace(" ", "%");
232 format!("%{}%", replaced)
235 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
236 let page = page.unwrap_or(1);
237 let limit = limit.unwrap_or(10);
238 let offset = limit * (page - 1);
242 pub fn is_email_regex(test: &str) -> bool {
243 EMAIL_REGEX.is_match(test)
246 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
248 // An empty string is an erase
250 if !unwrapped.eq("") {
251 Some(Some(unwrapped.to_owned()))
260 pub fn diesel_option_overwrite_to_url(
261 opt: &Option<String>,
262 ) -> Result<Option<Option<DbUrl>>, ApiError> {
263 match opt.as_ref().map(|s| s.as_str()) {
264 // An empty string is an erase
265 Some("") => Ok(Some(None)),
266 Some(str_url) => match Url::parse(str_url) {
267 Ok(url) => Ok(Some(Some(url.into()))),
268 Err(_) => Err(ApiError::err("invalid_url")),
276 pub fn establish_unpooled_connection() -> PgConnection {
277 let db_url = match get_database_url_from_env() {
280 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
285 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
286 embedded_migrations::run(&conn).expect("load migrations");
291 static ref EMAIL_REGEX: Regex =
292 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
293 .expect("compile email regex");
297 use diesel::sql_types::*;
300 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
306 use super::{fuzzy_search, *};
307 use crate::is_email_regex;
310 fn test_fuzzy_search() {
311 let test = "This is a fuzzy search";
312 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
317 assert!(is_email_regex("gush@gmail.com"));
318 assert!(!is_email_regex("nada_neutho"));
322 fn test_diesel_option_overwrite() {
323 assert_eq!(diesel_option_overwrite(&None), None);
324 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
326 diesel_option_overwrite(&Some("test".to_string())),
327 Some(Some("test".to_string()))
332 fn test_diesel_option_overwrite_to_url() {
333 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
335 diesel_option_overwrite_to_url(&Some("".to_string())),
339 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
342 let example_url = "https://example.com";
344 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
345 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()