perf: connection pooling, query consolidation, inline chart data, batch milestones

This commit is contained in:
Peter Stockings
2026-02-24 21:41:55 +11:00
parent 56168a182b
commit c76b4cd6fc
8 changed files with 219 additions and 88 deletions

View File

@@ -44,18 +44,24 @@ def progress_over_time():
where_sql = " AND ".join(where_clauses)
# Use CTE for first_weight instead of correlated subquery
rows = query(f"""
WITH first_weights AS (
SELECT DISTINCT ON (user_id) user_id, weight_kg AS first_weight
FROM checkins
ORDER BY user_id, checked_in_at ASC
)
SELECT
u.id AS user_id,
u.display_name,
u.username,
u.starting_weight_kg,
(SELECT weight_kg FROM checkins
WHERE user_id = u.id ORDER BY checked_in_at ASC LIMIT 1) AS first_weight,
fw.first_weight,
c.weight_kg,
c.checked_in_at
FROM checkins c
JOIN users u ON u.id = c.user_id
LEFT JOIN first_weights fw ON fw.user_id = u.id
WHERE {where_sql}
ORDER BY u.id, c.checked_in_at ASC
""", params)
@@ -144,17 +150,26 @@ def chart_data(user_id):
@login_required
def comparison():
"""Return all-user comparison data for bar charts."""
# Use CTE with window functions instead of 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,
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,
(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
uw.first_weight,
uw.current_weight
FROM users u
WHERE (SELECT COUNT(*) FROM checkins WHERE user_id = u.id) > 0
AND u.is_private = FALSE
JOIN user_weights uw ON uw.user_id = u.id AND uw.rn = 1
WHERE u.is_private = FALSE
ORDER BY u.display_name
""")