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