use aidaemon_channels::{ApprovalStore, StoredApproval};
use aidaemon_core::StoreError;
use async_trait::async_trait;
use sqlx::{Row, SqlitePool};
use crate::{Error, NOW, SqliteStore};
#[derive(Debug, Clone)]
pub struct SqliteApprovalStore {
pool: SqlitePool,
}
impl SqliteApprovalStore {
pub fn new(store: &SqliteStore) -> Self {
Self {
pool: store.pool().clone(),
}
}
}
#[async_trait]
impl ApprovalStore for SqliteApprovalStore {
async fn save(&self, approval: &StoredApproval) -> Result<(), StoreError> {
let record = serde_json::to_string(approval).map_err(Error::from)?;
sqlx::query(sqlx::AssertSqlSafe(format!(
"INSERT INTO channel_approvals
(prompt_id, session_id, channel, conversation_id, expires_at_ms, record, saved_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, {NOW})
ON CONFLICT (prompt_id) DO UPDATE SET
session_id = excluded.session_id,
channel = excluded.channel,
conversation_id = excluded.conversation_id,
expires_at_ms = excluded.expires_at_ms,
record = excluded.record,
saved_at = excluded.saved_at"
)))
.bind(&approval.prompt_id)
.bind(&approval.session_id)
.bind(&approval.channel)
.bind(&approval.conversation.id)
.bind(i64::try_from(approval.expires_at_ms).unwrap_or(i64::MAX))
.bind(record)
.execute(&self.pool)
.await
.map_err(Error::from)?;
Ok(())
}
async fn remove(&self, prompt_id: &str) -> Result<(), StoreError> {
sqlx::query("DELETE FROM channel_approvals WHERE prompt_id = ?1")
.bind(prompt_id)
.execute(&self.pool)
.await
.map_err(Error::from)?;
Ok(())
}
async fn load_all(&self) -> Result<Vec<StoredApproval>, StoreError> {
let rows = sqlx::query("SELECT record FROM channel_approvals ORDER BY saved_at, prompt_id")
.fetch_all(&self.pool)
.await
.map_err(Error::from)?;
Ok(rows
.iter()
.filter_map(|row| {
let text: String = row.get("record");
serde_json::from_str(&text).ok()
})
.collect())
}
}