1use super::expression::{AggregateFunction, BinaryOp, Expression, Quantifier};
2use crate::graph::Graph;
3use rust_decimal::prelude::ToPrimitive;
4use rust_decimal::Decimal;
5use std::convert::TryFrom;
6use std::str::FromStr;
7
8impl Expression {
9 pub fn expand(&self, graph: &Graph) -> Result<Expression, String> {
10 match self {
11 Expression::Quantifier {
12 quantifier,
13 variable,
14 collection,
15 condition,
16 } => {
17 let items = Self::get_collection(collection, graph)?;
18
19 match quantifier {
20 Quantifier::ForAll => {
21 if items.is_empty() {
22 return Ok(Expression::literal(true));
23 }
24
25 let mut result = Expression::literal(true);
26 for item in items {
27 let substituted = condition.substitute(variable, &item)?;
28 let expanded = substituted.expand(graph)?;
29 result = Expression::binary(BinaryOp::And, result, expanded);
30 }
31 Ok(result)
32 }
33 Quantifier::Exists => {
34 if items.is_empty() {
35 return Ok(Expression::literal(false));
36 }
37
38 let mut result = Expression::literal(false);
39 for item in items {
40 let substituted = condition.substitute(variable, &item)?;
41 let expanded = substituted.expand(graph)?;
42 result = Expression::binary(BinaryOp::Or, result, expanded);
43 }
44 Ok(result)
45 }
46 Quantifier::ExistsUnique => {
47 let mut count = 0;
48 let mut saw_unknown = false;
49 for item in items {
50 let substituted = condition.substitute(variable, &item)?;
51 let expanded = substituted.expand(graph)?;
52
53 if Self::is_true_literal(&expanded) {
54 count += 1;
55 } else if matches!(&expanded,
56 Expression::Literal(v) if v.as_bool().is_none())
57 {
58 saw_unknown = true;
61 }
62 }
63 if graph.use_three_valued_logic() {
68 if count > 1 {
69 return Ok(Expression::literal(false));
70 }
71 if saw_unknown {
72 return Ok(Expression::Literal(serde_json::Value::Null));
73 }
74 }
75 Ok(Expression::literal(count == 1))
76 }
77 }
78 }
79 Expression::GroupBy {
80 variable,
81 collection,
82 filter,
83 key,
84 condition,
85 } => {
86 let items = Self::get_collection(collection, graph)?;
87
88 let filtered_items = if let Some(filter_expr) = filter {
90 let mut filtered = Vec::new();
91 for item in items {
92 let substituted = filter_expr.substitute(variable, &item)?;
93 let expanded = substituted.expand(graph)?;
94 if Self::is_true_literal(&expanded) {
95 filtered.push(item);
96 }
97 }
98 filtered
99 } else {
100 items
101 };
102
103 let mut groups: std::collections::HashMap<String, Vec<serde_json::Value>> =
105 std::collections::HashMap::new();
106 for item in filtered_items {
107 let substituted_key = key.substitute(variable, &item)?;
108 let expanded_key = substituted_key.expand(graph)?;
109 let key_str = match expanded_key {
110 Expression::Literal(v) => match v {
111 serde_json::Value::String(s) => s,
112 serde_json::Value::Number(n) => n.to_string(),
113 serde_json::Value::Bool(b) => b.to_string(),
114 serde_json::Value::Null => "null".to_string(),
115 other => {
116 return Err(format!(
117 "Group key must be a string, number, bool, or null literal, got {}",
118 other
119 ))
120 }
121 },
122 _ => {
123 return Err("Group key must evaluate to a literal".to_string());
124 }
125 };
126 groups.entry(key_str).or_default().push(item);
127 }
128
129 for (_group_key, group_items) in groups {
131 let substituted_condition =
134 condition.substitute(variable, &serde_json::Value::Array(group_items))?;
135 let expanded = substituted_condition.expand(graph)?;
136 if !Self::is_true_literal(&expanded) {
137 return Ok(Expression::literal(false));
138 }
139 }
140 Ok(Expression::literal(true))
141 }
142 Expression::Binary { op, left, right } => {
143 let left_expanded = left.expand(graph)?;
144 let right_expanded = right.expand(graph)?;
145 Ok(Self::reduce_binary_expression(
146 op,
147 left_expanded,
148 right_expanded,
149 )?)
150 }
151 Expression::Unary { op, operand } => {
152 Ok(Expression::unary(op.clone(), operand.expand(graph)?))
153 }
154 Expression::MemberAccess { .. } => Ok(self.clone()),
155 Expression::Aggregation {
156 function,
157 collection,
158 field,
159 filter,
160 } => {
161 let result =
163 Self::evaluate_aggregation(function, collection, field, filter, graph)?;
164 Ok(Expression::Literal(result))
165 }
166 Expression::AggregationComprehension {
167 function,
168 variable,
169 collection,
170 window,
171 predicate,
172 projection,
173 target_unit,
174 } => {
175 let result = Self::evaluate_aggregation_comprehension(
176 function,
177 variable,
178 collection,
179 window,
180 predicate,
181 projection,
182 target_unit.as_deref(),
183 graph,
184 )?;
185 Ok(Expression::Literal(result))
186 }
187 _ => Ok(self.clone()),
188 }
189 }
190
191 pub fn substitute(&self, var: &str, value: &serde_json::Value) -> Result<Expression, String> {
192 match self {
193 Expression::Variable(n) => {
194 if n == var {
195 Ok(Expression::Literal(value.clone()))
196 } else if n.starts_with(&format!("{}.", var)) {
197 let field = &n[var.len() + 1..];
198 if let Some(field_value) = value.get(field) {
199 Ok(Expression::Literal(field_value.clone()))
200 } else {
201 Ok(Expression::Literal(serde_json::Value::Null))
206 }
207 } else {
208 Ok(self.clone())
209 }
210 }
211 Expression::Binary { op, left, right } => Ok(Expression::binary(
212 op.clone(),
213 left.substitute(var, value)?,
214 right.substitute(var, value)?,
215 )),
216 Expression::Unary { op, operand } => Ok(Expression::unary(
217 op.clone(),
218 operand.substitute(var, value)?,
219 )),
220 Expression::Quantifier {
221 quantifier,
222 variable,
223 collection,
224 condition,
225 } => {
226 if var == variable {
227 Ok(Expression::quantifier(
230 quantifier.clone(),
231 variable,
232 collection.substitute(var, value)?,
233 *condition.clone(),
234 ))
235 } else {
236 Ok(Expression::quantifier(
238 quantifier.clone(),
239 variable,
240 collection.substitute(var, value)?,
241 condition.substitute(var, value)?,
242 ))
243 }
244 }
245 Expression::MemberAccess { object, member } => {
246 if object == var {
247 if let Some(field_value) = value.get(member) {
248 Ok(Expression::Literal(field_value.clone()))
249 } else {
250 Ok(Expression::Literal(serde_json::Value::Null))
251 }
252 } else {
253 Ok(self.clone())
254 }
255 }
256 Expression::Aggregation {
257 function,
258 collection,
259 field,
260 filter,
261 } => Ok(Expression::aggregation(
262 function.clone(),
263 collection.substitute(var, value)?,
264 field.clone(),
265 filter
266 .as_ref()
267 .map(|f| f.substitute(var, value))
268 .transpose()?,
269 )),
270 Expression::AggregationComprehension {
271 function,
272 variable,
273 collection,
274 window,
275 predicate,
276 projection,
277 target_unit,
278 } => Ok(Expression::AggregationComprehension {
279 function: function.clone(),
280 variable: variable.clone(),
281 collection: Box::new(collection.substitute(var, value)?),
282 window: window.clone(),
283 predicate: Box::new(predicate.substitute(var, value)?),
284 projection: Box::new(projection.substitute(var, value)?),
285 target_unit: target_unit.clone(),
286 }),
287 Expression::GroupBy {
288 variable,
289 collection,
290 filter,
291 key,
292 condition,
293 } => {
294 if var == variable {
296 Ok(Expression::GroupBy {
297 variable: variable.clone(),
298 collection: Box::new(collection.substitute(var, value)?),
299 filter: filter.clone(),
300 key: key.clone(),
301 condition: condition.clone(),
302 })
303 } else {
304 Ok(Expression::GroupBy {
305 variable: variable.clone(),
306 collection: Box::new(collection.substitute(var, value)?),
307 filter: filter
308 .as_ref()
309 .map(|f| f.substitute(var, value))
310 .transpose()?
311 .map(Box::new),
312 key: Box::new(key.substitute(var, value)?),
313 condition: Box::new(condition.substitute(var, value)?),
314 })
315 }
316 }
317 _ => Ok(self.clone()),
318 }
319 }
320
321 pub(crate) fn get_collection(
322 expr: &Expression,
323 graph: &Graph,
324 ) -> Result<Vec<serde_json::Value>, String> {
325 match expr {
326 Expression::Variable(name) => {
327 if let Some(entity_type) = name.strip_prefix("entity_instances:") {
328 return Ok(Self::collect_entity_instances(graph, Some(entity_type)));
329 }
330 Self::get_named_collection(name, graph)
331 }
332 Expression::Literal(serde_json::Value::Array(arr)) => Ok(arr.clone()),
333 _ => Err("Collection expression must be a variable or array literal".to_string()),
334 }
335 }
336
337 fn collect_entity_instances(
338 graph: &Graph,
339 entity_type_filter: Option<&str>,
340 ) -> Vec<serde_json::Value> {
341 graph
342 .all_entity_instances()
343 .iter()
344 .filter(|instance| {
345 entity_type_filter.is_none_or(|filter| instance.entity_type() == filter)
346 })
347 .map(|instance| {
348 let mut map = serde_json::Map::new();
349 map.insert(
350 "id".to_string(),
351 serde_json::json!(instance.id().to_string()),
352 );
353 map.insert("name".to_string(), serde_json::json!(instance.name()));
354 map.insert(
355 "entity".to_string(),
356 serde_json::json!(instance.entity_type()),
357 );
358 map.insert(
359 "namespace".to_string(),
360 serde_json::json!(instance.namespace()),
361 );
362
363 let mut fields: Vec<_> = instance.fields().iter().collect();
364 fields.sort_by(|left, right| left.0.cmp(right.0));
365 for (name, value) in fields {
366 if matches!(name.as_str(), "id" | "name" | "entity" | "namespace") {
367 continue;
368 }
369 map.insert(name.clone(), value.clone());
370 }
371 serde_json::Value::Object(map)
372 })
373 .collect()
374 }
375
376 fn get_named_collection(name: &str, graph: &Graph) -> Result<Vec<serde_json::Value>, String> {
377 match name {
378 "flows" => {
379 let flows: Result<Vec<serde_json::Value>, String> = graph
380 .all_flows()
381 .iter()
382 .map(|f| {
383 let quantity = f.quantity().to_f64().ok_or_else(|| {
384 format!("Failed to convert flow quantity {} to f64", f.quantity())
385 })?;
386
387 let mut map = serde_json::Map::new();
388 map.insert("id".to_string(), serde_json::json!(f.id().to_string()));
389 map.insert(
390 "from_entity".to_string(),
391 serde_json::json!(f.from_id().to_string()),
392 );
393 map.insert(
394 "to_entity".to_string(),
395 serde_json::json!(f.to_id().to_string()),
396 );
397 map.insert(
398 "resource".to_string(),
399 serde_json::json!(f.resource_id().to_string()),
400 );
401 map.insert("quantity".to_string(), serde_json::json!(quantity));
402
403 for (k, v) in f.attributes().iter() {
404 if matches!(
405 k.as_str(),
406 "id" | "from_entity" | "to_entity" | "resource" | "quantity"
407 ) || map.contains_key(k)
408 {
409 continue;
410 }
411 map.insert(k.clone(), v.clone());
412 }
413 Ok(serde_json::Value::Object(map))
414 })
415 .collect();
416 flows
417 }
418 "entities" => {
419 let entities: Vec<serde_json::Value> = graph
420 .all_entities()
421 .iter()
422 .map(|e| {
423 let mut map = serde_json::Map::new();
424 map.insert("id".to_string(), serde_json::json!(e.id().to_string()));
425 map.insert("name".to_string(), serde_json::json!(e.name()));
426 map.insert("namespace".to_string(), serde_json::json!(e.namespace()));
427
428 let roles = graph.role_names_for_entity(e.id());
429 if !roles.is_empty() {
430 map.insert("roles".to_string(), serde_json::json!(roles));
431 }
432
433 for (k, v) in e.attributes().iter() {
434 if matches!(k.as_str(), "id" | "name" | "namespace")
435 || map.contains_key(k)
436 {
437 continue;
438 }
439 map.insert(k.clone(), v.clone());
440 }
441
442 serde_json::Value::Object(map)
443 })
444 .collect();
445 Ok(entities)
446 }
447 "entity_instances" => Ok(Self::collect_entity_instances(graph, None)),
448 "relations" => {
449 let relations: Vec<serde_json::Value> = graph
450 .all_relations()
451 .iter()
452 .map(|relation| {
453 let mut map = serde_json::Map::new();
454 map.insert(
455 "id".to_string(),
456 serde_json::json!(relation.id().to_string()),
457 );
458 map.insert("name".to_string(), serde_json::json!(relation.name()));
459 map.insert(
460 "predicate".to_string(),
461 serde_json::json!(relation.predicate()),
462 );
463
464 if let Some(subject) = graph.get_role(relation.subject_role()) {
465 map.insert(
466 "subject_role".to_string(),
467 serde_json::json!(subject.name()),
468 );
469 }
470
471 if let Some(object) = graph.get_role(relation.object_role()) {
472 map.insert("object_role".to_string(), serde_json::json!(object.name()));
473 }
474
475 if let Some(flow) = relation.via_flow() {
476 map.insert("via".to_string(), serde_json::json!(flow.to_string()));
477 }
478
479 serde_json::Value::Object(map)
480 })
481 .collect();
482
483 Ok(relations)
484 }
485 "resources" => {
486 let resources: Vec<serde_json::Value> = graph
487 .all_resources()
488 .iter()
489 .map(|r| {
490 let mut map = serde_json::Map::new();
491 map.insert("id".to_string(), serde_json::json!(r.id().to_string()));
492 map.insert("name".to_string(), serde_json::json!(r.name()));
493 map.insert("namespace".to_string(), serde_json::json!(r.namespace()));
494 map.insert("unit".to_string(), serde_json::json!(r.unit()));
495 for (k, v) in r.attributes().iter() {
496 if matches!(k.as_str(), "id" | "name" | "namespace" | "unit")
497 || map.contains_key(k)
498 {
499 continue;
500 }
501 map.insert(k.clone(), v.clone());
502 }
503 serde_json::Value::Object(map)
504 })
505 .collect();
506 Ok(resources)
507 }
508 "instances" => {
509 let instances: Vec<serde_json::Value> = graph
510 .all_instances()
511 .iter()
512 .map(|i| {
513 let mut map = serde_json::Map::new();
514 map.insert("id".to_string(), serde_json::json!(i.id().to_string()));
515 map.insert(
516 "entity".to_string(),
517 serde_json::json!(i.entity_id().to_string()),
518 );
519 map.insert(
520 "resource".to_string(),
521 serde_json::json!(i.resource_id().to_string()),
522 );
523 for (k, v) in i.attributes().iter() {
524 if matches!(k.as_str(), "id" | "entity" | "resource")
525 || map.contains_key(k)
526 {
527 continue;
528 }
529 map.insert(k.clone(), v.clone());
530 }
531 serde_json::Value::Object(map)
532 })
533 .collect();
534 Ok(instances)
535 }
536 _ => Err(format!("Unknown collection: {}", name)),
537 }
538 }
539
540 fn is_true_literal(expr: &Expression) -> bool {
541 matches!(expr, Expression::Literal(v) if v.as_bool() == Some(true))
542 }
543
544 pub(crate) fn evaluate_aggregation(
545 function: &AggregateFunction,
546 collection: &Expression,
547 field: &Option<String>,
548 filter: &Option<Box<Expression>>,
549 graph: &Graph,
550 ) -> Result<serde_json::Value, String> {
551 let items = Self::get_collection(collection, graph)?;
553
554 let filtered_items = if let Some(filter_expr) = filter {
556 let variable_name = match collection {
558 Expression::Variable(name) if name.starts_with("entity_instances:") => {
559 "entity_instance"
560 }
561 Expression::Variable(name) => match name.as_str() {
562 "flows" => "flow",
563 "entities" => "entity",
564 "entity_instances" => "entity_instance",
565 "resources" => "resource",
566 "instances" => "instance",
567 "relations" => "relation",
568 _ => "item",
569 },
570 _ => "item",
571 };
572
573 let mut kept = Vec::new();
574 for item in items {
575 let substituted = filter_expr.substitute(variable_name, &item)?;
580 let expanded = substituted.expand(graph)?;
581 if Self::is_true_literal(&expanded) {
582 kept.push(item);
583 }
584 }
585 kept
586 } else {
587 items
588 };
589
590 match function {
592 AggregateFunction::Count => Ok(serde_json::json!(filtered_items.len())),
593
594 AggregateFunction::Sum => {
595 let field_name = field.as_ref().ok_or("Sum requires a field specification")?;
596
597 let sum: Decimal = filtered_items
598 .iter()
599 .filter_map(|item| {
600 item.get(field_name).and_then(|v| {
601 if let Some(num) = v.as_f64() {
602 Decimal::from_str(&num.to_string()).ok()
603 } else if let Some(s) = v.as_str() {
604 Decimal::from_str(s).ok()
605 } else {
606 None
607 }
608 })
609 })
610 .sum();
611
612 let sum_f64 = sum
614 .to_f64()
615 .ok_or_else(|| format!("Failed to convert sum {} to f64", sum))?;
616
617 Ok(serde_json::json!(sum_f64))
618 }
619
620 AggregateFunction::Avg => {
621 let field_name = field.as_ref().ok_or("Avg requires a field specification")?;
622
623 let values: Vec<Decimal> = filtered_items
624 .iter()
625 .filter_map(|item| {
626 item.get(field_name).and_then(|v| {
627 if let Some(num) = v.as_f64() {
628 Decimal::from_str(&num.to_string()).ok()
629 } else if let Some(s) = v.as_str() {
630 Decimal::from_str(s).ok()
631 } else {
632 None
633 }
634 })
635 })
636 .collect();
637
638 if values.is_empty() {
639 return Ok(serde_json::json!(null));
640 }
641
642 let sum: Decimal = values.iter().copied().sum();
643 let avg = sum / Decimal::from(values.len());
644
645 let avg_f64 = avg
647 .to_f64()
648 .ok_or_else(|| format!("Failed to convert average {} to f64", avg))?;
649
650 Ok(serde_json::json!(avg_f64))
651 }
652
653 AggregateFunction::Min => {
654 let field_name = field.as_ref().ok_or("Min requires a field specification")?;
655
656 let min = filtered_items
657 .iter()
658 .filter_map(|item| {
659 item.get(field_name).and_then(|v| {
660 if let Some(num) = v.as_f64() {
661 Decimal::from_str(&num.to_string()).ok()
662 } else if let Some(s) = v.as_str() {
663 Decimal::from_str(s).ok()
664 } else {
665 None
666 }
667 })
668 })
669 .min();
670
671 if let Some(min_val) = min {
673 let min_f64 = min_val
674 .to_f64()
675 .ok_or_else(|| format!("Failed to convert min {} to f64", min_val))?;
676 Ok(serde_json::json!(min_f64))
677 } else {
678 Ok(serde_json::json!(null))
679 }
680 }
681
682 AggregateFunction::Max => {
683 let field_name = field.as_ref().ok_or("Max requires a field specification")?;
684
685 let max = filtered_items
686 .iter()
687 .filter_map(|item| {
688 item.get(field_name).and_then(|v| {
689 if let Some(num) = v.as_f64() {
690 Decimal::from_str(&num.to_string()).ok()
691 } else if let Some(s) = v.as_str() {
692 Decimal::from_str(s).ok()
693 } else {
694 None
695 }
696 })
697 })
698 .max();
699
700 if let Some(max_val) = max {
702 let max_f64 = max_val
703 .to_f64()
704 .ok_or_else(|| format!("Failed to convert max {} to f64", max_val))?;
705 Ok(serde_json::json!(max_f64))
706 } else {
707 Ok(serde_json::json!(null))
708 }
709 }
710 }
711 }
712
713 #[allow(clippy::too_many_arguments)]
714 pub(crate) fn evaluate_aggregation_comprehension(
715 function: &AggregateFunction,
716 variable: &str,
717 collection: &Expression,
718 window: &Option<crate::policy::WindowSpec>,
719 predicate: &Expression,
720 projection: &Expression,
721 target_unit: Option<&str>,
722 graph: &Graph,
723 ) -> Result<serde_json::Value, String> {
724 let items = Self::get_collection(collection, graph)?;
725
726 let items = if let Some(w) = window {
728 let now = crate::timefmt::now();
729 let duration_span = i64::try_from(w.duration)
730 .map_err(|_| format!("Window duration {} exceeds supported range", w.duration))?;
731 let unit_lower = w.unit.to_lowercase();
732 let duration = match unit_lower.as_str() {
733 "hour" | "hours" => time::Duration::hours(duration_span),
734 "minute" | "minutes" => time::Duration::minutes(duration_span),
735 "day" | "days" => time::Duration::days(duration_span),
736 "second" | "seconds" => time::Duration::seconds(duration_span),
737 _ => {
738 return Err(format!(
739 "Invalid window unit '{}' in aggregation window",
740 w.unit
741 ))
742 }
743 };
744
745 items
746 .into_iter()
747 .filter(|item| {
748 let ts_str = item
749 .get("timestamp")
750 .or_else(|| item.get("created_at"))
751 .and_then(|v| v.as_str());
752 if let Some(s) = ts_str {
753 if let Ok(ts) = crate::timefmt::parse_rfc3339(s) {
754 return ts >= now - duration;
755 }
756 }
757 false
760 })
761 .collect()
762 } else {
763 items
764 };
765
766 let mut projected_values = Vec::new();
767 for item in items {
768 let substituted_predicate = predicate.substitute(variable, &item)?;
769 let predicate_result = substituted_predicate.expand(graph)?;
770 if !Self::is_true_literal(&predicate_result) {
771 continue;
772 }
773
774 let substituted_projection = projection.substitute(variable, &item)?;
775 let projection_result = substituted_projection.expand(graph)?;
776 match projection_result {
777 Expression::Literal(value) => projected_values.push(value),
778 Expression::QuantityLiteral { value, unit } => {
779 projected_values.push(serde_json::json!({
780 "__quantity_value": value.to_string(),
781 "__quantity_unit": unit,
782 }));
783 }
784 _ => {
785 return Err(
786 "Projection in aggregation comprehension must reduce to a literal"
787 .to_string(),
788 );
789 }
790 }
791 }
792
793 match function {
794 AggregateFunction::Count => Ok(serde_json::json!(projected_values.len())),
795 AggregateFunction::Sum
796 | AggregateFunction::Avg
797 | AggregateFunction::Min
798 | AggregateFunction::Max => {
799 Self::fold_numeric(function, &projected_values, target_unit)
800 }
801 }
802 }
803
804 pub(crate) fn fold_numeric(
805 function: &AggregateFunction,
806 values: &[serde_json::Value],
807 target_unit: Option<&str>,
808 ) -> Result<serde_json::Value, String> {
809 use crate::units::UnitRegistry;
810
811 let mut decimals: Vec<Decimal> = Vec::new();
812 let mut source_unit: Option<String> = None;
813 for value in values {
814 if let Some(num) = value.as_f64() {
815 decimals.push(Decimal::from_str(&num.to_string()).map_err(|e| e.to_string())?);
816 } else if let Some(s) = value.as_str() {
817 decimals.push(Decimal::from_str(s).map_err(|e| e.to_string())?);
818 } else if value.is_object() {
819 let map = value
820 .as_object()
821 .ok_or_else(|| "Invalid quantity object".to_string())?;
822 if let Some(val) = map.get("__quantity_value") {
823 let s = val
824 .as_str()
825 .ok_or_else(|| "Quantity value must be a string".to_string())?;
826 decimals.push(Decimal::from_str(s).map_err(|e| e.to_string())?);
827 }
828 if let Some(unit) = map.get("__quantity_unit") {
829 if source_unit.is_none() {
830 if let Some(unit_str) = unit.as_str() {
831 source_unit = Some(unit_str.to_string());
832 }
833 }
834 }
835 }
836 }
837
838 if decimals.is_empty() {
839 return Ok(serde_json::json!(null));
840 }
841
842 if let Some(target_unit) = target_unit {
843 if let Some(unit) = source_unit.clone() {
844 let registry = UnitRegistry::global();
845 let registry = registry
846 .read()
847 .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
848 let from = registry
849 .get_unit(&unit)
850 .map_err(|e| format!("{}", e))?
851 .clone();
852 let to = registry
853 .get_unit(target_unit)
854 .map_err(|e| format!("{}", e))?
855 .clone();
856 decimals = decimals
857 .into_iter()
858 .map(|value| registry.convert(value, &from, &to))
859 .collect::<Result<Vec<_>, _>>()
860 .map_err(|e| format!("{}", e))?;
861 }
862 }
863
864 let result = match function {
865 AggregateFunction::Sum => decimals.iter().copied().sum(),
866 AggregateFunction::Avg => {
867 let sum: Decimal = decimals.iter().copied().sum();
868 sum / Decimal::from(decimals.len())
869 }
870 AggregateFunction::Min => decimals
871 .into_iter()
872 .min()
873 .ok_or_else(|| "No values available for min".to_string())?,
874 AggregateFunction::Max => decimals
875 .into_iter()
876 .max()
877 .ok_or_else(|| "No values available for max".to_string())?,
878 AggregateFunction::Count => Decimal::from(values.len() as i64),
879 };
880
881 let as_f64 = result
882 .to_f64()
883 .ok_or_else(|| format!("Failed to convert aggregated value {} to f64", result))?;
884
885 Ok(serde_json::json!(as_f64))
886 }
887
888 fn reduce_binary_expression(
889 op: &BinaryOp,
890 left: Expression,
891 right: Expression,
892 ) -> Result<Expression, String> {
893 match (&left, &right) {
894 (Expression::Literal(left_value), Expression::Literal(right_value)) => {
895 if left_value.is_null() || right_value.is_null() {
897 return Ok(Expression::Literal(serde_json::Value::Null));
898 }
899
900 let numeric_cmp = left_value.is_number() && right_value.is_number();
901 let reduced = match op {
902 BinaryOp::Equal => {
903 if numeric_cmp {
904 let left_num = Self::value_to_f64(left_value)
905 .ok_or_else(|| "Left operand is not numeric".to_string())?;
906 let right_num = Self::value_to_f64(right_value)
907 .ok_or_else(|| "Right operand is not numeric".to_string())?;
908 serde_json::json!(left_num == right_num)
909 } else {
910 serde_json::json!(left_value == right_value)
911 }
912 }
913 BinaryOp::NotEqual => {
914 if numeric_cmp {
915 let left_num = Self::value_to_f64(left_value)
916 .ok_or_else(|| "Left operand is not numeric".to_string())?;
917 let right_num = Self::value_to_f64(right_value)
918 .ok_or_else(|| "Right operand is not numeric".to_string())?;
919 serde_json::json!(left_num != right_num)
920 } else {
921 serde_json::json!(left_value != right_value)
922 }
923 }
924 BinaryOp::GreaterThan
925 | BinaryOp::LessThan
926 | BinaryOp::GreaterThanOrEqual
927 | BinaryOp::LessThanOrEqual => {
928 let left_num = Self::value_to_f64(left_value)
929 .ok_or_else(|| "Left operand is not numeric".to_string())?;
930 let right_num = Self::value_to_f64(right_value)
931 .ok_or_else(|| "Right operand is not numeric".to_string())?;
932 match op {
933 BinaryOp::GreaterThan => serde_json::json!(left_num > right_num),
934 BinaryOp::LessThan => serde_json::json!(left_num < right_num),
935 BinaryOp::GreaterThanOrEqual => {
936 serde_json::json!(left_num >= right_num)
937 }
938 BinaryOp::LessThanOrEqual => serde_json::json!(left_num <= right_num),
939 _ => unreachable!(),
940 }
941 }
942 BinaryOp::And | BinaryOp::Or => {
943 let left_bool = match left_value {
944 serde_json::Value::Bool(b) => Some(*b),
945 serde_json::Value::Null => None,
946 _ => return Err("Left operand is not boolean".to_string()),
947 };
948 let right_bool = match right_value {
949 serde_json::Value::Bool(b) => Some(*b),
950 serde_json::Value::Null => None,
951 _ => return Err("Right operand is not boolean".to_string()),
952 };
953
954 match op {
955 BinaryOp::And => {
956 if left_bool == Some(false) || right_bool == Some(false) {
957 serde_json::json!(false)
958 } else if left_bool.is_none() || right_bool.is_none() {
959 serde_json::Value::Null
960 } else {
961 serde_json::json!(left_bool.unwrap() && right_bool.unwrap())
962 }
963 }
964 BinaryOp::Or => {
965 if left_bool == Some(true) || right_bool == Some(true) {
966 serde_json::json!(true)
967 } else if left_bool.is_none() || right_bool.is_none() {
968 serde_json::Value::Null
969 } else {
970 serde_json::json!(left_bool.unwrap() || right_bool.unwrap())
971 }
972 }
973 _ => unreachable!(),
974 }
975 }
976 BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
977 let left_dec = Self::value_to_decimal(left_value)
983 .ok_or_else(|| "Left operand is not numeric".to_string())?;
984 let right_dec = Self::value_to_decimal(right_value)
985 .ok_or_else(|| "Right operand is not numeric".to_string())?;
986 let result = match op {
987 BinaryOp::Plus => left_dec + right_dec,
988 BinaryOp::Minus => left_dec - right_dec,
989 BinaryOp::Multiply => left_dec * right_dec,
990 BinaryOp::Divide => {
991 if right_dec.is_zero() {
992 return Err("Division by zero".to_string());
993 }
994 left_dec / right_dec
995 }
996 _ => unreachable!(),
997 };
998 serde_json::json!(result.to_f64().ok_or_else(|| format!(
999 "Failed to convert arithmetic result {} to f64",
1000 result
1001 ))?)
1002 }
1003 BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => {
1004 let left_str = left_value
1005 .as_str()
1006 .ok_or_else(|| "Left operand is not string".to_string())?;
1007 let right_str = right_value
1008 .as_str()
1009 .ok_or_else(|| "Right operand is not string".to_string())?;
1010 match op {
1011 BinaryOp::Contains => serde_json::json!(left_str.contains(right_str)),
1012 BinaryOp::StartsWith => {
1013 serde_json::json!(left_str.starts_with(right_str))
1014 }
1015 BinaryOp::EndsWith => serde_json::json!(left_str.ends_with(right_str)),
1016 _ => unreachable!(),
1017 }
1018 }
1019 _ => return Ok(Expression::binary(op.clone(), left.clone(), right.clone())),
1020 };
1021 Ok(Expression::Literal(reduced))
1022 }
1023 _ => Ok(Expression::binary(op.clone(), left, right)),
1024 }
1025 }
1026
1027 fn value_to_f64(value: &serde_json::Value) -> Option<f64> {
1028 value
1029 .as_f64()
1030 .or_else(|| value.as_i64().map(|v| v as f64))
1031 .or_else(|| value.as_u64().map(|v| v as f64))
1032 }
1033
1034 fn value_to_decimal(value: &serde_json::Value) -> Option<Decimal> {
1039 if let Some(i) = value.as_i64() {
1040 return Some(Decimal::from(i));
1041 }
1042 if let Some(u) = value.as_u64() {
1043 return Some(Decimal::from(u));
1044 }
1045 value
1046 .as_f64()
1047 .and_then(|f| Decimal::from_str(&f.to_string()).ok())
1048 }
1049}