Remove updated fields and update queries

This commit is contained in:
Raphaël Thériault 2019-10-15 08:16:23 -04:00
parent cc0f304563
commit eca73144f3
8 changed files with 26 additions and 163 deletions

View File

@ -1,6 +1,5 @@
CREATE TABLE files ( CREATE TABLE files (
id INTEGER NOT NULL PRIMARY KEY, id INTEGER NOT NULL PRIMARY KEY,
filepath TEXT NOT NULL, filepath TEXT NOT NULL,
created INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), created INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
updated INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) );
)

View File

@ -1,6 +1,5 @@
CREATE TABLE links ( CREATE TABLE links (
id INTEGER NOT NULL PRIMARY KEY, id INTEGER NOT NULL PRIMARY KEY,
forward TEXT NOT NULL, forward TEXT NOT NULL,
created INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), created INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
updated INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) );
)

View File

@ -1,6 +1,5 @@
CREATE TABLE texts ( CREATE TABLE texts (
id INTEGER NOT NULL PRIMARY KEY, id INTEGER NOT NULL PRIMARY KEY,
contents TEXT NOT NULL, contents TEXT NOT NULL,
created INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), created INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
updated INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) );
)

View File

@ -70,8 +70,8 @@ pub mod files {
use chrono::{Datelike, Utc}; use chrono::{Datelike, Utc};
use futures::future::{self, Either}; use futures::future::{self, Either};
use futures::Future; use futures::Future;
use std::path::PathBuf;
use std::fs; use std::fs;
use std::path::PathBuf;
select!(files); select!(files);
@ -189,7 +189,7 @@ pub mod links {
web::block(move || queries::links::find(id, pool)).then(|result| match result { web::block(move || queries::links::find(id, pool)).then(|result| match result {
Ok(link) => Ok(HttpResponse::Found() Ok(link) => Ok(HttpResponse::Found()
.header("Location", link.forward) .header("Location", link.forward)
.header("Last-Modified", timestamp_to_last_modified(link.updated)) .header("Last-Modified", timestamp_to_last_modified(link.created))
.finish()), .finish()),
Err(_) => Err(HttpResponse::NotFound().finish().into()), Err(_) => Err(HttpResponse::NotFound().finish().into()),
}), }),
@ -237,7 +237,7 @@ pub mod texts {
Either::A( Either::A(
web::block(move || queries::texts::find(id, pool)).then(|result| match result { web::block(move || queries::texts::find(id, pool)).then(|result| match result {
Ok(text) => Ok(HttpResponse::Ok() Ok(text) => Ok(HttpResponse::Ok()
.header("Last-Modified", timestamp_to_last_modified(text.updated)) .header("Last-Modified", timestamp_to_last_modified(text.created))
.body(text.contents)), .body(text.contents)),
Err(_) => Err(HttpResponse::NotFound().finish().into()), Err(_) => Err(HttpResponse::NotFound().finish().into()),
}), }),

View File

@ -13,8 +13,6 @@ pub mod files {
pub filepath: String, pub filepath: String,
/// Creation date and time as a UNIX timestamp /// Creation date and time as a UNIX timestamp
pub created: i32, pub created: i32,
/// Update date and time as a UNIX timestamp
pub updated: i32,
} }
/// A new entry to the `files` table /// A new entry to the `files` table
@ -41,8 +39,6 @@ pub mod links {
pub forward: String, pub forward: String,
/// Creation date and time as a UNIX timestamp /// Creation date and time as a UNIX timestamp
pub created: i32, pub created: i32,
/// Update date and time as a UNIX timestamp
pub updated: i32,
} }
/// A new entry to the `links` table /// A new entry to the `links` table
@ -65,11 +61,10 @@ pub mod texts {
pub struct Text { pub struct Text {
/// Primary key, its radix 36 value is used as an url /// Primary key, its radix 36 value is used as an url
pub id: i32, pub id: i32,
/// Text contents
pub contents: String, pub contents: String,
/// Creation date and time as a UNIX timestamp /// Creation date and time as a UNIX timestamp
pub created: i32, pub created: i32,
/// Update date and time as a UNIX timestamp
pub updated: i32,
} }
/// A new entry to the `texts` table /// A new entry to the `texts` table

View File

@ -1,57 +1,34 @@
//! Helper functions for SQL queries //! Helper functions for SQL queries
// A lot of duplicate code here could be merged by using macros
// but that would make adding different fields more troublesome
/// Date and time range specifying ranges for creation and update
pub struct SelectRange {
/// Creation time range
pub created: (Option<i32>, Option<i32>),
/// Update time range
pub updated: (Option<i32>, Option<i32>),
}
/// Query string for SELECT queries /// Query string for SELECT queries
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct SelectQuery { pub struct SelectQuery {
/// Left creation bounder timestamp /// Left creation bounder timestamp
pub cf: Option<i32>, pub from: Option<i32>,
/// Right creation bounder timestamp /// Right creation bounder timestamp
pub ct: Option<i32>, pub to: Option<i32>,
/// Left update bounder timestamp
pub uf: Option<i32>,
/// Right update bounder timestamp
pub ut: Option<i32>,
/// Query size limit /// Query size limit
pub limit: Option<i64>, pub limit: Option<i64>,
/// Whether to sort the results in ascending order /// Whether to sort the results in ascending order
pub asc: Option<bool>, pub asc: Option<bool>,
/// Whether to sort the results by creation date
pub created: Option<bool>,
} }
/// Filters for SELECT queries /// Filters for SELECT queries
pub struct SelectFilters { pub struct SelectFilters {
/// Creation and update date and time ranges /// Creation and update date and time ranges
pub range: SelectRange, pub range: (Option<i32>, Option<i32>),
/// Query size limit /// Query size limit
pub limit: Option<i64>, pub limit: Option<i64>,
/// Whether to sort the results in ascending order /// Whether to sort the results in ascending order
pub order_asc: bool, pub asc: bool,
/// Whether to sort the results by creation date
pub order_created: bool,
} }
impl From<SelectQuery> for SelectFilters { impl From<SelectQuery> for SelectFilters {
fn from(query: SelectQuery) -> Self { fn from(query: SelectQuery) -> Self {
SelectFilters { SelectFilters {
range: SelectRange { range: (query.from, query.to),
created: (query.cf, query.ct),
updated: (query.uf, query.ut),
},
limit: query.limit, limit: query.limit,
order_asc: query.asc.unwrap_or(false), asc: query.asc.unwrap_or(false),
order_created: query.created.unwrap_or(false),
} }
} }
} }
@ -59,29 +36,21 @@ impl From<SelectQuery> for SelectFilters {
/// Code common to all select functions /// Code common to all select functions
macro_rules! common_select { macro_rules! common_select {
($q:expr, $f:expr) => { ($q:expr, $f:expr) => {
if let Some(cf) = $f.range.created.0 { if let Some(from) = $f.range.0 {
$q = $q.filter(created.ge(cf)); $q = $q.filter(created.ge(from));
} }
if let Some(ct) = $f.range.created.1 { if let Some(to) = $f.range.1 {
$q = $q.filter(created.lt(ct)); $q = $q.filter(created.lt(to));
}
if let Some(uf) = $f.range.updated.0 {
$q = $q.filter(updated.ge(uf));
}
if let Some(ut) = $f.range.updated.1 {
$q = $q.filter(updated.lt(ut));
} }
if let Some(limit) = $f.limit { if let Some(limit) = $f.limit {
$q = $q.limit(limit); $q = $q.limit(limit);
} }
$q = match ($f.order_asc, $f.order_created) { match $f.asc {
(false, false) => $q.order(updated.desc()), false => $q = $q.order(created.desc()),
(true, false) => $q.order(updated.asc()), true => $q = $q.order(created.asc()),
(false, true) => $q.order(created.desc()), }
(true, true) => $q.order(created.asc()),
};
}; };
} }
@ -143,39 +112,6 @@ pub mod files {
find(r_id, pool) find(r_id, pool)
} }
/// UPDATE a file entry
pub fn update(
u_id: i32,
new_id: Option<i32>,
new_filepath: Option<&str>,
pool: Data<Pool>,
) -> QueryResult<File> {
let conn: &SqliteConnection = &pool.get().unwrap();
let file = find(u_id, pool)?;
let query = diesel::update(&file);
let time_update = updated.eq(chrono::Utc::now().timestamp() as i32);
match (new_id, new_filepath) {
(Some(new_id), Some(new_filepath)) => {
query
.set((id.eq(new_id), filepath.eq(new_filepath), time_update))
.execute(conn)?;
}
(Some(new_id), None) => {
query.set((id.eq(new_id), time_update)).execute(conn)?;
}
(None, Some(new_filepath)) => {
query
.set((filepath.eq(new_filepath), time_update))
.execute(conn)?;
}
(None, None) => {
return Ok(file);
}
}
Ok(file)
}
delete!(files); delete!(files);
} }
@ -215,37 +151,6 @@ pub mod links {
find(r_id, pool) find(r_id, pool)
} }
/// UPDATE a link entry
pub fn update(
u_id: i32,
new_id: Option<i32>,
new_forward: Option<&str>,
pool: Data<Pool>,
) -> QueryResult<Link> {
let conn: &SqliteConnection = &pool.get().unwrap();
let link = find(u_id, pool)?;
let query = diesel::update(&link);
let time_update = updated.eq(chrono::Utc::now().timestamp() as i32);
match (new_id, new_forward) {
(Some(new_id), Some(new_forward)) => {
query
.set((id.eq(new_id), forward.eq(new_forward), time_update))
.execute(conn)?;
}
(Some(new_id), None) => {
query.set((id.eq(new_id), time_update)).execute(conn)?;
}
(None, Some(new_forward)) => {
query
.set((forward.eq(new_forward), time_update))
.execute(conn)?;
}
(None, None) => (),
}
Ok(link)
}
delete!(links); delete!(links);
} }
@ -285,36 +190,5 @@ pub mod texts {
find(r_id, pool) find(r_id, pool)
} }
/// UPDATE a text entry
pub fn update(
u_id: i32,
new_id: Option<i32>,
new_contents: Option<&str>,
pool: Data<Pool>,
) -> QueryResult<Text> {
let conn: &SqliteConnection = &pool.get().unwrap();
let text = find(u_id, pool)?;
let query = diesel::update(&text);
let time_update = updated.eq(chrono::Utc::now().timestamp() as i32);
match (new_id, new_contents) {
(Some(new_id), Some(new_contents)) => {
query
.set((id.eq(new_id), contents.eq(new_contents), time_update))
.execute(conn)?;
}
(Some(new_id), None) => {
query.set((id.eq(new_id), time_update)).execute(conn)?;
}
(None, Some(new_contents)) => {
query
.set((contents.eq(new_contents), time_update))
.execute(conn)?;
}
(None, None) => (),
}
Ok(text)
}
delete!(texts); delete!(texts);
} }

View File

@ -3,7 +3,6 @@ table! {
id -> Integer, id -> Integer,
filepath -> Text, filepath -> Text,
created -> Integer, created -> Integer,
updated -> Integer,
} }
} }
@ -12,7 +11,6 @@ table! {
id -> Integer, id -> Integer,
forward -> Text, forward -> Text,
created -> Integer, created -> Integer,
updated -> Integer,
} }
} }
@ -21,7 +19,6 @@ table! {
id -> Integer, id -> Integer,
contents -> Text, contents -> Text,
created -> Integer, created -> Integer,
updated -> Integer,
} }
} }

View File

@ -10,10 +10,10 @@ use std::path::PathBuf;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
use dotenv; use dotenv;
#[cfg(debug_assertions)]
use std::str::FromStr;
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
use std::fs; use std::fs;
#[cfg(debug_assertions)]
use std::str::FromStr;
/// Returns a path to the directory storing application data /// Returns a path to the directory storing application data
pub fn get_data_dir() -> PathBuf { pub fn get_data_dir() -> PathBuf {