falkordb 0.8.7

A FalkorDB Rust client
Documentation
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
 * Copyright FalkorDB Ltd. 2023 - present
 * Licensed under the MIT License.
 */

use crate::{parser::redis_value_as_untyped_string_vec, FalkorResult};
use std::str::FromStr;
use std::sync::Arc;

pub(crate) mod constraint;
pub(crate) mod execution_plan;
pub(crate) mod index;
pub(crate) mod lazy_result_set;
pub(crate) mod row;
#[cfg(test)]
mod row_proptest;
#[cfg(feature = "tokio")]
pub(crate) mod row_stream;
pub(crate) mod slowlog_entry;
#[cfg(feature = "serde")]
pub(crate) mod typed_result_set;
#[cfg(all(feature = "serde", feature = "tokio"))]
pub(crate) mod typed_row_stream;

#[derive(Copy, Clone, Debug, Eq, PartialEq, strum::IntoStaticStr)]
enum StatisticType {
    #[strum(serialize = "Labels added")]
    LabelsAdded,
    #[strum(serialize = "Labels removed")]
    LabelsRemoved,
    #[strum(serialize = "Nodes created")]
    NodesCreated,
    #[strum(serialize = "Nodes deleted")]
    NodesDeleted,
    #[strum(serialize = "Properties set")]
    PropertiesSet,
    #[strum(serialize = "Properties removed")]
    PropertiesRemoved,
    #[strum(serialize = "Indices created")]
    IndicesCreated,
    #[strum(serialize = "Indices deleted")]
    IndicesDeleted,
    #[strum(serialize = "Relationships created")]
    RelationshipsCreated,
    #[strum(serialize = "Relationships deleted")]
    RelationshipsDeleted,
    #[strum(serialize = "Cached execution")]
    CachedExecution,
    #[strum(serialize = "internal execution time")]
    InternalExecutionTime,
}

/// A response struct which also contains the returned header and stats data
#[derive(Clone, Debug, Default)]
pub struct QueryResult<T> {
    /// Header for the result data: the column aliases, shared cheaply with each
    /// [`Row`](crate::Row) the result set yields.
    pub header: Arc<[String]>,
    /// The actual data returned from the database
    pub data: T,
    /// Various statistics regarding the request, such as execution time and number of successful operations
    pub stats: Vec<String>,
}

impl<T> QueryResult<T> {
    /// Creates a [`QueryResult`] from the specified data, an already-parsed `header`, and raw stats.
    ///
    /// # Arguments
    /// * `header`: the column aliases, parsed once and shared with the result set's rows
    /// * `data`: The actual data
    /// * `stats`: a [`redis::Value`] that is expected to be of variant [`redis::Value::Array`], where each element is expected to be of variant [`redis::Value::BulkString`], [`redis::Value::VerbatimString`] or [`redis::Value::SimpleString`]
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(name = "New Falkor Response", skip_all, level = "trace")
    )]
    pub fn from_response(
        header: Arc<[String]>,
        data: T,
        stats: redis::Value,
    ) -> FalkorResult<Self> {
        Ok(Self {
            header,
            data,
            stats: redis_value_as_untyped_string_vec(stats)?,
        })
    }

    fn get_statistics<S>(
        &self,
        stat_type: StatisticType,
    ) -> Option<S>
    where
        S: FromStr,
    {
        for stat in self.stats.iter() {
            if stat.contains(Into::<&'static str>::into(stat_type)) {
                // Splits the statistic string by ': ', then retrieves and parses the statistic value.
                return stat
                    .split(": ")
                    .nth(1)
                    .and_then(|stat_value| stat_value.split(' ').next())
                    .and_then(|res| res.parse().ok());
            }
        }

        None
    }

    /// Returns the number of labels added in this query
    pub fn get_labels_added(&self) -> Option<i64> {
        self.get_statistics(StatisticType::LabelsAdded)
    }

    /// Returns the number of labels removed in this query
    pub fn get_labels_removed(&self) -> Option<i64> {
        self.get_statistics(StatisticType::LabelsRemoved)
    }

    /// Returns the number of nodes created in this query
    pub fn get_nodes_created(&self) -> Option<i64> {
        self.get_statistics(StatisticType::NodesCreated)
    }

    /// Returns the number of nodes deleted in this query
    pub fn get_nodes_deleted(&self) -> Option<i64> {
        self.get_statistics(StatisticType::NodesDeleted)
    }

    /// Returns the number of properties set in this query
    pub fn get_properties_set(&self) -> Option<i64> {
        self.get_statistics(StatisticType::PropertiesSet)
    }

    /// Returns the number of properties removed in this query
    pub fn get_properties_removed(&self) -> Option<i64> {
        self.get_statistics(StatisticType::PropertiesRemoved)
    }

    /// Returns the number of indices created in this query
    pub fn get_indices_created(&self) -> Option<i64> {
        self.get_statistics(StatisticType::IndicesCreated)
    }

    /// Returns the number of indices deleted in this query
    pub fn get_indices_deleted(&self) -> Option<i64> {
        self.get_statistics(StatisticType::IndicesDeleted)
    }

    /// Returns the number of relationships created in this query
    pub fn get_relationship_created(&self) -> Option<i64> {
        self.get_statistics(StatisticType::RelationshipsCreated)
    }

    /// Returns the number of relationships deleted in this query
    pub fn get_relationship_deleted(&self) -> Option<i64> {
        self.get_statistics(StatisticType::RelationshipsDeleted)
    }

    /// Returns whether this query was ran from cache
    pub fn get_cached_execution(&self) -> Option<bool> {
        self.get_statistics(StatisticType::CachedExecution)
            .map(|res: i64| res != 0)
    }

    /// Returns the internal execution time of this query
    pub fn get_internal_execution_time(&self) -> Option<f64> {
        self.get_statistics(StatisticType::InternalExecutionTime)
    }
}

