some renamings

This commit is contained in:
VaclavT 2021-07-22 18:32:00 +02:00
parent dec99b823a
commit fc5fd32976
10 changed files with 171 additions and 170 deletions

View File

@ -1,13 +1,11 @@
### TODO ### TODO
- save table command - save table command
- unify using of float and double keywords to double - move csv generation from usql(save_table) to table class
- use long data type for int
- stoi -> stol, stof -> stod
- add exceptions - add exceptions
- class members should have prefix m_ - class members should have prefix m_
- add pipe | token - add pipe | token
- add to_date a to_number functions - add to_date a to_string functions
- add min and max functions, eg aggregate functions - add min and max functions, eg aggregate functions
- add logging - add logging
- add const wherever should be - add const wherever should be

View File

@ -17,21 +17,21 @@ int main(int argc, char *argv[]) {
"insert into a (i, s) values(5, 'five')", "insert into a (i, s) values(5, 'five')",
"insert into a (i, s) values(to_date('20.12.1973', '%d.%m.%Y'), 'six')", "insert into a (i, s) values(to_date('20.12.1973', '%d.%m.%Y'), 'six')",
"save table a into '/tmp/a.csv'", "save table a into '/tmp/a.csv'",
// "select i, s from a where i > 2", "select i, s from a where i > 2",
// "select i, s from a where i = 1", "select i, s from a where i = 1",
// "select i, s from a where s = 'two'", "select i, s from a where s = 'two'",
// "select i, s from a where i <= 3 and s = 'one'", "select i, s from a where i <= 3 and s = 'one'",
// "select i, s from a where i > 0", "select i, s from a where i > 0",
// "delete from a where i = 4", "delete from a where i = 4",
// "select i, s from a where i > 0", "select i, s from a where i > 0",
// "update a set f = 9.99 where i = 3", "update a set f = 9.99 where i = 3",
// "select i, s, f from a where i = 3", "select i, s, f from a where i = 3",
// "update a set s = 'three', f = f + 0.01 where i = 3", "update a set s = 'three', f = f + 0.01 where i = 3",
// "select i, s, f from a where i = 3", "select i, s, f from a where i = 3",
// "create table data (ticker varchar(8), price float null)", "create table data (ticker varchar(8), price float null)",
// "load data from '/Users/vaclavt/Library/Mobile Documents/com~apple~CloudDocs/Development/usql/data.csv')", "load data from '/Users/vaclavt/Library/Mobile Documents/com~apple~CloudDocs/Development/usql/data.csv')",
// "select ticker, price from data", "select ticker, price from data",
// "select i, s, f from a where i < 300", "select i, s, f from a where i < 300",
"create table x as select i, s, f from a where i < 300", "create table x as select i, s, f from a where i < 300",
"select i, s, f from x where i < 300", "select i, s, f from x where i < 300",
"select i, to_string(i, '%d.%m.%Y'), s, f from a where i > 300" "select i, to_string(i, '%d.%m.%Y'), s, f from a where i > 300"

View File

@ -106,9 +106,8 @@ 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<ColNameNode> column_names{};
std::vector<ColNameNode> cols_names{}; std::vector<std::unique_ptr<Node>> column_values{};
std::vector<std::unique_ptr<Node>> cols_values{};
m_lexer.skipToken(TokenType::keyword_insert); m_lexer.skipToken(TokenType::keyword_insert);
m_lexer.skipToken(TokenType::keyword_into); m_lexer.skipToken(TokenType::keyword_into);
@ -121,7 +120,7 @@ namespace usql {
m_lexer.skipToken(TokenType::open_paren); m_lexer.skipToken(TokenType::open_paren);
do { do {
if (m_lexer.tokenType() != TokenType::identifier) { /* TODO handle error */ } if (m_lexer.tokenType() != TokenType::identifier) { /* TODO handle error */ }
cols_names.push_back(m_lexer.consumeCurrentToken().token_string); column_names.push_back(m_lexer.consumeCurrentToken().token_string);
m_lexer.skipTokenOptional(TokenType::comma); m_lexer.skipTokenOptional(TokenType::comma);
} while (m_lexer.tokenType() != TokenType::close_paren); } while (m_lexer.tokenType() != TokenType::close_paren);
@ -132,15 +131,14 @@ namespace usql {
// column values // column values
m_lexer.skipToken(TokenType::open_paren); m_lexer.skipToken(TokenType::open_paren);
do { do {
// cols_values.push_back(m_lexer.consumeCurrentToken().token_string);
auto col_value = parse_value(); auto col_value = parse_value();
cols_values.push_back(std::move(col_value)); column_values.push_back(std::move(col_value));
m_lexer.skipTokenOptional(TokenType::comma); m_lexer.skipTokenOptional(TokenType::comma);
} while (m_lexer.tokenType() != TokenType::close_paren); } while (m_lexer.tokenType() != TokenType::close_paren);
m_lexer.skipToken(TokenType::close_paren); m_lexer.skipToken(TokenType::close_paren);
return std::make_unique<InsertIntoTableNode>(table_name, cols_names, std::move(cols_values)); return std::make_unique<InsertIntoTableNode>(table_name, column_names, std::move(column_values));
} }
std::unique_ptr<Node> Parser::parse_value() { std::unique_ptr<Node> Parser::parse_value() {
@ -148,16 +146,14 @@ std::unique_ptr<Node> Parser::parse_value() {
return std::make_unique<IntValueNode>(std::stoi(m_lexer.consumeCurrentToken().token_string)); return std::make_unique<IntValueNode>(std::stoi(m_lexer.consumeCurrentToken().token_string));
} }
if (m_lexer.tokenType() == TokenType::double_number) { if (m_lexer.tokenType() == TokenType::double_number) {
return std::make_unique<FloatValueNode>(std::stof(m_lexer.consumeCurrentToken().token_string)); return std::make_unique<DoubleValueNode>(std::stof(m_lexer.consumeCurrentToken().token_string));
} }
if (m_lexer.tokenType() == TokenType::string_literal) { if (m_lexer.tokenType() == TokenType::string_literal) {
return std::make_unique<StringValueNode>(m_lexer.consumeCurrentToken().token_string); return std::make_unique<StringValueNode>(m_lexer.consumeCurrentToken().token_string);
} }
if (m_lexer.tokenType() == TokenType::identifier) { if (m_lexer.tokenType() == TokenType::identifier && m_lexer.nextTokenType() == TokenType::open_paren) {
std::string name = m_lexer.consumeCurrentToken().token_string;
// function // function
if (m_lexer.tokenType() == TokenType::open_paren) { std::string function_name = m_lexer.consumeCurrentToken().token_string;
std::vector<std::unique_ptr<Node>> pars; std::vector<std::unique_ptr<Node>> pars;
m_lexer.skipToken(TokenType::open_paren); m_lexer.skipToken(TokenType::open_paren);
@ -166,11 +162,13 @@ std::unique_ptr<Node> Parser::parse_value() {
m_lexer.skipTokenOptional(TokenType::comma); m_lexer.skipTokenOptional(TokenType::comma);
} }
m_lexer.skipToken(TokenType::close_paren); m_lexer.skipToken(TokenType::close_paren);
return std::make_unique<FunctionNode>(name, std::move(pars)); return std::make_unique<FunctionNode>(function_name, std::move(pars));
} else { }
if (m_lexer.tokenType() == TokenType::identifier) {
std::string name = m_lexer.consumeCurrentToken().token_string;
return std::make_unique<ColNameNode>(name); return std::make_unique<ColNameNode>(name);
} }
}
throw Exception("Syntax error"); throw Exception("Syntax error");
} }
@ -178,23 +176,26 @@ std::unique_ptr<Node> Parser::parse_select_from_table() {
auto cols = std::make_unique<std::vector<SelectColNode>>(); auto cols = std::make_unique<std::vector<SelectColNode>>();
m_lexer.skipToken(TokenType::keyword_select); m_lexer.skipToken(TokenType::keyword_select);
int i = 1; int i = 1;
while (m_lexer.tokenType() != TokenType::keyword_from) { while (m_lexer.tokenType() != TokenType::keyword_from) {
auto col_value = parse_value(); auto column_value = parse_value();
std::string alias; std::string column_alias;
if (col_value->node_type == NodeType::column_name) {
alias = ((ColNameNode*) col_value.get())->name; if (column_value->node_type == NodeType::column_name) {
column_alias = ((ColNameNode*) column_value.get())->name;
} else { } else {
alias = "c" + std::to_string(i); column_alias = "c" + std::to_string(i);
i++; i++;
} }
cols->push_back(SelectColNode{std::move(col_value), alias}); cols->push_back(SelectColNode{std::move(column_value), column_alias});
m_lexer.skipTokenOptional(TokenType::comma); m_lexer.skipTokenOptional(TokenType::comma);
} }
m_lexer.skipToken(TokenType::keyword_from); m_lexer.skipToken(TokenType::keyword_from);
std::string table_name = m_lexer.consumeCurrentToken().token_string; std::string table_name = m_lexer.consumeCurrentToken().token_string;
std::unique_ptr<Node> where_node = parse_where_clause(); std::unique_ptr<Node> where_node = parse_where_clause();
@ -320,7 +321,7 @@ std::unique_ptr<Node> Parser::parse_select_from_table() {
case TokenType::int_number: case TokenType::int_number:
return std::make_unique<IntValueNode>(std::stoi(tokenString)); return std::make_unique<IntValueNode>(std::stoi(tokenString));
case TokenType::double_number: case TokenType::double_number:
return std::make_unique<FloatValueNode>(std::stod(tokenString)); return std::make_unique<DoubleValueNode>(std::stod(tokenString));
case TokenType::string_literal: case TokenType::string_literal:
return std::make_unique<StringValueNode>(tokenString); return std::make_unique<StringValueNode>(tokenString);
case TokenType::identifier: case TokenType::identifier:

View File

@ -54,7 +54,7 @@ namespace usql {
std::unique_ptr<Node> value; std::unique_ptr<Node> value;
std::string name; std::string name;
SelectColNode(std::unique_ptr<Node> column, const std::string alias) : SelectColNode(std::unique_ptr<Node> column, const std::string& alias) :
Node(NodeType::column_name), value(std::move(column)), name(alias) {} Node(NodeType::column_name), value(std::move(column)), name(alias) {}
}; };
@ -85,6 +85,7 @@ namespace usql {
struct ValueNode : Node { struct ValueNode : Node {
ValueNode(NodeType type) : Node(type) {} ValueNode(NodeType type) : Node(type) {}
virtual bool isNull() { return false; }
virtual long getIntValue() = 0; virtual long getIntValue() = 0;
virtual double getDoubleValue() = 0; virtual double getDoubleValue() = 0;
virtual std::string getStringValue() = 0; virtual std::string getStringValue() = 0;
@ -97,19 +98,19 @@ namespace usql {
IntValueNode(long value) : ValueNode(NodeType::int_value), value(value) {} IntValueNode(long value) : ValueNode(NodeType::int_value), value(value) {}
long getIntValue() { return value; }; long getIntValue() override { return value; };
double getDoubleValue() { return (double) value; }; double getDoubleValue() override { return (double) value; };
std::string getStringValue() { return std::to_string(value); } std::string getStringValue() override { return std::to_string(value); }
}; };
struct FloatValueNode : ValueNode { struct DoubleValueNode : ValueNode {
double value; double value;
FloatValueNode(double value) : ValueNode(NodeType::float_value), value(value) {} DoubleValueNode(double value) : ValueNode(NodeType::float_value), value(value) {}
long getIntValue() { return (int) value; }; long getIntValue() override { return (long) value; };
double getDoubleValue() { return value; }; double getDoubleValue() override { return value; };
std::string getStringValue() { return std::to_string(value); } std::string getStringValue() override { return std::to_string(value); }
}; };
struct StringValueNode : ValueNode { struct StringValueNode : ValueNode {
@ -117,9 +118,9 @@ namespace usql {
StringValueNode(std::string value) : ValueNode(NodeType::string_value), value(value) {} StringValueNode(std::string value) : ValueNode(NodeType::string_value), value(value) {}
long getIntValue() { return std::stoi(value); }; long getIntValue() override { return std::stoi(value); };
double getDoubleValue() { return std::stod(value); }; double getDoubleValue() override { return std::stod(value); };
std::string getStringValue() { return value; }; std::string getStringValue() override { return value; };
}; };
struct DatabaseValueNode : Node { struct DatabaseValueNode : Node {
@ -185,7 +186,7 @@ namespace usql {
std::string table_name; std::string table_name;
std::vector<ColDefNode> cols_defs; std::vector<ColDefNode> cols_defs;
CreateTableNode(const std::string name, std::vector<ColDefNode> defs) : CreateTableNode(const std::string& name, std::vector<ColDefNode> defs) :
Node(NodeType::create_table), table_name(name), cols_defs(defs) {} Node(NodeType::create_table), table_name(name), cols_defs(defs) {}
}; };
@ -239,7 +240,7 @@ namespace usql {
std::string table_name; std::string table_name;
std::string filename; std::string filename;
SaveTableNode(const std::string name, std::string file) : SaveTableNode(const std::string& name, std::string file) :
Node(NodeType::save_table), table_name(name), filename(file) {} Node(NodeType::save_table), table_name(name), filename(file) {}
}; };
@ -247,7 +248,7 @@ namespace usql {
std::string table_name; std::string table_name;
std::unique_ptr<Node> where; std::unique_ptr<Node> where;
DeleteFromTableNode(const std::string name, std::unique_ptr<Node> where_clause) : DeleteFromTableNode(const std::string& name, std::unique_ptr<Node> where_clause) :
Node(NodeType::delete_from), table_name(name), where(std::move(where_clause)) {} Node(NodeType::delete_from), table_name(name), where(std::move(where_clause)) {}
}; };

12
row.cpp
View File

@ -19,13 +19,13 @@ namespace usql {
for (int i = 0; i < other.m_columns.size(); i++) { for (int i = 0; i < other.m_columns.size(); i++) {
if (ColIntegerValue *other_v = dynamic_cast<ColIntegerValue *>(other.m_columns[i].get())) { if (ColIntegerValue *other_v = dynamic_cast<ColIntegerValue *>(other.m_columns[i].get())) {
setColumnValue(i, other_v->integerValue()); setColumnValue(i, other_v->getIntValue());
} }
if (ColFloatValue *other_v = dynamic_cast<ColFloatValue *>(other.m_columns[i].get())) { if (ColDoubleValue *other_v = dynamic_cast<ColDoubleValue *>(other.m_columns[i].get())) {
setColumnValue(i, other_v->floatValue()); setColumnValue(i, other_v->getDoubleValue());
} }
if (ColStringValue *other_v = dynamic_cast<ColStringValue *>(other.m_columns[i].get())) { if (ColStringValue *other_v = dynamic_cast<ColStringValue *>(other.m_columns[i].get())) {
setColumnValue(i, other_v->stringValue()); setColumnValue(i, other_v->getStringValue());
} }
} }
} }
@ -44,7 +44,7 @@ namespace usql {
} }
void Row::setColumnValue(int col_index, double value) { void Row::setColumnValue(int col_index, double value) {
m_columns[col_index] = std::make_unique<ColFloatValue>(value); m_columns[col_index] = std::make_unique<ColDoubleValue>(value);
} }
void Row::setColumnValue(int col_index, const std::string &value) { void Row::setColumnValue(int col_index, const std::string &value) {
@ -54,7 +54,7 @@ namespace usql {
void Row::print() { void Row::print() {
for (int ci = 0; ci < m_columns.size(); ci++) { for (int ci = 0; ci < m_columns.size(); ci++) {
if (ci > 0) std::cout << ","; if (ci > 0) std::cout << ",";
auto v = m_columns[ci]->stringValue(); auto v = m_columns[ci]->getStringValue();
std::cout << v; std::cout << v;
} }
std::cout << std::endl; std::cout << std::endl;

36
row.h
View File

@ -11,42 +11,42 @@ namespace usql {
struct ColValue { struct ColValue {
virtual bool isNull() { return false; }; virtual bool isNull() { return false; };
virtual long integerValue() { throw Exception("Not supported"); }; virtual long getIntValue() { throw Exception("Not supported"); };
virtual double floatValue() { throw Exception("Not supported"); }; virtual double getDoubleValue() { throw Exception("Not supported"); };
virtual std::string stringValue() { throw Exception("Not supported"); }; virtual std::string getStringValue() { throw Exception("Not supported"); };
}; };
struct ColNullValue : ColValue { struct ColNullValue : ColValue {
virtual bool isNull() { return true; }; virtual bool isNull() { return true; };
virtual std::string stringValue() { return "null"; }; virtual std::string getStringValue() { return "null"; };
}; };
struct ColIntegerValue : ColValue { struct ColIntegerValue : ColValue {
ColIntegerValue(int value) : m_integer(value) {}; ColIntegerValue(long value) : m_integer(value) {};
ColIntegerValue(const ColIntegerValue &other) : m_integer(other.m_integer) {}; ColIntegerValue(const ColIntegerValue &other) : m_integer(other.m_integer) {};
virtual long integerValue() { return m_integer; }; virtual long getIntValue() { return m_integer; };
virtual double floatValue() { return (double) m_integer; }; virtual double getDoubleValue() { return (double) m_integer; };
virtual std::string stringValue() { return std::to_string(m_integer); }; virtual std::string getStringValue() { return std::to_string(m_integer); };
int m_integer; int m_integer;
}; };
struct ColFloatValue : ColValue { struct ColDoubleValue : ColValue {
ColFloatValue(double value) : m_float(value) {}; ColDoubleValue(double value) : m_double(value) {};
ColFloatValue(const ColFloatValue &other) : m_float(other.m_float) {} ColDoubleValue(const ColDoubleValue &other) : m_double(other.m_double) {}
virtual long integerValue() { return (int) m_float; }; virtual long getIntValue() { return (long) m_double; };
virtual double floatValue() { return m_float; }; virtual double getDoubleValue() { return m_double; };
virtual std::string stringValue() { return std::to_string(m_float); }; virtual std::string getStringValue() { return std::to_string(m_double); };
double m_float; double m_double;
}; };
@ -55,9 +55,9 @@ namespace usql {
ColStringValue(const std::string value) : m_string(value) {}; ColStringValue(const std::string value) : m_string(value) {};
ColStringValue(const ColStringValue &other) : m_string(other.m_string) {}; ColStringValue(const ColStringValue &other) : m_string(other.m_string) {};
virtual long integerValue() { return std::stoi(m_string); }; virtual long getIntValue() { return std::stoi(m_string); };
virtual double floatValue() { return std::stod(m_string); }; virtual double getDoubleValue() { return std::stod(m_string); };
virtual std::string stringValue() { return m_string; }; virtual std::string getStringValue() { return m_string; };
std::string m_string; std::string m_string;
}; };

View File

@ -59,11 +59,11 @@ void Table::addCopyOfRow(const Row &row) {
new_row.setColumnNull(i); new_row.setColumnNull(i);
} else { } else {
if (m_col_defs[i].type == ColumnType::integer_type) { if (m_col_defs[i].type == ColumnType::integer_type) {
new_row.setColumnValue(i, row.ithColumn(i)->integerValue()); new_row.setColumnValue(i, row.ithColumn(i)->getIntValue());
} else if (m_col_defs[i].type == ColumnType::float_type) { } else if (m_col_defs[i].type == ColumnType::float_type) {
new_row.setColumnValue(i, row.ithColumn(i)->floatValue()); new_row.setColumnValue(i, row.ithColumn(i)->getDoubleValue());
} else if (m_col_defs[i].type == ColumnType::varchar_type) { } else if (m_col_defs[i].type == ColumnType::varchar_type) {
new_row.setColumnValue(i, row.ithColumn(i)->stringValue()); new_row.setColumnValue(i, row.ithColumn(i)->getStringValue());
} }
} }
} }

View File

@ -10,7 +10,6 @@ namespace usql {
struct Table { struct Table {
Table(const Table &other); Table(const Table &other);
Table(const std::string name, const std::vector<ColDefNode> columns); Table(const std::string name, const std::vector<ColDefNode> columns);
ColDefNode get_column_def(const std::string &col_name); ColDefNode get_column_def(const std::string &col_name);

139
usql.cpp
View File

@ -8,14 +8,8 @@
namespace usql { namespace usql {
USql::USql(){
m_tables.reserve(16); // some initial size, to prevent immediate reallocation
}
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); std::unique_ptr<Node> node = m_parser.parse(command);
return execute(*node); return execute(*node);
} }
@ -56,16 +50,16 @@ std::unique_ptr<Table> USql::execute_create_table(CreateTableNode &node) {
std::unique_ptr<Table> USql::execute_create_table_as_table(CreateTableAsSelectNode &node) { std::unique_ptr<Table> USql::execute_create_table_as_table(CreateTableAsSelectNode &node) {
// TODO check table does not exists // TODO check table does not exists
auto select = execute_select((SelectFromTableNode &) *node.select_table.get()); auto select = execute_select((SelectFromTableNode &) *node.select_table);
// create table // create table
Table new_table{node.table_name, select.get()->m_col_defs}; Table new_table{node.table_name, select->m_col_defs};
m_tables.push_back(new_table); m_tables.push_back(new_table);
// copy rows // copy rows
// must be here, if rows are put into new_table, they are lost during m_tables.push_table // must be here, if rows are put into new_table, they are lost during m_tables.push_table
Table *table = find_table(node.table_name); Table *table = find_table(node.table_name);
for( Row& orig_row : select.get()->m_rows) { for( Row& orig_row : select->m_rows) {
table->addCopyOfRow(orig_row); table->addCopyOfRow(orig_row);
} }
@ -103,42 +97,28 @@ std::unique_ptr<Table> USql::execute_insert_into_table(InsertIntoTableNode &node
// 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 succeeded");
} }
std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) { std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) {
// 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{};
// new column order
for (int i = 0; i < node.cols_names->size(); i++) { for (int i = 0; i < node.cols_names->size(); i++) {
auto column = node.cols_names.get(); auto [ src_tbl_col_index, col_def ] = getColumnDefinition(table, &node.cols_names->operator[](i), i);
std::string new_col_name = column->operator[](i).name;
if (column->operator[](i).value->node_type == NodeType::column_name) { source_table_col_index.push_back(src_tbl_col_index);
ColDefNode cdef = table->get_column_def(new_col_name); result_tbl_col_defs.push_back(col_def);
source_table_col_index.push_back(cdef.order);
auto col = ColDefNode(new_col_name, cdef.type, i, cdef.length, cdef.null);
result_tbl_col_defs.push_back(col);
} else {
// TODO replace this hardcoded values
ColDefNode cdef = ColDefNode{new_col_name, ColumnType::varchar_type, i, 64, true};
source_table_col_index.push_back(-1);
auto col = ColDefNode(new_col_name, cdef.type, i, cdef.length, cdef.null);
result_tbl_col_defs.push_back(col);
}
} }
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
@ -152,9 +132,9 @@ std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) {
if (row_col_index == -1) { if (row_col_index == -1) {
// todo its function TODO col_names zmenit na colValues // todo its function TODO col_names zmenit na colValues
auto evaluated_value = evalValueNode(table, *row, node.cols_names.get()->operator[](idx).value.get()); auto evaluated_value = evalValueNode(table, *row, node.cols_names->operator[](idx).value.get());
ValueNode *col_value = evaluated_value.get(); ValueNode *col_value = evaluated_value.get();
if (true /* !col_value->isNull() */) { // TODO sjednotit nasledujici if (!col_value->isNull()) { // TODO sjednotit nasledujici
if (result_tbl_col_defs[idx].type == ColumnType::integer_type) if (result_tbl_col_defs[idx].type == ColumnType::integer_type)
new_row.setColumnValue(idx, col_value->getIntValue()); new_row.setColumnValue(idx, col_value->getIntValue());
if (result_tbl_col_defs[idx].type == ColumnType::float_type) if (result_tbl_col_defs[idx].type == ColumnType::float_type)
@ -162,17 +142,19 @@ std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) {
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->getStringValue()); new_row.setColumnValue(idx, col_value->getStringValue());
} }
// TODO set to null
} else { } else {
ColValue *col_value = row->ithColumn(row_col_index); ColValue *col_value = row->ithColumn(row_col_index);
if (!col_value->isNull()) { if (!col_value->isNull()) {
if (result_tbl_col_defs[idx].type == ColumnType::integer_type) if (result_tbl_col_defs[idx].type == ColumnType::integer_type)
new_row.setColumnValue(idx, col_value->integerValue()); new_row.setColumnValue(idx, col_value->getIntValue());
if (result_tbl_col_defs[idx].type == ColumnType::float_type) else if (result_tbl_col_defs[idx].type == ColumnType::float_type)
new_row.setColumnValue(idx, col_value->floatValue()); new_row.setColumnValue(idx, col_value->getDoubleValue());
if (result_tbl_col_defs[idx].type == ColumnType::varchar_type) else if (result_tbl_col_defs[idx].type == ColumnType::varchar_type)
new_row.setColumnValue(idx, col_value->stringValue()); new_row.setColumnValue(idx, col_value->getStringValue());
} }
// TODO set to null
} }
} }
@ -184,10 +166,30 @@ std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) {
return std::move(result); return std::move(result);
} }
std::tuple<int, ColDefNode> USql::getColumnDefinition(Table *table, SelectColNode *select_col_node, int col_order ) {
std::string new_col_name = select_col_node->name;
if (select_col_node->value->node_type == NodeType::column_name) {
ColDefNode cdef = table->get_column_def(new_col_name);
return std::make_tuple(cdef.order, cdef);
} else if (select_col_node->value->node_type == NodeType::function) {
auto node = static_cast<FunctionNode *>(select_col_node->value.get());
if (node->function == "to_string") {
ColDefNode cdef = ColDefNode{new_col_name, ColumnType::varchar_type, col_order, 64, true};
return std::make_tuple(-1, cdef);
} else if (node->function == "to_date") {
ColDefNode cdef = ColDefNode{new_col_name, ColumnType::integer_type, col_order, 1, true};
return std::make_tuple(-1, cdef);
}
throw Exception("Unsupported function");
}
throw Exception("Unsupported node type");
}
std::unique_ptr<Table> USql::execute_delete(DeleteFromTableNode &node) { std::unique_ptr<Table> USql::execute_delete(DeleteFromTableNode &node) {
// 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);
@ -202,13 +204,11 @@ std::unique_ptr<Table> USql::execute_delete(DeleteFromTableNode &node) {
} }
} }
return create_stmt_result_table(0, "delete succeded"); return create_stmt_result_table(0, "delete succeeded");
} }
std::unique_ptr<Table> USql::execute_update(UpdateTableNode &node) { std::unique_ptr<Table> USql::execute_update(UpdateTableNode &node) {
// 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);
@ -217,7 +217,7 @@ std::unique_ptr<Table> USql::execute_update(UpdateTableNode &node) {
// 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 (const 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);
@ -298,13 +298,13 @@ std::unique_ptr<Table> USql::execute_save(SaveTableNode &node) {
// rows // rows
for (auto it = table_def->m_rows.begin() + 1; it != table_def->m_rows.end(); ++it) { for (auto it = table_def->m_rows.begin() + 1; it != table_def->m_rows.end(); ++it) {
std::string csv_line = ""; std::string csv_line;
for(int i = 0; i < table_def->m_col_defs.size(); i++) { for(int i = 0; i < table_def->m_col_defs.size(); i++) {
if (i > 0) csv_line += ","; if (i > 0) csv_line += ",";
auto col = it->ithColumn(i); auto col = it->ithColumn(i);
if (!col->isNull()) { if (!col->isNull()) {
csv_line += col->stringValue(); // TODO handle enclosing commas etc csv_line += col->getStringValue(); // TODO handle enclosing commas etc
} }
} }
out_string += "\n"; out_string += "\n";
@ -373,7 +373,7 @@ bool USql::evalRelationalOperator(const RelationalOperatorNode &filter, Table *t
} }
std::unique_ptr<ValueNode> USql::evalValueNode(Table *table, Row &row, Node *node) const { std::unique_ptr<ValueNode> USql::evalValueNode(Table *table, Row &row, Node *node) {
if (node->node_type == NodeType::database_value || node->node_type == NodeType::column_name) { // TODO sjednotit if (node->node_type == NodeType::database_value || node->node_type == NodeType::column_name) { // TODO sjednotit
return evalDatabaseValueNode(table, row, node); return evalDatabaseValueNode(table, row, node);
@ -387,35 +387,35 @@ std::unique_ptr<ValueNode> USql::evalValueNode(Table *table, Row &row, Node *nod
} }
std::unique_ptr<ValueNode> USql::evalDatabaseValueNode(Table *table, Row &row, Node *node) const { std::unique_ptr<ValueNode> USql::evalDatabaseValueNode(Table *table, Row &row, Node *node) {
DatabaseValueNode *dvl = static_cast<DatabaseValueNode *>(node); auto *dvl = static_cast<DatabaseValueNode *>(node);
ColDefNode col_def = table->get_column_def( dvl->col_name); // TODO optimize it to just get this def once ColDefNode col_def = table->get_column_def( 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::__1::make_unique<IntValueNode>(db_value->integerValue()); return std::__1::make_unique<IntValueNode>(db_value->getIntValue());
} }
if (col_def.type == ColumnType::float_type) { if (col_def.type == ColumnType::float_type) {
return std::__1::make_unique<FloatValueNode>(db_value->floatValue()); return std::__1::make_unique<DoubleValueNode>(db_value->getDoubleValue());
} }
if (col_def.type == ColumnType::varchar_type) { if (col_def.type == ColumnType::varchar_type) {
return std::__1::make_unique<StringValueNode>(db_value->stringValue()); return std::__1::make_unique<StringValueNode>(db_value->getStringValue());
} }
throw Exception("unknown database value type"); throw Exception("unknown database value type");
} }
std::unique_ptr<ValueNode> USql::evalLiteralValueNode(Table *table, Row &row, Node *node) const { std::unique_ptr<ValueNode> USql::evalLiteralValueNode(Table *table, Row &row, Node *node) {
if (node->node_type == NodeType::int_value) { if (node->node_type == NodeType::int_value) {
IntValueNode *ivl = static_cast<IntValueNode *>(node); auto *ivl = static_cast<IntValueNode *>(node);
return std::make_unique<IntValueNode>(ivl->value); return std::make_unique<IntValueNode>(ivl->value);
} else if (node->node_type == NodeType::float_value) { } else if (node->node_type == NodeType::float_value) {
FloatValueNode *ivl = static_cast<FloatValueNode *>(node); auto *ivl = static_cast<DoubleValueNode *>(node);
return std::make_unique<FloatValueNode>(ivl->value); return std::make_unique<DoubleValueNode>(ivl->value);
} else if (node->node_type == NodeType::string_value) { } else if (node->node_type == NodeType::string_value) {
StringValueNode *ivl = static_cast<StringValueNode *>(node); auto *ivl = static_cast<StringValueNode *>(node);
return std::make_unique<StringValueNode>(ivl->value); return std::make_unique<StringValueNode>(ivl->value);
} }
@ -424,12 +424,12 @@ std::unique_ptr<ValueNode> USql::evalLiteralValueNode(Table *table, Row &row, No
} }
std::unique_ptr<ValueNode> USql::evalFunctionValueNode(Table *table, Row &row, Node *node) const { std::unique_ptr<ValueNode> USql::evalFunctionValueNode(Table *table, Row &row, Node *node) {
FunctionNode *fnc = static_cast<FunctionNode *>(node); auto *fnc = static_cast<FunctionNode *>(node);
std::vector<std::unique_ptr<ValueNode>> evaluatedPars; std::vector<std::unique_ptr<ValueNode>> evaluatedPars;
for(int i = 0; i < fnc->params.size(); i++) { for(auto & param : fnc->params) {
evaluatedPars.push_back(evalValueNode(table, row, fnc->params[i].get())); evaluatedPars.push_back(evalValueNode(table, row, param.get()));
} }
// TODO use some enum // TODO use some enum
@ -464,8 +464,7 @@ std::unique_ptr<ValueNode> USql::evalFunctionValueNode(Table *table, Row &row, N
bool USql::evalLogicalOperator(LogicalOperatorNode &node, Table *pTable, Row &row) const { bool USql::evalLogicalOperator(LogicalOperatorNode &node, Table *pTable, Row &row) const {
bool left = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.left), pTable, row); bool left = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.left), pTable, row);
if ((node.op == LogicalOperatorType::and_operator && !left) || if ((node.op == LogicalOperatorType::and_operator && !left) || (node.op == LogicalOperatorType::or_operator && left))
(node.op == LogicalOperatorType::or_operator && left))
return left; return left;
bool right = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.right), pTable, row); bool right = evalRelationalOperator(static_cast<const RelationalOperatorNode &>(*node.right), pTable, row);
@ -486,19 +485,19 @@ std::unique_ptr<ValueNode> USql::evalArithmeticOperator(ColumnType outType, Arit
double r = ((ValueNode *) right.get())->getDoubleValue(); double r = ((ValueNode *) right.get())->getDoubleValue();
switch (node.op) { switch (node.op) {
case ArithmeticalOperatorType::plus_operator: case ArithmeticalOperatorType::plus_operator:
return std::make_unique<FloatValueNode>(l + r); return std::make_unique<DoubleValueNode>(l + r);
case ArithmeticalOperatorType::minus_operator: case ArithmeticalOperatorType::minus_operator:
return std::make_unique<FloatValueNode>(l - r); return std::make_unique<DoubleValueNode>(l - r);
case ArithmeticalOperatorType::multiply_operator: case ArithmeticalOperatorType::multiply_operator:
return std::make_unique<FloatValueNode>(l * r); return std::make_unique<DoubleValueNode>(l * r);
case ArithmeticalOperatorType::divide_operator: case ArithmeticalOperatorType::divide_operator:
return std::make_unique<FloatValueNode>(l / r); return std::make_unique<DoubleValueNode>(l / r);
default: default:
throw Exception("implement me!!"); throw Exception("implement me!!");
} }
} else if (outType == ColumnType::integer_type) { } else if (outType == ColumnType::integer_type) {
int l = ((ValueNode *) left.get())->getIntValue(); long l = ((ValueNode *) left.get())->getIntValue();
int r = ((ValueNode *) right.get())->getIntValue(); long r = ((ValueNode *) right.get())->getIntValue();
switch (node.op) { switch (node.op) {
case ArithmeticalOperatorType::plus_operator: case ArithmeticalOperatorType::plus_operator:
return std::make_unique<IntValueNode>(l + r); return std::make_unique<IntValueNode>(l + r);
@ -527,7 +526,7 @@ std::unique_ptr<ValueNode> USql::evalArithmeticOperator(ColumnType outType, Arit
} }
std::unique_ptr<Table> USql::create_stmt_result_table(long code, std::string text) { std::unique_ptr<Table> USql::create_stmt_result_table(long code, const std::string& text) {
std::vector<ColDefNode> result_tbl_col_defs{}; std::vector<ColDefNode> result_tbl_col_defs{};
result_tbl_col_defs.push_back(ColDefNode("code", ColumnType::integer_type, 0, 1, false)); result_tbl_col_defs.push_back(ColDefNode("code", ColumnType::integer_type, 0, 1, false));
result_tbl_col_defs.push_back(ColDefNode("desc", ColumnType::varchar_type, 1, 255, false)); result_tbl_col_defs.push_back(ColDefNode("desc", ColumnType::varchar_type, 1, 255, false));
@ -544,7 +543,7 @@ std::unique_ptr<Table> USql::create_stmt_result_table(long code, std::string tex
Table *USql::find_table(const std::string name) { Table *USql::find_table(const std::string &name) {
auto name_cmp = [name](const Table& t) { return t.m_name == 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); auto table_def = std::find_if(begin(m_tables), end(m_tables), name_cmp);
if (table_def != std::end(m_tables)) { if (table_def != std::end(m_tables)) {

19
usql.h
View File

@ -4,13 +4,15 @@
#include "table.h" #include "table.h"
#include <string> #include <string>
#include <list>
namespace usql { namespace usql {
class USql { class USql {
public: public:
USql(); USql() = default;
std::unique_ptr<Table> execute(const std::string &command); std::unique_ptr<Table> execute(const std::string &command);
@ -30,10 +32,10 @@ private:
private: private:
bool evalWhere(Node *where, Table *table, Row &row) const; bool evalWhere(Node *where, Table *table, Row &row) const;
std::unique_ptr<ValueNode> evalValueNode(Table *table, Row &row, Node *node) const; static std::unique_ptr<ValueNode> evalValueNode(Table *table, Row &row, Node *node);
std::unique_ptr<ValueNode> evalDatabaseValueNode(Table *table, Row &row, Node *node) const; static std::unique_ptr<ValueNode> evalDatabaseValueNode(Table *table, Row &row, Node *node);
std::unique_ptr<ValueNode> evalLiteralValueNode(Table *table, Row &row, Node *node) const; static std::unique_ptr<ValueNode> evalLiteralValueNode(Table *table, Row &row, Node *node);
std::unique_ptr<ValueNode> evalFunctionValueNode(Table *table, Row &row, Node *node) const; static std::unique_ptr<ValueNode> evalFunctionValueNode(Table *table, Row &row, Node *node);
bool evalRelationalOperator(const RelationalOperatorNode &filter, Table *table, Row &row) const; bool evalRelationalOperator(const RelationalOperatorNode &filter, Table *table, Row &row) const;
@ -41,13 +43,14 @@ private:
std::unique_ptr<ValueNode> evalArithmeticOperator(ColumnType outType, ArithmeticalOperatorNode &node, Table *table, Row &row) const; std::unique_ptr<ValueNode> evalArithmeticOperator(ColumnType outType, ArithmeticalOperatorNode &node, Table *table, Row &row) const;
std::unique_ptr<Table> create_stmt_result_table(long code, std::string text); static std::unique_ptr<Table> create_stmt_result_table(long code, const std::string& text);
Table *find_table(const std::string name); static std::tuple<int, ColDefNode> getColumnDefinition(Table *table, SelectColNode *select_col_node, int col_order) ;
Table *find_table(const std::string &name);
private: private:
Parser m_parser; Parser m_parser;
std::vector<Table> m_tables; std::list<Table> m_tables;
}; };
} // namespace } // namespace