use std::str::FromStr;
use async_trait::async_trait;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::SqlitePool;
use crate::ledger::{LedgerError, LedgerStore, UsageEntry};
pub struct SqliteLedger {
pool: SqlitePool,
}
impl SqliteLedger {
pub async fn connect(dsn: &str) -> Result<Self, LedgerError> {
let opts = SqliteConnectOptions::from_str(dsn)
.map_err(|e| LedgerError::Backend(e.to_string()))?
.create_if_missing(true);
let pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(opts)
.await
.map_err(|e| LedgerError::Backend(e.to_string()))?;
sqlx::raw_sql(include_str!("../../migrations/0001_usage_events.sql"))
.execute(&pool)
.await
.map_err(|e| LedgerError::Backend(e.to_string()))?;
let _ = sqlx::query("ALTER TABLE usage_events ADD COLUMN user_id TEXT")
.execute(&pool)
.await;
Ok(Self { pool })
}
}
#[async_trait]
impl LedgerStore for SqliteLedger {
async fn record(&self, e: &UsageEntry) -> Result<(), LedgerError> {
sqlx::query(
"INSERT INTO usage_events \
(ts, tenant, workspace, user_id, route, provider, model, lane, \
input_tokens, output_tokens, cost_usd, request_id, status) \
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
)
.bind(e.ts.to_rfc3339())
.bind(&e.tenant)
.bind(&e.workspace)
.bind(&e.user)
.bind(&e.route)
.bind(&e.provider)
.bind(&e.model)
.bind(&e.lane)
.bind(e.input_tokens as i64)
.bind(e.output_tokens as i64)
.bind(e.cost_usd)
.bind(&e.request_id)
.bind(&e.status)
.execute(&self.pool)
.await
.map_err(|e| LedgerError::Backend(e.to_string()))?;
Ok(())
}
}