Skip to content

Commit 3885c44

Browse files
committed
fix: parallelize user dependency cleanup deletes
1 parent 88a8832 commit 3885c44

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

app/db/crud/user.py

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
from copy import deepcopy
23
from datetime import UTC, datetime, timedelta, timezone
34
from enum import Enum
@@ -8,6 +9,7 @@
89
from sqlalchemy.orm import joinedload, selectinload
910
from sqlalchemy.sql.functions import coalesce
1011

12+
from app.db.base import GetDB, IS_SQLITE
1113
from app.db.compiles_types import DateDiff
1214
from app.db.models import (
1315
Admin,
@@ -39,8 +41,6 @@
3941
from .group import get_groups_by_ids
4042

4143
_USER_AGENT_MAX_LEN = UserSubscriptionUpdate.__table__.columns.user_agent.type.length or 512
42-
43-
4444
async def load_user_attrs(
4545
user: User,
4646
*,
@@ -696,12 +696,32 @@ async def _delete_user_dependencies(db: AsyncSession, user_ids: list[int]):
696696
if not user_ids:
697697
return
698698

699-
await db.execute(delete(NodeUserUsage).where(NodeUserUsage.user_id.in_(user_ids)))
700-
await db.execute(delete(NotificationReminder).where(NotificationReminder.user_id.in_(user_ids)))
701-
await db.execute(delete(UserSubscriptionUpdate).where(UserSubscriptionUpdate.user_id.in_(user_ids)))
702-
await db.execute(delete(UserUsageResetLogs).where(UserUsageResetLogs.user_id.in_(user_ids)))
703-
await db.execute(delete(NextPlan).where(NextPlan.user_id.in_(user_ids)))
704-
await db.execute(users_groups_association.delete().where(users_groups_association.c.user_id.in_(user_ids)))
699+
statements = [
700+
delete(NodeUserUsage).where(NodeUserUsage.user_id.in_(user_ids)),
701+
delete(NotificationReminder).where(NotificationReminder.user_id.in_(user_ids)),
702+
delete(UserSubscriptionUpdate).where(UserSubscriptionUpdate.user_id.in_(user_ids)),
703+
delete(UserUsageResetLogs).where(UserUsageResetLogs.user_id.in_(user_ids)),
704+
delete(NextPlan).where(NextPlan.user_id.in_(user_ids)),
705+
users_groups_association.delete().where(users_groups_association.c.user_id.in_(user_ids)),
706+
]
707+
708+
if IS_SQLITE:
709+
for stmt in statements:
710+
await db.execute(stmt)
711+
return
712+
713+
async def execute_in_isolated_session(statement):
714+
async with GetDB() as isolated_db:
715+
await isolated_db.execute(statement)
716+
await isolated_db.commit()
717+
718+
results = await asyncio.gather(
719+
*(execute_in_isolated_session(stmt) for stmt in statements),
720+
return_exceptions=True,
721+
)
722+
for result in results:
723+
if isinstance(result, Exception):
724+
raise result
705725

706726

707727
async def remove_user(db: AsyncSession, db_user: User) -> User:

0 commit comments

Comments
 (0)