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::DbUrl;
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>>;
29 fn create(conn: &PgConnection, form: &T) -> Result<Self, Error>
32 fn read(conn: &PgConnection, id: i32) -> Result<Self, Error>
35 fn update(conn: &PgConnection, id: i32, form: &T) -> Result<Self, Error>
38 fn delete(_conn: &PgConnection, _id: i32) -> Result<usize, Error>
46 pub trait Followable<T> {
47 fn follow(conn: &PgConnection, form: &T) -> Result<Self, Error>
50 fn follow_accepted(conn: &PgConnection, community_id: i32, user_id: i32) -> Result<Self, Error>
53 fn unfollow(conn: &PgConnection, form: &T) -> Result<usize, Error>
56 fn has_local_followers(conn: &PgConnection, community_id: i32) -> Result<bool, Error>;
59 pub trait Joinable<T> {
60 fn join(conn: &PgConnection, form: &T) -> Result<Self, Error>
63 fn leave(conn: &PgConnection, form: &T) -> Result<usize, Error>
68 pub trait Likeable<T> {
69 fn like(conn: &PgConnection, form: &T) -> Result<Self, Error>
72 fn remove(conn: &PgConnection, user_id: i32, item_id: i32) -> Result<usize, Error>
77 pub trait Bannable<T> {
78 fn ban(conn: &PgConnection, form: &T) -> Result<Self, Error>
81 fn unban(conn: &PgConnection, form: &T) -> Result<usize, Error>
86 pub trait Saveable<T> {
87 fn save(conn: &PgConnection, form: &T) -> Result<Self, Error>
90 fn unsave(conn: &PgConnection, form: &T) -> Result<usize, Error>
95 pub trait Readable<T> {
96 fn mark_as_read(conn: &PgConnection, form: &T) -> Result<Self, Error>
99 fn mark_as_unread(conn: &PgConnection, form: &T) -> Result<usize, Error>
104 pub trait Reportable<T> {
105 fn report(conn: &PgConnection, form: &T) -> Result<Self, Error>
108 fn resolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error>
111 fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error>
116 pub trait ApubObject<T> {
117 fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error>
120 fn upsert(conn: &PgConnection, user_form: &T) -> Result<Self, Error>
125 pub trait MaybeOptional<T> {
126 fn get_optional(self) -> Option<T>;
129 impl<T> MaybeOptional<T> for T {
130 fn get_optional(self) -> Option<T> {
135 impl<T> MaybeOptional<T> for Option<T> {
136 fn get_optional(self) -> Option<T> {
143 fn safe_columns_tuple() -> Self::SafeColumns;
146 pub trait ToSafeSettings {
147 type SafeSettingsColumns;
148 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
151 pub trait ViewToVec {
153 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
158 pub fn get_database_url_from_env() -> Result<String, VarError> {
159 env::var("LEMMY_DATABASE_URL")
162 #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]
176 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone)]
177 pub enum ListingType {
184 #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]
185 pub enum SearchType {
194 pub fn fuzzy_search(q: &str) -> String {
195 let replaced = q.replace(" ", "%");
196 format!("%{}%", replaced)
199 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
200 let page = page.unwrap_or(1);
201 let limit = limit.unwrap_or(10);
202 let offset = limit * (page - 1);
206 pub fn is_email_regex(test: &str) -> bool {
207 EMAIL_REGEX.is_match(test)
210 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
212 // An empty string is an erase
214 if !unwrapped.eq("") {
215 Some(Some(unwrapped.to_owned()))
224 pub fn diesel_option_overwrite_to_url(
225 opt: &Option<String>,
226 ) -> Result<Option<Option<DbUrl>>, ApiError> {
227 match opt.as_ref().map(|s| s.as_str()) {
228 // An empty string is an erase
229 Some("") => Ok(Some(None)),
230 Some(str_url) => match Url::parse(str_url) {
231 Ok(url) => Ok(Some(Some(url.into()))),
232 Err(_) => Err(ApiError::err("invalid_url")),
240 pub fn establish_unpooled_connection() -> PgConnection {
241 let db_url = match get_database_url_from_env() {
244 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
249 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
250 embedded_migrations::run(&conn).unwrap();
255 static ref EMAIL_REGEX: Regex =
256 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
260 use diesel::sql_types::*;
263 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
269 use super::{fuzzy_search, *};
270 use crate::is_email_regex;
273 fn test_fuzzy_search() {
274 let test = "This is a fuzzy search";
275 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
280 assert!(is_email_regex("gush@gmail.com"));
281 assert!(!is_email_regex("nada_neutho"));
285 fn test_diesel_option_overwrite() {
286 assert_eq!(diesel_option_overwrite(&None), None);
287 assert_eq!(diesel_option_overwrite(&Some("".to_string())), Some(None));
289 diesel_option_overwrite(&Some("test".to_string())),
290 Some(Some("test".to_string()))
295 fn test_diesel_option_overwrite_to_url() {
296 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
298 diesel_option_overwrite_to_url(&Some("".to_string())),
302 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
305 let example_url = "https://example.com";
307 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
308 Ok(Some(Some(url))) if url == Url::parse(&example_url).unwrap().into()