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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
//! # Common types (GraphDB)
//!
//! A set of common types that largely support the `ResultSet` type, a wrapper
//! around results that come back from a graph database that supports dynamic,
//! strongly-typed tuple extraction.
//!
//! These types are mostly copied wholesale from the RedisGraph client library
//! that can be found at https://github.com/malte-v/redisgraph-rs

use std::collections::HashMap;

#[macro_use]
extern crate serde_derive;

mod conversions;
mod errors;
pub mod protocol;

pub use crate::errors::GraphResult;
pub use errors::GraphError;

pub const CAPID_GRAPHDB: &str = "wascc:graphdb";

/// Represents the return data from a graph. You shouldn't have to use this
/// type directly, but rather extract rows and columns via vectors of tuples
/// and pattern matching/destructing
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResultSet {
    /// The columns of this result set.
    ///     
    /// Empty if the response did not contain any return values.
    pub columns: Vec<Column>,
    /// Contains statistics messages from the response.
    pub statistics: Statistics,
}

/// Human-readable statistics that are optionally returned with each query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Statistics(pub Vec<String>);

impl ResultSet {
    /// Returns the number of rows in the result set.
    pub fn num_columns(&self) -> usize {
        self.columns.len()
    }

    /// Returns the number of columns in the result set.
    pub fn num_rows(&self) -> usize {
        match self.columns.get(0) {
            Some(first_column) => first_column.len(),
            None => 0,
        }
    }

    /// Returns the scalar at the given position.
    ///
    /// Returns an error if the value at the given position is not a scalar
    /// or if the position is out of bounds.
    pub fn get_scalar(&self, row_idx: usize, column_idx: usize) -> GraphResult<&Scalar> {
        match self.columns.get(column_idx) {
            Some(column) => match column {
                Column::Scalars(cells) => match cells.get(row_idx) {
                    Some(cell) => Ok(cell),
                    None => client_type_error!(
                        "failed to get scalar: row index out of bounds: the len is {:?} but the index is {:?}", self.columns.len(), column_idx,
                    ),
                },
                any => client_type_error!(
                    "failed to get scalar: expected column of scalars, found {:?}",
                    any
                ),
            }
            None => client_type_error!(
                "failed to get scalar: column index out of bounds: the len is {:?} but the index is {:?}", self.columns.len(), column_idx,
            ),
        }
    }

    /// Returns the node at the given position.
    ///
    /// Returns an error if the value at the given position is not a node
    /// or if the position is out of bounds.
    pub fn get_node(&self, row_idx: usize, column_idx: usize) -> GraphResult<&Node> {
        match self.columns.get(column_idx) {
            Some(column) => match column {
                Column::Nodes(cells) => match cells.get(row_idx) {
                    Some(cell) => Ok(cell),
                    None => client_type_error!(
                        "failed to get node: row index out of bounds: the len is {:?} but the index is {:?}", self.columns.len(), column_idx,
                    ),
                },
                any => client_type_error!(
                    "failed to get node: expected column of nodes, found {:?}",
                    any
                ),
            }
            None => client_type_error!(
                "failed to get node: column index out of bounds: the len is {:?} but the index is {:?}", self.columns.len(), column_idx,
            ),
        }
    }

    /// Returns the relation at the given position.
    ///
    /// Returns an error if the value at the given position is not a relation
    /// or if the position is out of bounds.
    pub fn get_relation(&self, row_idx: usize, column_idx: usize) -> GraphResult<&Relation> {
        match self.columns.get(column_idx) {
            Some(column) => match column {
                Column::Relations(cells) => match cells.get(row_idx) {
                    Some(cell) => Ok(cell),
                    None => client_type_error!(
                        "failed to get relation: row index out of bounds: the len is {:?} but the index is {:?}", self.columns.len(), column_idx,
                    ),
                },
                any => client_type_error!(
                    "failed to get relation: expected column of relations, found {:?}",
                    any
                ),
            }
            None => client_type_error!(
                "failed to get relation: column index out of bounds: the len is {:?} but the index is {:?}", self.columns.len(), column_idx,
            ),
        }
    }
}

impl FromTable for ResultSet {
    fn from_table(result_set: &ResultSet) -> GraphResult<Self> {
        Ok(result_set.clone())
    }
}

impl<T: FromRow> FromTable for Vec<T> {
    fn from_table(result_set: &ResultSet) -> GraphResult<Self> {
        let num_rows = result_set.num_rows();
        let mut ret = Self::with_capacity(num_rows);

        for i in 0..num_rows {
            ret.push(T::from_row(result_set, i)?);
        }

        Ok(ret)
    }
}

pub trait FromTable: Sized {
    fn from_table(result_set: &ResultSet) -> GraphResult<Self>;
}

/// Implemented by types that can be constructed from a row in a [`ResultSet`](../result_set/struct.ResultSet.html).
pub trait FromRow: Sized {
    fn from_row(result_set: &ResultSet, row_idx: usize) -> GraphResult<Self>;
}

/// Implemented by types that can be constructed from a cell in a [`ResultSet`](../result_set/struct.ResultSet.html).
pub trait FromCell: Sized {
    fn from_cell(result_set: &ResultSet, row_idx: usize, column_idx: usize) -> GraphResult<Self>;
}

/// A single column of the result set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Column {
    Scalars(Vec<Scalar>),
    Nodes(Vec<Node>),
    Relations(Vec<Relation>),
}

impl Column {
    /// Returns the length of this column.
    pub fn len(&self) -> usize {
        match self {
            Self::Scalars(cells) => cells.len(),
            Self::Nodes(cells) => cells.len(),
            Self::Relations(cells) => cells.len(),
        }
    }

