use std::collections::HashMap;
use crate::{DbResult, DbError};
pub struct SqlTemplate {
templates: HashMap<String, String>,
}
impl SqlTemplate {
pub fn new() -> Self {
Self { templates: HashMap::new() }
}
pub fn add(&mut self, name: &str, sql: impl Into<String>) -> &mut Self {
self.templates.insert(name.to_string(), sql.into());
self
}
pub fn get_raw(&self, name: &str) -> Option<&str> {
self.templates.get(name).map(|s| s.as_str())
}
pub fn render(&self, name: &str, params: &HashMap<String, String>) -> DbResult<String> {
let template = self.templates
.get(name)
.ok_or_else(|| DbError::Argument(format!("SQL 模板不存在: {}", name)))?;
let mut result = template.clone();
for (key, value) in params {
let placeholder = format!("{{{{ {} }}}}", key);
result = result.replace(&placeholder, value);
}
Ok(result)
}
}
impl Default for SqlTemplate {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub struct SqlPara {
pub id: String,
pub sql: String,
pub params: Vec<String>,
}
impl SqlPara {
pub fn new(id: impl Into<String>, sql: impl Into<String>) -> Self {
Self {
id: id.into(),
sql: sql.into(),
params: Vec::new(),
}
}
}