From 61548888b9a8a80544875fb3fc93c386d60c6fd9 Mon Sep 17 00:00:00 2001 From: VaclavT Date: Mon, 20 Sep 2021 18:19:21 +0200 Subject: [PATCH] order by accepts column names now --- usql.h | 1 + usql_dml.cpp | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/usql.h b/usql.h index 0f84de0..0d910d0 100644 --- a/usql.h +++ b/usql.h @@ -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 &node, Table *table) const; bool check_for_aggregate_only_functions(SelectFromTableNode &node, int result_cols_cnt) const; diff --git a/usql_dml.cpp b/usql_dml.cpp index 56cd32c..54a297f 100644 --- a/usql_dml.cpp +++ b/usql_dml.cpp @@ -30,8 +30,11 @@ std::unique_ptr 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
("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(col.name), col.name}); + node.cols_names->emplace_back(SelectColNode{std::make_unique(col.name), col.name}); } } } +void USql::setup_order_columns(std::vector &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];