Skip to main content

systemprompt_database/repository/
cleanup.rs

1use anyhow::Result;
2use sqlx::PgPool;
3
4#[derive(Debug)]
5pub struct CleanupRepository {
6    write_pool: PgPool,
7}
8
9impl CleanupRepository {
10    pub const fn new(pool: PgPool) -> Self {
11        Self { write_pool: pool }
12    }
13
14    pub const fn new_with_write_pool(write_pool: PgPool) -> Self {
15        Self { write_pool }
16    }
17
18    pub async fn delete_orphaned_logs(&self) -> Result<u64> {
19        let result = sqlx::query!(
20            r#"
21            DELETE FROM logs
22            WHERE user_id IS NOT NULL
23              AND user_id NOT IN (SELECT id FROM users)
24            "#
25        )
26        .execute(&self.write_pool)
27        .await?;
28        Ok(result.rows_affected())
29    }
30
31    pub async fn delete_orphaned_mcp_executions(&self) -> Result<u64> {
32        let result = sqlx::query!(
33            r#"
34            DELETE FROM mcp_tool_executions
35            WHERE context_id IS NOT NULL
36              AND context_id NOT IN (SELECT context_id FROM user_contexts)
37            "#
38        )
39        .execute(&self.write_pool)
40        .await?;
41        Ok(result.rows_affected())
42    }
43
44    pub async fn delete_old_logs(&self, days: i32) -> Result<u64> {
45        let cutoff = chrono::Utc::now() - chrono::Duration::days(i64::from(days));
46        let result = sqlx::query!("DELETE FROM logs WHERE timestamp < $1", cutoff)
47            .execute(&self.write_pool)
48            .await?;
49        Ok(result.rows_affected())
50    }
51
52    pub async fn delete_expired_oauth_tokens(&self) -> Result<u64> {
53        let result = sqlx::query!("DELETE FROM oauth_refresh_tokens WHERE expires_at < NOW()")
54            .execute(&self.write_pool)
55            .await?;
56        Ok(result.rows_affected())
57    }
58
59    pub async fn delete_expired_oauth_codes(&self) -> Result<u64> {
60        let result = sqlx::query!(
61            "DELETE FROM oauth_auth_codes WHERE expires_at < NOW() OR used_at IS NOT NULL"
62        )
63        .execute(&self.write_pool)
64        .await?;
65        Ok(result.rows_affected())
66    }
67}