perf: connection pooling, query consolidation, inline chart data, batch milestones
This commit is contained in:
@@ -2,7 +2,7 @@ from flask import Blueprint, render_template
|
||||
from app.auth import login_required
|
||||
from app.db import query, query_one
|
||||
from app.config import SYDNEY_TZ
|
||||
from app.utils import calculate_streak, calculate_weight_change
|
||||
from app.utils import calculate_streaks_bulk, calculate_weight_change
|
||||
from datetime import timezone
|
||||
|
||||
bp = Blueprint("leaderboard", __name__)
|
||||
@@ -11,23 +11,38 @@ bp = Blueprint("leaderboard", __name__)
|
||||
@bp.route("/leaderboard")
|
||||
@login_required
|
||||
def index():
|
||||
# Get all users with their weight stats
|
||||
# Get all users with weight stats using window functions (no correlated subqueries)
|
||||
users = query("""
|
||||
WITH user_weights AS (
|
||||
SELECT
|
||||
user_id,
|
||||
FIRST_VALUE(weight_kg) OVER (PARTITION BY user_id ORDER BY checked_in_at ASC) AS first_weight,
|
||||
FIRST_VALUE(weight_kg) OVER (PARTITION BY user_id ORDER BY checked_in_at DESC) AS current_weight,
|
||||
COUNT(*) OVER (PARTITION BY user_id) AS total_checkins,
|
||||
MAX(checked_in_at) OVER (PARTITION BY user_id) AS last_checkin,
|
||||
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY checked_in_at DESC) AS rn
|
||||
FROM checkins
|
||||
)
|
||||
SELECT
|
||||
u.id,
|
||||
u.display_name,
|
||||
u.username,
|
||||
u.starting_weight_kg,
|
||||
u.goal_weight_kg,
|
||||
(SELECT weight_kg FROM checkins WHERE user_id = u.id ORDER BY checked_in_at ASC LIMIT 1) as first_weight,
|
||||
(SELECT weight_kg FROM checkins WHERE user_id = u.id ORDER BY checked_in_at DESC LIMIT 1) as current_weight,
|
||||
(SELECT COUNT(*) FROM checkins WHERE user_id = u.id) as total_checkins,
|
||||
(SELECT checked_in_at FROM checkins WHERE user_id = u.id ORDER BY checked_in_at DESC LIMIT 1) as last_checkin
|
||||
uw.first_weight,
|
||||
uw.current_weight,
|
||||
uw.total_checkins,
|
||||
uw.last_checkin
|
||||
FROM users u
|
||||
JOIN user_weights uw ON uw.user_id = u.id AND uw.rn = 1
|
||||
WHERE u.is_private = FALSE
|
||||
ORDER BY u.created_at
|
||||
""")
|
||||
|
||||
# Batch-compute streaks for all users in one query
|
||||
user_ids = [u["id"] for u in users]
|
||||
all_streaks = calculate_streaks_bulk(user_ids)
|
||||
|
||||
# Calculate rankings
|
||||
ranked = []
|
||||
for u in users:
|
||||
@@ -41,7 +56,7 @@ def index():
|
||||
total_to_lose = start_w - goal
|
||||
goal_progress = min(100, round((weight_lost / total_to_lose) * 100, 1)) if total_to_lose > 0 else 0
|
||||
|
||||
streak = calculate_streak(u["id"])
|
||||
streak = all_streaks.get(u["id"], {"current": 0, "best": 0})
|
||||
ranked.append({
|
||||
**u,
|
||||
"weight_lost": weight_lost,
|
||||
|
||||
Reference in New Issue
Block a user