Skip to main content

crisol_core/data/
query.rs

1//! A small, safe expression language for filters and derived columns.
2//!
3//! It supports comparison, `&&`, `||`, `!`, parentheses, membership in a range or a
4//! list, and string/boolean/number/null literals. There are no function calls, no
5//! assignments, and no I/O: a query can only read the row it is given.
6
7use std::fmt;
8
9use super::Dataset;
10
11mod ast;
12mod parser;
13
14use ast::{BoundExpr, Expr};
15use parser::{Lexer, Parser};
16
17/// A parsed filter expression.
18#[derive(Clone, Debug, PartialEq)]
19/// # Example
20///
21/// ```
22/// use crisol_core::data::Query;
23/// ```
24pub struct Query {
25    source: String,
26    expression: Expr,
27}
28
29impl Query {
30    /// Parse an expression.
31    ///
32    /// # Errors
33    /// When the token or the grammar is invalid, with a byte offset.
34    pub fn parse(source: &str) -> Result<Self, QueryError> {
35        let tokens = Lexer::new(source).tokens()?;
36        let mut parser = Parser::new(tokens);
37        let expression = parser.expression()?;
38        parser.expect_end()?;
39        Ok(Self {
40            source: source.to_owned(),
41            expression,
42        })
43    }
44
45    /// The source text.
46    pub fn source(&self) -> &str {
47        &self.source
48    }
49
50    /// The distinct column names referenced by the expression.
51    pub fn columns(&self) -> Vec<String> {
52        let mut columns = Vec::new();
53        self.expression.columns(&mut columns);
54        columns
55    }
56
57    /// Bind column names to indices once, for repeated evaluation.
58    pub fn bind(&self, data: &Dataset) -> BoundQuery {
59        BoundQuery {
60            expression: self.expression.bind(data),
61        }
62    }
63
64    /// Whether the row matches. A missing column evaluates to null.
65    pub fn matches(&self, data: &Dataset, row: usize) -> bool {
66        self.expression.evaluate(data, row).is_truthy()
67    }
68
69    /// The matching rows, in order.
70    pub fn matching_rows(&self, data: &Dataset) -> Vec<usize> {
71        self.bind(data).matching_rows(data)
72    }
73}
74
75/// A query with column names resolved to indices.
76/// # Example
77///
78/// ```
79/// use crisol_core::data::BoundQuery;
80/// ```
81pub struct BoundQuery {
82    expression: BoundExpr,
83}
84
85impl BoundQuery {
86    /// Whether the row matches.
87    pub fn matches(&self, data: &Dataset, row: usize) -> bool {
88        self.expression.evaluate(data, row).is_truthy()
89    }
90
91    /// The matching rows, in order.
92    pub fn matching_rows(&self, data: &Dataset) -> Vec<usize> {
93        (0..data.row_count())
94            .filter(|row| self.expression.evaluate(data, *row).is_truthy())
95            .collect()
96    }
97}
98
99impl fmt::Display for Query {
100    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
101        formatter.write_str(&self.source)
102    }
103}
104
105/// What went wrong while parsing or evaluating a query.
106#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
107#[non_exhaustive]
108/// # Example
109///
110/// ```
111/// use crisol_core::data::QueryError;
112/// ```
113#[error("{message} at byte {offset}")]
114pub struct QueryError {
115    message: String,
116    offset: usize,
117}
118
119impl QueryError {
120    /// A human-readable message.
121    pub fn message(&self) -> &str {
122        &self.message
123    }
124
125    /// The byte offset of the problem.
126    pub fn offset(&self) -> usize {
127        self.offset
128    }
129}