aggregate data

This commit is contained in:
Mateusz Gruszczyński
2026-07-28 11:43:40 +02:00
parent 176e7e4554
commit 916807bb5c
4 changed files with 94 additions and 11 deletions
+48
View File
@@ -99,6 +99,15 @@ pub struct Revision {
pub owner_map: String,
}
#[derive(Debug, Clone)]
pub struct NoteStats {
pub note_id: i64,
pub participant_count: i64,
pub file_count: i64,
pub file_size_bytes: i64,
pub revision_count: i64,
}
pub async fn find_workspace(pool: &Database, slug: &str) -> Result<Option<Workspace>, sqlx::Error> {
sqlx::query_as::<_, Workspace>(queries::get(pool.kind(), queries::Q001))
.bind(slug)
@@ -164,6 +173,45 @@ pub async fn list_notes(pool: &Database, workspace_id: i64) -> Result<Vec<Note>,
.await
}
pub async fn list_note_stats(
pool: &Database,
workspace_id: i64,
) -> Result<Vec<NoteStats>, sqlx::Error> {
let placeholder = match pool.kind() {
DatabaseKind::Postgres => "$1",
DatabaseKind::Sqlite | DatabaseKind::MySql => "?",
};
let query = format!(
"SELECT n.id AS note_id, \
((SELECT COUNT(DISTINCT r.author) FROM note_revisions r \
WHERE r.note_id = n.id AND r.author IS NOT NULL AND TRIM(r.author) <> '') + \
CASE WHEN n.created_by IS NOT NULL AND TRIM(n.created_by) <> '' AND NOT EXISTS (\
SELECT 1 FROM note_revisions r WHERE r.note_id = n.id AND r.author = n.created_by\
) THEN 1 ELSE 0 END) AS participant_count, \
(SELECT COUNT(*) FROM note_files f WHERE f.note_id = n.id) AS file_count, \
(SELECT COALESCE(SUM(f.size_bytes), 0) FROM note_files f WHERE f.note_id = n.id) AS file_size_bytes, \
(SELECT COUNT(*) FROM note_revisions r WHERE r.note_id = n.id) AS revision_count \
FROM notes n WHERE n.workspace_id = {placeholder}"
);
let rows = sqlx::query(&query)
.bind(workspace_id)
.fetch_all(pool.pool())
.await?;
rows.into_iter()
.map(|row| {
Ok(NoteStats {
note_id: row.try_get("note_id")?,
participant_count: row.try_get("participant_count")?,
file_count: row.try_get("file_count")?,
file_size_bytes: row.try_get("file_size_bytes")?,
revision_count: row.try_get("revision_count")?,
})
})
.collect()
}
pub async fn find_note(
pool: &Database,
workspace_id: i64,