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>
113 fn mark_as_read(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
116 fn mark_as_unread(conn: &PgConnection, form: &Self::Form) -> Result<usize, Error>
121 pub trait Reportable {
123 fn report(conn: &PgConnection, form: &Self::Form) -> Result<Self, Error>
126 fn resolve(conn: &PgConnection, report_id: i32, resolver_id: PersonId) -> Result<usize, Error>
129 fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: PersonId) -> Result<usize, Error>
134 pub trait DeleteableOrRemoveable {
135 fn blank_out_deleted_or_removed_info(self) -> Self;
138 pub trait ApubObject {
140 fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error>
143 fn upsert(conn: &PgConnection, user_form: &Self::Form) -> Result<Self, Error>
148 pub trait MaybeOptional<T> {
149 fn get_optional(self) -> Option<T>;
152 impl<T> MaybeOptional<T> for T {
153 fn get_optional(self) -> Option<T> {
158 impl<T> MaybeOptional<T> for Option<T> {
159 fn get_optional(self) -> Option<T> {
166 fn safe_columns_tuple() -> Self::SafeColumns;
169 pub trait ToSafeSettings {
170 type SafeSettingsColumns;
171 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
174 pub trait ViewToVec {
176 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
181 pub fn get_database_url_from_env() -> Result<String, VarError> {
182 env::var("LEMMY_DATABASE_URL")
185 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
199 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
200 pub enum ListingType {
207 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone, Copy)]
208 pub enum SearchType {
217 pub fn from_opt_str_to_opt_enum<T: std::str::FromStr>(opt: &Option<String>) -> Option<T> {
218 opt.as_ref().map(|t| T::from_str(t).ok()).flatten()
221 pub fn fuzzy_search(q: &str) -> String {
222 let replaced = q.replace(" ", "%");
223 format!("%{}%", replaced)
226 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
227 let page = page.unwrap_or(1);
228 let limit = limit.unwrap_or(10);
229 let offset = limit * (page - 1);
233 pub fn is_email_regex(test: &str) -> bool {
234 EMAIL_REGEX.is_match(test)
237 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
239 // An empty string is an erase
241 if !unwrapped.eq("") {
242 Some(Some(unwrapped.to_owned()))
251 pub fn diesel_option_overwrite_to_url(
252 opt: &Option<String>,
253 ) -> Result<Option<Option<DbUrl>>, ApiError> {
254 match opt.as_ref().map(|s| s.as_str()) {
255 // An empty string is an erase
256 Some("") => Ok(Some(None)),
257 Some(str_url) => match Url::parse(str_url) {
258 Ok(url) => Ok(Some(Some(url.into()))),
259 Err(_) => Err(ApiError::err("invalid_url")),
267 pub fn establish_unpooled_connection() -> PgConnection {
268 let db_url = match get_database_url_from_env() {
271 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
276 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
277 embedded_migrations::run(&conn).expect("load migrations");
282 static ref EMAIL_REGEX: Regex =
283 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
284 .expect("compile email regex");
288 use diesel::sql_types::*;
291 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
297 use super::{fuzzy_search, *};
298 use crate::is_email_regex;
301 fn test_fuzzy_search() {
302 let test = "This is a fuzzy search";
303 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
308 assert!(is_email_regex("gush@gmail.com"));
309 assert!(!is_email_regex("nada_neutho"));
313 fn test_diesel_option_overwrite() {
314 assert_eq!(diesel_option_overwrite(&None), None);
315 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
317 diesel_option_overwrite(&Some("test".to_string())),
318 Some(Some("test".to_string()))
323 fn test_diesel_option_overwrite_to_url() {
324 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
326 diesel_option_overwrite_to_url(&Some("".to_string())),
330 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
333 let example_url = "https://example.com";
335 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
336 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()