From 3f390faba0ba571c6a4bed22ce13ce7a23605193 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Th=C3=A9riault?= Date: Thu, 16 Jan 2020 01:27:50 -0500 Subject: [PATCH] Fix delete behaviour --- src/queries.rs | 44 +++++++++++++++++++++++++++++++++++++++++--- src/routes.rs | 2 +- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/queries.rs b/src/queries.rs index 9a17422..24f4ac4 100644 --- a/src/queries.rs +++ b/src/queries.rs @@ -77,15 +77,18 @@ macro_rules! delete { /// Queries affecting the `files` table pub mod files { use crate::{ - globals::POOL, + globals::{CONFIG, POOL}, models::files::*, queries::SelectFilters, schema::files::{dsl::*, table}, }; - use diesel::{prelude::*, result::QueryResult}; + use diesel::{ + prelude::*, + result::{DatabaseErrorKind, Error, QueryResult}, + }; + use std::fs; find!(files, File); - delete!(files); /// SELECT multiple file entries pub fn select(filters: SelectFilters) -> QueryResult> { @@ -95,8 +98,34 @@ pub mod files { query.load::(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 pub fn replace(r_id: i32, r_filepath: &str) -> QueryResult { + fs_del(r_id)?; + let conn: &SqliteConnection = &POOL.get().unwrap(); let new_file = NewFile { id: r_id, @@ -107,6 +136,15 @@ pub mod files { .execute(conn)?; 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 diff --git a/src/routes.rs b/src/routes.rs index e5274a7..d066ec2 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -154,7 +154,7 @@ macro_rules! delete { let id = crate::routes::parse_id(&path)?; 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), } }