crisol_core/data/
query.rs1use std::fmt;
8
9use super::Dataset;
10
11mod ast;
12mod parser;
13
14use ast::{BoundExpr, Expr};
15use parser::{Lexer, Parser};
16
17#[derive(Clone, Debug, PartialEq)]
19pub struct Query {
25 source: String,
26 expression: Expr,
27}
28
29impl Query {
30 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 pub fn source(&self) -> &str {
47 &self.source
48 }
49
50 pub fn columns(&self) -> Vec<String> {
52 let mut columns = Vec::new();
53 self.expression.columns(&mut columns);
54 columns
55 }
56
57 pub fn bind(&self, data: &Dataset) -> BoundQuery {
59 BoundQuery {
60 expression: self.expression.bind(data),
61 }
62 }
63
64 pub fn matches(&self, data: &Dataset, row: usize) -> bool {
66 self.expression.evaluate(data, row).is_truthy()
67 }
68
69 pub fn matching_rows(&self, data: &Dataset) -> Vec<usize> {
71 self.bind(data).matching_rows(data)
72 }
73}
74
75pub struct BoundQuery {
82 expression: BoundExpr,
83}
84
85impl BoundQuery {
86 pub fn matches(&self, data: &Dataset, row: usize) -> bool {
88 self.expression.evaluate(data, row).is_truthy()
89 }
90
91 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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
107#[non_exhaustive]
108#[error("{message} at byte {offset}")]
114pub struct QueryError {
115 message: String,
116 offset: usize,
117}
118
119impl QueryError {
120 pub fn message(&self) -> &str {
122 &self.message
123 }
124
125 pub fn offset(&self) -> usize {
127 self.offset
128 }
129}