server/posts: optimized query for fetching post relations

This was taking multiple seconds, now it's <200ms for the whole
/post/ api request. Updating relations is still slow, but that doesn't
impact user experience.
This commit is contained in:
Eva
2023-05-22 17:32:01 +02:00
parent f12e28855b
commit 362a86712a
2 changed files with 8 additions and 4 deletions

View File

@ -264,8 +264,8 @@ class PostSerializer(serialization.BaseSerializer):
{
post["id"]: post
for post in [
serialize_micro_post(rel, self.auth_user)
for rel in self.post.relations
serialize_micro_post(try_get_post_by_id(rel.child_id), self.auth_user)
for rel in get_post_relations(self.post.post_id)
]
}.values(),
key=lambda post: post["id"],
@ -363,6 +363,10 @@ def get_post_count() -> int:
return db.session.query(sa.func.count(model.Post.post_id)).one()[0]
def get_post_relations(post_id: int) -> List[model.Post]:
return db.session.query(model.PostRelation).filter(model.PostRelation.parent_id == post_id).all()
def try_get_post_by_id(post_id: int) -> Optional[model.Post]:
return (
db.session.query(model.Post)

View File

@ -4,7 +4,7 @@ from typing import Any, Callable, Dict, Optional
import sqlalchemy as sa
from szurubooru import db, model
from szurubooru.func import diff, net, users
from szurubooru.func import diff, net, users, posts
def get_tag_category_snapshot(category: model.TagCategory) -> Dict[str, Any]:
@ -53,7 +53,7 @@ def get_post_snapshot(post: model.Post) -> Dict[str, Any]:
"flags": post.flags,
"featured": post.is_featured,
"tags": sorted([tag.first_name for tag in post.tags]),
"relations": sorted([rel.post_id for rel in post.relations]),
"relations": sorted([rel.child_id for rel in posts.get_post_relations(post.post_id)]),
"notes": sorted(
[
{