logic exprs
This commit is contained in:
parent
a26ea16f55
commit
824a5cdb43
6 changed files with 474 additions and 26 deletions
|
|
@ -1,4 +1,5 @@
|
|||
use std::collections::{HashMap, HashSet};
|
||||
use std::mem;
|
||||
|
||||
use crate::table::table_definition::ColumnDefinition;
|
||||
use crate::{Datatype, TableDefinition};
|
||||
|
|
@ -20,6 +21,7 @@ pub struct CreateCommand {
|
|||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub struct DeleteCommand {
|
||||
pub table_name: String,
|
||||
pub logic_expression: Option<LogicExpression>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
|
|
@ -32,6 +34,7 @@ pub struct InsertCommand {
|
|||
pub struct SelectCommand {
|
||||
pub table_name: String,
|
||||
pub column_names: Vec<String>,
|
||||
pub logic_expression: Option<LogicExpression>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
|
|
@ -40,6 +43,38 @@ pub struct InsertItem {
|
|||
pub column_value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone)]
|
||||
enum LogicalOperator {
|
||||
Equal,
|
||||
GreaterThan,
|
||||
LessThan,
|
||||
GreaterThanEqualTo,
|
||||
LessThanEqualTo,
|
||||
And,
|
||||
Or,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone)]
|
||||
pub enum LogicValue {
|
||||
StringValue(String),
|
||||
U8Value(u8),
|
||||
BoolValue(bool),
|
||||
ColumnName(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum LogicSide {
|
||||
// pub expression: LogicExpression,
|
||||
Value(LogicValue)
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone)]
|
||||
pub struct LogicExpression {
|
||||
pub left_hand: LogicValue,
|
||||
pub right_hand: LogicValue,
|
||||
pub operator: LogicalOperator
|
||||
}
|
||||
|
||||
enum CreateParserState {
|
||||
Object,
|
||||
TableName,
|
||||
|
|
@ -55,12 +90,14 @@ enum SelectParserState {
|
|||
ColumnName,
|
||||
ColumnNameCommaOrFrom,
|
||||
TableName,
|
||||
WhereKeywordOrSemicolon,
|
||||
Semicolon,
|
||||
}
|
||||
|
||||
enum DeleteParserState {
|
||||
FromKeyword,
|
||||
TableName,
|
||||
WhereKeywordOrSemicolon,
|
||||
Semicolon,
|
||||
}
|
||||
|
||||
|
|
@ -77,8 +114,17 @@ enum InsertParserState {
|
|||
Semicolon,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum LogicExpressionParserState {
|
||||
NumberOrQuoteOrColname,
|
||||
StringValue,
|
||||
EndQuote,
|
||||
Operator,
|
||||
}
|
||||
|
||||
|
||||
pub fn tokenizer(text: String) -> Vec<String> {
|
||||
let parts = HashSet::from([' ', ',', ';', '(', ')']);
|
||||
let parts = HashSet::from([' ', ',', ';', '(', ')', '\'']);
|
||||
let mut tokens: Vec<String> = vec![];
|
||||
let mut cur_str = String::new();
|
||||
let mut in_quotes = false;
|
||||
|
|
@ -100,10 +146,154 @@ pub fn tokenizer(text: String) -> Vec<String> {
|
|||
cur_str.push(cur_char);
|
||||
}
|
||||
}
|
||||
tokens.push(cur_str);
|
||||
|
||||
tokens
|
||||
}
|
||||
|
||||
impl LogicValue {
|
||||
pub fn from_string(string: String) -> ::anyhow::Result<LogicValue> {
|
||||
let test = string.parse::<u8>();
|
||||
match test {
|
||||
Ok(u8_val) => {
|
||||
return Ok(LogicValue::U8Value(u8_val));
|
||||
},
|
||||
Err(_) => {
|
||||
let res = string.trim_matches(char::from(0));
|
||||
return Ok(LogicValue::StringValue(res.to_string()));
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogicExpression {
|
||||
pub fn is_valid(&self) -> bool {
|
||||
return mem::discriminant(&self.left_hand) == mem::discriminant(&self.right_hand);
|
||||
}
|
||||
|
||||
pub fn is_evaluatable(&self) -> bool {
|
||||
return mem::discriminant(&self.left_hand) != mem::discriminant(&LogicValue::ColumnName(String::from(""))) &&
|
||||
mem::discriminant(&self.right_hand) != mem::discriminant(&LogicValue::ColumnName(String::from("")));
|
||||
}
|
||||
|
||||
pub fn fill_values(&mut self, hmap: HashMap<String, LogicValue>) -> ::anyhow::Result<()> {
|
||||
for (name, value) in hmap {
|
||||
if self.left_hand == LogicValue::ColumnName(name.clone()) {
|
||||
self.left_hand = value.clone();
|
||||
}
|
||||
if self.right_hand == LogicValue::ColumnName(name.clone()) {
|
||||
self.right_hand = value.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn evaluate(&self) -> ::anyhow::Result<bool> {
|
||||
if !self.is_evaluatable() {
|
||||
return Err(anyhow!("Logical expression has not been properly filled. (Do you have a typo in a column name?)"));
|
||||
}
|
||||
if !self.is_valid() {
|
||||
return Err(anyhow!("Logical expression is comparing 2 differing datatypes"));
|
||||
}
|
||||
println!("{:?}", self);
|
||||
match self.left_hand {
|
||||
LogicValue::StringValue(_) => {
|
||||
return self.evaluate_string();
|
||||
}
|
||||
LogicValue::BoolValue(_) => {
|
||||
return self.evaluate_bool();
|
||||
}
|
||||
LogicValue::U8Value(_) => {
|
||||
return self.evaluate_u8();
|
||||
}
|
||||
LogicValue::ColumnName(_) => {
|
||||
return Err(anyhow!("Cannot compare names of 2 columns, only values"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_string(&self) -> ::anyhow::Result<bool> {
|
||||
match self.operator {
|
||||
LogicalOperator::Equal => {
|
||||
return Ok(self.left_hand == self.right_hand);
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("Invalid operator for datatype varchar"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_bool(&self) -> ::anyhow::Result<bool>{
|
||||
match self.operator {
|
||||
LogicalOperator::Equal => {
|
||||
return Ok(self.left_hand == self.right_hand);
|
||||
}
|
||||
LogicalOperator::And => {
|
||||
if let LogicValue::BoolValue(left) = self.left_hand {
|
||||
if let LogicValue::BoolValue(right) = self.right_hand {
|
||||
return Ok(left && right);
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Mismatched datatypes"));
|
||||
}
|
||||
LogicalOperator::Or => {
|
||||
if let LogicValue::BoolValue(left) = self.left_hand {
|
||||
if let LogicValue::BoolValue(right) = self.right_hand {
|
||||
return Ok(left || right);
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Mismatched datatypes"));
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("Invalid operator for datatype bool"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_u8(&self) -> ::anyhow::Result<bool>{
|
||||
match self.operator {
|
||||
LogicalOperator::Equal => {
|
||||
return Ok(self.left_hand == self.right_hand);
|
||||
}
|
||||
LogicalOperator::GreaterThan => {
|
||||
if let LogicValue::U8Value(left) = self.left_hand {
|
||||
if let LogicValue::U8Value(right) = self.right_hand {
|
||||
return Ok(left > right);
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Mismatched datatypes"));
|
||||
}
|
||||
LogicalOperator::LessThan => {
|
||||
if let LogicValue::U8Value(left) = self.left_hand {
|
||||
if let LogicValue::U8Value(right) = self.right_hand {
|
||||
return Ok(left < right);
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Mismatched datatypes"));
|
||||
}
|
||||
LogicalOperator::GreaterThanEqualTo => {
|
||||
if let LogicValue::U8Value(left) = self.left_hand {
|
||||
if let LogicValue::U8Value(right) = self.right_hand {
|
||||
return Ok(left >= right);
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Mismatched datatypes"));
|
||||
}
|
||||
LogicalOperator::LessThanEqualTo => {
|
||||
if let LogicValue::U8Value(left) = self.left_hand {
|
||||
if let LogicValue::U8Value(right) = self.right_hand {
|
||||
return Ok(left <= right);
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Mismatched datatypes"));
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("Invalid operator for datatype integer"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Command {
|
||||
fn parse_insert_command(tokens: &mut Vec<String>) -> ::anyhow::Result<Command> {
|
||||
let mut state: InsertParserState = InsertParserState::IntoKeyword;
|
||||
|
|
@ -218,12 +408,93 @@ impl Command {
|
|||
Err(anyhow!("Unexpected end of input"))
|
||||
}
|
||||
|
||||
fn parse_logic_expression(tokens: &mut Vec<String>) -> ::anyhow::Result<LogicExpression> {
|
||||
let mut state: LogicExpressionParserState = LogicExpressionParserState::NumberOrQuoteOrColname;
|
||||
let mut left_hand: Option<LogicValue> = None;
|
||||
let mut right_hand: Option<LogicValue> = None;
|
||||
let mut operator: Option<LogicalOperator> = None;
|
||||
|
||||
while let Some(token) = &tokens.pop() {
|
||||
match state {
|
||||
LogicExpressionParserState::NumberOrQuoteOrColname => {
|
||||
if token == "'" {
|
||||
state = LogicExpressionParserState::StringValue;
|
||||
} else {
|
||||
let test = token.parse::<u8>();
|
||||
match test {
|
||||
Ok(u8_val) => {
|
||||
if left_hand.is_none() {
|
||||
left_hand = Some(LogicValue::U8Value(u8_val));
|
||||
state = LogicExpressionParserState::Operator;
|
||||
} else {
|
||||
right_hand = Some(LogicValue::U8Value(u8_val));
|
||||
return Ok(LogicExpression {left_hand: left_hand.unwrap(), right_hand: right_hand.unwrap(), operator: operator.unwrap()});
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
if left_hand.is_none() {
|
||||
left_hand = Some(LogicValue::ColumnName(token.to_string()));
|
||||
state = LogicExpressionParserState::Operator;
|
||||
} else {
|
||||
right_hand = Some(LogicValue::ColumnName(token.to_string()));
|
||||
return Ok(LogicExpression {left_hand: left_hand.unwrap(), right_hand: right_hand.unwrap(), operator: operator.unwrap()});
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
LogicExpressionParserState::StringValue => {
|
||||
let mut value: Option<LogicValue> = None;
|
||||
if token == "'" {
|
||||
value = Some(LogicValue::StringValue("".to_string()));
|
||||
} else {
|
||||
value = Some(LogicValue::StringValue(token.to_string()));
|
||||
}
|
||||
if left_hand.is_none() {
|
||||
left_hand = value;
|
||||
} else {
|
||||
right_hand = value;
|
||||
}
|
||||
state = LogicExpressionParserState::EndQuote;
|
||||
}
|
||||
LogicExpressionParserState::EndQuote => {
|
||||
if token == "'" {
|
||||
if right_hand.is_none() {
|
||||
state = LogicExpressionParserState::Operator;
|
||||
} else {
|
||||
return Ok(LogicExpression {left_hand: left_hand.unwrap(), right_hand: right_hand.unwrap(), operator: operator.unwrap()});
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow!("Expected end quote at or near {}", token));
|
||||
}
|
||||
}
|
||||
LogicExpressionParserState::Operator => {
|
||||
operator = match token.as_str() {
|
||||
"OR" => Some(LogicalOperator::Or),
|
||||
"AND" => Some(LogicalOperator::And),
|
||||
"=" => Some(LogicalOperator::Equal),
|
||||
">" => Some(LogicalOperator::GreaterThan),
|
||||
"<" => Some(LogicalOperator::LessThan),
|
||||
">=" => Some(LogicalOperator::GreaterThanEqualTo),
|
||||
"<=" => Some(LogicalOperator::LessThanEqualTo),
|
||||
_ => return Err(anyhow!("Unknown operator {}", token))
|
||||
};
|
||||
state = LogicExpressionParserState::NumberOrQuoteOrColname;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow!("Unexpected end of input"))
|
||||
}
|
||||
|
||||
fn parse_select_command(tokens: &mut Vec<String>) -> ::anyhow::Result<Command> {
|
||||
let mut state: SelectParserState = SelectParserState::ColumnName;
|
||||
|
||||
// intermediate tmp vars
|
||||
let mut table_name = String::new();
|
||||
let mut column_names: Vec<String> = vec![];
|
||||
let mut logic_expression: Option<LogicExpression> = None;
|
||||
|
||||
while let Some(token) = &tokens.pop() {
|
||||
match state {
|
||||
|
|
@ -246,13 +517,24 @@ impl Command {
|
|||
}
|
||||
SelectParserState::TableName => {
|
||||
table_name = token.to_string();
|
||||
state = SelectParserState::Semicolon;
|
||||
state = SelectParserState::WhereKeywordOrSemicolon;
|
||||
}
|
||||
SelectParserState::WhereKeywordOrSemicolon => {
|
||||
if token == ";" {
|
||||
return Ok(Command::Select(SelectCommand { table_name, column_names, logic_expression: None }));
|
||||
} else if token == "WHERE" {
|
||||
logic_expression = Some(Self::parse_logic_expression(tokens)?);
|
||||
state = SelectParserState::Semicolon;
|
||||
} else {
|
||||
return Err(anyhow!("Expected semicolon at or near '{}'", token));
|
||||
|
||||
}
|
||||
}
|
||||
SelectParserState::Semicolon => {
|
||||
if token != ";" {
|
||||
return Err(anyhow!("Expected semicolon at or near '{}'", token));
|
||||
} else {
|
||||
return Ok(Command::Select(SelectCommand { table_name, column_names }));
|
||||
return Ok(Command::Select(SelectCommand { table_name, column_names, logic_expression }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -267,6 +549,7 @@ impl Command {
|
|||
|
||||
// intermediate tmp vars
|
||||
let mut table_name = String::new();
|
||||
let mut logic_expression: Option<LogicExpression> = None;
|
||||
|
||||
while let Some(token) = &tokens.pop() {
|
||||
match state {
|
||||
|
|
@ -279,13 +562,23 @@ impl Command {
|
|||
}
|
||||
DeleteParserState::TableName => {
|
||||
table_name = token.to_string();
|
||||
state = DeleteParserState::Semicolon;
|
||||
state = DeleteParserState::WhereKeywordOrSemicolon;
|
||||
}
|
||||
DeleteParserState::WhereKeywordOrSemicolon => {
|
||||
if token == ";" {
|
||||
return Ok(Command::Delete(DeleteCommand { table_name, logic_expression: None }));
|
||||
} else if token == "WHERE" {
|
||||
logic_expression = Some(Self::parse_logic_expression(tokens)?);
|
||||
state = DeleteParserState::Semicolon;
|
||||
} else {
|
||||
return Err(anyhow!("Expected semicolon at or near '{}'", token));
|
||||
}
|
||||
}
|
||||
DeleteParserState::Semicolon => {
|
||||
if token != ";" {
|
||||
return Err(anyhow!("Expected semicolon at or near '{}'", token));
|
||||
} else {
|
||||
return Ok(Command::Delete(DeleteCommand { table_name }));
|
||||
return Ok(Command::Delete(DeleteCommand { table_name, logic_expression }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -400,4 +693,12 @@ impl Command {
|
|||
|
||||
Err(anyhow!("Unexpected end of statement"))
|
||||
}
|
||||
|
||||
pub fn le_from_string(command_str: String) -> ::anyhow::Result<LogicExpression> {
|
||||
let mut tokens: Vec<String> = tokenizer(command_str.clone());
|
||||
println!("{}", command_str);
|
||||
println!("{:?}", tokens);
|
||||
tokens.reverse();
|
||||
return Ok(Self::parse_logic_expression(&mut tokens)?);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue