pub use super::named_store::{Catalogue, Declared, Stored, FILE_NAME};
use crate::error::{Failure, Result};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::Path;
#[must_use]
pub fn count_markers(statement: &str) -> usize {
crate::sql::strip(statement)
.text()
.chars()
.filter(|character| *character == '?')
.count()
}
pub fn arguments(stored: &Stored, given: &[String]) -> Result<Vec<String>> {
let mut supplied = BTreeMap::new();
for pair in given {
let (name, value) = pair.split_once('=').ok_or_else(|| {
Failure::usage(
"usage.malformed_argument",
format!("`{pair}` does not give a name and a value"),
)
.with_detail("detail", pair.clone())
.with_hint("write the argument as name=value")
})?;
supplied.insert(name.trim().to_owned(), value.to_owned());
}
let mut ordered = Vec::with_capacity(stored.params.len());
for declared in &stored.params {
let value = supplied.remove(&declared.name).ok_or_else(|| {
Failure::usage(
"usage.missing_argument",
format!("`{}` was declared and no value was given", declared.name),
)
.with_detail("detail", declared.name.clone())
.with_hint("give every declared parameter as --arg name=value")
})?;
let kind = declared.kind()?;
if !kind.accepts(&value) {
return Err(Failure::usage(
"usage.argument_kind",
format!(
"`{}` was declared as {} and the value given is not one",
declared.name,
kind.as_str()
),
)
.with_detail("detail", format!("{}:{}", declared.name, kind.as_str()))
.with_hint("give a value of the declared kind"));
}
ordered.push(value);
}
if let Some(extra) = supplied.keys().next() {
return Err(Failure::usage(
"usage.undeclared_argument",
format!("`{extra}` was given and this statement declares no such parameter"),
)
.with_detail("detail", extra.clone())
.with_hint("run `query named list` to see what this statement accepts"));
}
Ok(ordered)
}
pub fn keep(
catalogue: &mut Catalogue,
name: &str,
statement: &str,
declarations: &[String],
max_rows: Option<usize>,
policy: &crate::exec::Policy,
) -> Result<()> {
let params = declarations
.iter()
.map(|text| Declared::parse(text))
.collect::<Result<Vec<_>>>()?;
let markers = vec![String::new(); count_markers(statement)];
crate::exec::prepare::gate(statement, &markers, policy)?;
catalogue.put(
name,
Stored {
statement: statement.to_owned(),
params,
max_rows,
},
);
if policy.dry_run {
return Ok(());
}
catalogue.save()
}
pub fn serve(
action: &crate::cli::query::NamedAction,
directory: &Path,
policy: &crate::exec::Policy,
) -> Result<Value> {
use crate::cli::query::NamedAction;
let mut catalogue = Catalogue::open(directory)?;
match action {
NamedAction::Save {
name,
statement,
params,
max_rows,
} => {
keep(&mut catalogue, name, statement, params, *max_rows, policy)?;
Ok(json!({"stored": true, "name": name, "simulated": policy.dry_run}))
}
NamedAction::List => Ok(json!({"rows": catalogue.list()})),
NamedAction::Remove { name } => {
catalogue.remove(name)?;
if !policy.dry_run {
catalogue.save()?;
}
Ok(json!({"removed": true, "name": name, "simulated": policy.dry_run}))
}
NamedAction::Run { .. } => Err(Failure::usage(
"usage.needs_a_connection",
"running a stored statement reaches the server",
)
.with_hint("route this action through the path that opens a connection")),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stored() -> Stored {
Stored {
statement: "SELECT * FROM pedidos WHERE mes = ? AND pago = ?".to_owned(),
params: vec![
Declared {
name: "mes".to_owned(),
kind: "date".to_owned(),
},
Declared {
name: "pago".to_owned(),
kind: "boolean".to_owned(),
},
],
max_rows: Some(100),
}
}
fn scratch() -> tempfile::TempDir {
tempfile::tempdir().expect("scratch directory")
}
#[test]
fn running_by_name_needs_only_the_name_and_the_declared_values() {
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");
let found = reopened.get("pedidos_do_mes").expect("stored");
assert_eq!(
found,
&stored(),
"the statement survives being written back"
);
assert_eq!(
arguments(
found,
&["mes=2026-01-31".to_owned(), "pago=true".to_owned()]
)
.expect("both values are of their kind"),
vec!["2026-01-31".to_owned(), "true".to_owned()]
);
}
#[test]
fn a_call_that_does_not_match_the_declaration_is_refused_before_connecting() {
let cases = [
(
vec!["mes=janeiro".to_owned(), "pago=true".to_owned()],
"usage.argument_kind",
"date",
),
(
vec!["mes=2026-01-31".to_owned()],
"usage.missing_argument",
"pago",
),
(
vec![
"mes=2026-01-31".to_owned(),
"pago=true".to_owned(),
"outro=1".to_owned(),
],
"usage.undeclared_argument",
"outro",
),
];
for (given, code, mentioned) in cases {
let failure = arguments(&stored(), &given).expect_err("must refuse");
assert_eq!(failure.code(), code, "given {given:?}");
assert_eq!(failure.exit_number().code(), 2);
assert!(failure.message().contains(mentioned), "given {given:?}");
}
}
#[test]
fn the_values_are_ordered_by_the_declaration_and_not_by_the_call() {
let ordered = arguments(
&stored(),
&["pago=false".to_owned(), "mes=2026-01-31".to_owned()],
)
.expect("both given");
assert_eq!(ordered, vec!["2026-01-31".to_owned(), "false".to_owned()]);
}
#[test]
fn an_argument_without_a_value_is_refused_with_the_shape_it_should_have() {
let failure = arguments(&stored(), &["mes".to_owned()]).expect_err("must refuse");
assert_eq!(failure.code(), "usage.malformed_argument");
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("name=value")));
}
#[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 the_markers_of_a_statement_are_counted_over_its_blanked_text() {
assert_eq!(count_markers("SELECT * FROM t WHERE a = ? AND b = ?"), 2);
assert_eq!(
count_markers("SELECT 'why?' FROM t WHERE a = ?"),
1,
"a marker inside a literal is not a marker"
);
}
}