1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::convert::From;

/// Helper macro to simplify the creation of complex statements
///
/// Pass in the statement text as the first argument followed by the (optional) parameters, which
/// must be in the format `"param" => value` and wrapped in `{}`
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate rusted_cypher;
/// # fn main() {
/// // Without parameters
/// let statement = cypher_stmt!("MATCH n RETURN n");
/// // With parameters
/// let statement = cypher_stmt!("MATCH n RETURN n", {
///     "param1" => "value1",
///     "param2" => 2,
///     "param3" => 3.0
/// });
/// # }
/// ```
#[macro_export]
macro_rules! cypher_stmt {
    ( $s:expr ) => { $crate::Statement::new($s) };
    ( $s:expr, { $( $k:expr => $v:expr ),+ } ) => {
        $crate::Statement::new($s)
            $(.with_param($k, $v))*
    }
}

#[cfg(not(feature = "rustc-serialize"))]
mod inner {
    use std::collections::BTreeMap;
    use serde::{Serialize, Deserialize};
    use serde_json::{self, Value};

    /// Represents a statement to be sent to the server
    #[derive(Clone, Debug, Serialize)]
    pub struct Statement {
        statement: String,
        parameters: BTreeMap<String, Value>,
    }

    impl Statement  {
        pub fn new(statement: &str) -> Self {
            Statement {
                statement: statement.to_owned(),
                parameters: BTreeMap::new(),
            }
        }

        /// Returns the statement text
        pub fn statement(&self) -> &str {
            &self.statement
        }

        /// Adds parameter in builder style
        ///
        /// This method consumes `self` and returns it with the parameter added, so the binding does
        /// not need to be mutable
        ///
        /// # Examples
        ///
        /// ```
        /// # use rusted_cypher::Statement;
        /// let statement = Statement::new("MATCH n RETURN n")
        ///     .with_param("param1", "value1")
        ///     .with_param("param2", 2)
        ///     .with_param("param3", 3.0);
        /// ```
        pub fn with_param<V: Serialize + Copy>(mut self, key: &str, value: V) -> Self {
            self.add_param(key, value);
            self
        }

        /// Adds parameter to the `Statement`
        pub fn add_param<V: Serialize + Copy>(&mut self, key: &str, value: V) {
            self.parameters.insert(key.to_owned(), serde_json::value::to_value(&value));
        }

        /// Gets the value of the parameter
        ///
        /// Returns `None` if there is no parameter with the given name or `Some(serde_json::error::Error)``
        /// if the parameter cannot be converted back from `serde_json::value::Value`
        pub fn param<V: Deserialize>(&self, key: &str) -> Option<Result<V, serde_json::error::Error>> {
            self.parameters.get(key.into()).map(|v| serde_json::value::from_value(v.clone()))
        }

        /// deprecated: use `Statement::param` instead
        pub fn get_param<V: Deserialize>(&self, key: &str) -> Option<Result<V, serde_json::error::Error>> {
            self.param(key)
        }

        /// Gets a reference to the underlying parameters `BTreeMap`
        pub fn parameters(&self) -> &BTreeMap<String, Value> {
            &self.parameters
        }

        /// deprecated: use `Statement::parameters` instead
        pub fn get_params(&self) -> &BTreeMap<String, Value> {
            self.parameters()
        }

        /// Sets the parameters `BTreeMap`, overriding current values
        pub fn set_parameters<V: Serialize>(&mut self, params: &BTreeMap<String, V>) {
            self.parameters = params.iter()
                .map(|(k, v)| (k.to_owned(), serde_json::value::to_value(&v)))
                .collect();
        }

        /// deprecated: use `Statement::set_parameters` instead
        pub fn set_params<V: Serialize>(&mut self, params: &BTreeMap<String, V>) {
            self.set_parameters(params);
        }

        /// Removes parameter from the statment
        ///
        /// Trying to remove a non-existent parameter has no effect
        pub fn remove_param(&mut self, key: &str) {
            self.parameters.remove(key);
        }
    }
}

#[cfg(feature = "rustc-serialize")]
mod inner {
    use std::collections::BTreeMap;
    use std::error::Error;
    use rustc_serialize::{Encodable, Decodable};
    use rustc_serialize::json as rustc_json;
    use serde_json::{self, Value};
    use ::error::GraphError;

    /// Represents a statement to be sent to the server
    #[derive(Clone, Debug, Serialize)]
    pub struct Statement {
        statement: String,
        parameters: BTreeMap<String, Value>,
        #[serde(skip_serializing)]
        param_errors: Vec<(String, String)>,
    }

    impl Statement  {
        pub fn new(statement: &str) -> Self {
            Statement {
                statement: statement.to_owned(),
                parameters: BTreeMap::new(),
                param_errors: Vec::new(),
            }
        }

        /// Returns the statement text
        pub fn statement(&self) -> &str {
            &self.statement
        }

        /// Adds parameter in builder style
        ///
        /// This method consumes `self` and returns it with the parameter added, so the binding does
        /// not need to be mutable
        ///
        /// # Examples
        ///
        /// ```
        /// # use rusted_cypher::Statement;
        /// let statement = Statement::new("MATCH n RETURN n")
        ///     .with_param("param1", "value1")
        ///     .with_param("param2", 2)
        ///     .with_param("param3", 3.0);
        /// ```
        pub fn with_param<V: Encodable + Copy>(mut self, key: &str, value: V) -> Self {
            self.add_param(key, value);
            self
        }

