use anyhow::Context;
use tera::Tera;
use crate::core::error2::Result;
use crate::core::mysql::MysqlClient;
pub fn create_pool(settings: &crate::core::mysql::MysqlSettings) -> Result<MysqlClient> {
let _mapper_location = &settings.mappers.as_deref().unwrap_or_default();
let mut c = MysqlClient {
pool: settings.connect(),
tera: get_tera(_mapper_location).map_err(|e| anyhow::anyhow!(e))?,
};
c.init_sql_bind_filter();
Ok(c)
}
fn get_tera(_mapper_location: &str) -> std::result::Result<Tera, anyhow::Error> {
let mapper_location =
std::path::PathBuf::from(crate::commons::service_home()).join(_mapper_location);
let mappers_files = crate::commons::list_all_files(mapper_location.to_str().unwrap(), "yaml")
.context(format!(
"list-mysql-mapper-file-error={:?}",
mapper_location.to_str().unwrap()
))?;
let mut t = Tera::default();
for file in mappers_files {
let map_data: serde_json::Map<String, serde_json::Value> = match serde_any::from_file(&file)
{
Ok(map) => map,
Err(e) => {
log::error!(
"Mysql-Load-Mapper-YAML-Error: path={}, error={:?}",
&file.to_str().unwrap(),
e
);
serde_json::Map::new()
}
};
for (key, value) in map_data {
let stem = file
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or_default();
let path_str = file.to_str().unwrap_or_default();
let file_path = path_str.replace(&format!("{}/", crate::commons::service_home()), "");
let template_name = format!("{}_{}", stem, key);
let template_str = value.as_str().unwrap_or_default();
t.add_raw_template(&template_name, template_str)?;
log::debug!(
"mysql-mappers={:?}, template_name={}, template_str={}",
file_path,
template_name,
template_str.replace("\n", "").replace(" ", "")
);
}
}
Ok(t)
}