Fix tag count sorting, hopefully

This commit is contained in:
Cameron
2025-12-25 15:17:50 -05:00
parent 6c543ffa68
commit ae0886cd2e

View File

@@ -507,31 +507,51 @@ impl TagDao for SqliteTagDao {
trace_db_call(context, "query", "get_files_with_all_tags", |_| { trace_db_call(context, "query", "get_files_with_all_tags", |_| {
use diesel::dsl::*; use diesel::dsl::*;
let exclude_subquery = tagged_photo::table // Create the placeholders for the IN clauses
.filter(tagged_photo::tag_id.eq_any(exclude_tag_ids.clone())) let tag_placeholders = std::iter::repeat_n("?", tag_ids.len())
.select(tagged_photo::photo_name) .collect::<Vec<_>>()
.join(",");
let exclude_placeholders = std::iter::repeat_n("?", exclude_tag_ids.len())
.collect::<Vec<_>>()
.join(",");
let query = sql_query(format!(
r#"
WITH filtered_photos AS (
SELECT photo_name
FROM tagged_photo tp
WHERE tp.tag_id IN ({})
AND tp.photo_name NOT IN (
SELECT photo_name
FROM tagged_photo
WHERE tag_id IN ({})
)
GROUP BY photo_name
HAVING COUNT(DISTINCT tag_id) >= {}
)
SELECT
fp.photo_name as file_name,
COUNT(DISTINCT tp2.tag_id) as tag_count
FROM filtered_photos fp
JOIN tagged_photo tp2 ON fp.photo_name = tp2.photo_name
GROUP BY fp.photo_name"#,
tag_placeholders,
exclude_placeholders,
tag_ids.len()
))
.into_boxed(); .into_boxed();
tagged_photo::table // Bind all parameters
.filter(tagged_photo::tag_id.eq_any(tag_ids.clone())) let query = tag_ids
.filter(tagged_photo::photo_name.ne_all(exclude_subquery))
.group_by(tagged_photo::photo_name)
.select((
tagged_photo::photo_name,
count_distinct(tagged_photo::tag_id),
))
.having(count_distinct(tagged_photo::tag_id).ge(tag_ids.len() as i64))
.get_results::<(String, i64)>(&mut self.connection)
.map(|results| {
results
.into_iter() .into_iter()
.map(|(file_name, tag_count)| FileWithTagCount { .fold(query, |q, id| q.bind::<Integer, _>(id));
file_name, let query = exclude_tag_ids
tag_count, .into_iter()
}) .fold(query, |q, id| q.bind::<Integer, _>(id));
.collect()
}) query
.with_context(|| format!("Unable to get Tagged photos with ids: {:?}", tag_ids)) .load::<FileWithTagCount>(&mut self.connection)
.with_context(|| "Unable to get tagged photos with all specified tags")
}) })
} }