WIP on persisting chat history on daemon
This commit is contained in:
83
crates/daemon/src/chatpersistence.rs
Normal file
83
crates/daemon/src/chatpersistence.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use anyhow::Result;
|
||||
use directories::ProjectDirs;
|
||||
use sqlx::sqlite::SqliteConnectOptions;
|
||||
use sqlx::Row;
|
||||
use sqlx::SqlitePool;
|
||||
use tokio::fs;
|
||||
use tonic::async_trait;
|
||||
|
||||
pub struct ChatMessage {
|
||||
pub id: i64,
|
||||
pub text: String,
|
||||
pub is_user: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ChatRepository {
|
||||
async fn save_message(&self, text: &str, is_user: &bool) -> Result<()>;
|
||||
async fn get_all_messages(&self) -> Result<Vec<ChatMessage>>;
|
||||
}
|
||||
|
||||
pub struct SqliteChatRepository {
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
impl SqliteChatRepository {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let project_dirs = ProjectDirs::from("com", "jarno", "wsagent")
|
||||
.ok_or_else(|| anyhow::anyhow!("Could not find home directory!"))?;
|
||||
let config_dir = project_dirs.config_dir();
|
||||
fs::create_dir_all(config_dir).await?;
|
||||
let db_path = config_dir.join("agent.db");
|
||||
let connection_str = format!("sqlite:{}", db_path.display());
|
||||
println!("Connection string: {}", connection_str);
|
||||
|
||||
let pool = SqlitePool::connect_with(
|
||||
SqliteConnectOptions::new()
|
||||
.filename(&db_path)
|
||||
.create_if_missing(true),
|
||||
)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS message (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
text TEXT NOT NULL,
|
||||
is_user BOOL NOT NULL
|
||||
)",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
Ok(Self { pool })
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ChatRepository for SqliteChatRepository {
|
||||
async fn save_message(&self, text: &str, is_user: &bool) -> Result<()> {
|
||||
sqlx::query("INSERT INTO messages (text, is_user) values (?, ?)")
|
||||
.bind(text)
|
||||
.bind(is_user)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_all_messages(&self) -> Result<Vec<ChatMessage>> {
|
||||
let rows = sqlx::query("SELECT id, text, is_user FROM messages ORDER BY id DESC LIMIT 10")
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
|
||||
let messages = rows
|
||||
.into_iter()
|
||||
.map(|row| ChatMessage {
|
||||
id: row.get(0),
|
||||
text: row.get(1),
|
||||
is_user: row.get(2),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(messages)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user