Skip to main content

itzma_core/
predicate.rs

1//! Filter predicates.
2
3//!
4//! A typed tree, checked against the namespace's attribute schema before any
5//! read, then evaluated against each document's stored attributes.
6//!
7//! Logic is two-valued. A comparison against a null field is false, and
8//! [`Predicate::Not`] flips it, so `not (price > 10)` matches a document with no
9//! price. SQL would call that unknown and leave the document out. Use
10//! [`Predicate::IsNull`] when the difference matters.
11//!
12//! A stored value that does not fit its field's declared type is treated as
13//! null by the typed operators (`Number`, `Text`, `IsTrue`, `Contains` and the
14//! rest) but is still a value to `IsNull` and `IsNotNull`. This build cannot
15//! write one, so it only comes from a hand-made object.
16
17use serde::{Deserialize, Serialize};
18use serde_json::Value;
19
20use crate::attrs::{AttrSchema, AttrType};
21use crate::error::{ItzmaError, Result};
22
23/// How a number field is compared with a value.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25pub enum Compare {
26    /// Equal.
27    Eq,
28    /// Not equal.
29    Ne,
30    /// Less than.
31    Lt,
32    /// Less than or equal.
33    Le,
34    /// Greater than.
35    Gt,
36    /// Greater than or equal.
37    Ge,
38}
39
40impl Compare {
41    // Exact equality is the semantics: a stored number equals a value when the
42    // two `f64`s are the same.
43    #[allow(clippy::float_cmp)]
44    fn apply(self, field: f64, value: f64) -> bool {
45        match self {
46            Self::Eq => field == value,
47            Self::Ne => field != value,
48            Self::Lt => field < value,
49            Self::Le => field <= value,
50            Self::Gt => field > value,
51            Self::Ge => field >= value,
52        }
53    }
54}
55
56/// How a string field is compared with a value.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58pub enum TextCompare {
59    /// Equal.
60    Eq,
61    /// Not equal.
62    Ne,
63    /// The field begins with the value. An empty value matches every string.
64    StartsWith,
65}
66
67/// One element of a set, in a predicate.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub enum AttrValue {
70    /// An element of a `set<number>`.
71    Number(f64),
72    /// An element of a `set<string>`.
73    Text(String),
74}
75
76/// A condition over a document's attributes.
77///
78/// Fields are named as the namespace's [`AttrSchema`] declares them, and an
79/// operator has to fit the field's type: a wrong one is refused by
80/// [`Namespace::filter`](crate::Namespace::filter) before any read, never an
81/// empty result.
82///
83/// The serialized form is derived from the type and is not a promised format.
84///
85/// # Examples
86///
87/// ```
88/// use itzma_core::{Compare, Predicate};
89///
90/// // active is true and price is under 20
91/// let p = Predicate::and(vec![
92///     Predicate::is_true("active"),
93///     Predicate::number("price", Compare::Lt, 20.0),
94/// ]);
95/// # let _ = p;
96/// ```
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98#[non_exhaustive]
99pub enum Predicate {
100    /// Every condition holds. At least one is required.
101    And(Vec<Predicate>),
102    /// At least one condition holds. At least one is required.
103    Or(Vec<Predicate>),
104    /// The condition does not hold. A null field makes most conditions false,
105    /// so this matches it.
106    Not(Box<Predicate>),
107    /// The field is missing or `null`. Any type.
108    IsNull(String),
109    /// The field has a value. Any type.
110    IsNotNull(String),
111    /// A `bool` field is `true`.
112    IsTrue(String),
113    /// A `bool` field is `false`.
114    IsFalse(String),
115    /// A `number` field compared with a value.
116    Number {
117        /// The field.
118        field: String,
119        /// The comparison.
120        op: Compare,
121        /// The value, finite.
122        value: f64,
123    },
124    /// A `number` field equals one of the values.
125    NumberIn {
126        /// The field.
127        field: String,
128        /// The values, at least one, all finite.
129        values: Vec<f64>,
130    },
131    /// A `number` field is between `low` and `high`, both included.
132    Between {
133        /// The field.
134        field: String,
135        /// The lower bound, finite.
136        low: f64,
137        /// The upper bound, finite and not below `low`.
138        high: f64,
139    },
140    /// A `string` field compared with a value.
141    Text {
142        /// The field.
143        field: String,
144        /// The comparison.
145        op: TextCompare,
146        /// The value.
147        value: String,
148    },
149    /// A `string` field equals one of the values.
150    TextIn {
151        /// The field.
152        field: String,
153        /// The values, at least one.
154        values: Vec<String>,
155    },
156    /// A set field holds the element.
157    Contains {
158        /// The field.
159        field: String,
160        /// The element. Its kind must be the set's element type.
161        value: AttrValue,
162    },
163    /// A set field holds at least one of the elements.
164    ContainsAny {
165        /// The field.
166        field: String,
167        /// The elements, at least one.
168        values: Vec<AttrValue>,
169    },
170    /// A set field holds every one of the elements.
171    ContainsAll {
172        /// The field.
173        field: String,
174        /// The elements, at least one.
175        values: Vec<AttrValue>,
176    },
177    /// A set field is present and has no elements. A null field is not empty.
178    IsEmpty(String),
179}
180
181impl Predicate {
182    /// A `bool` field is `true`.
183    pub fn is_true(field: impl Into<String>) -> Self {
184        Self::IsTrue(field.into())
185    }
186
187    /// A `bool` field is `false`.
188    pub fn is_false(field: impl Into<String>) -> Self {
189        Self::IsFalse(field.into())
190    }
191
192    /// A `number` field compared with `value`.
193    pub fn number(field: impl Into<String>, op: Compare, value: f64) -> Self {
194        Self::Number {
195            field: field.into(),
196            op,
197            value,
198        }
199    }
200
201    /// A `string` field compared with `value`.
202    pub fn text(field: impl Into<String>, op: TextCompare, value: impl Into<String>) -> Self {
203        Self::Text {
204            field: field.into(),
205            op,
206            value: value.into(),
207        }
208    }
209
210    /// Every condition holds.
211    pub fn and(items: Vec<Predicate>) -> Self {
212        Self::And(items)
213    }
214
215    /// At least one condition holds.
216    pub fn or(items: Vec<Predicate>) -> Self {
217        Self::Or(items)
218    }
219
220    /// The condition does not hold. Named `negate` because `not` is
221    /// [`std::ops::Not`]'s method.
222    pub fn negate(inner: Predicate) -> Self {
223        Self::Not(Box::new(inner))
224    }
225
226    /// Check the predicate against the schema, without touching storage.
227    ///
228    /// # Errors
229    ///
230    /// - [`ItzmaError::UnknownAttr`] for a field the schema does not declare.
231    /// - [`ItzmaError::AttrTypeMismatch`] for an operator that does not fit the
232    ///   field's type (`expected` is what the operator needs).
233    /// - [`ItzmaError::InvalidQuery`] for an empty `And`, `Or`, `NumberIn`,
234    ///   `TextIn`, `ContainsAny` or `ContainsAll`, a number that is not finite,
235    ///   or a `Between` whose `low` is above its `high`.
236    pub(crate) fn check(&self, schema: &AttrSchema) -> Result<()> {
237        match self {
238            Self::And(items) | Self::Or(items) => {
239                if items.is_empty() {
240                    return Err(ItzmaError::InvalidQuery(
241                        "and and or need at least one condition",
242                    ));
243                }
244                items.iter().try_for_each(|item| item.check(schema))
245            }
246            Self::Not(inner) => inner.check(schema),
247            Self::IsNull(field) | Self::IsNotNull(field) => declared(schema, field).map(|_| ()),
248            Self::IsTrue(field) | Self::IsFalse(field) => expect(schema, field, AttrType::Bool),
249            Self::Number { field, value, .. } => {
250                expect(schema, field, AttrType::Number)?;
251                finite(*value)
252            }
253            Self::NumberIn { field, values } => {
254                expect(schema, field, AttrType::Number)?;
255                non_empty(values.len())?;
256                values.iter().try_for_each(|v| finite(*v))
257            }
258            Self::Between { field, low, high } => {
259                expect(schema, field, AttrType::Number)?;
260                finite(*low)?;
261                finite(*high)?;
262                if low > high {
263                    return Err(ItzmaError::InvalidQuery("between: low is above high"));
264                }
265                Ok(())
266            }
267            Self::Text { field, .. } => expect(schema, field, AttrType::Text),
268            Self::TextIn { field, values } => {
269                expect(schema, field, AttrType::Text)?;
270                non_empty(values.len())
271            }
272            Self::Contains { field, value } => elements(schema, field, std::slice::from_ref(value)),
273            Self::ContainsAny { field, values } | Self::ContainsAll { field, values } => {
274                non_empty(values.len())?;
275                elements(schema, field, values)
276            }
277            Self::IsEmpty(field) => {
278                let ty = declared(schema, field)?;
279                if matches!(ty, AttrType::TextSet | AttrType::NumberSet) {
280                    Ok(())
281                } else {
282                    Err(not_a_set(field, ty))
283                }
284            }
285        }
286    }
287
288    /// Whether a document with these stored attributes matches. Only right for
289    /// a predicate that passed [`check`](Self::check). A stored value that does
290    /// not fit its field's type counts as null: this build cannot write one, so
291    /// it can only come from a hand-made object, and failing a whole scan on it
292    /// would be worse than skipping it.
293    pub(crate) fn matches(&self, attrs: Option<&Value>) -> bool {
294        match self {
295            Self::And(items) => items.iter().all(|item| item.matches(attrs)),
296            Self::Or(items) => items.iter().any(|item| item.matches(attrs)),
297            Self::Not(inner) => !inner.matches(attrs),
298            Self::IsNull(field) => value_of(attrs, field).is_none(),
299            Self::IsNotNull(field) => value_of(attrs, field).is_some(),
300            Self::IsTrue(field) => value_of(attrs, field) == Some(&Value::Bool(true)),
301            Self::IsFalse(field) => value_of(attrs, field) == Some(&Value::Bool(false)),
302            Self::Number { field, op, value } => value_of(attrs, field)
303                .and_then(Value::as_f64)
304                .is_some_and(|x| op.apply(x, *value)),
305            Self::NumberIn { field, values } => value_of(attrs, field)
306                .and_then(Value::as_f64)
307                .is_some_and(|x| values.contains(&x)),
308            Self::Between { field, low, high } => value_of(attrs, field)
309                .and_then(Value::as_f64)
310                .is_some_and(|x| *low <= x && x <= *high),
311            Self::Text { field, op, value } => value_of(attrs, field)
312                .and_then(Value::as_str)
313                .is_some_and(|s| match op {
314                    TextCompare::Eq => s == value,
315                    TextCompare::Ne => s != value,
316                    TextCompare::StartsWith => s.starts_with(value.as_str()),
317                }),
318            Self::TextIn { field, values } => value_of(attrs, field)
319                .and_then(Value::as_str)
320                .is_some_and(|s| values.iter().any(|v| v == s)),
321            Self::Contains { field, value } => {
322                set_of(attrs, field).is_some_and(|items| holds(items, value))
323            }
324            Self::ContainsAny { field, values } => {
325                set_of(attrs, field).is_some_and(|items| values.iter().any(|v| holds(items, v)))
326            }
327            Self::ContainsAll { field, values } => {
328                set_of(attrs, field).is_some_and(|items| values.iter().all(|v| holds(items, v)))
329            }
330            Self::IsEmpty(field) => set_of(attrs, field).is_some_and(<[Value]>::is_empty),
331        }
332    }
333}
334
335/// The field's value, or `None` if the attributes have none or it is `null`.
336fn value_of<'a>(attrs: Option<&'a Value>, field: &str) -> Option<&'a Value> {
337    attrs?.get(field).filter(|v| !v.is_null())
338}
339
340fn set_of<'a>(attrs: Option<&'a Value>, field: &str) -> Option<&'a [Value]> {
341    value_of(attrs, field)?.as_array().map(Vec::as_slice)
342}
343
344fn holds(items: &[Value], value: &AttrValue) -> bool {
345    match value {
346        AttrValue::Number(n) => items.iter().any(|v| v.as_f64() == Some(*n)),
347        AttrValue::Text(s) => items.iter().any(|v| v.as_str() == Some(s.as_str())),
348    }
349}
350
351fn declared(schema: &AttrSchema, field: &str) -> Result<AttrType> {
352    schema.get(field).ok_or_else(|| ItzmaError::UnknownAttr {
353        field: field.to_string(),
354    })
355}
356
357fn expect(schema: &AttrSchema, field: &str, want: AttrType) -> Result<()> {
358    let found = declared(schema, field)?;
359    if found == want {
360        return Ok(());
361    }
362    Err(ItzmaError::AttrTypeMismatch {
363        field: field.to_string(),
364        expected: want.name(),
365        found: found.name(),
366    })
367}
368
369fn not_a_set(field: &str, found: AttrType) -> ItzmaError {
370    ItzmaError::AttrTypeMismatch {
371        field: field.to_string(),
372        expected: "set<string> or set<number>",
373        found: found.name(),
374    }
375}
376
377/// `values` against the element type of the set field.
378fn elements(schema: &AttrSchema, field: &str, values: &[AttrValue]) -> Result<()> {
379    let ty = declared(schema, field)?;
380    let element = match ty {
381        AttrType::TextSet => "string",
382        AttrType::NumberSet => "number",
383        other => return Err(not_a_set(field, other)),
384    };
385    for value in values {
386        let found = match (ty, value) {
387            (AttrType::TextSet, AttrValue::Text(_)) => continue,
388            (AttrType::NumberSet, AttrValue::Number(n)) => {
389                finite(*n)?;
390                continue;
391            }
392            (_, AttrValue::Number(_)) => "number",
393            (_, AttrValue::Text(_)) => "string",
394        };
395        return Err(ItzmaError::AttrTypeMismatch {
396            field: field.to_string(),
397            expected: element,
398            found,
399        });
400    }
401    Ok(())
402}
403
404fn finite(value: f64) -> Result<()> {
405    if value.is_finite() {
406        Ok(())
407    } else {
408        Err(ItzmaError::InvalidQuery(
409            "a number in a predicate must be finite",
410        ))
411    }
412}
413
414fn non_empty(len: usize) -> Result<()> {
415    if len == 0 {
416        return Err(ItzmaError::InvalidQuery(
417            "a list in a predicate needs at least one value",
418        ));
419    }
420    Ok(())
421}
422
423#[cfg(test)]
424mod tests {
425    use serde_json::json;
426
427    use super::*;
428    use Compare::*;
429
430    fn schema() -> AttrSchema {
431        AttrSchema::new()
432            .field("active", AttrType::Bool)
433            .field("price", AttrType::Number)
434            .field("name", AttrType::Text)
435            .field("tags", AttrType::TextSet)
436            .field("scores", AttrType::NumberSet)
437    }
438
439    fn text(s: &str) -> AttrValue {
440        AttrValue::Text(s.into())
441    }
442
443    fn num(n: f64) -> AttrValue {
444        AttrValue::Number(n)
445    }
446
447    fn ok(p: &Predicate) {
448        p.check(&schema()).expect("valid predicate");
449    }
450
451    fn eval(p: &Predicate, attrs: Value) -> bool {
452        ok(p);
453        p.matches(Some(&attrs))
454    }
455
456    #[test]
457    fn bool_operators_and_null() {
458        let t = Predicate::is_true("active");
459        let f = Predicate::is_false("active");
460        assert!(eval(&t, json!({"active": true})));
461        assert!(!eval(&t, json!({"active": false})));
462        assert!(eval(&f, json!({"active": false})));
463        for null in [json!({}), json!({"active": null})] {
464            assert!(
465                !eval(&t, null.clone()) && !eval(&f, null),
466                "null is neither"
467            );
468        }
469        assert!(!t.matches(None) && !f.matches(None));
470    }
471
472    #[test]
473    fn number_comparators_at_the_edges() {
474        let attrs = json!({"price": 10});
475        for (op, at, want) in [
476            (Eq, 10.0, true),
477            (Eq, 11.0, false),
478            (Ne, 10.0, false),
479            (Ne, 11.0, true),
480            (Lt, 10.0, false),
481            (Lt, 10.5, true),
482            (Le, 10.0, true),
483            (Le, 9.9, false),
484            (Gt, 10.0, false),
485            (Gt, 9.9, true),
486            (Ge, 10.0, true),
487            (Ge, 10.1, false),
488        ] {
489            let p = Predicate::number("price", op, at);
490            assert_eq!(eval(&p, attrs.clone()), want, "{op:?} {at}");
491        }
492    }
493
494    #[test]
495    fn number_comparison_against_null_is_false_for_every_operator_including_ne() {
496        for op in [Eq, Ne, Lt, Le, Gt, Ge] {
497            let p = Predicate::number("price", op, 1.0);
498            assert!(!eval(&p, json!({})), "{op:?}");
499            assert!(!eval(&p, json!({"price": null})), "{op:?}");
500        }
501    }
502
503    #[test]
504    fn negative_zero_equals_zero_and_big_numbers_compare() {
505        let zero = Predicate::number("price", Eq, 0.0);
506        assert!(eval(&zero, json!({"price": -0.0})));
507        let big = Predicate::number("price", Gt, 1e300);
508        assert!(eval(&big, json!({"price": 1.5e300})));
509        // Integers above 2^53 lose precision: the two differ as integers and
510        // are equal as f64.
511        let p = Predicate::number("price", Eq, 9_007_199_254_740_993.0);
512        assert!(eval(&p, json!({"price": 9_007_199_254_740_992_u64})));
513    }
514
515    #[test]
516    fn number_in_and_between_include_their_bounds() {
517        let inn = Predicate::NumberIn {
518            field: "price".into(),
519            values: vec![1.0, 5.0],
520        };
521        assert!(eval(&inn, json!({"price": 5})));
522        assert!(!eval(&inn, json!({"price": 4})));
523        assert!(!eval(&inn, json!({})));
524        let between = Predicate::Between {
525            field: "price".into(),
526            low: 2.0,
527            high: 4.0,
528        };
529        for (x, want) in [
530            (1.9, false),
531            (2.0, true),
532            (3.0, true),
533            (4.0, true),
534            (4.1, false),
535        ] {
536            assert_eq!(eval(&between, json!({ "price": x })), want, "{x}");
537        }
538        assert!(!eval(&between, json!({})));
539    }
540
541    #[test]
542    fn text_operators() {
543        let eq = Predicate::text("name", TextCompare::Eq, "abc");
544        let ne = Predicate::text("name", TextCompare::Ne, "abc");
545        let starts = Predicate::text("name", TextCompare::StartsWith, "ab");
546        assert!(eval(&eq, json!({"name": "abc"})) && !eval(&eq, json!({"name": "abd"})));
547        assert!(!eval(&ne, json!({"name": "abc"})) && eval(&ne, json!({"name": "abd"})));
548        assert!(eval(&starts, json!({"name": "abc"})) && !eval(&starts, json!({"name": "b"})));
549        assert!(!eval(&eq, json!({})) && !eval(&ne, json!({})) && !eval(&starts, json!({})));
550        let empty = Predicate::text("name", TextCompare::StartsWith, "");
551        assert!(eval(&empty, json!({"name": ""})) && eval(&empty, json!({"name": "x"})));
552        assert!(
553            !eval(&empty, json!({})),
554            "an empty prefix still needs a value"
555        );
556        let inn = Predicate::TextIn {
557            field: "name".into(),
558            values: vec!["a".into(), "b".into()],
559        };
560        assert!(eval(&inn, json!({"name": "b"})) && !eval(&inn, json!({"name": "c"})));
561    }
562
563    #[test]
564    fn set_operators_treat_the_array_as_a_set() {
565        let attrs = json!({"tags": ["a", "b", "a"], "scores": [1, 2.5]});
566        let has = |field: &str, value| Predicate::Contains {
567            field: field.into(),
568            value,
569        };
570        assert!(eval(&has("tags", text("a")), attrs.clone()));
571        assert!(!eval(&has("tags", text("z")), attrs.clone()));
572        assert!(eval(&has("scores", num(2.5)), attrs.clone()));
573        let any = Predicate::ContainsAny {
574            field: "tags".into(),
575            values: vec![text("z"), text("b")],
576        };
577        let all = Predicate::ContainsAll {
578            field: "tags".into(),
579            values: vec![text("a"), text("b")],
580        };
581        let all_missing = Predicate::ContainsAll {
582            field: "tags".into(),
583            values: vec![text("a"), text("z")],
584        };
585        assert!(
586            eval(&any, attrs.clone()) && eval(&all, attrs.clone()) && !eval(&all_missing, attrs)
587        );
588    }
589
590    #[test]
591    fn empty_sets_and_null_sets() {
592        let empty = Predicate::IsEmpty("tags".into());
593        assert!(eval(&empty, json!({"tags": []})));
594        assert!(!eval(&empty, json!({"tags": ["a"]})));
595        assert!(!eval(&empty, json!({})), "a null set is not empty");
596        assert!(!eval(&empty, json!({"tags": null})));
597        let has = Predicate::Contains {
598            field: "tags".into(),
599            value: text("a"),
600        };
601        assert!(!eval(&has, json!({})) && !eval(&has, json!({"tags": []})));
602        let all_of_one = Predicate::ContainsAll {
603            field: "tags".into(),
604            values: vec![text("a")],
605        };
606        assert!(!eval(&all_of_one, json!({})), "a null set contains nothing");
607    }
608
609    #[test]
610    fn is_null_and_is_not_null() {
611        let null = Predicate::IsNull("price".into());
612        let not_null = Predicate::IsNotNull("price".into());
613        for missing in [json!({}), json!({"price": null})] {
614            assert!(eval(&null, missing.clone()) && !eval(&not_null, missing));
615        }
616        assert!(!eval(&null, json!({"price": 0})) && eval(&not_null, json!({"price": 0})));
617        assert!(null.matches(None) && !not_null.matches(None));
618        let empty_set = Predicate::IsNull("tags".into());
619        assert!(
620            !eval(&empty_set, json!({"tags": []})),
621            "an empty set is not null"
622        );
623    }
624
625    #[test]
626    fn and_or_not_and_the_two_valued_null_rule() {
627        let cheap = Predicate::number("price", Lt, 10.0);
628        let active = Predicate::is_true("active");
629        let both = Predicate::and(vec![cheap.clone(), active.clone()]);
630        let either = Predicate::or(vec![cheap.clone(), active.clone()]);
631        let attrs = json!({"price": 5, "active": false});
632        assert!(!eval(&both, attrs.clone()) && eval(&either, attrs));
633        // not (price < 10) matches a document with no price: two-valued logic.
634        let not_cheap = Predicate::negate(cheap);
635        assert!(eval(&not_cheap, json!({})));
636        assert!(eval(&not_cheap, json!({"price": 50})));
637        assert!(!eval(&not_cheap, json!({"price": 5})));
638    }
639
640    #[test]
641    fn a_stored_value_of_the_wrong_type_counts_as_null() {
642        assert!(!eval(
643            &Predicate::number("price", Gt, 0.0),
644            json!({"price": "9"})
645        ));
646        assert!(!eval(
647            &Predicate::is_true("active"),
648            json!({"active": "yes"})
649        ));
650        assert!(!eval(
651            &Predicate::Contains {
652                field: "tags".into(),
653                value: text("a")
654            },
655            json!({"tags": "a"})
656        ));
657        // Only the typed operators see it as null: the value is there, so
658        // `IsNull` is false and `IsNotNull` is true.
659        assert!(!eval(
660            &Predicate::IsNull("price".into()),
661            json!({"price": "9"})
662        ));
663        assert!(eval(
664            &Predicate::IsNotNull("price".into()),
665            json!({"price": "9"})
666        ));
667    }
668
669    #[test]
670    fn check_refuses_unknown_fields_and_wrong_operators() {
671        let s = schema();
672        assert!(matches!(
673            Predicate::is_true("nope").check(&s),
674            Err(ItzmaError::UnknownAttr { field }) if field == "nope"
675        ));
676        let wrong = [
677            Predicate::is_true("price"),
678            Predicate::number("name", Gt, 1.0),
679            Predicate::text("price", TextCompare::Eq, "x"),
680            Predicate::IsEmpty("name".into()),
681            Predicate::Contains {
682                field: "price".into(),
683                value: num(1.0),
684            },
685            Predicate::Contains {
686                field: "tags".into(),
687                value: num(1.0),
688            },
689            Predicate::Contains {
690                field: "scores".into(),
691                value: text("a"),
692            },
693            Predicate::ContainsAny {
694                field: "tags".into(),
695                values: vec![text("a"), num(1.0)],
696            },
697        ];
698        for p in wrong {
699            assert!(
700                matches!(p.check(&s), Err(ItzmaError::AttrTypeMismatch { .. })),
701                "{p:?}"
702            );
703        }
704    }
705
706    #[test]
707    fn check_refuses_malformed_predicates() {
708        let s = schema();
709        let bad = [
710            Predicate::And(vec![]),
711            Predicate::Or(vec![]),
712            Predicate::number("price", Eq, f64::NAN),
713            Predicate::number("price", Eq, f64::INFINITY),
714            Predicate::NumberIn {
715                field: "price".into(),
716                values: vec![],
717            },
718            Predicate::NumberIn {
719                field: "price".into(),
720                values: vec![f64::NAN],
721            },
722            Predicate::Between {
723                field: "price".into(),
724                low: 2.0,
725                high: 1.0,
726            },
727            Predicate::TextIn {
728                field: "name".into(),
729                values: vec![],
730            },
731            Predicate::ContainsAny {
732                field: "tags".into(),
733                values: vec![],
734            },
735            Predicate::ContainsAll {
736                field: "tags".into(),
737                values: vec![],
738            },
739            Predicate::negate(Predicate::And(vec![])),
740        ];
741        for p in bad {
742            assert!(
743                matches!(p.check(&s), Err(ItzmaError::InvalidQuery(_))),
744                "{p:?}"
745            );
746        }
747        // A bad condition deep in the tree is found.
748        let deep = Predicate::and(vec![
749            Predicate::is_true("active"),
750            Predicate::is_true("nope"),
751        ]);
752        assert!(matches!(
753            deep.check(&s),
754            Err(ItzmaError::UnknownAttr { .. })
755        ));
756        // low == high is a valid single-point range.
757        ok(&Predicate::Between {
758            field: "price".into(),
759            low: 1.0,
760            high: 1.0,
761        });
762    }
763}