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::Url;
18 use serde::{Deserialize, Serialize};
19 use std::{env, env::VarError};
24 pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
27 fn create(conn: &PgConnection, form: &T) -> Result<Self, Error>
30 fn read(conn: &PgConnection, id: i32) -> Result<Self, Error>
33 fn update(conn: &PgConnection, id: i32, form: &T) -> Result<Self, Error>
36 fn delete(_conn: &PgConnection, _id: i32) -> Result<usize, Error>
44 pub trait Followable<T> {
45 fn follow(conn: &PgConnection, form: &T) -> Result<Self, Error>
48 fn follow_accepted(conn: &PgConnection, community_id: i32, user_id: i32) -> Result<Self, Error>
51 fn unfollow(conn: &PgConnection, form: &T) -> Result<usize, Error>
54 fn has_local_followers(conn: &PgConnection, community_id: i32) -> Result<bool, Error>;
57 pub trait Joinable<T> {
58 fn join(conn: &PgConnection, form: &T) -> Result<Self, Error>
61 fn leave(conn: &PgConnection, form: &T) -> Result<usize, Error>
66 pub trait Likeable<T> {
67 fn like(conn: &PgConnection, form: &T) -> Result<Self, Error>
70 fn remove(conn: &PgConnection, user_id: i32, item_id: i32) -> Result<usize, Error>
75 pub trait Bannable<T> {
76 fn ban(conn: &PgConnection, form: &T) -> Result<Self, Error>
79 fn unban(conn: &PgConnection, form: &T) -> Result<usize, Error>
84 pub trait Saveable<T> {
85 fn save(conn: &PgConnection, form: &T) -> Result<Self, Error>
88 fn unsave(conn: &PgConnection, form: &T) -> Result<usize, Error>
93 pub trait Readable<T> {
94 fn mark_as_read(conn: &PgConnection, form: &T) -> Result<Self, Error>
97 fn mark_as_unread(conn: &PgConnection, form: &T) -> Result<usize, Error>
102 pub trait Reportable<T> {
103 fn report(conn: &PgConnection, form: &T) -> Result<Self, Error>
106 fn resolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error>
109 fn unresolve(conn: &PgConnection, report_id: i32, resolver_id: i32) -> Result<usize, Error>
114 pub trait ApubObject<T> {
115 fn read_from_apub_id(conn: &PgConnection, object_id: &Url) -> Result<Self, Error>
118 fn upsert(conn: &PgConnection, user_form: &T) -> Result<Self, Error>
123 pub trait MaybeOptional<T> {
124 fn get_optional(self) -> Option<T>;
127 impl<T> MaybeOptional<T> for T {
128 fn get_optional(self) -> Option<T> {
133 impl<T> MaybeOptional<T> for Option<T> {
134 fn get_optional(self) -> Option<T> {
141 fn safe_columns_tuple() -> Self::SafeColumns;
144 pub trait ToSafeSettings {
145 type SafeSettingsColumns;
146 fn safe_settings_columns_tuple() -> Self::SafeSettingsColumns;
149 pub trait ViewToVec {
151 fn from_tuple_to_vec(tuple: Vec<Self::DbTuple>) -> Vec<Self>
156 pub fn get_database_url_from_env() -> Result<String, VarError> {
157 env::var("LEMMY_DATABASE_URL")
160 #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]
174 #[derive(EnumString, ToString, Debug, Serialize, Deserialize, Clone)]
175 pub enum ListingType {
182 #[derive(EnumString, ToString, Debug, Serialize, Deserialize)]
183 pub enum SearchType {
192 pub fn fuzzy_search(q: &str) -> String {
193 let replaced = q.replace(" ", "%");
194 format!("%{}%", replaced)
197 pub fn limit_and_offset(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
198 let page = page.unwrap_or(1);
199 let limit = limit.unwrap_or(10);
200 let offset = limit * (page - 1);
204 pub fn is_email_regex(test: &str) -> bool {
205 EMAIL_REGEX.is_match(test)
208 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
210 // An empty string is an erase
212 if !unwrapped.eq("") {
213 Some(Some(unwrapped.to_owned()))
224 pub fn establish_unpooled_connection() -> PgConnection {
225 let db_url = match get_database_url_from_env() {
228 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
233 PgConnection::establish(&db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
234 embedded_migrations::run(&conn).unwrap();
238 pub fn establish_pooled_connection(
239 ) -> diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>> {
240 use diesel::r2d2::{ConnectionManager, Pool};
242 // Set up the r2d2 connection pool
243 let db_url = match get_database_url_from_env() {
246 "Failed to read database URL from env var LEMMY_DATABASE_URL: {}",
251 let manager = ConnectionManager::<PgConnection>::new(&db_url);
252 let pool = Pool::builder()
255 .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
257 let conn = pool.get().unwrap();
259 // Run the migrations from code
260 embedded_migrations::run(&conn).unwrap();
266 static ref EMAIL_REGEX: Regex =
267 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
271 use diesel::sql_types::*;
274 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
280 use super::fuzzy_search;
281 use crate::is_email_regex;
284 fn test_fuzzy_search() {
285 let test = "This is a fuzzy search";
286 assert_eq!(fuzzy_search(test), "%This%is%a%fuzzy%search%".to_string());
291 assert!(is_email_regex("gush@gmail.com"));
292 assert!(!is_email_regex("nada_neutho"));