preparing for functions

This commit is contained in:
VaclavT 2021-07-14 23:18:54 +02:00
parent eebfaacde4
commit 24d4fb2567
9 changed files with 535 additions and 467 deletions

12
Radme.md Normal file
View File

@ -0,0 +1,12 @@
### TODO
- unify using of float and double keywords to double
- use long data type for int
- stoi -> stol, stof -> stod
- add exceptions
- class members should have prefix m_
- add pipe | token
- add to_date a to_number functions
- add min and max functions
- add logging
- add const wherever should be

View File

@ -2,10 +2,11 @@
namespace usql { namespace usql {
Exception::Exception(const std::string &msg) { Exception::Exception(const std::string &msg) {
cause = msg; cause = msg;
} }
const char *Exception::what() const noexcept { return cause.c_str(); } const char *Exception::what() const noexcept { return cause.c_str(); }
}
}

View File

@ -6,14 +6,14 @@
namespace usql { namespace usql {
class Exception : public std::exception { class Exception : public std::exception {
private: private:
std::string cause; std::string cause;
public: public:
Exception(const std::string &msg); Exception(const std::string &msg);
const char *what() const noexcept; const char *what() const noexcept;
}; };
} }

View File

@ -32,7 +32,7 @@ int main(int argc, char *argv[]) {
}; };
usql::uSQL uSql{}; usql::USql uSql{};
for (auto command : sql_commands) { for (auto command : sql_commands) {
std::cout << command << std::endl; std::cout << command << std::endl;

View File

@ -82,8 +82,7 @@ namespace usql {
lexer.nextToken(); lexer.nextToken();
} }
cols_def.push_back( cols_def.push_back( ColDefNode(column_name, column_type, column_order++, column_len, column_nullable));
ColDefNode(column_name, column_type, column_order++, column_len, column_nullable));
lexer.skipTokenOptional(TokenType::comma); lexer.skipTokenOptional(TokenType::comma);
@ -99,7 +98,7 @@ namespace usql {
std::unique_ptr<Node> Parser::parse_insert_into_table() { std::unique_ptr<Node> Parser::parse_insert_into_table() {
std::vector<Node> exec_code{}; std::vector<Node> exec_code{};
std::vector<ColNameNode> cols_names{}; std::vector<ColNameNode> cols_names{};
std::vector<ColValueNode> cols_values{}; std::vector<std::unique_ptr<Node>> cols_values{};
lexer.skipToken(TokenType::keyword_insert); lexer.skipToken(TokenType::keyword_insert);
lexer.skipToken(TokenType::keyword_into); lexer.skipToken(TokenType::keyword_into);
@ -123,15 +122,44 @@ namespace usql {
// column values // column values
lexer.skipToken(TokenType::open_paren); lexer.skipToken(TokenType::open_paren);
do { do {
cols_values.push_back(lexer.consumeCurrentToken().token_string); // cols_values.push_back(lexer.consumeCurrentToken().token_string);
auto col_value = parse_value();
cols_values.push_back(std::move(col_value));
lexer.skipTokenOptional(TokenType::comma); lexer.skipTokenOptional(TokenType::comma);
} while (lexer.tokenType() != TokenType::close_paren); } while (lexer.tokenType() != TokenType::close_paren);
lexer.skipToken(TokenType::close_paren); lexer.skipToken(TokenType::close_paren);
return std::make_unique<InsertIntoTableNode>(table_name, cols_names, cols_values); return std::make_unique<InsertIntoTableNode>(table_name, cols_names, std::move(cols_values));
} }
std::unique_ptr<Node> Parser::parse_value() {
if (lexer.tokenType() == TokenType::int_number) {
return std::make_unique<IntValueNode>(std::stoi(lexer.consumeCurrentToken().token_string));
}
if (lexer.tokenType() == TokenType::double_number) {
return std::make_unique<FloatValueNode>(std::stof(lexer.consumeCurrentToken().token_string));
}
if (lexer.tokenType() == TokenType::string_literal) {
if (lexer.nextTokenType() != TokenType::open_paren) {
return std::make_unique<StringValueNode>(lexer.consumeCurrentToken().token_string);
} else {
// function
std::string func_name = lexer.consumeCurrentToken().token_string;
std::vector<std::unique_ptr<Node>> pars;
lexer.skipToken(TokenType::open_paren);
while (lexer.tokenType() != TokenType::close_paren) { // TODO handle errors
auto par = parse_value();
lexer.skipTokenOptional(TokenType::comma);
}
lexer.skipToken(TokenType::close_paren);
return std::make_unique<FunctionNode>(func_name, std::move(pars));
}
}
throw Exception("Syntax error");
}
std::unique_ptr<Node> Parser::parse_select_from_table() { std::unique_ptr<Node> Parser::parse_select_from_table() {
std::vector<ColNameNode> cols_names{}; std::vector<ColNameNode> cols_names{};

View File

@ -32,6 +32,7 @@ namespace usql {
load_table, load_table,
column_name, column_name,
column_value, column_value,
function,
column_def, column_def,
error error
}; };
@ -49,13 +50,6 @@ namespace usql {
Node(NodeType::column_name), name(col_name) {} Node(NodeType::column_name), name(col_name) {}
}; };
struct ColValueNode : Node {
std::string value;
ColValueNode(const std::string col_value) :
Node(NodeType::column_value), value(col_value) {}
};
// TODO add order in row // TODO add order in row
struct ColDefNode : Node { struct ColDefNode : Node {
std::string name; std::string name;
@ -69,6 +63,20 @@ namespace usql {
null(nullable) {} null(nullable) {}
}; };
struct ColValueNode : Node {
std::string value;
ColValueNode(const std::string col_value) :
Node(NodeType::column_value), value(col_value) {}
};
struct FunctionNode : Node {
std::string function;
std::vector<std::unique_ptr<Node>> params;
FunctionNode(const std::string func_name, std::vector<std::unique_ptr<Node>> pars) :
Node(NodeType::function), function(func_name), params(std::move(pars)) {}
};
struct TrueNode : Node { struct TrueNode : Node {
TrueNode() : Node(NodeType::true_node) {} TrueNode() : Node(NodeType::true_node) {}
@ -193,10 +201,10 @@ namespace usql {
struct InsertIntoTableNode : Node { struct InsertIntoTableNode : Node {
std::string table_name; std::string table_name;
std::vector<ColNameNode> cols_names; std::vector<ColNameNode> cols_names;
std::vector<ColValueNode> cols_values; std::vector<std::unique_ptr<Node>> cols_values;
InsertIntoTableNode(const std::string name, std::vector<ColNameNode> names, std::vector<ColValueNode> values) : InsertIntoTableNode(const std::string name, std::vector<ColNameNode> names, std::vector<std::unique_ptr<Node>> values) :
Node(NodeType::insert_into), table_name(name), cols_names(names), cols_values(values) {} Node(NodeType::insert_into), table_name(name), cols_names(names), cols_values(std::move(values)) {}
}; };
struct SelectFromTableNode : Node { struct SelectFromTableNode : Node {
@ -252,6 +260,8 @@ namespace usql {
std::unique_ptr<Node> parse_insert_into_table(); std::unique_ptr<Node> parse_insert_into_table();
std::unique_ptr<Node> parse_value();
std::unique_ptr<Node> parse_select_from_table(); std::unique_ptr<Node> parse_select_from_table();
std::unique_ptr<Node> parse_delete_from_table(); std::unique_ptr<Node> parse_delete_from_table();

View File

@ -15,7 +15,7 @@ namespace usql {
ColDefNode get_column_def(const std::string &col_name); ColDefNode get_column_def(const std::string &col_name);
int columns_count() { return m_col_defs.size(); }; int columns_count() const { return m_col_defs.size(); };
Row createEmptyRow(); // TODO this means unnecessary copying Row createEmptyRow(); // TODO this means unnecessary copying
void addRow(const Row &row); void addRow(const Row &row);

827
usql.cpp
View File

@ -7,415 +7,422 @@
namespace usql { namespace usql {
std::unique_ptr<Table> uSQL::execute(const std::string &command) { std::unique_ptr<Table> USql::execute(const std::string &command) {
auto node = m_parser.parse(command); auto node = m_parser.parse(command);
return execute(*node); return execute(*node);
} }
std::unique_ptr<Table> USql::execute(Node &node) {
std::unique_ptr<Table> uSQL::execute(Node &node) { // TODO optimize execution nodes here
// TODO optimize execution nodes here switch (node.node_type) {
switch (node.node_type) { case NodeType::create_table:
case NodeType::create_table: return execute_create_table(static_cast<CreateTableNode &>(node));
return execute_create_table(static_cast<CreateTableNode &>(node)); case NodeType::insert_into:
case NodeType::insert_into: return execute_insert_into_table(static_cast<InsertIntoTableNode &>(node));
return execute_insert_into_table(static_cast<InsertIntoTableNode &>(node)); case NodeType::select_from:
case NodeType::select_from: return execute_select(static_cast<SelectFromTableNode &>(node));
return execute_select(static_cast<SelectFromTableNode &>(node)); case NodeType::delete_from:
case NodeType::delete_from: return execute_delete(static_cast<DeleteFromTableNode &>(node));
return execute_delete(static_cast<DeleteFromTableNode &>(node)); case NodeType::update_table:
case NodeType::update_table: return execute_update(static_cast<UpdateTableNode &>(node));
return execute_update(static_cast<UpdateTableNode &>(node)); case NodeType::load_table:
case NodeType::load_table: return execute_load(static_cast<LoadIntoTableNode &>(node));
return execute_load(static_cast<LoadIntoTableNode &>(node)); default:
default: return create_stmt_result_table(-1, "unknown statement");
return create_stmt_result_table(-1, "unknown statement"); }
} }
}
std::unique_ptr<Table> USql::execute_create_table(CreateTableNode &node) {
std::unique_ptr<Table> uSQL::execute_create_table(CreateTableNode &node) { // TODO check table does not exists
// TODO check table does not exists Table table{node.table_name, node.cols_defs};
Table table{node.table_name, node.cols_defs}; m_tables.push_back(table);
m_tables.push_back(table);
return create_stmt_result_table(0, "table created");
return create_stmt_result_table(0, "table created"); }
}
std::unique_ptr<Table> USql::execute_insert_into_table(InsertIntoTableNode &node) {
std::unique_ptr<Table> uSQL::execute_insert_into_table(InsertIntoTableNode &node) { // TODO check column names.size = values.size
// TODO check column names.size = values.size
// find table
// find table Table *table_def = find_table(node.table_name);
Table *table_def = find_table(node.table_name);
// prepare empty new_row
// prepare empty new_row Row new_row = table_def->createEmptyRow();
Row new_row = table_def->createEmptyRow();
// copy values
// copy values for (size_t i = 0; i < node.cols_names.size(); i++) {
for (size_t i = 0; i < node.cols_names.size(); i++) { ColDefNode col_def = table_def->get_column_def(node.cols_names[i].name);
ColDefNode col_def = table_def->get_column_def(node.cols_names[i].name);
// TODO validate value
// TODO validate value auto value = evalValueNode(node.cols_values[i].get());
if (col_def.type == ColumnType::integer_type) { if (col_def.type == ColumnType::integer_type) {
new_row.setColumnValue(col_def.order, std::stoi(node.cols_values[i].value)); new_row.setColumnValue(col_def.order, value->getIntValue());
} else if (col_def.type == ColumnType::float_type) { } else if (col_def.type == ColumnType::float_type) {
new_row.setColumnValue(col_def.order, std::stof(node.cols_values[i].value)); new_row.setColumnValue(col_def.order, value->getDoubleValue());
} else { } else {
new_row.setColumnValue(col_def.order, node.cols_values[i].value); new_row.setColumnValue(col_def.order, value->getStringValue());
} }
} }
// append new_row // append new_row
table_def->addRow(new_row); table_def->addRow(new_row);
return create_stmt_result_table(0, "insert succeded"); return create_stmt_result_table(0, "insert succeded");
} }
std::unique_ptr<Table> uSQL::execute_select(SelectFromTableNode &node) { std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) {
// TODO create plan for accessing rows // TODO create plan for accessing rows
// find source table // find source table
Table *table = find_table(node.table_name); Table *table = find_table(node.table_name);
// create result table // create result table
std::vector<ColDefNode> result_tbl_col_defs{}; std::vector<ColDefNode> result_tbl_col_defs{};
std::vector<int> source_table_col_index{}; std::vector<int> source_table_col_index{};
int i = 0; // new column order int i = 0; // new column order
for (auto rc : node.cols_names) { for (auto rc : node.cols_names) {
ColDefNode cdef = table->get_column_def(rc.name); ColDefNode cdef = table->get_column_def(rc.name);
source_table_col_index.push_back(cdef.order); source_table_col_index.push_back(cdef.order);
auto col = ColDefNode(rc.name, cdef.type, i, cdef.length, cdef.null); auto col = ColDefNode(rc.name, cdef.type, i, cdef.length, cdef.null);
result_tbl_col_defs.push_back(col); result_tbl_col_defs.push_back(col);
i++; i++;
} }
auto result = std::make_unique<Table>("result", result_tbl_col_defs); auto result = std::make_unique<Table>("result", result_tbl_col_defs);
// execute access plan // execute access plan
for (auto row = begin(table->m_rows); row != end(table->m_rows); ++row) { for (auto row = begin(table->m_rows); row != end(table->m_rows); ++row) {
// eval where for row // eval where for row
if (evalWhere(node.where.get(), table, row)) { if (evalWhere(node.where.get(), table, row)) {
// prepare empty row // prepare empty row
Row new_row = result->createEmptyRow(); Row new_row = result->createEmptyRow();
// copy column values // copy column values
for (auto idx = 0; idx < result->columns_count(); idx++) { for (auto idx = 0; idx < result->columns_count(); idx++) {
auto row_col_index = source_table_col_index[idx]; auto row_col_index = source_table_col_index[idx];
ColValue *col_value = row->ithColumn(row_col_index); ColValue *col_value = row->ithColumn(row_col_index);
if (result_tbl_col_defs[idx].type == ColumnType::integer_type) if (result_tbl_col_defs[idx].type == ColumnType::integer_type)
new_row.setColumnValue(idx, new_row.setColumnValue(idx,
((ColIntegerValue *) col_value)->integerValue()); ((ColIntegerValue *) col_value)->integerValue());
if (result_tbl_col_defs[idx].type == ColumnType::float_type) if (result_tbl_col_defs[idx].type == ColumnType::float_type)
new_row.setColumnValue(idx, col_value->floatValue()); new_row.setColumnValue(idx, col_value->floatValue());
if (result_tbl_col_defs[idx].type == ColumnType::varchar_type) if (result_tbl_col_defs[idx].type == ColumnType::varchar_type)
new_row.setColumnValue(idx, col_value->stringValue()); new_row.setColumnValue(idx, col_value->stringValue());
} }
// add row to result // add row to result
result->m_rows.push_back(new_row); result->m_rows.push_back(new_row);
} }
} }
return std::move(result); return std::move(result);
} }
std::unique_ptr<Table> uSQL::execute_delete(DeleteFromTableNode &node) { std::unique_ptr<Table> USql::execute_delete(DeleteFromTableNode &node) {
// TODO create plan for accessing rows // TODO create plan for accessing rows
// find source table // find source table
Table *table = find_table(node.table_name); Table *table = find_table(node.table_name);
// execute access plan // execute access plan
auto it = table->m_rows.begin(); auto it = table->m_rows.begin();
for (; it != table->m_rows.end();) { for (; it != table->m_rows.end();) {
if (evalWhere(node.where.get(), table, it)) { if (evalWhere(node.where.get(), table, it)) {
// TODO this can be really expensive operation // TODO this can be really expensive operation
it = table->m_rows.erase(it); it = table->m_rows.erase(it);
} else { } else {
++it; ++it;
} }
} }
return create_stmt_result_table(0, "delete succeded"); return create_stmt_result_table(0, "delete succeded");
} }
std::unique_ptr<Table> uSQL::execute_update(UpdateTableNode &node) { std::unique_ptr<Table> USql::execute_update(UpdateTableNode &node) {
// TODO create plan for accessing rows // TODO create plan for accessing rows
// find source table // find source table
Table *table = find_table(node.table_name); Table *table = find_table(node.table_name);
// execute access plan // execute access plan
for (auto row = begin(table->m_rows); row != end(table->m_rows); ++row) { for (auto row = begin(table->m_rows); row != end(table->m_rows); ++row) {
// eval where for row // eval where for row
if (evalWhere(node.where.get(), table, row)) { if (evalWhere(node.where.get(), table, row)) {
int i = 0; int i = 0;
for (auto col : node.cols_names) { for (auto col : node.cols_names) {
// TODO cache it like in select // TODO cache it like in select
ColDefNode cdef = table->get_column_def(col.name); ColDefNode cdef = table->get_column_def(col.name);
std::unique_ptr<ValueNode> new_val = evalArithmetic(cdef.type, std::unique_ptr<ValueNode> new_val = evalArithmetic(cdef.type,
static_cast<ArithmeticalOperatorNode &>(*node.values[i]), static_cast<ArithmeticalOperatorNode &>(*node.values[i]),
table, row); table, row);
if (cdef.type == ColumnType::integer_type) { if (cdef.type == ColumnType::integer_type) {
row->setColumnValue(cdef.order, new_val->getIntValue()); row->setColumnValue(cdef.order, new_val->getIntValue());
} else if (cdef.type == ColumnType::float_type) { } else if (cdef.type == ColumnType::float_type) {
row->setColumnValue(cdef.order, new_val->getDoubleValue()); row->setColumnValue(cdef.order, new_val->getDoubleValue());
} else if (cdef.type == ColumnType::varchar_type) { } else if (cdef.type == ColumnType::varchar_type) {
row->setColumnValue(cdef.order, new_val->getStringValue()); row->setColumnValue(cdef.order, new_val->getStringValue());
} else { } else {
throw Exception("Implement me!"); throw Exception("Implement me!");
} }
i++; i++;
} }
} }
} }
return create_stmt_result_table(0, "delete succeeded"); return create_stmt_result_table(0, "delete succeeded");
} }
std::unique_ptr<Table> uSQL::execute_load(LoadIntoTableNode &node) { std::unique_ptr<Table> USql::execute_load(LoadIntoTableNode &node) {
// find source table // find source table
Table *table_def = find_table(node.table_name); Table *table_def = find_table(node.table_name);
// read data // read data
std::ifstream ifs(node.filename); std::ifstream ifs(node.filename);
std::string content((std::istreambuf_iterator<char>(ifs)), std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>())); (std::istreambuf_iterator<char>()));
CsvReader csvparser{}; CsvReader csvparser{};
auto csv = csvparser.parseCSV(content); auto csv = csvparser.parseCSV(content);
std::vector<ColDefNode> &colDefs = table_def->m_col_defs; std::vector<ColDefNode> &colDefs = table_def->m_col_defs;
for (auto it = csv.begin() + 1; it != csv.end(); ++it) { for (auto it = csv.begin() + 1; it != csv.end(); ++it) {
std::vector<std::string> csv_line = *it; std::vector<std::string> csv_line = *it;
// prepare empty new_row // prepare empty new_row
Row new_row = table_def->createEmptyRow(); Row new_row = table_def->createEmptyRow();
// copy values // copy values
for (size_t i = 0; i < table_def->columns_count(); i++) { for (size_t i = 0; i < table_def->columns_count(); i++) {
ColDefNode col_def = table_def->get_column_def(colDefs[i].name); ColDefNode col_def = table_def->get_column_def(colDefs[i].name);
// TODO validate value // TODO validate value
if (col_def.type == ColumnType::integer_type) { if (col_def.type == ColumnType::integer_type) {
new_row.setColumnValue(col_def.order, std::stoi(csv_line[i])); new_row.setColumnValue(col_def.order, std::stoi(csv_line[i]));
} else if (col_def.type == ColumnType::float_type) { } else if (col_def.type == ColumnType::float_type) {
new_row.setColumnValue(col_def.order, std::stof(csv_line[i])); new_row.setColumnValue(col_def.order, std::stof(csv_line[i]));
} else { } else {
new_row.setColumnValue(col_def.order, csv_line[i]); new_row.setColumnValue(col_def.order, csv_line[i]);
} }
} }
// append new_row // append new_row
table_def->addRow(new_row); table_def->addRow(new_row);
} }
return create_stmt_result_table(0, "load succeeded"); return create_stmt_result_table(0, "load succeeded");
} }
bool uSQL::evalWhere(Node *where, Table *table, bool USql::evalWhere(Node *where, Table *table,
std::vector<Row, std::allocator<Row>>::iterator &row) const { std::vector<Row, std::allocator<Row>>::iterator &row) const {
switch (where->node_type) { // no where clause switch (where->node_type) { // no where clause
case NodeType::true_node: case NodeType::true_node:
return true; return true;
case NodeType::relational_operator: // just one condition case NodeType::relational_operator: // just one condition
return evalRelationalOperator(*((RelationalOperatorNode *) where), table, row); return evalRelationalOperator(*((RelationalOperatorNode *) where), table, row);
case NodeType::logical_operator: case NodeType::logical_operator:
return evalLogicalOperator(*((LogicalOperatorNode *) where), table, row); return evalLogicalOperator(*((LogicalOperatorNode *) where), table, row);
default: default:
throw Exception("Wrong node type"); throw Exception("Wrong node type");
} }
return false; return false;
} }
bool uSQL::evalRelationalOperator(const RelationalOperatorNode &filter, Table *table, bool USql::evalRelationalOperator(const RelationalOperatorNode &filter, Table *table,
std::vector<Row, std::allocator<Row>>::iterator &row) const { std::vector<Row, std::allocator<Row>>::iterator &row) const {
std::unique_ptr<ValueNode> left_value = evalNode(table, row, filter.left.get()); std::unique_ptr<ValueNode> left_value = evalNode(table, row, filter.left.get());
std::unique_ptr<ValueNode> right_value = evalNode(table, row, filter.right.get()); std::unique_ptr<ValueNode> right_value = evalNode(table, row, filter.right.get());
double comparator; double comparator;
if (left_value->node_type == NodeType::int_value && right_value->node_type == NodeType::int_value) { if (left_value->node_type == NodeType::int_value && right_value->node_type == NodeType::int_value) {
comparator = left_value->getIntValue() - right_value->getIntValue(); comparator = left_value->getIntValue() - right_value->getIntValue();
} else if ((left_value->node_type == NodeType::int_value && } else if ((left_value->node_type == NodeType::int_value &&
right_value->node_type == NodeType::float_value) || right_value->node_type == NodeType::float_value) ||
(left_value->node_type == NodeType::float_value && (left_value->node_type == NodeType::float_value &&
right_value->node_type == NodeType::int_value) || right_value->node_type == NodeType::int_value) ||
(left_value->node_type == NodeType::float_value && (left_value->node_type == NodeType::float_value &&
right_value->node_type == NodeType::float_value)) { right_value->node_type == NodeType::float_value)) {
comparator = left_value->getDoubleValue() - right_value->getDoubleValue(); comparator = left_value->getDoubleValue() - right_value->getDoubleValue();
} else if (left_value->node_type == NodeType::string_value || } else if (left_value->node_type == NodeType::string_value ||
right_value->node_type == NodeType::string_value) { right_value->node_type == NodeType::string_value) {
comparator = left_value->getStringValue().compare(right_value->getStringValue()); comparator = left_value->getStringValue().compare(right_value->getStringValue());
} else { } else {
// TODO throw exception // TODO throw exception
} }
switch (filter.op) { switch (filter.op) {
case RelationalOperatorType::equal: case RelationalOperatorType::equal:
return comparator == 0.0; return comparator == 0.0;
case RelationalOperatorType::not_equal: case RelationalOperatorType::not_equal:
return comparator != 0.0; return comparator != 0.0;
case RelationalOperatorType::greater: case RelationalOperatorType::greater:
return comparator > 0.0; return comparator > 0.0;
case RelationalOperatorType::greater_equal: case RelationalOperatorType::greater_equal:
return comparator >= 0.0; return comparator >= 0.0;
case RelationalOperatorType::lesser: case RelationalOperatorType::lesser:
return comparator < 0.0; return comparator < 0.0;
case RelationalOperatorType::lesser_equal: case RelationalOperatorType::lesser_equal:
return comparator <= 0.0; return comparator <= 0.0;
} }
throw Exception("invalid relational operator"); throw Exception("invalid relational operator");
} }
std::unique_ptr<ValueNode> std::unique_ptr<ValueNode>
uSQL::evalNode(Table *table, std::vector<Row, std::allocator<Row>>::iterator &row, Node *node) const { USql::evalNode(Table *table, std::vector<Row, std::allocator<Row>>::iterator &row, Node *node) const {
if (node->node_type == NodeType::database_value) { if (node->node_type == NodeType::database_value) {
DatabaseValueNode *dvl = static_cast<DatabaseValueNode *>(node); DatabaseValueNode *dvl = static_cast<DatabaseValueNode *>(node);
ColDefNode col_def = table->get_column_def( ColDefNode col_def = table->get_column_def(
dvl->col_name); // TODO optimize it to just get this def once dvl->col_name); // TODO optimize it to just get this def once
auto db_value = row->ithColumn(col_def.order); auto db_value = row->ithColumn(col_def.order);
if (col_def.type == ColumnType::integer_type) { if (col_def.type == ColumnType::integer_type) {
return std::make_unique<IntValueNode>(db_value->integerValue()); return std::make_unique<IntValueNode>(db_value->integerValue());
} }
if (col_def.type == ColumnType::float_type) { if (col_def.type == ColumnType::float_type) {
return std::make_unique<FloatValueNode>(db_value->floatValue()); return std::make_unique<FloatValueNode>(db_value->floatValue());
} }
if (col_def.type == ColumnType::varchar_type) { if (col_def.type == ColumnType::varchar_type) {
return std::make_unique<StringValueNode>(db_value->stringValue()); return std::make_unique<StringValueNode>(db_value->stringValue());
} }
} else {
} else if (node->node_type == NodeType::int_value) { return evalValueNode(node);
IntValueNode *ivl = static_cast<IntValueNode *>(node); }
return std::make_unique<IntValueNode>(ivl->value); }
} else if (node->node_type == NodeType::float_value) {
FloatValueNode *ivl = static_cast<FloatValueNode *>(node); std::unique_ptr<ValueNode> USql::evalValueNode(Node *node) const {
return std::make_unique<FloatValueNode>(ivl->value); if (node->node_type == NodeType::int_value) {
IntValueNode *ivl = static_cast<IntValueNode *>(node);
} else if (node->node_type == NodeType::string_value) { return std::make_unique<IntValueNode>(ivl->value);
StringValueNode *ivl = static_cast<StringValueNode *>(node);
return std::make_unique<StringValueNode>(ivl->value); } else if (node->node_type == NodeType::float_value) {
} FloatValueNode *ivl = static_cast<FloatValueNode *>(node);
return std::make_unique<FloatValueNode>(ivl->value);
throw Exception("invalid type");
} } else if (node->node_type == NodeType::string_value) {
StringValueNode *ivl = static_cast<StringValueNode *>(node);
return std::make_unique<StringValueNode>(ivl->value);
bool uSQL::evalLogicalOperator(LogicalOperatorNode &node, Table *pTable, } else if ("function eval" == "xxx") {
std::vector<Row, std::allocator<Row>>::iterator &iter) const {
bool left = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.left), pTable, iter); }
if ((node.op == LogicalOperatorType::and_operator && !left) || throw Exception("invalid type");
(node.op == LogicalOperatorType::or_operator && left)) }
return left;
bool USql::evalLogicalOperator(LogicalOperatorNode &node, Table *pTable,
bool right = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.right), pTable, iter); std::vector<Row, std::allocator<Row>>::iterator &iter) const {
return right; bool left = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.left), pTable, iter);
}
if ((node.op == LogicalOperatorType::and_operator && !left) ||
(node.op == LogicalOperatorType::or_operator && left))
std::unique_ptr<ValueNode> return left;
uSQL::evalArithmetic(ColumnType outType, ArithmeticalOperatorNode &node, Table *table,
std::vector<Row, std::allocator<Row>>::iterator &row) const { bool right = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.right), pTable, iter);
if (node.op == ArithmeticalOperatorType::copy_value) { return right;
return evalNode(table, row, node.left.get()); }
}
std::unique_ptr<ValueNode> left = evalNode(table, row, node.left.get()); std::unique_ptr<ValueNode>
std::unique_ptr<ValueNode> right = evalNode(table, row, node.right.get()); USql::evalArithmetic(ColumnType outType, ArithmeticalOperatorNode &node, Table *table,
std::vector<Row, std::allocator<Row>>::iterator &row) const {
if (outType == ColumnType::float_type) { if (node.op == ArithmeticalOperatorType::copy_value) {
double l = ((ValueNode *) left.get())->getDoubleValue(); return evalNode(table, row, node.left.get());
double r = ((ValueNode *) right.get())->getDoubleValue(); }
switch (node.op) {
case ArithmeticalOperatorType::plus_operator: std::unique_ptr<ValueNode> left = evalNode(table, row, node.left.get());
return std::make_unique<FloatValueNode>(l + r); std::unique_ptr<ValueNode> right = evalNode(table, row, node.right.get());
case ArithmeticalOperatorType::minus_operator:
return std::make_unique<FloatValueNode>(l - r); if (outType == ColumnType::float_type) {
case ArithmeticalOperatorType::multiply_operator: double l = ((ValueNode *) left.get())->getDoubleValue();
return std::make_unique<FloatValueNode>(l * r); double r = ((ValueNode *) right.get())->getDoubleValue();
case ArithmeticalOperatorType::divide_operator: switch (node.op) {
return std::make_unique<FloatValueNode>(l / r); case ArithmeticalOperatorType::plus_operator:
default: return std::make_unique<FloatValueNode>(l + r);
throw Exception("implement me!!"); case ArithmeticalOperatorType::minus_operator:
} return std::make_unique<FloatValueNode>(l - r);
} else if (outType == ColumnType::integer_type) { case ArithmeticalOperatorType::multiply_operator:
int l = ((ValueNode *) left.get())->getIntValue(); return std::make_unique<FloatValueNode>(l * r);
int r = ((ValueNode *) right.get())->getIntValue(); case ArithmeticalOperatorType::divide_operator:
switch (node.op) { return std::make_unique<FloatValueNode>(l / r);
case ArithmeticalOperatorType::plus_operator: default:
return std::make_unique<IntValueNode>(l + r); throw Exception("implement me!!");
case ArithmeticalOperatorType::minus_operator: }
return std::make_unique<IntValueNode>(l - r); } else if (outType == ColumnType::integer_type) {
case ArithmeticalOperatorType::multiply_operator: int l = ((ValueNode *) left.get())->getIntValue();
return std::make_unique<IntValueNode>(l * r); int r = ((ValueNode *) right.get())->getIntValue();
case ArithmeticalOperatorType::divide_operator: switch (node.op) {
return std::make_unique<IntValueNode>(l / r); case ArithmeticalOperatorType::plus_operator:
default: return std::make_unique<IntValueNode>(l + r);
throw Exception("implement me!!"); case ArithmeticalOperatorType::minus_operator:
} return std::make_unique<IntValueNode>(l - r);
case ArithmeticalOperatorType::multiply_operator:
} else if (outType == ColumnType::varchar_type) { return std::make_unique<IntValueNode>(l * r);
std::string l = ((ValueNode *) left.get())->getStringValue(); case ArithmeticalOperatorType::divide_operator:
std::string r = ((ValueNode *) right.get())->getStringValue(); return std::make_unique<IntValueNode>(l / r);
switch (node.op) { default:
case ArithmeticalOperatorType::plus_operator: throw Exception("implement me!!");
return std::make_unique<StringValueNode>(l + r); }
default: } else if (outType == ColumnType::varchar_type) {
throw Exception("implement me!!"); std::string l = ((ValueNode *) left.get())->getStringValue();
} std::string r = ((ValueNode *) right.get())->getStringValue();
} switch (node.op) {
case ArithmeticalOperatorType::plus_operator:
throw Exception("implement me!!"); return std::make_unique<StringValueNode>(l + r);
}
default:
throw Exception("implement me!!");
}
Table *uSQL::find_table(const std::string name) { }
auto name_cmp = [name](const Table& t) { return t.m_name == name; };
auto table_def = std::find_if(begin(m_tables), end(m_tables), name_cmp); throw Exception("implement me!!");
if (table_def != std::end(m_tables)) { }
return table_def.operator->();
} else {
throw Exception("table not found (" + name + ")");
} Table *USql::find_table(const std::string name) {
} auto name_cmp = [name](const 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)) {
std::unique_ptr<Table> uSQL::create_stmt_result_table(int code, std::string text) { return table_def.operator->();
std::vector<ColDefNode> result_tbl_col_defs{}; } else {
result_tbl_col_defs.push_back(ColDefNode("code", ColumnType::integer_type, 0, 1, false)); throw Exception("table not found (" + name + ")");
result_tbl_col_defs.push_back(ColDefNode("desc", ColumnType::varchar_type, 1, 255, false)); }
}
auto table_def = std::make_unique<Table>("result", result_tbl_col_defs);
Row new_row = table_def->createEmptyRow(); std::unique_ptr<Table> USql::create_stmt_result_table(int code, std::string text) {
new_row.setColumnValue(0, code); std::vector<ColDefNode> result_tbl_col_defs{};
new_row.setColumnValue(1, text); result_tbl_col_defs.push_back(ColDefNode("code", ColumnType::integer_type, 0, 1, false));
table_def->addRow(new_row); result_tbl_col_defs.push_back(ColDefNode("desc", ColumnType::varchar_type, 1, 255, false));
return std::move(table_def); auto table_def = std::make_unique<Table>("result", result_tbl_col_defs);
}
Row new_row = table_def->createEmptyRow();
new_row.setColumnValue(0, code);
new_row.setColumnValue(1, text);
table_def->addRow(new_row);
return std::move(table_def);
}
} }

