use crate::row::Serialize; use crate::table::Table; use crate::{row}; pub enum StatementType { Insert { row: row::Row }, Select, } pub enum ExecuteResult { Error { error: String }, Success, } 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(crate) 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 } }, StatementType::Select => { let rows = table.get_rows(); for row in rows { row.print() } return ExecuteResult::Success; } } } }