optimise counting number of results for one negative tag

This commit is contained in:
Shish 2020-02-04 23:05:07 +00:00
parent 9216be3c96
commit aa5cf0e81b

View File

@ -199,6 +199,26 @@ class Image
* Image-related utility functions * Image-related utility functions
*/ */
public static function count_total_images(): int
{
global $cache, $database;
$total = $cache->get("image-count");
if (!$total) {
$total = (int)$database->get_one("SELECT COUNT(*) FROM images");
$cache->set("image-count", $total, 600);
}
return $total;
}
public static function count_tag(string $tag): int
{
global $database;
return (int)$database->get_one(
"SELECT count FROM tags WHERE LOWER(tag) = LOWER(:tag)",
["tag"=>$tag]
);
}
/** /**
* Count the number of image results for a given search * Count the number of image results for a given search
* *
@ -211,18 +231,15 @@ class Image
if ($tag_count === 0) { if ($tag_count === 0) {
// total number of images in the DB // total number of images in the DB
$total = $cache->get("image-count"); $total = self::count_total_images();
if (!$total) {
$total = (int)$database->get_one("SELECT COUNT(*) FROM images");
$cache->set("image-count", $total, 600);
}
} elseif ($tag_count === 1 && !preg_match("/[:=><\*\?]/", $tags[0])) { } elseif ($tag_count === 1 && !preg_match("/[:=><\*\?]/", $tags[0])) {
if (!startsWith($tags[0], "-")) {
// one tag - we can look that up directly // one tag - we can look that up directly
// TODO: one negative tag = (total - tag.count) $total = self::count_tag($tags[0]);
$total = (int)$database->get_one( } else {
"SELECT count FROM tags WHERE LOWER(tag) = LOWER(:tag)", // one negative tag - subtract from the total
["tag"=>$tags[0]] $total = self::count_total_images() - self::count_tag(substr($tags[0], 1));
); }
} else { } else {
// complex query // complex query
$total = $cache->get("image-count:" . Tag::implode($tags)); $total = $cache->get("image-count:" . Tag::implode($tags));