Skip to content

Force task switch every 2000 rows when creating objects #1939

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

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
10 changes: 6 additions & 4 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ Changelog
0.25
====

0.25.1 (unreleased)
------------------
Changed
^^^^^
- Force async task switch every 2000 rows when converting db objects to python objects to avoid blocking the event loop (#1939)

0.25.0
------
Fixed
Expand All @@ -24,10 +30,6 @@ Added
^^^^^
- `.only` supports selecting related fields, e.g. `.only("related__field")` (#1923)

Fixed
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed a duplicate

^^^^^
- Fix pydantic_model_creator incompatibility with Pydantic 2.11 (#1930)


0.24
====
Expand Down
9 changes: 8 additions & 1 deletion tortoise/backends/base/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
tuple[list, str, list, str, str, dict[str, str]],
] = {}

CHUNK_SIZE = 2000


class BaseExecutor:
FILTER_FUNC_OVERRIDE: dict[Callable, Callable] = {}
Expand Down Expand Up @@ -105,7 +107,12 @@ async def execute_select(
) -> list:
_, raw_results = await self.db.execute_query(sql, values)
instance_list = []
for row in raw_results:
for row_idx, row in enumerate(raw_results):
if row_idx != 0 and row_idx % CHUNK_SIZE == 0:
# Forcibly yield to the event loop to avoid blocking the event loop
# when selecting a large number of rows
await asyncio.sleep(0)

if self.select_related_idx:
_, current_idx, _, _, path = self.select_related_idx[0]
row_items = list(dict(row).items())
Expand Down