use super::prepare::Kind;
use crate::error::{Failure, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub const FILE_NAME: &str = "named.toml";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Declared {
pub name: String,
pub kind: String,
}
impl Declared {
pub fn parse(text: &str) -> Result<Self> {
let (name, kind) = text.split_once(':').ok_or_else(|| {
Failure::usage(
"usage.malformed_declaration",
format!("`{text}` does not declare a name and a kind"),
)
.with_detail("detail", text)
.with_hint("write the declaration as name:kind, such as mes:date")
})?;
if name.trim().is_empty() {
return Err(Failure::usage(
"usage.malformed_declaration",
"a declared parameter has no name",
)
.with_detail("detail", text)
.with_hint("write the declaration as name:kind"));
}
Ok(Self {
name: name.trim().to_owned(),
kind: Kind::parse(kind)?.as_str().to_owned(),
})
}
pub fn kind(&self) -> Result<Kind> {
Kind::parse(&self.kind)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stored {
pub statement: String,
#[serde(default)]
pub params: Vec<Declared>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_rows: Option<usize>,
}
#[derive(Debug, Default)]
pub struct Catalogue {
file: PathBuf,
entries: BTreeMap<String, Stored>,
}
impl Catalogue {
pub fn open(directory: &Path) -> Result<Self> {
let file = directory.join(FILE_NAME);
if !file.exists() {
return Ok(Self {
file,
entries: BTreeMap::new(),
});
}
let text = std::fs::read_to_string(&file).map_err(|cause| {
Failure::config(
"config.named_unreadable",
"the stored statements could not be read",
)
.with_cause(cause.to_string())
})?;
let entries = toml::from_str(&text).map_err(|cause| {
Failure::config(
"config.named_malformed",
"the stored statements are not in the form this product writes",
)
.with_cause(cause.to_string())
})?;
Ok(Self { file, entries })
}
#[must_use]
pub fn file(&self) -> &Path {
&self.file
}
pub fn put(&mut self, name: &str, stored: Stored) {
self.entries.insert(name.to_owned(), stored);
}
pub fn get(&self, name: &str) -> Result<&Stored> {
self.entries.get(name).ok_or_else(|| unknown(name))
}
pub fn remove(&mut self, name: &str) -> Result<Stored> {
self.entries.remove(name).ok_or_else(|| unknown(name))
}
#[must_use]
pub fn list(&self) -> Vec<Value> {
self.entries
.iter()
.map(|(name, stored)| {
json!({
"name": name,
"statement": stored.statement,
"params": stored.params,
"max_rows": stored.max_rows,
})
})
.collect()
}
pub fn save(&self) -> Result<()> {
if let Some(parent) = self.file.parent() {
std::fs::create_dir_all(parent).map_err(unwritable)?;
}
let text = toml::to_string_pretty(&self.entries).map_err(unwritable)?;
std::fs::write(&self.file, text).map_err(unwritable)
}
}
fn unknown(name: &str) -> Failure {
Failure::absence(
"absence.unknown_named_statement",
format!("nothing is stored under the name `{name}`"),
)
.with_detail("detail", name)
.with_hint("run `query named list` to see what is stored")
}
fn unwritable(cause: impl std::fmt::Display) -> Failure {
Failure::config(
"config.named_unwritable",
"the stored statements could not be written",
)
.with_cause(cause.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn stored() -> Stored {
Stored {
statement: "SELECT * FROM pedidos WHERE mes = ?".to_owned(),
params: vec![Declared {
name: "mes".to_owned(),
kind: "date".to_owned(),
}],
max_rows: Some(100),
}
}
fn scratch() -> tempfile::TempDir {
tempfile::tempdir().expect("scratch directory")
}
#[test]
fn a_stored_statement_survives_being_written_and_read_back() {
let dir = scratch();
let mut catalogue = Catalogue::open(dir.path()).expect("opens");
catalogue.put("pedidos_do_mes", stored());
catalogue.save().expect("saves");
let reopened = Catalogue::open(dir.path()).expect("reopens");
assert_eq!(reopened.get("pedidos_do_mes").expect("stored"), &stored());
}
#[test]
fn a_name_that_was_never_stored_is_an_absence_and_not_a_failure_of_use() {
let dir = scratch();
let mut catalogue = Catalogue::open(dir.path()).expect("opens");
let failure = catalogue.get("nao_existe").expect_err("must refuse");
assert_eq!(failure.code(), "absence.unknown_named_statement");
assert_eq!(failure.exit_number().code(), 8);
assert_eq!(
catalogue
.remove("nao_existe")
.expect_err("must refuse")
.code(),
"absence.unknown_named_statement"
);
assert!(catalogue.list().is_empty());
assert!(catalogue.file().ends_with(FILE_NAME));
}
#[test]
fn the_listing_is_ordered_so_two_runs_produce_the_same_bytes() {
let dir = scratch();
let mut catalogue = Catalogue::open(dir.path()).expect("opens");
for name in ["zebra", "alfa", "meio"] {
catalogue.put(name, stored());
}
let names: Vec<String> = catalogue
.list()
.iter()
.filter_map(|entry| entry["name"].as_str().map(ToOwned::to_owned))
.collect();
assert_eq!(names, vec!["alfa", "meio", "zebra"]);
}
#[test]
fn a_declaration_is_refused_when_it_is_malformed() {
assert_eq!(
Declared::parse("mes:date").expect("reads").kind,
Kind::Date.as_str()
);
for (text, code) in [
("mes", "usage.malformed_declaration"),
("mes:colour", "usage.unknown_parameter_kind"),
] {
assert_eq!(Declared::parse(text).expect_err("must refuse").code(), code);
}
}
}