3 diesel_migrations::MigrationHarness,
8 use activitypub_federation::{core::object_id::ObjectId, traits::ApubObject};
9 use bb8::PooledConnection;
10 use chrono::NaiveDateTime;
15 result::{Error as DieselError, Error::QueryBuilderError},
16 serialize::{Output, ToSql},
21 pg::AsyncPgConnection,
22 pooled_connection::{bb8::Pool, AsyncDieselConnectionManager},
24 use diesel_migrations::EmbeddedMigrations;
25 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
26 use once_cell::sync::Lazy;
28 use std::{env, env::VarError};
32 const FETCH_LIMIT_DEFAULT: i64 = 10;
33 pub const FETCH_LIMIT_MAX: i64 = 50;
35 pub type DbPool = Pool<AsyncPgConnection>;
37 pub async fn get_conn(
39 ) -> Result<PooledConnection<AsyncDieselConnectionManager<AsyncPgConnection>>, DieselError> {
40 pool.get().await.map_err(|e| QueryBuilderError(e.into()))
43 pub fn get_database_url_from_env() -> Result<String, VarError> {
44 env::var("LEMMY_DATABASE_URL")
47 pub fn fuzzy_search(q: &str) -> String {
48 let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
49 format!("%{replaced}%")
52 pub fn limit_and_offset(
55 ) -> Result<(i64, i64), diesel::result::Error> {
56 let page = match page {
59 return Err(QueryBuilderError("Page is < 1".into()));
66 let limit = match limit {
68 if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
69 return Err(QueryBuilderError(
70 format!("Fetch limit is > {FETCH_LIMIT_MAX}").into(),
76 None => FETCH_LIMIT_DEFAULT,
78 let offset = limit * (page - 1);
82 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
83 let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
84 let offset = limit * (page.unwrap_or(1) - 1);
88 pub fn is_email_regex(test: &str) -> bool {
89 EMAIL_REGEX.is_match(test)
92 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
94 // An empty string is an erase
96 if !unwrapped.eq("") {
97 Some(Some(unwrapped.clone()))
106 pub fn diesel_option_overwrite_to_url(
107 opt: &Option<String>,
108 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
109 match opt.as_ref().map(std::string::String::as_str) {
110 // An empty string is an erase
111 Some("") => Ok(Some(None)),
112 Some(str_url) => match Url::parse(str_url) {
113 Ok(url) => Ok(Some(Some(url.into()))),
114 Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
120 pub fn diesel_option_overwrite_to_url_create(
121 opt: &Option<String>,
122 ) -> Result<Option<DbUrl>, LemmyError> {
123 match opt.as_ref().map(std::string::String::as_str) {
124 // An empty string is nothing
125 Some("") => Ok(None),
126 Some(str_url) => match Url::parse(str_url) {
127 Ok(url) => Ok(Some(url.into())),
128 Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
134 async fn build_db_pool_settings_opt(settings: Option<&Settings>) -> Result<DbPool, LemmyError> {
135 let db_url = get_database_url(settings);
136 let pool_size = settings.map(|s| s.database.pool_size).unwrap_or(5);
137 let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new(&db_url);
138 let pool = Pool::builder()
144 // If there's no settings, that means its a unit test, and migrations need to be run
145 if settings.is_none() {
146 run_migrations(&db_url);
152 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
154 pub fn run_migrations(db_url: &str) {
155 // Needs to be a sync connection
157 PgConnection::establish(db_url).unwrap_or_else(|_| panic!("Error connecting to {db_url}"));
158 info!("Running Database migrations (This may take a long time)...");
160 .run_pending_migrations(MIGRATIONS)
161 .unwrap_or_else(|_| panic!("Couldn't run DB Migrations"));
162 info!("Database migrations complete.");
165 pub async fn build_db_pool(settings: &Settings) -> Result<DbPool, LemmyError> {
166 build_db_pool_settings_opt(Some(settings)).await
169 pub async fn build_db_pool_for_tests() -> DbPool {
170 build_db_pool_settings_opt(None)
172 .expect("db pool missing")
175 pub fn get_database_url(settings: Option<&Settings>) -> String {
176 // The env var should override anything in the settings config
177 match get_database_url_from_env() {
179 Err(e) => match settings {
180 Some(settings) => settings.get_database_url(),
181 None => panic!("Failed to read database URL from env var LEMMY_DATABASE_URL: {e}"),
186 pub fn naive_now() -> NaiveDateTime {
187 chrono::prelude::Utc::now().naive_utc()
190 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
192 SortType::Active | SortType::Hot => CommentSortType::Hot,
193 SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
194 SortType::Old => CommentSortType::Old,
199 | SortType::TopMonth => CommentSortType::Top,
203 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
204 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
205 .expect("compile email regex")
209 use diesel::sql_types::{BigInt, Text, Timestamp};
212 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
215 sql_function!(fn lower(x: Text) -> Text);
218 impl ToSql<Text, Pg> for DbUrl {
219 fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
220 <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
224 impl<DB: Backend> FromSql<Text, DB> for DbUrl
226 String: FromSql<Text, DB>,
228 fn from_sql(value: diesel::backend::RawValue<'_, DB>) -> diesel::deserialize::Result<Self> {
229 let str = String::from_sql(value)?;
230 Ok(DbUrl(Url::parse(&str)?))
234 impl<Kind> From<ObjectId<Kind>> for DbUrl
236 Kind: ApubObject + Send + 'static,
237 for<'de2> <Kind as ApubObject>::ApubType: serde::Deserialize<'de2>,
239 fn from(id: ObjectId<Kind>) -> Self {
246 use super::{fuzzy_search, *};
247 use crate::utils::is_email_regex;
250 fn test_fuzzy_search() {
251 let test = "This %is% _a_ fuzzy search";
254 "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
260 assert!(is_email_regex("gush@gmail.com"));
261 assert!(!is_email_regex("nada_neutho"));
265 fn test_diesel_option_overwrite() {
266 assert_eq!(diesel_option_overwrite(&None), None);
267 assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
269 diesel_option_overwrite(&Some("test".to_string())),
270 Some(Some("test".to_string()))
275 fn test_diesel_option_overwrite_to_url() {
276 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
278 diesel_option_overwrite_to_url(&Some(String::new())),
282 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
285 let example_url = "https://example.com";
287 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
288 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()