use std::fmt;
use super::Dataset;
mod ast;
mod parser;
use ast::{BoundExpr, Expr};
use parser::{Lexer, Parser};
#[derive(Clone, Debug, PartialEq)]
pub struct Query {
source: String,
expression: Expr,
}
impl Query {
pub fn parse(source: &str) -> Result<Self, QueryError> {
let tokens = Lexer::new(source).tokens()?;
let mut parser = Parser::new(tokens);
let expression = parser.expression()?;
parser.expect_end()?;
Ok(Self {
source: source.to_owned(),
expression,
})
}
pub fn source(&self) -> &str {
&self.source
}
pub fn columns(&self) -> Vec<String> {
let mut columns = Vec::new();
self.expression.columns(&mut columns);
columns
}
pub fn bind(&self, data: &Dataset) -> BoundQuery {
BoundQuery {
expression: self.expression.bind(data),
}
}
pub fn matches(&self, data: &Dataset, row: usize) -> bool {
self.expression.evaluate(data, row).is_truthy()
}
pub fn matching_rows(&self, data: &Dataset) -> Vec<usize> {
self.bind(data).matching_rows(data)
}
}
pub struct BoundQuery {
expression: BoundExpr,
}
impl BoundQuery {
pub fn matches(&self, data: &Dataset, row: usize) -> bool {
self.expression.evaluate(data, row).is_truthy()
}
pub fn matching_rows(&self, data: &Dataset) -> Vec<usize> {
(0..data.row_count())
.filter(|row| self.expression.evaluate(data, *row).is_truthy())
.collect()
}
}
impl fmt::Display for Query {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.source)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
#[error("{message} at byte {offset}")]
pub struct QueryError {
message: String,
offset: usize,
}
impl QueryError {
pub fn message(&self) -> &str {
&self.message
}
pub fn offset(&self) -> usize {
self.offset
}
}