Fix delete behaviour

This commit is contained in:
Raphaël Thériault 2020-01-16 01:27:50 -05:00
parent 35ba76a28d
commit 3f390faba0
2 changed files with 42 additions and 4 deletions

View File

@ -77,15 +77,18 @@ macro_rules! delete {
/// Queries affecting the `files` table /// Queries affecting the `files` table
pub mod files { pub mod files {
use crate::{ use crate::{
globals::POOL, globals::{CONFIG, POOL},
models::files::*, models::files::*,
queries::SelectFilters, queries::SelectFilters,
schema::files::{dsl::*, table}, schema::files::{dsl::*, table},
}; };
use diesel::{prelude::*, result::QueryResult}; use diesel::{
prelude::*,
result::{DatabaseErrorKind, Error, QueryResult},
};
use std::fs;
find!(files, File); find!(files, File);
delete!(files);
/// SELECT multiple file entries /// SELECT multiple file entries
pub fn select(filters: SelectFilters) -> QueryResult<Vec<File>> { pub fn select(filters: SelectFilters) -> QueryResult<Vec<File>> {
@ -95,8 +98,34 @@ pub mod files {
query.load::<File>(conn) query.load::<File>(conn)
} }
/// Delete an existing file on disk
fn fs_del(fid: i32) -> QueryResult<()> {
let mut path = CONFIG.files_dir.clone();
path.push(match find(fid) {
Ok(f) => f.filepath,
Err(e) => {
return match e {
Error::NotFound => Ok(()),
_ => Err(e),
}
}
});
if !path.exists() {
return Ok(());
}
fs::remove_file(path).map_err(|e| {
Error::DatabaseError(
DatabaseErrorKind::UnableToSendCommand,
Box::new(format!("{}", e)),
)
})
}
/// REPLACE a file entry /// REPLACE a file entry
pub fn replace(r_id: i32, r_filepath: &str) -> QueryResult<File> { pub fn replace(r_id: i32, r_filepath: &str) -> QueryResult<File> {
fs_del(r_id)?;
let conn: &SqliteConnection = &POOL.get().unwrap(); let conn: &SqliteConnection = &POOL.get().unwrap();
let new_file = NewFile { let new_file = NewFile {
id: r_id, id: r_id,
@ -107,6 +136,15 @@ pub mod files {
.execute(conn)?; .execute(conn)?;
find(r_id) find(r_id)
} }
/// DELETE an entry
pub fn delete(d_id: i32) -> QueryResult<()> {
fs_del(d_id)?;
let conn: &SqliteConnection = &POOL.get().unwrap();
diesel::delete(files.find(d_id)).execute(conn)?;
Ok(())
}
} }
/// Queries affecting the `links` table /// Queries affecting the `links` table

View File

@ -154,7 +154,7 @@ macro_rules! delete {
let id = crate::routes::parse_id(&path)?; let id = crate::routes::parse_id(&path)?;
match actix_web::web::block(move || crate::queries::$m::delete(id)).await { match actix_web::web::block(move || crate::queries::$m::delete(id)).await {
Ok(()) => Ok(actix_web::HttpResponse::NoContent().body("Deleted")), Ok(()) => Ok(actix_web::HttpResponse::Ok().body("Deleted")),
Err(e) => crate::routes::match_find_error(e), Err(e) => crate::routes::match_find_error(e),
} }
} }