diff options
| author | Nathan Perry <avaglir@gmail.com> | 2019-02-18 21:30:14 -0500 |
|---|---|---|
| committer | Nathan Perry <avaglir@gmail.com> | 2019-02-18 21:30:14 -0500 |
| commit | 2f0af295cd75d64943edb4f1af0ebcd950297893 (patch) | |
| tree | b0ce867f26072b8d6d1226c269a54b7e61dfe304 /src/db | |
| parent | 372f09c41034899dfa307501296a2822b70680eb (diff) | |
improve randomizer
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/mod.rs | 42 |
1 files changed, 25 insertions, 17 deletions
diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ff05ce..1c2a032 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -102,26 +102,34 @@ pub fn delete_meme<T: AsRef<str>>(conn: &PgConnection, search: T, deleted_by: u6 }) } -pub fn rand_text(conn: &PgConnection) -> Result<Meme> { - memes::table - .filter(memes::content.is_not_null()) - .order(random.desc()) - .first::<Meme>(conn) - .map_err(Error::from) -} +pub fn rand_meme(conn: &PgConnection, audio: bool) -> Result<Meme> { + use rand::{thread_rng, seq::SliceRandom}; + use failure::err_msg; + use std::ops::Try; -pub fn rand_image(conn: &PgConnection) -> Result<Meme> { - memes::table - .filter(memes::image_id.is_not_null()) - .order(random.desc()) - .first::<Meme>(conn) - .map_err(Error::from) -} + let ids: Vec<i32> = if audio { + memes::table + .select(memes::id) + .filter(memes::content.is_not_null() + .or(memes::image_id.is_not_null()) + .or(memes::audio_id.is_not_null())) + .load(conn) + .map_err(Error::from)? + } else { + memes::table + .select(memes::id) + .filter(memes::content.is_not_null() + .or(memes::image_id.is_not_null())) + .load(conn) + .map_err(Error::from)? + }; + + let id = ids.choose(&mut thread_rng()) + .into_result() + .map_err( |_| err_msg("couldn't load meme"))?; -pub fn rand_audio(conn: &PgConnection) -> Result<Meme> { memes::table - .filter(memes::audio_id.is_not_null()) - .order(random.desc()) + .find(id) .first::<Meme>(conn) .map_err(Error::from) } |
