order by accepts column names now

This commit is contained in:
VaclavT 2021-09-20 18:19:21 +02:00
parent c73e082cfd
commit 61548888b9
2 changed files with 20 additions and 3 deletions

1
usql.h
View File

@ -63,6 +63,7 @@ private:
static void execute_offset_limit(OffsetLimitNode &node, Table *result) ;
void expand_asterix_char(SelectFromTableNode &node, Table *table) const;
void setup_order_columns(std::vector<ColOrderNode> &node, Table *table) const;
bool check_for_aggregate_only_functions(SelectFromTableNode &node, int result_cols_cnt) const;

View File

@ -30,8 +30,11 @@ std::unique_ptr<Table> USql::execute_select(SelectFromTableNode &node) {
// check for aggregate function
bool aggregate_funcs = check_for_aggregate_only_functions(node, result_tbl_col_defs.size());
// prepare result table structure
auto result = std::make_unique<Table>("result", result_tbl_col_defs);
// replace possible order by col names to col indexes and validate
setup_order_columns(node.order_by, result.get());
// execute access plan
Row* new_row = nullptr;
@ -101,11 +104,25 @@ void USql::expand_asterix_char(SelectFromTableNode &node, Table *table) const {
node.cols_names->clear();
node.cols_names->reserve(table->columns_count());
for(const auto& col : table->m_col_defs) {
node.cols_names->emplace_back(SelectColNode{std::__1::make_unique<DatabaseValueNode>(col.name), col.name});
node.cols_names->emplace_back(SelectColNode{std::make_unique<DatabaseValueNode>(col.name), col.name});
}
}
}
void USql::setup_order_columns(std::vector<ColOrderNode> &node, Table *table) const {
for (auto& order_node : node) {
if (!order_node.col_name.empty()) {
ColDefNode col_def = table->get_column_def(order_node.col_name);
order_node.col_index = col_def.order;
} else {
order_node.col_index = order_node.col_index - 1; // user counts from 1
}
if (order_node.col_index < 0 || order_node.col_index >= table->columns_count())
throw Exception("unknown column in order by clause (" + order_node.col_name + ")");
}
}
void USql::execute_distinct(SelectFromTableNode &node, Table *result) {
if (!node.distinct) return;
@ -120,8 +137,7 @@ void USql::execute_order_by(SelectFromTableNode &node, Table *table, Table *resu
auto compare_rows = [&node, &result](const Row &a, const Row &b) {
for(const auto& order_by_col_def : node.order_by) {
// TODO validate index
ColDefNode col_def = result->get_column_def(order_by_col_def.col_index - 1);
ColDefNode col_def = result->get_column_def(order_by_col_def.col_index);
ColValue &a_val = a[col_def.order];
ColValue &b_val = b[col_def.order];