use crate::row; use crate::row::Serialize; use crate::table::Table; pub enum StatementType { Insert { row: row::Row }, Select, } pub enum StatementResultType { Insert, Select { rows: Vec }, } pub enum ExecuteResult { Error { error: String, }, Success { statement_result_type: StatementResultType, }, } pub struct Statement { statement_type: StatementType, } impl Statement { pub fn new(statement_type: StatementType) -> Self { Self { statement_type } } pub fn parse_statement(command: &String) -> Result { if command.starts_with("insert") { match sscanf::scanf!(command, "insert {} {} {}", usize, str, str) { Ok((id, username, email)) => { match row::Row::new( u32::try_from(id).unwrap(), username.to_string(), email.to_string(), ) { Ok(row) => Ok(Statement::new(StatementType::Insert { row })), Err(e) => Err(e), } } _ => Err(String::from("could not parse insert statement")), } } else if command.starts_with("select") { Ok(Statement::new(StatementType::Select)) } else { Err(String::from("Could not parse command")) } } pub fn execute(&self, table: &mut Table) -> ExecuteResult { match &self.statement_type { StatementType::Insert { row } => match row.serialize() { Err(e) => ExecuteResult::Error { error: e.to_string(), }, Ok(serialization) => { table.append_row(serialization); ExecuteResult::Success { statement_result_type: StatementResultType::Insert {}, } } }, StatementType::Select => { let rows = table.get_rows(); return ExecuteResult::Success { statement_result_type: StatementResultType::Select { rows }, }; } } } }