perf: 优化 dashboard 的查询性能 (#393)

This commit is contained in:
ᴀᴍᴛᴏᴀᴇʀ
2025-07-12 16:06:16 +08:00
committed by GitHub
parent 87fb597ba4
commit 29d78dabdd
3 changed files with 54 additions and 26 deletions
@@ -34,35 +34,25 @@ async fn get_dashboard(
// 用 SeaORM 太复杂了,直接写个裸 SQL // 用 SeaORM 太复杂了,直接写个裸 SQL
" "
SELECT SELECT
dates.day AS day, dates.day AS day,
COUNT(video.id) AS cnt COUNT(video.id) AS cnt
FROM FROM
( (
SELECT SELECT
STRFTIME( STRFTIME('%Y-%m-%d', DATE('now', '-' || n || ' days', 'localtime')) AS day,
'%Y-%m-%d', DATETIME(DATE('now', '-' || n || ' days', 'localtime'), 'utc') AS start_utc_datetime,
DATE('now', '-' || n || ' days', 'localtime')) AS day DATETIME(DATE('now', '-' || n || ' days', '+1 day', 'localtime'), 'utc') AS end_utc_datetime
FROM FROM
( (
SELECT SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
0 AS n UNION ALL )
SELECT ) AS dates
1 UNION ALL LEFT JOIN
SELECT video ON video.created_at >= dates.start_utc_datetime AND video.created_at < dates.end_utc_datetime
2 UNION ALL
SELECT
3 UNION ALL
SELECT
4 UNION ALL
SELECT
5 UNION ALL
SELECT
6)) AS dates
LEFT JOIN video ON STRFTIME('%Y-%m-%d', video.created_at, 'localtime') = dates.day
GROUP BY GROUP BY
dates.day dates.day
ORDER BY ORDER BY
dates.day; dates.day;
" "
)) ))
.all(db.as_ref()), .all(db.as_ref()),
+2
View File
@@ -7,6 +7,7 @@ mod m20240724_161008_submission;
mod m20250122_062926_add_latest_row_at; mod m20250122_062926_add_latest_row_at;
mod m20250612_090826_add_enabled; mod m20250612_090826_add_enabled;
mod m20250613_043257_add_config; mod m20250613_043257_add_config;
mod m20250712_080013_add_video_created_at_index;
pub struct Migrator; pub struct Migrator;
@@ -21,6 +22,7 @@ impl MigratorTrait for Migrator {
Box::new(m20250122_062926_add_latest_row_at::Migration), Box::new(m20250122_062926_add_latest_row_at::Migration),
Box::new(m20250612_090826_add_enabled::Migration), Box::new(m20250612_090826_add_enabled::Migration),
Box::new(m20250613_043257_add_config::Migration), Box::new(m20250613_043257_add_config::Migration),
Box::new(m20250712_080013_add_video_created_at_index::Migration),
] ]
} }
} }
@@ -0,0 +1,36 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_index(
Index::create()
.table(Video::Table)
.name("video_created_at_index")
.col(Video::CreatedAt)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_index(
Index::drop()
.table(Video::Table)
.name("video_created_at_index")
.to_owned(),
)
.await
}
}
#[derive(DeriveIden)]
enum Video {
Table,
CreatedAt,
}