1pub use super::named_store::{Catalogue, Declared, Stored, FILE_NAME};
13
14use crate::error::{Failure, Result};
15use serde_json::{json, Value};
16use std::collections::BTreeMap;
17use std::path::Path;
18
19#[must_use]
24pub fn count_markers(statement: &str) -> usize {
25 crate::sql::strip(statement)
26 .text()
27 .chars()
28 .filter(|character| *character == '?')
29 .count()
30}
31
32pub fn arguments(stored: &Stored, given: &[String]) -> Result<Vec<String>> {
42 let mut supplied = BTreeMap::new();
43 for pair in given {
44 let (name, value) = pair.split_once('=').ok_or_else(|| {
45 Failure::usage(
46 "usage.malformed_argument",
47 format!("`{pair}` does not give a name and a value"),
48 )
49 .with_detail("detail", pair.clone())
50 .with_hint("write the argument as name=value")
51 })?;
52 supplied.insert(name.trim().to_owned(), value.to_owned());
53 }
54
55 let mut ordered = Vec::with_capacity(stored.params.len());
56 for declared in &stored.params {
57 let value = supplied.remove(&declared.name).ok_or_else(|| {
58 Failure::usage(
59 "usage.missing_argument",
60 format!("`{}` was declared and no value was given", declared.name),
61 )
62 .with_detail("detail", declared.name.clone())
63 .with_hint("give every declared parameter as --arg name=value")
64 })?;
65 let kind = declared.kind()?;
66 if !kind.accepts(&value) {
67 return Err(Failure::usage(
68 "usage.argument_kind",
69 format!(
70 "`{}` was declared as {} and the value given is not one",
71 declared.name,
72 kind.as_str()
73 ),
74 )
75 .with_detail("detail", format!("{}:{}", declared.name, kind.as_str()))
76 .with_hint("give a value of the declared kind"));
77 }
78 ordered.push(value);
79 }
80
81 if let Some(extra) = supplied.keys().next() {
82 return Err(Failure::usage(
83 "usage.undeclared_argument",
84 format!("`{extra}` was given and this statement declares no such parameter"),
85 )
86 .with_detail("detail", extra.clone())
87 .with_hint("run `query named list` to see what this statement accepts"));
88 }
89 Ok(ordered)
90}
91
92pub fn keep(
104 catalogue: &mut Catalogue,
105 name: &str,
106 statement: &str,
107 declarations: &[String],
108 max_rows: Option<usize>,
109 policy: &crate::exec::Policy,
110) -> Result<()> {
111 let params = declarations
112 .iter()
113 .map(|text| Declared::parse(text))
114 .collect::<Result<Vec<_>>>()?;
115 let markers = vec![String::new(); count_markers(statement)];
116 crate::exec::prepare::gate(statement, &markers, policy)?;
117
118 catalogue.put(
119 name,
120 Stored {
121 statement: statement.to_owned(),
122 params,
123 max_rows,
124 },
125 );
126 if policy.dry_run {
131 return Ok(());
132 }
133 catalogue.save()
134}
135
136pub fn serve(
147 action: &crate::cli::query::NamedAction,
148 directory: &Path,
149 policy: &crate::exec::Policy,
150) -> Result<Value> {
151 use crate::cli::query::NamedAction;
152
153 let mut catalogue = Catalogue::open(directory)?;
154 match action {
155 NamedAction::Save {
156 name,
157 statement,
158 params,
159 max_rows,
160 } => {
161 keep(&mut catalogue, name, statement, params, *max_rows, policy)?;
162 Ok(json!({"stored": true, "name": name, "simulated": policy.dry_run}))
163 }
164 NamedAction::List => Ok(json!({"rows": catalogue.list()})),
165 NamedAction::Remove { name } => {
166 catalogue.remove(name)?;
170 if !policy.dry_run {
171 catalogue.save()?;
172 }
173 Ok(json!({"removed": true, "name": name, "simulated": policy.dry_run}))
174 }
175 NamedAction::Run { .. } => Err(Failure::usage(
176 "usage.needs_a_connection",
177 "running a stored statement reaches the server",
178 )
179 .with_hint("route this action through the path that opens a connection")),
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 fn stored() -> Stored {
188 Stored {
189 statement: "SELECT * FROM pedidos WHERE mes = ? AND pago = ?".to_owned(),
190 params: vec![
191 Declared {
192 name: "mes".to_owned(),
193 kind: "date".to_owned(),
194 },
195 Declared {
196 name: "pago".to_owned(),
197 kind: "boolean".to_owned(),
198 },
199 ],
200 max_rows: Some(100),
201 }
202 }
203
204 fn scratch() -> tempfile::TempDir {
205 tempfile::tempdir().expect("scratch directory")
206 }
207
208 #[test]
211 fn running_by_name_needs_only_the_name_and_the_declared_values() {
212 let dir = scratch();
213 let mut catalogue = Catalogue::open(dir.path()).expect("opens");
214 catalogue.put("pedidos_do_mes", stored());
215 catalogue.save().expect("saves");
216
217 let reopened = Catalogue::open(dir.path()).expect("reopens");
218 let found = reopened.get("pedidos_do_mes").expect("stored");
219 assert_eq!(
220 found,
221 &stored(),
222 "the statement survives being written back"
223 );
224 assert_eq!(
225 arguments(
226 found,
227 &["mes=2026-01-31".to_owned(), "pago=true".to_owned()]
228 )
229 .expect("both values are of their kind"),
230 vec!["2026-01-31".to_owned(), "true".to_owned()]
231 );
232 }
233
234 #[test]
237 fn a_call_that_does_not_match_the_declaration_is_refused_before_connecting() {
238 let cases = [
239 (
240 vec!["mes=janeiro".to_owned(), "pago=true".to_owned()],
241 "usage.argument_kind",
242 "date",
243 ),
244 (
245 vec!["mes=2026-01-31".to_owned()],
246 "usage.missing_argument",
247 "pago",
248 ),
249 (
250 vec![
251 "mes=2026-01-31".to_owned(),
252 "pago=true".to_owned(),
253 "outro=1".to_owned(),
254 ],
255 "usage.undeclared_argument",
256 "outro",
257 ),
258 ];
259 for (given, code, mentioned) in cases {
260 let failure = arguments(&stored(), &given).expect_err("must refuse");
261 assert_eq!(failure.code(), code, "given {given:?}");
262 assert_eq!(failure.exit_number().code(), 2);
263 assert!(failure.message().contains(mentioned), "given {given:?}");
264 }
265 }
266
267 #[test]
270 fn the_values_are_ordered_by_the_declaration_and_not_by_the_call() {
271 let ordered = arguments(
272 &stored(),
273 &["pago=false".to_owned(), "mes=2026-01-31".to_owned()],
274 )
275 .expect("both given");
276 assert_eq!(ordered, vec!["2026-01-31".to_owned(), "false".to_owned()]);
277 }
278
279 #[test]
280 fn an_argument_without_a_value_is_refused_with_the_shape_it_should_have() {
281 let failure = arguments(&stored(), &["mes".to_owned()]).expect_err("must refuse");
282 assert_eq!(failure.code(), "usage.malformed_argument");
283 assert!(failure
284 .hint()
285 .is_some_and(|hint| hint.contains("name=value")));
286 }
287
288 #[test]
289 fn a_name_that_was_never_stored_is_an_absence_and_not_a_failure_of_use() {
290 let dir = scratch();
291 let mut catalogue = Catalogue::open(dir.path()).expect("opens");
292 let failure = catalogue.get("nao_existe").expect_err("must refuse");
293 assert_eq!(failure.code(), "absence.unknown_named_statement");
294 assert_eq!(failure.exit_number().code(), 8);
295 assert_eq!(
296 catalogue
297 .remove("nao_existe")
298 .expect_err("must refuse")
299 .code(),
300 "absence.unknown_named_statement"
301 );
302 assert!(catalogue.list().is_empty());
303 assert!(catalogue.file().ends_with(FILE_NAME));
304 }
305
306 #[test]
307 fn the_listing_is_ordered_so_two_runs_produce_the_same_bytes() {
308 let dir = scratch();
309 let mut catalogue = Catalogue::open(dir.path()).expect("opens");
310 for name in ["zebra", "alfa", "meio"] {
311 catalogue.put(name, stored());
312 }
313 let names: Vec<String> = catalogue
314 .list()
315 .iter()
316 .filter_map(|entry| entry["name"].as_str().map(ToOwned::to_owned))
317 .collect();
318 assert_eq!(names, vec!["alfa", "meio", "zebra"]);
319 }
320
321 #[test]
322 fn the_markers_of_a_statement_are_counted_over_its_blanked_text() {
323 assert_eq!(count_markers("SELECT * FROM t WHERE a = ? AND b = ?"), 2);
324 assert_eq!(
325 count_markers("SELECT 'why?' FROM t WHERE a = ?"),
326 1,
327 "a marker inside a literal is not a marker"
328 );
329 }
330}