66
usql.h
View File

@ -7,44 +7,54 @@
namespace usql { namespace usql {
class uSQL { class USql {
public: public:
std::unique_ptr<Table> execute(const std::string &command); USql() {};
private: std::unique_ptr<Table> execute(const std::string &command);
std::unique_ptr<Table> execute(Node &node);
std::unique_ptr<Table> execute_create_table(CreateTableNode &node); private:
std::unique_ptr<Table> execute_insert_into_table(InsertIntoTableNode &node); std::unique_ptr<Table> execute(Node &node);
std::unique_ptr<Table> execute_select(SelectFromTableNode &node);
std::unique_ptr<Table> execute_delete(DeleteFromTableNode &node);
std::unique_ptr<Table> execute_update(UpdateTableNode &node);
std::unique_ptr<Table> execute_load(LoadIntoTableNode &node);
Table *find_table(const std::string name); std::unique_ptr<Table> execute_create_table(CreateTableNode &node);
std::unique_ptr<Table> create_stmt_result_table(int code, std::string text);
std::unique_ptr<Table> execute_insert_into_table(InsertIntoTableNode &node);
std::unique_ptr<Table> execute_select(SelectFromTableNode &node);
std::unique_ptr<Table> execute_delete(DeleteFromTableNode &node);
std::unique_ptr<Table> execute_update(UpdateTableNode &node);
std::unique_ptr<Table> execute_load(LoadIntoTableNode &node);
Table *find_table(const std::string name);
std::unique_ptr<Table> create_stmt_result_table(int code, std::string text);
private: private:
bool evalWhere(Node *where, Table *table, bool evalWhere(Node *where, Table *table,
std::vector<Row, std::allocator<Row>>::iterator &row) const; std::vector<Row, std::allocator<Row>>::iterator &row) const;
std::unique_ptr<ValueNode> evalNode(Table *table, std::vector<Row, std::allocator<Row>>::iterator &row, std::unique_ptr<ValueNode> evalNode(Table *table, std::vector<Row, std::allocator<Row>>::iterator &row,
Node *node) const; Node *node) const;
bool evalRelationalOperator(const RelationalOperatorNode &filter, Table *table, std::unique_ptr<ValueNode> evalValueNode(Node *node) const;
std::vector<Row, std::allocator<Row>>::iterator &row) const;
bool evalLogicalOperator(LogicalOperatorNode &node, Table *pTable, bool evalRelationalOperator(const RelationalOperatorNode &filter, Table *table,
std::vector<Row, std::allocator<Row>>::iterator &iter) const; std::vector<Row, std::allocator<Row>>::iterator &row) const;
std::unique_ptr<ValueNode> evalArithmetic(ColumnType outType, ArithmeticalOperatorNode &node, Table *table, bool evalLogicalOperator(LogicalOperatorNode &node, Table *pTable,
std::vector<Row, std::allocator<Row>>::iterator &row) const; std::vector<Row, std::allocator<Row>>::iterator &iter) const;
private: std::unique_ptr<ValueNode> evalArithmetic(ColumnType outType, ArithmeticalOperatorNode &node, Table *table,
Parser m_parser; std::vector<Row, std::allocator<Row>>::iterator &row) const;
std::vector<Table> m_tables;
}; private:
Parser m_parser;
std::vector<Table> m_tables;
};
} }