summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/database.rs38
1 files changed, 38 insertions, 0 deletions
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<Vec<(i64, String)>> {
+ 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<i64> = (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);
+ }
}