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
430
431
432
433
434
435
436
437
438
//! CQLite provides an embedded property graph database.
//!
//! A `Graph` can store a number of nodes, as well as edges
//! forming relationships between those nodes. Each node or
//! edge has a set of zero or more key value pairs called properties.
//!
//! The graph supports ACID queries using a simplified subset of the
//! [`CYPHER`](https://opencypher.org) graph query language, which can
//! be run inside read-only or read-write transactions.
//!
//! # Example
//! ```
//! # fn test() -> Result<(), cqlite::Error> {
//! use cqlite::Graph;
//!
//! let graph = Graph::open_anon()?;
//!
//! let mut txn = graph.mut_txn()?;
//! let edge: u64 = graph.prepare(
//!         "
//!         CREATE (a:PERSON { name: 'Peter Parker' })
//!         CREATE (b:PERSON { name: 'Clark Kent' })
//!         CREATE (a) -[e:KNOWS]-> (b)
//!         RETURN ID(e)
//!         "
//!     )?
//!     .query_map(&mut txn, (), |m| m.get(0))?
//!     .next()
//!     .unwrap()?;
//! txn.commit()?;
//!
//! let name: String = graph.prepare(
//!         "
//!         MATCH (p:PERSON) <-[e:KNOWS]- (:PERSON)
//!         WHERE ID(e) = $edge
//!         RETURN p.name
//!         "
//!     )?
//!     .query_map(&mut graph.txn()?, ("edge", edge), |m| m.get(0))?
//!     .next()
//!     .unwrap()?;
//! assert_eq!("Clark Kent", name);
//! # Ok(())
//! # }
//! # test().unwrap();
//! ```

use planner::QueryPlan;
use runtime::{Program, Status, VirtualMachine};
use std::{convert::TryInto, path::Path};
use store::{Store, StoreTxn};

pub(crate) mod error;
pub(crate) mod params;
pub(crate) mod parser;
pub(crate) mod planner;
pub(crate) mod property;
pub(crate) mod runtime;
pub(crate) mod store;

#[cfg(feature = "ffi")]
mod ffi;

pub use error::Error;
pub use params::Params;
pub use property::Property;

/// A graph is a collection of nodes and edges.
///
/// Graphs may be held in-memory or persisted to a single
/// file and support ACID queries over the graph.
pub struct Graph {
    store: Store,
}

/// An ongoing transaction.
///
/// Any modifications to the graph that occurred during this transaction
/// are discarded unless the transaction is committed.
///
/// Once a transaction has started, it will not observe any later
/// modifications to the graph which occur inside other transactions.
pub struct Txn<'graph>(StoreTxn<'graph>);

/// A prepared statement.
pub struct Statement<'graph> {
    _graph: &'graph Graph,
    program: Program,
}

/// RAII guard which represents an ongoing query.
pub struct Query<'stmt, 'txn> {
    stmt: &'stmt Statement<'stmt>,
    vm: VirtualMachine<'stmt, 'txn, 'stmt>,
}

/// RAII guard which represents a set of nodes and edges
/// matching a query.
pub struct Match<'query> {
    query: &'query Query<'query, 'query>,
}

/// Iterator which yields all matches of the contained
/// query after mapping them with a user provided
/// function.
///
/// A `MappedQuery` can be obtained by calling
/// [`query_map`][Statement::query_map].
pub struct MappedQuery<'stmt, 'txn, F> {
    query: Query<'stmt, 'txn>,
    map: F,
}

