perf(stats): combine three COUNT queries into one conditional aggregation
This commit is contained in:
parent
170c021b37
commit
51e20980db
@ -31,37 +31,23 @@ pub async fn get_post_stats() -> Result<PostStatsResponse, ServerFnError> {
|
|||||||
|
|
||||||
let client = get_conn().await.map_err(AppError::db_conn)?;
|
let client = get_conn().await.map_err(AppError::db_conn)?;
|
||||||
|
|
||||||
// 统计未删除文章总数。
|
// 通过单次条件聚合查询同时统计总数、草稿数与已发布数。
|
||||||
let total: i64 = client
|
let row = client
|
||||||
.query_one("SELECT COUNT(*) FROM posts WHERE deleted_at IS NULL", &[])
|
|
||||||
.await
|
|
||||||
.map_err(AppError::query)?
|
|
||||||
.get(0);
|
|
||||||
|
|
||||||
// 统计草稿数量。
|
|
||||||
let drafts: i64 = client
|
|
||||||
.query_one(
|
.query_one(
|
||||||
"SELECT COUNT(*) FROM posts WHERE deleted_at IS NULL AND status = 'draft'",
|
"SELECT
|
||||||
|
COUNT(*) FILTER (WHERE deleted_at IS NULL) AS total,
|
||||||
|
COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 'draft') AS drafts,
|
||||||
|
COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 'published') AS published
|
||||||
|
FROM posts",
|
||||||
&[],
|
&[],
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(AppError::query)?
|
.map_err(AppError::query)?;
|
||||||
.get(0);
|
|
||||||
|
|
||||||
// 统计已发布数量。
|
|
||||||
let published: i64 = client
|
|
||||||
.query_one(
|
|
||||||
"SELECT COUNT(*) FROM posts WHERE deleted_at IS NULL AND status = 'published'",
|
|
||||||
&[],
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(AppError::query)?
|
|
||||||
.get(0);
|
|
||||||
|
|
||||||
let stats = PostStats {
|
let stats = PostStats {
|
||||||
total,
|
total: row.get("total"),
|
||||||
drafts,
|
drafts: row.get("drafts"),
|
||||||
published,
|
published: row.get("published"),
|
||||||
};
|
};
|
||||||
crate::cache::set_post_stats(stats.clone()).await;
|
crate::cache::set_post_stats(stats.clone()).await;
|
||||||
Ok(PostStatsResponse { stats })
|
Ok(PostStatsResponse { stats })
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user