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 chrono::NaiveDateTime;
16 use diesel::{result::Error, *};
17 use lemmy_db_schema::{CommunityId, DbUrl, PersonId};
18 use lemmy_utils::ApiError;
20 use serde::{Deserialize, Serialize};
21 use std::{env, env::VarError};
27 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
32 fn create(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
35 fn read(conn: &PgConnection, id: Self::IdType) -> Result<Self, Error>
38 fn update(conn: &PgConnection, id: Self::IdType, form: &Self::Form) -> Result<Self, Error>
41 fn delete(_conn: &PgConnection, _id: Self::IdType) -> Result<usize, Error>
49 pub trait Followable {
51 fn follow(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
56 community_id: CommunityId,
58 ) -> Result<Self, Error>
61 fn unfollow(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
64 fn has_local_followers(conn: &PgConnection, community_id: CommunityId) -> Result<bool, Error>;
69 fn join(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
72 fn leave(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
80 fn like(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
86 item_id: Self::IdType,
87 ) -> Result<usize, Error>
94 fn ban(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
97 fn unban(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
104 fn save(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
107 fn unsave(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
112 pub trait Blockable {
114 fn block(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
117 fn unblock(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
124 fn mark_as_read(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
127 fn mark_as_unread(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
132 pub trait Reportable {
135 fn report(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
140 report_id: Self::IdType,
141 resolver_id: PersonId,
142 ) -> Result<usize, Error>
147 report_id: Self::IdType,
148 resolver_id: PersonId,
149 ) -> Result<usize, Error>
154 pub trait DeleteableOrRemoveable {
155 fn blank_out_deleted_or_removed_info(self) -> Self;
158 // TODO: move this to apub lib
159 pub trait ApubObject {
160 /// If this object should be refetched after a certain interval, it should return the last refresh
161 /// time here. This is mainly used to update remote actors.
162 fn last_refreshed_at(&self) -> Option<NaiveDateTime>;
163 fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error>
168 pub trait MaybeOptional<T> {
169 fn get_optional(self) -> Option<T>;
172 impl<T> MaybeOptional<T> for T {
173 fn get_optional(self) -> Option<T> {
178 impl<T> MaybeOptional<T> for Option<T> {
179 fn get_optional(self) -> Option<T> {
186 fn safe_columns_tuple() -> Self::SafeColumns;
189 pub trait ToSafeSettings {
190 type SafeSettingsColumns;
191 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
194 pub trait ViewToVec {
196 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
201 pub fn get_database_url_from_env() -> Result<String, VarError> {
202 env::var("LEMMY_DATABASE_URL")
205 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
219 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
220 pub enum ListingType {
227 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
228 pub enum SearchType {
237 pub fn from_opt_str_to_opt_enum<T: std::str::FromStr>(opt: &Option<String>) -> Option<T> {
238 opt.as_ref().map(|t| T::from_str(t).ok()).flatten()
241 pub fn fuzzy_search(q: &str) -> String {
242 let replaced = q.replace(" ", "%");
243 format!("%{}%", replaced)
246 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
247 let page = page.unwrap_or(1);
248 let limit = limit.unwrap_or(10);
249 let offset = limit * (page - 1);
253 pub fn is_email_regex(test: &str) -> bool {
254 EMAIL_REGEX.is_match(test)
257 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
259 // An empty string is an erase
261 if !unwrapped.eq("") {
262 Some(Some(unwrapped.to_owned()))
271 pub fn diesel_option_overwrite_to_url(
272 opt: &Option<String>,
273 ) -> Result<Option<Option<DbUrl>>, ApiError> {
274 match opt.as_ref().map(|s| s.as_str()) {
275 // An empty string is an erase
276 Some("") => Ok(Some(None)),
277 Some(str_url) => match Url::parse(str_url) {
278 Ok(url) => Ok(Some(Some(url.into()))),
279 Err(_) => Err(ApiError::err("invalid_url")),
287 pub fn establish_unpooled_connection() -> PgConnection {
288 let db_url = match get_database_url_from_env() {
291 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
296 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
297 embedded_migrations::run(&conn).expect("load migrations");
302 static ref EMAIL_REGEX: Regex =
303 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
304 .expect("compile email regex");
308 use diesel::sql_types::*;
311 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
317 use super::{fuzzy_search, *};
318 use crate::is_email_regex;
321 fn test_fuzzy_search() {
322 let test = "This is a fuzzy search";
323 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
328 assert!(is_email_regex("gush@gmail.com"));
329 assert!(!is_email_regex("nada_neutho"));
333 fn test_diesel_option_overwrite() {
334 assert_eq!(diesel_option_overwrite(&None), None);
335 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
337 diesel_option_overwrite(&Some("test".to_string())),
338 Some(Some("test".to_string()))
343 fn test_diesel_option_overwrite_to_url() {
344 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
346 diesel_option_overwrite_to_url(&Some("".to_string())),
350 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
353 let example_url = "https://example.com";
355 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
356 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()