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