3 diesel_migrations::MigrationHarness,
8 use activitypub_federation::{fetch::object_id::ObjectId, traits::Object};
9 use chrono::NaiveDateTime;
10 use deadpool::Runtime;
15 result::{Error as DieselError, Error::QueryBuilderError},
16 serialize::{Output, ToSql},
21 pg::AsyncPgConnection,
23 deadpool::{Object as PooledConnection, Pool},
24 AsyncDieselConnectionManager,
27 use diesel_migrations::EmbeddedMigrations;
28 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
29 use once_cell::sync::Lazy;
31 use std::{env, env::VarError, time::Duration};
35 const FETCH_LIMIT_DEFAULT: i64 = 10;
36 pub const FETCH_LIMIT_MAX: i64 = 50;
37 const POOL_TIMEOUT: Option<Duration> = Some(Duration::from_secs(5));
39 pub type DbPool = Pool<AsyncPgConnection>;
41 pub async fn get_conn(pool: &DbPool) -> Result<PooledConnection<AsyncPgConnection>, DieselError> {
42 pool.get().await.map_err(|e| QueryBuilderError(e.into()))
45 pub fn get_database_url_from_env() -> Result<String, VarError> {
46 env::var("LEMMY_DATABASE_URL")
49 pub fn fuzzy_search(q: &str) -> String {
50 let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
51 format!("%{replaced}%")
54 pub fn limit_and_offset(
57 ) -> Result<(i64, i64), diesel::result::Error> {
58 let page = match page {
61 return Err(QueryBuilderError("Page is < 1".into()));
68 let limit = match limit {
70 if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
71 return Err(QueryBuilderError(
72 format!("Fetch limit is > {FETCH_LIMIT_MAX}").into(),
78 None => FETCH_LIMIT_DEFAULT,
80 let offset = limit * (page - 1);
84 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
85 let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
86 let offset = limit * (page.unwrap_or(1) - 1);
90 pub fn is_email_regex(test: &str) -> bool {
91 EMAIL_REGEX.is_match(test)
94 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
96 // An empty string is an erase
98 if !unwrapped.eq("") {
99 Some(Some(unwrapped.clone()))
108 pub fn diesel_option_overwrite_to_url(
109 opt: &Option<String>,
110 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
111 match opt.as_ref().map(std::string::String::as_str) {
112 // An empty string is an erase
113 Some("") => Ok(Some(None)),
114 Some(str_url) => match Url::parse(str_url) {
115 Ok(url) => Ok(Some(Some(url.into()))),
116 Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
122 pub fn diesel_option_overwrite_to_url_create(
123 opt: &Option<String>,
124 ) -> Result<Option<DbUrl>, LemmyError> {
125 match opt.as_ref().map(std::string::String::as_str) {
126 // An empty string is nothing
127 Some("") => Ok(None),
128 Some(str_url) => match Url::parse(str_url) {
129 Ok(url) => Ok(Some(url.into())),
130 Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
136 async fn build_db_pool_settings_opt(settings: Option<&Settings>) -> Result<DbPool, LemmyError> {
137 let db_url = get_database_url(settings);
138 let pool_size = settings.map(|s| s.database.pool_size).unwrap_or(5);
139 let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new(&db_url);
140 let pool = Pool::builder(manager)
142 .wait_timeout(POOL_TIMEOUT)
143 .create_timeout(POOL_TIMEOUT)
144 .recycle_timeout(POOL_TIMEOUT)
145 .runtime(Runtime::Tokio1)
148 // If there's no settings, that means its a unit test, and migrations need to be run
149 if settings.is_none() {
150 run_migrations(&db_url);
156 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
158 pub fn run_migrations(db_url: &str) {
159 // Needs to be a sync connection
161 PgConnection::establish(db_url).unwrap_or_else(|e| panic!("Error connecting to {db_url}: {e}"));
162 info!("Running Database migrations (This may take a long time)...");
164 .run_pending_migrations(MIGRATIONS)
165 .unwrap_or_else(|e| panic!("Couldn't run DB Migrations: {e}"));
166 info!("Database migrations complete.");
169 pub async fn build_db_pool(settings: &Settings) -> Result<DbPool, LemmyError> {
170 build_db_pool_settings_opt(Some(settings)).await
173 pub async fn build_db_pool_for_tests() -> DbPool {
174 build_db_pool_settings_opt(None)
176 .expect("db pool missing")
179 pub fn get_database_url(settings: Option<&Settings>) -> String {
180 // The env var should override anything in the settings config
181 match get_database_url_from_env() {
183 Err(e) => match settings {
184 Some(settings) => settings.get_database_url(),
185 None => panic!("Failed to read database URL from env var LEMMY_DATABASE_URL: {e}"),
190 pub fn naive_now() -> NaiveDateTime {
191 chrono::prelude::Utc::now().naive_utc()
194 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
196 SortType::Active | SortType::Hot => CommentSortType::Hot,
197 SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
198 SortType::Old => CommentSortType::Old,
203 | SortType::TopMonth => CommentSortType::Top,
207 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
208 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
209 .expect("compile email regex")
213 use diesel::sql_types::{BigInt, Text, Timestamp};
216 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
219 sql_function!(fn lower(x: Text) -> Text);
222 impl ToSql<Text, Pg> for DbUrl {
223 fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
224 <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
228 impl<DB: Backend> FromSql<Text, DB> for DbUrl
230 String: FromSql<Text, DB>,
232 fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
233 let str = String::from_sql(value)?;
234 Ok(DbUrl(Box::new(Url::parse(&str)?)))
238 impl<Kind> From<ObjectId<Kind>> for DbUrl
240 Kind: Object + Send + 'static,
241 for<'de2> <Kind as Object>::Kind: serde::Deserialize<'de2>,
243 fn from(id: ObjectId<Kind>) -> Self {
244 DbUrl(Box::new(id.into()))
250 use super::{fuzzy_search, *};
251 use crate::utils::is_email_regex;
254 fn test_fuzzy_search() {
255 let test = "This %is% _a_ fuzzy search";
258 "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
264 assert!(is_email_regex("gush@gmail.com"));
265 assert!(!is_email_regex("nada_neutho"));
269 fn test_diesel_option_overwrite() {
270 assert_eq!(diesel_option_overwrite(&None), None);
271 assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
273 diesel_option_overwrite(&Some("test".to_string())),
274 Some(Some("test".to_string()))
279 fn test_diesel_option_overwrite_to_url() {
280 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
282 diesel_option_overwrite_to_url(&Some(String::new())),
286 diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
289 let example_url = "https://example.com";
291 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
292 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()