#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::fmt;
use api::types::{Value, UnwrapValue};
#[derive(Debug, Clone, PartialEq)]
pub struct Query {
string: String,
params: HashMap<String, Value>,
}
impl Query {
pub fn new<Q>(query_string: Q) -> Self
where Q: Into<String>
{
Query {
string: query_string.into(),
params: HashMap::new(),
}
}
pub fn unwrap(self) -> (String, HashMap<String, Value>) {
(self.string, self.params)
}
pub fn str(&self) -> &str {
&self.string
}
pub fn set_parameter<N, T>(&mut self, name: N, value: T)
where N: Into<String>, T: Into<Value>
{
self.params.insert(name.into(), value.into());
}
pub fn parameter<T>(&self, name: &str) -> Option<&T>
where T: UnwrapValue
{
self.params.get(name).map(UnwrapValue::unwrap)
}
}
impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::fmt::Write;
f.write_str(&self.string)?;
if !self.params.is_empty() {
f.write_str("\n with: ")?;
let mut first = true;
for (name, value) in &self.params {
if first {
first = false;
} else {
f.write_str(", ")?;
}
f.write_str(name)?;
f.write_char('=')?;
f.write_str(&value.to_string())?;
}
}
Ok(())
}
}