sqlite-clone/sqlite_core/src/statement.rs

78 lines
2.2 KiB
Rust
Raw Normal View History

2022-04-02 21:58:23 +02:00
use crate::row;
2022-03-29 22:11:49 +02:00
use crate::row::Serialize;
use crate::table::Table;
2022-03-27 23:17:29 +02:00
pub enum StatementType {
2022-03-29 22:11:49 +02:00
Insert { row: row::Row },
2022-03-27 23:17:29 +02:00
Select,
}
2022-04-02 21:58:23 +02:00
pub enum StatementResultType {
Insert,
Select { rows: Vec<row::Row> },
}
2022-03-29 22:11:49 +02:00
pub enum ExecuteResult {
2022-04-02 21:58:23 +02:00
Error {
error: String,
},
Success {
statement_result_type: StatementResultType,
},
2022-03-27 23:17:29 +02:00
}
pub struct Statement {
statement_type: StatementType,
}
impl Statement {
pub fn new(statement_type: StatementType) -> Self {
2022-03-29 22:11:49 +02:00
Self { statement_type }
2022-03-27 23:17:29 +02:00
}
pub fn parse_statement(command: &String) -> Result<Self, String> {
if command.starts_with("insert") {
match sscanf::scanf!(command, "insert {} {} {}", usize, str, str) {
Ok((id, username, email)) => {
2022-03-29 22:11:49 +02:00
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),
2022-03-27 23:17:29 +02:00
}
}
2022-03-29 22:11:49 +02:00
_ => Err(String::from("could not parse insert statement")),
2022-03-27 23:17:29 +02:00
}
} else if command.starts_with("select") {
Ok(Statement::new(StatementType::Select))
} else {
2022-03-29 22:11:49 +02:00
Err(String::from("Could not parse command"))
2022-03-27 23:17:29 +02:00
}
}
2022-04-02 21:58:23 +02:00
pub fn execute(&self, table: &mut Table) -> ExecuteResult {
2022-03-27 23:17:29 +02:00
match &self.statement_type {
2022-03-29 22:11:49 +02:00
StatementType::Insert { row } => match row.serialize() {
Err(e) => ExecuteResult::Error {
error: e.to_string(),
},
Ok(serialization) => {
table.append_row(serialization);
2022-04-02 21:58:23 +02:00
ExecuteResult::Success {
statement_result_type: StatementResultType::Insert {},
}
2022-03-29 22:11:49 +02:00
}
},
2022-03-27 23:17:29 +02:00
StatementType::Select => {
2022-03-29 22:11:49 +02:00
let rows = table.get_rows();
2022-04-02 21:58:23 +02:00
return ExecuteResult::Success {
statement_result_type: StatementResultType::Select { rows },
};
2022-03-27 23:17:29 +02:00
}
}
}
}