usql/executor.cpp

121 lines
3.2 KiB
C++

#include "executor.h"
#include "exception.h"
#include <algorithm>
Executor::Executor() {
m_tables.clear();
}
Table* Executor::find_table(const std::string name) {
auto name_cmp = [name](Table t){ return t.m_name == name; };
auto table_def = std::find_if(begin(m_tables), end(m_tables), name_cmp );
if (table_def != std::end(m_tables)) {
return table_def.operator->();
} else {
// TODO throw exception
}
}
bool Executor::execute(Node& node) {
// TODO optimize node here
switch (node.node_type) {
case NodeType::create_table:
return execute_create_table(static_cast<CreateTableNode &>(node));
case NodeType::insert_into:
return execute_insert_into_table(static_cast<InsertIntoTableNode &>(node));
case NodeType::select_from:
return execute_select(static_cast<SelectFromTableNode &>(node));
default:
// TODO error message
return false;
}
}
bool Executor::execute_create_table(CreateTableNode& node) {
// TODO check table does not exists
Table table{node.table_name, node.cols_defs};
m_tables.push_back(table);
return true;
}
bool Executor::execute_insert_into_table(InsertIntoTableNode& node) {
// TODO check column names.size = values.size
// find table
Table* table_def = find_table(node.table_name);
// prepare empty new_row
std::vector<std::string> new_row;
new_row.reserve(table_def->columns_count());
for(size_t i=0; i<table_def->columns_count(); i++) {
new_row.push_back(std::string {""});
}
// copy values
for(size_t i=0; i<node.cols_names.size(); i++) {
auto colNameNode = node.cols_names[i];
ColDefNode col_def = table_def->get_column_def(colNameNode.name);
// TODO validate
new_row[col_def.order] = node.cols_values[i].value;
}
// TODO check not null columns
// append new_row
table_def->m_rows.push_back(new_row);
return true;
}
bool Executor::execute_select(SelectFromTableNode& node) {
// TODO create plan for accessing rows
// find source table
Table* table = find_table(node.table_name);
// create result table
std::vector<ColDefNode> result_tbl_col_defs{};
std::vector<int> source_table_col_index{};
int i = 0; // new column order
for(ColNameNode rc : node.cols_names) {
ColDefNode cdef = table->get_column_def(rc.name);
source_table_col_index.push_back(cdef.order);
auto col = ColDefNode(rc.name, cdef.type, i, cdef.length, cdef.null);
result_tbl_col_defs.push_back(col);
i++;
}
Table result {"result", result_tbl_col_defs};
// execute access plan
for (auto row = begin (table->m_rows); row != end (table->m_rows); ++row) {
// eval there for row
bool where_true = true;
if (where_true) {
// prepare empty row
std::vector<std::string> new_row;
new_row.reserve(result.columns_count());
for(auto i=0; i<result.columns_count(); i++) {
new_row.push_back(row->at(source_table_col_index[i]));
}
result.m_rows.push_back(new_row);
}
}
result.print();
return true;
}