From df25eaf9051f2aea0805e42b2400f7a35a2a5297 Mon Sep 17 00:00:00 2001 From: Untone Date: Wed, 7 Aug 2024 07:27:56 +0300 Subject: [PATCH] query-fitness --- resolvers/reaction.py | 20 ++++++++++++-------- resolvers/reader.py | 8 +++----- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/resolvers/reaction.py b/resolvers/reaction.py index 53cbfed7..12e9b5ad 100644 --- a/resolvers/reaction.py +++ b/resolvers/reaction.py @@ -21,15 +21,19 @@ from services.viewed import ViewedStorage def add_reaction_stat_columns(q, aliased_reaction): - q = q.outerjoin(aliased_reaction, aliased_reaction.deleted_at.is_(None)).add_columns( - func.sum(aliased_reaction.id).label("reacted_stat"), - func.sum(case((aliased_reaction.kind == str(ReactionKind.COMMENT.value), 1), else_=0)).label("comments_stat"), - func.sum(case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)).label("likes_stat"), - func.sum(case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)).label("dislikes_stat"), - func.max(aliased_reaction.created_at).label("last_comment_stat"), + reaction_subquery = ( + select( + aliased_reaction.shout, + func.count(aliased_reaction.id).label("reacted_stat"), + func.count(case([(aliased_reaction.kind == str(ReactionKind.COMMENT.value), 1)])).label("comments_stat"), + func.count(case([(aliased_reaction.kind == str(ReactionKind.LIKE.value), 1)])).label("likes_stat"), + func.count(case([(aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1)])).label("dislikes_stat"), + func.max(aliased_reaction.created_at).label("last_comment_stat"), + ) + .where(aliased_reaction.deleted_at.is_(None)) + .group_by(aliased_reaction.shout) ) - - return q + return q.outerjoin(reaction_subquery, Shout.id == reaction_subquery.c.shout) def is_featured_author(session, author_id): diff --git a/resolvers/reader.py b/resolvers/reader.py index da4ea632..8ea42958 100644 --- a/resolvers/reader.py +++ b/resolvers/reader.py @@ -38,16 +38,14 @@ def filter_my(info, session, q): user_id = info.context.get("user_id") reader_id = info.context.get("author", {}).get("id") if user_id and reader_id: - # Предварительный расчет ID для автора и темы reader_followed_authors = select(AuthorFollower.author).where(AuthorFollower.follower == reader_id) reader_followed_topics = select(TopicFollower.topic).where(TopicFollower.follower == reader_id) - # Используйте подзапросы для фильтрации subquery = ( select(Shout.id) - .where(Shout.id == ShoutAuthor.shout) - .where(Shout.id == ShoutTopic.shout) - .where((ShoutAuthor.author.in_(reader_followed_authors)) | (ShoutTopic.topic.in_(reader_followed_topics))) + .join(ShoutAuthor, ShoutAuthor.shout == Shout.id) + .join(ShoutTopic, ShoutTopic.shout == Shout.id) + .where(ShoutAuthor.author.in_(reader_followed_authors) | ShoutTopic.topic.in_(reader_followed_topics)) ) q = q.filter(Shout.id.in_(subquery)) return q, reader_id