use std::sync::Arc;
use agent_sdk_core::AgentError;
use serde_json::Value;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PostgresSqlRequest {
pub statement: String,
pub params: Vec<Value>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PostgresSqlResponse {
pub rows: Vec<Value>,
pub affected: u64,
}
impl PostgresSqlResponse {
pub fn rows(rows: impl IntoIterator<Item = Value>) -> Self {
Self {
rows: rows.into_iter().collect(),
affected: 0,
}
}
pub fn affected(affected: u64) -> Self {
Self {
rows: Vec::new(),
affected,
}
}
}
pub trait PostgresSqlTransport: Send + Sync {
fn execute(&self, request: PostgresSqlRequest) -> Result<PostgresSqlResponse, AgentError>;
}
#[derive(Clone, Debug)]
pub struct PostgresStoreConfig {
pub schema: String,
pub store_scope: String,
}
impl PostgresStoreConfig {
pub fn new(schema: impl Into<String>, store_scope: impl Into<String>) -> Self {
Self {
schema: schema.into(),
store_scope: store_scope.into(),
}
}
}
#[derive(Clone)]
pub struct PostgresStoreClient {
pub(crate) config: PostgresStoreConfig,
transport: Arc<dyn PostgresSqlTransport>,
}
impl PostgresStoreClient {
pub fn new(config: PostgresStoreConfig, transport: Arc<dyn PostgresSqlTransport>) -> Self {
Self { config, transport }
}
pub(crate) fn execute(
&self,
statement: impl Into<String>,
params: Vec<Value>,
) -> Result<PostgresSqlResponse, AgentError> {
self.transport.execute(PostgresSqlRequest {
statement: statement.into(),
params,
})
}
pub(crate) fn table(&self, table: &str) -> String {
format!("{}.{}", self.config.schema, table)
}
pub(crate) fn scope(&self) -> Value {
Value::String(self.config.store_scope.clone())
}
}