Files
mylinspirer/src/db/repositories/commands.rs

79 lines
2.0 KiB
Rust

use crate::db::models::Command;
use sqlx::SqlitePool;
pub async fn list_all(pool: &SqlitePool) -> anyhow::Result<Vec<Command>> {
let commands = sqlx::query_as::<_, Command>("SELECT * FROM commands ORDER BY received_at DESC")
.fetch_all(pool)
.await?;
Ok(commands)
}
pub async fn list_by_status(pool: &SqlitePool, status: &str) -> anyhow::Result<Vec<Command>> {
let commands = sqlx::query_as::<_, Command>(
"SELECT * FROM commands WHERE status = ? ORDER BY received_at DESC",
)
.bind(status)
.fetch_all(pool)
.await?;
Ok(commands)
}
pub async fn find_by_id(pool: &SqlitePool, id: i64) -> anyhow::Result<Option<Command>> {
let command = sqlx::query_as::<_, Command>("SELECT * FROM commands WHERE id = ?")
.bind(id)
.fetch_optional(pool)
.await?;
Ok(command)
}
pub async fn insert(pool: &SqlitePool, command_json: &str, status: &str) -> anyhow::Result<i64> {
let result = sqlx::query("INSERT INTO commands (command_json, status) VALUES (?, ?)")
.bind(command_json)
.bind(status)
.execute(pool)
.await?;
Ok(result.last_insert_rowid())
}
pub async fn update_status(
pool: &SqlitePool,
id: i64,
status: &str,
notes: Option<&str>,
) -> anyhow::Result<()> {
sqlx::query(
"UPDATE commands SET status = ?, processed_at = CURRENT_TIMESTAMP, notes = ? WHERE id = ?",
)
.bind(status)
.bind(notes)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_old(pool: &SqlitePool, days: i64) -> anyhow::Result<u64> {
let result = sqlx::query(
"DELETE FROM commands WHERE status IN ('verified', 'rejected')
AND processed_at < datetime('now', '-' || ? || ' days')",
)
.bind(days)
.execute(pool)
.await?;
Ok(result.rows_affected())
}
pub async fn clear_verified(pool: &SqlitePool) -> anyhow::Result<()> {
sqlx::query("DELETE FROM commands WHERE status = 'verified'")
.execute(pool)
.await?;
Ok(())
}