1use rust_decimal::Decimal;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct WindowSpec {
7 pub duration: u64,
8 pub unit: String,
9}
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub enum Expression {
13 Literal(serde_json::Value),
14
15 QuantityLiteral {
16 value: Decimal,
17 unit: String,
18 },
19
20 TimeLiteral(String), IntervalLiteral {
23 start: String, end: String, },
26
27 Variable(String),
28
29 GroupBy {
30 variable: String,
31 collection: Box<Expression>,
32 filter: Option<Box<Expression>>,
33 key: Box<Expression>,
34 condition: Box<Expression>,
35 },
36
37 Binary {
38 op: BinaryOp,
39 left: Box<Expression>,
40 right: Box<Expression>,
41 },
42
43 Unary {
44 op: UnaryOp,
45 operand: Box<Expression>,
46 },
47
48 Cast {
49 operand: Box<Expression>,
50 target_type: String,
51 },
52
53 Quantifier {
54 quantifier: Quantifier,
55 variable: String,
56 collection: Box<Expression>,
57 condition: Box<Expression>,
58 },
59
60 MemberAccess {
61 object: String,
62 member: String,
63 },
64
65 Aggregation {
66 function: AggregateFunction,
67 collection: Box<Expression>,
68 field: Option<String>,
69 filter: Option<Box<Expression>>,
70 },
71
72 AggregationComprehension {
73 function: AggregateFunction,
74 variable: String,
75 collection: Box<Expression>,
76 window: Option<WindowSpec>,
77 predicate: Box<Expression>,
78 projection: Box<Expression>,
79 target_unit: Option<String>,
80 },
81
82 RoleReference {
86 role: String,
87 },
88}
89
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91pub enum BinaryOp {
92 And,
93 Or,
94
95 Equal,
96 NotEqual,
97 GreaterThan,
98 LessThan,
99 GreaterThanOrEqual,
100 LessThanOrEqual,
101
102 Plus,
103 Minus,
104 Multiply,
105 Divide,
106
107 Contains,
108 StartsWith,
109 EndsWith,
110 Matches,
111
112 HasRole,
113
114 Before,
116 After,
117 During,
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub enum UnaryOp {
122 Not,
123 Negate,
124}
125
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127pub enum Quantifier {
128 ForAll,
129 Exists,
130 ExistsUnique,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134pub enum AggregateFunction {
135 Count,
136 Sum,
137 Min,
138 Max,
139 Avg,
140}
141
142impl Expression {
143 #[must_use]
153 pub fn normalize(&self) -> super::NormalizedExpression {
154 super::NormalizedExpression::new(self)
155 }
156
157 #[must_use]
161 pub fn is_equivalent(&self, other: &Expression) -> bool {
162 self.normalize() == other.normalize()
163 }
164
165 pub fn literal(value: impl Into<serde_json::Value>) -> Self {
166 Expression::Literal(value.into())
167 }
168
169 pub fn variable(name: &str) -> Self {
170 Expression::Variable(name.to_string())
171 }
172
173 pub fn binary(op: BinaryOp, left: Expression, right: Expression) -> Self {
174 Expression::Binary {
175 op,
176 left: Box::new(left),
177 right: Box::new(right),
178 }
179 }
180
181 pub fn unary(op: UnaryOp, operand: Expression) -> Self {
182 Expression::Unary {
183 op,
184 operand: Box::new(operand),
185 }
186 }
187
188 pub fn quantifier(
189 q: Quantifier,
190 var: &str,
191 collection: Expression,
192 condition: Expression,
193 ) -> Self {
194 Expression::Quantifier {
195 quantifier: q,
196 variable: var.to_string(),
197 collection: Box::new(collection),
198 condition: Box::new(condition),
199 }
200 }
201
202 pub fn cast(operand: Expression, target_type: impl Into<String>) -> Self {
203 Expression::Cast {
204 operand: Box::new(operand),
205 target_type: target_type.into(),
206 }
207 }
208
209 pub fn comparison(
210 var: &str,
211 op: &str,
212 value: impl Into<serde_json::Value>,
213 ) -> Result<Self, String> {
214 let op = match op {
215 ">" => BinaryOp::GreaterThan,
216 "<" => BinaryOp::LessThan,
217 ">=" => BinaryOp::GreaterThanOrEqual,
218 "<=" => BinaryOp::LessThanOrEqual,
219 "==" => BinaryOp::Equal,
220 "!=" => BinaryOp::NotEqual,
221 _ => return Err(format!("Unknown operator: {}", op)),
222 };
223
224 Ok(Expression::binary(
225 op,
226 Expression::variable(var),
227 Expression::literal(value),
228 ))
229 }
230
231 pub fn aggregation(
232 function: AggregateFunction,
233 collection: Expression,
234 field: Option<impl Into<String>>,
235 filter: Option<Expression>,
236 ) -> Self {
237 Expression::Aggregation {
238 function,
239 collection: Box::new(collection),
240 field: field.map(|f| f.into()),
241 filter: filter.map(Box::new),
242 }
243 }
244
245 pub fn member_access(object: &str, member: &str) -> Self {
246 Expression::MemberAccess {
247 object: object.to_string(),
248 member: member.to_string(),
249 }
250 }
251}
252
253impl fmt::Display for Expression {
254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255 match self {
256 Expression::Literal(v) => write!(f, "{}", v),
257 Expression::QuantityLiteral { value, unit } => {
258 write!(f, "{} {}", value, unit)
259 }
260 Expression::TimeLiteral(timestamp) => write!(f, "\"{}\"", timestamp),
261 Expression::IntervalLiteral { start, end } => {
262 write!(f, "interval(\"{}\", \"{}\")", start, end)
263 }
264 Expression::Variable(n) => write!(f, "{}", n),
265 Expression::GroupBy {
266 variable,
267 collection,
268 filter,
269 key,
270 condition,
271 } => {
272 write!(
273 f,
274 "group_by({} in {}",
275 variable,
276 format_collection(collection)
277 )?;
278 if let Some(flt) = filter {
279 write!(f, " WHERE {}", flt)?;
280 }
281 write!(f, ": {}) {{ {} }}", key, condition)
282 }
283 Expression::Binary { op, left, right } => {
284 write!(f, "({} {} {})", left, op, right)
285 }
286 Expression::Unary { op, operand } => {
287 write!(f, "{} {}", op, operand)
288 }
289 Expression::Cast {
290 operand,
291 target_type,
292 } => {
293 write!(f, "{} as \"{}\"", operand, target_type)
294 }
295 Expression::Quantifier {
296 quantifier,
297 variable,
298 collection,
299 condition,
300 } => {
301 write!(
310 f,
311 "{} {} in {}: ",
312 quantifier_keyword(quantifier),
313 variable,
314 format_collection(collection)
315 )?;
316 if matches!(condition.as_ref(), Expression::Binary { .. }) {
317 write!(f, "{}", condition)
318 } else {
319 write!(f, "({})", condition)
320 }
321 }
322 Expression::MemberAccess { object, member } => {
323 write!(f, "{}.{}", object, member)
324 }
325 Expression::Aggregation {
326 function,
327 collection,
328 field,
329 filter,
330 } => {
331 write!(f, "{}({}", function, format_collection(collection))?;
332 if let Some(fld) = field {
333 write!(f, ".{}", fld)?;
334 }
335 if let Some(flt) = filter {
336 write!(f, " WHERE {}", flt)?;
337 }
338 write!(f, ")")
339 }
340 Expression::AggregationComprehension {
341 function,
342 variable,
343 collection,
344 window,
345 predicate,
346 projection,
347 target_unit,
348 } => {
349 write!(
350 f,
351 "{}({} in {}",
352 function,
353 variable,
354 format_collection(collection)
355 )?;
356 if let Some(w) = window {
357 write!(f, " OVER LAST {} \"{}\"", w.duration, w.unit)?;
358 }
359 match predicate.as_ref() {
360 Expression::Literal(serde_json::Value::Bool(true)) => {
361 write!(f, ": {}", projection)?;
362 }
363 _ => {
364 write!(f, " WHERE {}: {}", predicate, projection)?;
365 }
366 }
367 if let Some(unit) = target_unit {
368 write!(f, " AS \"{}\"", unit)?;
369 }
370 write!(f, ")")
371 }
372 Expression::RoleReference { role } => write!(f, "role<{}>", role),
373 }
374 }
375}
376
377impl fmt::Display for BinaryOp {
378 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
379 match self {
380 BinaryOp::And => write!(f, "AND"),
381 BinaryOp::Or => write!(f, "OR"),
382 BinaryOp::Equal => write!(f, "=="),
383 BinaryOp::NotEqual => write!(f, "!="),
384 BinaryOp::GreaterThan => write!(f, ">"),
385 BinaryOp::LessThan => write!(f, "<"),
386 BinaryOp::GreaterThanOrEqual => write!(f, ">="),
387 BinaryOp::LessThanOrEqual => write!(f, "<="),
388 BinaryOp::Plus => write!(f, "+"),
389 BinaryOp::Minus => write!(f, "-"),
390 BinaryOp::Multiply => write!(f, "*"),
391 BinaryOp::Divide => write!(f, "/"),
392 BinaryOp::Contains => write!(f, "CONTAINS"),
393 BinaryOp::StartsWith => write!(f, "STARTS_WITH"),
394 BinaryOp::EndsWith => write!(f, "ENDS_WITH"),
395 BinaryOp::Matches => write!(f, "MATCHES"),
396 BinaryOp::HasRole => write!(f, "HAS_ROLE"),
397 BinaryOp::Before => write!(f, "BEFORE"),
398 BinaryOp::After => write!(f, "AFTER"),
399 BinaryOp::During => write!(f, "DURING"),
400 }
401 }
402}
403
404impl fmt::Display for UnaryOp {
405 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406 match self {
407 UnaryOp::Not => write!(f, "NOT"),
408 UnaryOp::Negate => write!(f, "-"),
409 }
410 }
411}
412
413impl fmt::Display for Quantifier {
414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 match self {
416 Quantifier::ForAll => write!(f, "ForAll"),
417 Quantifier::Exists => write!(f, "Exists"),
418 Quantifier::ExistsUnique => write!(f, "ExistsUnique"),
419 }
420 }
421}
422
423fn quantifier_keyword(q: &Quantifier) -> &'static str {
428 match q {
429 Quantifier::ForAll => "forall",
430 Quantifier::Exists => "exists",
431 Quantifier::ExistsUnique => "exists_unique",
432 }
433}
434
435fn format_collection(collection: &Expression) -> String {
444 if let Expression::Variable(name) = collection {
445 if let Some(entity_type) = name.strip_prefix("entity_instances:") {
446 return format!("entity_instances of \"{}\"", entity_type);
447 }
448 }
449 collection.to_string()
450}
451
452impl fmt::Display for AggregateFunction {
453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
454 match self {
455 AggregateFunction::Count => write!(f, "COUNT"),
456 AggregateFunction::Sum => write!(f, "SUM"),
457 AggregateFunction::Min => write!(f, "MIN"),
458 AggregateFunction::Max => write!(f, "MAX"),
459 AggregateFunction::Avg => write!(f, "AVG"),
460 }
461 }
462}