diff options
| author | Jakob L. Kreuze <zerodaysfordays@sdf.org> | 2020-05-26 19:45:38 -0400 |
|---|---|---|
| committer | Jakob L. Kreuze <zerodaysfordays@sdf.org> | 2020-05-26 19:45:38 -0400 |
| commit | a932889c9a01537a53e9c587e13e25843744b6f0 (patch) | |
| tree | 593fcd0fdfb643ffab57294470bbb6a2b70d3626 /src | |
| parent | 0915c0f653f19f4dbeec6f2916eac149d0eb43bd (diff) | |
Implement `top_tags`.
Diffstat (limited to 'src')
| -rw-r--r-- | src/database.rs | 38 |
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); + } } |