        /// Adds parameter to the `Statement`
        pub fn add_param<V: Encodable + Copy>(&mut self, key: &str, value: V) {
            let between = match rustc_json::encode(&value) {
                Ok(value) => value,
                Err(e) => {
                    self.param_errors.push((key.to_owned(), format!("{}", e)));
                    return
                }
            };

            let value = match serde_json::from_str::<Value>(&between) {
                Ok(value) => value,
                Err(e) => {
                    self.param_errors.push((key.to_owned(), format!("{}", e)));
                    return
                }
            };

            self.parameters.insert(key.to_owned(), value);
        }

        /// Gets the value of the parameter
        ///
        /// Returns `None` if there is no parameter with the given name or `Some(serde_json::error::Error)``
        /// if the parameter cannot be converted back from `serde_json::value::Value`
        pub fn param<V: Decodable>(&self, key: &str) -> Option<Result<V, GraphError>> {
            self.parameters.get(key.into()).map(|v| {
                let between = try!(serde_json::to_string(&v));
                rustc_json::decode(&between).map_err(From::from)
            })
        }

        /// Use `Self::param`
        pub fn get_param<V: Decodable>(&self, key: &str) -> Option<Result<V, GraphError>> {
            self.param(key)
        }

        /// Gets a reference to the underlying parameters `BTreeMap`
        pub fn parameters(&self) -> &BTreeMap<String, Value> {
            &self.parameters
        }

        /// Use `Self::parameters`
        pub fn get_params(&self) -> &BTreeMap<String, Value> {
            self.parameters()
        }

        /// Sets the parameters `BTreeMap`, overriding current values
        pub fn set_parameters<V: Encodable>(&mut self, params: &BTreeMap<String, V>) -> Result<(), Box<Error>> {
            let mut new_params: BTreeMap<String, Value> = BTreeMap::new();

            for (k, v) in params.iter() {
                let between = try!(rustc_json::encode(&v));
                let value: Value = try!(serde_json::from_str(&between));
                new_params.insert(k.to_owned(), value);
            }

            Ok(())
        }

        /// Use `Self::set_parameters`
        pub fn set_params<V: Encodable>(&mut self, params: &BTreeMap<String, V>) -> Result<(), Box<Error>> {
            self.set_parameters(params)
        }

        /// Removes parameter from the statment
        ///
        /// Trying to remove a non-existent parameter has no effect
        pub fn remove_param(&mut self, key: &str) {
            self.parameters.remove(key);
        }

        pub fn has_param_errors(&self) -> bool {
            !self.param_errors.is_empty()
        }

        pub fn param_errors(&self) -> &Vec<(String, String)> {
            &self.param_errors
        }
    }
}

pub use self::inner::Statement;

impl<'a> From<&'a str> for Statement {
    fn from(stmt: &str) -> Self {
        Statement::new(stmt)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[allow(unused_variables)]
    fn from_str() {
        let stmt = Statement::new("MATCH n RETURN n");
    }

    #[test]
    fn with_param() {
        let statement = Statement::new("MATCH n RETURN n")
            .with_param("param1", "value1")
            .with_param("param2", 2)
            .with_param("param3", 3.0)
            .with_param("param4", [0; 4]);

        assert_eq!(statement.parameters().len(), 4);
    }

    #[test]
    fn add_param() {
        let mut statement = Statement::new("MATCH n RETURN n");
        statement.add_param("param1", "value1");
        statement.add_param("param2", 2);
        statement.add_param("param3", 3.0);
        statement.add_param("param4", [0; 4]);

        assert_eq!(statement.parameters().len(), 4);
    }

    #[test]
    fn remove_param() {
        let mut statement = Statement::new("MATCH n RETURN n")
            .with_param("param1", "value1")
            .with_param("param2", 2)
            .with_param("param3", 3.0)
            .with_param("param4", [0; 4]);

        statement.remove_param("param1");

        assert_eq!(statement.parameters().len(), 3);
    }

    #[test]
    #[allow(unused_variables)]
    fn macro_without_params() {
        let stmt = cypher_stmt!("MATCH n RETURN n");
    }

    #[test]
    fn macro_single_param() {
        let statement1 = cypher_stmt!("MATCH n RETURN n", {
            "name" => "test"
        });

        let param = 1;
        let statement2 = cypher_stmt!("MATCH n RETURN n", {
            "value" => param
        });

        assert_eq!("test", statement1.param::<String>("name").unwrap().unwrap());
        assert_eq!(param, statement2.param::<i32>("value").unwrap().unwrap());
    }

    #[test]
    fn macro_multiple_params() {
        let param = 3f32;
        let statement = cypher_stmt!("MATCH n RETURN n", {
            "param1" => "one",
            "param2" => 2,
            "param3" => param
        });

        assert_eq!("one", statement.param::<String>("param1").unwrap().unwrap());
        assert_eq!(2, statement.param::<i32>("param2").unwrap().unwrap());
        assert_eq!(param, statement.param::<f32>("param3").unwrap().unwrap());
    }
}