From: Michael Tremer Date: Sun, 28 Dec 2025 13:21:23 +0000 (+0000) Subject: lists: Create a CTE to fetch all domains X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=d72bfef02f4592a9446e2ead9c180a531c8bf5e4;p=dbl.git lists: Create a CTE to fetch all domains This is reusable so that we don't have to copy any queries. Signed-off-by: Michael Tremer --- diff --git a/src/dnsbl/lists.py b/src/dnsbl/lists.py index 6035d80..07ca3b8 100644 --- a/src/dnsbl/lists.py +++ b/src/dnsbl/lists.py @@ -114,23 +114,9 @@ class List(sqlmodel.SQLModel, database.BackendMixin, table=True): sqlmodel .select( sqlmodel.func.count( - sqlmodel.func.distinct( - sources.SourceDomain.name, - ), + self.__domains.c.name, ), ) - .select_from( - sources.Source, - ) - .join( - sources.SourceDomain, - sources.SourceDomain.source_id == sources.Source.id, - ) - .where( - sources.Source.list_id == self.id, - sources.Source.deleted_at == None, - sources.SourceDomain.removed_at == None, - ) ) return self.backend.db.fetch_one(stmt) @@ -211,15 +197,15 @@ class List(sqlmodel.SQLModel, database.BackendMixin, table=True): # Join it all together return ".".join(e for e in s if e) - @property - def domains(self): + @functools.cached_property + def __domains(self): """ - Returns all domains that are on this list + A CTE to access all (active) domains on this list """ - stmt = ( + cte = ( sqlmodel .select( - sources.SourceDomain.name, + sources.SourceDomain.name.label("name"), ) .distinct( sources.SourceDomain.name, @@ -256,6 +242,21 @@ class List(sqlmodel.SQLModel, database.BackendMixin, table=True): .order_by( sources.SourceDomain.name, ) + .cte("domains") + ) + + return cte + + @property + def domains(self): + """ + Returns all domains that are on this list + """ + stmt = ( + sqlmodel + .select( + self.__domains.c.name, + ) ) return self.backend.db.fetch(stmt)