Skip to main content

mariadb_cli/exec/
named_store.rs

1//! Where a statement kept under a name lives between invocations.
2//!
3//! This module owns the file and nothing else: it reads it, writes it and says
4//! plainly when a name was never stored. Deciding whether a call matches the
5//! declaration, and whether the statement may be kept at all, is
6//! [`super::named`].
7//!
8//! # The statement is stored, never the values
9//!
10//! What is kept on disk is the text and the shape of its parameters. A value is
11//! given at the moment of the call and travels bound, exactly as it does for a
12//! statement written by hand. Storing values would put whatever they carry into
13//! a file that outlives the invocation.
14
15use 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
22/// The file the stored statements live in, inside the settings location.
23pub const FILE_NAME: &str = "named.toml";
24
25/// One declared parameter.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Declared {
28    /// The name a caller gives the value under.
29    pub name: String,
30    /// The kind the value must be, by its stable name.
31    pub kind: String,
32}
33
34impl Declared {
35    /// Reads a declaration written as a name and a kind.
36    ///
37    /// # Errors
38    ///
39    /// Returns a usage failure when the shape is wrong or the kind is unknown.
40    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    /// The kind this declaration names.
64    ///
65    /// # Errors
66    ///
67    /// Returns a usage failure when the stored kind is not one that exists,
68    /// which is how a hand-edited file is caught.
69    pub fn kind(&self) -> Result<Kind> {
70        Kind::parse(&self.kind)
71    }
72}
73
74/// One statement kept under a name.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct Stored {
77    /// The statement itself, with a marker where each value goes.
78    pub statement: String,
79    /// The parameters it accepts, in the order the markers appear.
80    #[serde(default)]
81    pub params: Vec<Declared>,
82    /// A ceiling of its own on the rows it may return.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub max_rows: Option<usize>,
85}
86
87/// Every statement kept under a name.
88#[derive(Debug, Default)]
89pub struct Catalogue {
90    file: PathBuf,
91    entries: BTreeMap<String, Stored>,
92}
93
94impl Catalogue {
95    /// Reads the stored statements from a settings location.
96    ///
97    /// A location with no such file yet is an empty catalogue and never a
98    /// failure, because nothing has been stored yet.
99    ///
100    /// # Errors
101    ///
102    /// Returns a configuration failure when the file exists and cannot be read
103    /// or does not hold what this product wrote.
104    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    /// Where the stored statements live.
130    #[must_use]
131    pub fn file(&self) -> &Path {
132        &self.file
133    }
134
135    /// Keeps one statement under a name, replacing any statement of that name.
136    pub fn put(&mut self, name: &str, stored: Stored) {
137        self.entries.insert(name.to_owned(), stored);
138    }
139
140    /// The statement kept under one name.
141    ///
142    /// # Errors
143    ///
144    /// Returns an absence failure when nothing is stored under that name.
145    pub fn get(&self, name: &str) -> Result<&Stored> {
146        self.entries.get(name).ok_or_else(|| unknown(name))
147    }
148
149    /// Removes the statement kept under one name.
150    ///
151    /// # Errors
152    ///
153    /// Returns an absence failure when nothing is stored under that name.
154    pub fn remove(&mut self, name: &str) -> Result<Stored> {
155        self.entries.remove(name).ok_or_else(|| unknown(name))
156    }
157
158    /// Every stored statement, in a fixed order so two runs agree.
159    #[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    /// Writes the catalogue back.
175    ///
176    /// # Errors
177    ///
178    /// Returns a configuration failure when the location cannot be created or
179    /// the file cannot be written.
180    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
189/// The failure a name nothing was ever stored under produces.
190fn 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
199/// The failure every way of not writing the catalogue produces.
200fn 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    /// A declaration that names a kind this product does not have is refused
272    /// when it is written, not when somebody runs the statement by name.
273    #[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}