3 diesel_migrations::MigrationHarness,
8 use activitypub_federation::{fetch::object_id::ObjectId, traits::Object};
9 use chrono::NaiveDateTime;
10 use deadpool::Runtime;
15 result::{ConnectionError, ConnectionResult, 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 futures_util::{future::BoxFuture, FutureExt};
30 error::{LemmyError, LemmyErrorExt, LemmyErrorType},
31 settings::structs::Settings,
33 use once_cell::sync::Lazy;
36 client::{ServerCertVerified, ServerCertVerifier},
43 time::{Duration, SystemTime},
45 use tracing::{error, info};
48 const FETCH_LIMIT_DEFAULT: i64 = 10;
49 pub const FETCH_LIMIT_MAX: i64 = 50;
50 const POOL_TIMEOUT: Option<Duration> = Some(Duration::from_secs(5));
52 pub type DbPool = Pool<AsyncPgConnection>;
54 pub async fn get_conn(pool: &DbPool) -> Result<PooledConnection<AsyncPgConnection>, DieselError> {
55 pool.get().await.map_err(|e| QueryBuilderError(e.into()))
58 pub fn get_database_url_from_env() -> Result<String, VarError> {
59 env::var("LEMMY_DATABASE_URL")
62 pub fn fuzzy_search(q: &str) -> String {
63 let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
64 format!("%{replaced}%")
67 pub fn limit_and_offset(
70 ) -> Result<(i64, i64), diesel::result::Error> {
71 let page = match page {
74 return Err(QueryBuilderError("Page is < 1".into()));
81 let limit = match limit {
83 if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
84 return Err(QueryBuilderError(
85 format!("Fetch limit is > {FETCH_LIMIT_MAX}").into(),
91 None => FETCH_LIMIT_DEFAULT,
93 let offset = limit * (page - 1);
97 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
98 let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
99 let offset = limit * (page.unwrap_or(1) - 1);
103 pub fn is_email_regex(test: &str) -> bool {
104 EMAIL_REGEX.is_match(test)
107 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
109 // An empty string is an erase
111 if !unwrapped.eq("") {
112 Some(Some(unwrapped.clone()))
121 pub fn diesel_option_overwrite_to_url(
122 opt: &Option<String>,
123 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
124 match opt.as_ref().map(String::as_str) {
125 // An empty string is an erase
126 Some("") => Ok(Some(None)),
127 Some(str_url) => Url::parse(str_url)
128 .map(|u| Some(Some(u.into())))
129 .with_lemmy_type(LemmyErrorType::InvalidUrl),
134 pub fn diesel_option_overwrite_to_url_create(
135 opt: &Option<String>,
136 ) -> Result<Option<DbUrl>, LemmyError> {
137 match opt.as_ref().map(String::as_str) {
138 // An empty string is nothing
139 Some("") => Ok(None),
140 Some(str_url) => Url::parse(str_url)
141 .map(|u| Some(u.into()))
142 .with_lemmy_type(LemmyErrorType::InvalidUrl),
147 async fn build_db_pool_settings_opt(settings: Option<&Settings>) -> Result<DbPool, LemmyError> {
148 let db_url = get_database_url(settings);
149 let pool_size = settings.map(|s| s.database.pool_size).unwrap_or(5);
150 // We only support TLS with sslmode=require currently
151 let tls_enabled = db_url.contains("sslmode=require");
152 let manager = if tls_enabled {
153 // diesel-async does not support any TLS connections out of the box, so we need to manually
154 // provide a setup function which handles creating the connection
155 AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_setup(&db_url, establish_connection)
157 AsyncDieselConnectionManager::<AsyncPgConnection>::new(&db_url)
159 let pool = Pool::builder(manager)
161 .wait_timeout(POOL_TIMEOUT)
162 .create_timeout(POOL_TIMEOUT)
163 .recycle_timeout(POOL_TIMEOUT)
164 .runtime(Runtime::Tokio1)
167 // If there's no settings, that means its a unit test, and migrations need to be run
168 if settings.is_none() {
169 run_migrations(&db_url);
175 fn establish_connection(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> {
177 let rustls_config = rustls::ClientConfig::builder()
178 .with_safe_defaults()
179 .with_custom_certificate_verifier(Arc::new(NoCertVerifier {}))
180 .with_no_client_auth();
182 let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config);
183 let (client, conn) = tokio_postgres::connect(config, tls)
185 .map_err(|e| ConnectionError::BadConnection(e.to_string()))?;
186 tokio::spawn(async move {
187 if let Err(e) = conn.await {
188 error!("Database connection failed: {e}");
191 AsyncPgConnection::try_from(client).await
196 struct NoCertVerifier {}
198 impl ServerCertVerifier for NoCertVerifier {
199 fn verify_server_cert(
201 _end_entity: &rustls::Certificate,
202 _intermediates: &[rustls::Certificate],
203 _server_name: &ServerName,
204 _scts: &mut dyn Iterator<Item = &[u8]>,
205 _ocsp_response: &[u8],
207 ) -> Result<ServerCertVerified, rustls::Error> {
208 // Will verify all (even invalid) certs without any checks (sslmode=require)
209 Ok(ServerCertVerified::assertion())
213 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
215 pub fn run_migrations(db_url: &str) {
216 // Needs to be a sync connection
218 PgConnection::establish(db_url).unwrap_or_else(|e| panic!("Error connecting to {db_url}: {e}"));
219 info!("Running Database migrations (This may take a long time)...");
221 .run_pending_migrations(MIGRATIONS)
222 .unwrap_or_else(|e| panic!("Couldn't run DB Migrations: {e}"));
223 info!("Database migrations complete.");
226 pub async fn build_db_pool(settings: &Settings) -> Result<DbPool, LemmyError> {
227 build_db_pool_settings_opt(Some(settings)).await
230 pub async fn build_db_pool_for_tests() -> DbPool {
231 build_db_pool_settings_opt(None)
233 .expect("db pool missing")
236 pub fn get_database_url(settings: Option<&Settings>) -> String {
237 // The env var should override anything in the settings config
238 match get_database_url_from_env() {
240 Err(e) => match settings {
241 Some(settings) => settings.get_database_url(),
242 None => panic!("Failed to read database URL from env var LEMMY_DATABASE_URL: {e}"),
247 pub fn naive_now() -> NaiveDateTime {
248 chrono::prelude::Utc::now().naive_utc()
251 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
253 SortType::Active | SortType::Hot => CommentSortType::Hot,
254 SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
255 SortType::Old => CommentSortType::Old,
257 | SortType::TopSixHour
258 | SortType::TopTwelveHour
264 | SortType::TopThreeMonths
265 | SortType::TopSixMonths
266 | SortType::TopNineMonths => CommentSortType::Top,
270 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
271 Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
272 .expect("compile email regex")
276 use diesel::sql_types::{BigInt, Text, Timestamp};
279 fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
282 sql_function!(fn lower(x: Text) -> Text);
285 pub const DELETED_REPLACEMENT_TEXT: &str = "*Permanently Deleted*";
287 impl ToSql<Text, Pg> for DbUrl {
288 fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
289 <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
293 impl<DB: Backend> FromSql<Text, DB> for DbUrl
295 String: FromSql<Text, DB>,
297 fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
298 let str = String::from_sql(value)?;
299 Ok(DbUrl(Box::new(Url::parse(&str)?)))
303 impl<Kind> From<ObjectId<Kind>> for DbUrl
305 Kind: Object + Send + 'static,
306 for<'de2> <Kind as Object>::Kind: serde::Deserialize<'de2>,
308 fn from(id: ObjectId<Kind>) -> Self {
309 DbUrl(Box::new(id.into()))
315 use super::{fuzzy_search, *};
316 use crate::utils::is_email_regex;
319 fn test_fuzzy_search() {
320 let test = "This %is% _a_ fuzzy search";
323 "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
329 assert!(is_email_regex("gush@gmail.com"));
330 assert!(!is_email_regex("nada_neutho"));
334 fn test_diesel_option_overwrite() {
335 assert_eq!(diesel_option_overwrite(&None), None);
336 assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
338 diesel_option_overwrite(&Some("test".to_string())),
339 Some(Some("test".to_string()))
344 fn test_diesel_option_overwrite_to_url() {
345 assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
347 diesel_option_overwrite_to_url(&Some(String::new())),
350 assert!(diesel_option_overwrite_to_url(&Some("invalid_url".to_string())).is_err());
351 let example_url = "https://example.com";
353 diesel_option_overwrite_to_url(&Some(example_url.to_string())),
354 Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()