Skip to main content

khive_query/
ast.rs

1//! GQL abstract syntax tree.
2
3use std::collections::HashMap;
4
5#[derive(Debug, Clone)]
6pub struct GqlQuery {
7    pub pattern: MatchPattern,
8    pub where_clause: Vec<Condition>,
9    pub return_items: Vec<ReturnItem>,
10    pub limit: Option<usize>,
11}
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ReturnItem {
15    Variable(String),
16    Property(String, String),
17}
18
19impl ReturnItem {
20    pub fn variable(&self) -> &str {
21        match self {
22            Self::Variable(v) | Self::Property(v, _) => v,
23        }
24    }
25}
26
27#[derive(Debug, Clone)]
28pub struct MatchPattern {
29    pub elements: Vec<PatternElement>,
30}
31
32impl MatchPattern {
33    pub fn nodes(&self) -> impl Iterator<Item = &NodePattern> {
34        self.elements.iter().filter_map(|e| match e {
35            PatternElement::Node(n) => Some(n),
36            _ => None,
37        })
38    }
39
40    pub fn edges(&self) -> impl Iterator<Item = &EdgePattern> {
41        self.elements.iter().filter_map(|e| match e {
42            PatternElement::Edge(e) => Some(e),
43            _ => None,
44        })
45    }
46
47    pub fn has_variable_length(&self) -> bool {
48        self.edges().any(|e| e.max_hops > 1)
49    }
50}
51
52#[derive(Debug, Clone)]
53pub enum PatternElement {
54    Node(NodePattern),
55    Edge(EdgePattern),
56}
57
58#[derive(Debug, Clone)]
59pub struct NodePattern {
60    pub variable: Option<String>,
61    pub kind: Option<String>,
62    pub properties: HashMap<String, String>,
63}
64
65#[derive(Debug, Clone)]
66pub struct EdgePattern {
67    pub variable: Option<String>,
68    pub relations: Vec<String>,
69    pub direction: EdgeDirection,
70    pub min_hops: usize,
71    pub max_hops: usize,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum EdgeDirection {
76    Out,
77    In,
78    Both,
79}
80
81#[derive(Debug, Clone)]
82pub struct Condition {
83    pub variable: String,
84    pub property: String,
85    pub op: CompareOp,
86    pub value: ConditionValue,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum CompareOp {
91    Eq,
92    Neq,
93    Gt,
94    Lt,
95    Gte,
96    Lte,
97    Like,
98}
99
100#[derive(Debug, Clone)]
101pub enum ConditionValue {
102    String(String),
103    Number(f64),
104    Bool(bool),
105}