    /// Returns `true` if this column is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[derive(Serialize, Debug, Deserialize)]
enum ColumnType {
    Unknown = 0,
    Scalar = 1,
    Node = 2,
    Relation = 3,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Relation {
    /// The type name of this relation.
    pub type_name: String,
    /// The properties of this relation.
    pub properties: HashMap<String, Scalar>,
}

/// A scalar value returned by the Graph provider
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Scalar {
    Nil,
    Boolean(bool),
    Integer(i64),
    Double(f64),
    String(GraphString), // A string returned by the graph DB
}

/// The valid types of scalars
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
enum ScalarType {
    Unknown = 0,
    Nil = 1,
    String = 2,
    Integer = 3,
    Boolean = 4,
    Double = 5,
}

/// A string returned by the graph DB as a vector of bytes
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GraphString(pub Vec<u8>);

// Methods to round-trip between regular strings and GraphStrings

impl From<String> for GraphString {
    fn from(string: String) -> Self {
        Self(string.into_bytes())
    }
}

impl From<Vec<u8>> for GraphString {
    fn from(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }
}

impl From<GraphString> for Vec<u8> {
    fn from(redis_string: GraphString) -> Self {
        redis_string.0
    }
}

// A node returned by the Graph DB provider
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
    /// The labels attached to this node.
    pub labels: Vec<String>,
    /// The properties of this node.
    pub properties: HashMap<String, Scalar>,
}

// Macro generates generic "From" implementations to allow
// tuples/vecs-of-tuples to be extracted from various types
//
// Altered version of https://github.com/mitsuhiko/redis-rs/blob/master/src/types.rs#L1080
macro_rules! impl_row_for_tuple {
    () => ();
    ($($name:ident,)+) => (
        #[doc(hidden)]
        impl<$($name: FromCell),*> FromRow for ($($name,)*) {
            // we have local variables named T1 as dummies and those
            // variables are unused.
            #[allow(non_snake_case, unused_variables, clippy::eval_order_dependence)]
            fn from_row(result_set: &ResultSet, row_idx: usize) -> GraphResult<($($name,)*)> {
                // hacky way to count the tuple size
                let mut n = 0;
                $(let $name = (); n += 1;)*
                if result_set.num_columns() != n {
                    return client_type_error!(
                        "failed to construct tuple: tuple has {:?} entries but result table has {:?} columns",
                        n,
                        result_set.num_columns()
                    );
                }

                // this is pretty ugly too. The { i += 1; i - 1 } is rust's
                // postfix increment :)
                let mut i = 0;
                Ok(($({let $name = (); $name::from_cell(result_set, row_idx, { i += 1; i - 1 })?},)*))
            }
        }
        impl_row_for_tuple_peel!($($name,)*);
    )
}

// Support for the recursive macro calls
macro_rules! impl_row_for_tuple_peel {
    ($name:ident, $($other:ident,)*) => (impl_row_for_tuple!($($other,)*);)
}

// The library supports tuples of up to 12 items
impl_row_for_tuple! { T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, }

// Row and column indices default to zero for lower-level values
impl<T: FromCell> FromRow for T {
    fn from_row(result_set: &ResultSet, row_idx: usize) -> GraphResult<Self> {
        T::from_cell(result_set, row_idx, 0)
    }
}

impl<T: FromRow> FromTable for T {
    fn from_table(result_set: &ResultSet) -> GraphResult<Self> {
        T::from_row(result_set, 0)
    }
}

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

    // Verifies that we can extract the tuples we expect from the raw ResultSet
    // structure and that the various return types are automatically converted
    #[test]
    fn tuple_extraction_test() {
        let (name, birth_year): (String, u32) = fake_query("fake query").unwrap();
        assert_eq!("tester", name);
        assert_eq!(1985, birth_year);
    }

    #[test]
    fn vec_tuple_extraction_test() {
        let res: Vec<(String, u32)> = fake_vec_query("foo").unwrap();
        assert_eq!(("tester".to_string(), 1985), res[0]);
        assert_eq!(("test2".to_string(), 1986), res[1]);
    }

    fn fake_vec_query<T: FromTable>(_query: &str) -> GraphResult<T> {
        query_with_statistics2().map(|(value, _)| value)
    }

    fn fake_query<T: FromTable>(_query: &str) -> GraphResult<T> {
        query_with_statistics().map(|(value, _)| value)
    }

    fn query_with_statistics<T: FromTable>() -> GraphResult<(T, Statistics)> {
        let result_set = get_result_set()?;
        let value = T::from_table(&result_set)?;
        Ok((value, result_set.statistics))
    }

    fn query_with_statistics2<T: FromTable>() -> GraphResult<(T, Statistics)> {
        let result_set = get_result_set2()?;
        let value = T::from_table(&result_set)?;
        Ok((value, result_set.statistics))
    }

    fn get_result_set() -> GraphResult<ResultSet> {
        Ok(ResultSet {
            statistics: Statistics(vec![]),
            columns: vec![
                Column::Scalars(vec![Scalar::String(GraphString::from(
                    "tester".to_string(),
                ))]),
                Column::Scalars(vec![Scalar::Integer(1985)]),
            ],
        })
    }

    fn get_result_set2() -> GraphResult<ResultSet> {
        Ok(ResultSet {
            statistics: Statistics(vec![]),
            columns: vec![
                Column::Scalars(vec![
                    Scalar::String(GraphString::from("tester".to_string())),
                    Scalar::String(GraphString::from("test2".to_string())),
                ]),
                Column::Scalars(vec![Scalar::Integer(1985), Scalar::Integer(1986)]),
            ],
        })
    }
}