Skip to content

Commit

Permalink
Use Diesels MultiConnections Derive
Browse files Browse the repository at this point in the history
With this PR we remove allmost all custom macro's to create the multiple
database type code. This is now handled by Diesel it self.

This removed the need of the following functions/macro's:
- `db_object!`
- `::to_db`
- `.from_db()`

It is also possible to just use one schema instead of multiple per type.
  • Loading branch information
BlackDex committed Aug 24, 2023
1 parent 3d2df6c commit 50163c2
Show file tree
Hide file tree
Showing 28 changed files with 871 additions and 1,708 deletions.
75 changes: 59 additions & 16 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ publish = false
build = "build.rs"

[features]
# default = ["sqlite"]
default = [
# "sqlite",
# "postgresql",
# "mysql",
]
# Empty to keep compatibility, prefer to set USE_SYSLOG=true
enable_syslog = []
mysql = ["diesel/mysql", "diesel_migrations/mysql"]
Expand Down Expand Up @@ -166,6 +170,8 @@ rpassword = "7.2.0"
[patch.crates-io]
rocket = { git = 'https://github.com/SergioBenitez/Rocket', rev = 'ce441b5f46fdf5cd99cb32b8b8638835e4c2a5fa' } # v0.5 branch
# rocket_ws = { git = 'https://github.com/SergioBenitez/Rocket', rev = 'ce441b5f46fdf5cd99cb32b8b8638835e4c2a5fa' } # v0.5 branch
diesel = { git = 'https://github.com/diesel-rs/diesel', rev = "409585e9548f61f4e180ea5fe13ee4c3b7ab241c" }
diesel_migrations = { git = 'https://github.com/diesel-rs/diesel', rev = "409585e9548f61f4e180ea5fe13ee4c3b7ab241c" }

# Strip debuginfo from the release builds
# Also enable thin LTO for some optimizations
Expand Down
15 changes: 11 additions & 4 deletions src/api/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,22 @@ pub fn catchers() -> Vec<Catcher> {
static DB_TYPE: Lazy<&str> = Lazy::new(|| {
DbConnType::from_url(&CONFIG.database_url())
.map(|t| match t {
DbConnType::sqlite => "SQLite",
DbConnType::mysql => "MySQL",
DbConnType::postgresql => "PostgreSQL",
#[cfg(sqlite)]
DbConnType::Sqlite => "SQLite",
#[cfg(mysql)]
DbConnType::Mysql => "MySQL",
#[cfg(postgresql)]
DbConnType::Postgresql => "PostgreSQL",
})
.unwrap_or("Unknown")
});

#[cfg(sqlite)]
static CAN_BACKUP: Lazy<bool> =
Lazy::new(|| DbConnType::from_url(&CONFIG.database_url()).map(|t| t == DbConnType::sqlite).unwrap_or(false));
Lazy::new(|| DbConnType::from_url(&CONFIG.database_url()).map(|t| t == DbConnType::Sqlite).unwrap_or(false));

#[cfg(not(sqlite))]
static CAN_BACKUP: Lazy<bool> = Lazy::new(|| false);

#[get("/")]
fn admin_disabled() -> &'static str {
Expand Down
8 changes: 6 additions & 2 deletions src/api/core/sends.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,9 +340,13 @@ async fn post_send_file_v2_data(

let mut data = data.into_inner();

let Some(send) = Send::find_by_uuid(send_uuid, &mut conn).await else { err!("Send not found. Unable to save the file.") };
let Some(send) = Send::find_by_uuid(send_uuid, &mut conn).await else {
err!("Send not found. Unable to save the file.")
};

let Some(send_user_id) = &send.user_uuid else {err!("Sends are only supported for users at the moment")};
let Some(send_user_id) = &send.user_uuid else {
err!("Sends are only supported for users at the moment")
};
if send_user_id != &headers.user.uuid {
err!("Send doesn't belong to user");
}
Expand Down
4 changes: 3 additions & 1 deletion src/api/icons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,9 @@ async fn download_icon(domain: &str) -> Result<(Bytes, Option<&str>), Error> {

for icon in icon_result.iconlist.iter().take(5) {
if icon.href.starts_with("data:image") {
let Ok(datauri) = DataUrl::process(&icon.href) else {continue};
let Ok(datauri) = DataUrl::process(&icon.href) else {
continue;
};
// Check if we are able to decode the data uri
let mut body = BytesMut::new();
match datauri.decode::<_, ()>(|bytes| {
Expand Down
8 changes: 6 additions & 2 deletions src/api/notifications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,12 @@ fn websockets_hub<'r>(
let addr = ip.ip;
info!("Accepting Rocket WS connection from {addr}");

let Some(token) = data.access_token else { err_code!("Invalid claim", 401) };
let Ok(claims) = crate::auth::decode_login(&token) else { err_code!("Invalid token", 401) };
let Some(token) = data.access_token else {
err_code!("Invalid claim", 401)
};
let Ok(claims) = crate::auth::decode_login(&token) else {
err_code!("Invalid token", 401)
};

let (mut rx, guard) = {
let users = Arc::clone(&WS_USERS);
Expand Down
4 changes: 3 additions & 1 deletion src/api/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ async fn web_files(p: PathBuf) -> Cached<Option<NamedFile>> {

#[get("/attachments/<uuid>/<file_id>?<token>")]
async fn attachments(uuid: SafeString, file_id: SafeString, token: String) -> Option<NamedFile> {
let Ok(claims) = decode_file_download(&token) else { return None };
let Ok(claims) = decode_file_download(&token) else {
return None;
};
if claims.sub != *uuid || claims.file_id != *file_id {
return None;
}
Expand Down
19 changes: 12 additions & 7 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use once_cell::sync::Lazy;
use reqwest::Url;

use crate::{
db::DbConnType,
error::Error,
util::{get_env, get_env_bool},
};
Expand Down Expand Up @@ -687,12 +686,18 @@ make_config! {

fn validate_config(cfg: &ConfigItems) -> Result<(), Error> {
// Validate connection URL is valid and DB feature is enabled
let url = &cfg.database_url;
if DbConnType::from_url(url)? == DbConnType::sqlite && url.contains('/') {
let path = std::path::Path::new(&url);
if let Some(parent) = path.parent() {
if !parent.is_dir() {
err!(format!("SQLite database directory `{}` does not exist or is not a directory", parent.display()));
#[cfg(sqlite)]
{
let url = &cfg.database_url;
if crate::db::DbConnType::from_url(url)? == crate::db::DbConnType::Sqlite && url.contains('/') {
let path = std::path::Path::new(&url);
if let Some(parent) = path.parent() {
if !parent.is_dir() {
err!(format!(
"SQLite database directory `{}` does not exist or is not a directory",
parent.display()
));
}
}
}
}
Expand Down
Loading

0 comments on commit 50163c2

Please sign in to comment.