Solve the join order approximately using a greedy algorithm.
312555 {
312556
312557
312558
312559 vector<reference<JoinRelationSet>> join_relations;
312562 }
312563 while (join_relations.size() > 1) {
312564
312565
312566
312567
312568
312569 idx_t best_left = 0, best_right = 0;
312570 optional_ptr<DPJoinNode> best_connection;
312571 for (
idx_t i = 0; i < join_relations.size(); i++) {
312572 auto left = join_relations[i];
312573 for (
idx_t j = i + 1; j < join_relations.size(); j++) {
312574 auto right = join_relations[j];
312575
312576 auto connection =
query_graph.GetConnections(left, right);
312577 if (!connection.empty()) {
312578
312579 auto node =
EmitPair(left, right, connection);
312580
312581
312582
312583
312584
312585
312586 if (!best_connection || node.cost < best_connection->cost) {
312587
312588 best_connection = &
EmitPair(left, right, connection);
312589 best_left = i;
312590 best_right = j;
312591 }
312592 }
312593 }
312594 }
312595 if (!best_connection) {
312596
312597
312598 optional_ptr<DPJoinNode> smallest_plans[2];
312599 size_t smallest_index[2];
312600 D_ASSERT(join_relations.size() >= 2);
312601
312602
312603
312604 for (
idx_t i = 0; i < 2; i++) {
312605 optional_ptr<DPJoinNode> current_plan =
plans[join_relations[i]];
312606 smallest_plans[i] = current_plan;
312607 smallest_index[i] = i;
312608 }
312609
312610
312611
312612 for (
idx_t i = 2; i < join_relations.size(); i++) {
312613
312614 optional_ptr<DPJoinNode> current_plan =
plans[join_relations[i]];
312615
312616 for (
idx_t j = 0; j < 2; j++) {
312617 if (!smallest_plans[j] || smallest_plans[j]->cost > current_plan->cost) {
312618 smallest_plans[j] = current_plan;
312619 smallest_index[j] = i;
312620 break;
312621 }
312622 }
312623 }
312624 if (!smallest_plans[0] || !smallest_plans[1]) {
312625 throw InternalException("Internal error in join order optimizer");
312626 }
312627 D_ASSERT(smallest_plans[0] && smallest_plans[1]);
312628 D_ASSERT(smallest_index[0] != smallest_index[1]);
312629 auto &left = smallest_plans[0]->set;
312630 auto &right = smallest_plans[1]->set;
312631
312633
312634 auto connections =
query_graph.GetConnections(left, right);
312635 D_ASSERT(!connections.empty());
312636
312637 best_connection = &
EmitPair(left, right, connections);
312638 best_left = smallest_index[0];
312639 best_right = smallest_index[1];
312640
312641
312642 if (best_left > best_right) {
312643 std::swap(best_left, best_right);
312644 }
312645 }
312646
312647
312648
312649
312650
312651 auto &new_set =
query_graph_manager.set_manager.Union(join_relations.at(best_left).get(),
312652 join_relations.at(best_right).get());
312653 D_ASSERT(best_right > best_left);
312654 join_relations.erase(join_relations.begin() + (int64_t)best_right);
312655 join_relations.erase(join_relations.begin() + (int64_t)best_left);
312656 join_relations.push_back(new_set);
312657 }
312658}