Skip to content

Commit

Permalink
Fixed tests + added support to handle folders rather than table directly
Browse files Browse the repository at this point in the history
  • Loading branch information
lucas794 committed Sep 20, 2024
1 parent 4ee821b commit ee3c77f
Show file tree
Hide file tree
Showing 12 changed files with 230 additions and 222 deletions.
11 changes: 0 additions & 11 deletions default_file.csv

This file was deleted.

28 changes: 16 additions & 12 deletions src/conditions/condition.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::errors::tperrors::Tperrors;

use super::value::Value;

/// representation of the condition that can be used on a query
Expand All @@ -17,12 +19,14 @@ impl Condition {
///
/// a query with ```"Name = 'John'"``` will return true
///
pub fn matches_condition(&self, conditions: &str) -> bool {
pub fn matches_condition(&self, conditions: &str) -> Result<bool, Tperrors> {
let splitted_conditions = conditions.split_whitespace().collect::<Vec<&str>>();

/*if (splitted_conditions.len() % 2) == 0 {
return false; // Invalid number of tokens
}*/
if splitted_conditions.len() <= 1 {
return Err(Tperrors::Syntax(
"Condition should be separated. Example: Name = 'John'".to_string(),
));
}
let mut i = 0;
let mut result = true;
let mut is_negated = false; // Initialize negation to false
Expand All @@ -48,7 +52,7 @@ impl Condition {
is_negated = false; // Reset negation flag after use
if result {
// a single true in OR is enough
return true;
return Ok(true);
}
}
_ => {
Expand All @@ -57,7 +61,7 @@ impl Condition {
}
}
}
result
Ok(result)
}

/// given a condition, it will evaluate if the condition is met
Expand All @@ -66,9 +70,9 @@ impl Condition {
return false; // Avoid out-of-bounds access
}

let column = &conditions[*i].trim_matches('\'');
let column = &conditions[*i].trim_matches('\'').trim_matches('\"');
let operator = &conditions[*i + 1];
let value = &conditions[*i + 2].trim_matches('\'');
let value = &conditions[*i + 2].trim_matches('\'').trim_matches('\"');

*i += 3; // Advance the index

Expand Down Expand Up @@ -158,7 +162,7 @@ mod test {
];

for str_condition in str_conditions {
assert_eq!(conditions.matches_condition(str_condition), true);
assert_eq!(conditions.matches_condition(str_condition).unwrap(), true);
}
}

Expand All @@ -174,7 +178,7 @@ mod test {
let str_conditions = vec!["name = 'John'", "age = 20 OR name = 'John'"];

for str_condition in str_conditions {
assert_eq!(conditions.matches_condition(str_condition), true);
assert_eq!(conditions.matches_condition(str_condition).unwrap(), true);
}
}

Expand All @@ -190,7 +194,7 @@ mod test {
];

for str_condition in str_conditions {
assert_ne!(conditions.matches_condition(str_condition), false);
assert_ne!(conditions.matches_condition(str_condition).unwrap(), false);
}
}

Expand All @@ -208,7 +212,7 @@ mod test {
];

for str_condition in str_conditions {
assert_eq!(conditions.matches_condition(str_condition), true);
assert_eq!(conditions.matches_condition(str_condition).unwrap(), true);
}
}
}
18 changes: 9 additions & 9 deletions src/consults/delete.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::{
errors::{fileerrors::FileErrors, tperrors::Tperrors},
table::Table,
};
use crate::errors::{fileerrors::FileErrors, tperrors::Tperrors};
use crate::handler_tables::table::Table;

pub struct Delete;

Expand Down Expand Up @@ -41,19 +39,21 @@ impl Delete {
Ok(_) => {}
Err(e) => match e {
FileErrors::DeletionFailed => {
return Err(Tperrors::Generic("Deletion failed"));
return Err(Tperrors::Generic("Deletion failed".to_string()));
}
FileErrors::InvalidFile => {
return Err(Tperrors::Generic("Error while updating the file"));
return Err(Tperrors::Generic(
"Error while updating the file".to_string(),
));
}
},
}

Ok(())
}
Err(_) => {
return Err(Tperrors::Syntax("Invalid columns inside the query"));
}
Err(_) => Err(Tperrors::Syntax(
"Invalid columns inside the query".to_string(),
)),
}
}
}
15 changes: 6 additions & 9 deletions src/consults/insert.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{errors::tperrors::Tperrors, table::Table};
use crate::errors::tperrors::Tperrors;
use crate::handler_tables::table::*;

pub struct Insert;

Expand Down Expand Up @@ -43,16 +44,12 @@ impl Insert {
line.push('\n');
match table.insert_line_to_csv(line) {
Ok(_) => Ok(()),
Err(_) => {
return Err(Tperrors::Generic("Error while inserting line"));
}
Err(_) => Err(Tperrors::Generic("Error while inserting line".to_string())),
}
}
Err(_) => {
return Err(Tperrors::Generic(
"Invalid columns inside the query / mismatch with the table",
));
}
Err(_) => Err(Tperrors::Generic(
"Invalid columns inside the query / mismatch with the table".to_string(),
)),
}
}
}
9 changes: 5 additions & 4 deletions src/consults/select.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::errors::tperrors::*;
use crate::table::Table;
use crate::handler_tables::table::*;

pub struct Select;

Expand Down Expand Up @@ -52,8 +52,9 @@ impl Select {
}
Ok(())
}
Err(_) => {
return Err(Tperrors::Syntax("Invalid columns inside the query"));
Err(e) => {
let formatted_error = format!("{}", e);
Err(Tperrors::Generic(formatted_error))
}
}
}
Expand All @@ -78,7 +79,7 @@ mod tests {

#[test]
fn execute_select_fails_with_invalid_columns() {
let mut table = Table::new("./tests/database.csv").unwrap();
let mut table = Table::new("./tests/test_tables/database.csv".to_string()).unwrap();
let select = Select::new();
// i'm trying to select a column that does not exist
let columns = vec!["Trabajo Profesional".to_string()];
Expand Down
15 changes: 9 additions & 6 deletions src/consults/update.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::errors::fileerrors::*;
use crate::{errors::tperrors::Tperrors, table::Table};
use crate::errors::tperrors::Tperrors;
use crate::handler_tables::table::*;

pub struct Update;

Expand Down Expand Up @@ -49,19 +50,21 @@ impl Update {
Ok(_) => {}
Err(e) => match e {
FileErrors::DeletionFailed => {
return Err(Tperrors::Generic("Deletion failed"));
return Err(Tperrors::Generic("Deletion failed".to_string()));
}
FileErrors::InvalidFile => {
return Err(Tperrors::Generic("Error while updating the file"));
return Err(Tperrors::Generic(
"Error while updating the file".to_string(),
));
}
},
}

Ok(())
}
Err(_) => {
return Err(Tperrors::Syntax("Invalid columns inside the query"));
}
Err(_) => Err(Tperrors::Syntax(
"Invalid columns inside the query".to_string(),
)),
}
}
}
10 changes: 5 additions & 5 deletions src/errors/tperrors.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::fmt::{Display, Formatter, Result};

#[derive(Debug)]
pub enum Tperrors<'a> {
Table(&'a str),
Syntax(&'a str),
Generic(&'a str),
pub enum Tperrors {
Table(String),
Syntax(String),
Generic(String),
}

impl<'a> Display for Tperrors<'a> {
impl Display for Tperrors {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
Tperrors::Generic(e) => write!(f, "ERROR {}", e),
Expand Down
41 changes: 21 additions & 20 deletions src/extractors/extractor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ impl Extractor {
/// Example
/// SELECT name, age FROM table;
/// Returns ["name", "age"]
pub fn extract_columns_for_select(
&self,
query: &str,
) -> Result<Vec<String>, Tperrors<'static>> {
pub fn extract_columns_for_select(&self, query: &str) -> Result<Vec<String>, Tperrors> {
let query = query.trim();

let where_pos = query.find("FROM");
Expand All @@ -42,9 +39,9 @@ impl Extractor {

Ok(columns)
}
None => {
return Err(Tperrors::Syntax("Invalid select query (Missing FROM)"));
}
None => Err(Tperrors::Syntax(
"Invalid select query (Missing FROM)".to_string(),
)),
}
}

Expand All @@ -58,18 +55,22 @@ impl Extractor {
pub fn extract_columns_and_values_for_insert(
&self,
query: &str,
) -> Result<(Vec<String>, Vec<String>), Tperrors<'static>> {
) -> Result<(Vec<String>, Vec<String>), Tperrors> {
let (start_columns, end_columns) = match (query.find("("), query.find(")")) {
(Some(start), Some(end)) => (start, end),
_ => {
return Err(Tperrors::Syntax("Invalid INSERT query (Missing columns)"));
return Err(Tperrors::Syntax(
"Invalid INSERT query (Missing columns)".to_string(),
));
}
};

let (start_values, end_values) = match (query.rfind("("), query.rfind(")")) {
(Some(start), Some(end)) => (start, end),
_ => {
return Err(Tperrors::Syntax("Invalid INSERT query (Missing values)"));
return Err(Tperrors::Syntax(
"Invalid INSERT query (Missing values)".to_string(),
));
}
};

Expand Down Expand Up @@ -97,7 +98,7 @@ impl Extractor {
// if len doesnt match we return an error
if columns.len() != values.len() {
return Err(Tperrors::Syntax(
"Invalid INSERT query (Columns and values do not match)",
"Invalid INSERT query (Columns and values do not match)".to_string(),
));
}

Expand All @@ -117,13 +118,13 @@ impl Extractor {
pub fn extract_columns_and_values_for_update(
&self,
query: &str,
) -> Result<(Vec<String>, Vec<String>), Tperrors<'static>> {
) -> Result<(Vec<String>, Vec<String>), Tperrors> {
let (start_columns, end_columns) = match (query.find("SET"), query.find("WHERE")) {
(Some(start), Some(end)) => (start, end),
(Some(start), None) => (start, query.len() - 1), // no WHERE, it means ALL tables.., risky..
_ => {
return Err(Tperrors::Syntax(
"Invalid UPDATE query (Missing SET or WHERE)",
"Invalid UPDATE query (Missing SET or WHERE)".to_string(),
));
}
};
Expand All @@ -144,7 +145,9 @@ impl Extractor {
let what_to_update = what_to_update.split('=').collect::<Vec<&str>>();

if what_to_update.len() != 2 {
return Err(Tperrors::Syntax("Invalid UPDATE query (Missing =)"));
return Err(Tperrors::Syntax(
"Invalid UPDATE query (Missing =)".to_string(),
));
}

let column = what_to_update[0].trim().to_string();
Expand All @@ -167,17 +170,15 @@ impl Extractor {
&self,
query: &'a str,
consult: SQLCommand,
) -> Result<&'a str, Tperrors<'static>> {
) -> Result<&'a str, Tperrors> {
let query = query.trim();

let (start, offset, end) = self.extract_positions(query, consult);

match (start, end) {
(0, 0) => {
return Err(Tperrors::Syntax(
"Invalid query (Missing any KEY words on your consult)",
));
}
(0, 0) => Err(Tperrors::Syntax(
"Invalid query (Missing any KEY words on your consult)".to_string(),
)),
_ => {
let table_data = &query[start + offset..end];
let table_data = table_data.trim();
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ pub mod conditions;
pub mod consults;
pub mod errors;
pub mod extractors;
pub mod table;
pub mod handler_tables;
Loading

0 comments on commit ee3c77f

Please sign in to comment.