From 2f0af295cd75d64943edb4f1af0ebcd950297893 Mon Sep 17 00:00:00 2001 From: Nathan Perry Date: Mon, 18 Feb 2019 21:30:14 -0500 Subject: improve randomizer --- src/db/mod.rs | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) (limited to 'src/db/mod.rs') 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>(conn: &PgConnection, search: T, deleted_by: u6 }) } -pub fn rand_text(conn: &PgConnection) -> Result { - memes::table - .filter(memes::content.is_not_null()) - .order(random.desc()) - .first::(conn) - .map_err(Error::from) -} - -pub fn rand_image(conn: &PgConnection) -> Result { - memes::table - .filter(memes::image_id.is_not_null()) - .order(random.desc()) - .first::(conn) - .map_err(Error::from) -} +pub fn rand_meme(conn: &PgConnection, audio: bool) -> Result { + use rand::{thread_rng, seq::SliceRandom}; + use failure::err_msg; + use std::ops::Try; + + let ids: Vec = 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 { memes::table - .filter(memes::audio_id.is_not_null()) - .order(random.desc()) + .find(id) .first::(conn) .map_err(Error::from) } -- cgit v1.3.1