Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 34 additions & 90 deletions src/db/database.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
use crate::db::table::alter_table;
use crate::db::table::create_table;
use crate::db::table::delete;
use crate::db::table::insert;
use crate::db::table::select;
use crate::db::table::update;
use crate::db::table::{Row, Table, drop_table};
use crate::db::table::core::{row::Row, table::Table};
use crate::db::table::operations::{
alter_table, create_table, delete, drop_table, insert, select, update,
};
use crate::db::transactions::{TransactionEntry, TransactionLog};
use crate::interpreter::ast::SqlStatement;
use std::collections::HashMap;

pub struct Database {
pub tables: HashMap<String, Table>,
pub transaction: Option<TransactionLog>,
}

pub struct TransactionLog {
pub entries: Vec<TransactionEntry>,
pub savepoint_name: Vec<Savepoint>,
}

pub struct TransactionEntry {
pub statement: SqlStatement,
pub table_name: String,
pub affected_rows: Vec<usize>,
}

pub struct Savepoint {
pub name: String,
pub transaction: TransactionLog,
}

impl Database {
pub fn new() -> Self {
Self {
tables: HashMap::new(),
transaction: None,
transaction: TransactionLog { entries: None },
}
}

Expand All @@ -41,13 +24,14 @@ impl Database {
return match sql_statement {
SqlStatement::CreateTable(statement) => {
create_table::create_table(self, statement)?;
self.append_to_transaction(sql_statement_clone, vec![])?;
self.transaction.append_entry(sql_statement_clone, vec![])?;
Ok(None)
}
SqlStatement::InsertInto(statement) => {
let table = self.get_table_mut(&statement.table_name)?;
let rows_inserted = insert::insert(table, statement)?;
self.append_to_transaction(sql_statement_clone, rows_inserted)?;
self.transaction
.append_entry(sql_statement_clone, rows_inserted)?;
Ok(None)
}
SqlStatement::Select(statement) => {
Expand All @@ -57,73 +41,59 @@ impl Database {
SqlStatement::UpdateStatement(statement) => {
let table = self.get_table_mut(&statement.table_name)?;
let rows_updated = update::update(table, statement)?;
self.append_to_transaction(sql_statement_clone, rows_updated)?;
self.transaction
.append_entry(sql_statement_clone, rows_updated)?;
Ok(None)
}
SqlStatement::DeleteStatement(statement) => {
let table = self.get_table_mut(&statement.table_name)?;
let rows_deleted = delete::delete(table, statement)?;
self.append_to_transaction(sql_statement_clone, rows_deleted)?;
self.transaction
.append_entry(sql_statement_clone, rows_deleted)?;
Ok(None)
}
SqlStatement::DropTable(statement) => {
drop_table::drop_table(self, statement)?;
self.append_to_transaction(sql_statement_clone, vec![])?;
self.transaction.append_entry(sql_statement_clone, vec![])?;
Ok(None)
}
SqlStatement::AlterTable(statement) => {
alter_table::alter_table(self, statement, self.transaction.is_some())?;
self.append_to_transaction(sql_statement_clone, vec![])?;
alter_table::alter_table(self, statement, self.transaction.in_transaction())?;
self.transaction.append_entry(sql_statement_clone, vec![])?;
Ok(None)
}
SqlStatement::BeginTransaction(_) => {
self.transaction = Some(TransactionLog {
entries: vec![],
savepoint_name: vec![],
});
self.transaction.begin_transaction();
Ok(None)
}
SqlStatement::Commit => {
if let Some(transaction) = self.transaction.take() {
for transaction_entry in transaction.entries.iter() {
let table = self.get_table_mut(transaction_entry.table_name.as_str())?;
table.commit_transaction(&transaction_entry.affected_rows)?;
let transaction_log = self.transaction.commit_transaction()?;
for transaction_entry in transaction_log.get_entries()?.iter() {
match transaction_entry {
TransactionEntry::Statement(statement) => {
let table = self.get_table_mut(statement.table_name.as_str())?;
table.commit_transaction(&statement.affected_rows)?;
}
TransactionEntry::Savepoint(_) => {}
}
}

Ok(None)
}
SqlStatement::Rollback(_) => {
self.transaction = None;
self.transaction.commit_transaction()?;
self.tables.iter_mut().for_each(|(_, table)| {
table.rollback_transaction();
});
Ok(None)
}
SqlStatement::Savepoint(statement) => {
match &mut self.transaction {
Some(transaction) => {
transaction.savepoint_name.push(Savepoint {
name: statement.savepoint_name.clone(),
});
}
None => {
return Err("No transaction is currently active".to_string());
}
}
self.append_to_transaction(sql_statement_clone, vec![])?;
SqlStatement::Savepoint(_) => {
self.transaction.append_entry(sql_statement_clone, vec![])?;
Ok(None)
}
SqlStatement::Release(statement) => {
match &mut self.transaction {
Some(transaction) => {
transaction
.savepoint_name
.retain(|savepoint| savepoint.name != statement.savepoint_name);
}
None => {
return Err("No transaction is currently active".to_string());
}
}
self.transaction
.release_savepoint(&statement.savepoint_name)?;
Ok(None)
}
};
Expand All @@ -146,38 +116,12 @@ impl Database {
}
Ok(self.tables.get_mut(table_name).unwrap())
}

fn append_to_transaction(
&mut self,
sql_statement: SqlStatement,
affected_rows: Vec<usize>,
) -> Result<(), String> {
let table_name = match &sql_statement {
SqlStatement::CreateTable(statement) => statement.table_name.clone(),
SqlStatement::InsertInto(statement) => statement.table_name.clone(),
SqlStatement::UpdateStatement(statement) => statement.table_name.clone(),
SqlStatement::DeleteStatement(statement) => statement.table_name.clone(),
SqlStatement::DropTable(statement) => statement.table_name.clone(),
SqlStatement::AlterTable(statement) => statement.table_name.clone(),
SqlStatement::Savepoint(_) => "".to_string(),
_ => unreachable!(),
};

if let Some(transaction) = &mut self.transaction {
transaction.entries.push(TransactionEntry {
statement: sql_statement,
table_name: table_name,
affected_rows: affected_rows,
});
}
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::db::table::{ColumnDefinition, DataType};
use crate::db::table::core::{column::ColumnDefinition, value::DataType};

fn default_database() -> Database {
Database {
Expand All @@ -199,7 +143,7 @@ mod tests {
],
),
)]),
transaction: None,
transaction: TransactionLog { entries: None },
}
}

Expand Down
1 change: 1 addition & 0 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod database;
pub mod table;
pub mod transactions;
112 changes: 112 additions & 0 deletions src/db/table/core/column.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use crate::db::table::core::value::DataType;

#[derive(Debug, PartialEq, Clone)]
pub struct ColumnDefinition {
pub name: String,
pub data_type: DataType,
pub constraints: Vec<ColumnConstraint>,
}

#[derive(Debug, PartialEq, Clone)]
pub struct ColumnConstraint {
pub constraint_type: String,
}

#[derive(Debug, PartialEq, Clone)]
pub struct ColumnStack {
pub stack: Vec<Vec<ColumnDefinition>>,
}

impl ColumnStack {
pub fn new(columns: Vec<ColumnDefinition>) -> Self {
Self {
stack: vec![columns],
}
}

fn append_clone(&mut self) -> Result<(), String> {
self.stack.push(self.peek()?.clone());
Ok(())
}

pub fn push_column(&mut self, column: ColumnDefinition, is_transaction: bool) {
if is_transaction {
self.stack.push(self.stack.last().unwrap().clone());
}
self.stack.last_mut().unwrap().push(column);
}

pub fn rename_column(
&mut self,
old_column_name: &String,
new_column_name: &String,
table_name: &String,
is_transaction: bool,
) -> Result<(), String> {
if is_transaction {
self.append_clone()?;
}
let columns = self
.peek_mut()?
.iter_mut()
.find(|column| column.name == *old_column_name);
match columns {
Some(column) => column.name = new_column_name.clone(),
None => {
return Err(format!(
"Column `{}` does not exist in table `{}`",
old_column_name, table_name
));
}
}
Ok(())
}

pub fn drop_column(
&mut self,
column_name: &String,
table_name: &String,
is_transaction: bool,
) -> Result<(), String> {
if is_transaction {
self.append_clone()?;
}
match self.get_index_of_column(column_name) {
Ok(index) => self.peek_mut()?.remove(index),
Err(_) => {
return Err(format!(
"Column `{}` does not exist in table `{}`",
column_name, table_name
));
}
};
Ok(())
}

pub fn get_index_of_column(&self, column_name: &String) -> Result<usize, String> {
let columns = self.peek();
match columns {
Ok(columns) => {
if let Some(index) = columns
.iter()
.position(|column| column.name == *column_name)
{
Ok(index)
} else {
Err(format!("Column `{}` does not exist", column_name))
}
}
Err(_) => Err("Column stack is empty".to_string()),
}
}

fn peek(&self) -> Result<&Vec<ColumnDefinition>, String> {
self.stack.last().ok_or("Column stack is empty".to_string())
}

fn peek_mut(&mut self) -> Result<&mut Vec<ColumnDefinition>, String> {
self.stack
.last_mut()
.ok_or("Column stack is empty".to_string())
}
}
4 changes: 4 additions & 0 deletions src/db/table/core/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod column;
pub mod row;
pub mod table;
pub mod value;
30 changes: 30 additions & 0 deletions src/db/table/core/row.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use crate::db::table::core::value::Value;
use std::ops::{Deref, DerefMut};

#[derive(Debug, Eq, PartialEq, Hash, Clone)]
#[repr(transparent)]
pub struct Row(pub Vec<Value>);

#[derive(Debug)]
pub struct RowStack {
pub stack: Vec<Row>,
}

impl Deref for Row {
type Target = Vec<Value>;
fn deref(&self) -> &Self::Target {
&self.0
}
}

impl DerefMut for Row {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

impl RowStack {
pub fn new(stack: Row) -> Self {
Self { stack: vec![stack] }
}
}
Loading
Loading