impl Graph {
    /// Opens the file at the given path. If the file does not exist,
    /// it will be created. A newly created graph will start out empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::Graph;
    ///
    /// let graph = Graph::open("example.graph")?;
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let store = Store::open(path)?;
        Ok(Self { store })
    }

    /// Open an anonymous graph which is held in-memory.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::Graph;
    ///
    /// let graph = Graph::open_anon()?;
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn open_anon() -> Result<Self, Error> {
        let store = Store::open_anon()?;
        Ok(Self { store })
    }

    /// Prepare a statement given a query `&str`. Queries support
    /// a subset of the [`CYPHER`](https://opencypher.org) graph
    /// query language.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::Graph;
    ///
    /// let graph = Graph::open_anon()?;
    /// let stmt = graph.prepare(
    ///     "
    ///     MATCH (a:PERSON { name: 'Test', age: 42 })
    ///     RETURN ID(a)
    ///     "
    /// )?;
    /// let stmt = graph.prepare(
    ///     "
    ///     MATCH (a:PERSON) -[:KNOWS]-> (b:PERSON)
    ///     RETURN a.name, b.name
    ///     "
    /// )?;
    /// let stmt = graph.prepare(
    ///     "
    ///     MATCH (a:PERSON)
    ///     MATCH (b:PERSON)
    ///     CREATE (a) -[:KNOWS { since: 'today' }]-> (b)
    ///     "
    /// )?;
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn prepare<'graph>(&'graph self, query: &str) -> Result<Statement<'graph>, Error> {
        let ast = parser::parse(query)?;
        let plan = QueryPlan::new(&ast)?.optimize()?;
        Ok(Statement {
            _graph: self,
            program: Program::new(&plan)?,
        })
    }

    /// Start a new read-only transaction. There may be many simultaneous
    /// read-only transactions.
    pub fn txn(&self) -> Result<Txn, Error> {
        Ok(Txn(self.store.txn()?))
    }

    /// Start a new write transaction. Queries executed within this transaction
    /// may modify the graph. Multiple write transactions exclude each other.
    pub fn mut_txn(&self) -> Result<Txn, Error> {
        Ok(Txn(self.store.mut_txn()?))
    }
}

impl<'graph> Txn<'graph> {
    /// Commit any changes made to the graph using this transaction. This fails
    /// if the transaction was not created using [`mut_txn`][Graph::mut_txn].
    ///
    /// If a write transaction is dropped without calling `commit`, any modifications
    /// to the graph will be discarded.
    pub fn commit(self) -> Result<(), Error> {
        self.0.commit()
    }
}

impl<'graph> Statement<'graph> {
    /// Execute this statement. The returned `Query` RAII
    /// guard can be used to step through the produced matches.
    ///
    /// Queries may include parameters of the form `$identifier`.
    /// Parameters can be provided using the `params`
    /// argument, providing a value which implementing [`Params`][Params].
    /// If a value for a given parameter is not provided, it
    /// defaults to `NULL`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::Graph;
    ///
    /// let graph = Graph::open_anon()?;
    /// let stmt = graph.prepare(
    ///     "
    ///     CREATE (a:PERSON { message: $msg, age: 42 })
    ///     RETURN ID(a), a.message, a.age
    ///     "
    /// )?;
    ///
    /// let mut txn = graph.mut_txn()?;
    /// let mut query = stmt.query(&mut txn, ("msg", "Hello World!"))?;
    ///
    /// let m = query.step()?.unwrap();
    /// assert_eq!(m.get::<u64, _>(0)?, 0);
    /// assert_eq!(m.get::<String, _>(1)?, "Hello World!");
    /// assert_eq!(m.get::<i64, _>(2)?, 42);
    ///
    /// assert!(query.step()?.is_none());
    ///
    /// txn.commit()?;
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn query<'stmt, 'txn, P>(
        &'stmt self,
        txn: &'txn mut Txn<'graph>,
        params: P,
    ) -> Result<Query<'stmt, 'txn>, Error>
    where
        P: Params,
    {
        txn.0.flush()?;
        Ok(Query {
            stmt: self,
            vm: VirtualMachine::new(
                &mut txn.0,
                &self.program,
                params
                    .build()
                    .into_iter()
                    .map(|(k, v)| (k, v.to_internal()))
                    .collect(),
            ),
        })
    }

