use serde_json::Value;
use std::collections::BTreeMap;
pub type Parameters = BTreeMap<String, Value>;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParametersBuilder {
entries: Parameters,
}
impl ParametersBuilder {
pub fn new() -> Self {
ParametersBuilder::default()
}
pub fn set(mut self, name: impl Into<String>, value: Value) -> Self {
self.entries.insert(name.into(), value);
self
}
pub fn build(&self) -> Parameters {
self.entries.clone()
}
}
pub fn parameters(pairs: &[(&str, Value)]) -> Parameters {
pairs
.iter()
.map(|(name, value)| ((*name).to_string(), value.clone()))
.collect()
}
#[derive(Debug, Clone, PartialEq)]
pub enum DbError {
QueryFailed(String),
}
impl std::fmt::Display for DbError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DbError::QueryFailed(message) => write!(f, "query failed: {message}"),
}
}
}
impl std::error::Error for DbError {}
pub trait Connection {
fn query_grids(&self, sql: &str, params: &Parameters) -> Result<Vec<Vec<crate::Row>>, DbError>;
fn execute(&mut self, sql: &str, params: &Parameters) -> Result<usize, DbError>;
fn execute_scalar_value(&self, sql: &str, params: &Parameters) -> Result<Value, DbError>;
}
#[derive(Debug, Clone)]
pub struct ExecutedCommand {
pub sql: String,
pub params: Parameters,
}
#[derive(Debug, Clone)]
pub struct InMemoryConnection {
grids: Vec<Vec<crate::Row>>,
affected: usize,
scalar: Value,
pub executed: std::cell::RefCell<Vec<ExecutedCommand>>,
}
impl InMemoryConnection {
pub fn with_grids(grids: Vec<Vec<crate::Row>>) -> Self {
InMemoryConnection {
grids,
affected: 0,
scalar: Value::Null,
executed: std::cell::RefCell::new(Vec::new()),
}
}
pub fn with_affected(mut self, affected: usize) -> Self {
self.affected = affected;
self
}
pub fn with_scalar(mut self, scalar: Value) -> Self {
self.scalar = scalar;
self
}
}
impl Connection for InMemoryConnection {
fn query_grids(&self, sql: &str, params: &Parameters) -> Result<Vec<Vec<crate::Row>>, DbError> {
self.executed.borrow_mut().push(ExecutedCommand {
sql: sql.to_string(),
params: params.clone(),
});
Ok(self.grids.clone())
}
fn execute(&mut self, sql: &str, params: &Parameters) -> Result<usize, DbError> {
self.executed.borrow_mut().push(ExecutedCommand {
sql: sql.to_string(),
params: params.clone(),
});
Ok(self.affected)
}
fn execute_scalar_value(&self, sql: &str, params: &Parameters) -> Result<Value, DbError> {
self.executed.borrow_mut().push(ExecutedCommand {
sql: sql.to_string(),
params: params.clone(),
});
Ok(self.scalar.clone())
}
}