diff --git a/src/tribler/core/database/store.py b/src/tribler/core/database/store.py index 9bfe4b812b..c424c16c3c 100644 --- a/src/tribler/core/database/store.py +++ b/src/tribler/core/database/store.py @@ -557,26 +557,25 @@ def get_entries_query( # noqa: C901, PLR0912, PLR0913 if txt_filter: pony_query = self.search_keyword(txt_filter, origin_id=origin_id) - else: - pony_query = left_join(g for g in self.TorrentMetadata) - - infohash_set = infohash_set or ({infohash} if infohash else None) - if popular: + elif popular: if metadata_type != REGULAR_TORRENT: msg = "With `popular=True`, only `metadata_type=REGULAR_TORRENT` is allowed" raise TypeError(msg) t = time() - POPULAR_TORRENTS_FRESHNESS_PERIOD - health_list = list( - select( - health for health in self.TorrentState + return select( + g for g in self.TorrentMetadata + for health in self.TorrentState if health.has_data == 1 # The condition had to be written this way for the partial index to work and health.last_check >= t and (health.seeders > 0 or health.leechers > 0) + and g.health == health ).order_by( - lambda health: (desc(health.seeders), desc(health.leechers), desc(health.last_check)) - )[:POPULAR_TORRENTS_COUNT] - ) - pony_query = pony_query.where(lambda g: g.health in health_list) + lambda g: (desc(g.health.seeders), desc(g.health.leechers), desc(g.health.last_check)) + ).limit(POPULAR_TORRENTS_COUNT) + else: + pony_query = left_join(g for g in self.TorrentMetadata) + + infohash_set = infohash_set or ({infohash} if infohash else None) if max_rowid is not None: pony_query = pony_query.where(lambda g: g.rowid <= max_rowid) @@ -670,8 +669,6 @@ def get_entries_query( # noqa: C901, PLR0912, PLR0913 desc(g.health.last_check) # just to trigger the TorrentState table inclusion into the left join """ ) - elif popular: - pony_query = pony_query.sort_by('(desc(g.health.seeders), desc(g.health.leechers))') return pony_query