Skip to content

Conversation

@maynetee
Copy link
Owner

@maynetee maynetee commented Feb 3, 2026

The get_overview_stats endpoint in app/api/stats.py executes 4 separate sequential await db.execute() calls to compute total_messages, active_channels, messages_24h, and duplicates_24h. Each query independently joins through user_channels for user scoping, causing 4 full round-trips to the database. PostgreSQL's FILTER clause or CASE-based conditional aggregation can collapse the 3 message counts into a single query, reducing total DB round-trips from 4 to 2 (one for messages, one for channels).

Mendel and others added 3 commits February 3, 2026 08:59
…nditional aggregation

- Import case from sqlalchemy for conditional aggregation
- Consolidate total_messages, messages_24h, and duplicates_24h into single query
- Use func.sum(case(...)) pattern for conditional counts
- Reduce database round-trips from 4 to 2
- Keep active_channels query separate (different table)
- Maintain user isolation via user_channels join

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
When the database has no messages, func.sum() returns NULL instead of 0.
Wrap conditional aggregations with func.coalesce() to convert NULL to 0,
ensuring the API always returns integers as expected.

This follows the existing pattern in the codebase (see stats.py lines 236, 242).

Fixes: test_overview_stats_empty_database

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@maynetee maynetee merged commit 6c7ee6a into main Feb 3, 2026
0 of 2 checks passed
@maynetee maynetee deleted the auto-claude/021-consolidate-stats-overview-into-single-query-using branch February 3, 2026 14:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants