Skip to content

Commit 5872b40

Browse files
committed
fix(db): optimize N+1 queries in collection endpoints using eager loading
1 parent 33b9e3e commit 5872b40

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

‎backend/app.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from flask_limiter import Limiter
1111
from flask_limiter.errors import RateLimitExceeded
1212
from flask_limiter.util import get_remote_address
13-
from sqlalchemy.orm import joinedload
13+
from sqlalchemy.orm import joinedload, selectinload
1414
from flask_migrate import Migrate
1515
from flask_wtf.csrf import CSRFProtect, generate_csrf, CSRFError
1616
from sqlalchemy.exc import SQLAlchemyError
@@ -2114,7 +2114,9 @@ def get_collections():
21142114
return forbidden_error("Unauthorized")
21152115

21162116
try:
2117-
collections = Collection.query.filter_by(user_id=user_id).order_by(Collection.created_at.desc()).all()
2117+
collections = Collection.query.options(
2118+
selectinload(Collection.items)
2119+
).filter_by(user_id=user_id).order_by(Collection.created_at.desc()).all()
21182120
return jsonify({"collections": [c.to_dict() for c in collections]}), 200
21192121
except Exception as e:
21202122
return jsonify({"error": str(e)}), 500
@@ -2127,7 +2129,9 @@ def get_collection(collection_id):
21272129
current_user_id = get_jwt_identity()
21282130

21292131
try:
2130-
collection = Collection.query.get(collection_id)
2132+
collection = Collection.query.options(
2133+
selectinload(Collection.items).joinedload(CollectionItem.book)
2134+
).get(collection_id)
21312135
if not collection:
21322136
return jsonify({"error": "Collection not found"}), 404
21332137

@@ -2302,7 +2306,10 @@ def get_public_collections():
23022306
limit = request.args.get('limit', 20, type=int)
23032307
offset = request.args.get('offset', 0, type=int)
23042308

2305-
collections = Collection.query.filter_by(is_public=True).order_by(
2309+
collections = Collection.query.options(
2310+
joinedload(Collection.user),
2311+
selectinload(Collection.items)
2312+
).filter_by(is_public=True).order_by(
23062313
Collection.created_at.desc()
23072314
).offset(offset).limit(limit).all()
23082315

@@ -2311,8 +2318,7 @@ def get_public_collections():
23112318
result = []
23122319
for c in collections:
23132320
collection_data = c.to_dict()
2314-
user = User.query.get(c.user_id)
2315-
collection_data['owner_username'] = user.username if user else "Unknown"
2321+
collection_data['owner_username'] = c.user.username if c.user else "Unknown"
23162322
result.append(collection_data)
23172323

23182324
return jsonify({"collections": result, "total": total, "limit": limit, "offset": offset}), 200

0 commit comments

Comments
 (0)