1#include "duckdb/optimizer/topn_optimizer.hpp"
2#include "duckdb/planner/operator/logical_order.hpp"
3#include "duckdb/planner/operator/logical_limit.hpp"
4#include "duckdb/planner/operator/logical_top_n.hpp"
5
6using namespace duckdb;
7using namespace std;
8
9unique_ptr<LogicalOperator> TopN::Optimize(unique_ptr<LogicalOperator> op) {
10 if (op->type == LogicalOperatorType::LIMIT && op->children[0]->type == LogicalOperatorType::ORDER_BY) {
11 auto &limit = (LogicalLimit &)*op;
12 auto &order_by = (LogicalOrder &)*(op->children[0]);
13
14 // This optimization doesn't apply when OFFSET is present without LIMIT
15 if (limit.limit != std::numeric_limits<int64_t>::max()) {
16 auto topn = make_unique<LogicalTopN>(move(order_by.orders), limit.limit, limit.offset);
17 topn->AddChild(move(order_by.children[0]));
18 op = move(topn);
19 }
20 } else {
21 for (auto &child : op->children) {
22 child = Optimize(move(child));
23 }
24 }
25 return op;
26}
27