interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! # GQL Parser, Compiler, and Mutation Executor
//!
//! This module provides GQL (Graph Query Language) support for Interstellar.
//! GQL is a declarative query language for property graphs, offering a
//! SQL-like syntax for pattern matching, data retrieval, and mutations.
//!
//! ## Overview
//!
//! The GQL implementation follows a pipeline architecture:
//!
//! ```text
//! GQL Query Text → Parser → AST → Compiler/Executor → Results
//! ```
//!
//! 1. **Parser** ([`parse`], [`parse_statement`]): Converts GQL text into a typed AST
//! 2. **Compiler** ([`compile`]): Transforms read-only AST into traversal operations
//! 3. **Mutation Executor** ([`execute_mutation`]): Executes mutation statements
//! 4. **Execution**: The traversal engine or mutation executor processes the query
//!
//! ## Quick Start - Read Queries
//!
//! The simplest way to execute a GQL query is through [`GraphSnapshot::gql()`](crate::storage::GraphSnapshot::gql):
//!
//! ```rust
//! use interstellar::prelude::*;
//! use std::collections::HashMap;
//! use std::sync::Arc;
//!
//! // Create a graph with data
//! let graph = Arc::new(Graph::new());
//! graph.add_vertex("Person", HashMap::from([
//!     ("name".to_string(), Value::from("Alice")),
//!     ("age".to_string(), Value::from(30i64)),
//! ]));
//!
//! let snapshot = graph.snapshot();
//!
//! // Execute GQL query
//! let results = graph.gql("MATCH (n:Person) RETURN n").unwrap();
//! assert_eq!(results.len(), 1);
//! ```
//!
//! ## Quick Start - Mutations
//!
//! For mutations (CREATE, SET, DELETE, etc.), use [`execute_mutation`] with mutable storage:
//!
//! ```rust
//! use interstellar::gql::{parse_statement, execute_mutation};
//! use interstellar::storage::{Graph, GraphStorage};
//!
//! let graph = Graph::new();
//! let mut storage = graph.as_storage_mut();
//!
//! // CREATE a new vertex
//! let stmt = parse_statement("CREATE (n:Person {name: 'Alice', age: 30})").unwrap();
//! execute_mutation(&stmt, &mut storage).unwrap();
//!
//! assert_eq!(storage.vertex_count(), 1);
//!
//! // UPDATE with SET
//! let stmt = parse_statement("MATCH (n:Person {name: 'Alice'}) SET n.age = 31").unwrap();
//! execute_mutation(&stmt, &mut storage).unwrap();
//!
//! // DELETE
//! let stmt = parse_statement("MATCH (n:Person {name: 'Alice'}) DELETE n").unwrap();
//! execute_mutation(&stmt, &mut storage).unwrap();
//!
//! assert_eq!(storage.vertex_count(), 0);
//! ```
//!
//! ## Supported Features
//!
//! ### MATCH Clause - Pattern Matching
//!
//! The `MATCH` clause specifies patterns to find in the graph.
//!
//! **Node patterns:**
//! ```text
//! (n)                         -- Any vertex, bound to variable 'n'
//! (n:Person)                  -- Vertex with label 'Person'
//! (n:Person:Employee)         -- Vertex with multiple labels
//! (n {name: 'Alice'})         -- Vertex with property constraint
//! (n:Person {name: 'Alice'})  -- Label and property constraint
//! (:Person)                   -- Anonymous (unbound) vertex
//! ```
//!
//! **Edge patterns:**
//! ```text
//! -[:KNOWS]->                 -- Outgoing edge with label 'KNOWS'
//! <-[:KNOWS]-                 -- Incoming edge
//! -[:KNOWS]-                  -- Bidirectional (either direction)
//! -[e:KNOWS]->                -- Edge bound to variable 'e'
//! -[]->                       -- Any outgoing edge
//! ```
//!
//! **Variable-length paths:**
//! ```text
//! -[:KNOWS*]->                -- Any number of hops (default max: 10)
//! -[:KNOWS*2]->               -- Exactly 2 hops
//! -[:KNOWS*1..3]->            -- 1 to 3 hops
//! -[:KNOWS*..5]->             -- 0 to 5 hops (includes start vertex)
//! -[:KNOWS*2..]->             -- 2 or more hops
//! ```
//!
//! **Complete pattern example:**
//! ```rust
//! # use interstellar::prelude::*;
//! # use std::sync::Arc;
//! # let graph = Arc::new(Graph::in_memory());
//! # let snapshot = graph.snapshot();
//! let results = graph.gql(r#"
//!     MATCH (a:Person {name: 'Alice'})-[:KNOWS]->(friend:Person)
//!     RETURN friend
//! "#);
//! ```
//!
//! ### WHERE Clause - Filtering
//!
//! The `WHERE` clause filters results using boolean expressions.
//!
//! **Comparison operators:**
//! - `=`, `<>`, `!=` - Equality and inequality
//! - `<`, `<=`, `>`, `>=` - Numeric/string comparison
//!
//! **Logical operators:**
//! - `AND` - Logical conjunction
//! - `OR` - Logical disjunction
//! - `NOT` - Logical negation
//!
//! **String operators:**
//! - `CONTAINS` - Substring match
//! - `STARTS WITH` - Prefix match
//! - `ENDS WITH` - Suffix match
//!
//! **Null checks:**
//! - `IS NULL` - Check for missing property
//! - `IS NOT NULL` - Check for existing property
//!
//! **List membership:**
//! - `IN [...]` - Value in list
//! - `NOT IN [...]` - Value not in list
//!
//! **Examples:**
//! ```rust
//! # use interstellar::prelude::*;
//! # use std::sync::Arc;
//! # let graph = Arc::new(Graph::in_memory());
//! # let snapshot = graph.snapshot();
//! // Numeric comparison
//! let _ = graph.gql("MATCH (p:Person) WHERE p.age > 25 RETURN p");
//!
//! // Combined conditions
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     WHERE p.age >= 25 AND p.age <= 35
//!     RETURN p
//! "#);
//!
//! // String matching
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     WHERE p.name STARTS WITH 'A'
//!     RETURN p
//! "#);
//!
//! // Null check
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     WHERE p.email IS NOT NULL
//!     RETURN p
//! "#);
//!
//! // List membership
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     WHERE p.status IN ['active', 'pending']
//!     RETURN p
//! "#);
//! ```
//!
//! ### RETURN Clause - Result Projection
//!
//! The `RETURN` clause specifies what data to return.
//!
//! **Return types:**
//! - Variables: `RETURN n` - Returns the vertex/edge
//! - Properties: `RETURN n.name` - Returns property value
//! - Aliases: `RETURN n.name AS personName` - Rename in output
//! - Multiple items: `RETURN n.name, n.age` - Returns a map
//! - Literals: `RETURN 'constant'` - Returns constant value
//! - Distinct: `RETURN DISTINCT n.city` - Deduplicate results
//!
//! **Aggregate functions:**
//! - `COUNT(*)` - Count all results
//! - `COUNT(expr)` - Count non-null values
//! - `COUNT(DISTINCT expr)` - Count unique values
//! - `SUM(expr)` - Sum numeric values
//! - `AVG(expr)` - Average of numeric values
//! - `MIN(expr)` - Minimum value
//! - `MAX(expr)` - Maximum value
//! - `COLLECT(expr)` - Collect values into a list
//!
//! **Examples:**
//! ```rust
//! # use interstellar::prelude::*;
//! # use std::sync::Arc;
//! # let graph = Arc::new(Graph::in_memory());
//! # let snapshot = graph.snapshot();
//! // Return multiple properties as a map
//! let _ = graph.gql("MATCH (p:Person) RETURN p.name, p.age");
//!
//! // With aliases
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     RETURN p.name AS name, p.age AS years
//! "#);
//!
//! // Aggregation
//! let _ = graph.gql("MATCH (p:Person) RETURN count(*)");
//! let _ = graph.gql("MATCH (p:Person) RETURN avg(p.age)");
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     RETURN count(DISTINCT p.city) AS uniqueCities
//! "#);
//! ```
//!
//! ### ORDER BY Clause - Sorting
//!
//! Sort results by one or more expressions.
//!
//! ```rust
//! # use interstellar::prelude::*;
//! # use std::sync::Arc;
//! # let graph = Arc::new(Graph::in_memory());
//! # let snapshot = graph.snapshot();
//! // Ascending (default)
//! let _ = graph.gql("MATCH (p:Person) RETURN p ORDER BY p.age");
//!
//! // Descending
//! let _ = graph.gql("MATCH (p:Person) RETURN p ORDER BY p.age DESC");
//!
//! // Multiple sort keys
//! let _ = graph.gql(r#"
//!     MATCH (p:Person)
//!     RETURN p
//!     ORDER BY p.age DESC, p.name ASC
//! "#);
//! ```
//!
//! ### LIMIT/OFFSET Clause - Pagination
//!
//! Limit the number of results and skip initial results.
//!
//! ```rust
//! # use interstellar::prelude::*;
//! # use std::sync::Arc;
//! # let graph = Arc::new(Graph::in_memory());
//! # let snapshot = graph.snapshot();
//! // First 10 results
//! let _ = graph.gql("MATCH (p:Person) RETURN p LIMIT 10");
//!
//! // Pagination: skip 20, take 10
//! let _ = graph.gql("MATCH (p:Person) RETURN p LIMIT 10 OFFSET 20");
//! ```
//!
//! ## Complete Query Example
//!
//! ```rust
//! # use interstellar::prelude::*;
//! # use std::sync::Arc;
//! # let graph = Arc::new(Graph::in_memory());
//! # let snapshot = graph.snapshot();
//! let results = graph.gql(r#"
//!     MATCH (p:Person)-[:KNOWS]->(friend:Person)
//!     WHERE p.age > 25 AND friend.city = 'NYC'
//!     RETURN p.name AS person, friend.name AS friendName, friend.age
//!     ORDER BY friend.age DESC
//!     LIMIT 10
//! "#);
//! ```
//!
//! ## Error Handling
//!
//! GQL operations can fail with two types of errors:
//!
//! - [`ParseError`] - Syntax errors in the query text
//! - [`CompileError`] - Semantic errors (undefined variables, type mismatches)
//!
//! Both are wrapped in [`GqlError`] when using [`Graph::gql()`](crate::storage::Graph::gql).
//!
//! ```rust
//! use interstellar::prelude::*;
//! use interstellar::gql::GqlError;
//! use std::sync::Arc;
//!
//! let graph = Arc::new(Graph::in_memory());
//! let snapshot = graph.snapshot();
//!
//! match graph.gql("MATCH (n:Person) RETURN x") {
//!     Ok(results) => println!("Found {} results", results.len()),
//!     Err(GqlError::Parse(e)) => eprintln!("Syntax error: {}", e),
//!     Err(GqlError::Compile(e)) => eprintln!("Compilation error: {}", e),
//!     Err(GqlError::Mutation(e)) => eprintln!("Mutation error: {}", e),
//! }
//! ```
//!
//! ## Mutation Clauses
//!
//! GQL mutations allow you to modify the graph declaratively.
//!
//! ### CREATE - Add New Elements
//!
//! ```text
//! CREATE (n:Person {name: 'Alice', age: 30})
//! CREATE (a:Person)-[:KNOWS]->(b:Person)
//! CREATE (n:Person {name: 'Alice'}) RETURN n
//! ```
//!
//! ### SET - Update Properties
//!
//! ```text
//! MATCH (n:Person {name: 'Alice'}) SET n.age = 31
//! MATCH (n:Person) SET n.updated = true, n.timestamp = 123
//! ```
//!
//! ### REMOVE - Remove Properties
//!
//! ```text
//! MATCH (n:Person) REMOVE n.temporary_field
//! ```
//!
//! ### DELETE - Remove Elements
//!
//! ```text
//! MATCH (n:Person {status: 'inactive'}) DELETE n
//! MATCH ()-[r:OLD_RELATION]->() DELETE r
//! ```
//!
//! Note: DELETE fails if a vertex has connected edges. Use DETACH DELETE instead.
//!
//! ### DETACH DELETE - Remove Vertices with Edges
//!
//! ```text
//! MATCH (n:Person {name: 'Alice'}) DETACH DELETE n
//! ```
//!
//! DETACH DELETE removes the vertex and all connected edges automatically.
//!
//! ### MERGE - Upsert Operation
//!
//! ```text
//! MERGE (n:Person {name: 'Alice'}) ON CREATE SET n.created = true
//! MERGE (n:Person {name: 'Alice'}) ON MATCH SET n.lastSeen = 123
//! MERGE (n:Person {name: 'Alice'}) ON CREATE SET n.new = true ON MATCH SET n.existing = true
//! ```
//!
//! MERGE creates the pattern if it doesn't exist, or matches existing elements.
//!
//! ## Limitations
//!
//! The current implementation does not support:
//!
//! - **UNWIND**: No list unpacking in queries
//! - **Subqueries**: No nested queries or `CALL` procedures
//! - **Multiple graphs**: Single graph queries only
//! - **Path expressions**: Cannot return paths directly (use variable-length
//!   patterns and return endpoints)
//! - **Anonymous endpoint patterns**: `MATCH ()-[r]->()` requires explicit labels
//!
//! ## Architecture
//!
//! For implementers, the module is organized as:
//!
//! - [`ast`](ast) - AST type definitions ([`Query`], [`Pattern`], [`Expression`], etc.)
//! - [`parser`](parser) - pest-based parser (grammar in `grammar.pest`)
//! - [`compiler`](compiler) - AST to traversal compiler for read queries
//! - [`mutation`](mutation) - Mutation execution engine ([`execute_mutation`], [`MutationContext`])
//! - [`error`](error) - Error types with source span information
//!
//! The parser uses the [pest](https://pest.rs) parsing library with a PEG grammar.
//! The compiler transforms read AST nodes into calls to the traversal API.
//! The mutation executor directly modifies storage via [`GraphStorageMut`](crate::storage::GraphStorageMut).

mod ast;
mod compiler;
mod ddl;
mod error;
mod mutation;
mod parser;

pub use ast::*;
pub use compiler::{
    compile, compile_statement, compile_statement_with_config, compile_statement_with_graph,
    compile_statement_with_params, compile_statement_with_params_and_graph, compile_with_config,
    compile_with_params, CompilerConfig, Parameters,
};
pub use ddl::{create_index_spec, create_index_spec_for_edge, execute_ddl};
pub use error::{CompileError, GqlError, ParseError, Span};
pub use mutation::{
    execute_mutation, execute_mutation_query, execute_mutation_query_with_schema,
    execute_mutation_with_schema, Element, MutationContext, MutationError,
};
pub use parser::{parse, parse_statement};