Files
zesdex/src/model/msglog/query.rs
T

34 lines
1.4 KiB
Rust
Raw Normal View History

//! Insert queries against the message log's `messages` table.
use rusqlite::{Connection, params};
use anyhow::Result;
use crate::dto::chat::message::{ChatMessage, Role};
/// Insert a chat message into the session's message log.
///
/// Flow: extract optional content/tool_call_id/tool_name → serialize
/// `tool_calls` to a JSON string if present → map `Role` to its string
/// column value → `INSERT` the row with the current timestamp.
///
/// Return: the new row's `rowid` on success, or the underlying error.
pub fn insert_message(conn: &Connection, session_id: &str, msg: &ChatMessage) -> Result<i64> {
let content = msg.content.as_deref();
let tool_call_id = msg.tool_call_id.as_deref();
let tool_name = msg.name.as_deref();
let tool_arguments = msg.tool_calls.as_ref().map(|calls| {
serde_json::to_string(calls).unwrap_or_default()
});
let created_at = chrono::Utc::now().timestamp_millis();
let role_str = match msg.role {
Role::User => "user",
Role::Assistant => "assistant",
Role::System => "system",
Role::Tool => "tool",
};
conn.execute(
"INSERT INTO messages (session_id, role, content, tool_call_id, tool_name, tool_arguments, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![session_id, role_str, content, tool_call_id, tool_name, tool_arguments, created_at],
)?;
Ok(conn.last_insert_rowid())
}