1use spargebra::algebra::{Expression, Function};
4use waratah_storage::{StrHash, Term, vocab::xsd, well_known_iri};
5
6use crate::custom_fns::process_registry;
7use crate::error::ComputeError;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
11pub enum ExprCapability {
12 AlwaysEncoded,
14 MaybeEncoded,
16 AlwaysResolve,
18 Unsupported,
20}
21
22pub fn classify(expression: &Expression) -> ExprCapability {
24 match expression {
25 Expression::NamedNode(_) | Expression::Literal(_) | Expression::Variable(_) => {
26 ExprCapability::AlwaysEncoded
27 }
28 Expression::Bound(_) => ExprCapability::AlwaysEncoded,
29 Expression::Not(inner) => classify(inner),
30 Expression::And(left, right) | Expression::Or(left, right) => {
31 max_cap(classify(left), classify(right))
32 }
33 Expression::SameTerm(left, right) => {
34 max_cap(classify(left), classify(right)).max(ExprCapability::AlwaysEncoded)
35 }
36 Expression::Equal(left, right) => max_cap(classify(left), classify(right)),
41 Expression::Greater(left, right)
42 | Expression::GreaterOrEqual(left, right)
43 | Expression::Less(left, right)
44 | Expression::LessOrEqual(left, right) => {
45 let operands = max_cap(classify(left), classify(right));
54 if is_resolve_free_comparison_literal(left) || is_resolve_free_comparison_literal(right)
55 {
56 operands
57 } else {
58 operands.max(ExprCapability::MaybeEncoded)
59 }
60 }
61 Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => classify(inner),
65 Expression::Add(left, right)
66 | Expression::Subtract(left, right)
67 | Expression::Multiply(left, right)
68 | Expression::Divide(left, right) => max_cap(classify(left), classify(right)),
69 Expression::FunctionCall(
70 Function::IsIri
71 | Function::IsLiteral
72 | Function::IsBlank
73 | Function::IsNumeric
74 | Function::Datatype,
75 args,
76 ) => args
77 .iter()
78 .map(classify)
79 .fold(ExprCapability::AlwaysEncoded, max_cap),
80 Expression::FunctionCall(Function::Lang | Function::LangMatches, args) => args
84 .iter()
85 .map(classify)
86 .fold(ExprCapability::AlwaysEncoded, max_cap)
87 .max(ExprCapability::MaybeEncoded),
88 Expression::Coalesce(args) => args
89 .iter()
90 .map(classify)
91 .fold(ExprCapability::AlwaysEncoded, max_cap),
92 Expression::FunctionCall(Function::Now, args) => args
93 .iter()
94 .map(classify)
95 .fold(ExprCapability::AlwaysEncoded, max_cap),
96 Expression::FunctionCall(
101 Function::Abs
102 | Function::Ceil
103 | Function::Floor
104 | Function::Round
105 | Function::Year
106 | Function::Month
107 | Function::Day
108 | Function::Hours
109 | Function::Minutes
110 | Function::Seconds
111 | Function::Timezone
112 | Function::Tz,
113 args,
114 ) => args
115 .iter()
116 .map(classify)
117 .fold(ExprCapability::AlwaysEncoded, max_cap),
118 Expression::FunctionCall(Function::BNode, args) if args.is_empty() => {
119 ExprCapability::AlwaysEncoded
120 }
121 Expression::FunctionCall(
122 Function::Str
123 | Function::Iri
124 | Function::BNode
125 | Function::StrLen
126 | Function::StrLang
127 | Function::StrDt,
128 args,
129 ) => args
130 .iter()
131 .map(classify)
132 .fold(ExprCapability::AlwaysEncoded, max_cap)
133 .max(ExprCapability::MaybeEncoded),
134 Expression::FunctionCall(Function::Concat, args) if args.is_empty() => {
136 ExprCapability::AlwaysEncoded
137 }
138 Expression::FunctionCall(
139 Function::Concat
140 | Function::SubStr
141 | Function::Replace
142 | Function::UCase
143 | Function::LCase
144 | Function::EncodeForUri
145 | Function::Md5
146 | Function::Sha1
147 | Function::Sha256
148 | Function::Sha384
149 | Function::Sha512
150 | Function::Contains
151 | Function::StrStarts
152 | Function::StrEnds
153 | Function::StrBefore
154 | Function::StrAfter
155 | Function::Regex,
156 args,
157 ) => args
158 .iter()
159 .map(classify)
160 .fold(ExprCapability::AlwaysResolve, max_cap)
161 .max(ExprCapability::AlwaysResolve),
162 Expression::Exists(_) => ExprCapability::Unsupported,
163 Expression::If(condition, then_branch, else_branch) => max_cap(
167 max_cap(classify(condition), classify(then_branch)),
168 classify(else_branch),
169 ),
170 Expression::In(left, args) => args.iter().map(classify).fold(classify(left), max_cap),
175 Expression::FunctionCall(Function::Custom(iri), args) => {
176 match process_registry().get(iri) {
177 Some(function) => {
178 let mut cap = function.capability();
179 for arg in args {
180 cap = cap.max(classify(arg));
181 }
182 cap
183 }
184 None => ExprCapability::Unsupported,
185 }
186 }
187 Expression::FunctionCall(_, _) => ExprCapability::Unsupported,
188 }
189}
190
191fn is_resolve_free_comparison_literal(expression: &Expression) -> bool {
213 let Expression::Literal(literal) = expression else {
214 return false;
215 };
216 if literal.language().is_some() {
217 return false;
218 }
219 let datatype = literal.datatype();
220 datatype == xsd::INTEGER
221 || datatype == xsd::NON_POSITIVE_INTEGER
222 || datatype == xsd::NEGATIVE_INTEGER
223 || datatype == xsd::LONG
224 || datatype == xsd::INT
225 || datatype == xsd::SHORT
226 || datatype == xsd::BYTE
227 || datatype == xsd::NON_NEGATIVE_INTEGER
228 || datatype == xsd::UNSIGNED_LONG
229 || datatype == xsd::UNSIGNED_INT
230 || datatype == xsd::UNSIGNED_SHORT
231 || datatype == xsd::UNSIGNED_BYTE
232 || datatype == xsd::POSITIVE_INTEGER
233 || datatype == xsd::DECIMAL
234 || datatype == xsd::FLOAT
235 || datatype == xsd::DOUBLE
236 || datatype == xsd::DATE_TIME
237 || datatype == xsd::DATE_TIME_STAMP
238 || datatype == xsd::DATE
239 || datatype == xsd::G_YEAR
240 || datatype == xsd::G_YEAR_MONTH
241}
242
243pub fn split_filter(
249 expression: &Expression,
250) -> Result<(Option<Expression>, Option<Expression>), ComputeError> {
251 let conjuncts = flatten_and(expression);
252 if conjuncts.len() == 1 {
253 return match classify(expression) {
254 ExprCapability::AlwaysEncoded | ExprCapability::MaybeEncoded => {
255 Ok((Some(expression.clone()), None))
256 }
257 ExprCapability::AlwaysResolve => Ok((None, Some(expression.clone()))),
258 ExprCapability::Unsupported => Err(ComputeError::UnsupportedSparql(format!(
259 "FILTER expression is not supported: {expression}"
260 ))),
261 };
262 }
263
264 let mut early = Vec::new();
265 let mut residual = Vec::new();
266 for conjunct in conjuncts {
267 match classify(&conjunct) {
268 ExprCapability::AlwaysEncoded | ExprCapability::MaybeEncoded => early.push(conjunct),
269 ExprCapability::AlwaysResolve => residual.push(conjunct),
270 ExprCapability::Unsupported => {
271 return Err(ComputeError::UnsupportedSparql(format!(
272 "FILTER expression is not supported: {conjunct}"
273 )));
274 }
275 }
276 }
277 Ok((and_fold(early), and_fold(residual)))
278}
279
280pub fn variables_in_expression(expression: &Expression) -> Vec<waratah_storage::Variable> {
282 let mut out = Vec::new();
283 collect_vars(expression, &mut out);
284 out.sort_by(|a, b| a.as_str().cmp(b.as_str()));
285 out.dedup();
286 out
287}
288
289fn collect_vars(expression: &Expression, out: &mut Vec<waratah_storage::Variable>) {
290 match expression {
291 Expression::Variable(v) | Expression::Bound(v) => out.push(v.clone()),
292 Expression::NamedNode(_) | Expression::Literal(_) => {}
293 Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
294 collect_vars(inner, out)
295 }
296 Expression::And(a, b)
297 | Expression::Or(a, b)
298 | Expression::SameTerm(a, b)
299 | Expression::Equal(a, b)
300 | Expression::Greater(a, b)
301 | Expression::GreaterOrEqual(a, b)
302 | Expression::Less(a, b)
303 | Expression::LessOrEqual(a, b)
304 | Expression::Add(a, b)
305 | Expression::Subtract(a, b)
306 | Expression::Multiply(a, b)
307 | Expression::Divide(a, b) => {
308 collect_vars(a, out);
309 collect_vars(b, out);
310 }
311 Expression::FunctionCall(_, args) => {
312 for arg in args {
313 collect_vars(arg, out);
314 }
315 }
316 Expression::If(a, b, c) => {
317 collect_vars(a, out);
318 collect_vars(b, out);
319 collect_vars(c, out);
320 }
321 Expression::Coalesce(args) => {
322 for arg in args {
323 collect_vars(arg, out);
324 }
325 }
326 Expression::In(inner, args) => {
327 collect_vars(inner, out);
328 for arg in args {
329 collect_vars(arg, out);
330 }
331 }
332 Expression::Exists(_) => {}
333 }
334}
335
336pub fn flatten_and(expression: &Expression) -> Vec<Expression> {
338 match expression {
339 Expression::And(left, right) => {
340 let mut out = flatten_and(left);
341 out.extend(flatten_and(right));
342 out
343 }
344 other => vec![other.clone()],
345 }
346}
347
348pub fn and_fold(parts: Vec<Expression>) -> Option<Expression> {
350 parts
351 .into_iter()
352 .reduce(|a, b| Expression::And(Box::new(a), Box::new(b)))
353}
354
355fn max_cap(a: ExprCapability, b: ExprCapability) -> ExprCapability {
356 a.max(b)
357}
358
359#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
372pub enum Mints {
373 Never,
378 Wellknown,
383 Locally,
393 Ground,
403}
404
405pub fn mint_provenance(expression: &Expression) -> Mints {
416 match expression {
417 Expression::Variable(_) | Expression::Bound(_) => Mints::Never,
418 Expression::NamedNode(node) => {
419 if well_known_iri(StrHash::new(node.as_str())).is_some() {
420 Mints::Wellknown
421 } else {
422 Mints::Locally
423 }
424 }
425 Expression::Literal(literal) => {
426 let term = Term::Literal(literal.clone());
427 let (_encoded, (strings, blobs)) = crate::query::caches::mint_const_entries(&term);
431 if strings.is_empty() && blobs.is_empty() {
432 Mints::Never
435 } else if strings
436 .iter()
437 .all(|(hash, _)| well_known_iri(*hash).is_some())
438 {
439 Mints::Wellknown
440 } else {
441 Mints::Locally
442 }
443 }
444 Expression::Not(_)
448 | Expression::UnaryPlus(_)
449 | Expression::UnaryMinus(_)
450 | Expression::And(_, _)
451 | Expression::Or(_, _)
452 | Expression::SameTerm(_, _)
453 | Expression::Equal(_, _)
454 | Expression::Greater(_, _)
455 | Expression::GreaterOrEqual(_, _)
456 | Expression::Less(_, _)
457 | Expression::LessOrEqual(_, _)
458 | Expression::Add(_, _)
459 | Expression::Subtract(_, _)
460 | Expression::Multiply(_, _)
461 | Expression::Divide(_, _)
462 | Expression::In(_, _) => Mints::Never,
463 Expression::FunctionCall(
464 Function::IsIri | Function::IsLiteral | Function::IsBlank | Function::IsNumeric,
465 _,
466 ) => Mints::Never,
467 Expression::FunctionCall(Function::Datatype, _) => Mints::Wellknown,
474 Expression::FunctionCall(Function::Now | Function::BNode, _) => Mints::Never,
476 Expression::FunctionCall(
477 Function::Abs
478 | Function::Ceil
479 | Function::Floor
480 | Function::Round
481 | Function::Year
482 | Function::Month
483 | Function::Day
484 | Function::Hours
485 | Function::Minutes
486 | Function::Seconds
487 | Function::Timezone
488 | Function::Tz
489 | Function::StrLen,
490 _,
491 ) => Mints::Never,
492 Expression::FunctionCall(
494 Function::Str | Function::Iri | Function::StrLang | Function::StrDt,
495 _,
496 ) => Mints::Locally,
497 Expression::FunctionCall(Function::Rand, _) => Mints::Never,
503 Expression::FunctionCall(Function::Uuid | Function::StrUuid, _) => Mints::Locally,
504 Expression::FunctionCall(Function::Lang, _) => Mints::Ground,
508 Expression::FunctionCall(
514 Function::Contains
515 | Function::StrStarts
516 | Function::StrEnds
517 | Function::Regex
518 | Function::LangMatches,
519 _,
520 ) => Mints::Never,
521 Expression::FunctionCall(
525 Function::Concat
526 | Function::SubStr
527 | Function::Replace
528 | Function::UCase
529 | Function::LCase
530 | Function::EncodeForUri
531 | Function::Md5
532 | Function::Sha1
533 | Function::Sha256
534 | Function::Sha384
535 | Function::Sha512
536 | Function::StrBefore
537 | Function::StrAfter,
538 _,
539 ) => Mints::Ground,
540 Expression::FunctionCall(Function::Custom(_), _) => Mints::Ground,
543 Expression::Exists(_) => Mints::Ground,
546 Expression::If(a, b, c) => mint_provenance(a)
548 .max(mint_provenance(b))
549 .max(mint_provenance(c)),
550 Expression::Coalesce(args) => args
551 .iter()
552 .map(mint_provenance)
553 .max()
554 .unwrap_or(Mints::Never),
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561 use spargebra::SparqlParser;
562 use spargebra::algebra::{Function, GraphPattern};
563
564 fn filter_expr(sparql: &str) -> Expression {
565 let q = SparqlParser::new().parse_query(sparql).unwrap();
566 let spargebra::Query::Select { pattern, .. } = q else {
567 panic!("expected SELECT");
568 };
569 match pattern {
570 GraphPattern::Project { inner, .. } => match *inner {
571 GraphPattern::Filter { expr, .. } => expr,
572 GraphPattern::Join { left, right, .. } => {
573 match (*left, *right) {
575 (GraphPattern::Filter { expr, .. }, _)
576 | (_, GraphPattern::Filter { expr, .. }) => expr,
577 _ => panic!("no filter"),
578 }
579 }
580 other => panic!("unexpected {other:?}"),
581 },
582 GraphPattern::Filter { expr, .. } => expr,
583 other => panic!("unexpected root {other:?}"),
584 }
585 }
586
587 #[test]
588 fn and_split_bound_and_regex() {
589 let expr = filter_expr(
590 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(BOUND(?v) && REGEX(STR(?v), "a")) }"#,
591 );
592 let (early, residual) = split_filter(&expr).unwrap();
593 assert!(early.is_some());
594 assert!(matches!(
595 classify(early.as_ref().unwrap()),
596 ExprCapability::AlwaysEncoded
597 ));
598 assert!(residual.is_some());
599 assert_eq!(
600 classify(residual.as_ref().unwrap()),
601 ExprCapability::AlwaysResolve
602 );
603 }
604
605 #[test]
606 fn literal_bounded_comparisons_are_encoded() {
607 let expr = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v < 2) }"#);
610 assert_eq!(classify(&expr), ExprCapability::AlwaysEncoded);
611 let (early, residual) = split_filter(&expr).unwrap();
612 assert!(early.is_some());
613 assert!(residual.is_none());
614
615 let range = filter_expr(
617 r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
618 SELECT ?x WHERE { ?x <http://ex/p> ?v .
619 FILTER(?v >= 1967 && ?v <= 1971) }"#,
620 );
621 assert_eq!(classify(&range), ExprCapability::AlwaysEncoded);
622
623 let eq = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = 1967) }"#);
625 assert_eq!(classify(&eq), ExprCapability::AlwaysEncoded);
626 }
627
628 #[test]
629 fn kernel_total_operators_are_encoded() {
630 let string_eq =
633 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = "abc") }"#);
634 assert_eq!(classify(&string_eq), ExprCapability::AlwaysEncoded);
635 let lang_eq =
636 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = "abc"@en) }"#);
637 assert_eq!(classify(&lang_eq), ExprCapability::AlwaysEncoded);
638 let iri_eq = filter_expr(
639 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = <http://ex/iri>) }"#,
640 );
641 assert_eq!(classify(&iri_eq), ExprCapability::AlwaysEncoded);
642 let add = filter_expr(
644 r#"SELECT ?x WHERE { ?x <http://ex/p> ?a . ?x <http://ex/q> ?b .
645 FILTER(?a + ?b > 3) }"#,
646 );
647 assert_eq!(classify(&add), ExprCapability::AlwaysEncoded);
648 let resolved_eq =
650 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = UCASE(?v)) }"#);
651 assert_eq!(classify(&resolved_eq), ExprCapability::AlwaysResolve);
652 }
653
654 #[test]
655 fn unresolvable_comparison_bounds_keep_maybe_encoded() {
656 let var_var = filter_expr(
658 r#"SELECT ?x WHERE { ?x <http://ex/p> ?a . ?x <http://ex/q> ?b .
659 FILTER(?a < ?b) }"#,
660 );
661 assert_eq!(classify(&var_var), ExprCapability::MaybeEncoded);
662 let string_bound =
664 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v < "abc") }"#);
665 assert_eq!(classify(&string_bound), ExprCapability::MaybeEncoded);
666 let lang_bound =
668 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v < "abc"@en) }"#);
669 assert_eq!(classify(&lang_bound), ExprCapability::MaybeEncoded);
670 let str_operand =
672 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(STR(?v) < 2) }"#);
673 assert_eq!(classify(&str_operand), ExprCapability::MaybeEncoded);
674 }
675
676 #[test]
677 fn is_numeric_and_coalesce_are_encoded() {
678 let numeric =
679 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(isNUMERIC(?v)) }"#);
680 assert_eq!(classify(&numeric), ExprCapability::AlwaysEncoded);
681 let coalesce =
682 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(COALESCE(?v, 1) = 1) }"#);
683 assert_ne!(classify(&coalesce), ExprCapability::Unsupported);
684 let with_div = filter_expr(
685 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(COALESCE(?v / 1, 1) = 1) }"#,
686 );
687 assert_eq!(classify(&with_div), ExprCapability::AlwaysEncoded);
688 let datatype = filter_expr(
689 r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
690 SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(DATATYPE(?v) = xsd:integer) }"#,
691 );
692 assert_eq!(classify(&datatype), ExprCapability::AlwaysEncoded);
693 let langmatches = filter_expr(
694 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(LANGMATCHES(LANG(?v), "en")) }"#,
695 );
696 assert_eq!(classify(&langmatches), ExprCapability::MaybeEncoded);
697 let (early, residual) = split_filter(&langmatches).unwrap();
698 assert!(early.is_some());
699 assert!(residual.is_none());
700 }
701
702 #[test]
703 fn xsd_casts_classify_through_the_registry() {
704 let cast_eq = filter_expr(
706 r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
707 SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(xsd:integer(?v) = 5) }"#,
708 );
709 assert_eq!(classify(&cast_eq), ExprCapability::MaybeEncoded);
710 let (early, residual) = split_filter(&cast_eq).unwrap();
711 assert!(early.is_some(), "cast conjunct stays on the early path");
712 assert!(residual.is_none());
713
714 let cast_same = filter_expr(
715 r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
716 SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(sameTerm(DATATYPE(xsd:string(?v)), xsd:string)) }"#,
717 );
718 assert_eq!(classify(&cast_same), ExprCapability::MaybeEncoded);
719 let (early, residual) = split_filter(&cast_same).unwrap();
720 assert!(early.is_some());
721 assert!(residual.is_none());
722 }
723
724 #[test]
725 fn unknown_custom_functions_stay_unsupported() {
726 let unknown = filter_expr(
727 r#"PREFIX ex: <http://example.org/fns#>
728 SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(ex:explode(?v)) }"#,
729 );
730 assert_eq!(classify(&unknown), ExprCapability::Unsupported);
731 assert!(split_filter(&unknown).is_err());
732 }
733
734 #[test]
735 fn if_classifies_honestly() {
736 let lazy = filter_expr(
739 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(IF(BOUND(?v), ?v, 1/0)) }"#,
740 );
741 assert_eq!(classify(&lazy), ExprCapability::AlwaysEncoded);
742 let (early, residual) = split_filter(&lazy).unwrap();
743 assert!(early.is_some());
744 assert!(residual.is_none());
745 let with_exists = filter_expr(
748 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v .
749 FILTER(IF(BOUND(?v), EXISTS { ?x <http://ex/q> ?w }, 1)) }"#,
750 );
751 assert_eq!(classify(&with_exists), ExprCapability::Unsupported);
752 assert!(split_filter(&with_exists).is_err());
753 }
754
755 #[test]
756 fn in_classifies_as_comparison() {
757 let plain =
760 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v IN (1, 2)) }"#);
761 assert_eq!(classify(&plain), ExprCapability::AlwaysEncoded);
762 let (early, residual) = split_filter(&plain).unwrap();
763 assert!(early.is_some());
764 assert!(residual.is_none());
765 let strings =
766 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v IN ("a", "b")) }"#);
767 assert_eq!(classify(&strings), ExprCapability::AlwaysEncoded);
768 let with_ucase = filter_expr(
770 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v IN (UCASE(?v), 2)) }"#,
771 );
772 assert_eq!(classify(&with_ucase), ExprCapability::AlwaysResolve);
773 let (early, residual) = split_filter(&with_ucase).unwrap();
774 assert!(early.is_none());
775 assert!(residual.is_some());
776 }
777
778 #[test]
779 fn now_is_always_encoded_str_is_maybe() {
780 let now = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(NOW()) }"#);
781 assert_eq!(classify(&now), ExprCapability::AlwaysEncoded);
782 let strlen =
783 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(STRLEN(?v) > 0) }"#);
784 assert_eq!(classify(&strlen), ExprCapability::MaybeEncoded);
785 let regex =
786 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(REGEX(?v, "a")) }"#);
787 assert_eq!(classify(®ex), ExprCapability::AlwaysResolve);
788 }
789
790 #[test]
791 fn abs_and_year_are_always_encoded_unless_the_arg_resolves() {
792 use waratah_storage::Variable;
793 let abs_call = Expression::FunctionCall(
794 Function::Abs,
795 vec![Expression::Variable(Variable::new("v").unwrap())],
796 );
797 assert_eq!(classify(&abs_call), ExprCapability::AlwaysEncoded);
798 let year_call = Expression::FunctionCall(
799 Function::Year,
800 vec![Expression::Variable(Variable::new("d").unwrap())],
801 );
802 assert_eq!(classify(&year_call), ExprCapability::AlwaysEncoded);
803 let abs = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(ABS(?v) > 0) }"#);
806 assert_eq!(classify(&abs), ExprCapability::AlwaysEncoded);
807 let year =
808 filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?d . FILTER(YEAR(?d) = 2010) }"#);
809 assert_eq!(classify(&year), ExprCapability::AlwaysEncoded);
810 let (early, residual) = split_filter(&abs).unwrap();
811 assert!(early.is_some());
812 assert!(residual.is_none());
813 let abs_ucase = filter_expr(
814 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(ABS(STRLEN(UCASE(?v))) > 0) }"#,
815 );
816 assert_eq!(classify(&abs_ucase), ExprCapability::AlwaysResolve);
817 let (early, residual) = split_filter(&abs_ucase).unwrap();
818 assert!(early.is_none());
819 assert!(residual.is_some());
820 }
821
822 #[test]
823 fn empty_concat_is_always_encoded() {
824 let empty = Expression::FunctionCall(Function::Concat, Vec::new());
825 assert_eq!(classify(&empty), ExprCapability::AlwaysEncoded);
826 let nonempty = filter_expr(
827 r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(CONCAT(?v, "a") = "xa") }"#,
828 );
829 assert_eq!(classify(&nonempty), ExprCapability::AlwaysResolve);
830 }
831
832 #[test]
833 fn hash_functions_are_always_resolve() {
834 let expr = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(MD5(?v)) }"#);
835 assert_eq!(classify(&expr), ExprCapability::AlwaysResolve);
836 let (early, residual) = split_filter(&expr).unwrap();
837 assert!(early.is_none());
838 assert!(residual.is_some());
839 }
840
841 #[test]
848 fn mint_provenance_stamps() {
849 use waratah_storage::{Literal as RdfLiteral, NamedNode as RdfNamedNode, Variable};
850 let var = |name: &str| Expression::Variable(Variable::new(name).unwrap());
851 let node = |iri: &str| Expression::NamedNode(RdfNamedNode::new(iri).unwrap());
852 let lit = |value: &str| Expression::Literal(RdfLiteral::new_simple_literal(value));
853
854 assert_eq!(mint_provenance(&var("x")), Mints::Never);
857 assert_eq!(
858 mint_provenance(&Expression::Equal(
859 Box::new(var("a")),
860 Box::new(node("urn:ex:a"))
861 )),
862 Mints::Never
863 );
864 assert_eq!(
865 mint_provenance(&Expression::In(
866 Box::new(var("a")),
867 vec![node("urn:ex:a"), lit("big-value-in-a-list")]
868 )),
869 Mints::Never
870 );
871
872 assert_eq!(
875 mint_provenance(&node("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
876 Mints::Wellknown
877 );
878 assert_eq!(mint_provenance(&node("urn:ex:a")), Mints::Locally);
879
880 assert_eq!(mint_provenance(&lit("1")), Mints::Never);
883 assert_eq!(mint_provenance(&lit("abc")), Mints::Never);
884 assert_eq!(
885 mint_provenance(&lit("a long lexical form with many characters")),
886 Mints::Locally
887 );
888
889 assert_eq!(
891 mint_provenance(&Expression::Coalesce(vec![
892 var("missing"),
893 node("urn:ex:a")
894 ])),
895 Mints::Locally
896 );
897 assert_eq!(
898 mint_provenance(&Expression::If(
899 Box::new(var("flag")),
900 Box::new(node("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
901 Box::new(var("x"))
902 )),
903 Mints::Wellknown
904 );
905
906 assert_eq!(
908 mint_provenance(&Expression::FunctionCall(Function::Str, vec![var("x")])),
909 Mints::Locally
910 );
911 assert_eq!(
912 mint_provenance(&Expression::FunctionCall(Function::Lang, vec![var("x")])),
913 Mints::Ground
914 );
915 assert_eq!(
919 mint_provenance(&Expression::FunctionCall(
920 Function::Regex,
921 vec![var("x"), lit("a")]
922 )),
923 Mints::Never
924 );
925 assert_eq!(
926 mint_provenance(&Expression::FunctionCall(
927 Function::StrStarts,
928 vec![var("x"), lit("a")]
929 )),
930 Mints::Never
931 );
932 assert_eq!(
934 mint_provenance(&Expression::FunctionCall(
935 Function::StrBefore,
936 vec![var("x"), lit("a")]
937 )),
938 Mints::Ground
939 );
940 assert_eq!(
943 mint_provenance(&Expression::FunctionCall(
944 Function::Custom(RdfNamedNode::new("http://ex/unknown-fn").unwrap()),
945 vec![var("x")]
946 )),
947 Mints::Ground
948 );
949 assert_eq!(
951 mint_provenance(&Expression::FunctionCall(Function::Rand, vec![])),
952 Mints::Never
953 );
954 assert_eq!(
955 mint_provenance(&Expression::FunctionCall(Function::Uuid, vec![])),
956 Mints::Locally
957 );
958 }
959}