mariadb_cli/exec/
named_store.rs1use super::prepare::Kind;
16use crate::error::{Failure, Result};
17use serde::{Deserialize, Serialize};
18use serde_json::{json, Value};
19use std::collections::BTreeMap;
20use std::path::{Path, PathBuf};
21
22pub const FILE_NAME: &str = "named.toml";
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Declared {
28 pub name: String,
30 pub kind: String,
32}
33
34impl Declared {
35 pub fn parse(text: &str) -> Result<Self> {
41 let (name, kind) = text.split_once(':').ok_or_else(|| {
42 Failure::usage(
43 "usage.malformed_declaration",
44 format!("`{text}` does not declare a name and a kind"),
45 )
46 .with_detail("detail", text)
47 .with_hint("write the declaration as name:kind, such as mes:date")
48 })?;
49 if name.trim().is_empty() {
50 return Err(Failure::usage(
51 "usage.malformed_declaration",
52 "a declared parameter has no name",
53 )
54 .with_detail("detail", text)
55 .with_hint("write the declaration as name:kind"));
56 }
57 Ok(Self {
58 name: name.trim().to_owned(),
59 kind: Kind::parse(kind)?.as_str().to_owned(),
60 })
61 }
62
63 pub fn kind(&self) -> Result<Kind> {
70 Kind::parse(&self.kind)
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct Stored {
77 pub statement: String,
79 #[serde(default)]
81 pub params: Vec<Declared>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub max_rows: Option<usize>,
85}
86
87#[derive(Debug, Default)]
89pub struct Catalogue {
90 file: PathBuf,
91 entries: BTreeMap<String, Stored>,
92}
93
94impl Catalogue {
95 pub fn open(directory: &Path) -> Result<Self> {
105 let file = directory.join(FILE_NAME);
106 if !file.exists() {
107 return Ok(Self {
108 file,
109 entries: BTreeMap::new(),
110 });
111 }
112 let text = std::fs::read_to_string(&file).map_err(|cause| {
113 Failure::config(
114 "config.named_unreadable",
115 "the stored statements could not be read",
116 )
117 .with_cause(cause.to_string())
118 })?;
119 let entries = toml::from_str(&text).map_err(|cause| {
120 Failure::config(
121 "config.named_malformed",
122 "the stored statements are not in the form this product writes",
123 )
124 .with_cause(cause.to_string())
125 })?;
126 Ok(Self { file, entries })
127 }
128
129 #[must_use]
131 pub fn file(&self) -> &Path {
132 &self.file
133 }
134
135 pub fn put(&mut self, name: &str, stored: Stored) {
137 self.entries.insert(name.to_owned(), stored);
138 }
139
140 pub fn get(&self, name: &str) -> Result<&Stored> {
146 self.entries.get(name).ok_or_else(|| unknown(name))
147 }
148
149 pub fn remove(&mut self, name: &str) -> Result<Stored> {
155 self.entries.remove(name).ok_or_else(|| unknown(name))
156 }
157
158 #[must_use]
160 pub fn list(&self) -> Vec<Value> {
161 self.entries
162 .iter()
163 .map(|(name, stored)| {
164 json!({
165 "name": name,
166 "statement": stored.statement,
167 "params": stored.params,
168 "max_rows": stored.max_rows,
169 })
170 })
171 .collect()
172 }
173
174 pub fn save(&self) -> Result<()> {
181 if let Some(parent) = self.file.parent() {
182 std::fs::create_dir_all(parent).map_err(unwritable)?;
183 }
184 let text = toml::to_string_pretty(&self.entries).map_err(unwritable)?;
185 std::fs::write(&self.file, text).map_err(unwritable)
186 }
187}
188
189fn unknown(name: &str) -> Failure {
191 Failure::absence(
192 "absence.unknown_named_statement",
193 format!("nothing is stored under the name `{name}`"),
194 )
195 .with_detail("detail", name)
196 .with_hint("run `query named list` to see what is stored")
197}
198
199fn unwritable(cause: impl std::fmt::Display) -> Failure {
201 Failure::config(
202 "config.named_unwritable",
203 "the stored statements could not be written",
204 )
205 .with_cause(cause.to_string())
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 fn stored() -> Stored {
213 Stored {
214 statement: "SELECT * FROM pedidos WHERE mes = ?".to_owned(),
215 params: vec![Declared {
216 name: "mes".to_owned(),
217 kind: "date".to_owned(),
218 }],
219 max_rows: Some(100),
220 }
221 }
222
223 fn scratch() -> tempfile::TempDir {
224 tempfile::tempdir().expect("scratch directory")
225 }
226
227 #[test]
228 fn a_stored_statement_survives_being_written_and_read_back() {
229 let dir = scratch();
230 let mut catalogue = Catalogue::open(dir.path()).expect("opens");
231 catalogue.put("pedidos_do_mes", stored());
232 catalogue.save().expect("saves");
233
234 let reopened = Catalogue::open(dir.path()).expect("reopens");
235 assert_eq!(reopened.get("pedidos_do_mes").expect("stored"), &stored());
236 }
237
238 #[test]
239 fn a_name_that_was_never_stored_is_an_absence_and_not_a_failure_of_use() {
240 let dir = scratch();
241 let mut catalogue = Catalogue::open(dir.path()).expect("opens");
242 let failure = catalogue.get("nao_existe").expect_err("must refuse");
243 assert_eq!(failure.code(), "absence.unknown_named_statement");
244 assert_eq!(failure.exit_number().code(), 8);
245 assert_eq!(
246 catalogue
247 .remove("nao_existe")
248 .expect_err("must refuse")
249 .code(),
250 "absence.unknown_named_statement"
251 );
252 assert!(catalogue.list().is_empty());
253 assert!(catalogue.file().ends_with(FILE_NAME));
254 }
255
256 #[test]
257 fn the_listing_is_ordered_so_two_runs_produce_the_same_bytes() {
258 let dir = scratch();
259 let mut catalogue = Catalogue::open(dir.path()).expect("opens");
260 for name in ["zebra", "alfa", "meio"] {
261 catalogue.put(name, stored());
262 }
263 let names: Vec<String> = catalogue
264 .list()
265 .iter()
266 .filter_map(|entry| entry["name"].as_str().map(ToOwned::to_owned))
267 .collect();
268 assert_eq!(names, vec!["alfa", "meio", "zebra"]);
269 }
270
271 #[test]
274 fn a_declaration_is_refused_when_it_is_malformed() {
275 assert_eq!(
276 Declared::parse("mes:date").expect("reads").kind,
277 Kind::Date.as_str()
278 );
279 for (text, code) in [
280 ("mes", "usage.malformed_declaration"),
281 ("mes:colour", "usage.unknown_parameter_kind"),
282 ] {
283 assert_eq!(Declared::parse(text).expect_err("must refuse").code(), code);
284 }
285 }
286}