diff --git a/src/cache/mod.rs b/src/cache/mod.rs index 33c28e2..7b3bc57 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -41,13 +41,7 @@ impl Cache { /// ref to download probems pub fn update(self) -> Result<(), Error> { - let c = conn((&self.0.conf.storage.cache()?).to_owned()); - let ps = self.download_problems()?; - for i in ps.into_iter() { - let target = problems.filter(id.eq(i.id)); - diesel::update(target).set(i.to_owned()).execute(&c)?; - } - + self.download_problems()?; Ok(()) } @@ -68,13 +62,9 @@ impl Cache { parser::problem(&mut ps, json)?; } - let count = self.get_problems()?.len(); - if count == 0 { - ps.sort_by(|a, b| b.id.partial_cmp(&a.id).unwrap_or(std::cmp::Ordering::Equal)); - diesel::insert_into(problems) - .values(&ps) - .execute(&self.conn()?)?; - } + diesel::replace_into(problems) + .values(&ps) + .execute(&self.conn()?)?; Ok(ps) } diff --git a/src/cmds/pick.rs b/src/cmds/pick.rs index 02dcc52..fa35d3b 100644 --- a/src/cmds/pick.rs +++ b/src/cmds/pick.rs @@ -100,13 +100,16 @@ impl Command for PickCommand { crate::helper::filter(&mut problems, query.to_string()); } - if let Some(id) = m.value_of("id") { - problems.retain(|x| x.fid.to_string() == id); - } - - let problem = &problems[rand::thread_rng().gen_range(0, problems.len())]; + let fid = m + .value_of("id") + .and_then(|id| id.parse::().ok()) + .unwrap_or_else(|| { + // Pick random without specify id + let problem = &problems[rand::thread_rng().gen_range(0, problems.len())]; + problem.fid + }); - let r = cache.get_question(problem.fid); + let r = cache.get_question(fid); if r.is_err() { let e = r.err()?; eprintln!("{:?}", &e); diff --git a/src/err.rs b/src/err.rs index a01fe77..cc3360e 100644 --- a/src/err.rs +++ b/src/err.rs @@ -1,4 +1,5 @@ //! Errors in leetcode-cli +use crate::cmds::{Command, DataCommand}; use colored::Colorize; use std::fmt; @@ -14,6 +15,7 @@ pub enum Error { ScriptError(String), CookieError, DecryptError, + SilentError, } impl std::fmt::Debug for Error { @@ -40,6 +42,7 @@ impl std::fmt::Debug for Error { Error::MatchError => write!(f, "{} Nothing matches", e), Error::DecryptError => write!(f, "{} openssl decrypt failed", e), Error::ScriptError(s) => write!(f, "{} {}", e, s), + Error::SilentError => write!(f, ""), } } } @@ -61,7 +64,14 @@ impl std::convert::From for Error { // sql impl std::convert::From for Error { fn from(err: diesel::result::Error) -> Self { - Error::CacheError(err.to_string()) + match err { + diesel::result::Error::NotFound => { + println!("NotFound, you may update cache, and try it again\r\n"); + DataCommand::usage().print_help().unwrap_or(()); + Error::SilentError + } + _ => Error::CacheError(err.to_string()), + } } }