Skip to main content

datacraft_query/
query_criteria.rs

1//! Criteria parsing (step 7.3, item H27).
2//!
3//! Criteria strings parse to typed predicates per column kind: optional
4//! operator prefix, then a literal coerced to the column family. Family
5//! comparisons and OLE date math live here; execution is
6//! [crate::query_engine].
7
8use datacraft_types::{FieldDef, FieldKind, FieldValue, NumericKind, compare, parse_date};
9
10use crate::query_engine::EngineError;
11
12#[derive(Debug, Clone, PartialEq)]
13pub enum Predicate {
14    Equal(FieldValue),
15    NotEqual(FieldValue),
16    Less(FieldValue),
17    LessEqual(FieldValue),
18    Greater(FieldValue),
19    GreaterEqual(FieldValue),
20    /// Access `Like` on a text column — matched through the expression
21    /// service's Access-wildcard matcher, case-insensitively (step 39.3,
22    /// item M37).
23    Like(String),
24}
25
26impl Predicate {
27    /// Evaluates against a row value (NULL never satisfies). Complex values
28    /// use EXISTS semantics: the predicate holds when at least one
29    /// sub-record's scalar satisfies it (step 16.1, M4).
30    pub fn matches(&self, value: &FieldValue) -> bool {
31        if let FieldValue::Complex(records) = value {
32            return records
33                .iter()
34                .filter_map(|record| record.scalar())
35                .any(|scalar| self.matches_scalar(scalar));
36        }
37        self.matches_scalar(value)
38    }
39
40    /// Scalar evaluation shared by plain and complex cells.
41    fn matches_scalar(&self, value: &FieldValue) -> bool {
42        if matches!(value, FieldValue::Null | FieldValue::Guid(_)) {
43            return false;
44        }
45        if let Predicate::Like(pattern) = self {
46            return datacraft_expr::like::matches(&datacraft_types::display_value(value), pattern);
47        }
48        let literal = match self {
49            Predicate::Equal(v)
50            | Predicate::NotEqual(v)
51            | Predicate::Less(v)
52            | Predicate::LessEqual(v)
53            | Predicate::Greater(v)
54            | Predicate::GreaterEqual(v) => v,
55            Predicate::Like(_) => unreachable!("handled above"),
56        };
57        let Some(ordering) = compare(value, literal) else {
58            return false;
59        };
60        match self {
61            Predicate::Equal(_) => ordering == std::cmp::Ordering::Equal,
62            Predicate::NotEqual(_) => ordering != std::cmp::Ordering::Equal,
63            Predicate::Less(_) => ordering == std::cmp::Ordering::Less,
64            Predicate::LessEqual(_) => ordering != std::cmp::Ordering::Greater,
65            Predicate::Greater(_) => ordering == std::cmp::Ordering::Greater,
66            Predicate::GreaterEqual(_) => ordering != std::cmp::Ordering::Less,
67            Predicate::Like(_) => unreachable!("handled above"),
68        }
69    }
70}
71
72/// literal per the column kind. A plain value means equality. The Access
73/// forms outside the typed subset are recognized and answered precisely —
74/// they never degrade to an equality fallback (step 39.3, item M37).
75pub fn parse_predicate(
76    text: &str,
77    field: &str,
78    column: &FieldDef,
79) -> Result<Predicate, EngineError> {
80    let trimmed = text.trim();
81    let lowercase = trimmed.to_lowercase();
82    if let Some(pattern) = like_pattern(trimmed, &lowercase) {
83        return like_predicate(pattern, field, column);
84    }
85    const UNSUPPORTED_FORMS: [&str; 6] = [
86        "between ",
87        "in (",
88        "in(",
89        "is null",
90        "is not null",
91        "not like ",
92    ];
93    if UNSUPPORTED_FORMS
94        .iter()
95        .any(|form| lowercase.starts_with(form))
96    {
97        return Err(EngineError::BadLiteral {
98            field: field.to_owned(),
99            criteria: text.to_owned(),
100            detail: "this Access criteria form is recognized but outside the \
101                     supported subset (=, <>, <, <=, >, >=, Like)"
102                .to_owned(),
103        });
104    }
105    let (operator, literal) = if let Some(rest) = trimmed.strip_prefix("<>") {
106        ("<>", rest)
107    } else if let Some(rest) = trimmed.strip_prefix("<=") {
108        ("<=", rest)
109    } else if let Some(rest) = trimmed.strip_prefix(">=") {
110        (">=", rest)
111    } else if let Some(rest) = trimmed.strip_prefix('=') {
112        ("=", rest)
113    } else if let Some(rest) = trimmed.strip_prefix('<') {
114        ("<", rest)
115    } else if let Some(rest) = trimmed.strip_prefix('>') {
116        (">", rest)
117    } else {
118        ("=", trimmed)
119    };
120    // A bare wildcard pattern on a text column is an implicit Like — the
121    // Access filter semantics the dialog's syntax help promises (step
122    // 70.1, item H58). An explicit operator keeps the literal path.
123    let explicit_operator = ["<>", "<=", ">=", "=", "<", ">"]
124        .iter()
125        .any(|op| trimmed.starts_with(op));
126    let text_column = matches!(&column.kind, FieldKind::Text { .. } | FieldKind::Memo);
127    let wildcard = literal.contains(['*', '?', '#']);
128    if !explicit_operator && text_column && wildcard {
129        return like_predicate(literal.trim(), field, column);
130    }
131    let value = coerce(literal.trim(), &column.kind).map_err(|detail| EngineError::BadLiteral {
132        field: field.to_owned(),
133        criteria: text.to_owned(),
134        detail,
135    })?;
136    Ok(match operator {
137        "=" => Predicate::Equal(value),
138        "<>" => Predicate::NotEqual(value),
139        "<" => Predicate::Less(value),
140        "<=" => Predicate::LessEqual(value),
141        ">" => Predicate::Greater(value),
142        _ => Predicate::GreaterEqual(value),
143    })
144}
145
146/// `Like "pattern"` with a case-insensitive keyword — the pattern argument
147/// stays as written; `None` when the criteria is not a Like form.
148fn like_pattern<'a>(trimmed: &'a str, lowercase: &str) -> Option<&'a str> {
149    if !lowercase.starts_with("like ") {
150        return None;
151    }
152    let argument = trimmed[5..].trim();
153    let pattern = argument
154        .strip_prefix('"')
155        .and_then(|rest| rest.strip_suffix('"'))?;
156    Some(pattern)
157}
158
159/// Like is a text-column form; on text and text-element multi-value columns
160/// it matches through the expression service's Access-wildcard matcher
161/// (case-insensitive, `Option Compare Database` semantics).
162fn like_predicate(pattern: &str, field: &str, column: &FieldDef) -> Result<Predicate, EngineError> {
163    fn is_text(kind: &FieldKind) -> bool {
164        matches!(kind, FieldKind::Text { .. } | FieldKind::Memo)
165    }
166    let supported = is_text(&column.kind)
167        || matches!(&column.kind, FieldKind::MultiValue(multi) if is_text(&multi.element_kind()));
168    if !supported {
169        return Err(EngineError::BadLiteral {
170            field: field.to_owned(),
171            criteria: format!("Like \"{pattern}\""),
172            detail: format!(
173                "Like is only supported on text columns, not on {}",
174                datacraft_types::field_kind_display(&column.kind)
175            ),
176        });
177    }
178    Ok(Predicate::Like(pattern.to_owned()))
179}
180
181/// Coerces a literal to the column kind (Access-like wording accepted).
182fn coerce(literal: &str, kind: &FieldKind) -> Result<FieldValue, String> {
183    let unquoted = literal
184        .strip_prefix('"')
185        .and_then(|s| s.strip_suffix('"'))
186        .unwrap_or(literal);
187    match kind {
188        FieldKind::Number(NumericKind::Byte)
189        | FieldKind::Number(NumericKind::Integer)
190        | FieldKind::Number(NumericKind::LongInteger)
191        | FieldKind::AutoNumber(datacraft_types::AutoKind::LongInteger) => unquoted
192            .parse::<i64>()
193            .map(FieldValue::Integer)
194            .map_err(|e| format!("{unquoted:?} is not an integer ({e})")),
195        FieldKind::Number(NumericKind::Single) | FieldKind::Number(NumericKind::Double) => {
196            let value: f64 = unquoted
197                .parse()
198                .map_err(|e| format!("{unquoted:?} is not a number ({e})"))?;
199            if value.is_finite() {
200                Ok(FieldValue::Float(value))
201            } else {
202                Err(format!("{unquoted:?} is not finite"))
203            }
204        }
205        FieldKind::Number(NumericKind::Decimal { .. }) => unquoted
206            .parse::<i128>()
207            .map(FieldValue::Decimal)
208            .map_err(|e| format!("{unquoted:?} is not a scaled integer ({e})")),
209        FieldKind::Currency => {
210            let value: f64 = unquoted
211                .parse()
212                .map_err(|e| format!("{unquoted:?} is not a currency amount ({e})"))?;
213            Ok(FieldValue::Currency((value * 10_000.0).round() as i64))
214        }
215        FieldKind::DateTime => parse_date(unquoted)
216            .ok_or_else(|| format!("{unquoted:?} is not a YYYY-MM-DD [HH:MM] date")),
217        FieldKind::Boolean { .. } => match unquoted.to_lowercase().as_str() {
218            "yes" | "true" | "1" => Ok(FieldValue::Boolean(true)),
219            "no" | "false" | "0" => Ok(FieldValue::Boolean(false)),
220            other => Err(format!("{other:?} is not a yes/no value")),
221        },
222        FieldKind::Text { .. } | FieldKind::Memo => Ok(FieldValue::Text(unquoted.to_owned())),
223        // Multi-value criteria coerce to the element family; the predicate
224        // then applies with EXISTS semantics over the sub-records.
225        FieldKind::MultiValue(multi) => coerce(literal, &multi.element_kind()),
226        FieldKind::AutoNumber(datacraft_types::AutoKind::ReplicationId)
227        | FieldKind::Guid
228        | FieldKind::Binary(_)
229        | FieldKind::Complex => Err(format!(
230            "criteria are not supported on {:?} columns",
231            datacraft_types::field_kind_display(kind)
232        )),
233    }
234}
235
236#[cfg(test)]
237mod tests;