    /// Execute this statement and return an iterator which
    /// maps each match using a user-provided function.
    ///
    /// This is almost always more convenient than using
    /// [`query`][Statement::query] directly.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::Graph;
    ///
    /// let graph = Graph::open_anon()?;
    /// let stmt = graph.prepare(
    ///     "
    ///     CREATE (a:PERSON { message: $msg, age: 42 })
    ///     RETURN ID(a), a.message, a.age
    ///     "
    /// )?;
    ///
    /// let mut txn = graph.mut_txn()?;
    /// let nodes = stmt
    ///     .query_map(&mut txn, ("msg", "Hello World!"), |m| {
    ///         Ok((m.get(0)?, m.get(1)?, m.get(2)?))
    ///     })?
    ///     .collect::<Result<Vec<(u64, String, i64)>, _>>()?;
    ///
    /// assert_eq!(nodes, [(0, "Hello World!".into(), 42)]);
    ///
    /// txn.commit()?;
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn query_map<'stmt, 'txn, T, P, F>(
        &'stmt self,
        txn: &'txn mut Txn<'graph>,
        params: P,
        map: F,
    ) -> Result<MappedQuery<'stmt, 'txn, F>, Error>
    where
        P: Params,
        F: FnMut(Match<'_>) -> Result<T, Error>,
    {
        Ok(MappedQuery {
            query: self.query(txn, params)?,
            map,
        })
    }

    /// Run the query to completion, ignoring any
    /// values which may be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::Graph;
    ///
    /// let graph = Graph::open_anon()?;
    /// let mut txn = graph.mut_txn()?;
    /// graph
    ///     .prepare("CREATE (a:PERSON { message: $msg, age: 42 })")?
    ///     .execute(&mut txn, ("msg", "Hello World!"))?;
    /// txn.commit()?;
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn execute<'stmt, 'txn, P>(
        &'stmt self,
        txn: &'txn mut Txn<'graph>,
        params: P,
    ) -> Result<(), Error>
    where
        P: Params,
    {
        let mut query = self.query(txn, params)?;
        while query.step()?.is_some() {}
        txn.0.flush()?;
        Ok(())
    }
}

impl<'stmt, 'txn> Query<'stmt, 'txn> {
    /// Advance the query to the next return. If the query is
    /// completed, returns `None`, otherwise the match is
    /// returned.
    #[inline]
    pub fn step(&mut self) -> Result<Option<Match>, Error> {
        if self.stmt.program.returns.is_empty() {
            loop {
                match self.vm.run()? {
                    Status::Yield => continue,
                    Status::Halt => break Ok(None),
                }
            }
        } else {
            match self.vm.run()? {
                Status::Yield => Ok(Some(Match { query: self })),
                Status::Halt => Ok(None),
            }
        }
    }
}

impl<'query> Match<'query> {
    /// Return the nth expression from the queries `RETURN`
    /// statement. The index starts from `0`. Out of bounds
    /// indices return an error.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn test() -> Result<(), cqlite::Error> {
    /// use cqlite::{Graph, Property};
    ///
    /// let graph = Graph::open_anon()?;
    /// let stmt = graph.prepare("RETURN $first, $second, $third")?;
    /// let mut txn = graph.txn()?;
    /// let mut query = stmt.query(&mut txn, (("first", "one"), ("second", 2.0), ("third", 3)))?;
    ///
    /// let m = query.step()?.unwrap();
    /// assert_eq!(m.get::<String, _>(0)?, "one");
    /// assert_eq!(m.get::<f64, _>(1)?, 2.0);
    /// assert_eq!(m.get::<i64, _>(2)?, 3);
    /// assert!(m.get::<Property, _>(3).is_err());
    /// # Ok(())
    /// # }
    /// # test().unwrap();
    /// ```
    pub fn get<P, E>(&self, idx: usize) -> Result<P, Error>
    where
        Property: TryInto<P, Error = E>,
        Error: From<E>,
    {
        Ok(self.query.vm.access_return(idx)?.to_external().try_into()?)
    }

    /// Return the number of properties returned
    /// by this query.
    pub fn count(&self) -> usize {
        self.query.stmt.program.returns.len()
    }
}

impl<'stmt, 'txn, T, F> Iterator for MappedQuery<'stmt, 'txn, F>
where
    F: FnMut(Match<'_>) -> Result<T, Error>,
{
    type Item = Result<T, Error>;

    fn next(&mut self) -> Option<Result<T, Error>> {
        let query = &mut self.query;
        let map = &mut self.map;
        query.step().transpose().map(|res| res.and_then(map))
    }
}