| 38 | } |
| 39 | |
| 40 | InputOrderInfoPtr ReadInOrderOptimizer::getInputOrder(const StorageMetadataPtr & metadata_snapshot, ContextPtr context) const |
| 41 | { |
| 42 | Names sorting_key_columns = metadata_snapshot->getSortingKeyColumns(); |
| 43 | if (!metadata_snapshot->hasSortingKey()) |
| 44 | return {}; |
| 45 | |
| 46 | SortDescription order_key_prefix_descr; |
| 47 | int read_direction = required_sort_description.at(0).direction; |
| 48 | |
| 49 | size_t prefix_size = std::min(required_sort_description.size(), sorting_key_columns.size()); |
| 50 | auto aliased_columns = metadata_snapshot->getColumns().getAliases(); |
| 51 | |
| 52 | for (size_t i = 0; i < prefix_size; ++i) |
| 53 | { |
| 54 | if (forbidden_columns.count(required_sort_description[i].column_name)) |
| 55 | break; |
| 56 | |
| 57 | /// Optimize in case of exact match with order key element |
| 58 | /// or in some simple cases when order key element is wrapped into monotonic function. |
| 59 | auto apply_order_judge = [&] (const ExpressionActions::Actions & actions, const String & sort_column) |
| 60 | { |
| 61 | /// If required order depend on collation, it cannot be matched with primary key order. |
| 62 | /// Because primary keys cannot have collations. |
| 63 | if (required_sort_description[i].collator) |
| 64 | return false; |
| 65 | |
| 66 | int current_direction = required_sort_description[i].direction; |
| 67 | /// For the path: order by (sort_column, ...) |
| 68 | if (sort_column == sorting_key_columns[i] && current_direction == read_direction) |
| 69 | { |
| 70 | return true; |
| 71 | } |
| 72 | /// For the path: order by (function(sort_column), ...) |
| 73 | /// Allow only one simple monotonic functions with one argument |
| 74 | /// Why not allow multi monotonic functions? |
| 75 | else |
| 76 | { |
| 77 | bool found_function = false; |
| 78 | |
| 79 | for (const auto & action : actions) |
| 80 | { |
| 81 | if (action.node->type != ActionsDAG::ActionType::FUNCTION) |
| 82 | { |
| 83 | continue; |
| 84 | } |
| 85 | |
| 86 | if (found_function) |
| 87 | { |
| 88 | current_direction = 0; |
| 89 | break; |
| 90 | } |
| 91 | else |
| 92 | found_function = true; |
| 93 | |
| 94 | if (action.node->children.size() != 1 || action.node->children.at(0)->result_name != sorting_key_columns[i]) |
| 95 | { |
| 96 | current_direction = 0; |
| 97 | break; |
no test coverage detected