From a932889c9a01537a53e9c587e13e25843744b6f0 Mon Sep 17 00:00:00 2001 From: "Jakob L. Kreuze" Date: Tue, 26 May 2020 19:45:38 -0400 Subject: Implement `top_tags`. --- src/database.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'src') diff --git a/src/database.rs b/src/database.rs index db33117..bd195f2 100644 --- a/src/database.rs +++ b/src/database.rs @@ -254,6 +254,24 @@ impl TagDatabase { limit: None, }) } + + pub fn top_tags(&self, n: i64) -> Result> { + Ok(self + .0 + .prepare( + "SELECT tags.name, COUNT(mapping.tag) AS tag_count + FROM mapping + INNER JOIN tags ON tags.id = mapping.tag + GROUP BY tag + ORDER BY tag_count DESC + LIMIT ?", + )? + .query_map(params![n], |row| -> rusqlite::Result<(i64, String)> { + Ok((row.get(1)?, row.get(0)?)) + })? + .filter_map(|s| s.ok()) + .collect()) + } } /// The result of an image query in бирка-тян's tag database. @@ -357,4 +375,24 @@ mod tests { assert_eq!(tb.images_by_tags(&["2"]).unwrap().len(), 2); assert_eq!(tb.images_by_tags(&["1", "2"]).unwrap().len(), 1); } + + #[test] + fn top_tags() { + let tb = TagDatabase::new_mem().unwrap(); + let ids: Vec = (1..4) + .map(|i| { + let i = i.to_string(); + tb.import_image(Path::new(&i), &i).unwrap() + }) + .collect(); + tb.add_tag("1").unwrap(); + tb.add_tag("2").unwrap(); + tb.tag_image(ids[0], "1").unwrap(); + tb.tag_image(ids[1], "2").unwrap(); + tb.tag_image(ids[2], "1").unwrap(); + tb.tag_image(ids[2], "2").unwrap(); + assert_eq!(tb.top_tags(2).unwrap().len(), 2); + assert_eq!(tb.top_tags(2).unwrap()[0].0, 2); + assert_eq!(tb.top_tags(2).unwrap()[1].0, 2); + } } -- cgit v1.3