author-stat-fix
All checks were successful
Deploy on push / deploy (push) Successful in 1m22s

This commit is contained in:
Untone 2025-02-10 18:38:26 +03:00
parent 759520f024
commit 9671ef2508
2 changed files with 23 additions and 27 deletions

View File

@ -17,7 +17,6 @@ from cache.revalidator import revalidation_manager
from services.exception import ExceptionHandlerMiddleware
from services.redis import redis
from services.schema import create_all_tables, resolvers
from services.db import engine
from services.search import search_service
from services.viewed import ViewedStorage
from services.webhook import WebhookEndpoint, create_webhook_endpoint

View File

@ -63,38 +63,35 @@ def add_author_stat_columns(q):
:param q: SQL-запрос для получения авторов.
:return: Запрос с добавленными колонками статистики.
"""
# Алиасирование таблиц для предотвращения конфликтов имен
aliased_shout_author = aliased(ShoutAuthor)
aliased_shout = aliased(Shout)
aliased_author_follower = aliased(AuthorFollower)
# Подзапрос для подсчета публикаций
shouts_subq = (
select(func.count(distinct(Shout.id)))
.select_from(ShoutAuthor)
.join(Shout, and_(
Shout.id == ShoutAuthor.shout,
Shout.deleted_at.is_(None)
))
.where(ShoutAuthor.author == Author.id)
.scalar_subquery()
)
# Применение фильтров и добавление колонок статистики
# Подзапрос для подсчета подписчиков
followers_subq = (
select(func.count(distinct(AuthorFollower.follower)))
.where(AuthorFollower.author == Author.id)
.scalar_subquery()
)
# Основной запрос
q = (
q.select_from(Author)
.join(
aliased_shout_author,
aliased_shout_author.author == Author.id,
)
.join(
aliased_shout,
and_(
aliased_shout.id == aliased_shout_author.shout,
aliased_shout.deleted_at.is_(None),
),
)
.add_columns(
func.count(distinct(aliased_shout.id)).label("shouts_stat")
) # Подсчет уникальных публикаций автора
shouts_subq.label("shouts_stat"),
followers_subq.label("followers_stat")
)
.group_by(Author.id)
)
# Добавляем количество подписчиков автора
q = q.outerjoin(aliased_author_follower, aliased_author_follower.author == Author.id).add_columns(
func.count(distinct(aliased_author_follower.follower)).label("followers_stat")
)
# Группировка по идентификатору автора
q = q.group_by(Author.id)
return q