Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pagination): Performance optimization - DIA-74957 #221

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions fastapi_sqla/async_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Annotated, Optional, Union, cast

from fastapi import Depends, Query
from sqlalchemy.sql import Select, func, select
from sqlalchemy.sql import Select, func

from fastapi_sqla.async_sqla import AsyncSessionDependency, SqlaAsyncSession
from fastapi_sqla.models import Meta, Page
Expand All @@ -19,8 +19,11 @@


async def default_query_count(session: SqlaAsyncSession, query: Select) -> int:
result = await session.execute(select(func.count()).select_from(query.subquery()))
return cast(int, result.scalar())
count_query = query.add_columns(
func.count().over().label("overall_count")
).order_by(None)
result = await session.execute(count_query)
return cast(int, result.first().overall_count) # type: ignore


async def paginate_query(
Expand Down
12 changes: 8 additions & 4 deletions fastapi_sqla/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from fastapi import Depends, Query
from sqlalchemy.orm import Query as LegacyQuery
from sqlalchemy.sql import Select, func, select
from sqlalchemy.sql import Select, func

from fastapi_sqla.models import Meta, Page
from fastapi_sqla.sqla import _DEFAULT_SESSION_KEY, SessionDependency, SqlaSession
Expand All @@ -32,9 +32,13 @@ def default_query_count(session: SqlaSession, query: DbQuery) -> int:
elif isinstance(query, Select):
result = cast(
int,
session.execute(
select(func.count()).select_from(query.subquery())
).scalar(),
session.execute( # type: ignore
query.add_columns(func.count().over().label("overall_count")).order_by(
None
)
)
.first()
.overall_count,
)

else: # pragma: no cover
Expand Down