#[cfg(feature = "serde")]
impl<'a> QueryResult<crate::LazyResultSet<'a>> {
    /// Convert this result set into one whose rows are deserialized into `T` on demand.
    ///
    /// The [`header`](Self::header) and [`stats`](Self::stats) are preserved; only `data` is
    /// replaced by a [`TypedLazyResultSet`](crate::TypedLazyResultSet) that maps each row with
    /// [`Row::deserialize`](crate::Row::deserialize).
    pub(crate) fn into_typed<T>(self) -> QueryResult<typed_result_set::TypedLazyResultSet<'a, T>> {
        QueryResult {
            data: typed_result_set::TypedLazyResultSet::new(self.data),
            header: self.header,
            stats: self.stats,
        }
    }
}

#[cfg(all(feature = "serde", feature = "tokio"))]
impl QueryResult<crate::RowStream> {
    /// Convert this owned result set into one whose rows are deserialized into `T` on demand,
    /// preserving the [`header`](Self::header) and [`stats`](Self::stats).
    pub(crate) fn into_typed<T>(self) -> QueryResult<crate::TypedRowStream<T>> {
        QueryResult {
            data: typed_row_stream::TypedRowStream::new(self.data),
            header: self.header,
            stats: self.stats,
        }
    }
}

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

    #[test]
    fn test_get_statistics() {
        let mut graph = open_empty_test_graph("imdb_stats_test");
        {
            let query_result = graph
                .inner
                .query("CREATE (a:new_node { new_property: 1})-[b:new_relationship]->(a)")
                .execute()
                .expect("Could not run query");

            assert!(query_result.get_internal_execution_time().is_some());
            assert_eq!(query_result.get_nodes_created(), Some(1));
            assert_eq!(query_result.get_relationship_created(), Some(1));
            assert_eq!(query_result.get_properties_set(), Some(1));
        }
        {
            let query_result = graph
                .inner
                .query(
                    "MATCH (a:new_node { new_property: 1})-[b:new_relationship]->(a) DELETE b, a",
                )
                .execute()
                .expect("Could not run query");
            assert_eq!(query_result.get_nodes_deleted(), Some(1));
            assert_eq!(query_result.get_relationship_deleted(), Some(1));
        }

        {
            let query_result = graph
                .inner
                .query("UNWIND range(0, 1000) AS x RETURN x")
                .execute()
                .expect("Could not run query");
            assert_eq!(query_result.get_cached_execution(), Some(false));
        }

        {
            let query_result = graph
                .inner
                .query("UNWIND range(0, 1000) AS x RETURN x")
                .execute()
                .expect("Could not run query");
            assert_eq!(query_result.get_cached_execution(), Some(true));
        }
    }

    #[test]
    fn test_query_result_default() {
        let result: QueryResult<Vec<String>> = QueryResult::default();
        assert!(result.header.is_empty());
        assert!(result.data.is_empty());
        assert!(result.stats.is_empty());
    }

    #[test]
    fn test_query_result_clone() {
        let result = QueryResult {
            header: vec!["col1".to_string()].into(),
            data: vec!["value1".to_string()],
            stats: vec!["Nodes created: 5".to_string()],
        };

        let result_clone = result.clone();
        assert_eq!(result.header, result_clone.header);
        assert_eq!(result.data, result_clone.data);
        assert_eq!(result.stats, result_clone.stats);
    }

    #[test]
    fn test_query_result_debug() {
        let result = QueryResult {
            header: vec!["name".to_string()].into(),
            data: vec!["Alice".to_string()],
            stats: vec!["Query internal execution time: 0.5 milliseconds".to_string()],
        };

        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("name"));
        assert!(debug_str.contains("Alice"));
    }

    #[test]
    fn test_get_labels_added() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Labels added: 10".to_string()],
        };
        assert_eq!(result.get_labels_added(), Some(10));
    }

    #[test]
    fn test_get_labels_removed() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Labels removed: 5".to_string()],
        };
        assert_eq!(result.get_labels_removed(), Some(5));
    }

    #[test]
    fn test_get_nodes_created() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Nodes created: 20".to_string()],
        };
        assert_eq!(result.get_nodes_created(), Some(20));
    }

    #[test]
    fn test_get_nodes_deleted() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Nodes deleted: 8".to_string()],
        };
        assert_eq!(result.get_nodes_deleted(), Some(8));
    }

    #[test]
    fn test_get_properties_set() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Properties set: 15".to_string()],
        };
        assert_eq!(result.get_properties_set(), Some(15));
    }

    #[test]
    fn test_get_properties_removed() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Properties removed: 3".to_string()],
        };
        assert_eq!(result.get_properties_removed(), Some(3));
    }

    #[test]
    fn test_get_indices_created() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Indices created: 2".to_string()],
        };
        assert_eq!(result.get_indices_created(), Some(2));
    }

    #[test]
    fn test_get_indices_deleted() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Indices deleted: 1".to_string()],
        };
        assert_eq!(result.get_indices_deleted(), Some(1));
    }

    #[test]
    fn test_get_relationship_created() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Relationships created: 12".to_string()],
        };
        assert_eq!(result.get_relationship_created(), Some(12));
    }

    #[test]
    fn test_get_relationship_deleted() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Relationships deleted: 7".to_string()],
        };
        assert_eq!(result.get_relationship_deleted(), Some(7));
    }

    #[test]
    fn test_get_internal_execution_time() {
        let result = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Query internal execution time: 1.234 milliseconds".to_string()],
        };
        assert_eq!(result.get_internal_execution_time(), Some(1.234));
    }

    #[test]
    fn test_get_statistics_none() {
        let result: QueryResult<()> = QueryResult {
            header: Vec::new().into(),
            data: (),
            stats: vec!["Some other stat: 100".to_string()],
        };
        assert_eq!(result.get_nodes_created(), None);
    }

    #[test]
    fn test_statistic_type_clone() {
        let stat = StatisticType::NodesCreated;
        let stat_clone = stat;
        assert_eq!(stat, stat_clone);
    }

    #[test]
    fn test_statistic_type_debug() {
        assert!(format!("{:?}", StatisticType::NodesCreated).contains("NodesCreated"));
    }

    #[test]
    fn test_statistic_type_into_static_str() {
        let s: &'static str = StatisticType::NodesCreated.into();
        assert_eq!(s, "Nodes created");

        let s: &'static str = StatisticType::LabelsAdded.into();
        assert_eq!(s, "Labels added");

        let s: &'static str = StatisticType::RelationshipsDeleted.into();
        assert_eq!(s, "Relationships deleted");
    }
}