ob_log_plan.cpp 606.8 KB
Newer Older
O
oceanbase-admin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/**
 * Copyright (c) 2021 OceanBase
 * OceanBase CE is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#define USING_LOG_PREFIX SQL_OPT
#include <stdint.h>
W
wangzelin.wzl 已提交
15
#include "lib/utility/utility.h"
O
oceanbase-admin 已提交
16 17 18 19
#include "lib/container/ob_array.h"
#include "lib/container/ob_array_iterator.h"
#include "lib/hash/ob_hashset.h"
#include "share/ob_server_locality_cache.h"
O
obdev 已提交
20 21
#include "share/stat/ob_opt_column_stat_cache.h"
#include "share/stat/ob_opt_stat_manager.h"
O
oceanbase-admin 已提交
22 23 24 25 26 27 28 29 30
#include "sql/resolver/expr/ob_raw_expr_util.h"
#include "sql/ob_sql_utils.h"
#include "sql/ob_sql_trans_control.h"
#include "sql/optimizer/ob_log_plan.h"
#include "sql/optimizer/ob_log_table_scan.h"
#include "sql/optimizer/ob_log_join.h"
#include "sql/optimizer/ob_intersect_route_policy.h"
#include "sql/optimizer/ob_join_order.h"
#include "sql/optimizer/ob_log_plan_factory.h"
W
wangzelin.wzl 已提交
31
#include "sql/optimizer/ob_log_join_filter.h"
O
oceanbase-admin 已提交
32 33
#include "sql/optimizer/ob_log_sort.h"
#include "sql/optimizer/ob_log_group_by.h"
O
obdev 已提交
34
#include "sql/optimizer/ob_log_window_function.h"
O
oceanbase-admin 已提交
35
#include "sql/optimizer/ob_log_distinct.h"
W
wangzelin.wzl 已提交
36
#include "sql/optimizer/ob_log_window_function.h"
O
oceanbase-admin 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49
#include "sql/optimizer/ob_log_limit.h"
#include "sql/optimizer/ob_log_sequence.h"
#include "sql/optimizer/ob_log_set.h"
#include "sql/optimizer/ob_log_subplan_scan.h"
#include "sql/optimizer/ob_log_subplan_filter.h"
#include "sql/optimizer/ob_log_material.h"
#include "sql/optimizer/ob_log_select_into.h"
#include "sql/optimizer/ob_log_count.h"
#include "sql/optimizer/ob_opt_est_cost.h"
#include "sql/optimizer/ob_optimizer.h"
#include "sql/optimizer/ob_log_del_upd.h"
#include "sql/optimizer/ob_log_expr_values.h"
#include "sql/optimizer/ob_log_function_table.h"
O
obdev 已提交
50
#include "sql/optimizer/ob_log_json_table.h"
O
oceanbase-admin 已提交
51 52 53 54 55 56 57 58
#include "sql/rewrite/ob_transform_utils.h"
#include "sql/optimizer/ob_log_exchange.h"
#include "sql/optimizer/ob_log_values.h"
#include "sql/optimizer/ob_log_temp_table_insert.h"
#include "sql/optimizer/ob_log_temp_table_access.h"
#include "sql/optimizer/ob_log_temp_table_transformation.h"
#include "sql/optimizer/ob_px_resource_analyzer.h"
#include "common/ob_smart_call.h"
W
wangzelin.wzl 已提交
59 60 61 62 63 64
#include "observer/omt/ob_tenant_config_mgr.h"
#include "sql/optimizer/ob_log_err_log.h"
#include "sql/optimizer/ob_log_update.h"
#include "sql/optimizer/ob_log_insert.h"
#include "sql/optimizer/ob_log_delete.h"
#include "sql/optimizer/ob_log_del_upd.h"
O
obdev 已提交
65 66
#include "sql/optimizer/ob_log_insert_all.h"
#include "sql/optimizer/ob_log_merge.h"
W
wangzelin.wzl 已提交
67 68 69 70 71 72
#include "sql/optimizer/ob_log_stat_collector.h"
#include "lib/utility/ob_tracepoint.h"
#include "sql/optimizer/ob_update_log_plan.h"
#include "sql/resolver/dml/ob_sql_hint.h"
#include "sql/optimizer/ob_log_for_update.h"
#include "sql/rewrite/ob_transform_utils.h"
O
obdev 已提交
73
#include "sql/ob_optimizer_trace_impl.h"
O
oceanbase-admin 已提交
74 75 76 77 78 79 80 81

using namespace oceanbase;
using namespace sql;
using namespace oceanbase::common;
using namespace oceanbase::share;
using namespace oceanbase::transaction;
using namespace oceanbase::storage;
using namespace oceanbase::sql::log_op_def;
W
wangzelin.wzl 已提交
82
using share::schema::ObTableSchema;
O
oceanbase-admin 已提交
83 84 85 86
using share::schema::ObColumnSchemaV2;
using share::schema::ObSchemaGetterGuard;

#include "sql/optimizer/ob_join_property.map"
W
wangzelin.wzl 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
static const char *ExplainColumnName[] =
{
  "ID",
  "OPERATOR",
  "NAME",
  "EST. ROWS",
  "COST"
};

ObLogPlan::ObLogPlan(ObOptimizerContext &ctx, const ObDMLStmt *stmt)
  : optimizer_context_(ctx),
    allocator_(ctx.get_allocator()),
    stmt_(stmt),
    log_op_factory_(allocator_),
    candidates_(),
    group_replaced_exprs_(),
O
obdev 已提交
103
    window_function_replaced_exprs_(),
W
wangzelin.wzl 已提交
104 105 106 107 108
    query_ref_(NULL),
    root_(NULL),
    sql_text_(),
    hash_value_(0),
    subplan_infos_(),
O
obdev 已提交
109
    outline_print_flags_(0),
W
wangzelin.wzl 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    onetime_exprs_(),
    join_order_(NULL),
    id_order_map_allocer_(RELORDER_HASHBUCKET_SIZE,
                          ObWrapperAllocator(&allocator_)),
    bucket_allocator_wrapper_(&allocator_),
    relid_joinorder_map_(),
    join_path_set_allocer_(JOINPATH_SET_HASHBUCKET_SIZE,
                           ObWrapperAllocator(&allocator_)),
    join_path_set_(),
    recycled_join_paths_(),
    pred_sels_(),
    multi_stmt_rowkey_pos_(),
    equal_sets_(),
    max_op_id_(OB_INVALID_ID),
    is_subplan_scan_(false),
O
obdev 已提交
125
    is_parent_set_distinct_(false),
W
wangzelin.wzl 已提交
126 127 128 129 130 131 132
    temp_table_info_(NULL),
    const_exprs_(),
    hash_dist_info_(),
    insert_stmt_(NULL),
    basic_table_metas_(),
    update_table_metas_(),
    selectivity_ctx_(ctx, this, stmt),
O
obdev 已提交
133 134
    alloc_sfu_list_(),
    onetime_copier_(NULL)
W
wangzelin.wzl 已提交
135 136
{
}
O
oceanbase-admin 已提交
137 138 139 140 141 142 143 144

ObLogPlan::~ObLogPlan()
{
  if (NULL != join_order_) {
    join_order_->~ObJoinOrder();
    join_order_ = NULL;
  }

W
wangzelin.wzl 已提交
145
  for(int64_t i = 0; i< subplan_infos_.count(); ++i) {
O
oceanbase-admin 已提交
146 147 148
    if (NULL != subplan_infos_.at(i)) {
      subplan_infos_.at(i)->~SubPlanInfo();
      subplan_infos_.at(i) = NULL;
W
wangzelin.wzl 已提交
149
    } else { /* Do nothing */ }
O
oceanbase-admin 已提交
150 151 152
  }
}

O
obdev 已提交
153 154 155 156 157 158 159 160
void ObLogPlan::destory()
{
  if (NULL != onetime_copier_) {
    onetime_copier_->~ObRawExprCopier();
    onetime_copier_ = NULL;
  }
}

O
oceanbase-admin 已提交
161 162 163 164 165 166 167 168 169
double ObLogPlan::get_optimization_cost()
{
  double opt_cost = 0.0;
  if (OB_NOT_NULL(root_)) {
    opt_cost = root_->get_cost();
  }
  return opt_cost;
}

W
wangzelin.wzl 已提交
170
int ObLogPlan::make_candidate_plans(ObLogicalOperator *top)
O
oceanbase-admin 已提交
171 172
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
173 174
  candidates_.reuse();
  if (OB_ISNULL(top)) {
O
oceanbase-admin 已提交
175 176
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
W
wangzelin.wzl 已提交
177 178
  } else if (OB_FAIL(candidates_.candidate_plans_.push_back(CandidatePlan(top)))) {
    LOG_WARN("push back error", K(ret));
O
oceanbase-admin 已提交
179
  } else {
W
wangzelin.wzl 已提交
180 181
    candidates_.plain_plan_.first = top->get_cost();
    candidates_.plain_plan_.second = 0;
O
oceanbase-admin 已提交
182 183 184
  }
  return ret;
}
W
wangzelin.wzl 已提交
185 186 187 188 189

int64_t ObLogPlan::to_string(char *buf,
                             const int64_t buf_len,
                             ExplainType type,
                             const ObExplainDisplayOpt &display_opt) const
O
oceanbase-admin 已提交
190 191
{
  int ret = OB_SUCCESS;
O
obdev 已提交
192 193 194 195
  UNUSED(buf);
  UNUSED(buf_len);
  UNUSED(type);
  return 0;
O
oceanbase-admin 已提交
196 197
}

W
wangzelin.wzl 已提交
198 199 200 201 202
/*
 * 找出from items中对应的table items
 */
int ObLogPlan::get_from_table_items(const ObIArray<FromItem> &from_items,
                                    ObIArray<TableItem *> &table_items)
O
oceanbase-admin 已提交
203 204
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
205
  const ObDMLStmt *stmt = NULL;
O
oceanbase-admin 已提交
206 207 208 209 210
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("null stmt", K(stmt), K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < from_items.count(); i++) {
W
wangzelin.wzl 已提交
211 212
      const FromItem &from_item = from_items.at(i);
      TableItem *temp_table_item = NULL;
O
oceanbase-admin 已提交
213
      if (!from_item.is_joined_) {
W
wangzelin.wzl 已提交
214
        //如果是基表或SubQuery
O
oceanbase-admin 已提交
215 216
        temp_table_item = stmt->get_table_item_by_id(from_item.table_id_);
      } else {
W
wangzelin.wzl 已提交
217
        //如果是Joined table
O
oceanbase-admin 已提交
218 219 220 221
        temp_table_item = stmt->get_joined_table(from_item.table_id_);
      }
      if (OB_FAIL(table_items.push_back(temp_table_item))) {
        LOG_WARN("failed to push back table item", K(ret));
W
wangzelin.wzl 已提交
222
      } else { /*do nothing*/ }
O
oceanbase-admin 已提交
223 224 225 226 227
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
228 229
int ObLogPlan::get_table_ids(TableItem *table_item,
                            ObRelIds &table_ids)
O
oceanbase-admin 已提交
230 231
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
232
  const ObDMLStmt *stmt = get_stmt();
O
oceanbase-admin 已提交
233 234 235 236 237 238 239 240
  if (OB_ISNULL(table_item) || OB_ISNULL(stmt)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null table item or stmt", K(ret));
  } else if (!table_item->is_joined_table()) {
    if (OB_FAIL(table_ids.add_member(stmt->get_table_bit_index(table_item->table_id_)))) {
      LOG_WARN("failed to add members", K(ret));
    }
  } else {
W
wangzelin.wzl 已提交
241 242 243 244 245 246
    JoinedTable *joined_table = static_cast<JoinedTable*>(table_item);
    for (int64_t i = 0; OB_SUCC(ret) && i < joined_table->single_table_ids_.count(); ++i) {
      if (OB_FAIL(table_ids.add_member(
                    stmt->get_table_bit_index(joined_table->single_table_ids_.at(i))))) {
        LOG_WARN("failed to add member", K(ret), K(joined_table->single_table_ids_.at(i)));
      } else { /* do nothing. */ }
O
oceanbase-admin 已提交
247 248 249 250 251
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
252 253
int ObLogPlan::get_table_ids(const ObIArray<uint64_t> &table_ids,
                             ObRelIds &rel_ids)
O
oceanbase-admin 已提交
254 255
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
256
  const ObDMLStmt *stmt = NULL;
O
oceanbase-admin 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  int32_t idx = OB_INVALID_INDEX;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null stmt", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < table_ids.count(); ++i) {
    idx = stmt->get_table_bit_index(table_ids.at(i));
    if (OB_UNLIKELY(OB_INVALID_INDEX == idx)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null table item or stmt", K(ret));
    } else if (OB_FAIL(rel_ids.add_member(idx))) {
      LOG_WARN("failed to add members", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
274 275
int ObLogPlan::get_table_ids(const ObIArray<TableItem*> &table_items,
                            ObRelIds& table_ids)
O
oceanbase-admin 已提交
276 277 278
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
W
wangzelin.wzl 已提交
279
    TableItem *item = table_items.at(i);
O
oceanbase-admin 已提交
280 281 282 283 284 285 286 287 288 289
    if (OB_ISNULL(item)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null table item", K(ret));
    } else if (OB_FAIL(get_table_ids(item, table_ids))) {
      LOG_WARN("failed to get table ids", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
290 291
int ObLogPlan::get_table_ids(const ObIArray<ObRawExpr*> &exprs,
                            ObRelIds& table_ids)
O
oceanbase-admin 已提交
292 293 294
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < exprs.count(); ++i) {
W
wangzelin.wzl 已提交
295
    ObRawExpr *expr = exprs.at(i);
O
oceanbase-admin 已提交
296 297 298 299 300 301 302 303 304 305
    if (OB_ISNULL(expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null expr", K(ret));
    } else if (OB_FAIL(table_ids.add_members(expr->get_relation_ids()))) {
      LOG_WARN("failed to add members", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
306 307 308
int ObLogPlan::is_joined_table_filter(const ObIArray<TableItem*> &table_items,
                                      const ObRawExpr *expr,
                                      bool &is_filter)
O
oceanbase-admin 已提交
309 310 311 312 313 314 315
{
  int ret = OB_SUCCESS;
  is_filter = false;
  if (OB_ISNULL(expr)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null expr or stmt", K(ret));
  } else if (expr->get_relation_ids().is_empty()) {
W
wangzelin.wzl 已提交
316
    //do nothing
O
oceanbase-admin 已提交
317 318
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && !is_filter && i < table_items.count(); ++i) {
W
wangzelin.wzl 已提交
319
      TableItem *item = table_items.at(i);
O
oceanbase-admin 已提交
320 321 322 323 324
      ObRelIds joined_table_ids;
      if (OB_ISNULL(item)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null semi item", K(ret));
      } else if (!item->is_joined_table()) {
W
wangzelin.wzl 已提交
325 326 327
        //do nothing
      } else if (OB_FAIL(get_table_ids(item,
                                      joined_table_ids))) {
O
oceanbase-admin 已提交
328 329 330 331 332 333 334 335 336
        LOG_WARN("failed to get table ids", K(ret));
      } else if (joined_table_ids.is_superset(expr->get_relation_ids())) {
        is_filter = true;
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
337 338 339
int ObLogPlan::find_inner_conflict_detector(const ObIArray<ConflictDetector*> &inner_conflict_detectors,
                                            const ObRelIds &rel_ids,
                                            ConflictDetector* &detector)
O
oceanbase-admin 已提交
340 341 342 343 344 345 346 347 348 349
{
  int ret = OB_SUCCESS;
  detector = NULL;
  int64_t N = inner_conflict_detectors.count();
  for (int64_t i = 0; OB_SUCC(ret) && NULL == detector && i < N; ++i) {
    ConflictDetector* temp_detector = inner_conflict_detectors.at(i);
    if (OB_ISNULL(temp_detector)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null detector", K(ret));
    } else if (temp_detector->join_info_.join_type_ != INNER_JOIN) {
W
wangzelin.wzl 已提交
350
      //do nothing
O
oceanbase-admin 已提交
351 352 353 354 355 356 357
    } else if (temp_detector->join_info_.table_set_.equal(rel_ids)) {
      detector = temp_detector;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
358 359 360 361 362 363 364 365 366 367 368 369
/**
 * 检查两个join运算是否满足结合律
 * 如果是left outer join assoc left outer join
 * 需要满足第二个连接的条件拒绝第二张表的空值
 * 如果是full outer join assoc left outer join
 * 需要满足第二个连接的条件拒绝第二张表的空值
 * 如果是full outer join assoc full outer join
 * 需要满足第二个连接的条件拒绝第二张表的空值
 */
int ObLogPlan::satisfy_associativity_rule(const ConflictDetector &left,
                                          const ConflictDetector &right,
                                          bool &is_satisfy)
O
oceanbase-admin 已提交
370 371 372 373 374

{
  int ret = OB_SUCCESS;
  if (!ASSOC_PROPERTY[left.join_info_.join_type_][right.join_info_.join_type_]) {
    is_satisfy = false;
W
wangzelin.wzl 已提交
375 376
  } else if ((LEFT_OUTER_JOIN == left.join_info_.join_type_ ||
              FULL_OUTER_JOIN == left.join_info_.join_type_) &&
O
oceanbase-admin 已提交
377
             LEFT_OUTER_JOIN == right.join_info_.join_type_) {
W
wangzelin.wzl 已提交
378 379 380 381 382
    //需要满足p23 reject null on A(e2)
    if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
                        right.join_info_.on_conditions_,
                        left.R_DS_.is_subset(right.L_DS_) ? left.R_DS_ : right.L_DS_,
                        is_satisfy))) {
O
oceanbase-admin 已提交
383 384
      LOG_WARN("failed to check is null reject conditions", K(ret));
    }
W
wangzelin.wzl 已提交
385 386 387
  } else if (FULL_OUTER_JOIN == left.join_info_.join_type_ &&
             FULL_OUTER_JOIN == right.join_info_.join_type_) {
    //需要满足p12、p23 reject null on A(e2)
O
oceanbase-admin 已提交
388
    if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
W
wangzelin.wzl 已提交
389 390 391
                        left.join_info_.on_conditions_,
                        left.R_DS_.is_subset(right.L_DS_) ? left.R_DS_ : right.L_DS_,
                        is_satisfy))) {
O
oceanbase-admin 已提交
392 393
      LOG_WARN("failed to check is null reject conditions", K(ret));
    } else if (!is_satisfy) {
W
wangzelin.wzl 已提交
394 395 396 397 398
      //do nothing
    } else if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
                        right.join_info_.on_conditions_,
                        left.R_DS_.is_subset(right.L_DS_) ? left.R_DS_ : right.L_DS_,
                        is_satisfy))) {
O
oceanbase-admin 已提交
399 400 401 402 403
      LOG_WARN("failed to check is null reject conditions", K(ret));
    }
  } else {
    is_satisfy = true;
  }
W
wangzelin.wzl 已提交
404
  LOG_TRACE("succeed to check assoc", K(left), K(right), K(is_satisfy));
O
oceanbase-admin 已提交
405 406 407
  return ret;
}

W
wangzelin.wzl 已提交
408 409 410 411 412 413 414 415
/**
 * 检查两个join运算是否满足左交换律
 * 对于left outer join、full outer join
 * 需要满足额外的空值拒绝条件
 */
int ObLogPlan::satisfy_left_asscom_rule(const ConflictDetector &left,
                                        const ConflictDetector &right,
                                        bool &is_satisfy)
O
oceanbase-admin 已提交
416 417 418 419 420

{
  int ret = OB_SUCCESS;
  if (!L_ASSCOM_PROPERTY[left.join_info_.join_type_][right.join_info_.join_type_]) {
    is_satisfy = false;
W
wangzelin.wzl 已提交
421 422 423 424 425 426 427
  } else if (LEFT_OUTER_JOIN == left.join_info_.join_type_ &&
             FULL_OUTER_JOIN == right.join_info_.join_type_) {
    //需要满足p12 reject null on A(e1)
    if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
                                          left.join_info_.on_conditions_,
                                          left.L_DS_,
                                          is_satisfy))) {
O
oceanbase-admin 已提交
428 429
      LOG_WARN("failed to check is null reject conditions", K(ret));
    }
W
wangzelin.wzl 已提交
430 431 432 433 434 435 436
  } else if (FULL_OUTER_JOIN == left.join_info_.join_type_ &&
             LEFT_OUTER_JOIN == right.join_info_.join_type_) {
    //需要满足p13 reject null on A(e1)
    if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
                                          right.join_info_.on_conditions_,
                                          left.L_DS_,
                                          is_satisfy))) {
O
oceanbase-admin 已提交
437 438
      LOG_WARN("failed to check is null reject conditions", K(ret));
    }
W
wangzelin.wzl 已提交
439 440 441 442 443 444 445
  } else if (FULL_OUTER_JOIN == left.join_info_.join_type_ &&
             FULL_OUTER_JOIN == right.join_info_.join_type_) {
    //需要满足p12、p13 reject null on A(e1)
    if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
                                          left.join_info_.on_conditions_,
                                          left.L_DS_,
                                          is_satisfy))) {
O
oceanbase-admin 已提交
446 447
      LOG_WARN("failed to check is null reject conditions", K(ret));
    } else if (!is_satisfy) {
W
wangzelin.wzl 已提交
448
      //do nothing
O
oceanbase-admin 已提交
449
    } else if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
W
wangzelin.wzl 已提交
450 451 452
                                                right.join_info_.on_conditions_,
                                                left.L_DS_,
                                                is_satisfy))) {
O
oceanbase-admin 已提交
453 454 455 456 457 458 459 460 461
      LOG_WARN("failed to check is null reject conditions", K(ret));
    }
  } else {
    is_satisfy = true;
  }
  LOG_TRACE("succeed to check l-asscom", K(left), K(right), K(is_satisfy));
  return ret;
}

W
wangzelin.wzl 已提交
462 463 464 465 466 467 468 469
/**
 * 检查两个join运算是否满足右交换律
 * 对于left outer join、full outer join
 * 需要满足额外的空值拒绝条件
 */
int ObLogPlan::satisfy_right_asscom_rule(const ConflictDetector &left,
                                        const ConflictDetector &right,
                                        bool &is_satisfy)
O
oceanbase-admin 已提交
470 471 472 473 474

{
  int ret = OB_SUCCESS;
  if (!R_ASSCOM_PROPERTY[left.join_info_.join_type_][right.join_info_.join_type_]) {
    is_satisfy = false;
W
wangzelin.wzl 已提交
475 476 477 478 479 480 481
  } else if (FULL_OUTER_JOIN == left.join_info_.join_type_ &&
             FULL_OUTER_JOIN == right.join_info_.join_type_) {
    //需要满足p12、p23 reject null on A(e3)
    if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
                                          left.join_info_.on_conditions_,
                                          right.R_DS_,
                                          is_satisfy))) {
O
oceanbase-admin 已提交
482 483
      LOG_WARN("failed to check is null reject conditions", K(ret));
    } else if (!is_satisfy) {
W
wangzelin.wzl 已提交
484
      //do nothing
O
oceanbase-admin 已提交
485
    } else if (OB_FAIL(ObTransformUtils::is_null_reject_conditions(
W
wangzelin.wzl 已提交
486 487 488
                                                right.join_info_.on_conditions_,
                                                right.R_DS_,
                                                is_satisfy))) {
O
oceanbase-admin 已提交
489 490 491 492 493 494 495 496 497
      LOG_WARN("failed to check is null reject conditions", K(ret));
    }
  } else {
    is_satisfy = true;
  }
  LOG_TRACE("succeed to check r-asscom", K(left), K(right), K(is_satisfy));
  return ret;
}

W
wangzelin.wzl 已提交
498 499 500 501 502 503 504 505 506 507 508 509
/**
 * 加入冲突规则left --> right
 * 简化规则:
 * A -> B, A -> C
 * 简化为:A -> (B,C)
 * A -> B, C -> B
 * 简化为:(A,C) -> B
 *
 */
int ObLogPlan::add_conflict_rule(const ObRelIds &left,
                                const ObRelIds &right,
                                ObIArray<std::pair<ObRelIds, ObRelIds>> &rules)
O
oceanbase-admin 已提交
510 511
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
512 513
  ObRelIds *left_handle_rule = NULL;
  ObRelIds *right_handle_rule = NULL;
O
oceanbase-admin 已提交
514
  bool find = false;
W
wangzelin.wzl 已提交
515
  for (int64_t i =0; !find && i < rules.count(); ++i) {
O
oceanbase-admin 已提交
516 517 518 519 520 521 522 523 524
    if (rules.at(i).first.equal(left) && rules.at(i).second.equal(right)) {
      find = true;
    } else if (rules.at(i).first.equal(left)) {
      left_handle_rule = &rules.at(i).second;
    } else if (rules.at(i).second.equal(right)) {
      right_handle_rule = &rules.at(i).first;
    }
  }
  if (find) {
W
wangzelin.wzl 已提交
525
    //do nothing
O
oceanbase-admin 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
  } else if (NULL != left_handle_rule) {
    if (OB_FAIL(left_handle_rule->add_members(right))) {
      LOG_WARN("failed to add members", K(ret));
    }
  } else if (NULL != right_handle_rule) {
    if (OB_FAIL(right_handle_rule->add_members(left))) {
      LOG_WARN("failed to add members", K(ret));
    }
  } else {
    std::pair<ObRelIds, ObRelIds> rule;
    if (OB_FAIL(rule.first.add_members(left))) {
      LOG_WARN("failed to add members", K(ret));
    } else if (OB_FAIL(rule.second.add_members(right))) {
      LOG_WARN("failed to add members", K(ret));
    } else if (OB_FAIL(rules.push_back(rule))) {
      LOG_WARN("failed to push back rule", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
547 548 549 550
int ObLogPlan::generate_conflict_rule(ConflictDetector *parent,
                                      ConflictDetector *child,
                                      bool is_left_child,
                                      ObIArray<std::pair<ObRelIds, ObRelIds>> &rules)
O
oceanbase-admin 已提交
551 552 553 554 555 556 557
{
  int ret = OB_SUCCESS;
  bool is_satisfy = false;
  ObRelIds ids;
  if (OB_ISNULL(parent) || OB_ISNULL(child)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null detector", K(ret));
W
wangzelin.wzl 已提交
558 559
  } else if (child->is_redundancy_) {
    //do nothing
O
oceanbase-admin 已提交
560 561
  } else if (is_left_child) {
    LOG_TRACE("generate left child conflict rule for ", K(*parent), K(*child));
W
wangzelin.wzl 已提交
562
    //check assoc(o^a, o^b)
O
oceanbase-admin 已提交
563 564 565 566 567 568 569
    if (OB_FAIL(satisfy_associativity_rule(*child, *parent, is_satisfy))) {
      LOG_WARN("failed to check satisfy assoc", K(ret));
    } else if (is_satisfy) {
      LOG_TRACE("satisfy assoc");
    } else if (OB_FAIL(ids.intersect(child->L_DS_, child->join_info_.table_set_))) {
      LOG_WARN("failed to cal intersect table ids", K(ret));
    } else if (ids.is_empty()) {
W
wangzelin.wzl 已提交
570
      //CR += T(right(o^a)) -> T(left(o^a))
O
oceanbase-admin 已提交
571 572 573 574 575 576 577 578
      if (OB_FAIL(add_conflict_rule(child->R_DS_, child->L_DS_, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else if (OB_FAIL(add_conflict_rule(child->R_DS_, child->R_DS_, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict1", K(rules));
      }
    } else {
W
wangzelin.wzl 已提交
579
      //CR += T(right(o^a)) -> T(left(o^a)) n T(quals)
O
oceanbase-admin 已提交
580 581 582 583 584 585 586 587
      if (OB_FAIL(add_conflict_rule(child->R_DS_, ids, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else if (OB_FAIL(add_conflict_rule(child->R_DS_, child->R_DS_, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict2", K(rules));
      }
    }
W
wangzelin.wzl 已提交
588
    //check l-asscom(o^a, o^b)
O
oceanbase-admin 已提交
589 590 591 592 593 594 595 596
    if (OB_FAIL(ret)) {
    } else if (OB_FAIL(satisfy_left_asscom_rule(*child, *parent, is_satisfy))) {
      LOG_WARN("failed to check satisfy assoc", K(ret));
    } else if (is_satisfy) {
      LOG_TRACE("satisfy l-asscom");
    } else if (OB_FAIL(ids.intersect(child->R_DS_, child->join_info_.table_set_))) {
      LOG_WARN("failed to cal intersect table ids", K(ret));
    } else if (ids.is_empty()) {
W
wangzelin.wzl 已提交
597
      //CR += T(left(o^a)) -> T(right(o^a))
O
oceanbase-admin 已提交
598 599 600 601 602 603
      if (OB_FAIL(add_conflict_rule(child->L_DS_, child->R_DS_, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict3", K(rules));
      }
    } else {
W
wangzelin.wzl 已提交
604
      //CR += T(left(o^a)) -> T(right(o^a)) n T(quals)
O
oceanbase-admin 已提交
605 606 607 608 609 610 611 612
      if (OB_FAIL(add_conflict_rule(child->L_DS_, ids, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict4", K(rules));
      }
    }
  } else {
    LOG_TRACE("generate right child conflict rule for ", K(*parent), K(*child));
W
wangzelin.wzl 已提交
613
    //check assoc(o^b, o^a)
O
oceanbase-admin 已提交
614 615 616 617 618 619 620
    if (OB_FAIL(satisfy_associativity_rule(*parent, *child, is_satisfy))) {
      LOG_WARN("failed to check satisfy assoc", K(ret));
    } else if (is_satisfy) {
      LOG_TRACE("satisfy assoc");
    } else if (OB_FAIL(ids.intersect(child->R_DS_, child->join_info_.table_set_))) {
      LOG_WARN("failed to cal intersect table ids", K(ret));
    } else if (ids.is_empty()) {
W
wangzelin.wzl 已提交
621
      //CR += T(left(o^a)) -> T(right(o^a))
O
oceanbase-admin 已提交
622 623 624 625 626 627
      if (OB_FAIL(add_conflict_rule(child->L_DS_, child->R_DS_, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict5", K(rules));
      }
    } else {
W
wangzelin.wzl 已提交
628
      //CR += T(left(o^a)) -> T(right(o^a)) n T(quals)
O
oceanbase-admin 已提交
629 630 631 632 633 634
      if (OB_FAIL(add_conflict_rule(child->L_DS_, ids, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict6", K(rules));
      }
    }
W
wangzelin.wzl 已提交
635
    //check r-asscom(o^b, o^a)
O
oceanbase-admin 已提交
636 637 638 639 640 641 642 643
    if (OB_FAIL(ret)) {
    } else if (OB_FAIL(satisfy_right_asscom_rule(*parent, *child, is_satisfy))) {
      LOG_WARN("failed to check satisfy assoc", K(ret));
    } else if (is_satisfy) {
      LOG_TRACE("satisfy r-asscom");
    } else if (OB_FAIL(ids.intersect(child->L_DS_, child->join_info_.table_set_))) {
      LOG_WARN("failed to cal intersect table ids", K(ret));
    } else if (ids.is_empty()) {
W
wangzelin.wzl 已提交
644
      //CR += T(right(o^a)) -> T(left(o^a))
O
oceanbase-admin 已提交
645 646 647 648 649 650
      if (OB_FAIL(add_conflict_rule(child->R_DS_, child->L_DS_, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict7", K(rules));
      }
    } else {
W
wangzelin.wzl 已提交
651
      //CR += T(right(o^a)) -> T(left(o^a)) n T(quals)
O
oceanbase-admin 已提交
652 653 654 655 656 657 658 659 660 661
      if (OB_FAIL(add_conflict_rule(child->R_DS_, ids, rules))) {
        LOG_WARN("failed to add conflict rule", K(ret));
      } else {
        LOG_TRACE("succeed to add condlict8", K(rules));
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
662 663 664 665
int ObLogPlan::get_base_table_items(const ObDMLStmt &stmt,
                                    const ObIArray<TableItem*> &table_items,
                                    const ObIArray<SemiInfo*> &semi_infos,
                                    ObIArray<TableItem*> &base_tables)
O
oceanbase-admin 已提交
666 667 668
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
W
wangzelin.wzl 已提交
669
    TableItem *item = table_items.at(i);
O
oceanbase-admin 已提交
670 671 672 673 674 675
    if (OB_ISNULL(item)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null table item", K(ret));
    } else if (!item->is_joined_table()) {
      ret = base_tables.push_back(item);
    } else {
W
wangzelin.wzl 已提交
676
      JoinedTable *joined_table = static_cast<JoinedTable*>(item);
O
oceanbase-admin 已提交
677
      for (int64_t j = 0; OB_SUCC(ret) && j < joined_table->single_table_ids_.count(); ++j) {
W
wangzelin.wzl 已提交
678
        TableItem *table = stmt.get_table_item_by_id(joined_table->single_table_ids_.at(j));
O
oceanbase-admin 已提交
679 680 681 682 683 684 685 686 687
        ret = base_tables.push_back(table);
      }
    }
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < semi_infos.count(); ++i) {
    if (OB_ISNULL(semi_infos.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null semi info", K(ret));
    } else {
W
wangzelin.wzl 已提交
688
      TableItem *table = stmt.get_table_item_by_id(semi_infos.at(i)->right_table_id_);
O
oceanbase-admin 已提交
689 690 691 692 693 694
      ret = base_tables.push_back(table);
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
695 696 697 698 699 700 701 702 703
//1. 添加基本表的ObJoinOrder结构到base level
//2. 添加Semi Join的右支block到base level
//3. 条件下推到基表
//4. 初始化动态规划数据结构,即每层ObJoinOrders
//5. 生成第一级ObJoinOrder, 即单表路径
//6. 选择location
//7. 设置第一级ObJoinOrder的sharding info
//8. 依次进行下一层级的规划过程(generate_join_levels())
//9. 取出最后一级的ObJoinOrder,输出
O
oceanbase-admin 已提交
704 705 706
int ObLogPlan::generate_join_orders()
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
707
  const ObDMLStmt *stmt = NULL;
O
oceanbase-admin 已提交
708
  ObSEArray<ObRawExpr*, 8> quals;
W
wangzelin.wzl 已提交
709 710
  ObSEArray<TableItem*, 8> from_table_items;
  ObSEArray<TableItem*, 8> base_table_items;
O
oceanbase-admin 已提交
711 712 713 714 715 716
  JoinOrderArray base_level;
  int64_t join_level = 0;
  common::ObArray<JoinOrderArray> join_rels;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected NULL", K(stmt), K(ret));
W
wangzelin.wzl 已提交
717 718 719 720 721 722 723
  } else if (OB_FAIL(get_from_table_items(stmt->get_from_items(), from_table_items))) {
      LOG_WARN("failed to get table items", K(ret));
  } else if (OB_FAIL(get_base_table_items(*stmt,
                                          from_table_items,
                                          stmt->get_semi_infos(),
                                          base_table_items))) {
    LOG_WARN("failed to flatten table items", K(ret));
O
oceanbase-admin 已提交
724 725 726 727 728 729 730
  } else if (OB_FAIL(append(quals, get_stmt()->get_condition_exprs()))) {
    LOG_WARN("failed to append exprs", K(ret));
  } else if (OB_FAIL(append(quals, get_pushdown_filters()))) {
    LOG_WARN("failed to append exprs", K(ret));
  }

  if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
731 732 733
    if (OB_FAIL(pre_process_quals(from_table_items,
                                  stmt->get_semi_infos(),
                                  quals))) {
O
oceanbase-admin 已提交
734
      LOG_WARN("failed to distribute special quals", K(ret));
W
wangzelin.wzl 已提交
735 736 737 738 739 740 741
    } else if (OB_FAIL(collect_subq_pushdown_filter_table_relids(quals))) {
      LOG_WARN("failed to compute subplan das table ids", K(ret));
    } else if (OB_FAIL(generate_base_level_join_order(base_table_items,
                                                      base_level))) {
      LOG_WARN("fail to generate base level join order", K(ret));
    } else if (OB_FAIL(init_function_table_depend_info(base_table_items))) {
      LOG_WARN("failed to init function table depend infos", K(ret));
O
obdev 已提交
742 743
    } else if (OB_FAIL(init_json_table_depend_info(base_table_items))) {
      LOG_WARN("failed to init json table depend infos", K(ret));
W
wangzelin.wzl 已提交
744 745 746 747
    } else if (OB_FAIL(generate_conflict_detectors(from_table_items,
                                                  stmt->get_semi_infos(),
                                                  quals,
                                                  base_level))) {
O
oceanbase-admin 已提交
748
      LOG_WARN("failed to generate conflict detectors", K(ret));
W
wangzelin.wzl 已提交
749 750 751
    }  else {
      //初始化动规数据结构
      join_level = base_level.count(); //需要连接的层次数
O
oceanbase-admin 已提交
752 753 754 755 756 757 758
      if (OB_UNLIKELY(join_level < 1)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected join level", K(ret), K(join_level));
      } else if (OB_FAIL(join_rels.prepare_allocate(join_level))) {
        LOG_WARN("failed to prepare allocate join rels", K(ret));
      } else if (OB_FAIL(join_rels.at(0).assign(base_level))) {
        LOG_WARN("failed to assign base level join order", K(ret));
W
wangzelin.wzl 已提交
759 760
      } else if (OB_FAIL(prepare_ordermap_pathset(base_level))) {
        LOG_WARN("failed to prepare order map and path set", K(ret));
O
oceanbase-admin 已提交
761 762 763
      }
    }
  }
W
wangzelin.wzl 已提交
764 765

  //生成第一级Array:单表路径
O
obdev 已提交
766
  OPT_TRACE_TITLE("GENERATE BASE PATH");
O
oceanbase-admin 已提交
767 768 769 770
  for (int64_t i = 0; OB_SUCC(ret) && i < join_level; ++i) {
    if (OB_ISNULL(join_rels.at(0).at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("join_rels_.at(0).at(i) is null", K(ret), K(i));
W
wangzelin.wzl 已提交
771 772 773
    } else if (OB_FAIL(mock_base_rel_detectors(join_rels.at(0).at(i)))) {
      LOG_WARN("failed to mock base rel detectors", K(ret));
    } else {
O
obdev 已提交
774 775
      OPT_TRACE("create base path for ", join_rels.at(0).at(i));
      OPT_TRACE_BEGIN_SECTION;
W
wangzelin.wzl 已提交
776
      ret = join_rels.at(0).at(i)->generate_base_paths();
O
obdev 已提交
777
      OPT_TRACE_END_SECTION;
O
oceanbase-admin 已提交
778 779 780
    }
  }

W
wangzelin.wzl 已提交
781 782 783
  //枚举join order
  //如果有leading hint就在这里按leading hint指定的join order枚举,
  //如果根据leading hint没有枚举到有效join order,就忽略hint重新枚举。
O
oceanbase-admin 已提交
784
  if (OB_SUCC(ret)) {
O
obdev 已提交
785 786
    OPT_TRACE_STATIS(stmt, get_basic_table_metas());
    OPT_TRACE_TITLE("START GENERATE JOIN ORDER");
W
wangzelin.wzl 已提交
787
    if (OB_FAIL(init_bushy_tree_info(from_table_items))) {
O
oceanbase-admin 已提交
788
      LOG_WARN("failed to init bushy tree infos", K(ret));
W
wangzelin.wzl 已提交
789 790 791 792 793 794 795 796
    } else if (OB_FAIL(init_width_estimation_info(stmt))) {
      LOG_WARN("failed to init width estimation info", K(ret));
    } else if (OB_FAIL(generate_join_levels_with_IDP(join_rels))) {
      LOG_WARN("failed to generate join levels with dynamic program", K(ret));
    } else if (join_rels.at(join_level - 1).count() < 1 &&
               OB_FAIL(generate_join_levels_with_orgleading(join_rels))) {
      LOG_WARN("failed to enum with greedy", K(ret));
    } else if (1 != join_rels.at(join_level - 1).count()) {
O
oceanbase-admin 已提交
797
      ret = OB_ERR_NO_JOIN_ORDER_GENERATED;
W
wangzelin.wzl 已提交
798 799 800
      LOG_WARN("No final JoinOrder generated",
                K(ret), K(join_level), K(join_rels.at(join_level -1).count()));
    } else if (OB_ISNULL(join_order_ = join_rels.at(join_level -1).at(0))) {
O
oceanbase-admin 已提交
801 802 803 804 805 806 807
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("null join order", K(ret), K(join_order_));
    } else if (OB_UNLIKELY(join_order_->get_interesting_paths().empty())) {
      ret = OB_ERR_NO_PATH_GENERATED;
      LOG_WARN("No final join path generated", K(ret), K(*join_order_));
    } else {
      LOG_TRACE("succeed to generate join order", K(ret));
O
obdev 已提交
808 809 810 811
      OPT_TRACE("SUCCEED TO GENERATE JOIN ORDER, try path count:",
                        join_order_->get_total_path_num());
      OPT_TRACE_TIME_USED;
      OPT_TRACE_MEM_USED;
O
oceanbase-admin 已提交
812 813 814 815 816
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
int ObLogPlan::prepare_ordermap_pathset(const JoinOrderArray base_level)
{
  int ret = OB_SUCCESS;
  if (!relid_joinorder_map_.created() &&
      OB_FAIL(relid_joinorder_map_.create(RELORDER_HASHBUCKET_SIZE,
                                          &id_order_map_allocer_,
                                          &bucket_allocator_wrapper_))) {
    LOG_WARN("create hash map failed", K(ret));
  } else if (!join_path_set_.created() &&
             OB_FAIL(join_path_set_.create(JOINPATH_SET_HASHBUCKET_SIZE,
                                          &join_path_set_allocer_,
                                          &bucket_allocator_wrapper_))) {
    LOG_WARN("create hash set failed", K(ret));
  } else {
    int64_t join_level = base_level.count();
    for (int64_t i = 0; OB_SUCC(ret) && i < join_level; ++i) {
      ObJoinOrder *join_order = base_level.at(i);
      if (OB_ISNULL(join_order)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("invalid join order", K(ret));
      } else if (OB_FAIL(relid_joinorder_map_.set_refactored(join_order->get_tables(), join_order))) {
        LOG_WARN("failed to add basic join orders into map", K(ret));
      }
    }
  }
  return ret;
}

//生成单表ObJoinOrder结构, 并设置ObJoinOrder中table_set_
int ObLogPlan::generate_base_level_join_order(const ObIArray<TableItem*> &table_items,
                                              ObIArray<ObJoinOrder*> &base_level)
O
oceanbase-admin 已提交
848 849
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
850 851
  ObJoinOrder *this_jo = NULL;
  //首先加入基表
O
oceanbase-admin 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865
  int64_t N = table_items.count();
  for (int64_t i = 0; OB_SUCC(ret) && i < N; ++i) {
    if (OB_ISNULL(table_items.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("null table item", K(ret), K(i));
    } else if (OB_ISNULL(this_jo = create_join_order(ACCESS))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("failed to allocate an ObJoinOrder", K(ret));
    } else if (OB_FAIL(this_jo->init_base_join_order(table_items.at(i)))) {
      LOG_WARN("fail to generate the base rel", K(ret), K(*table_items.at(i)));
      this_jo->~ObJoinOrder();
      this_jo = NULL;
    } else if (OB_FAIL(base_level.push_back(this_jo))) {
      LOG_WARN("fail to push back an ObJoinOrder", K(ret));
W
wangzelin.wzl 已提交
866
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
867 868 869 870
  }
  return ret;
}

W
wangzelin.wzl 已提交
871 872
int ObLogPlan::split_or_quals(const ObIArray<TableItem*> &table_items,
                              ObIArray<ObRawExpr*> &quals)
O
oceanbase-admin 已提交
873 874 875 876
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr*, 8> new_quals;
  for (int64_t i = 0; OB_SUCC(ret) && i < quals.count(); ++i) {
W
wangzelin.wzl 已提交
877 878 879
    if (OB_FAIL(split_or_quals(table_items,
                               quals.at(i),
                               new_quals))) {
O
oceanbase-admin 已提交
880 881 882 883 884 885 886 887 888 889 890
      LOG_WARN("failed to split or quals", K(ret));
    }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(append(quals, new_quals))) {
      LOG_WARN("failed to append quals", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
891 892 893
int ObLogPlan::split_or_quals(const ObIArray<TableItem*> &table_items,
                              ObRawExpr *qual,
                              ObIArray<ObRawExpr*> &new_quals)
O
oceanbase-admin 已提交
894 895 896 897 898 899 900 901
{
  int ret = OB_SUCCESS;
  ObRelIds table_ids;
  bool is_filter = false;
  if (OB_ISNULL(qual)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null qual", K(ret));
  } else if (T_OP_OR != qual->get_expr_type()) {
W
wangzelin.wzl 已提交
902 903 904
    //do nothing
  } else if (!qual->has_flag(CNT_SUB_QUERY) &&
              OB_FAIL(is_joined_table_filter(table_items, qual, is_filter))) {
O
oceanbase-admin 已提交
905 906
    LOG_WARN("failed to check is joined table filter", K(ret));
  } else if (is_filter) {
W
wangzelin.wzl 已提交
907
    //joined table内部谓词等到下推on condition再拆分,否则会重复拆分or谓词
O
oceanbase-admin 已提交
908
  } else {
W
wangzelin.wzl 已提交
909
    ObOpRawExpr *or_qual = static_cast<ObOpRawExpr*>(qual);
O
oceanbase-admin 已提交
910
    for (int64_t j = 0; OB_SUCC(ret) && j < table_items.count(); ++j) {
W
wangzelin.wzl 已提交
911
      TableItem *table_item = table_items.at(j);
O
oceanbase-admin 已提交
912 913 914 915 916 917 918
      table_ids.reuse();
      if (OB_ISNULL(table_item)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table item is null", K(ret));
      } else if (OB_FAIL(get_table_ids(table_item, table_ids))) {
        LOG_WARN("failed to get table ids", K(ret));
      } else if (!table_ids.overlap(or_qual->get_relation_ids())) {
W
wangzelin.wzl 已提交
919 920 921 922
        //do nothing
      } else if (qual->has_flag(CNT_SUB_QUERY) ||
                (!table_ids.is_superset(or_qual->get_relation_ids()))) {
        ret= try_split_or_qual(table_ids, *or_qual, new_quals);
O
oceanbase-admin 已提交
923 924 925 926 927 928
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
929 930 931
int ObLogPlan::pre_process_quals(const ObIArray<TableItem*> &table_items,
                                const ObIArray<SemiInfo*> &semi_infos,
                                ObIArray<ObRawExpr*> &quals)
O
oceanbase-admin 已提交
932 933 934
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr*, 8> normal_quals;
W
wangzelin.wzl 已提交
935
  //1. where conditions
O
oceanbase-admin 已提交
936
  for (int64_t i = 0; OB_SUCC(ret) && i < quals.count(); ++i) {
W
wangzelin.wzl 已提交
937
    ObRawExpr *qual = quals.at(i);
O
obdev 已提交
938 939 940
    if (OB_FAIL(adjust_expr_with_onetime(qual))) {
      LOG_WARN("failed to try replace onetime subquery", K(ret));
    } else if (OB_ISNULL(qual)) {
O
oceanbase-admin 已提交
941 942 943 944 945
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null qual", K(ret));
    } else if (qual->has_flag(CNT_ROWNUM)) {
      ret = add_rownum_expr(qual);
    } else if (qual->has_flag(CNT_SUB_QUERY)) {
W
wangzelin.wzl 已提交
946 947
      if (OB_FAIL(split_or_quals(table_items, qual, quals))) {
        LOG_WARN("failed to split or quals", K(ret));
O
oceanbase-admin 已提交
948
      } else {
W
wangzelin.wzl 已提交
949
        ret = add_subquery_filter(qual);
O
oceanbase-admin 已提交
950
      }
O
obdev 已提交
951 952
    } else if (qual->is_const_expr()) {
      ret = add_startup_filter(qual);
W
wangzelin.wzl 已提交
953 954 955 956 957
    } else if (qual->has_flag(CNT_RAND_FUNC) ||
               qual->has_flag(CNT_USER_VARIABLE) ||
               qual->has_flag(CNT_PL_UDF) ||
               qual->has_flag(CNT_SO_UDF)) {
      ret = add_special_expr(qual);
O
oceanbase-admin 已提交
958 959 960 961 962
    } else if (ObOptimizerUtil::has_hierarchical_expr(*qual)) {
      ret = normal_quals.push_back(qual);
    } else {
      ret = normal_quals.push_back(qual);
    }
W
wangzelin.wzl 已提交
963 964 965 966 967
    if (OB_SUCC(ret) && qual->has_flag(CNT_ONETIME) && !qual->has_flag(CNT_SUB_QUERY)) {
      if (OB_FAIL(add_subquery_filter(qual))) {
        LOG_WARN("failed to push back subquery filter", K(ret));
      }
    }
O
oceanbase-admin 已提交
968 969 970 971 972 973
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(quals.assign(normal_quals))) {
      LOG_WARN("failed to assign quals", K(ret));
    }
  }
W
wangzelin.wzl 已提交
974
  //2. on conditions
O
oceanbase-admin 已提交
975 976 977
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
    ret = pre_process_quals(table_items.at(i));
  }
W
wangzelin.wzl 已提交
978
  //3. semi conditions
O
oceanbase-admin 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992
  for (int64_t i = 0; OB_SUCC(ret) && i < semi_infos.count(); ++i) {
    ret = pre_process_quals(semi_infos.at(i));
  }
  return ret;
}

int ObLogPlan::pre_process_quals(SemiInfo* semi_info)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(semi_info)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null semi info", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < semi_info->semi_conditions_.count(); ++i) {
O
obdev 已提交
993 994 995 996
    ObRawExpr *expr = semi_info->semi_conditions_.at(i);
    if (OB_FAIL(adjust_expr_with_onetime(expr))) {
      LOG_WARN("failed to try replace onetime subquery", K(ret));
    } else if (OB_ISNULL(expr)) {
O
oceanbase-admin 已提交
997 998
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpected NULL", K(ret), K(expr));
W
wangzelin.wzl 已提交
999
    } else if (expr->has_flag(CNT_ROWNUM) || expr->has_flag(CNT_RAND_FUNC)) {
O
oceanbase-admin 已提交
1000 1001
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpected expr in semi condition", K(ret), K(*expr));
O
obdev 已提交
1002
    } else if (!expr->has_flag(CNT_ONETIME) || expr->has_flag(CNT_SUB_QUERY)) {
W
wangzelin.wzl 已提交
1003 1004 1005
      // do nothing
    } else if (OB_FAIL(add_subquery_filter(expr))) {
      LOG_WARN("failed to add subquery filter", K(ret));
O
oceanbase-admin 已提交
1006 1007 1008 1009 1010
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1011
int ObLogPlan::pre_process_quals(TableItem *table_item)
O
oceanbase-admin 已提交
1012 1013
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1014
  JoinedTable *joined_table = static_cast<JoinedTable*>(table_item);
O
oceanbase-admin 已提交
1015 1016 1017 1018
  if (OB_ISNULL(table_item)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null table item", K(ret));
  } else if (!table_item->is_joined_table()) {
W
wangzelin.wzl 已提交
1019
    //do nothing
O
oceanbase-admin 已提交
1020 1021 1022 1023 1024 1025
  } else if (OB_FAIL(SMART_CALL(pre_process_quals(joined_table->left_table_)))) {
    LOG_WARN("failed to distribute special quals", K(ret));
  } else if (OB_FAIL(SMART_CALL(pre_process_quals(joined_table->right_table_)))) {
    LOG_WARN("failed to distribute special quals", K(ret));
  } else {
    if (FULL_OUTER_JOIN == joined_table->joined_type_ &&
W
wangzelin.wzl 已提交
1026
             !ObOptimizerUtil::has_equal_join_conditions(joined_table->join_conditions_)) {
O
oceanbase-admin 已提交
1027 1028
      ret = OB_NOT_SUPPORTED;
      LOG_WARN("full outer join without equal join conditions is not supported now", K(ret));
W
wangzelin.wzl 已提交
1029
      LOG_USER_ERROR(OB_NOT_SUPPORTED, "full outer join without equal join conditions");
O
oceanbase-admin 已提交
1030 1031
    }
    for (int64_t i = 0; OB_SUCC(ret) && i < joined_table->join_conditions_.count(); ++i) {
O
obdev 已提交
1032 1033 1034 1035
      ObRawExpr *expr = joined_table->join_conditions_.at(i);
      if (OB_FAIL(adjust_expr_with_onetime(expr))) {
        LOG_WARN("failed to try replace onetime subquery", K(ret));
      } else if (OB_ISNULL(expr)) {
O
oceanbase-admin 已提交
1036 1037
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected NULL", K(ret), K(expr));
O
obdev 已提交
1038
      } else if (!expr->has_flag(CNT_ONETIME) || expr->has_flag(CNT_SUB_QUERY)) {
W
wangzelin.wzl 已提交
1039 1040 1041
        // do nothing
      } else if (OB_FAIL(add_subquery_filter(expr))) {
        LOG_WARN("failed to add subquery filter", K(ret));
O
oceanbase-admin 已提交
1042 1043 1044 1045 1046 1047
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1048 1049 1050 1051
int ObLogPlan::generate_conflict_detectors(const ObIArray<TableItem*> &table_items,
                                          const ObIArray<SemiInfo*> &semi_infos,
                                          ObIArray<ObRawExpr*> &quals,
                                          ObIArray<ObJoinOrder *> &baserels)
O
oceanbase-admin 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060
{
  int ret = OB_SUCCESS;
  ObRelIds table_ids;
  ObSEArray<ConflictDetector*, 8> semi_join_detectors;
  ObSEArray<ConflictDetector*, 8> inner_join_detectors;
  LOG_TRACE("start to generate conflict detector", K(table_items), K(semi_infos), K(quals));
  conflict_detectors_.reuse();
  if (OB_FAIL(get_table_ids(table_items, table_ids))) {
    LOG_WARN("failed to get table ids", K(ret));
W
wangzelin.wzl 已提交
1061 1062 1063 1064
  } else if (OB_FAIL(generate_inner_join_detectors(table_items,
                                                  quals,
                                                  baserels,
                                                  inner_join_detectors))) {
O
oceanbase-admin 已提交
1065
    LOG_WARN("failed to generate inner join detectors", K(ret));
W
wangzelin.wzl 已提交
1066 1067 1068 1069
  } else if (OB_FAIL(generate_semi_join_detectors(semi_infos,
                                                  table_ids,
                                                  inner_join_detectors,
                                                  semi_join_detectors))) {
O
oceanbase-admin 已提交
1070 1071 1072 1073 1074 1075
    LOG_WARN("failed to generate semi join detectors", K(ret));
  } else if (OB_FAIL(append(conflict_detectors_, semi_join_detectors))) {
    LOG_WARN("failed to append detectors", K(ret));
  } else if (OB_FAIL(append(conflict_detectors_, inner_join_detectors))) {
    LOG_WARN("failed to append detectors", K(ret));
  } else {
W
wangzelin.wzl 已提交
1076 1077 1078
    LOG_TRACE("succeed to generate confilct detectors",
                                        K(semi_join_detectors),
                                        K(inner_join_detectors));
O
oceanbase-admin 已提交
1079 1080 1081 1082
  }
  return ret;
}

W
wangzelin.wzl 已提交
1083 1084 1085 1086
int ObLogPlan::generate_semi_join_detectors(const ObIArray<SemiInfo*> &semi_infos,
                                            ObRelIds &left_rel_ids,
                                            const ObIArray<ConflictDetector*> &inner_join_detectors,
                                            ObIArray<ConflictDetector*> &semi_join_detectors)
O
oceanbase-admin 已提交
1087 1088 1089
{
  int ret = OB_SUCCESS;
  ObSqlBitSet<> right_rel_ids;
W
wangzelin.wzl 已提交
1090
  const ObDMLStmt *stmt = get_stmt();
O
oceanbase-admin 已提交
1091 1092 1093 1094 1095 1096
  if (OB_ISNULL(stmt)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("Get unexpected null", K(ret), K(stmt));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < semi_infos.count(); ++i) {
    right_rel_ids.reuse();
W
wangzelin.wzl 已提交
1097 1098
    SemiInfo *info = semi_infos.at(i);
    ConflictDetector *detector = NULL;
O
oceanbase-admin 已提交
1099 1100 1101
    if (OB_ISNULL(info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null semi info", K(ret));
W
wangzelin.wzl 已提交
1102
      //1. create conflict detector
O
oceanbase-admin 已提交
1103 1104 1105 1106 1107 1108 1109
    } else if (OB_FAIL(ConflictDetector::build_confict(get_allocator(), detector))) {
      LOG_WARN("failed to build conflict detector", K(ret));
    } else if (OB_ISNULL(detector)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null conflict detector", K(ret));
    } else if (OB_FAIL(detector->L_DS_.add_members(left_rel_ids))) {
      LOG_WARN("failed to add members", K(ret));
O
obdev 已提交
1110
    } else if (OB_FAIL(stmt->get_table_rel_ids(info->right_table_id_, right_rel_ids))) {
O
oceanbase-admin 已提交
1111 1112 1113 1114 1115 1116 1117 1118
      LOG_WARN("failed to get table ids", K(ret));
    } else if (OB_FAIL(detector->R_DS_.add_members(right_rel_ids))) {
      LOG_WARN("failed to add members", K(ret));
    } else if (OB_FAIL(semi_join_detectors.push_back(detector))) {
      LOG_WARN("failed to push back detector", K(ret));
    } else {
      detector->join_info_.join_type_ = info->join_type_;
      // 2. add equal join conditions
W
wangzelin.wzl 已提交
1119
      ObRawExpr *expr = NULL;
O
oceanbase-admin 已提交
1120 1121 1122 1123
      for (int64_t j = 0; OB_SUCC(ret) && j < info->semi_conditions_.count(); ++j) {
        if (OB_ISNULL(expr = info->semi_conditions_.at(j))) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("unexpected null", K(ret), K(expr));
1124 1125
        } else if (OB_FAIL(adjust_expr_with_onetime(expr))) {
          LOG_WARN("failed to try replace onetime subquery", K(ret));
O
oceanbase-admin 已提交
1126 1127
        } else if (OB_FAIL(detector->join_info_.table_set_.add_members(expr->get_relation_ids()))) {
          LOG_WARN("failed to add members", K(ret));
W
wangzelin.wzl 已提交
1128
        } else if (OB_FAIL(detector->join_info_.where_conditions_.push_back(expr))) {
O
oceanbase-admin 已提交
1129 1130
          LOG_WARN("failed to push back exprs", K(ret));
        } else if (expr->has_flag(IS_JOIN_COND) &&
W
wangzelin.wzl 已提交
1131
                   OB_FAIL(detector->join_info_.equal_join_conditions_.push_back(expr))) {
O
oceanbase-admin 已提交
1132 1133 1134 1135 1136
          LOG_WARN("failed to push back qual", K(ret));
        }
      }
      // 3. add other infos to conflict detector
      if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
1137 1138
      } else if (OB_FAIL(detector->L_TES_.intersect(detector->join_info_.table_set_,
                                                    detector->L_DS_))) {
O
oceanbase-admin 已提交
1139
        LOG_WARN("failed to generate L-TES", K(ret));
W
wangzelin.wzl 已提交
1140 1141
      } else if (OB_FAIL(detector->R_TES_.intersect(detector->join_info_.table_set_,
                                                    detector->R_DS_))) {
O
oceanbase-admin 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        LOG_WARN("failed to generate R-TES", K(ret));
      } else if (detector->join_info_.table_set_.overlap(detector->L_DS_) &&
                 detector->join_info_.table_set_.overlap(detector->R_DS_)) {
        detector->is_degenerate_pred_ = false;
        detector->is_commutative_ = COMM_PROPERTY[detector->join_info_.join_type_];
      } else {
        detector->is_degenerate_pred_ = true;
        detector->is_commutative_ = COMM_PROPERTY[detector->join_info_.join_type_];
      }
    }
W
wangzelin.wzl 已提交
1152
    // 4. 生成冲突规则
O
oceanbase-admin 已提交
1153
    for (int64_t j = 0; OB_SUCC(ret) && j < inner_join_detectors.count(); ++j) {
W
wangzelin.wzl 已提交
1154 1155 1156 1157
      if (OB_FAIL(generate_conflict_rule(detector,
                                         inner_join_detectors.at(j),
                                         true,
                                         detector->CR_))) {
O
oceanbase-admin 已提交
1158 1159 1160 1161 1162 1163 1164
        LOG_WARN("failed to generate conflict rule", K(ret));
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1165 1166 1167 1168
int ObLogPlan::generate_inner_join_detectors(const ObIArray<TableItem*> &table_items,
                                            ObIArray<ObRawExpr*> &quals,
                                            ObIArray<ObJoinOrder *> &baserels,
                                            ObIArray<ConflictDetector*> &inner_join_detectors)
O
oceanbase-admin 已提交
1169 1170 1171 1172 1173
{
  int ret = OB_SUCCESS;
  ObSEArray<ConflictDetector*, 8> outer_join_detectors;
  ObSEArray<ObRawExpr*, 4> all_table_filters;
  ObSEArray<ObRawExpr*, 4> table_filters;
W
wangzelin.wzl 已提交
1174
  ObRelIds all_table_ids;
O
oceanbase-admin 已提交
1175 1176 1177
  ObRelIds table_ids;
  if (OB_FAIL(split_or_quals(table_items, quals))) {
    LOG_WARN("failed to split or quals", K(ret));
W
wangzelin.wzl 已提交
1178 1179
  } else if (OB_FAIL(get_table_ids(table_items, all_table_ids))) {
    LOG_WARN("failed to get table ids", K(ret));
O
oceanbase-admin 已提交
1180
  }
W
wangzelin.wzl 已提交
1181
  //1. 生成单个table item内部的冲突规则
O
oceanbase-admin 已提交
1182 1183 1184 1185 1186 1187
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
    table_filters.reuse();
    table_ids.reuse();
    if (OB_FAIL(get_table_ids(table_items.at(i), table_ids))) {
      LOG_WARN("failed to get table ids", K(ret));
    }
W
wangzelin.wzl 已提交
1188
    //找到table item的过滤谓词
O
oceanbase-admin 已提交
1189
    for (int64_t j = 0; OB_SUCC(ret) && j < quals.count(); ++j) {
W
wangzelin.wzl 已提交
1190
      ObRawExpr *expr = quals.at(j);
O
oceanbase-admin 已提交
1191 1192 1193
      if (OB_ISNULL(expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null expr", K(ret));
W
wangzelin.wzl 已提交
1194 1195 1196
      } else if (!expr->get_relation_ids().is_subset(table_ids) ||
                  expr->has_flag(CNT_SUB_QUERY)) {
        //do nothing
O
oceanbase-admin 已提交
1197 1198 1199 1200 1201 1202 1203
      } else if (OB_FAIL(table_filters.push_back(expr))) {
        LOG_WARN("failed to push back expr", K(ret));
      } else if (OB_FAIL(all_table_filters.push_back(expr))) {
        LOG_WARN("failed to push back expr", K(ret));
      }
    }
    if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
1204 1205 1206 1207
      if (OB_FAIL(generate_outer_join_detectors(table_items.at(i),
                                                table_filters,
                                                baserels,
                                                outer_join_detectors))) {
O
oceanbase-admin 已提交
1208 1209 1210 1211
        LOG_WARN("failed to generate outer join detectors", K(ret));
      }
    }
  }
W
wangzelin.wzl 已提交
1212 1213 1214
  //2. 生成from item之间的inner join的冲突检测器
  ObRawExpr *expr = NULL;
  ConflictDetector *detector = NULL;
O
oceanbase-admin 已提交
1215 1216 1217 1218 1219 1220
  ObSEArray<ObRawExpr*, 4> join_conditions;
  for (int64_t i = 0; OB_SUCC(ret) && i < quals.count(); ++i) {
    if (OB_ISNULL(expr = quals.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null expr", K(ret));
    } else if (ObOptimizerUtil::find_item(all_table_filters, expr)) {
W
wangzelin.wzl 已提交
1221
      //do nothing
O
oceanbase-admin 已提交
1222 1223
    } else if (OB_FAIL(join_conditions.push_back(expr))) {
      LOG_WARN("failed to push back expr", K(ret));
W
wangzelin.wzl 已提交
1224 1225 1226
    } else if (OB_FAIL(find_inner_conflict_detector(inner_join_detectors,
                                                    expr->get_relation_ids(),
                                                    detector))) {
O
oceanbase-admin 已提交
1227 1228 1229 1230 1231 1232 1233
      LOG_WARN("failed to find conflict detector", K(ret));
    } else if (NULL == detector) {
      if (OB_FAIL(ConflictDetector::build_confict(get_allocator(), detector))) {
        LOG_WARN("failed to build conflict detector", K(ret));
      } else if (OB_ISNULL(detector)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null detector", K(ret));
W
wangzelin.wzl 已提交
1234
      } else if (OB_FAIL(detector->join_info_.where_conditions_.push_back(expr))) {
O
oceanbase-admin 已提交
1235
        LOG_WARN("failed to push back expr", K(ret));
W
wangzelin.wzl 已提交
1236 1237
      } else if (expr->has_flag(IS_JOIN_COND) &&
                  OB_FAIL(detector->join_info_.equal_join_conditions_.push_back(expr))) {
O
oceanbase-admin 已提交
1238 1239 1240
        LOG_WARN("failed to push back qual", K(ret));
      } else if (OB_FAIL(detector->join_info_.table_set_.add_members(expr->get_relation_ids()))) {
        LOG_WARN("failed to add members", K(ret));
O
obdev 已提交
1241 1242 1243
      } else if (expr->has_flag(CNT_SUB_QUERY) &&
                 OB_FAIL(detector->join_info_.table_set_.add_members(all_table_ids))) {
        LOG_WARN("failed to add members", K(ret));
O
oceanbase-admin 已提交
1244 1245 1246
      } else if (OB_FAIL(inner_join_detectors.push_back(detector))) {
        LOG_WARN("failed to push back detector", K(ret));
      } else {
W
wangzelin.wzl 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        //检查连接谓词是否是退化谓词
        if (detector->join_info_.table_set_.num_members() > 1) {
          detector->is_degenerate_pred_ = false;
        } else {
          detector->is_degenerate_pred_ = true;
          if (OB_FAIL(detector->L_DS_.add_members(all_table_ids))) {
            LOG_WARN("failed to generate R-TES", K(ret));
          } else if (OB_FAIL(detector->R_DS_.add_members(all_table_ids))) {
            LOG_WARN("failed to generate R-TES", K(ret));
          }
        }
O
oceanbase-admin 已提交
1258 1259 1260
        detector->is_commutative_ = COMM_PROPERTY[INNER_JOIN];
        detector->join_info_.join_type_ = INNER_JOIN;
      }
W
wangzelin.wzl 已提交
1261
    } else if (OB_FAIL(detector->join_info_.where_conditions_.push_back(expr))) {
O
oceanbase-admin 已提交
1262
      LOG_WARN("failed to push back expr", K(ret));
W
wangzelin.wzl 已提交
1263 1264 1265
    } else if (expr->has_flag(IS_JOIN_COND) &&
               OB_FAIL(detector->join_info_.equal_join_conditions_.push_back(expr))) {
        LOG_WARN("failed to push back qual", K(ret));
O
obdev 已提交
1266 1267 1268
    } else if (expr->has_flag(CNT_SUB_QUERY) &&
               OB_FAIL(detector->join_info_.table_set_.add_members(all_table_ids))) {
      LOG_WARN("failed to add members", K(ret));
1269
    }
O
oceanbase-admin 已提交
1270
  }
W
wangzelin.wzl 已提交
1271
  //3. 生成inner join的冲突规则
O
oceanbase-admin 已提交
1272
  for (int64_t i = 0; OB_SUCC(ret) && i < inner_join_detectors.count(); ++i) {
W
wangzelin.wzl 已提交
1273 1274 1275 1276
    ConflictDetector *inner_detector = inner_join_detectors.at(i);
    const ObRelIds &table_set = inner_detector->join_info_.table_set_;
    //对于inner join来说,满足交换律,所以不需要区分L_TES、R_TES
    //为了方便之后统一applicable算法,L_TES、R_TES都等于SES
O
oceanbase-admin 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285
    if (OB_ISNULL(inner_detector)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null detector", K(ret));
    }
    for (int64_t j = 0; OB_SUCC(ret) && j < table_items.count(); ++j) {
      table_ids.reuse();
      if (OB_FAIL(get_table_ids(table_items.at(j), table_ids))) {
        LOG_WARN("failed to get table ids", K(ret));
      } else if (!table_ids.overlap(table_set)) {
W
wangzelin.wzl 已提交
1286
        //do nothing
O
oceanbase-admin 已提交
1287 1288 1289 1290 1291 1292
      } else if (OB_FAIL(inner_detector->L_DS_.add_members(table_ids))) {
        LOG_WARN("failed to generate R-TES", K(ret));
      } else if (OB_FAIL(inner_detector->R_DS_.add_members(table_ids))) {
        LOG_WARN("failed to generate R-TES", K(ret));
      }
    }
W
wangzelin.wzl 已提交
1293 1294
    //对于inner join来说,满足交换律,所以不需要区分L_TES、R_TES
    //为了方便之后统一applicable算法,L_TES、R_TES都等于SES
O
oceanbase-admin 已提交
1295 1296 1297 1298 1299 1300 1301
    if (OB_FAIL(ret)) {
    } else if (OB_FAIL(inner_detector->L_TES_.add_members(table_set))) {
      LOG_WARN("failed to generate L-TES", K(ret));
    } else if (OB_FAIL(inner_detector->R_TES_.add_members(table_set))) {
      LOG_WARN("failed to generate R-TES", K(ret));
    }
    for (int64_t j = 0; OB_SUCC(ret) && j < outer_join_detectors.count(); ++j) {
W
wangzelin.wzl 已提交
1302
      ConflictDetector *outer_detector = outer_join_detectors.at(j);
O
oceanbase-admin 已提交
1303 1304 1305 1306
      if (OB_ISNULL(outer_detector)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null detector", K(ret));
      } else if (!IS_OUTER_OR_CONNECT_BY_JOIN(outer_detector->join_info_.join_type_)) {
W
wangzelin.wzl 已提交
1307 1308 1309 1310 1311
        //inner join与inner join之前没有冲突,do nothing
      } else if (OB_FAIL(generate_conflict_rule(inner_detector,
                                                outer_detector,
                                                true,
                                                inner_detector->CR_))) {
O
oceanbase-admin 已提交
1312
        LOG_WARN("failed to generate conflict rule", K(ret));
W
wangzelin.wzl 已提交
1313 1314 1315 1316
      } else if (OB_FAIL(generate_conflict_rule(inner_detector,
                                                outer_detector,
                                                false,
                                                inner_detector->CR_))) {
O
oceanbase-admin 已提交
1317 1318 1319 1320
        LOG_WARN("failed to generate conflict rule", K(ret));
      }
    }
  }
W
wangzelin.wzl 已提交
1321
  //4. 生成可选的笛卡尔积
O
oceanbase-admin 已提交
1322 1323 1324
  if (OB_SUCC(ret)) {
    if (OB_FAIL(append(inner_join_detectors, outer_join_detectors))) {
      LOG_WARN("failed to append detectors", K(ret));
W
wangzelin.wzl 已提交
1325 1326 1327
    } else if (OB_FAIL(generate_cross_product_detector(table_items,
                                                       join_conditions,
                                                       inner_join_detectors))) {
O
oceanbase-admin 已提交
1328 1329 1330 1331 1332 1333
      LOG_WARN("failed to generate cross product detector", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
int ObLogPlan::mock_base_rel_detectors(ObJoinOrder *&base_rel)
{
  int ret = OB_SUCCESS;
  ConflictDetector *detector = NULL;
  // mock a conflict detector whose join info's where_condition
  // is base rel's base table pushdown filter, and add it into
  // used_conflict_detector, which will be used for width est.
  // see ObJoinOrder::est_join_width() condition exclusion for detail
  if (OB_ISNULL(base_rel)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid input", K(ret));
  } else if (base_rel->get_restrict_infos().empty() ||
             !base_rel->get_conflict_detectors().empty()) {
    // do nothing
  } else if (OB_FAIL(ConflictDetector::build_confict(get_allocator(), detector))) {
    LOG_WARN("failed to build conflict detector", K(ret));
  } else if (OB_ISNULL(detector)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null detector", K(ret));
  } else if (OB_FAIL(append_array_no_dup(detector->join_info_.where_conditions_,
                                         base_rel->get_restrict_infos()))) {
    LOG_WARN("failed to push back expr", K(ret));
  } else if (OB_FAIL(add_var_to_array_no_dup(base_rel->get_conflict_detectors(), detector))) {
    LOG_WARN("failed to append into used conflict detectors", K(ret));
  } else {/*do nothing*/}
  return ret;
}

int ObLogPlan::generate_outer_join_detectors(TableItem *table_item,
                                             ObIArray<ObRawExpr*> &table_filter,
                                             ObIArray<ObJoinOrder *> &baserels,
                                             ObIArray<ConflictDetector*> &outer_join_detectors)
O
oceanbase-admin 已提交
1366 1367
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1368
  JoinedTable *joined_table = static_cast<JoinedTable*>(table_item);
O
oceanbase-admin 已提交
1369 1370 1371 1372
  if (OB_ISNULL(table_item)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null table item", K(ret));
  } else if (!table_item->is_joined_table()) {
W
wangzelin.wzl 已提交
1373
    //如果是基表,直接把过程谓词分发到join order里
O
oceanbase-admin 已提交
1374 1375 1376 1377
    if (OB_FAIL(distribute_quals(table_item, table_filter, baserels))) {
      LOG_WARN("failed to distribute table filter", K(ret));
    }
  } else if (INNER_JOIN == joined_table->joined_type_) {
W
wangzelin.wzl 已提交
1378 1379
    //抚平joined table内部的inner join
    ObSEArray<TableItem *, 4> table_items;
O
oceanbase-admin 已提交
1380 1381 1382
    ObSEArray<ConflictDetector*, 4> detectors;
    if (OB_FAIL(flatten_inner_join(table_item, table_filter, table_items))) {
      LOG_WARN("failed to flatten inner join", K(ret));
W
wangzelin.wzl 已提交
1383 1384 1385 1386
    } else if (OB_FAIL(generate_inner_join_detectors(table_items,
                                                     table_filter,
                                                     baserels,
                                                     detectors))) {
O
oceanbase-admin 已提交
1387 1388 1389 1390
      LOG_WARN("failed to generate inner join detectors", K(ret));
    } else if (OB_FAIL(append(outer_join_detectors, detectors))) {
      LOG_WARN("failed to append detectors", K(ret));
    }
W
wangzelin.wzl 已提交
1391 1392 1393 1394
  } else if (OB_FAIL(inner_generate_outer_join_detectors(joined_table,
                                                         table_filter,
                                                         baserels,
                                                         outer_join_detectors))) {
O
oceanbase-admin 已提交
1395 1396 1397 1398 1399
    LOG_WARN("failed to generate outer join detectors", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
1400 1401 1402
int ObLogPlan::distribute_quals(TableItem *table_item,
                                const ObIArray<ObRawExpr*> &table_filter,
                                ObIArray<ObJoinOrder *> &baserels)
O
oceanbase-admin 已提交
1403 1404
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1405
  ObJoinOrder *cur_rel = NULL;
O
oceanbase-admin 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414
  ObSEArray<int64_t, 8> relids;
  ObRelIds table_ids;
  if (OB_ISNULL(table_item)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("Get unexpected null", K(ret), K(table_item));
  } else if (OB_FAIL(get_table_ids(table_item, table_ids))) {
    LOG_WARN("failed to get table ids", K(ret));
  } else if (OB_FAIL(table_ids.to_array(relids))) {
    LOG_WARN("to_array error", K(ret));
W
wangzelin.wzl 已提交
1415
  }  else if (1 != relids.count()) {
O
oceanbase-admin 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("expect basic table item", K(ret));
  } else if (OB_FAIL(find_base_rel(baserels, relids.at(0), cur_rel))) {
    LOG_WARN("find_base_rel fails", K(ret));
  } else if (OB_ISNULL(cur_rel)) {
    ret = OB_SQL_OPT_ERROR;
    LOG_WARN("failed to distribute qual to rel", K(baserels), K(relids), K(ret));
  } else if (OB_FAIL(append(cur_rel->get_restrict_infos(), table_filter))) {
    LOG_WARN("failed to distribute qual to rel", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
1429 1430 1431
int ObLogPlan::flatten_inner_join(TableItem *table_item,
                                  ObIArray<ObRawExpr*> &table_filter,
                                  ObIArray<TableItem*> &table_items)
O
oceanbase-admin 已提交
1432 1433
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1434
  JoinedTable *joined_table = static_cast<JoinedTable*>(table_item);
O
obdev 已提交
1435
  ObSEArray<ObRawExpr*, 16> new_conditions;
O
oceanbase-admin 已提交
1436 1437 1438
  if (OB_ISNULL(table_item)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null table item", K(ret));
W
wangzelin.wzl 已提交
1439 1440
  } else if (!table_item->is_joined_table() ||
             INNER_JOIN != joined_table->joined_type_) {
O
oceanbase-admin 已提交
1441
    ret = table_items.push_back(table_item);
W
wangzelin.wzl 已提交
1442 1443 1444
  } else if (OB_FAIL(SMART_CALL(flatten_inner_join(joined_table->left_table_,
                                                   table_filter,
                                                   table_items)))) {
O
oceanbase-admin 已提交
1445
    LOG_WARN("failed to faltten inner join", K(ret));
W
wangzelin.wzl 已提交
1446 1447 1448
  } else if (OB_FAIL(SMART_CALL(flatten_inner_join(joined_table->right_table_,
                                                   table_filter,
                                                   table_items)))) {
O
oceanbase-admin 已提交
1449
    LOG_WARN("failed to faltten inner join", K(ret));
O
obdev 已提交
1450 1451 1452 1453
  } else if (OB_FAIL(adjust_exprs_with_onetime(joined_table->join_conditions_,
                                               new_conditions))) {
    LOG_WARN("failed to adjust join conditions with onetime", K(ret));
  } else if (OB_FAIL(append(table_filter, new_conditions))) {
O
oceanbase-admin 已提交
1454 1455 1456 1457 1458
    LOG_WARN("failed to append exprs", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
1459 1460 1461 1462
int ObLogPlan::inner_generate_outer_join_detectors(JoinedTable *joined_table,
                                                  ObIArray<ObRawExpr*> &table_filter,
                                                  ObIArray<ObJoinOrder *> &baserels,
                                                  ObIArray<ConflictDetector*> &outer_join_detectors)
O
oceanbase-admin 已提交
1463 1464 1465 1466 1467
{
  int ret = OB_SUCCESS;
  ObRelIds table_set;
  ObRelIds left_table_ids;
  ObRelIds right_table_ids;
W
wangzelin.wzl 已提交
1468 1469 1470 1471
  ConflictDetector *detector = NULL;
  ObSEArray<ObRawExpr *, 4> left_quals;
  ObSEArray<ObRawExpr *, 4> right_quals;
  ObSEArray<ObRawExpr *, 4> join_quals;
O
oceanbase-admin 已提交
1472 1473 1474 1475 1476 1477 1478
  ObSEArray<ConflictDetector*, 4> left_detectors;
  ObSEArray<ConflictDetector*, 4> right_detectors;
  if (OB_ISNULL(joined_table)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null table item", K(ret));
  } else if (OB_FAIL(get_table_ids(joined_table->join_conditions_, table_set))) {
    LOG_WARN("failed to get table ids", K(ret));
W
wangzelin.wzl 已提交
1479 1480 1481 1482 1483
    //1. pushdown where condition
  } else if (OB_FAIL(pushdown_where_filters(joined_table,
                                            table_filter,
                                            left_quals,
                                            right_quals))) {
O
oceanbase-admin 已提交
1484
    LOG_WARN("failed to pushdown where filters", K(ret));
W
wangzelin.wzl 已提交
1485 1486 1487 1488 1489
    //2. pushdown on condition
  } else if (OB_FAIL(pushdown_on_conditions(joined_table,
                                            left_quals,
                                            right_quals,
                                            join_quals))) {
O
oceanbase-admin 已提交
1490
    LOG_WARN("failed to pushdown on conditions", K(ret));
W
wangzelin.wzl 已提交
1491 1492 1493 1494 1495
    //3. generate left child detectors
  } else if (OB_FAIL(generate_outer_join_detectors(joined_table->left_table_,
                                                    left_quals,
                                                    baserels,
                                                    left_detectors))) {
O
oceanbase-admin 已提交
1496 1497 1498
    LOG_WARN("failed to generate outer join detectors", K(ret));
  } else if (OB_FAIL(append(outer_join_detectors, left_detectors))) {
    LOG_WARN("failed to append detectors", K(ret));
W
wangzelin.wzl 已提交
1499 1500 1501 1502 1503
    //4. generate right child detectors
  } else if (OB_FAIL(generate_outer_join_detectors(joined_table->right_table_,
                                                    right_quals,
                                                    baserels,
                                                    right_detectors))) {
O
oceanbase-admin 已提交
1504 1505 1506
    LOG_WARN("failed to generate outer join detectors", K(ret));
  } else if (OB_FAIL(append(outer_join_detectors, right_detectors))) {
    LOG_WARN("failed to append detectors", K(ret));
W
wangzelin.wzl 已提交
1507 1508 1509
    //5. create outer join detector
  } else if (OB_FAIL(ConflictDetector::build_confict(get_allocator(),
                                                      detector))) {
O
oceanbase-admin 已提交
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    LOG_WARN("failed to build conflict detector", K(ret));
  } else if (OB_ISNULL(detector)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null detector", K(ret));
  } else if (OB_FAIL(get_table_ids(joined_table->left_table_, left_table_ids))) {
    LOG_WARN("failed to get table ids", K(ret));
  } else if (OB_FAIL(get_table_ids(joined_table->right_table_, right_table_ids))) {
    LOG_WARN("failed to get table ids", K(ret));
  } else if (OB_FAIL(detector->join_info_.table_set_.add_members(table_set))) {
    LOG_WARN("failed to add members", K(ret));
  } else if (OB_FAIL(detector->L_DS_.add_members(left_table_ids))) {
    LOG_WARN("failed to add members", K(ret));
  } else if (OB_FAIL(detector->R_DS_.add_members(right_table_ids))) {
    LOG_WARN("failed to add members", K(ret));
W
wangzelin.wzl 已提交
1524 1525
  } else if (OB_FAIL(append(detector->join_info_.on_conditions_,
                            join_quals))) {
O
oceanbase-admin 已提交
1526 1527 1528 1529
    LOG_WARN("failed to append exprs", K(ret));
  } else if (OB_FAIL(outer_join_detectors.push_back(detector))) {
    LOG_WARN("failed to push back detecotor", K(ret));
  } else {
W
wangzelin.wzl 已提交
1530
    //检查连接是否具备交换律
O
oceanbase-admin 已提交
1531 1532
    detector->is_commutative_ = COMM_PROPERTY[joined_table->joined_type_];
    detector->join_info_.join_type_ = joined_table->joined_type_;
W
wangzelin.wzl 已提交
1533 1534 1535
    //检查连接谓词是否是退化谓词
    if (table_set.overlap(left_table_ids) &&
        table_set.overlap(right_table_ids)) {
O
oceanbase-admin 已提交
1536 1537 1538 1539
      detector->is_degenerate_pred_ = false;
    } else {
      detector->is_degenerate_pred_ = true;
    }
W
wangzelin.wzl 已提交
1540
    //connect by join强制依赖所有的表,与连接谓词无关
O
oceanbase-admin 已提交
1541 1542 1543 1544 1545 1546 1547 1548
    if (CONNECT_BY_JOIN == joined_table->joined_type_) {
      if (OB_FAIL(detector->join_info_.table_set_.add_members(left_table_ids))) {
        LOG_WARN("failed to add members", K(ret));
      } else if (OB_FAIL(detector->join_info_.table_set_.add_members(right_table_ids))) {
        LOG_WARN("failed to add members", K(ret));
      }
    }
    if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
1549 1550
      if (OB_FAIL(detector->L_TES_.intersect(detector->join_info_.table_set_,
                                             detector->L_DS_))) {
O
oceanbase-admin 已提交
1551
        LOG_WARN("failed to generate L-TES", K(ret));
W
wangzelin.wzl 已提交
1552 1553
      } else if (OB_FAIL(detector->R_TES_.intersect(detector->join_info_.table_set_,
                                                    detector->R_DS_))) {
O
oceanbase-admin 已提交
1554 1555 1556
        LOG_WARN("failed to generate R-TES", K(ret));
      }
    }
W
wangzelin.wzl 已提交
1557 1558
    for (int64_t i = 0; OB_SUCC(ret) && i < join_quals.count(); ++i) {
      ObRawExpr *expr = join_quals.at(i);
O
oceanbase-admin 已提交
1559 1560 1561
      if (OB_ISNULL(expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null expr", K(ret));
W
wangzelin.wzl 已提交
1562 1563
      } else if (expr->has_flag(IS_JOIN_COND) &&
                  OB_FAIL(detector->join_info_.equal_join_conditions_.push_back(expr))) {
O
oceanbase-admin 已提交
1564 1565 1566
        LOG_WARN("failed to push back qual", K(ret));
      }
    }
W
wangzelin.wzl 已提交
1567
    //6. generate conflict rules
O
oceanbase-admin 已提交
1568
    for (int64_t i = 0; OB_SUCC(ret) && i < left_detectors.count(); ++i) {
W
wangzelin.wzl 已提交
1569 1570 1571 1572
      if (OB_FAIL(generate_conflict_rule(detector,
                                          left_detectors.at(i),
                                          true,
                                          detector->CR_))) {
O
oceanbase-admin 已提交
1573 1574 1575 1576
        LOG_WARN("failed to generate conflict rule", K(ret));
      }
    }
    for (int64_t i = 0; OB_SUCC(ret) && i < right_detectors.count(); ++i) {
W
wangzelin.wzl 已提交
1577 1578 1579 1580
      if (OB_FAIL(generate_conflict_rule(detector,
                                          right_detectors.at(i),
                                          false,
                                          detector->CR_))) {
O
oceanbase-admin 已提交
1581 1582 1583
        LOG_WARN("failed to generate conflict rule", K(ret));
      }
    }
W
wangzelin.wzl 已提交
1584
    //7. generate conflict detector for table filter
O
oceanbase-admin 已提交
1585 1586 1587 1588 1589 1590
    if (OB_SUCC(ret) && !table_filter.empty()) {
      if (OB_FAIL(ConflictDetector::build_confict(get_allocator(), detector))) {
        LOG_WARN("failed to build conflict detector", K(ret));
      } else if (OB_ISNULL(detector)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null detector", K(ret));
W
wangzelin.wzl 已提交
1591
      } else if (OB_FAIL(append(detector->join_info_.where_conditions_, table_filter))) {
O
oceanbase-admin 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
        LOG_WARN("failed to append expr", K(ret));
      } else if (OB_FAIL(detector->join_info_.table_set_.add_members(left_table_ids))) {
        LOG_WARN("failed to add members", K(ret));
      } else if (OB_FAIL(detector->join_info_.table_set_.add_members(right_table_ids))) {
        LOG_WARN("failed to add members", K(ret));
      } else if (OB_FAIL(outer_join_detectors.push_back(detector))) {
        LOG_WARN("failed to push back detector", K(ret));
      } else {
        detector->is_degenerate_pred_ = false;
        detector->is_commutative_ = COMM_PROPERTY[INNER_JOIN];
        detector->join_info_.join_type_ = INNER_JOIN;
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1609 1610 1611 1612
int ObLogPlan::pushdown_where_filters(JoinedTable* joined_table,
                                      ObIArray<ObRawExpr*> &table_filter,
                                      ObIArray<ObRawExpr*> &left_quals,
                                      ObIArray<ObRawExpr*> &right_quals)
O
oceanbase-admin 已提交
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(joined_table)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null param", K(ret));
  } else {
    ObRelIds left_table_set;
    ObRelIds right_table_set;
    int64_t N = table_filter.count();
    ObSEArray<ObRawExpr*, 4> new_quals;
    ObJoinType join_type = joined_table->joined_type_;
    if (OB_FAIL(get_table_ids(joined_table->left_table_, left_table_set))) {
      LOG_WARN("failed to get table ids", K(ret));
    } else if (OB_FAIL(get_table_ids(joined_table->right_table_, right_table_set))) {
      LOG_WARN("failed to get table ids", K(ret));
    }
    for (int64_t i = 0; OB_SUCC(ret) && i < N; i++) {
W
wangzelin.wzl 已提交
1630
      ObRawExpr *qual =  table_filter.at(i);
O
oceanbase-admin 已提交
1631 1632 1633
      if (OB_ISNULL(qual)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("null expr", K(qual), K(ret));
W
wangzelin.wzl 已提交
1634 1635 1636 1637 1638 1639 1640
      } else if (qual->has_flag(CNT_ROWNUM)) {
        if (OB_FAIL(new_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
      } else if (qual->get_relation_ids().is_empty() &&
                 !ObOptimizerUtil::has_hierarchical_expr(*qual)) {
        //where level < 2不能向下推
O
oceanbase-admin 已提交
1641 1642 1643 1644 1645
        if (OB_FAIL(left_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        } else if (OB_FAIL(right_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
W
wangzelin.wzl 已提交
1646 1647
      } else if (LEFT_OUTER_JOIN == join_type &&
                 qual->get_relation_ids().is_subset(left_table_set)) {
O
oceanbase-admin 已提交
1648 1649 1650
        if (OB_FAIL(left_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
W
wangzelin.wzl 已提交
1651 1652
      } else if (RIGHT_OUTER_JOIN == join_type &&
                 qual->get_relation_ids().is_subset(right_table_set)) {
O
oceanbase-admin 已提交
1653 1654 1655 1656 1657 1658
        if (OB_FAIL(right_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
      } else if (OB_FAIL(new_quals.push_back(qual))) {
        LOG_WARN("failed to push back expr", K(ret));
      } else if (T_OP_OR == qual->get_expr_type()) {
W
wangzelin.wzl 已提交
1659 1660 1661 1662 1663
        ObOpRawExpr *or_qual = static_cast<ObOpRawExpr *>(qual);
        if (LEFT_OUTER_JOIN == join_type
            && OB_FAIL(try_split_or_qual(left_table_set,
                                          *or_qual,
                                          left_quals))) {
O
oceanbase-admin 已提交
1664
          LOG_WARN("failed to split or qual on left table", K(ret));
W
wangzelin.wzl 已提交
1665 1666 1667 1668
        } else if (RIGHT_OUTER_JOIN ==join_type
                  && OB_FAIL(try_split_or_qual(right_table_set,
                                              *or_qual,
                                              right_quals))) {
O
oceanbase-admin 已提交
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
          LOG_WARN("failed to split or qual on right table", K(ret));
        }
      }
    }
    if (OB_SUCC(ret)) {
      if (OB_FAIL(table_filter.assign(new_quals))) {
        LOG_WARN("failed to assign exprs", K(ret));
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1682 1683 1684 1685
int ObLogPlan::pushdown_on_conditions(JoinedTable* joined_table,
                                      ObIArray<ObRawExpr*> &left_quals,
                                      ObIArray<ObRawExpr*> &right_quals,
                                      ObIArray<ObRawExpr*> &join_quals)
O
oceanbase-admin 已提交
1686 1687 1688 1689 1690 1691
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(joined_table)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null param", K(ret));
  } else {
W
wangzelin.wzl 已提交
1692
    ObRawExpr *qual = NULL;
O
oceanbase-admin 已提交
1693 1694 1695 1696
    ObRelIds left_table_set;
    ObRelIds right_table_set;
    ObJoinType join_type = joined_table->joined_type_;
    int64_t N = joined_table->join_conditions_.count();
O
obdev 已提交
1697
    ObSEArray<ObRawExpr*, 16> new_conditions;
O
oceanbase-admin 已提交
1698 1699 1700 1701
    if (OB_FAIL(get_table_ids(joined_table->left_table_, left_table_set))) {
      LOG_WARN("failed to get table ids", K(ret));
    } else if (OB_FAIL(get_table_ids(joined_table->right_table_, right_table_set))) {
      LOG_WARN("failed to get table ids", K(ret));
O
obdev 已提交
1702 1703 1704 1705 1706 1707
    } else if (OB_FAIL(adjust_exprs_with_onetime(joined_table->join_conditions_,
                                                 new_conditions))) {
      LOG_WARN("failed to adjust join conditions with onetime", K(ret));
    } else if (OB_UNLIKELY(new_conditions.count() != N)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("expr count mismatch", K(ret));
O
oceanbase-admin 已提交
1708 1709
    }
    for (int64_t i = 0; OB_SUCC(ret) && i < N; i++) {
O
obdev 已提交
1710
      if (OB_ISNULL(qual = new_conditions.at(i))) {
O
oceanbase-admin 已提交
1711 1712
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("null expr", K(qual), K(ret));
W
wangzelin.wzl 已提交
1713 1714 1715 1716 1717
      } else if (qual->has_flag(CNT_ROWNUM) || qual->has_flag(CNT_SUB_QUERY)) {
        if (OB_FAIL(join_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
      } else if (RIGHT_OUTER_JOIN == join_type &&
O
oceanbase-admin 已提交
1718 1719 1720 1721
                 qual->get_relation_ids().is_subset(left_table_set)) {
        if (OB_FAIL(left_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
W
wangzelin.wzl 已提交
1722
      } else if (LEFT_OUTER_JOIN == join_type &&
O
oceanbase-admin 已提交
1723 1724 1725 1726
                 qual->get_relation_ids().is_subset(right_table_set)) {
        if (OB_FAIL(right_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
W
wangzelin.wzl 已提交
1727 1728 1729 1730 1731 1732
      } else if (CONNECT_BY_JOIN == join_type &&
                 !qual->get_relation_ids().is_empty() &&
                 qual->get_relation_ids().is_subset(right_table_set)
                 && !qual->has_flag(CNT_LEVEL)
                 && !qual->has_flag(CNT_PRIOR)
                 && !qual->has_flag(CNT_ROWNUM)) {
O
oceanbase-admin 已提交
1733 1734 1735
        if (OB_FAIL(right_quals.push_back(qual))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
W
wangzelin.wzl 已提交
1736
      } else if (OB_FAIL(join_quals.push_back(qual))) {
O
oceanbase-admin 已提交
1737
        LOG_WARN("failed to push back expr", K(ret));
W
wangzelin.wzl 已提交
1738 1739 1740 1741 1742 1743 1744
      } else if (!qual->get_relation_ids().is_empty() &&
                  T_OP_OR == qual->get_expr_type()) {
        ObOpRawExpr *or_qual = static_cast<ObOpRawExpr *>(qual);
        if (LEFT_OUTER_JOIN == join_type &&
            OB_FAIL(try_split_or_qual(right_table_set,
                                      *or_qual,
                                      right_quals))) {
O
oceanbase-admin 已提交
1745
          LOG_WARN("failed to split or qual on right table", K(ret));
W
wangzelin.wzl 已提交
1746 1747 1748 1749
        } else if (RIGHT_OUTER_JOIN ==join_type &&
                    OB_FAIL(try_split_or_qual(left_table_set,
                                            *or_qual,
                                            left_quals))) {
O
oceanbase-admin 已提交
1750
          LOG_WARN("failed to split or qual on left table", K(ret));
W
wangzelin.wzl 已提交
1751 1752 1753 1754 1755 1756 1757
        } else if (CONNECT_BY_JOIN == join_type &&
                    !qual->has_flag(CNT_LEVEL) &&
                    !qual->has_flag(CNT_ROWNUM) &&
                    !qual->has_flag(CNT_PRIOR) &&
                    OB_FAIL(try_split_or_qual(right_table_set,
                                              *or_qual,
                                              right_quals))) {
O
oceanbase-admin 已提交
1758 1759 1760 1761 1762 1763 1764 1765
          LOG_WARN("failed to split or qual on right table", K(ret));
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1766 1767 1768
int ObLogPlan::generate_cross_product_detector(const ObIArray<TableItem*> &table_items,
                                              ObIArray<ObRawExpr*> &quals,
                                              ObIArray<ConflictDetector*> &inner_join_detectors)
O
oceanbase-admin 已提交
1769 1770
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1771 1772
  //生成笛卡尔积的冲突检测器
  //在OB中,笛卡尔积也是inner join
O
oceanbase-admin 已提交
1773
  ObRelIds table_ids;
W
wangzelin.wzl 已提交
1774
  ConflictDetector *detector = NULL;
O
oceanbase-admin 已提交
1775
  if (table_items.count() < 2) {
W
wangzelin.wzl 已提交
1776
    //do nothing
O
oceanbase-admin 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
  } else if (OB_FAIL(get_table_ids(table_items, table_ids))) {
    LOG_WARN("failed to get table ids", K(ret));
  } else if (OB_FAIL(ConflictDetector::build_confict(get_allocator(), detector))) {
    LOG_WARN("failed to build conflict detector", K(ret));
  } else if (OB_ISNULL(detector)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null conflict detector", K(ret));
  } else if (OB_FAIL(detector->L_DS_.add_members(table_ids))) {
    LOG_WARN("failed to add members", K(ret));
  } else if (OB_FAIL(detector->R_DS_.add_members(table_ids))) {
    LOG_WARN("failed to add members", K(ret));
  } else if (OB_FAIL(generate_cross_product_conflict_rule(detector, table_items, quals))) {
    LOG_WARN("failed to generate cross product conflict rule", K(ret));
  } else if (OB_FAIL(inner_join_detectors.push_back(detector))) {
    LOG_WARN("failed to push back detector", K(ret));
  } else {
    detector->join_info_.join_type_ = INNER_JOIN;
    detector->is_degenerate_pred_ = true;
    detector->is_commutative_ = true;
  }
  return ret;
}

W
wangzelin.wzl 已提交
1800 1801 1802 1803
int ObLogPlan::check_join_info(const ObRelIds &left,
                               const ObRelIds &right,
                               const ObIArray<ObRelIds> &base_table_ids,
                               bool &is_connected)
O
oceanbase-admin 已提交
1804 1805
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1806
  ObSqlBitSet<> table_ids;
O
oceanbase-admin 已提交
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
  is_connected = false;
  if (OB_FAIL(table_ids.except(left, right))) {
    LOG_WARN("failed to cal except for rel ids", K(ret));
  } else if (table_ids.is_empty()) {
    is_connected = true;
  } else {
    int64_t N = base_table_ids.count();
    for (int64_t i = 0; OB_SUCC(ret) && !is_connected && i < N; ++i) {
      if (table_ids.is_subset(base_table_ids.at(i))) {
        is_connected = true;
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1823 1824 1825
int ObLogPlan::generate_cross_product_conflict_rule(ConflictDetector *cross_product_detector,
                                                    const ObIArray<TableItem*> &table_items,
                                                    const ObIArray<ObRawExpr*> &join_conditions)
O
oceanbase-admin 已提交
1826 1827 1828 1829 1830 1831 1832 1833 1834
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(cross_product_detector)) {
    ret = OB_SUCCESS;
    LOG_WARN("unexpect null detector", K(ret));
  } else {
    ObRelIds table_ids;
    bool have_new_connect_info = true;
    ObSEArray<ObRelIds, 8> base_table_ids;
W
wangzelin.wzl 已提交
1835
    //连通图信息
O
oceanbase-admin 已提交
1836
    ObSEArray<ObRelIds, 8> connect_infos;
W
wangzelin.wzl 已提交
1837 1838
    //初始化base table,joined table看做整体
    //笛卡尔积应该在所有的joined table枚举完再枚举
O
oceanbase-admin 已提交
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
    LOG_TRACE("start generate cross product conflict rule", K(table_items), K(join_conditions));
    for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
      table_ids.reuse();
      if (OB_FAIL(get_table_ids(table_items.at(i), table_ids))) {
        LOG_WARN("failed to get table ids", K(ret));
      } else if (OB_FAIL(base_table_ids.push_back(table_ids))) {
        LOG_WARN("failed to push back rel ids", K(ret));
      } else if (OB_FAIL(connect_infos.push_back(table_ids))) {
        LOG_WARN("failed to push back rel ids", K(ret));
      }
    }
W
wangzelin.wzl 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
    /**
     * 计算连通图信息,核心算法:
     * 初始状态:每个base table为一个独立的图
     * 连通原则:如果某一个join condition引用的表对于某个图而言
     * 只增加了一张表A,那么我们认为这个图通过这个join condition
     * 连通了表A,表A加入这张表。
     * 如果某一个join condition连通了多个图,那么我们认为这些图之间是连通的,
     * 需要合并这些图。
     * 算法思想:由于每个join condition可能相互依赖,所以采用迭代算法,
     * 只要连通图的状态发生变化,就需要遍历未使用的join condition,直到
     * 连通图的状态稳定。
     */
O
oceanbase-admin 已提交
1862
    ObSqlBitSet<> used_join_conditions;
W
wangzelin.wzl 已提交
1863 1864
    ObSqlBitSet<> used_infos;
    ObSqlBitSet<> connect_tables;
O
oceanbase-admin 已提交
1865 1866
    while (have_new_connect_info) {
      have_new_connect_info = false;
W
wangzelin.wzl 已提交
1867
      //遍历未使用的join condition,检查是否连通某个图
O
oceanbase-admin 已提交
1868
      for (int64_t i = 0; OB_SUCC(ret) && i < join_conditions.count(); ++i) {
W
wangzelin.wzl 已提交
1869
        ObRawExpr *expr = join_conditions.at(i);
O
oceanbase-admin 已提交
1870
        if (used_join_conditions.has_member(i)) {
W
wangzelin.wzl 已提交
1871
          //do nothing
O
oceanbase-admin 已提交
1872 1873 1874
        } else if (OB_ISNULL(expr)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("unexpect null expr", K(ret));
O
obdev 已提交
1875 1876
        } else if (has_depend_function_table(expr->get_relation_ids())
                  || has_depend_json_table(expr->get_relation_ids())) {
W
wangzelin.wzl 已提交
1877
          //do nothing
O
oceanbase-admin 已提交
1878
        } else {
W
wangzelin.wzl 已提交
1879 1880
          used_infos.reuse();
          connect_tables.reuse();
O
oceanbase-admin 已提交
1881 1882 1883
          if (OB_FAIL(connect_tables.add_members(expr->get_relation_ids()))) {
            LOG_WARN("failed to add members", K(ret));
          }
W
wangzelin.wzl 已提交
1884
          //遍历所有的连通图,检查join condition是否连通某个图
O
oceanbase-admin 已提交
1885 1886
          for (int64_t j = 0; OB_SUCC(ret) && j < connect_infos.count(); ++j) {
            bool is_connected = false;
W
wangzelin.wzl 已提交
1887 1888 1889
            if (OB_FAIL(check_join_info(expr->get_relation_ids(),
                                        connect_infos.at(j),
                                        base_table_ids, is_connected))) {
O
oceanbase-admin 已提交
1890 1891
              LOG_WARN("failed to check join info", K(ret));
            } else if (!is_connected) {
W
wangzelin.wzl 已提交
1892
              //do nothing
O
oceanbase-admin 已提交
1893 1894 1895 1896 1897 1898
            } else if (OB_FAIL(used_infos.add_member(j))) {
              LOG_WARN("failed to add member", K(ret));
            } else if (connect_tables.add_members(connect_infos.at(j))) {
              LOG_WARN("failed to add members", K(ret));
            }
          }
W
wangzelin.wzl 已提交
1899 1900 1901 1902
          /**
           * 合并连通图,实际上并没有删除冗余的图,
           * 这个最后再统一删除,避免容器反复变更size引起数据拷贝
           */
O
oceanbase-admin 已提交
1903 1904 1905 1906 1907 1908 1909
          if (OB_SUCC(ret) && !used_infos.is_empty()) {
            have_new_connect_info = true;
            if (OB_FAIL(used_join_conditions.add_member(i))) {
              LOG_WARN("failed to add member", K(ret));
            }
            for (int64_t j = 0; OB_SUCC(ret) && j < connect_infos.count(); ++j) {
              if (!used_infos.has_member(j)) {
W
wangzelin.wzl 已提交
1910
                //do nothing
O
oceanbase-admin 已提交
1911 1912 1913 1914 1915 1916 1917 1918 1919
              } else if (OB_FAIL(connect_infos.at(j).add_members(connect_tables))) {
                LOG_WARN("failed to add members", K(ret));
              }
            }
            LOG_TRACE("succeed to add new connect info", K(*expr), K(connect_infos));
          }
        }
      }
    }
W
wangzelin.wzl 已提交
1920
    //去重
O
oceanbase-admin 已提交
1921 1922 1923
    ObSEArray<ObRelIds, 8> new_connect_infos;
    for (int64_t i = 0; OB_SUCC(ret) && i < connect_infos.count(); ++i) {
      bool find = false;
W
wangzelin.wzl 已提交
1924
      for (int64_t j =0; !find && j < new_connect_infos.count(); ++j) {
O
oceanbase-admin 已提交
1925 1926 1927 1928 1929 1930 1931 1932
        if (new_connect_infos.at(j).equal(connect_infos.at(i))) {
          find = true;
        }
      }
      if (!find) {
        ret = new_connect_infos.push_back(connect_infos.at(i));
      }
    }
W
wangzelin.wzl 已提交
1933
    //使用连通图信息生成冲突规则
O
oceanbase-admin 已提交
1934 1935
    for (int64_t i = 0; OB_SUCC(ret) && i < base_table_ids.count(); ++i) {
      if (base_table_ids.at(i).num_members() < 2) {
W
wangzelin.wzl 已提交
1936 1937 1938 1939
        //do nothing
      } else if (OB_FAIL(add_conflict_rule(base_table_ids.at(i),
                                          base_table_ids.at(i),
                                          cross_product_detector->cross_product_rule_))) {
O
oceanbase-admin 已提交
1940 1941 1942 1943 1944
        LOG_WARN("failed to add conflict rule", K(ret));
      }
    }
    for (int64_t i = 0; OB_SUCC(ret) && i < new_connect_infos.count(); ++i) {
      if (new_connect_infos.at(i).num_members() < 2) {
W
wangzelin.wzl 已提交
1945
        //do nothing
O
oceanbase-admin 已提交
1946
      } else if (OB_FAIL(add_conflict_rule(new_connect_infos.at(i),
W
wangzelin.wzl 已提交
1947 1948
                                            new_connect_infos.at(i),
                                            cross_product_detector->delay_cross_product_rule_))) {
O
oceanbase-admin 已提交
1949 1950 1951
        LOG_WARN("failed to add conflict rule", K(ret));
      }
    }
W
wangzelin.wzl 已提交
1952 1953 1954
    //为了能够延迟笛卡尔积,需要生成bushy tree info辅助join order枚举
    //例如(A inner join B on xxx) inner join (C inner join D on xxx)
    //需要生成bushy tree info(A,B,C,D)
O
oceanbase-admin 已提交
1955 1956
    for (int64_t i = 0; OB_SUCC(ret) && i < new_connect_infos.count(); ++i) {
      if (new_connect_infos.at(i).num_members() > 1) {
W
wangzelin.wzl 已提交
1957
        for (int64_t j = i+1; OB_SUCC(ret) && j < new_connect_infos.count(); ++j) {
O
oceanbase-admin 已提交
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
          if (new_connect_infos.at(j).num_members() > 1) {
            ObRelIds bushy_info;
            if (OB_FAIL(bushy_info.add_members(new_connect_infos.at(i)))) {
              LOG_WARN("failed to add members", K(ret));
            } else if (OB_FAIL(bushy_info.add_members(new_connect_infos.at(j)))) {
              LOG_WARN("failed to add members", K(ret));
            } else if (OB_FAIL(bushy_tree_infos_.push_back(bushy_info))) {
              LOG_WARN("failed to push back info", K(ret));
            }
          }
        }
      }
    }
    if (OB_SUCC(ret)) {
      if (new_connect_infos.count() == 1) {
W
wangzelin.wzl 已提交
1973
        //全连通图,意味着这个笛卡尔是冗余的,leading hint使用
O
oceanbase-admin 已提交
1974 1975 1976 1977 1978 1979 1980 1981
        cross_product_detector->is_redundancy_ = true;
      }
    }
    LOG_TRACE("update bushy tree info", K(bushy_tree_infos_));
  }
  return ret;
}

W
wangzelin.wzl 已提交
1982 1983
// 选择location
int ObLogPlan::select_location(ObIArray<ObTablePartitionInfo *> &tbl_part_info_list)
O
oceanbase-admin 已提交
1984 1985
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1986
  ObExecContext *exec_ctx = optimizer_context_.get_exec_ctx();
O
oceanbase-admin 已提交
1987
  ObSEArray<const ObTableLocation*, 1> tbl_loc_list;
W
wangzelin.wzl 已提交
1988
  ObSEArray<ObCandiTableLoc*, 1> phy_tbl_loc_info_list;
O
oceanbase-admin 已提交
1989
  if (OB_ISNULL(exec_ctx)) {
O
obdev 已提交
1990
    ret = OB_ERR_UNEXPECTED;
O
oceanbase-admin 已提交
1991 1992 1993
    LOG_ERROR("exec ctx is NULL", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < tbl_part_info_list.count(); ++i) {
W
wangzelin.wzl 已提交
1994
    ObTablePartitionInfo *tbl_part_info = tbl_part_info_list.at(i);
O
oceanbase-admin 已提交
1995 1996 1997 1998
    if (OB_ISNULL(tbl_part_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("tbl part info is NULL", K(ret), K(i), K(tbl_part_info_list.count()));
    } else if (OB_FAIL(tbl_loc_list.push_back(&tbl_part_info->get_table_location()))) {
W
wangzelin.wzl 已提交
1999 2000 2001 2002 2003 2004
      LOG_WARN("fail to push back table location list",
               K(ret), K(tbl_part_info->get_table_location()));
    } else if (OB_FAIL(phy_tbl_loc_info_list.push_back(
                &tbl_part_info->get_phy_tbl_location_info_for_update()))) {
      LOG_WARN("fail to push back phy tble loc info",
               K(ret), K(tbl_part_info->get_phy_tbl_location_info_for_update()));
O
oceanbase-admin 已提交
2005 2006 2007
    }
  }
  if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
2008 2009 2010 2011 2012 2013 2014
  } else if (OB_FAIL(ObLogPlan::select_replicas(*exec_ctx,
                                                tbl_loc_list,
                                                optimizer_context_.get_local_server_addr(),
                                                phy_tbl_loc_info_list))) {
    LOG_WARN("fail to select replicas", K(ret), K(tbl_loc_list.count()),
             K(optimizer_context_.get_local_server_addr()),
             K(phy_tbl_loc_info_list.count()));
O
oceanbase-admin 已提交
2015 2016 2017 2018
  }
  return ret;
}

W
wangzelin.wzl 已提交
2019 2020 2021 2022
int ObLogPlan::select_replicas(ObExecContext &exec_ctx,
                               const ObIArray<const ObTableLocation*> &tbl_loc_list,
                               const ObAddr &local_server,
                               ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list)
O
oceanbase-admin 已提交
2023 2024 2025 2026 2027
{
  int ret = OB_SUCCESS;
  bool is_weak = true;
  for (int64_t i = 0; OB_SUCC(ret) && is_weak && i < tbl_loc_list.count(); i++) {
    bool is_weak_read = false;
W
wangzelin.wzl 已提交
2028
    const ObTableLocation *table_location = tbl_loc_list.at(i);
O
oceanbase-admin 已提交
2029 2030 2031
    if (OB_ISNULL(table_location)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("table location is NULL", K(ret), K(i), K(tbl_loc_list.count()));
W
wangzelin.wzl 已提交
2032
    } else if (!table_location->get_loc_meta().is_weak_read_) {
O
oceanbase-admin 已提交
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
      is_weak = false;
    }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(select_replicas(exec_ctx, is_weak, local_server, phy_tbl_loc_info_list))) {
      LOG_WARN("select replicas failed", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2044 2045 2046 2047
int ObLogPlan::select_replicas(ObExecContext &exec_ctx,
                               bool is_weak,
                               const ObAddr &local_server,
                               ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list)
O
oceanbase-admin 已提交
2048 2049
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2050 2051 2052 2053
  // 计算是否为weak读
  // 当所有的location都是weak读的时候,总的才是weak读,否则就是strong
  ObSQLSessionInfo *session = exec_ctx.get_my_session();
  ObTaskExecutorCtx &task_exec_ctx = exec_ctx.get_task_exec_ctx();
O
oceanbase-admin 已提交
2054 2055 2056 2057
  bool is_hit_partition = false;
  ObFollowerFirstFeedbackType follower_first_feedback = FFF_HIT_MIN;
  int64_t route_policy_type = 0;
  bool proxy_priority_hit_support = false;
W
wangzelin.wzl 已提交
2058
  if (OB_ISNULL(session)) {
O
oceanbase-admin 已提交
2059
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
2060
    LOG_ERROR("session is NULL", K(ret), K(session));
O
oceanbase-admin 已提交
2061 2062 2063 2064 2065 2066 2067
  } else if (OB_FAIL(session->get_sys_variable(SYS_VAR_OB_ROUTE_POLICY, route_policy_type))) {
    LOG_WARN("fail to get sys variable", K(ret));
  } else {
    proxy_priority_hit_support = session->get_proxy_cap_flags().is_priority_hit_support();
  }

  if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
2068
  } else if (is_weak && !exec_ctx.get_my_session()->get_is_in_retry()) {
2069 2070
    int64_t max_read_stale_time = exec_ctx.get_my_session()->get_ob_max_read_stale_time();
    uint64_t tenant_id = exec_ctx.get_my_session()->get_effective_tenant_id();
W
wangzelin.wzl 已提交
2071 2072 2073
    if (OB_FAIL(ObLogPlan::weak_select_replicas(local_server,
                                                static_cast<ObRoutePolicyType>(route_policy_type),
                                                proxy_priority_hit_support,
2074 2075
                                                tenant_id,
                                                max_read_stale_time,
W
wangzelin.wzl 已提交
2076 2077
                                                phy_tbl_loc_info_list,
                                                is_hit_partition, follower_first_feedback))) {
O
oceanbase-admin 已提交
2078 2079 2080 2081 2082 2083 2084 2085 2086
      LOG_WARN("fail to weak select intersect replicas", K(ret), K(local_server), K(phy_tbl_loc_info_list.count()));
    } else {
      session->partition_hit().try_set_bool(is_hit_partition);
      if (FFF_HIT_MIN != follower_first_feedback) {
        if (OB_FAIL(session->set_follower_first_feedback(follower_first_feedback))) {
          LOG_WARN("fail to set_follower_first_feedback", K(follower_first_feedback), K(ret));
        }
      }
      if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
2087
        // weak读如果不命中,要刷新location cache
O
oceanbase-admin 已提交
2088
        task_exec_ctx.set_need_renew_location_cache(!is_hit_partition);
W
wangzelin.wzl 已提交
2089 2090 2091 2092 2093
        // 目前暂时没想到如何处理分布式的情况,分布式的情况一定是命中,
        // 暂时没想到办法判断是否要刷location cache。
        // 这里有可能会被多次递归到,但是按目前的选择策略,
        // 要么每次递归到这里都是命中,要么每次递归到这里都是不命中或者分布式的情况,
        // 所以只需要在不命中的时候add_need_renew_tablet_keys_distinctly就可以了。
O
oceanbase-admin 已提交
2094 2095
        if (task_exec_ctx.is_need_renew_location_cache()) {
          for (int64_t i = 0; OB_SUCC(ret) && i < phy_tbl_loc_info_list.count(); ++i) {
W
wangzelin.wzl 已提交
2096
            const ObCandiTableLoc *phy_tbl_loc_info = phy_tbl_loc_info_list.at(i);
O
oceanbase-admin 已提交
2097 2098 2099 2100
            if (OB_ISNULL(phy_tbl_loc_info)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_ERROR("phy tbl loc info is NULL", K(ret), K(i));
            } else {
W
wangzelin.wzl 已提交
2101
              const ObCandiTabletLocIArray &phy_part_loc_info_list = phy_tbl_loc_info->get_phy_part_loc_info_list();
O
oceanbase-admin 已提交
2102
              for (int64_t j = 0; OB_SUCC(ret) && j < phy_part_loc_info_list.count(); ++j) {
W
wangzelin.wzl 已提交
2103 2104 2105 2106
                const ObCandiTabletLoc &phy_part_loc_info = phy_part_loc_info_list.at(j);
                if (OB_FAIL(task_exec_ctx.add_need_renew_tablet_keys_distinctly(
                    phy_part_loc_info.get_partition_location().get_tablet_id()))) {
                  LOG_WARN("fail to add need renew partition key", K(ret));
O
oceanbase-admin 已提交
2107 2108 2109 2110 2111 2112 2113 2114
                }
              }
            }
          }
        }
      }
    }
  } else {
W
wangzelin.wzl 已提交
2115 2116
    const bool sess_in_retry = session->get_is_in_retry_for_dup_tbl(); //重试状态下不优化复制表的副本选择
    if (OB_FAIL(ObLogPlan::strong_select_replicas(local_server, phy_tbl_loc_info_list, is_hit_partition, sess_in_retry))) {
O
oceanbase-admin 已提交
2117 2118 2119
      LOG_WARN("fail to strong select replicas", K(ret), K(local_server), K(phy_tbl_loc_info_list.count()));
    } else {
      session->partition_hit().try_set_bool(is_hit_partition);
W
wangzelin.wzl 已提交
2120
      task_exec_ctx.set_need_renew_location_cache(false); // 含有strong的无论如何都不renew了
O
oceanbase-admin 已提交
2121 2122 2123 2124 2125
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2126 2127 2128 2129
int ObLogPlan::strong_select_replicas(const ObAddr &local_server,
                                      ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list,
                                      bool &is_hit_partition,
                                      bool sess_in_retry) //当前session是否在retry中
O
oceanbase-admin 已提交
2130 2131
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2132
  // 全部选主
O
oceanbase-admin 已提交
2133
  bool all_is_on_same_server = true;
W
wangzelin.wzl 已提交
2134
  ObAddr all_same_server = local_server; // 初始化为本机,如果下面所有的表的partition个数都为0的话,same_server就是本机,就会返回给客户端命中
O
oceanbase-admin 已提交
2135 2136 2137
  ObAddr cur_same_server;
  for (int64_t i = 0; OB_SUCC(ret) && i < phy_tbl_loc_info_list.count(); ++i) {
    cur_same_server.reset();
W
wangzelin.wzl 已提交
2138
    ObCandiTableLoc *phy_tbl_loc_info = phy_tbl_loc_info_list.at(i);
O
oceanbase-admin 已提交
2139 2140 2141 2142 2143
    bool is_on_same_server = false;
    if (OB_ISNULL(phy_tbl_loc_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("phy_tbl_loc_info is NULL", K(ret), K(i), K(phy_tbl_loc_info_list.count()));
    } else if (0 == phy_tbl_loc_info->get_partition_cnt()) {
W
wangzelin.wzl 已提交
2144
      // 该table的partition个数为0,跳过
O
oceanbase-admin 已提交
2145 2146
    } else {
      if (!sess_in_retry && phy_tbl_loc_info->is_duplicate_table_not_in_dml()) {
W
wangzelin.wzl 已提交
2147
        if (OB_FAIL(phy_tbl_loc_info->all_select_local_replica_or_leader(is_on_same_server, cur_same_server, local_server))) {
O
oceanbase-admin 已提交
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
          LOG_WARN("fail to all select leader", K(ret), K(*phy_tbl_loc_info));
        } else {
          LOG_TRACE("succeed to select replica for duplicate table", K(*phy_tbl_loc_info), K(is_on_same_server));
        }
      } else {
        if (OB_FAIL(phy_tbl_loc_info->all_select_leader(is_on_same_server, cur_same_server))) {
          LOG_WARN("fail to all select leader", K(ret), K(*phy_tbl_loc_info));
        }
      }
      if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
2158 2159 2160
        //do nothing...
      } else if (all_is_on_same_server) { // 还在同一个server才判断,否则已经不需要判断了
        if (is_on_same_server) { // 该表选择的所有副本在同一个server
O
oceanbase-admin 已提交
2161 2162 2163 2164 2165
          if (0 == i) {
            all_same_server = cur_same_server;
          } else if (all_same_server != cur_same_server) {
            all_is_on_same_server = false;
          }
W
wangzelin.wzl 已提交
2166
        } else { // 该表选择的所有副本不在同一个server
O
oceanbase-admin 已提交
2167 2168 2169 2170 2171 2172
          all_is_on_same_server = false;
        }
      }
    }
  }
  if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
2173
    // 当选择的所有副本在同一个server并且不是本机时,给客户端返回不命中,否则返回命中
O
oceanbase-admin 已提交
2174 2175 2176 2177 2178 2179 2180 2181 2182
    if (all_is_on_same_server && local_server != all_same_server) {
      is_hit_partition = false;
    } else {
      is_hit_partition = true;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2183 2184 2185
int ObLogPlan::weak_select_replicas(const ObAddr &local_server,
                                    ObRoutePolicyType route_type,
                                    bool proxy_priority_hit_support,
2186 2187
                                    uint64_t tenant_id,
                                    int64_t max_read_stale_time,
W
wangzelin.wzl 已提交
2188 2189 2190
                                    ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list,
                                    bool &is_hit_partition,
                                    ObFollowerFirstFeedbackType &follower_first_feedback)
O
oceanbase-admin 已提交
2191 2192
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2193 2194
  is_hit_partition = true;//当前没有办法来判断是否能选择在一台机器上,所以将该值设置为true
  ObCandiTableLoc * phy_tbl_loc_info = nullptr;
O
oceanbase-admin 已提交
2195 2196
  ObArenaAllocator allocator(ObModIds::OB_SQL_OPTIMIZER_SELECT_REPLICA);
  ObList<ObRoutePolicy::CandidateReplica, ObArenaAllocator> intersect_server_list(allocator);
W
wangzelin.wzl 已提交
2197 2198 2199 2200 2201
  SMART_VAR(ObRoutePolicy, route_policy, local_server) {
    ObRoutePolicyCtx route_policy_ctx;
    route_policy_ctx.policy_type_ = route_type;
    route_policy_ctx.consistency_level_ = WEAK;
    route_policy_ctx.is_proxy_priority_hit_support_ = proxy_priority_hit_support;
2202 2203
    route_policy_ctx.max_read_stale_time_ = max_read_stale_time;
    route_policy_ctx.tenant_id_ = tenant_id;
O
oceanbase-admin 已提交
2204

W
wangzelin.wzl 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
    if (OB_FAIL(route_policy.init())) {
      LOG_WARN("fail to init route policy", K(ret));
    }
    for (int64_t i = 0 ; OB_SUCC(ret) && i < phy_tbl_loc_info_list.count(); ++i) {
      if (OB_ISNULL(phy_tbl_loc_info = phy_tbl_loc_info_list.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("phy table loc info is NULL", K(phy_tbl_loc_info), K(i), K(ret));
      } else {
        ObCandiTabletLocIArray &phy_part_loc_info_list = phy_tbl_loc_info->get_phy_part_loc_info_list_for_update();
        for (int64_t j = 0; OB_SUCC(ret) && j < phy_part_loc_info_list.count(); ++j) {
          ObCandiTabletLoc &phy_part_loc_info = phy_part_loc_info_list.at(j);
          if (phy_part_loc_info.has_selected_replica()) {//do nothing
          } else {
            ObIArray<ObRoutePolicy::CandidateReplica> &replica_array = phy_part_loc_info.get_partition_location().get_replica_locations();
            if (OB_FAIL(route_policy.init_candidate_replicas(replica_array))) {
              LOG_WARN("fail to init candidate replicas", K(replica_array), K(ret));
2221 2222 2223
            } else if (OB_FAIL(route_policy.calculate_replica_priority(phy_part_loc_info.get_ls_id(),
                                                                       replica_array,
                                                                       route_policy_ctx))) {
W
wangzelin.wzl 已提交
2224 2225 2226 2227
              LOG_WARN("fail to calculate replica priority", K(replica_array), K(route_policy_ctx), K(ret));
            } else if (OB_FAIL(route_policy.select_replica_with_priority(route_policy_ctx, replica_array, phy_part_loc_info))) {
              LOG_WARN("fail to select replica", K(replica_array), K(ret));
            }
O
oceanbase-admin 已提交
2228 2229 2230 2231 2232
          }
        }
      }
    }

W
wangzelin.wzl 已提交
2233 2234 2235 2236 2237 2238 2239
    if (OB_FAIL(ret)) {
    } else if (OB_FAIL(route_policy.select_intersect_replica(route_policy_ctx,
                                                              phy_tbl_loc_info_list,
                                                              intersect_server_list,
                                                              is_hit_partition))) {
      LOG_WARN("fail to select intersect replica", K(route_policy_ctx), K(phy_tbl_loc_info_list), K(intersect_server_list), K(ret));
    }
O
oceanbase-admin 已提交
2240

W
wangzelin.wzl 已提交
2241 2242 2243
    if (OB_SUCC(ret)) {
      if (proxy_priority_hit_support) {
        // nothing, current doesn't support
O
oceanbase-admin 已提交
2244
      } else {
W
wangzelin.wzl 已提交
2245 2246 2247 2248 2249 2250 2251 2252 2253
        ObArenaAllocator allocator(ObModIds::OB_SQL_OPTIMIZER_SELECT_REPLICA);
        ObAddrList intersect_servers(allocator);
        if (OB_FAIL(calc_hit_partition_for_compat(phy_tbl_loc_info_list, local_server, is_hit_partition, intersect_servers))) {
          LOG_WARN("fail to calc hit partition for compat", K(ret));
        } else {
          if (is_hit_partition && route_policy.is_follower_first_route_policy_type(route_policy_ctx)) {
            if (OB_FAIL(calc_follower_first_feedback(phy_tbl_loc_info_list, local_server, intersect_servers, follower_first_feedback))) {
              LOG_WARN("fail to calc follower first feedback", K(ret));
            }
O
oceanbase-admin 已提交
2254 2255 2256 2257
          }
        }
      }
    }
W
wangzelin.wzl 已提交
2258 2259 2260 2261 2262 2263 2264 2265
    if (REACH_TIME_INTERVAL(10 * 1000 * 1000)) {//10s打印一次
        LOG_INFO("selected replica ", "intersect_server_list", intersect_server_list,
                "\n phy_tbl_loc_info_list", phy_tbl_loc_info_list,
                "\n route_policy", route_policy,
                "\n route_policy_ctx", route_policy_ctx,
                "\n follower_first_feedback", follower_first_feedback,
                "\n is_hit_partition", is_hit_partition);
    }
O
oceanbase-admin 已提交
2266 2267 2268 2269
  }
  return ret;
}

W
wangzelin.wzl 已提交
2270 2271 2272 2273
int ObLogPlan::calc_follower_first_feedback(const ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list,
                                            const ObAddr &local_server,
                                            const ObAddrList &intersect_servers,
                                            ObFollowerFirstFeedbackType &follower_first_feedback)
O
oceanbase-admin 已提交
2274 2275
{
  INIT_SUCC(ret);
W
wangzelin.wzl 已提交
2276 2277 2278 2279 2280
  // UNMERGE_FOLLOWER_FIRST反馈策略(在partition_hit为true的情况下生效)
  //
  // 1. 如果所涉及的所有partition的主都在本机,则为FFF_HIT_LEADER(相当于未命中);
  // 2. 其它情况均认为命中, 注意备优先读在非读写分离架构下才生效;
  //
O
oceanbase-admin 已提交
2281 2282 2283 2284 2285 2286
  follower_first_feedback = FFF_HIT_MIN;
  if (intersect_servers.empty()) {
    // nothing, no need feedback
  } else {
    bool is_leader_replica = true;
    for (int64_t i = 0; OB_SUCC(ret) && is_leader_replica && (i < phy_tbl_loc_info_list.count()); ++i) {
W
wangzelin.wzl 已提交
2287
      const ObCandiTableLoc *phy_tbl_loc_info = phy_tbl_loc_info_list.at(i);
O
oceanbase-admin 已提交
2288 2289 2290 2291
      if (OB_ISNULL(phy_tbl_loc_info)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("phy_tbl_loc_info is NULL", K(ret), K(i), K(phy_tbl_loc_info_list.count()));
      } else {
W
wangzelin.wzl 已提交
2292
        const ObCandiTabletLocIArray &phy_part_loc_info_list = phy_tbl_loc_info->get_phy_part_loc_info_list();
O
oceanbase-admin 已提交
2293 2294 2295 2296 2297 2298
        if (phy_part_loc_info_list.empty()) {
          // juest defense, when partition location list is empty, treat as it's not leader replica
          is_leader_replica = false;
        }
        for (int64_t j = 0; OB_SUCC(ret) && is_leader_replica && (j < phy_part_loc_info_list.count()); ++j) {
          bool found_server = false;
W
wangzelin.wzl 已提交
2299 2300 2301
          const ObCandiTabletLoc &phy_part_loc_info = phy_part_loc_info_list.at(j);
          const ObIArray<ObRoutePolicy::CandidateReplica> &replica_loc_list =
            phy_part_loc_info.get_partition_location().get_replica_locations();
O
oceanbase-admin 已提交
2302
          for (int64_t k = 0; !found_server && (k < replica_loc_list.count()); ++k) {
W
wangzelin.wzl 已提交
2303 2304
            const ObRoutePolicy::CandidateReplica &tmp_replica = replica_loc_list.at(k);
            if (local_server == tmp_replica.get_server()) {
O
oceanbase-admin 已提交
2305
              found_server = true;
W
wangzelin.wzl 已提交
2306
              is_leader_replica = (is_strong_leader(tmp_replica.get_role()));
O
oceanbase-admin 已提交
2307 2308
            }
          }
W
wangzelin.wzl 已提交
2309
          if (!found_server) { // if not found, just treat as it's not leader
O
oceanbase-admin 已提交
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
            is_leader_replica = false;
          }
        }
      }
    }

    if (is_leader_replica) {
      follower_first_feedback = FFF_HIT_LEADER;
    } else {
      // nothing, no need feedback
    }
W
wangzelin.wzl 已提交
2321 2322
    LOG_TRACE("after calc follower first feedback", K(follower_first_feedback),
              K(is_leader_replica), K(local_server), K(intersect_servers));
O
oceanbase-admin 已提交
2323 2324 2325 2326 2327
  }

  return ret;
}

W
wangzelin.wzl 已提交
2328 2329 2330 2331 2332
//该函数是为了兼容老版本proxy的hit策略,当proxy更新后可以去掉该函数
int ObLogPlan::calc_hit_partition_for_compat(const ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list,
                                             const ObAddr &local_server,
                                             bool &is_hit_partition,
                                             ObAddrList &intersect_servers)
O
oceanbase-admin 已提交
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
{
  int ret = OB_SUCCESS;
  bool can_select_local_server = false;
  is_hit_partition = false;
  if (OB_FAIL(calc_intersect_servers(phy_tbl_loc_info_list, intersect_servers))) {
    LOG_WARN("fail to calc hit partition for compat", K(ret));
  } else if (intersect_servers.empty()) {
    is_hit_partition = true;
  } else {
    ObAddrList::iterator candidate_server_list_iter = intersect_servers.begin();
    for (; OB_SUCC(ret) && !can_select_local_server && candidate_server_list_iter != intersect_servers.end();
         candidate_server_list_iter++) {
W
wangzelin.wzl 已提交
2345
      const ObAddr &candidate_server = *candidate_server_list_iter;
O
oceanbase-admin 已提交
2346 2347 2348 2349 2350 2351 2352 2353 2354
      if (local_server == candidate_server) {
        is_hit_partition = true;
        can_select_local_server = true;
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2355 2356
int ObLogPlan::calc_intersect_servers(const ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list,
                                      ObAddrList &candidate_server_list)
O
oceanbase-admin 已提交
2357 2358 2359 2360 2361 2362
{
  int ret = OB_SUCCESS;
  bool can_select_one_server = true;
  ObRoutePolicy::CandidateReplica tmp_replica;
  candidate_server_list.reset();
  for (int64_t i = 0; OB_SUCC(ret) && can_select_one_server && i < phy_tbl_loc_info_list.count(); ++i) {
W
wangzelin.wzl 已提交
2363
    const ObCandiTableLoc *phy_tbl_loc_info = phy_tbl_loc_info_list.at(i);
O
oceanbase-admin 已提交
2364 2365 2366 2367
    if (OB_ISNULL(phy_tbl_loc_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("phy_tbl_loc_info is NULL", K(ret), K(i), K(phy_tbl_loc_info_list.count()));
    } else {
W
wangzelin.wzl 已提交
2368
      const ObCandiTabletLocIArray &phy_part_loc_info_list = phy_tbl_loc_info->get_phy_part_loc_info_list();
O
oceanbase-admin 已提交
2369
      for (int64_t j = 0; OB_SUCC(ret) && can_select_one_server && j < phy_part_loc_info_list.count(); ++j) {
W
wangzelin.wzl 已提交
2370 2371 2372
        const ObCandiTabletLoc &phy_part_loc_info = phy_part_loc_info_list.at(j);
        const ObIArray<ObRoutePolicy::CandidateReplica> &replica_loc_list = phy_part_loc_info.get_partition_location().get_replica_locations();
        if (0 == i && 0 == j) { // 第一个partition
O
oceanbase-admin 已提交
2373
          for (int64_t k = 0; OB_SUCC(ret) && k < replica_loc_list.count(); ++k) {
W
wangzelin.wzl 已提交
2374
            if (OB_FAIL(candidate_server_list.push_back(replica_loc_list.at(k).get_server()))) {
O
oceanbase-admin 已提交
2375 2376 2377
              LOG_WARN("fail to push back candidate server", K(ret), K(k), K(replica_loc_list.at(k)));
            }
          }
W
wangzelin.wzl 已提交
2378
        } else { // 不是第一个partition
O
oceanbase-admin 已提交
2379
          ObAddrList::iterator candidate_server_list_iter = candidate_server_list.begin();
W
wangzelin.wzl 已提交
2380 2381
          for (; OB_SUCC(ret) && candidate_server_list_iter != candidate_server_list.end(); candidate_server_list_iter++) {
            const ObAddr &candidate_server = *candidate_server_list_iter;
O
oceanbase-admin 已提交
2382 2383
            bool has_replica = false;
            for (int64_t k = 0; OB_SUCC(ret) && !has_replica && k < replica_loc_list.count(); ++k) {
W
wangzelin.wzl 已提交
2384
              if (replica_loc_list.at(k).get_server() == candidate_server) {
O
oceanbase-admin 已提交
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
                has_replica = true;
              }
            }
            if (OB_SUCC(ret) && !has_replica) {
              if (OB_FAIL(candidate_server_list.erase(candidate_server_list_iter))) {
                LOG_WARN("fail to erase from list", K(ret), K(replica_loc_list), K(candidate_server));
              }
            }
          }
          if (OB_SUCC(ret) && candidate_server_list.empty()) {
            can_select_one_server = false;
          }
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2404 2405
int ObLogPlan::select_one_server(const ObAddr &selected_server,
                                 ObIArray<ObCandiTableLoc*> &phy_tbl_loc_info_list)
O
oceanbase-admin 已提交
2406 2407 2408
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < phy_tbl_loc_info_list.count(); ++i) {
W
wangzelin.wzl 已提交
2409
    ObCandiTableLoc *phy_tbl_loc_info = phy_tbl_loc_info_list.at(i);
O
oceanbase-admin 已提交
2410 2411 2412 2413
    if (OB_ISNULL(phy_tbl_loc_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("phy_tbl_loc_info is NULL", K(ret), K(i), K(phy_tbl_loc_info_list.count()));
    } else {
W
wangzelin.wzl 已提交
2414
      ObCandiTabletLocIArray &phy_part_loc_info_list =
O
oceanbase-admin 已提交
2415 2416
          phy_tbl_loc_info->get_phy_part_loc_info_list_for_update();
      for (int64_t j = 0; OB_SUCC(ret) && j < phy_part_loc_info_list.count(); ++j) {
W
wangzelin.wzl 已提交
2417
        ObCandiTabletLoc &phy_part_loc_info = phy_part_loc_info_list.at(j);
O
oceanbase-admin 已提交
2418
        if (phy_part_loc_info.has_selected_replica()) {
W
wangzelin.wzl 已提交
2419
          // 已经选好了,跳过
O
oceanbase-admin 已提交
2420
        } else {
W
wangzelin.wzl 已提交
2421
          const ObIArray<ObRoutePolicy::CandidateReplica> &replica_loc_list =
O
oceanbase-admin 已提交
2422 2423 2424
              phy_part_loc_info.get_partition_location().get_replica_locations();
          bool replica_is_selected = false;
          for (int64_t k = 0; OB_SUCC(ret) && !replica_is_selected && k < replica_loc_list.count(); ++k) {
W
wangzelin.wzl 已提交
2425
            if (selected_server == replica_loc_list.at(k).get_server()) {
O
oceanbase-admin 已提交
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
              if (OB_FAIL(phy_part_loc_info.set_selected_replica_idx(k))) {
                LOG_WARN("fail to set selected replica idx", K(ret), K(k), K(phy_part_loc_info));
              } else {
                replica_is_selected = true;
              }
            }
          }
          if (OB_SUCC(ret) && OB_UNLIKELY(!replica_is_selected)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_ERROR("has no selected replica", K(ret), K(selected_server), K(replica_loc_list));
          }
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2444
int ObLogPlan::init_bushy_tree_info(const ObIArray<TableItem*> &table_items)
O
oceanbase-admin 已提交
2445 2446
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2447 2448 2449 2450 2451 2452
  ObIArray<LeadingInfo> &leading_infos = log_plan_hint_.join_order_.leading_infos_;
  for (int64_t i = 0; OB_SUCC(ret) && i < leading_infos.count(); ++i) {
    const LeadingInfo &info = leading_infos.at(i);
    if (info.left_table_set_.num_members() > 1 &&
        info.right_table_set_.num_members() > 1) {
      ret = bushy_tree_infos_.push_back(info.table_set_);
O
oceanbase-admin 已提交
2453 2454 2455
    }
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
W
wangzelin.wzl 已提交
2456 2457
    if (OB_FAIL(init_bushy_tree_info_from_joined_tables(table_items.at(i)))) {
      LOG_WARN("failed to init bushy tree info", K(ret));
O
oceanbase-admin 已提交
2458 2459
    }
  }
W
wangzelin.wzl 已提交
2460 2461
  if (OB_SUCC(ret)) {
    LOG_TRACE("succeed to get bushy infos", K(bushy_tree_infos_));
O
oceanbase-admin 已提交
2462 2463 2464 2465
  }
  return ret;
}

W
wangzelin.wzl 已提交
2466
int ObLogPlan::init_bushy_tree_info_from_joined_tables(TableItem *table)
O
oceanbase-admin 已提交
2467 2468
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2469
  if (OB_ISNULL(table)) {
O
oceanbase-admin 已提交
2470
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
2471 2472 2473
    LOG_WARN("unexpect null table item", K(ret));
  } else if (!table->is_joined_table()) {
    //do nothing
O
oceanbase-admin 已提交
2474
  } else {
W
wangzelin.wzl 已提交
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
    JoinedTable *joined_table = static_cast<JoinedTable*>(table);
    if (OB_ISNULL(joined_table->left_table_) ||
        OB_ISNULL(joined_table->right_table_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null table item", K(ret));
    } else if (joined_table->left_table_->is_joined_table() &&
               joined_table->right_table_->is_joined_table()) {
      ObRelIds table_ids;
      if (OB_FAIL(get_table_ids(table, table_ids))) {
        LOG_WARN("failed to get table ids", K(ret));
      } else if (OB_FAIL(bushy_tree_infos_.push_back(table_ids))) {
        LOG_WARN("failed to push back table ids", K(ret));
O
oceanbase-admin 已提交
2487 2488
      }
    }
W
wangzelin.wzl 已提交
2489 2490 2491 2492 2493 2494 2495
    if (OB_FAIL(ret)) {
      //do nothing
    } else if (OB_FAIL(SMART_CALL(init_bushy_tree_info_from_joined_tables(joined_table->left_table_)))) {
      LOG_WARN("failed to init bushy tree infos", K(ret));
    } else if (OB_FAIL(SMART_CALL(init_bushy_tree_info_from_joined_tables(joined_table->right_table_)))) {
      LOG_WARN("failed to init bushy tree infos", K(ret));
    }
O
oceanbase-admin 已提交
2496 2497 2498 2499
  }
  return ret;
}

W
wangzelin.wzl 已提交
2500
int ObLogPlan::init_function_table_depend_info(const ObIArray<TableItem*> &table_items)
O
oceanbase-admin 已提交
2501 2502
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2503
  const ObDMLStmt *stmt = get_stmt();
O
oceanbase-admin 已提交
2504 2505 2506
  if (OB_ISNULL(stmt)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null stmt", K(ret));
W
wangzelin.wzl 已提交
2507 2508 2509 2510 2511
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
    TableItem *table = table_items.at(i);
    FunctionTableDependInfo info;
    if (OB_ISNULL(table)) {
O
oceanbase-admin 已提交
2512
      ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
2513 2514 2515 2516
      LOG_WARN("unexpect null table item", K(ret));
    } else if (!table->is_function_table()) {
      //do nothing
    } else if (OB_ISNULL(table->function_table_expr_)) {
O
oceanbase-admin 已提交
2517
      ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
2518 2519 2520 2521 2522 2523 2524 2525
      LOG_WARN("unexpect null function table expr", K(ret));
    } else if (table->function_table_expr_->get_relation_ids().is_empty()) {
      //do thing
    } else if (OB_FAIL(info.depend_table_set_.add_members(table->function_table_expr_->get_relation_ids()))) {
      LOG_WARN("failed to assign table ids", K(ret));
    } else if (OB_FALSE_IT(info.table_idx_ = stmt->get_table_bit_index(table->table_id_))) {
    } else if (OB_FAIL(function_table_depend_infos_.push_back(info))) {
      LOG_WARN("failed to push back info", K(ret));
O
oceanbase-admin 已提交
2526 2527
    }
  }
W
wangzelin.wzl 已提交
2528 2529
  if (OB_SUCC(ret)) {
    LOG_TRACE("succeed to init function table depend info", K(function_table_depend_infos_));
O
oceanbase-admin 已提交
2530 2531 2532 2533
  }
  return ret;
}

W
wangzelin.wzl 已提交
2534
int ObLogPlan::init_width_estimation_info(const ObDMLStmt *stmt)
O
oceanbase-admin 已提交
2535 2536 2537 2538
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(stmt)) {
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
    LOG_WARN("invalid input", K(ret));
  } else if (stmt->is_select_stmt()) {
    const ObSelectStmt *select_stmt = NULL;
    select_stmt = static_cast<const ObSelectStmt*>(stmt);
    // group by/rollup related info
    if (OB_FAIL(append_array_no_dup(groupby_rollup_exprs_, select_stmt->get_group_exprs()))) {
      LOG_WARN("failed to add group exprs into output exprs", K(ret));
    } else if (OB_FAIL(append_array_no_dup(groupby_rollup_exprs_, select_stmt->get_rollup_exprs()))) {
      LOG_WARN("failed to add rollup exprs into output exprs", K(ret));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < select_stmt->get_multi_rollup_items_size(); ++i) {
        ObMultiRollupItem multi_rollup_item = select_stmt->get_multi_rollup_items().at(i);
        for (int64_t j = 0; OB_SUCC(ret) && j < multi_rollup_item.rollup_list_exprs_.count(); ++j) {
          ObGroupbyExpr expr = multi_rollup_item.rollup_list_exprs_.at(j);
          for (int64_t k = 0; OB_SUCC(ret) && k < expr.groupby_exprs_.count(); ++k) {
            ObRawExpr *gby_expr = expr.groupby_exprs_.at(k);
            if (OB_ISNULL(gby_expr)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_WARN("invalid expr", K(ret));
            } else if (OB_FAIL(add_var_to_array_no_dup(groupby_rollup_exprs_, gby_expr))) {
              LOG_WARN("failed to do appending to current array", K(ret));
            }
          }
        }
      }
      for (int64_t i = 0; OB_SUCC(ret) && i < select_stmt->get_grouping_sets_items_size(); ++i) {
        ObGroupingSetsItem groupingsets_item = select_stmt->get_grouping_sets_items().at(i);
        for (int64_t j = 0; OB_SUCC(ret) && j < groupingsets_item.grouping_sets_exprs_.count(); ++j) {
          ObGroupbyExpr expr = groupingsets_item.grouping_sets_exprs_.at(j);
          for (int64_t k = 0; OB_SUCC(ret) && k < expr.groupby_exprs_.count(); ++k) {
            ObRawExpr *gby_expr = expr.groupby_exprs_.at(k);
            if (OB_ISNULL(gby_expr)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_WARN("invalid expr", K(ret));
            } else if (OB_FAIL(add_var_to_array_no_dup(groupby_rollup_exprs_, gby_expr))) {
              LOG_WARN("failed to do appending to current array", K(ret));
            }
          }
        }
        for (int64_t j = 0; OB_SUCC(ret) && j < select_stmt->get_multi_rollup_items_size(); ++j) {
          ObMultiRollupItem multi_rollup_item = select_stmt->get_multi_rollup_items().at(j);
          for (int64_t k = 0; OB_SUCC(ret) && k < multi_rollup_item.rollup_list_exprs_.count(); ++k) {
            ObGroupbyExpr expr = multi_rollup_item.rollup_list_exprs_.at(k);
              for (int64_t l = 0; OB_SUCC(ret) && l < expr.groupby_exprs_.count(); ++l) {
              ObRawExpr *gby_expr = expr.groupby_exprs_.at(l);
              if (OB_ISNULL(gby_expr)) {
                ret = OB_ERR_UNEXPECTED;
                LOG_WARN("invalid expr", K(ret));
              } else if (OB_FAIL(add_var_to_array_no_dup(groupby_rollup_exprs_, gby_expr))) {
                LOG_WARN("failed to do appending to current array", K(ret));
              }
            }
          }
        }
      }
O
oceanbase-admin 已提交
2594
    }
W
wangzelin.wzl 已提交
2595 2596 2597
    // having exprs
    if (OB_SUCC(ret) && OB_FAIL(append_array_no_dup(having_exprs_, select_stmt->get_having_exprs()))) {
      LOG_WARN("failed to add having exprs into output exprs", K(ret));
O
oceanbase-admin 已提交
2598
    }
W
wangzelin.wzl 已提交
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
    // winfunc exprs
    if (OB_SUCC(ret)) {
      for (int64_t i = 0; OB_SUCC(ret) && i < select_stmt->get_window_func_exprs().count(); ++i) {
        const ObWinFunRawExpr *winfunc_expr = select_stmt->get_window_func_expr(i);
        if (OB_ISNULL(winfunc_expr)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid expr", K(ret));
        } else {
          for (int64_t j = 0; OB_SUCC(ret) && j < winfunc_expr->get_partition_exprs().count(); ++j) {
            ObRawExpr *partition_by_expr = winfunc_expr->get_partition_exprs().at(j);
            if (OB_ISNULL(partition_by_expr)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_WARN("invalid expr", K(ret));
            } else if (OB_FAIL(add_var_to_array_no_dup(winfunc_exprs_, partition_by_expr))) {
              LOG_WARN("failed to do appending to current array", K(ret));
            }
          }
          for (int64_t j = 0; OB_SUCC(ret) && j < winfunc_expr->get_order_items().count(); ++j) {
            OrderItem orderby_item = winfunc_expr->get_order_items().at(j);
            if (OB_ISNULL(orderby_item.expr_)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_WARN("invalid expr", K(ret));
            } else if (OB_FAIL(add_var_to_array_no_dup(winfunc_exprs_, orderby_item.expr_))) {
              LOG_WARN("failed to do appending to current array", K(ret));
            }
          }
        }
      }
    }
    // select item related info
    if (OB_SUCC(ret)) {
      for (int64_t i = 0; OB_SUCC(ret) && i < select_stmt->get_select_item_size(); ++i) {
        SelectItem select_item = select_stmt->get_select_item(i);
        if (OB_ISNULL(select_item.expr_)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid expr", K(ret));
        } else if (OB_FAIL(add_var_to_array_no_dup(select_item_exprs_, select_item.expr_))) {
          LOG_WARN("failed to do appending to current array", K(ret));
        }
      }
O
oceanbase-admin 已提交
2639 2640
    }
  }
W
wangzelin.wzl 已提交
2641
  // condition exprs related info
O
oceanbase-admin 已提交
2642
  if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
    if (OB_FAIL(stmt->get_where_scope_conditions(condition_exprs_))) {
      LOG_WARN("failed to add condition expr into output exprs", K(ret));
    } else {
      // order by related info
      for (int64_t i = 0; OB_SUCC(ret) && i < stmt->get_order_item_size(); ++i) {
        OrderItem orderby_item = stmt->get_order_item(i);
        if (OB_ISNULL(orderby_item.expr_)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid expr", K(ret));
        } else if (OB_FAIL(add_var_to_array_no_dup(orderby_exprs_, orderby_item.expr_))) {
          LOG_WARN("failed to do appending to current array", K(ret));
        }
O
oceanbase-admin 已提交
2655 2656 2657 2658 2659 2660
      }
    }
  }
  return ret;
}

O
obdev 已提交
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
int ObLogPlan::init_json_table_depend_info(const ObIArray<TableItem*> &table_items)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = get_stmt();
  if (OB_ISNULL(stmt)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null stmt", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
    TableItem *table = table_items.at(i);
    JsonTableDependInfo info;
    if (OB_ISNULL(table)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null table item", K(ret));
    } else if (!table->is_json_table()) {
      //do nothing
    } else if (OB_ISNULL(table->json_table_def_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null function table expr", K(ret));
    } else if (table->json_table_def_->doc_expr_->get_relation_ids().is_empty()) {
      //do thing
    } else if (OB_FAIL(info.depend_table_set_.add_members(table->json_table_def_->doc_expr_->get_relation_ids()))) {
      LOG_WARN("failed to assign table ids", K(ret));
    } else if (OB_FALSE_IT(info.table_idx_ = stmt->get_table_bit_index(table->table_id_))) {
    } else if (OB_FAIL(json_table_depend_infos_.push_back(info))) {
      LOG_WARN("failed to push back info", K(ret));
    }
  }
  if (OB_SUCC(ret)) {
    LOG_TRACE("succeed to init function table depend info", K(json_table_depend_infos_));
  }
  return ret;
}

W
wangzelin.wzl 已提交
2695 2696 2697
int ObLogPlan::check_need_bushy_tree(common::ObIArray<JoinOrderArray> &join_rels,
                                    const int64_t level,
                                    bool &need)
O
oceanbase-admin 已提交
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
{
  int ret = OB_SUCCESS;
  need = false;
  if (level >= join_rels.count()) {
    ret = OB_INDEX_OUT_OF_RANGE;
    LOG_WARN("Index out of range", K(ret), K(join_rels.count()), K(level));
  } else if (join_rels.at(level).empty()) {
    need = true;
  }
  for (int64_t i = 0; OB_SUCC(ret) && !need && i < bushy_tree_infos_.count(); ++i) {
W
wangzelin.wzl 已提交
2708
    const ObRelIds &table_ids = bushy_tree_infos_.at(i);
O
oceanbase-admin 已提交
2709
    if (table_ids.num_members() != level + 1) {
W
wangzelin.wzl 已提交
2710
      //do nothing
O
oceanbase-admin 已提交
2711 2712 2713 2714
    } else {
      bool has_generated = false;
      int64_t N = join_rels.at(level).count();
      for (int64_t j = 0; OB_SUCC(ret) && !has_generated && j < N; ++j) {
W
wangzelin.wzl 已提交
2715
        ObJoinOrder *join_order = join_rels.at(level).at(j);
O
oceanbase-admin 已提交
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
        if (OB_ISNULL(join_order)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("unexpect null join order", K(ret));
        } else if (table_ids.is_subset(join_order->get_tables())) {
          has_generated = true;
        }
      }
      if (OB_SUCC(ret)) {
        need = !has_generated;
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
int ObLogPlan::init_idp(int64_t initial_idp_step,
                        common::ObIArray<JoinOrderArray> &idp_join_rels,
                        common::ObIArray<JoinOrderArray> &full_join_rels)
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(idp_join_rels.prepare_allocate(initial_idp_step))) {
    LOG_WARN("failed to prepare allocate join rels", K(ret));
  } else if (relid_joinorder_map_.created() || join_path_set_.created()) {
    relid_joinorder_map_.reuse();
    join_path_set_.reuse();
  }
  if (OB_SUCC(ret)) {
    for (int64_t i = 0; OB_SUCC(ret) && i < full_join_rels.at(0).count(); ++i) {
      if (OB_FAIL(idp_join_rels.at(0).push_back(full_join_rels.at(0).at(i)))) {
        LOG_WARN("failed to init level 0 rels", K(ret));
      }
    }
  }
  return ret;
}

int ObLogPlan::generate_join_levels_with_IDP(common::ObIArray<JoinOrderArray> &join_rels)
O
oceanbase-admin 已提交
2753 2754
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2755 2756 2757 2758
  int64_t join_level = join_rels.count();
  if (has_join_order_hint() &&
      OB_FAIL(inner_generate_join_levels_with_IDP(join_rels,
                                                false))) {
O
oceanbase-admin 已提交
2759 2760
    LOG_WARN("failed to generate join levels with hint", K(ret));
  } else if (1 == join_rels.at(join_level - 1).count()) {
W
wangzelin.wzl 已提交
2761
    //根据hint,枚举到了有效join order
O
obdev 已提交
2762
    OPT_TRACE("succeed to generate join order with hint");
W
wangzelin.wzl 已提交
2763 2764
  } else if (OB_FAIL(inner_generate_join_levels_with_IDP(join_rels,
                                                        true))) {
O
oceanbase-admin 已提交
2765 2766 2767 2768 2769
    LOG_WARN("failed to generate join level in generate_join_orders", K(ret), K(join_level));
  }
  return ret;
}

W
wangzelin.wzl 已提交
2770
int ObLogPlan::generate_join_levels_with_orgleading(common::ObIArray<JoinOrderArray> &join_rels)
O
oceanbase-admin 已提交
2771 2772
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
  ObArray<JoinOrderArray> temp_join_rels;
  int64_t join_level = join_rels.count();
  const ObDMLStmt *stmt = get_stmt();
  ObSEArray<TableItem*, 4> table_items;
  if (OB_ISNULL(stmt)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected NULL", K(stmt), K(ret));
  } else if (OB_FAIL(get_from_table_items(stmt->get_from_items(), table_items))) {
      LOG_WARN("failed to get table items", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < stmt->get_semi_infos().count(); ++i) {
    SemiInfo *semi_info = stmt->get_semi_infos().at(i);
    if (OB_ISNULL(semi_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null semi info", K(ret));
    } else {
      TableItem *table = stmt->get_table_item_by_id(semi_info->right_table_id_);
      ret = table_items.push_back(table);
    }
  }
  int64_t temp_join_level = table_items.count();
  LOG_TRACE("idp start enum join order with orig leading", K(temp_join_level));
  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(process_join_level_info(table_items,
                                             join_rels,
                                             temp_join_rels))) {
O
oceanbase-admin 已提交
2799
    LOG_WARN("failed to preprocess for linear", K(ret));
W
wangzelin.wzl 已提交
2800
  } else if (OB_FAIL(generate_join_levels_with_IDP(temp_join_rels))) {
O
oceanbase-admin 已提交
2801
    LOG_WARN("failed to generate join level in generate_join_orders", K(ret), K(join_level));
W
wangzelin.wzl 已提交
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
  } else if (OB_FALSE_IT(join_rels.at(join_level - 1).reset())) {
  } else if (OB_FAIL(append(join_rels.at(join_level - 1),
                            temp_join_rels.at(temp_join_level -1)))) {
    LOG_WARN("failed to append join orders", K(ret));
  }
  return ret;
}

int ObLogPlan::inner_generate_join_levels_with_IDP(common::ObIArray<JoinOrderArray> &join_rels,
                                                   bool ignore_hint)
{
  int ret = OB_SUCCESS;
  // stop plan enumeration if
  // a. illegal ordered hint
  // b. idp path num exceeds limitation
  // c. idp enumeration failed, under bushy cases, etc
  ObIDPAbortType abort_type = ObIDPAbortType::IDP_NO_ABORT;
  uint32_t join_level = 0;
  ObArray<JoinOrderArray> temp_join_rels;
O
obdev 已提交
2821 2822 2823 2824 2825
  if (ignore_hint) {
    OPT_TRACE("IDP without hint");
  } else {
    OPT_TRACE("IDP with hint");
  }
W
wangzelin.wzl 已提交
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
  if (join_rels.empty()) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect empty join rels", K(ret));
  } else {
    join_level = join_rels.at(0).count();
    uint32_t initial_idp_step = join_level;
    if (OB_FAIL(init_idp(initial_idp_step, temp_join_rels, join_rels))) {
      LOG_WARN("failed to init idp", K(ret));
    } else {
      uint32_t curr_idp_step = initial_idp_step;
      uint32_t curr_level = 1;
      for (uint32_t i = 1; OB_SUCC(ret) && i < join_level &&
          ObIDPAbortType::IDP_NO_ABORT == abort_type; i += curr_level) {
        if (curr_idp_step > join_level - i + 1) {
          curr_idp_step = join_level - i + 1;
        }
        LOG_TRACE("start new round of idp", K(i), K(curr_idp_step));
O
obdev 已提交
2843
        OPT_TRACE("start new round of idp", KV(i), KV(curr_idp_step));
W
wangzelin.wzl 已提交
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
        if (OB_FAIL(do_one_round_idp(temp_join_rels,
                                    curr_idp_step,
                                    ignore_hint,
                                    curr_level,
                                    abort_type))) {
          LOG_WARN("failed to do idp internal", K(ret));
        } else if (ObIDPAbortType::IDP_INVALID_HINT_ABORT == abort_type) {
          LOG_WARN("failed to do idp internal", K(ret));
        } else if (temp_join_rels.at(curr_level).count() < 1) {
          abort_type = ObIDPAbortType::IDP_ENUM_FAILED_ABORT;
O
obdev 已提交
2854
          OPT_TRACE("failed to enum join order at current level", KV(curr_level));
W
wangzelin.wzl 已提交
2855
        } else {
O
obdev 已提交
2856
          OPT_TRACE("end new round of idp", K(i), K(curr_idp_step));
W
wangzelin.wzl 已提交
2857 2858 2859 2860 2861 2862 2863 2864 2865
          ObJoinOrder *best_order = NULL;
          bool is_last_round = (i >= join_level - curr_level);
          if (abort_type == ObIDPAbortType::IDP_STOPENUM_EXPDOWN_ABORT) {
            curr_idp_step /= 2;
            curr_idp_step = max(curr_idp_step, 2U);
          } else if (abort_type == ObIDPAbortType::IDP_STOPENUM_LINEARDOWN_ABORT) {
            curr_idp_step -= 2;
            curr_idp_step = max(curr_idp_step, 2U);
          }
O
obdev 已提交
2866
          OPT_TRACE("select best join order");
W
wangzelin.wzl 已提交
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
          if (OB_FAIL(greedy_idp_best_order(curr_level,
                                            temp_join_rels,
                                            best_order))) {
            LOG_WARN("failed to greedy idp best order", K(ret));
          } else if (OB_ISNULL(best_order)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("unexpected invalid best order", K(ret));
          } else if (!is_last_round &&
                    OB_FAIL(prepare_next_round_idp(temp_join_rels,
                                                   initial_idp_step,
                                                   best_order))) {
            LOG_WARN("failed to prepare next round of idp", K(curr_level));
          } else {
            if (abort_type == ObIDPAbortType::IDP_STOPENUM_EXPDOWN_ABORT ||
                abort_type == ObIDPAbortType::IDP_STOPENUM_LINEARDOWN_ABORT) {
              abort_type = ObIDPAbortType::IDP_NO_ABORT;
            }
            if (is_last_round) {
              if (OB_FALSE_IT(join_rels.at(join_level - 1).reset())) {
              } else if (OB_FAIL(append(join_rels.at(join_level - 1),
                                        temp_join_rels.at(curr_level)))) {
                LOG_WARN("failed to append join orders", K(ret));
              }
            }
          }
        }
      }
    }
O
oceanbase-admin 已提交
2895 2896 2897 2898
  }
  return ret;
}

W
wangzelin.wzl 已提交
2899 2900 2901 2902 2903
int ObLogPlan::do_one_round_idp(common::ObIArray<JoinOrderArray> &temp_join_rels,
                                uint32_t curr_idp_step,
                                bool ignore_hint,
                                uint32_t &real_base_level,
                                ObIDPAbortType &abort_type)
O
oceanbase-admin 已提交
2904 2905
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2906 2907 2908 2909
  real_base_level = 1;
  for (uint32_t base_level = 1; OB_SUCC(ret) && base_level < curr_idp_step &&
       ObIDPAbortType::IDP_NO_ABORT == abort_type; ++base_level) {
    LOG_TRACE("idp start base level plan enumeration", K(base_level), K(curr_idp_step));
O
obdev 已提交
2910
    OPT_TRACE("idp start base level plan enumeration", K(base_level), K(curr_idp_step));
W
wangzelin.wzl 已提交
2911 2912
    for (uint32_t i = 0; OB_SUCC(ret) && i <= base_level/2 &&
         ObIDPAbortType::IDP_NO_ABORT == abort_type; ++i) {
O
oceanbase-admin 已提交
2913 2914 2915
      uint32_t right_level = i;
      uint32_t left_level = base_level - 1 - right_level;
      if (right_level > left_level) {
W
wangzelin.wzl 已提交
2916
        //do nothing
O
oceanbase-admin 已提交
2917 2918
      } else if (OB_FAIL(THIS_WORKER.check_status())) {
        LOG_WARN("check status fail", K(ret));
W
wangzelin.wzl 已提交
2919 2920 2921 2922 2923 2924
      } else if (OB_FAIL(generate_single_join_level_with_DP(temp_join_rels,
                                                            left_level,
                                                            right_level,
                                                            base_level,
                                                            ignore_hint,
                                                            abort_type))) {
O
oceanbase-admin 已提交
2925 2926 2927 2928
        LOG_WARN("failed to generate join order with dynamic program", K(ret));
      }
      bool need_bushy = false;
      if (OB_FAIL(ret) || right_level > left_level) {
W
wangzelin.wzl 已提交
2929 2930 2931 2932
      } else if (abort_type < ObIDPAbortType::IDP_NO_ABORT) {
        LOG_TRACE("abort idp join order generation",
                  K(left_level), K(right_level), K(abort_type));
      } else if (temp_join_rels.count() <= base_level) {
O
oceanbase-admin 已提交
2933
        ret = OB_INDEX_OUT_OF_RANGE;
W
wangzelin.wzl 已提交
2934 2935 2936 2937
        LOG_WARN("Index out of range", K(ret), K(temp_join_rels.count()), K(base_level));
      } else if (OB_FAIL(check_need_bushy_tree(temp_join_rels,
                                              base_level,
                                              need_bushy))) {
O
oceanbase-admin 已提交
2938 2939
        LOG_WARN("failed to check need bushy tree", K(ret));
      } else if (need_bushy) {
O
obdev 已提交
2940
        OPT_TRACE("no valid ZigZag tree or leading hint required, we will enumerate bushy tree");
O
oceanbase-admin 已提交
2941
      } else {
W
wangzelin.wzl 已提交
2942
        //如果当前level已经枚举到了有效计划,默认关闭bushy tree
O
obdev 已提交
2943
        OPT_TRACE("there is valid ZigZag tree, we will not enumerate bushy tree");
O
oceanbase-admin 已提交
2944 2945 2946
        break;
      }
    }
W
wangzelin.wzl 已提交
2947 2948 2949 2950 2951 2952 2953 2954 2955
    if (OB_SUCC(ret)) {
      real_base_level = base_level;
      if (abort_type == ObIDPAbortType::IDP_NO_ABORT &&
          OB_FAIL(check_and_abort_curr_round_idp(temp_join_rels,
                                                 base_level,
                                                 abort_type))) {
        LOG_WARN("failed to check and abort current round idp", K(ret));
      }
    }
O
oceanbase-admin 已提交
2956 2957 2958 2959
  }
  return ret;
}

W
wangzelin.wzl 已提交
2960 2961 2962
int ObLogPlan::check_and_abort_curr_level_dp(common::ObIArray<JoinOrderArray> &idp_join_rels,
                                             uint32_t curr_level,
                                             ObIDPAbortType &abort_type)
O
oceanbase-admin 已提交
2963 2964
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
  if (curr_level < 0 || curr_level >= idp_join_rels.count()) {
    ret = OB_INDEX_OUT_OF_RANGE;
    LOG_WARN("Index out of range", K(ret), K(idp_join_rels.count()), K(curr_level));
  } else if (abort_type < ObIDPAbortType::IDP_NO_ABORT) {
    // do nothing
  } else {
    uint64_t total_path_num = 0;
    for (int64_t i = 0; OB_SUCC(ret) && i < idp_join_rels.at(curr_level).count(); ++i) {
      total_path_num += idp_join_rels.at(curr_level).at(i)->get_total_path_num();
    }
    if (OB_SUCC(ret)) {
      uint64_t stop_down_abort_limit = 2 * IDP_PATHNUM_THRESHOLD;
      if (total_path_num >= stop_down_abort_limit) {
        abort_type = ObIDPAbortType::IDP_STOPENUM_EXPDOWN_ABORT;
O
obdev 已提交
2979 2980
        OPT_TRACE("there is too much path, we will stop current level idp ",
        KV(total_path_num), KV(stop_down_abort_limit));
O
oceanbase-admin 已提交
2981
      } else {
W
wangzelin.wzl 已提交
2982
        // do nothing
O
oceanbase-admin 已提交
2983 2984 2985 2986 2987 2988
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2989 2990 2991
int ObLogPlan::check_and_abort_curr_round_idp(common::ObIArray<JoinOrderArray> &idp_join_rels,
                                              uint32_t curr_level,
                                              ObIDPAbortType &abort_type)
O
oceanbase-admin 已提交
2992 2993
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2994
  if (curr_level < 0 || curr_level >= idp_join_rels.count()) {
O
oceanbase-admin 已提交
2995
    ret = OB_INDEX_OUT_OF_RANGE;
W
wangzelin.wzl 已提交
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
    LOG_WARN("Index out of range", K(ret), K(idp_join_rels.count()), K(curr_level));
  } else if (abort_type < ObIDPAbortType::IDP_NO_ABORT) {
    // do nothing
  } else {
    uint64_t total_path_num = 0;
    for (int64_t i = 0; OB_SUCC(ret) && i < idp_join_rels.at(curr_level).count(); ++i) {
      total_path_num += idp_join_rels.at(curr_level).at(i)->get_total_path_num();
    }
    if (OB_SUCC(ret)) {
      uint64_t stop_abort_limit = IDP_PATHNUM_THRESHOLD;
      if (total_path_num >= stop_abort_limit) {
        abort_type = ObIDPAbortType::IDP_STOPENUM_LINEARDOWN_ABORT;
O
obdev 已提交
3008 3009
        OPT_TRACE("there is too much path, we will stop current round idp ",
        KV(total_path_num), KV(stop_abort_limit));
W
wangzelin.wzl 已提交
3010 3011 3012
      } else {
        // do nothing
      }
O
oceanbase-admin 已提交
3013 3014 3015 3016 3017
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3018 3019 3020
int ObLogPlan::prepare_next_round_idp(common::ObIArray<JoinOrderArray> &idp_join_rels,
                                      uint32_t initial_idp_step,
                                      ObJoinOrder *&best_order)
O
oceanbase-admin 已提交
3021 3022
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3023 3024
  JoinOrderArray remained_rels;
  if (OB_ISNULL(best_order)) {
O
oceanbase-admin 已提交
3025
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
3026 3027 3028 3029 3030 3031 3032
    LOG_WARN("invalid best order", K(best_order), K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < idp_join_rels.at(0).count(); ++i) {
      if (!idp_join_rels.at(0).at(i)->get_tables().overlap2(best_order->get_tables())) {
        if (OB_FAIL(remained_rels.push_back(idp_join_rels.at(0).at(i)))) {
          LOG_WARN("failed to add level 0 rels", K(ret));
        }
O
oceanbase-admin 已提交
3033 3034
      }
    }
W
wangzelin.wzl 已提交
3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
    if (OB_SUCC(ret)) {
      for (int64_t j = 0; OB_SUCC(ret) && j < initial_idp_step; ++j) {
        idp_join_rels.at(j).reuse();
      }
      if (OB_SUCC(ret)) {
        if (OB_FAIL(idp_join_rels.at(0).assign(remained_rels))) {
          LOG_WARN("failed to add remained rels", K(ret));
        } else if (OB_FAIL(idp_join_rels.at(0).push_back(best_order))) {
          LOG_WARN("failed to add selected tree rels", K(ret));
        }
      }
    }
  }
  return ret;
}

int ObLogPlan::greedy_idp_best_order(uint32_t current_level,
                                     common::ObIArray<JoinOrderArray> &idp_join_rels,
                                     ObJoinOrder *&best_order)
{
  // choose best order from join_rels at current_level
  // can be based on cost/min cards/max interesting path num
  // currently based on cost
  int ret = OB_SUCCESS;
  best_order = NULL;
  if (current_level < 0 ||
      current_level >= idp_join_rels.count()) {
    ret = OB_INDEX_OUT_OF_RANGE;
    LOG_WARN("index out of range", K(ret), K(idp_join_rels.count()), K(current_level));
  } else if (idp_join_rels.at(current_level).count() < 1) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("illegal join rels at current level", K(ret));
  }
  if (OB_SUCC(ret)) {
    Path *min_cost_path = NULL;
    for (int64_t i = 0; OB_SUCC(ret) && i < idp_join_rels.at(current_level).count(); ++i) {
      ObJoinOrder * join_order = idp_join_rels.at(current_level).at(i);
      if (OB_ISNULL(join_order)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("invalid join order found", K(ret));
      } else {
        for (int64_t j = 0; OB_SUCC(ret) && j < join_order->get_interesting_paths().count(); ++j) {
          Path *path = join_order->get_interesting_paths().at(j);
          if (OB_ISNULL(path)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("invalid join order found", K(ret));
          } else if (NULL == min_cost_path || min_cost_path->cost_ > path->cost_) {
            best_order = join_order;
            min_cost_path = path;
          }
        }
      }
    }
  }
  return ret;
}

/**
 * 进行join order枚举前,需要为所有的joined table生成join order
 * 然后把joined table当前整体进行join reorder
 **/
int ObLogPlan::process_join_level_info(const ObIArray<TableItem*> &table_items,
                                      ObIArray<JoinOrderArray> &join_rels,
                                      ObIArray<JoinOrderArray> &new_join_rels)
{
  int ret = OB_SUCCESS;
  int64_t new_join_level = table_items.count();
  if (join_rels.empty()) {
    ret = OB_INDEX_OUT_OF_RANGE;
    LOG_WARN("join_rels is empty", K(ret), K(join_rels.count()));
  } else if (OB_FAIL(new_join_rels.prepare_allocate(new_join_level))) {
    LOG_WARN("failed to prepare allocate join rels", K(ret));
  } else if (relid_joinorder_map_.created() || join_path_set_.created()) {
    // clear relid_joinorder map to avoid existing join order misuse
    relid_joinorder_map_.reuse();
    join_path_set_.reuse();
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < table_items.count(); ++i) {
    ObJoinOrder *join_tree = NULL;
    if (OB_FAIL(generate_join_order_with_table_tree(join_rels,
                                                    table_items.at(i),
                                                    join_tree))) {
      LOG_WARN("failed to generate join order", K(ret));
O
oceanbase-admin 已提交
3118
    } else if (OB_ISNULL(join_tree)) {
W
wangzelin.wzl 已提交
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
      ret = OB_ERR_NO_JOIN_ORDER_GENERATED;
      LOG_WARN("no valid join order generated", K(ret));
    } else if (OB_FAIL(new_join_rels.at(0).push_back(join_tree))) {
      LOG_WARN("failed to push back base level join order", K(ret));
    }
  }
  return ret;
}

int ObLogPlan::generate_join_order_with_table_tree(ObIArray<JoinOrderArray> &join_rels,
                                                  TableItem *table,
                                                  ObJoinOrder* &join_tree)
{
  int ret = OB_SUCCESS;
  JoinedTable *joined_table = NULL;
  ObJoinOrder *left_tree = NULL;
  ObJoinOrder *right_tree = NULL;
  join_tree = NULL;
  if (OB_ISNULL(table) || join_rels.empty()) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null param", K(ret));
  } else if (!table->is_joined_table()) {
    //find base join rels
    ObIArray<ObJoinOrder *> &single_join_rels = join_rels.at(0);
    for (int64_t i = 0; OB_SUCC(ret) && NULL == join_tree && i < single_join_rels.count(); ++i) {
      ObJoinOrder *base_rel = single_join_rels.at(i);
      if (OB_ISNULL(base_rel)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null base rel", K(ret));
      } else if (table->table_id_ == base_rel->get_table_id()) {
        join_tree = base_rel;
      }
    }
  } else if (OB_FALSE_IT(joined_table = static_cast<JoinedTable*>(table))) {
    // do nothing
  } else if (OB_FAIL(SMART_CALL(generate_join_order_with_table_tree(join_rels,
                                                                    joined_table->left_table_,
                                                                    left_tree)))) {
    LOG_WARN("failed to generate join order", K(ret));
  } else if (OB_FAIL(SMART_CALL(generate_join_order_with_table_tree(join_rels,
                                                                    joined_table->right_table_,
                                                                    right_tree)))) {
    LOG_WARN("failed to generate join order", K(ret));
  } else if (OB_ISNULL(left_tree) || OB_ISNULL(right_tree)) {
    ret = OB_ERR_NO_JOIN_ORDER_GENERATED;
    LOG_WARN("no valid join order generated", K(ret));
  } else {
    bool is_valid_join = false;
    int64_t level = left_tree->get_tables().num_members() + right_tree->get_tables().num_members() - 1;
    if (OB_FAIL(inner_generate_join_order(join_rels,
                                          left_tree,
                                          right_tree,
                                          level,
                                          false,
                                          false,
                                          is_valid_join,
                                          join_tree))) {
      LOG_WARN("failed to generated join order", K(ret));
O
oceanbase-admin 已提交
3177 3178 3179 3180 3181
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3182 3183 3184 3185 3186 3187
int ObLogPlan::generate_single_join_level_with_DP(ObIArray<JoinOrderArray> &join_rels,
                                                  uint32_t left_level,
                                                  uint32_t right_level,
                                                  uint32_t level,
                                                  bool ignore_hint,
                                                  ObIDPAbortType &abort_type)
O
oceanbase-admin 已提交
3188 3189
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3190 3191 3192 3193
  abort_type = ObIDPAbortType::IDP_NO_ABORT;
  if (join_rels.empty() ||
      left_level >= join_rels.count() ||
      right_level >= join_rels.count() ||
O
oceanbase-admin 已提交
3194 3195
      level >= join_rels.count()) {
    ret = OB_INDEX_OUT_OF_RANGE;
W
wangzelin.wzl 已提交
3196 3197
    LOG_WARN("Index out of range", K(ret), K(join_rels.count()),
                          K(left_level), K(right_level), K(level));
O
oceanbase-admin 已提交
3198
  } else {
W
wangzelin.wzl 已提交
3199 3200 3201 3202 3203 3204 3205 3206
    ObIArray<ObJoinOrder *> &left_rels = join_rels.at(left_level);
    ObIArray<ObJoinOrder *> &right_rels = join_rels.at(right_level);
    ObJoinOrder *left_tree = NULL;
    ObJoinOrder *right_tree = NULL;
    ObJoinOrder *join_tree = NULL;
    //优先枚举有连接条件的join order
    for (int64_t i = 0; OB_SUCC(ret) && i < left_rels.count() &&
         ObIDPAbortType::IDP_NO_ABORT == abort_type; ++i) {
O
oceanbase-admin 已提交
3207 3208 3209 3210 3211
      left_tree = left_rels.at(i);
      if (OB_ISNULL(left_tree)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null join tree", K(ret));
      } else {
O
obdev 已提交
3212 3213
        OPT_TRACE("Permutations for Starting Table :", left_tree);
        OPT_TRACE_BEGIN_SECTION;
W
wangzelin.wzl 已提交
3214 3215
        for (int64_t j = 0; OB_SUCC(ret) && j < right_rels.count() &&
             ObIDPAbortType::IDP_NO_ABORT == abort_type; ++j) {
O
oceanbase-admin 已提交
3216 3217 3218 3219 3220 3221 3222 3223 3224
          right_tree = right_rels.at(j);
          bool match_hint = false;
          bool is_legal = true;
          bool is_strict_order = true;
          bool is_valid_join = false;
          if (OB_ISNULL(right_tree)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("unexpect null join tree", K(ret));
          } else if (!ignore_hint &&
W
wangzelin.wzl 已提交
3225 3226 3227 3228 3229
                    OB_FAIL(check_join_hint(left_tree->get_tables(),
                                            right_tree->get_tables(),
                                            match_hint,
                                            is_legal,
                                            is_strict_order))) {
O
oceanbase-admin 已提交
3230 3231
            LOG_WARN("failed to check join hint", K(ret));
          } else if (!is_legal) {
W
wangzelin.wzl 已提交
3232
            //与hint冲突
O
obdev 已提交
3233
            OPT_TRACE("join order conflict with leading hint,", left_tree, right_tree);
W
wangzelin.wzl 已提交
3234 3235
            LOG_TRACE("join order conflict with leading hint",
                      K(left_tree->get_tables()), K(right_tree->get_tables()));
O
oceanbase-admin 已提交
3236
          } else if (OB_FAIL(inner_generate_join_order(join_rels,
W
wangzelin.wzl 已提交
3237 3238 3239 3240 3241 3242 3243
                                                        is_strict_order ? left_tree : right_tree,
                                                        is_strict_order ? right_tree : left_tree,
                                                        level,
                                                        match_hint,
                                                        !match_hint,
                                                        is_valid_join,
                                                        join_tree))) {
O
oceanbase-admin 已提交
3244
            LOG_WARN("failed to generate join order", K(level), K(ret));
W
wangzelin.wzl 已提交
3245 3246 3247 3248
          } else if (match_hint &&
                     !get_leading_tables().is_subset(left_tree->get_tables()) &&
                     !is_valid_join) {
            abort_type = ObIDPAbortType::IDP_INVALID_HINT_ABORT;
O
obdev 已提交
3249
            OPT_TRACE("leading hint is invalid, stop idp ", left_tree, right_tree);
W
wangzelin.wzl 已提交
3250 3251 3252 3253
          } else if (OB_FAIL(check_and_abort_curr_level_dp(join_rels,
                                                           level,
                                                           abort_type))) {
            LOG_WARN("failed to check abort current dp", K(level), K(abort_type));
O
oceanbase-admin 已提交
3254
          } else {
W
wangzelin.wzl 已提交
3255 3256
            LOG_TRACE("succeed to generate join order", K(left_tree->get_tables()),
                       K(right_tree->get_tables()), K(is_valid_join), K(abort_type));
O
oceanbase-admin 已提交
3257 3258
          }
        }
O
obdev 已提交
3259
        OPT_TRACE_END_SECTION;
O
oceanbase-admin 已提交
3260 3261 3262 3263 3264 3265
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
/**
 * 使用动态规划算法
 * 通过join_rels[left_level]组合join_rels[right_level]
 * 来枚举join_rels[level]的有效计划
 */
int ObLogPlan::inner_generate_join_order(ObIArray<JoinOrderArray> &join_rels,
                                        ObJoinOrder *left_tree,
                                        ObJoinOrder *right_tree,
                                        uint32_t level,
                                        bool hint_force_order,
                                        bool delay_cross_product,
                                        bool &is_valid_join,
                                        ObJoinOrder *&join_tree)
O
oceanbase-admin 已提交
3279 3280 3281
{
  int ret = OB_SUCCESS;
  is_valid_join = false;
W
wangzelin.wzl 已提交
3282 3283 3284 3285
  join_tree = NULL;
  bool need_gen = true;
  if (join_rels.empty() || level >= join_rels.count() ||
      OB_ISNULL(left_tree) || OB_ISNULL(right_tree)) {
O
oceanbase-admin 已提交
3286
    ret = OB_INDEX_OUT_OF_RANGE;
W
wangzelin.wzl 已提交
3287 3288
    LOG_WARN("Index out of range", K(ret), K(join_rels.count()),
                          K(left_tree), K(right_tree), K(level));
O
oceanbase-admin 已提交
3289
  } else {
W
wangzelin.wzl 已提交
3290
    //依次检查每一个join info,是否有合法的连接
O
oceanbase-admin 已提交
3291 3292 3293 3294 3295
    ObSEArray<ConflictDetector*, 4> valid_detectors;
    ObRelIds cur_relids;
    JoinInfo join_info;
    bool is_strict_order = true;
    if (left_tree->get_tables().overlap(right_tree->get_tables())) {
W
wangzelin.wzl 已提交
3296
      //非法连接,do nothing
O
oceanbase-admin 已提交
3297 3298 3299 3300
    } else if (OB_FAIL(cur_relids.add_members(left_tree->get_tables()))) {
      LOG_WARN("fail to add left tree' table ids", K(ret));
    } else if (OB_FAIL(cur_relids.add_members(right_tree->get_tables()))) {
      LOG_WARN("fail to add right tree' table ids", K(ret));
W
wangzelin.wzl 已提交
3301 3302 3303 3304 3305 3306 3307
    } else if (OB_FAIL(find_join_rel(cur_relids, join_tree))) {
      LOG_WARN("fail to find join rel", K(ret), K(level));
    } else if (OB_FAIL(check_need_gen_join_path(left_tree, right_tree, need_gen))) {
      LOG_WARN("failed to find join tree pair", K(ret));
    } else if (!need_gen) {
      // do nothing
      is_valid_join = true;
O
obdev 已提交
3308 3309
      OPT_TRACE(left_tree, right_tree,
      " is legal, and has join path cache, no need to generate join path");
W
wangzelin.wzl 已提交
3310 3311 3312 3313 3314 3315 3316
    } else if (OB_FAIL(choose_join_info(left_tree,
                                        right_tree,
                                        valid_detectors,
                                        delay_cross_product,
                                        is_strict_order))) {
      LOG_WARN("failed to choose join info", K(ret));
    } else if (valid_detectors.empty()) {
O
obdev 已提交
3317
      OPT_TRACE("there is no valid join condition for ", left_tree, "join", right_tree);
W
wangzelin.wzl 已提交
3318 3319 3320 3321 3322 3323
      LOG_TRACE("there is no valid join info for ", K(left_tree->get_tables()),
                                                    K(right_tree->get_tables()));
    } else if (OB_FAIL(merge_join_info(left_tree,
                                       right_tree,
                                       valid_detectors,
                                       join_info))) {
O
oceanbase-admin 已提交
3324 3325
      LOG_WARN("failed to merge join info", K(ret));
    } else if (NULL != join_tree && level <= 1 && !hint_force_order) {
W
wangzelin.wzl 已提交
3326
      //level==1的时候,左右树都是单表,如果已经生成过AB的话,BA的path也已经生成了,没必要再次生成一遍BA
O
oceanbase-admin 已提交
3327
      is_valid_join = true;
O
obdev 已提交
3328
      OPT_TRACE("path has been generated in level one");
O
oceanbase-admin 已提交
3329 3330 3331 3332 3333
    } else {
      if (!is_strict_order) {
        if (!hint_force_order) {
          std::swap(left_tree, right_tree);
        } else {
W
wangzelin.wzl 已提交
3334 3335
          //如果leading hint指定了join order,但是合法的join order与
          //leading hint指定的join order相反,那么应该把连接类型取反
O
oceanbase-admin 已提交
3336 3337 3338
          join_info.join_type_ = get_opposite_join_type(join_info.join_type_);
        }
      }
W
wangzelin.wzl 已提交
3339 3340 3341
      JoinPathPairInfo pair;
      pair.left_ids_ = left_tree->get_tables();
      pair.right_ids_ = right_tree->get_tables();
O
oceanbase-admin 已提交
3342
      if (NULL == join_tree) {
W
wangzelin.wzl 已提交
3343
        if(OB_ISNULL(join_tree = create_join_order(JOIN))) {
O
oceanbase-admin 已提交
3344 3345
          ret = OB_ALLOCATE_MEMORY_FAILED;
          LOG_WARN("failed to create join tree", K(ret));
W
wangzelin.wzl 已提交
3346 3347 3348 3349
        } else if (OB_FAIL(join_tree->init_join_order(left_tree,
                                                      right_tree,
                                                      &join_info,
                                                      valid_detectors))) {
O
oceanbase-admin 已提交
3350 3351 3352
          LOG_WARN("failed to init join order", K(ret));
        } else if (OB_FAIL(join_rels.at(level).push_back(join_tree))) {
          LOG_WARN("failed to push back join order", K(ret));
W
wangzelin.wzl 已提交
3353 3354 3355
        } else if (relid_joinorder_map_.created() &&
                   OB_FAIL(relid_joinorder_map_.set_refactored(join_tree->get_tables(), join_tree))) {
          LOG_WARN("failed to add table ids join order to hash map", K(ret));
O
oceanbase-admin 已提交
3356 3357
        }
      }
O
obdev 已提交
3358
      OPT_TRACE_TITLE("Now", left_tree, "join", right_tree, join_info);
O
oceanbase-admin 已提交
3359
      if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
3360 3361 3362 3363 3364
        //do nothing
      } else if (OB_FAIL(join_tree->generate_join_paths(*left_tree,
                                                        *right_tree,
                                                        join_info,
                                                        hint_force_order))) {
O
oceanbase-admin 已提交
3365
        LOG_WARN("failed to generate join paths for left_tree", K(level), K(ret));
W
wangzelin.wzl 已提交
3366 3367 3368
      } else if (join_path_set_.created() &&
                 OB_FAIL(join_path_set_.set_refactored(pair))) {
        LOG_WARN("failed to add join path set", K(ret));
O
oceanbase-admin 已提交
3369 3370
      } else {
        is_valid_join = true;
W
wangzelin.wzl 已提交
3371 3372
        LOG_TRACE("succeed to generate join order for ", K(left_tree->get_tables()),
                  K(right_tree->get_tables()), K(is_strict_order));
O
oceanbase-admin 已提交
3373 3374 3375 3376 3377 3378
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3379 3380 3381 3382
int ObLogPlan::is_detector_used(ObJoinOrder *left_tree,
                                ObJoinOrder *right_tree,
                                ConflictDetector *detector,
                                bool &is_used)
O
oceanbase-admin 已提交
3383 3384 3385 3386 3387 3388
{
  int ret = OB_SUCCESS;
  is_used = false;
  if (OB_ISNULL(left_tree) || OB_ISNULL(right_tree) || OB_ISNULL(detector)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null param", K(ret));
W
wangzelin.wzl 已提交
3389 3390 3391 3392
  } else if (INNER_JOIN == detector->join_info_.join_type_ &&
             detector->join_info_.where_conditions_.empty()) {
    //笛卡尔积的冲突检测器可以重复使用
  }else if (ObOptimizerUtil::find_item(left_tree->get_conflict_detectors(), detector)) {
O
oceanbase-admin 已提交
3393 3394 3395 3396 3397 3398 3399
    is_used = true;
  } else if (ObOptimizerUtil::find_item(right_tree->get_conflict_detectors(), detector)) {
    is_used = true;
  }
  return ret;
}

W
wangzelin.wzl 已提交
3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
/**
 * 为左右连接树选择合法的连接条件
 * is_strict_order:
 * true:left join right是合法的,right join left是非法的
 * false:left join right是非法的,right join left是合法的
 */
int ObLogPlan::choose_join_info(ObJoinOrder *left_tree,
                                ObJoinOrder *right_tree,
                                ObIArray<ConflictDetector*> &valid_detectors,
                                bool delay_cross_product,
                                bool &is_strict_order)
O
oceanbase-admin 已提交
3411 3412 3413
{
  int ret = OB_SUCCESS;
  bool is_legal = false;
W
wangzelin.wzl 已提交
3414
  ObRelIds combined_relids;
O
oceanbase-admin 已提交
3415 3416 3417
  if (OB_ISNULL(left_tree) || OB_ISNULL(right_tree)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect empty conflict detectors", K(ret));
W
wangzelin.wzl 已提交
3418 3419 3420 3421
  } else if (OB_FAIL(combined_relids.add_members(left_tree->get_tables()))) {
    LOG_WARN("failed to add left relids into combined relids", K(ret));
  } else if (OB_FAIL(combined_relids.add_members(right_tree->get_tables()))) {
    LOG_WARN("failed to add right relids into combined relids", K(ret));
O
oceanbase-admin 已提交
3422 3423 3424
  }
  is_strict_order = true;
  for (int64_t i = 0; OB_SUCC(ret) && i < conflict_detectors_.count(); ++i) {
W
wangzelin.wzl 已提交
3425
    ConflictDetector *detector = conflict_detectors_.at(i);
O
oceanbase-admin 已提交
3426 3427 3428 3429
    bool is_used = false;
    if (OB_ISNULL(detector)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("conflict detector is null", K(ret));
W
wangzelin.wzl 已提交
3430 3431 3432 3433
    } else if (OB_FAIL(is_detector_used(left_tree,
                                        right_tree,
                                        detector,
                                        is_used))) {
O
oceanbase-admin 已提交
3434 3435
      LOG_WARN("failed to check detector is used", K(ret));
    } else if (is_used) {
W
wangzelin.wzl 已提交
3436 3437 3438 3439 3440 3441 3442
      //do nothing
    } else if (OB_FAIL(check_join_legal(left_tree->get_tables(),
                                        right_tree->get_tables(),
                                        combined_relids,
                                        detector,
                                        delay_cross_product,
                                        is_legal))) {
O
oceanbase-admin 已提交
3443 3444
      LOG_WARN("failed to check join legal", K(ret));
    } else if (!is_legal) {
W
wangzelin.wzl 已提交
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
      //对于可交换的join如inner join,既left join right合法
      //也right join left合法,但是我们只需要保存left inner join right
      //因为在generate join path的时候会生成right inner join left的path
      //并且不可能存在一种join,既有left join1 right合法,又有right join2 left合法
      LOG_TRACE("left tree join right tree is not legal", K(left_tree->get_tables()),
                K(right_tree->get_tables()), K(*detector));
      //尝试right tree join left tree
      if (OB_FAIL(check_join_legal(right_tree->get_tables(),
                                   left_tree->get_tables(),
                                   combined_relids,
                                   detector,
                                   delay_cross_product,
                                   is_legal))) {
O
oceanbase-admin 已提交
3458 3459
        LOG_WARN("failed to check join legal", K(ret));
      } else if (!is_legal) {
W
wangzelin.wzl 已提交
3460 3461
        LOG_TRACE("right tree join left tree is not legal", K(right_tree->get_tables()),
                K(left_tree->get_tables()), K(*detector));
O
oceanbase-admin 已提交
3462 3463 3464 3465
      } else if (OB_FAIL(valid_detectors.push_back(detector))) {
        LOG_WARN("failed to push back detector", K(ret));
      } else {
        is_strict_order = false;
W
wangzelin.wzl 已提交
3466 3467 3468
        LOG_TRACE("succeed to find join info for ", K(left_tree->get_tables()),
                  K(right_tree->get_tables()), K(left_tree->get_conflict_detectors()),
                  K(right_tree->get_conflict_detectors()), K(*detector));
O
oceanbase-admin 已提交
3469 3470 3471 3472
      }
    } else if (OB_FAIL(valid_detectors.push_back(detector))) {
      LOG_WARN("failed to push back detector", K(ret));
    } else {
W
wangzelin.wzl 已提交
3473 3474 3475
      LOG_TRACE("succeed to find join info for ", K(left_tree->get_tables()),
                  K(right_tree->get_tables()), K(left_tree->get_conflict_detectors()),
                  K(right_tree->get_conflict_detectors()), K(*detector));
O
oceanbase-admin 已提交
3476 3477 3478 3479 3480
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3481 3482 3483 3484 3485 3486 3487 3488 3489
/**
 * 只允许多个inner join叠加成一个join info
 * 例如:select * from A, B where A.c1 = B.c1 and A.c2 = B.c2
 * 或者单个OUTER JOIN加上多个inner join info,inner join info作为join qual
 * 例如:select * from A left join B on A.c1 = B.c1 where A.c2 = B.c2
 */
int ObLogPlan::check_join_info(const ObIArray<ConflictDetector*> &valid_detectors,
                               ObJoinType &join_type,
                               bool &is_valid)
O
oceanbase-admin 已提交
3490 3491
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3492
  ConflictDetector *detector = NULL;
O
oceanbase-admin 已提交
3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
  bool has_non_inner_join = false;
  is_valid = true;
  join_type = INNER_JOIN;
  if (valid_detectors.empty()) {
    is_valid = false;
  }
  for (int64_t i = 0; OB_SUCC(ret) && is_valid && i < valid_detectors.count(); ++i) {
    detector = valid_detectors.at(i);
    if (OB_ISNULL(detector)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null detectors", K(ret));
    } else if (INNER_JOIN == detector->join_info_.join_type_) {
W
wangzelin.wzl 已提交
3505
      //do nothing
O
oceanbase-admin 已提交
3506
    } else if (has_non_inner_join) {
W
wangzelin.wzl 已提交
3507
      //不允许出现多个非inner join的join info
O
oceanbase-admin 已提交
3508 3509 3510 3511 3512 3513 3514 3515 3516
      is_valid = false;
    } else {
      has_non_inner_join = true;
      join_type = detector->join_info_.join_type_;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3517 3518 3519 3520
int ObLogPlan::merge_join_info(ObJoinOrder *left_tree,
                               ObJoinOrder *right_tree,
                               const ObIArray<ConflictDetector*> &valid_detectors,
                               JoinInfo &join_info)
O
oceanbase-admin 已提交
3521 3522 3523
{
  int ret = OB_SUCCESS;
  bool is_valid = false;
W
wangzelin.wzl 已提交
3524 3525 3526
  if (OB_FAIL(check_join_info(valid_detectors,
                              join_info.join_type_,
                              is_valid))) {
O
oceanbase-admin 已提交
3527 3528 3529 3530 3531
    LOG_WARN("failed to check join info", K(ret));
  } else if (!is_valid) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect different join info", K(valid_detectors), K(ret));
  } else {
W
wangzelin.wzl 已提交
3532
    ConflictDetector *detector = NULL;
O
oceanbase-admin 已提交
3533 3534 3535 3536 3537 3538 3539
    for (int64_t i = 0; OB_SUCC(ret) && i < valid_detectors.count(); ++i) {
      detector = valid_detectors.at(i);
      if (OB_ISNULL(detector)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null detectors", K(ret));
      } else if (OB_FAIL(join_info.table_set_.add_members(detector->join_info_.table_set_))) {
        LOG_WARN("failed to add members", K(ret));
W
wangzelin.wzl 已提交
3540
      } else if (OB_FAIL(append_array_no_dup(join_info.where_conditions_, detector->join_info_.where_conditions_))) {
O
oceanbase-admin 已提交
3541
        LOG_WARN("failed to append exprs", K(ret));
W
wangzelin.wzl 已提交
3542 3543
      } else if (INNER_JOIN == join_info.join_type_ &&
                 OB_FAIL(append_array_no_dup(join_info.where_conditions_, detector->join_info_.on_conditions_))) {
O
oceanbase-admin 已提交
3544
        LOG_WARN("failed to append exprs", K(ret));
W
wangzelin.wzl 已提交
3545 3546 3547 3548 3549 3550 3551 3552 3553
      } else if (INNER_JOIN != join_info.join_type_ &&
                 OB_FAIL(append_array_no_dup(join_info.on_conditions_, detector->join_info_.on_conditions_))) {
        LOG_WARN("failed to append exprs", K(ret));
      }
    }
    if (OB_SUCC(ret)) {
      // TODO: need to optimize this hotspot
      if (OB_FAIL(remove_redundancy_pred(left_tree, right_tree, join_info))) {
        LOG_WARN("failed to remove redundancy pred", K(ret));
O
oceanbase-admin 已提交
3554 3555
      }
    }
W
wangzelin.wzl 已提交
3556
    //抽取简单join condition
O
oceanbase-admin 已提交
3557 3558
    if (OB_SUCC(ret)) {
      if (INNER_JOIN == join_info.join_type_) {
W
wangzelin.wzl 已提交
3559 3560
        for (int64_t i = 0; OB_SUCC(ret) && i < join_info.where_conditions_.count(); ++i) {
          ObRawExpr *qual = join_info.where_conditions_.at(i);
O
oceanbase-admin 已提交
3561 3562 3563 3564
          if (OB_ISNULL(qual)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("unexpect null join qual", K(ret));
          } else if (!qual->has_flag(IS_JOIN_COND)) {
W
wangzelin.wzl 已提交
3565 3566
            //do nothing
          } else if (OB_FAIL(join_info.equal_join_conditions_.push_back(qual))) {
O
oceanbase-admin 已提交
3567 3568 3569 3570
            LOG_WARN("failed to push back join qual", K(ret));
          }
        }
      } else {
W
wangzelin.wzl 已提交
3571 3572
        for (int64_t i = 0; OB_SUCC(ret) && i < join_info.on_conditions_.count(); ++i) {
          ObRawExpr *qual = join_info.on_conditions_.at(i);
O
oceanbase-admin 已提交
3573 3574 3575 3576
          if (OB_ISNULL(qual)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("unexpect null join qual", K(ret));
          } else if (!qual->has_flag(IS_JOIN_COND)) {
W
wangzelin.wzl 已提交
3577 3578
            //do nothing
          } else if (OB_FAIL(join_info.equal_join_conditions_.push_back(qual))) {
O
oceanbase-admin 已提交
3579 3580 3581 3582 3583 3584 3585 3586 3587
            LOG_WARN("failed to push back join qual", K(ret));
          }
        }
      }
    }
  }
  return ret;
}

O
obdev 已提交
3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
/**
 * Try keep EQ preds that join same two tables.
 * For example, we will keep the two preds which join t1 and t3 in the below case.
 * (t1 join t2 on t1.c1 = t2.c1)
 *   join
 * (t3 join t4 on t3.c2 = t4.c2)
 *   on t1.c1 = t3.c1 and t2.c1 = t3.c1 and t1.c2 = t3.c2 and t1.c2 = t4.c2
 * =>
 * (t1 join t2 on t1.c1 = t2.c1)
 *   join
 * (t3 join t4 on t3.c2 = t4.c2)
 *   on t1.c1 = t3.c1 and t1.c2 = t3.c2
 *
 * Remove preds which is equation between two exprs in the same equal sets
 * (t1 where c1 = 1) join (t2 where c2 = 1) on t1.c1 = t2.c1
 *  => (t1 where c1 = 1) join (t2 where c2 = 1) on true
 * */
W
wangzelin.wzl 已提交
3605 3606 3607
int ObLogPlan::remove_redundancy_pred(ObJoinOrder *left_tree,
                                      ObJoinOrder *right_tree,
                                      JoinInfo &join_info)
O
oceanbase-admin 已提交
3608 3609
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3610 3611 3612 3613 3614 3615 3616
  if (INNER_JOIN == join_info.join_type_ ||
      LEFT_SEMI_JOIN == join_info.join_type_ ||
      LEFT_ANTI_JOIN == join_info.join_type_ ||
      RIGHT_SEMI_JOIN == join_info.join_type_ ||
      RIGHT_ANTI_JOIN == join_info.join_type_ ||
      LEFT_OUTER_JOIN == join_info.join_type_ ||
      RIGHT_OUTER_JOIN == join_info.join_type_) {
O
obdev 已提交
3617 3618 3619 3620
    ObIArray<ObRawExpr*> &join_pred = IS_OUTER_JOIN(join_info.join_type_) ?
                                      join_info.on_conditions_ :
                                      join_info.where_conditions_;
    EqualSets input_equal_sets;
W
wangzelin.wzl 已提交
3621
    if (OB_FAIL(ObEqualAnalysis::merge_equal_set(&allocator_,
O
obdev 已提交
3622 3623 3624
                                                        left_tree->get_output_equal_sets(),
                                                        right_tree->get_output_equal_sets(),
                                                        input_equal_sets))) {
W
wangzelin.wzl 已提交
3625
      LOG_WARN("failed to compute equal sets for inner join", K(ret));
O
obdev 已提交
3626 3627 3628 3629
    } else if (OB_FAIL(inner_remove_redundancy_pred(join_pred,
                                                    input_equal_sets,
                                                    left_tree,
                                                    right_tree))) {
W
wangzelin.wzl 已提交
3630 3631
      LOG_WARN("failed to inner remove redundancy pred", K(ret));
    }
O
oceanbase-admin 已提交
3632 3633 3634 3635
  }
  return ret;
}

O
obdev 已提交
3636 3637 3638 3639
int ObLogPlan::join_side_from_one_table(ObJoinOrder &child_tree,
                                        ObIArray<ObRawExpr*> &join_pred,
                                        bool &is_valid,
                                        ObRelIds &intersect_rel_ids)
O
oceanbase-admin 已提交
3640 3641
{
  int ret = OB_SUCCESS;
O
obdev 已提交
3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
  ObSEArray<ObRelIds, 4> eq_sets_rel_ids;
  ObRawExpr *expr_in_tree = NULL;
  intersect_rel_ids.reuse();
  is_valid = true;
  if (OB_FAIL(intersect_rel_ids.add_members(child_tree.get_tables()))){
    LOG_WARN("failed to add members", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::build_rel_ids_by_equal_sets(child_tree.get_output_equal_sets(),
                                                                  eq_sets_rel_ids))) {
    LOG_WARN("failed to build rel ids", K(ret));
  }
  const ObRelIds &tree_rel_ids = child_tree.get_tables();
  for (int64_t i = 0; OB_SUCC(ret) && is_valid && i < join_pred.count(); i++) {
    ObRawExpr *cur_expr = join_pred.at(i);
    ObRawExpr *left_expr = NULL;
    ObRawExpr *right_expr = NULL;
    if (OB_ISNULL(cur_expr)) {
W
wangzelin.wzl 已提交
3658
      ret = OB_ERR_UNEXPECTED;
O
obdev 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691
      LOG_WARN("get unexpected null", K(ret), K(cur_expr));
    } else if (T_OP_EQ == cur_expr->get_expr_type()) {
      if (OB_ISNULL(left_expr = cur_expr->get_param_expr(0)) ||
          OB_ISNULL(right_expr = cur_expr->get_param_expr(1))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret), KPC(cur_expr), K(left_expr), K(right_expr));
      } else if (tree_rel_ids.is_superset(left_expr->get_relation_ids())) {
        expr_in_tree = left_expr;
      } else if (tree_rel_ids.is_superset(right_expr->get_relation_ids())) {
        expr_in_tree = right_expr;
      } else {
        is_valid = false;
      }
      if (OB_SUCC(ret) && is_valid) {
        const ObRelIds &expr_rel_ids = expr_in_tree->get_relation_ids();
        int64_t eq_set_idx = OB_INVALID_ID;
        if (expr_rel_ids.num_members() != 1) {
          is_valid = false;
        } else if (OB_FAIL(ObOptimizerUtil::find_expr_in_equal_sets(child_tree.get_output_equal_sets(),
                                                                    expr_in_tree,
                                                                    eq_set_idx))) {
          LOG_WARN("failed to find expr", K(ret));
        } else {
          const ObRelIds &to_intersect = (eq_set_idx == OB_INVALID_ID) ?
                                          expr_rel_ids :
                                          eq_sets_rel_ids.at(eq_set_idx);
          if (OB_FAIL(intersect_rel_ids.intersect_members(to_intersect))) {
            LOG_WARN("failed to intersect", K(ret));
          } else if (intersect_rel_ids.is_empty()) {
            is_valid = false;
          }
        }
      }
O
oceanbase-admin 已提交
3692 3693
    }
  }
O
obdev 已提交
3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
  if (OB_FAIL(ret) || !is_valid) {
  } else if (OB_FAIL(intersect_rel_ids.reserve_first())) {
    LOG_WARN("failed to reserve first", K(ret));
  }

  return ret;
}

// Check if there are some predicates that were lost
// for situations where predicate derivation did not happen or predicate derivation was incomplete
int ObLogPlan::re_add_necessary_predicate(ObIArray<ObRawExpr*> &join_pred,
                                          ObIArray<ObRawExpr*> &new_join_pred,
                                          ObIArray<bool> &skip,
                                          EqualSets &equal_sets)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(join_pred.count() != skip.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected params", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < join_pred.count(); i++) {
    ObRawExpr *cur_expr= join_pred.at(i);
    ObRawExpr *left_expr = NULL;
    ObRawExpr *right_expr = NULL;
    if (OB_ISNULL(cur_expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(cur_expr));
    } else if (skip.at(i)) {
      // skip
    } else if (OB_ISNULL(left_expr = cur_expr->get_param_expr(0)) ||
               OB_ISNULL(right_expr = cur_expr->get_param_expr(1))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(left_expr), K(right_expr));
    } else if (ObOptimizerUtil::is_expr_equivalent(left_expr,
                                                   right_expr,
                                                   equal_sets)) {
      // remove preds which is equation between two exprs in the same equal sets
      OPT_TRACE("remove redundancy join condition:", cur_expr);
    } else {
      bool find = false;
      for (int64_t j = 0; OB_SUCC(ret) && !find && j < new_join_pred.count(); j++) {
        ObRawExpr *cur_new_expr = new_join_pred.at(j);
        ObRawExpr *left_new_expr = NULL;
        ObRawExpr *right_new_expr = NULL;
        if (OB_ISNULL(cur_new_expr)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(ret));
        } else if (cur_expr->get_expr_type() != cur_new_expr->get_expr_type()) {
          // skip
        } else if(OB_ISNULL(left_new_expr = cur_new_expr->get_param_expr(0)) ||
                  OB_ISNULL(right_new_expr = cur_new_expr->get_param_expr(1))) {
          LOG_WARN("get unexpected null", K(ret), K(left_new_expr), K(right_new_expr));
        } else if (ObOptimizerUtil::is_expr_equivalent(left_expr,
                                                       left_new_expr,
                                                       equal_sets) &&
                   ObOptimizerUtil::is_expr_equivalent(right_expr,
                                                       right_new_expr,
                                                       equal_sets)) {
          find = true;
        } else if (ObOptimizerUtil::is_expr_equivalent(left_expr,
                                                       right_new_expr,
                                                       equal_sets) &&
                   ObOptimizerUtil::is_expr_equivalent(right_expr,
                                                       left_new_expr,
                                                       equal_sets)) {
          find = true;
        }
      }
      if (OB_FAIL(ret)) {
      } else if (!find && OB_FAIL(new_join_pred.push_back(cur_expr))) {
        LOG_WARN("failed to push back", K(ret));
      } else if (find) {
        // remove preds which do not join the given two tables
        OPT_TRACE("remove redundancy join condition:", cur_expr);
O
oceanbase-admin 已提交
3768
      }
W
wangzelin.wzl 已提交
3769
    }
O
oceanbase-admin 已提交
3770 3771 3772 3773
  }
  return ret;
}

O
obdev 已提交
3774 3775 3776 3777
int ObLogPlan::inner_remove_redundancy_pred(ObIArray<ObRawExpr*> &join_pred,
                                            EqualSets &equal_sets,
                                            ObJoinOrder *left_tree,
                                            ObJoinOrder *right_tree)
O
oceanbase-admin 已提交
3778 3779
{
  int ret = OB_SUCCESS;
O
obdev 已提交
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813
  ObSEArray<ObRawExpr*, 4> new_join_pred;
  ObSEArray<bool, 4> has_checked;
  bool join_two_tables = true;
  ObRelIds left_table, right_table;
  if (OB_ISNULL(left_tree) || OB_ISNULL(right_tree)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected null", K(ret));
  } else if (OB_FAIL(join_side_from_one_table(*left_tree,
                                              join_pred,
                                              join_two_tables,
                                              left_table))) {
    LOG_WARN("failed to check there is only one left table", K(ret));
  } else if (join_two_tables &&
             OB_FAIL(join_side_from_one_table(*right_tree,
                                              join_pred,
                                              join_two_tables,
                                              right_table))) {
    LOG_WARN("failed to check there is only one right table", K(ret));
  } else if (join_two_tables &&
             (OB_UNLIKELY(left_table.num_members() != 1) ||
              OB_UNLIKELY(right_table.num_members() != 1))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected params", K(ret), K(left_table), K(right_table));
  } else if (has_checked.prepare_allocate(join_pred.count(), false)) {
    LOG_WARN("failed to allocate", K(ret));
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < join_pred.count(); i++) {
    ObRawExpr *cur_expr = join_pred.at(i);
    ObRawExpr *left_expr = NULL;
    ObRawExpr *right_expr = NULL;
    if (OB_ISNULL(cur_expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(cur_expr));
3814 3815 3816
    } else if (T_OP_EQ == cur_expr->get_expr_type() &&
               2 == cur_expr->get_param_count() &&
               cur_expr->get_param_expr(0) != cur_expr->get_param_expr(1)) {
O
obdev 已提交
3817 3818
      if (OB_ISNULL(left_expr = cur_expr->get_param_expr(0)) ||
          OB_ISNULL(right_expr = cur_expr->get_param_expr(1))) {
O
oceanbase-admin 已提交
3819
        ret = OB_ERR_UNEXPECTED;
O
obdev 已提交
3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844
        LOG_WARN("get unexpected null", K(ret), KPC(cur_expr), K(left_expr), K(right_expr));
      } else if (!join_two_tables) {
        // do nothing
      } else if (left_tree->get_tables().is_superset(left_expr->get_relation_ids()) &&
          right_tree->get_tables().is_superset(right_expr->get_relation_ids())) {
        // do nothing
      } else if (left_tree->get_tables().is_superset(right_expr->get_relation_ids()) &&
          right_tree->get_tables().is_superset(left_expr->get_relation_ids())) {
        std::swap(left_expr, right_expr);
      } else {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected expression", K(ret), KPC(cur_expr));
      }
      if (OB_FAIL(ret)) {
      } else if (join_two_tables &&
                 !(left_table.is_superset(left_expr->get_relation_ids()) &&
                   right_table.is_superset(right_expr->get_relation_ids()))) {
        // the pred does not join the given two tables,
        // decide whether remove this qual later
      } else if (ObOptimizerUtil::is_expr_equivalent(left_expr,
                                                     right_expr,
                                                     equal_sets)) {
        // remove preds which is equation between two exprs in the same equal sets
        has_checked.at(i) = true;
        OPT_TRACE("remove redundancy join condition:", cur_expr);
W
wangzelin.wzl 已提交
3845
      } else if (OB_FAIL(ObEqualAnalysis::compute_equal_set(&allocator_,
O
obdev 已提交
3846 3847 3848
                                                            cur_expr,
                                                            equal_sets,
                                                            equal_sets))) {
W
wangzelin.wzl 已提交
3849
        LOG_WARN("failed to compute equal sets for inner join", K(ret));
O
obdev 已提交
3850 3851 3852 3853
      } else if (OB_FAIL(new_join_pred.push_back(cur_expr))) {
        LOG_WARN("failed to push back", K(ret));
      } else {
        has_checked.at(i) = true;
O
oceanbase-admin 已提交
3854
      }
O
obdev 已提交
3855 3856 3857 3858
    } else if (OB_FAIL(new_join_pred.push_back(cur_expr))) {
      LOG_WARN("failed to push back", K(ret));
    } else {
      has_checked.at(i) = true;
O
oceanbase-admin 已提交
3859 3860
    }
  }
O
obdev 已提交
3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874

  if (OB_FAIL(ret)) {
  } else if (join_two_tables &&
             OB_FAIL(re_add_necessary_predicate(join_pred, new_join_pred,
                                                has_checked, equal_sets))) {
    LOG_WARN("failed to re-add preds", K(ret));
  } else if (new_join_pred.count() == join_pred.count()) {
  } else if (OB_UNLIKELY(new_join_pred.count() > join_pred.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected pred count", K(ret), K(new_join_pred), K(join_pred));
  } else if (OB_FAIL(join_pred.assign(new_join_pred))) {
    LOG_WARN("failed to assign exprs", K(ret));
  }
  OPT_TRACE("output join conditions:", join_pred);
O
oceanbase-admin 已提交
3875 3876 3877
  return ret;
}

W
wangzelin.wzl 已提交
3878 3879 3880
int ObLogPlan::try_split_or_qual(const ObRelIds &table_ids,
                                 ObOpRawExpr &or_qual,
                                 ObIArray<ObRawExpr*> &table_quals)
O
oceanbase-admin 已提交
3881 3882
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3883 3884 3885 3886 3887 3888
  ObOpRawExpr *new_expr = NULL;
  if (OB_FAIL(ObOptimizerUtil::split_or_qual_on_table(get_stmt(),
                                                      get_optimizer_context(),
                                                      table_ids,
                                                      or_qual,
                                                      new_expr))) {
O
oceanbase-admin 已提交
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
    LOG_WARN("failed to split or qual on table", K(ret));
  } else if (NULL == new_expr) {
    /* do nothing */
  } else if (ObOptimizerUtil::find_equal_expr(table_quals, new_expr)) {
    /* do nothing */
  } else if (OB_FAIL(table_quals.push_back(new_expr))) {
    LOG_WARN("failed to push back new expr", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
3900 3901
int ObLogPlan::generate_subplan_for_query_ref(ObQueryRefRawExpr *query_ref,
                                              SubPlanInfo *&subplan_info)
O
oceanbase-admin 已提交
3902 3903
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3904 3905 3906 3907
  // check if sub plan has been generated
  const ObSelectStmt *subquery = NULL;
  ObLogPlan *logical_plan = NULL;
  ObOptimizerContext &opt_ctx = get_optimizer_context();
O
obdev 已提交
3908 3909
  OPT_TRACE_TITLE("start generate subplan for subquery expr");
  OPT_TRACE_BEGIN_SECTION;
W
wangzelin.wzl 已提交
3910
  if (OB_ISNULL(subquery = query_ref->get_ref_stmt())) {
O
oceanbase-admin 已提交
3911
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
    LOG_WARN("subquery stmt is null", K(ret), K(query_ref));
  } else if (OB_ISNULL(opt_ctx.get_query_ctx())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("query ctx is null", K(ret));
  } else if (OB_ISNULL(logical_plan = opt_ctx.get_log_plan_factory().create(opt_ctx, *subquery))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to create plan", K(ret), K(opt_ctx.get_query_ctx()->get_sql_stmt()));
  } else if (OB_FAIL(logical_plan->init_plan_info())) {
    LOG_WARN("failed to init equal sets" ,K(ret));
  } else if (OB_FAIL(static_cast<ObSelectLogPlan *>(logical_plan)->generate_raw_plan())) {
    LOG_WARN("failed to optimize sub-select", K(ret));
O
oceanbase-admin 已提交
3923
  } else {
W
wangzelin.wzl 已提交
3924 3925 3926 3927 3928 3929 3930
    SubPlanInfo *info = static_cast<SubPlanInfo *>(get_allocator().alloc(sizeof(SubPlanInfo)));
    bool has_ref_assign_user_var = false;
    if (OB_ISNULL(info)) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_ERROR("failed to alloc semi info", K(ret));
    } else if (OB_FAIL(subquery->has_ref_assign_user_var(has_ref_assign_user_var))) {
      LOG_WARN("faield to check stmt has assignment ref user var", K(ret));
O
oceanbase-admin 已提交
3931
    } else {
W
wangzelin.wzl 已提交
3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945
      /**
           * 作为initplan的条件:
           * 1. 不含上层变量,如果含上层变量会在本层当作Const
           * 2. 不含存在赋值操作的用户变量
           */
      bool is_initplan = !query_ref->has_exec_param() && !has_ref_assign_user_var;
      info = new(info)SubPlanInfo(query_ref, logical_plan, is_initplan);
      if (OB_FAIL(add_subplan(info))) {
        LOG_WARN("failed to add sp params to rel", K(ret));
      } else {
        logical_plan->set_query_ref(query_ref);
        subplan_info = info;
        LOG_TRACE("succ to generate logical plan of sub-select");
      }
O
oceanbase-admin 已提交
3946
    }
W
wangzelin.wzl 已提交
3947 3948 3949 3950 3951 3952 3953

    if (OB_FAIL(ret) && NULL != info) {
      info->subplan_ = NULL; // we leave logical plan to be freed later
      info->~SubPlanInfo();
      info = NULL;
      subplan_info = NULL;
    } else { /* Do nothing */ }
O
oceanbase-admin 已提交
3954
  }
O
obdev 已提交
3955 3956
  OPT_TRACE_TITLE("end generate subplan for subquery expr");
  OPT_TRACE_END_SECTION;
O
oceanbase-admin 已提交
3957 3958 3959
  return ret;
}

W
wangzelin.wzl 已提交
3960 3961
//在已有sub_plan_infos中查找expr对应的subplan
int ObLogPlan::get_subplan(const ObRawExpr *expr, SubPlanInfo *&info)
O
oceanbase-admin 已提交
3962 3963
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
  info = NULL;
  bool found = false;
  for (int64_t i = 0; OB_SUCC(ret) && !found && i < get_subplans().count(); ++i) {
    if (OB_ISNULL(get_subplans().at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get_subplans().at(i) returns null", K(ret), K(i));
    } else if (get_subplans().at(i)->init_expr_ == expr) {
      info = get_subplans().at(i);
      found = true;
    } else { /* Do nothing */ }
O
oceanbase-admin 已提交
3974 3975 3976 3977
  }
  return ret;
}

W
wangzelin.wzl 已提交
3978
int ObLogPlan::get_subplan(const ObStmt *stmt, SubPlanInfo *&info)
O
oceanbase-admin 已提交
3979 3980
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991
  info = NULL;
  bool found = false;
  for (int64_t i = 0; OB_SUCC(ret) && !found && i < get_subplans().count(); ++i) {
    if (OB_ISNULL(get_subplans().at(i)) ||
        OB_ISNULL(get_subplans().at(i)->subplan_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get_subplans().at(i) returns null", K(ret), K(i));
    } else if (get_subplans().at(i)->subplan_->get_stmt() == stmt) {
      info = get_subplans().at(i);
      found = true;
    } else { /* Do nothing */ }
O
oceanbase-admin 已提交
3992 3993 3994 3995
  }
  return ret;
}

W
wangzelin.wzl 已提交
3996
int ObLogPlan::find_base_rel(ObIArray<ObJoinOrder *> &base_level, int64_t table_idx, ObJoinOrder *&base_rel)
O
oceanbase-admin 已提交
3997 3998
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012
  ObJoinOrder *cur_rel = NULL;
  bool find = false;
  base_rel = NULL;
  for (int64_t i = 0; OB_SUCC(ret) && !find && i < base_level.count(); ++i) {
    //如果是OJ,这里table_set_可能不止一项,所以不能认为cur_rel->table_set_.num_members() == 1
    if (OB_ISNULL(cur_rel = base_level.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(cur_rel));
    } else if (cur_rel->get_tables().has_member(table_idx)){
      find = true;
      base_rel = cur_rel;
      LOG_TRACE("succeed to find base rel", K(cur_rel->get_tables()), K(table_idx));
    } else { /* do nothing */ }
  }
O
oceanbase-admin 已提交
4013 4014 4015
  return ret;
}

W
wangzelin.wzl 已提交
4016
int ObLogPlan::find_join_rel(ObRelIds& relids, ObJoinOrder *&join_rel)
O
oceanbase-admin 已提交
4017 4018
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4019 4020 4021 4022 4023
  join_rel = NULL;
  if (relid_joinorder_map_.created() &&
      OB_FAIL(relid_joinorder_map_.get_refactored(relids, join_rel))) {
    if (ret != OB_HASH_NOT_EXIST) {
      LOG_WARN("failed to get refactored", K(ret), K(relids));
O
oceanbase-admin 已提交
4024
    } else {
W
wangzelin.wzl 已提交
4025
      ret = OB_SUCCESS;
O
oceanbase-admin 已提交
4026 4027 4028 4029 4030
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4031 4032 4033
int ObLogPlan::check_need_gen_join_path(const ObJoinOrder *left_tree,
                                        const ObJoinOrder *right_tree,
                                        bool &need_gen)
O
oceanbase-admin 已提交
4034 4035
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4036 4037 4038
  int hash_ret = OB_SUCCESS;
  need_gen = true;
  if (OB_ISNULL(left_tree) || OB_ISNULL(right_tree)) {
O
oceanbase-admin 已提交
4039
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
    LOG_WARN("invalid input join order", K(left_tree), K(right_tree), K(ret));
  } else if (join_path_set_.created()) {
    JoinPathPairInfo pair;
    pair.left_ids_ = left_tree->get_tables();
    pair.right_ids_ = right_tree->get_tables();
    hash_ret = join_path_set_.exist_refactored(pair);
    if (OB_HASH_EXIST == hash_ret) {
      need_gen = false;
    } else if (OB_HASH_NOT_EXIST == hash_ret) {
      // do nothing
    } else {
      ret = hash_ret != OB_SUCCESS ? hash_ret : OB_ERR_UNEXPECTED;
      LOG_WARN("failed to check hash set exsit", K(ret), K(hash_ret), K(pair));
O
oceanbase-admin 已提交
4053 4054 4055 4056 4057
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4058 4059
int ObLogPlan::allocate_function_table_path(FunctionTablePath *func_table_path,
                                            ObLogicalOperator *&out_access_path_op)
O
oceanbase-admin 已提交
4060 4061
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4062 4063 4064 4065
  ObLogFunctionTable *op = NULL;
  const TableItem *table_item = NULL;
  if (OB_ISNULL(func_table_path) || OB_ISNULL(get_stmt()) ||
      OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(func_table_path->table_id_))) {
O
oceanbase-admin 已提交
4066
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4067 4068 4069 4070 4071
    LOG_WARN("get unexpected null", K(func_table_path), K(get_stmt()), K(ret));
  } else if (OB_ISNULL(op = static_cast<ObLogFunctionTable*>(get_log_op_factory().
                                        allocate(*this, LOG_FUNCTION_TABLE)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate function table", K(ret));
O
oceanbase-admin 已提交
4072
  } else {
W
wangzelin.wzl 已提交
4073 4074 4075 4076 4077 4078 4079 4080 4081
    op->set_table_id(func_table_path->table_id_);
    op->add_values_expr(func_table_path->value_expr_);
    op->set_table_name(table_item->get_table_name());
    if (OB_FAIL(append(op->get_filter_exprs(), func_table_path->filter_))) {
      LOG_WARN("failed to append expr", K(ret));
    } else if (OB_FAIL(op->compute_property(func_table_path))) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      out_access_path_op = op;
O
oceanbase-admin 已提交
4082 4083 4084 4085 4086
    }
  }
  return ret;
}

O
obdev 已提交
4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122
int ObLogPlan::allocate_json_table_path(JsonTablePath *json_table_path,
                                        ObLogicalOperator *&out_access_path_op)
{
  int ret = OB_SUCCESS;
  ObLogJsonTable *op = NULL;
  TableItem *table_item = NULL;
  if (OB_ISNULL(json_table_path) || OB_ISNULL(get_stmt()) ||
      OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(json_table_path->table_id_))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(json_table_path), K(get_stmt()), K(ret));
  } else if (OB_ISNULL(op = static_cast<ObLogJsonTable*>(get_log_op_factory().
                                        allocate(*this, LOG_JSON_TABLE)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate json table path", K(ret));
  } else {
    op->set_table_id(json_table_path->table_id_);
    op->add_values_expr(json_table_path->value_expr_);
    op->set_table_name(table_item->get_table_name());
    ObJsonTableDef* tbl_def = table_item->get_json_table_def();

    if (OB_ISNULL(tbl_def)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpected param, table define can't be null", K(ret));
    } else if (OB_FAIL(append(op->get_origin_cols_def(), tbl_def->all_cols_))) {
      LOG_WARN("failed to append orgin defs", K(ret));
    } else if (OB_FAIL(append(op->get_filter_exprs(), json_table_path->filter_))) {
      LOG_WARN("failed to append expr", K(ret));
    } else if (OB_FAIL(op->compute_property(json_table_path))) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      out_access_path_op = op;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4123 4124
int ObLogPlan::allocate_temp_table_path(TempTablePath *temp_table_path,
                                        ObLogicalOperator *&out_access_path_op)
O
oceanbase-admin 已提交
4125 4126
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4127 4128 4129 4130
  const TableItem *table_item = NULL;
  ObLogTempTableAccess *op = NULL;
  if (OB_ISNULL(temp_table_path) || OB_ISNULL(get_stmt()) ||
      OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(temp_table_path->table_id_))) {
O
oceanbase-admin 已提交
4131
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149
    LOG_WARN("get unexpected null", K(temp_table_path), K(get_stmt()), K(table_item), K(ret));
  } else if (OB_ISNULL(op = static_cast<ObLogTempTableAccess*>
               (log_op_factory_.allocate(*this, LOG_TEMP_TABLE_ACCESS)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("allocate memory for ObLogFunctionTableScan failed", K(ret));
  } else {
    op->set_table_id(temp_table_path->table_id_);
    op->set_temp_table_id(temp_table_path->temp_table_id_);
    op->get_table_name().assign_ptr(table_item->table_name_.ptr(),
                                    table_item->table_name_.length());
    op->get_access_name().assign_ptr(table_item->alias_name_.ptr(),
                                     table_item->alias_name_.length());
    if (OB_FAIL(op->get_filter_exprs().assign(temp_table_path->filter_))) {
      LOG_WARN("failed to assign filter exprs", K(ret));
    } else if (OB_FAIL(op->compute_property(temp_table_path))) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      out_access_path_op = op;
O
oceanbase-admin 已提交
4150 4151 4152 4153 4154
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4155 4156
int ObLogPlan::allocate_cte_table_path(CteTablePath *cte_table_path,
                                       ObLogicalOperator *&out_access_path_op)
O
oceanbase-admin 已提交
4157 4158
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4159 4160 4161 4162
  ObLogTableScan *scan = NULL;
  const TableItem *table_item = NULL;
  if (OB_ISNULL(get_stmt()) || OB_ISNULL(cte_table_path) ||
      OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(cte_table_path->table_id_))) {
O
oceanbase-admin 已提交
4163
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4164 4165 4166 4167 4168
    LOG_WARN("get unexpected null", K(get_stmt()), K(table_item), K(ret));
  } else if (OB_UNLIKELY(NULL == (scan = static_cast<ObLogTableScan *>
                 (get_log_op_factory().allocate(*this, LOG_TABLE_SCAN))))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate table/index operator", K(ret));
O
oceanbase-admin 已提交
4169
  } else {
W
wangzelin.wzl 已提交
4170 4171 4172 4173 4174 4175 4176 4177
    scan->set_table_id(cte_table_path->table_id_);
    scan->set_ref_table_id(cte_table_path->ref_table_id_);
    scan->set_index_table_id(cte_table_path->ref_table_id_);
    scan->set_table_name(table_item->get_table_name());
    if (OB_FAIL(scan->get_filter_exprs().assign(cte_table_path->filter_))) {
      LOG_WARN("failed to set filters", K(ret));
    } else if (OB_FAIL(scan->compute_property(cte_table_path))) {
      LOG_WARN("failed to compute property", K(ret));
O
oceanbase-admin 已提交
4178
    } else {
W
wangzelin.wzl 已提交
4179
      out_access_path_op = scan;
O
oceanbase-admin 已提交
4180 4181 4182 4183 4184
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4185 4186
int ObLogPlan::allocate_access_path(AccessPath *ap,
                                    ObLogicalOperator *&out_access_path_op)
O
oceanbase-admin 已提交
4187 4188
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4189 4190 4191 4192
  ObLogTableScan *scan = NULL;
  ObSqlSchemaGuard *schema_guard = NULL;
  const ObTableSchema *table_schema = NULL;
  const TableItem *table_item = NULL;
O
obdev 已提交
4193
  if (OB_ISNULL(ap) || OB_ISNULL(get_stmt()) || OB_ISNULL(ap->parent_)
W
wangzelin.wzl 已提交
4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207
      || OB_ISNULL(ap->get_strong_sharding()) || OB_ISNULL(ap->table_partition_info_)
      || OB_ISNULL(schema_guard = get_optimizer_context().get_sql_schema_guard())
      || OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(ap->get_table_id()))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ap), K(get_stmt()),
        K(schema_guard), K(table_item), K(ret));
  } else if (OB_FAIL(schema_guard->get_table_schema(ap->table_id_, ap->ref_table_id_, get_stmt(), table_schema))) {
    LOG_WARN("fail to get_table_schema", K(ret));
  } else if (OB_ISNULL(scan = static_cast<ObLogTableScan *>
                 (get_log_op_factory().allocate(*this, ObLogOpType::LOG_TABLE_SCAN)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate table/index operator", K(ret));
  } else if (OB_FAIL(scan->set_est_row_count_record(ap->est_records_))) {
    LOG_WARN("failed to set estimation info", K(ret));
O
oceanbase-admin 已提交
4208
  } else {
W
wangzelin.wzl 已提交
4209 4210 4211 4212 4213 4214 4215 4216
    scan->set_est_cost_info(&ap->get_cost_table_scan_info());
    scan->set_flashback_query_expr(table_item->flashback_query_expr_);
    scan->set_flashback_query_type(table_item->flashback_query_type_);
    scan->set_table_id(ap->get_table_id());
    scan->set_ref_table_id(ap->get_ref_table_id());
    scan->set_index_table_id(ap->get_index_table_id());
    scan->set_scan_direction(ap->order_direction_);
    scan->set_is_index_global(ap->is_global_index_);
O
obdev 已提交
4217
    scan->set_index_back(ap->est_cost_info_.index_meta_info_.is_index_back_);
O
obdev 已提交
4218
    scan->set_is_spatial_index(ap->est_cost_info_.index_meta_info_.is_geo_index_);
W
wangzelin.wzl 已提交
4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
    scan->set_use_das(ap->use_das_);
    scan->set_table_partition_info(ap->table_partition_info_);
    scan->set_table_opt_info(ap->table_opt_info_);
    scan->set_access_path(ap);
    scan->set_dblink_id(table_item->dblink_id_); // will be delete after implement log_link_table_scan
    scan->set_sample_info(ap->sample_info_);
    if (NULL != table_schema && table_schema->is_tmp_table()) {
      scan->set_session_id(table_schema->get_session_id());
    }
    scan->set_table_row_count(ap->table_row_count_);
    scan->set_output_row_count(ap->output_row_count_);
    scan->set_phy_query_range_row_count(ap->phy_query_range_row_count_);
    scan->set_query_range_row_count(ap->query_range_row_count_);
    scan->set_index_back_row_count(ap->index_back_row_count_);
    scan->set_estimate_method(ap->est_cost_info_.row_est_method_);
    scan->set_pre_query_range(ap->pre_query_range_);
4235
    scan->set_skip_scan(OptSkipScanState::SS_DISABLE != ap->use_skip_scan_);
W
wangzelin.wzl 已提交
4236
    if (!ap->is_inner_path_ &&
4237 4238
        OB_FAIL(scan->set_query_ranges(ap->get_cost_table_scan_info().ranges_,
                                       ap->get_cost_table_scan_info().ss_ranges_))) {
W
wangzelin.wzl 已提交
4239 4240 4241
      LOG_WARN("failed to set query ranges", K(ret));
    } else if (OB_FAIL(scan->set_range_columns(ap->get_cost_table_scan_info().range_columns_))) {
      LOG_WARN("failed to set range column", K(ret));
O
obdev 已提交
4242 4243
    } else if (OB_FAIL(append(scan->get_server_list(), ap->get_server_list()))) {
      LOG_WARN("failed to assign server list", K(ret));
W
wangzelin.wzl 已提交
4244 4245 4246 4247 4248 4249
    } else { // set table name and index name
      scan->set_table_name(table_item->get_table_name());
      scan->set_diverse_path_count(ap->parent_->get_diverse_path_count());
      if (ap->get_index_table_id() != ap->get_ref_table_id()) {
        if (OB_FAIL(store_index_column_ids(*schema_guard, *scan, ap->get_table_id(), ap->get_index_table_id()))) {
          LOG_WARN("Failed to store index column id", K(ret));
O
oceanbase-admin 已提交
4250 4251 4252 4253
        }
      }
    }

W
wangzelin.wzl 已提交
4254
    if (OB_SUCC(ret)) {
O
obdev 已提交
4255 4256
      if (OB_FAIL(scan->set_table_scan_filters(ap->filter_))) {
        LOG_WARN("failed to set filters", K(ret));
W
wangzelin.wzl 已提交
4257 4258
      } else if (OB_FAIL(append(scan->get_pushdown_filter_exprs(), ap->pushdown_filters_))) {
        LOG_WARN("failed to append pushdown filters", K(ret));
O
obdev 已提交
4259 4260
      }
    }
W
wangzelin.wzl 已提交
4261 4262

    //init part/subpart expr for query range prune
O
oceanbase-admin 已提交
4263
    if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
4264 4265 4266 4267 4268 4269 4270
      ObRawExpr *part_expr = NULL;
      ObRawExpr *subpart_expr = NULL;
      uint64_t table_id = scan->get_table_id();
      uint64_t ref_table_id = scan->get_location_table_id();
      share::schema::ObPartitionLevel part_level = share::schema::PARTITION_LEVEL_MAX;
      if (is_virtual_table(ref_table_id)
          || is_inner_table(ref_table_id)
O
obdev 已提交
4271
          || is_cte_table(ref_table_id)) {
W
wangzelin.wzl 已提交
4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
        // do nothing
      } else if (OB_FAIL(get_part_exprs(table_id,
                                        ref_table_id,
                                        part_level,
                                        part_expr,
                                        subpart_expr))) {
        LOG_WARN("failed to get part exprs", K(ret));
      } else {
        scan->set_part_expr(part_expr);
        scan->set_subpart_expr(subpart_expr);
O
oceanbase-admin 已提交
4282 4283 4284
      }
    }

W
wangzelin.wzl 已提交
4285
    if (OB_SUCC(ret) && OB_FAIL(scan->compute_property(ap))) {
O
oceanbase-admin 已提交
4286 4287 4288
      LOG_WARN("failed to compute property", K(ret));
    }

W
wangzelin.wzl 已提交
4289
    if (OB_SUCC(ret)) {
O
obdev 已提交
4290
      if (ap->is_global_index_ && scan->get_index_back()) {
W
wangzelin.wzl 已提交
4291 4292
        if (OB_FAIL(scan->init_calc_part_id_expr())) {
          LOG_WARN("failed to init calc part id expr", K(ret));
O
oceanbase-admin 已提交
4293
        } else {
O
obdev 已提交
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307
          scan->set_global_index_back_table_partition_info(ap->parent_->get_table_partition_info());
          if (ap->est_cost_info_.table_filters_.count() > 0) {
            bool has_index_scan_filter = false;
            bool has_index_lookup_filter = false;
            if (OB_FAIL(get_has_global_index_filters(ap->filter_,
                                                     scan->get_idx_columns(),
                                                     has_index_scan_filter,
                                                     has_index_lookup_filter))) {
              LOG_WARN("failed to get has global index filters", K(ret));
            } else {
              scan->set_has_index_scan_filter(has_index_scan_filter);
              scan->set_has_index_lookup_filter(has_index_lookup_filter);
            }
          }
O
oceanbase-admin 已提交
4308 4309 4310
        }
      }
    }
O
obdev 已提交
4311 4312 4313
    if (OB_SUCC(ret)) {
      out_access_path_op = scan;
    }
O
oceanbase-admin 已提交
4314 4315 4316 4317
  }
  return ret;
}

O
obdev 已提交
4318 4319 4320 4321
int ObLogPlan::get_has_global_index_filters(const ObIArray<ObRawExpr*> &filter_exprs,
                                            const ObIArray<uint64_t> &index_columns,
                                            bool &has_index_scan_filter,
                                            bool &has_index_lookup_filter)
O
oceanbase-admin 已提交
4322 4323
{
  int ret = OB_SUCCESS;
O
obdev 已提交
4324 4325
  has_index_scan_filter = false;
  has_index_lookup_filter = false;
O
oceanbase-admin 已提交
4326
  ObSEArray<bool, 4> filter_before_index_back;
W
wangzelin.wzl 已提交
4327 4328 4329
  if (OB_FAIL(ObOptimizerUtil::check_filter_before_indexback(filter_exprs,
                                                             index_columns,
                                                             filter_before_index_back))) {
O
oceanbase-admin 已提交
4330
    LOG_WARN("Failed to check filter before index back", K(ret));
W
wangzelin.wzl 已提交
4331
  } else if (OB_UNLIKELY(filter_before_index_back.count() != filter_exprs.count())) {
O
oceanbase-admin 已提交
4332
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4333 4334
    LOG_WARN("unequal array size", K(filter_before_index_back.count()),
        K(filter_exprs.count()), K(ret));
O
oceanbase-admin 已提交
4335 4336
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < filter_before_index_back.count(); i++) {
W
wangzelin.wzl 已提交
4337
      if (OB_ISNULL(filter_exprs.at(i))) {
O
oceanbase-admin 已提交
4338 4339
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("null expr", K(ret));
W
wangzelin.wzl 已提交
4340 4341
      } else if (filter_before_index_back.at(i) &&
                 !filter_exprs.at(i)->has_flag(CNT_SUB_QUERY)) {
O
obdev 已提交
4342
        has_index_scan_filter = true;
O
oceanbase-admin 已提交
4343
      } else {
O
obdev 已提交
4344
        has_index_lookup_filter = true;
O
oceanbase-admin 已提交
4345 4346 4347 4348 4349 4350
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4351 4352 4353 4354 4355
int ObLogPlan::store_index_column_ids(
    ObSqlSchemaGuard &schema_guard,
    ObLogTableScan &scan,
    const int64_t table_id,
    const int64_t index_id)
O
oceanbase-admin 已提交
4356 4357 4358
{
  int ret = OB_SUCCESS;
  ObString index_name;
W
wangzelin.wzl 已提交
4359 4360
  const ObTableSchema *index_schema = NULL;
  if (OB_FAIL(schema_guard.get_table_schema(table_id, index_id, get_stmt(), index_schema))) {
O
oceanbase-admin 已提交
4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374
    ret = OB_SCHEMA_ERROR;
    LOG_WARN("set index name error", K(ret), K(index_id), K(index_schema));
  } else {
    if (index_schema->is_materialized_view()) {
      index_name = index_schema->get_table_name_str();
    } else {
      if (OB_FAIL(index_schema->get_index_name(index_name))) {
        LOG_WARN("fail to get index name", K(index_name), K(ret));
      }
    }
  }
  if (OB_SUCC(ret)) {
    scan.set_index_name(index_name);
    for (ObTableSchema::const_column_iterator iter = index_schema->column_begin();
W
wangzelin.wzl 已提交
4375
        OB_SUCC(ret) && iter != index_schema->column_end(); ++iter) {
O
oceanbase-admin 已提交
4376 4377 4378 4379
      if (OB_ISNULL(iter)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("iter is null", K(ret), K(iter));
      } else {
W
wangzelin.wzl 已提交
4380
        const ObColumnSchemaV2 *column_schema = *iter;
O
oceanbase-admin 已提交
4381 4382 4383 4384 4385
        if (OB_ISNULL(column_schema)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("column_schema is null", K(ret));
        } else if (OB_FAIL(scan.add_idx_column_id(column_schema->get_column_id()))) {
          LOG_WARN("Fail to add column id to scan", K(ret));
W
wangzelin.wzl 已提交
4386
        } else { }//do nothing
O
oceanbase-admin 已提交
4387 4388 4389 4390 4391 4392
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4393 4394
int ObLogPlan::allocate_join_path(JoinPath *join_path,
                                  ObLogicalOperator *&out_join_path_op)
O
oceanbase-admin 已提交
4395 4396
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4397
  ObJoinOrder *join_order = NULL;
O
oceanbase-admin 已提交
4398 4399 4400 4401
  if (OB_ISNULL(join_path) || OB_ISNULL(join_order = join_path->parent_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(join_path), K(join_order));
  } else {
W
wangzelin.wzl 已提交
4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412
    Path *left_path = const_cast<Path*>(join_path->left_path_);
    Path *right_path = const_cast<Path*>(join_path->right_path_);
    ObLogicalOperator *left_child = NULL;
    ObLogicalOperator *right_child = NULL;
    ObExchangeInfo left_exch_info;
    bool left_exch_is_non_preserve_side = (join_path->is_naaj_
                                            && RIGHT_ANTI_JOIN == join_path->join_type_);
    ObExchangeInfo right_exch_info;
    bool right_exch_is_non_preserve_side = (join_path->is_naaj_
                                             && LEFT_ANTI_JOIN == join_path->join_type_);
    ObLogJoin *join_op = NULL;
O
oceanbase-admin 已提交
4413 4414 4415
    if (OB_ISNULL(left_path) || OB_ISNULL(right_path)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(left_path), K(right_path));
Z
zzg19950727 已提交
4416 4417
    } else if (OB_FAIL(SMART_CALL(create_plan_tree_from_path(left_path, left_child))) ||
               OB_FAIL(SMART_CALL(create_plan_tree_from_path(right_path, right_child)))) {
O
oceanbase-admin 已提交
4418 4419 4420 4421
      LOG_WARN("failed to create plan tree from path", K(ret));
    } else if (OB_ISNULL(left_child) || OB_ISNULL(right_child)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get expected null", K(left_child), K(right_child), K(ret));
W
wangzelin.wzl 已提交
4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444
    } else if (OB_FAIL(compute_join_exchange_info(*join_path, left_exch_info, right_exch_info,
                        left_exch_is_non_preserve_side, right_exch_is_non_preserve_side))) {
      LOG_WARN("failed to compute join exchange info", K(ret));
    } else if (OB_FAIL(allocate_sort_and_exchange_as_top(left_child,
                                                         left_exch_info,
                                                         join_path->left_sort_keys_,
                                                         join_path->left_need_sort_,
                                                         join_path->left_prefix_pos_,
                                                         join_path->is_left_local_order()))) {
      LOG_WARN("failed to allocate operator for child", K(ret));
    } else if (OB_FAIL(allocate_sort_and_exchange_as_top(right_child,
                                                         right_exch_info,
                                                         join_path->right_sort_keys_,
                                                         join_path->right_need_sort_,
                                                         join_path->right_prefix_pos_,
                                                         join_path->is_right_local_order()))) {
      LOG_WARN("failed to allocate operator for child", K(ret));
    } else if (join_path->need_mat_ && OB_FAIL(allocate_material_as_top(right_child))) {
      LOG_WARN("failed to allocate material as top", K(ret));
    } else if (OB_ISNULL(left_child) || OB_ISNULL(right_child)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(left_child), K(right_child), K(ret));
    } else if (OB_ISNULL(join_op = static_cast<ObLogJoin *>(get_log_op_factory().allocate(*this, LOG_JOIN)))) {
O
oceanbase-admin 已提交
4445 4446
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_ERROR("failed to allocate join_op operator", K(ret));
W
wangzelin.wzl 已提交
4447 4448
    } else if (OB_FAIL(join_op->set_join_filter_infos(join_path->join_filter_infos_))) {
      LOG_WARN("failed to set join filter infos", K(ret));
O
oceanbase-admin 已提交
4449
    } else {
W
wangzelin.wzl 已提交
4450 4451 4452 4453
      //此时EXCHANGE-IN算子不能继承EXCHANGE_OUT的并行度,需要设置成与JOIN算子相同的并行度
      if (log_op_def::LOG_EXCHANGE == left_child->get_type()) {
        left_child->set_parallel(join_path->parallel_);
        left_child->set_server_cnt(join_path->server_cnt_);
O
obdev 已提交
4454 4455 4456
        if (OB_FAIL(left_child->get_server_list().assign(join_path->get_server_list()))) {
          LOG_WARN("failed to assign server list", K(ret));
        }
W
wangzelin.wzl 已提交
4457 4458 4459 4460
      }
      if (log_op_def::LOG_EXCHANGE == right_child->get_type()) {
        right_child->set_parallel(join_path->parallel_);
        right_child->set_server_cnt(join_path->server_cnt_);
O
obdev 已提交
4461 4462 4463
        if (OB_FAIL(right_child->get_server_list().assign(join_path->get_server_list()))) {
          LOG_WARN("failed to assign server list", K(ret));
        }
O
oceanbase-admin 已提交
4464 4465 4466 4467 4468
      }
      join_op->set_left_child(left_child);
      join_op->set_right_child(right_child);
      join_op->set_join_type(join_path->join_type_);
      join_op->set_join_algo(join_path->join_algo_);
W
wangzelin.wzl 已提交
4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
      join_op->set_join_distributed_method(join_path->join_dist_algo_);
      join_op->set_slave_mapping_type(join_path->get_slave_mapping_type());
      join_op->set_is_partition_wise(join_path->is_partition_wise());
      join_op->set_can_use_batch_nlj(join_path->can_use_batch_nlj_);
      join_op->set_join_path(join_path);
      if (OB_FAIL(join_op->get_dup_table_pos().push_back(join_path->get_left_dup_table_pos())) ||
          OB_FAIL(join_op->get_dup_table_pos().push_back(join_path->get_right_dup_table_pos()))) {
        LOG_WARN("failed to push back to array", K(ret));
      } else if (OB_FAIL(join_op->set_merge_directions(join_path->merge_directions_))) {
        LOG_WARN("failed to set merge directions", K(ret));
      } else if (OB_FAIL(join_op->set_nl_params(static_cast<AccessPath*>(right_path)->nl_params_))) {
        LOG_WARN("failed to set nl params", K(ret));
      } else if (OB_FAIL(join_op->set_join_conditions(join_path->equal_join_conditions_))) {
O
oceanbase-admin 已提交
4482 4483
        LOG_WARN("append error in allocate_join_path", K(ret));
      } else if (IS_OUTER_OR_CONNECT_BY_JOIN(join_path->join_type_)) {
W
wangzelin.wzl 已提交
4484
        if (OB_FAIL(append(join_op->get_join_filters(), join_path->other_join_conditions_))) {
O
oceanbase-admin 已提交
4485 4486 4487 4488
          LOG_WARN("failed to allocate filter", K(ret));
        } else if (OB_FAIL(append(join_op->get_filter_exprs(), join_path->filter_))) {
          LOG_WARN("failed to allocate filter", K(ret));
        } else {
W
wangzelin.wzl 已提交
4489
          LOG_TRACE("connect by join exec params", K(join_path->other_join_conditions_), K(ret));
O
oceanbase-admin 已提交
4490
        }
W
wangzelin.wzl 已提交
4491
      } else if (OB_FAIL(append(join_op->get_join_filters(), join_path->other_join_conditions_))) {
O
oceanbase-admin 已提交
4492
        LOG_WARN("failed to allocate filter", K(ret));
W
wangzelin.wzl 已提交
4493 4494 4495
      } else if (OB_FAIL(append(join_op->get_join_filters(), join_path->filter_))) {
        LOG_WARN("failed to allocate filter", K(ret));
      } else { /* do nothing */}
O
oceanbase-admin 已提交
4496 4497

      if (OB_SUCC(ret) && CONNECT_BY_JOIN == join_path->join_type_) {
W
wangzelin.wzl 已提交
4498 4499 4500
        if (OB_FAIL(set_connect_by_property(join_path, *join_op))) {
          LOG_WARN("failed to set connect by property", K(ret));
        } else { /*do nothing*/ }
O
oceanbase-admin 已提交
4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515
      }
      // compute property for join
      // (equal sets, unique sets, est_sel_info, cost, card, width)
      if (OB_SUCC(ret)) {
        if (OB_FAIL(join_op->compute_property(join_path))) {
          LOG_WARN("failed to compute property for join op", K(ret));
        } else {
          out_join_path_op = join_op;
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4516 4517 4518 4519 4520
int ObLogPlan::compute_join_exchange_info(JoinPath &join_path,
                                          ObExchangeInfo &left_exch_info,
                                          ObExchangeInfo &right_exch_info,
                                          bool left_is_non_preserve_side,
                                          bool right_is_non_preserve_side)
O
oceanbase-admin 已提交
4521 4522
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538
  EqualSets equal_sets;
  ObSEArray<ObRawExpr*, 8> left_keys;
  ObSEArray<ObRawExpr*, 8> right_keys;
  ObSEArray<bool, 8> null_safe_info;
  SlaveMappingType sm_type = join_path.get_slave_mapping_type();
  left_exch_info.dist_method_ = ObPQDistributeMethod::NONE;
  right_exch_info.dist_method_ = ObPQDistributeMethod::NONE;
  if (OB_ISNULL(join_path.left_path_) || OB_ISNULL(join_path.left_path_->parent_) ||
      OB_ISNULL(join_path.right_path_) || OB_ISNULL(join_path.right_path_->parent_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(join_path.left_path_), K(join_path.right_path_), K(ret));
  } else if (OB_FAIL(append(equal_sets, join_path.left_path_->parent_->get_output_equal_sets())) ||
             OB_FAIL(append(equal_sets, join_path.right_path_->parent_->get_output_equal_sets()))) {
    LOG_WARN("failed to append equal sets", K(ret));
  } else if (OB_FAIL(get_join_path_keys(join_path, left_keys, right_keys, null_safe_info))) {
    LOG_WARN("failed to get join path keys", K(ret));
O
obdev 已提交
4539 4540
  } else if (DistAlgo::DIST_PARTITION_WISE == join_path.join_dist_algo_ ||
             DistAlgo::DIST_EXT_PARTITION_WISE == join_path.join_dist_algo_) {
W
wangzelin.wzl 已提交
4541
    if (join_path.is_slave_mapping_) {
O
obdev 已提交
4542 4543 4544
      if (OB_FAIL(compute_hash_distribution_info(join_path.join_type_,
                                                 join_path.use_hybrid_hash_dm_,
                                                 join_path.equal_join_conditions_,
W
wangzelin.wzl 已提交
4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569
                                                 join_path.left_path_->parent_->get_output_tables(),
                                                 left_exch_info,
                                                 right_exch_info))) {
        LOG_WARN("failed to compute exchange info for hash distribution", K(ret));
      } else {
        left_exch_info.slave_mapping_type_ = sm_type;
        right_exch_info.slave_mapping_type_ = sm_type;
      }
    } else { /*do nothing*/ }
  } else if (DistAlgo::DIST_PARTITION_NONE == join_path.join_dist_algo_) {
    ObPQDistributeMethod::Type unmatch_method = ObPQDistributeMethod::DROP;
    if (LEFT_ANTI_JOIN == join_path.join_type_ ||
        LEFT_OUTER_JOIN == join_path.join_type_ ||
        FULL_OUTER_JOIN == join_path.join_type_) {
      unmatch_method = ObPQDistributeMethod::RANDOM;
    }
    if (OB_FAIL(compute_repartition_distribution_info(equal_sets,
                                                      left_keys,
                                                      right_keys,
                                                      *join_path.right_path_,
                                                       left_exch_info))) {
      LOG_WARN("failed to compute repartition distribution info", K(ret));
    } else {
      left_exch_info.unmatch_row_dist_method_ = unmatch_method;
      if (join_path.is_slave_mapping_) {
O
obdev 已提交
4570 4571 4572
        if (OB_FAIL(compute_hash_distribution_info(join_path.join_type_,
                                                   join_path.use_hybrid_hash_dm_,
                                                   join_path.equal_join_conditions_,
W
wangzelin.wzl 已提交
4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
                                                   join_path.left_path_->parent_->get_output_tables(),
                                                   left_exch_info,
                                                   right_exch_info))) {
          LOG_WARN("failed to compute hash distribution info", K(ret));
        } else {
          left_exch_info.dist_method_ = ObPQDistributeMethod::PARTITION_HASH;
          right_exch_info.dist_method_ = ObPQDistributeMethod::HASH;
          left_exch_info.slave_mapping_type_ = sm_type;
          right_exch_info.slave_mapping_type_ = sm_type;
        }
      }
    }
  } else if (DistAlgo::DIST_NONE_PARTITION == join_path.join_dist_algo_) {
    ObPQDistributeMethod::Type unmatch_method = ObPQDistributeMethod::DROP;
    if (RIGHT_ANTI_JOIN == join_path.join_type_ ||
        RIGHT_OUTER_JOIN == join_path.join_type_ ||
        FULL_OUTER_JOIN == join_path.join_type_) {
      unmatch_method = ObPQDistributeMethod::RANDOM;
    }
    if (OB_FAIL(compute_repartition_distribution_info(equal_sets,
                                                      right_keys,
                                                      left_keys,
                                                      *join_path.left_path_,
                                                       right_exch_info))) {
      LOG_WARN("failed to compute repartition distribution_info", K(ret));
O
oceanbase-admin 已提交
4598
    } else {
W
wangzelin.wzl 已提交
4599 4600
      right_exch_info.unmatch_row_dist_method_ = unmatch_method;
      if (join_path.is_slave_mapping_) {
O
obdev 已提交
4601 4602 4603
        if (OB_FAIL(compute_hash_distribution_info(join_path.join_type_,
                                                   join_path.use_hybrid_hash_dm_,
                                                   join_path.equal_join_conditions_,
W
wangzelin.wzl 已提交
4604 4605 4606 4607 4608 4609 4610 4611 4612
                                                   join_path.left_path_->parent_->get_output_tables(),
                                                   left_exch_info,
                                                   right_exch_info))) {
          LOG_WARN("failed to compute hash distribution info", K(ret));
        } else {
          left_exch_info.dist_method_ = ObPQDistributeMethod::HASH;
          right_exch_info.dist_method_ = ObPQDistributeMethod::PARTITION_HASH;
          left_exch_info.slave_mapping_type_ = sm_type;
          right_exch_info.slave_mapping_type_ = sm_type;
O
oceanbase-admin 已提交
4613 4614 4615
        }
      }
    }
W
wangzelin.wzl 已提交
4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
  } else if (DistAlgo::DIST_BC2HOST_NONE == join_path.join_dist_algo_) {
     left_exch_info.dist_method_ = ObPQDistributeMethod::BC2HOST;
  } else if (DistAlgo::DIST_BROADCAST_NONE == join_path.join_dist_algo_) {
    if (!join_path.is_slave_mapping_) {
       left_exch_info.dist_method_ = ObPQDistributeMethod::BROADCAST;
    } else {
      if (OB_FAIL(compute_repartition_distribution_info(equal_sets,
                                                        left_keys,
                                                        right_keys,
                                                        *join_path.right_path_,
                                                        left_exch_info))) {
        LOG_WARN("failed to compute repartition distrubution info", K(ret));
      } else {
        left_exch_info.repartition_type_ = OB_REPARTITION_NO_REPARTITION;
        left_exch_info.dist_method_ = ObPQDistributeMethod::SM_BROADCAST;
        left_exch_info.slave_mapping_type_ = sm_type;
      }
    }
  } else if (DistAlgo::DIST_NONE_BROADCAST == join_path.join_dist_algo_) {
    if (!join_path.is_slave_mapping_) {
      right_exch_info.dist_method_ = ObPQDistributeMethod::BROADCAST;
    } else {
      if (OB_FAIL(compute_repartition_distribution_info(equal_sets,
                                                        right_keys,
                                                        left_keys,
                                                        *join_path.left_path_,
                                                        right_exch_info))) {
        LOG_WARN("failed to compute repartition distribution_info", K(ret));
      } else {
        right_exch_info.repartition_type_ = OB_REPARTITION_NO_REPARTITION;
        right_exch_info.dist_method_ = ObPQDistributeMethod::SM_BROADCAST;
        right_exch_info.slave_mapping_type_ = sm_type;
      }
    }
O
obdev 已提交
4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685
  } else if (DistAlgo::DIST_HASH_NONE == join_path.join_dist_algo_) {
    ObPQDistributeMethod::Type unmatch_method = ObPQDistributeMethod::DROP;
    if (LEFT_ANTI_JOIN == join_path.join_type_ ||
        LEFT_OUTER_JOIN == join_path.join_type_ ||
        FULL_OUTER_JOIN == join_path.join_type_) {
      unmatch_method = ObPQDistributeMethod::RANDOM;
    }
    if (OB_FAIL(compute_single_side_hash_distribution_info(equal_sets,
                                                           left_keys,
                                                           right_keys,
                                                           *join_path.right_path_,
                                                           left_exch_info))) {
      LOG_WARN("failed to compute left hash distribution info", K(ret));
    } else {
      left_exch_info.dist_method_ = ObPQDistributeMethod::HASH;
      right_exch_info.dist_method_ = ObPQDistributeMethod::NONE;
      right_exch_info.unmatch_row_dist_method_ = unmatch_method;
    }
  } else if (DistAlgo::DIST_NONE_HASH == join_path.join_dist_algo_) {
    ObPQDistributeMethod::Type unmatch_method = ObPQDistributeMethod::DROP;
    if (RIGHT_ANTI_JOIN == join_path.join_type_ ||
        RIGHT_OUTER_JOIN == join_path.join_type_ ||
        FULL_OUTER_JOIN == join_path.join_type_) {
      unmatch_method = ObPQDistributeMethod::RANDOM;
    }
    if (OB_FAIL(compute_single_side_hash_distribution_info(equal_sets,
                                                           right_keys,
                                                           left_keys,
                                                           *join_path.left_path_,
                                                           right_exch_info))) {
      LOG_WARN("failed to compute left hash distribution info", K(ret));
    } else {
      left_exch_info.dist_method_ = ObPQDistributeMethod::NONE;
      right_exch_info.dist_method_ = ObPQDistributeMethod::HASH;
      left_exch_info.unmatch_row_dist_method_ = unmatch_method;
    }
W
wangzelin.wzl 已提交
4686
  } else if (DistAlgo::DIST_HASH_HASH == join_path.join_dist_algo_) {
O
obdev 已提交
4687 4688 4689
    if (OB_FAIL(compute_hash_distribution_info(join_path.join_type_,
                                               join_path.use_hybrid_hash_dm_,
                                               join_path.equal_join_conditions_,
W
wangzelin.wzl 已提交
4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709
                                               join_path.left_path_->parent_->get_output_tables(),
                                               left_exch_info,
                                               right_exch_info))) {
      LOG_WARN("failed to compute hash distribution info", K(ret));
    } else { /* do nothing*/ }
  } else if (DistAlgo::DIST_PULL_TO_LOCAL == join_path.join_dist_algo_) {
    if (join_path.left_path_->is_sharding() && !join_path.left_path_->contain_fake_cte()) {
      left_exch_info.dist_method_ = ObPQDistributeMethod::LOCAL;
    }
    if (join_path.right_path_->is_sharding() && !join_path.right_path_->contain_fake_cte()) {
      right_exch_info.dist_method_ = ObPQDistributeMethod::LOCAL;
    }
  } else if (DistAlgo::DIST_NONE_ALL == join_path.join_dist_algo_ ||
             DistAlgo::DIST_ALL_NONE == join_path.join_dist_algo_) {
    // do nothing
  } else { /*do nothing*/ }

  if (OB_SUCC(ret)) {
    // support null skew handling
    compute_null_distribution_info(join_path.join_type_, left_exch_info, right_exch_info, null_safe_info);
O
oceanbase-admin 已提交
4710 4711
  }

W
wangzelin.wzl 已提交
4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725
  if (OB_SUCC(ret)) {
    if (left_exch_info.need_exchange()) {
      if (OB_FAIL(left_exch_info.weak_sharding_.assign(join_path.get_weak_sharding()))) {
        LOG_WARN("failed to assign weak sharding", K(ret));
      } else {
        left_exch_info.strong_sharding_ = join_path.get_strong_sharding();
        left_exch_info.need_null_aware_shuffle_ = (left_is_non_preserve_side
                        && (ObPQDistributeMethod::HASH == left_exch_info.dist_method_
                            || ObPQDistributeMethod::PARTITION == left_exch_info.dist_method_));
      }
    }
    if (right_exch_info.need_exchange()) {
      if (OB_FAIL(right_exch_info.weak_sharding_.assign(join_path.get_weak_sharding()))) {
        LOG_WARN("failed to assign weak sharding", K(ret));
O
oceanbase-admin 已提交
4726
      } else {
W
wangzelin.wzl 已提交
4727 4728 4729 4730
        right_exch_info.strong_sharding_ = join_path.get_strong_sharding();
        right_exch_info.need_null_aware_shuffle_ = (right_is_non_preserve_side
                              && (ObPQDistributeMethod::HASH == right_exch_info.dist_method_
                              || ObPQDistributeMethod::PARTITION == right_exch_info.dist_method_));
O
oceanbase-admin 已提交
4731 4732 4733 4734 4735 4736
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4737 4738 4739 4740
int ObLogPlan::get_join_path_keys(const JoinPath &join_path,
                                  ObIArray<ObRawExpr*> &left_keys,
                                  ObIArray<ObRawExpr*> &right_keys,
                                  ObIArray<bool> &null_safe_info)
O
oceanbase-admin 已提交
4741 4742
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4743 4744 4745
  ObSEArray<ObRawExpr*, 8> conditions;
  if (OB_ISNULL(join_path.left_path_) || OB_ISNULL(join_path.left_path_->parent_) ||
      OB_ISNULL(join_path.right_path_)) {
O
oceanbase-admin 已提交
4746
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4747 4748 4749 4750 4751 4752
    LOG_WARN("get unexpected null", K(join_path.left_path_), K(join_path.right_path_), K(ret));
  } else if (JoinAlgo::HASH_JOIN == join_path.join_algo_ ||
             JoinAlgo::MERGE_JOIN == join_path.join_algo_) {
    if (OB_FAIL(append(conditions, join_path.equal_join_conditions_))) {
      LOG_WARN("failed to append conditions", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
4753
  } else {
W
wangzelin.wzl 已提交
4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
    if (OB_FAIL(append(conditions, join_path.other_join_conditions_))) {
      LOG_WARN("failed to append conditions", K(ret));
    } else if (OB_FAIL(append_array_no_dup(conditions, join_path.right_path_->pushdown_filters_))) {
      LOG_WARN("failed to append keys", K(ret));
    } else { /*do nothing*/ }
  }
  if (OB_FAIL(ret)) {
    /*do nothing*/
  } else if (OB_FAIL(ObOptimizerUtil::get_equal_keys(conditions,
                                                     join_path.left_path_->parent_->get_tables(),
                                                     left_keys,
                                                     right_keys,
                                                     null_safe_info))) {
    LOG_WARN("failed to get equal keys", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

// to support null skew handling
void ObLogPlan::compute_null_distribution_info(const ObJoinType &join_type,
                                              ObExchangeInfo &left_exch_info,
                                              ObExchangeInfo &right_exch_info,
                                              ObIArray<bool> &null_safe_info)
{
  bool contain_ns_cond = false;
  for (int64_t i = 0; i < null_safe_info.count(); ++i) {
    // as null safe is rarely used, don't need to early break the loop
    contain_ns_cond = contain_ns_cond || null_safe_info.at(i);
  }
  if (contain_ns_cond) {
    left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::NONE;
    right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::NONE;
  } else {
    switch (join_type) {
      case ObJoinType::INNER_JOIN: {
        left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::DROP;
        right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::DROP;
        break;
      }
      case ObJoinType::LEFT_SEMI_JOIN:
      case ObJoinType::RIGHT_SEMI_JOIN:
        left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::DROP;
        right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::DROP;
        break;
      case ObJoinType::LEFT_OUTER_JOIN:
        left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::RANDOM;
        right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::DROP;
        break;
      case ObJoinType::RIGHT_OUTER_JOIN:
        left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::DROP;
        right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::RANDOM;
        break;
      case ObJoinType::FULL_OUTER_JOIN:
        left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::RANDOM;
        right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::RANDOM;
        break;
      default:
        left_exch_info.null_row_dist_method_ = ObNullDistributeMethod::NONE;
        right_exch_info.null_row_dist_method_ = ObNullDistributeMethod::NONE;
        break;
O
oceanbase-admin 已提交
4814 4815 4816 4817
    }
  }
}

O
obdev 已提交
4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899
int ObLogPlan::get_histogram_by_join_exprs(ObOptimizerContext &optimizer_ctx,
                                           const ObDMLStmt *stmt,
                                           const ObRawExpr &expr,
                                           ObOptColumnStatHandle &handle) const
{
  int ret = OB_SUCCESS;
  ObSQLSessionInfo* session_info = optimizer_ctx.get_session_info();
  ObSchemaGetterGuard *schema_guard = optimizer_ctx.get_schema_guard();
  if (OB_ISNULL(stmt) || OB_ISNULL(schema_guard) || OB_ISNULL(session_info)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("session_info get unexpected null", K(ret));
  } else {
    uint64_t table_id = static_cast<const ObColumnRefRawExpr&>(expr).get_table_id();
    uint64_t column_id = static_cast<const ObColumnRefRawExpr&>(expr).get_column_id();
    const TableItem *table_item = NULL;
    const ObTableSchema *table_schema = NULL;
    if (OB_ISNULL(table_item = stmt->get_table_item_by_id(table_id))) {
      ret = OB_INVALID_ARGUMENT;
      LOG_WARN("Invalid argument passed in", K(table_id), K(ret));
    } else if (!table_item->is_basic_table()) {
      // nop, don't skip none base table (such as view) for now.
    } else if (OB_FAIL(schema_guard->get_table_schema(session_info->get_effective_tenant_id(),
                                                      table_item->ref_id_, table_schema))) {
      LOG_WARN("get table schema failed", K(ret), K(table_id), K(column_id), K(table_item->ref_id_), K(*table_item));
    } else if (OB_ISNULL(table_schema)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(optimizer_ctx.get_opt_stat_manager()->get_column_stat(
                session_info->get_effective_tenant_id(),
                table_item->ref_id_,
                table_schema->is_partitioned_table() ? -1 : table_item->ref_id_, /* use -1 for part table */
                column_id, handle))) {
      LOG_WARN("fail get full table column stat", K(ret), K(table_id), K(column_id));
    } else if (OB_ISNULL(handle.stat_)) {
      ret = OB_ERR_UNEXPECTED;
    }
  }
  return ret;
}

int ObLogPlan::check_if_use_hybrid_hash_distribution(ObOptimizerContext &optimizer_ctx,
                                                     const ObDMLStmt *stmt,
                                                     ObJoinType join_type,
                                                     ObRawExpr  &expr,
                                                     ObIArray<ObObj> &popular_values) const
{
  int ret = OB_SUCCESS;
  ObSQLSessionInfo* session_info = optimizer_ctx.get_session_info();
  bool enable_skew_handling = optimizer_ctx.get_session_info()->get_px_join_skew_handling();
  if (OB_SUCC(ret)
      && enable_skew_handling
      && expr.is_column_ref_expr()
      && (ObJoinType::INNER_JOIN == join_type
          || ObJoinType::RIGHT_OUTER_JOIN == join_type
          || ObJoinType::RIGHT_SEMI_JOIN == join_type
          || RIGHT_ANTI_JOIN == join_type)
     ) {
    ObOptColumnStatHandle handle;
    if (OB_FAIL(get_histogram_by_join_exprs(optimizer_ctx,
                                            stmt,
                                            expr,
                                            handle))) {
      LOG_WARN("fail get hisstogram by join exprs", K(ret));
    } else if (OB_FAIL(get_popular_values_hash(get_allocator(), handle, popular_values))) {
      LOG_WARN("fail get popular values hash", K(ret));
    }
  }
  return ret;
}
int ObLogPlan::get_popular_values_hash(ObIAllocator &allocator,
                                       ObOptColumnStatHandle &handle,
                                       common::ObIArray<ObObj> &popular_values) const
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(handle.stat_)
      || 0 >= handle.stat_->get_last_analyzed()
      || handle.stat_->get_histogram().get_bucket_size() <= 0) {
    // no histogram info, don't use hybrid hash
    LOG_DEBUG("table not analyzed. disable hybrid hash DM", K(ret));
  } else {
    const ObHistogram &histogram = handle.stat_->get_histogram();
    // get total value count via last bucket by it's cumulative endpoint num
4900
    const ObHistBucket &last_bucket = histogram.get(histogram.get_bucket_size() - 1);
O
obdev 已提交
4901 4902 4903
    int64_t total_cnt = std::max(1L, last_bucket.endpoint_num_); // avoid zero div
    int64_t min_freq = optimizer_context_.get_session_info()->get_px_join_skew_minfreq();
    for (int64_t i = 0; OB_SUCC(ret) && i < histogram.get_bucket_size(); ++i) {
4904
      const ObHistBucket &bucket = histogram.get(i);
O
obdev 已提交
4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923
      int64_t freq = bucket.endpoint_repeat_count_ * 100 / total_cnt;
      if (freq >= min_freq) {
        ObObj value;
        if (OB_FAIL(ob_write_obj(allocator, bucket.endpoint_value_, value))) {
          LOG_WARN("fail write object", K(ret));
        } else if (OB_FAIL(popular_values.push_back(value))) {
          LOG_WARN("fail add value to exchange info", K(ret));
        }
      }
      LOG_DEBUG("add a popular value to array",
                K(freq), K(bucket.endpoint_repeat_count_), K(total_cnt), K(min_freq));
    }
  }
  return ret;
}

int ObLogPlan::compute_hash_distribution_info(const ObJoinType &join_type,
                                              const bool enable_hybrid_hash_dm,
                                              const ObIArray<ObRawExpr*> &join_exprs,
W
wangzelin.wzl 已提交
4924 4925 4926
                                              const ObRelIds &left_table_set,
                                              ObExchangeInfo &left_exch_info,
                                              ObExchangeInfo &right_exch_info)
O
oceanbase-admin 已提交
4927 4928
{
  int ret = OB_SUCCESS;
O
obdev 已提交
4929
  bool use_hybrid_hash = false;
W
wangzelin.wzl 已提交
4930
  if (OB_UNLIKELY(join_exprs.empty())) {
O
oceanbase-admin 已提交
4931
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
4932
    LOG_WARN("join expr is empty", K(ret));
O
oceanbase-admin 已提交
4933
  } else {
W
wangzelin.wzl 已提交
4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945
    for (int64_t i = 0; OB_SUCC(ret) && i < join_exprs.count(); i++) {
      ObRawExpr *expr = NULL;
      ObRawExpr *left_expr = NULL;
      ObRawExpr *right_expr = NULL;
      if (OB_ISNULL(expr = join_exprs.at(i)) ||
          OB_ISNULL(left_expr = expr->get_param_expr(0)) ||
          OB_ISNULL(right_expr = expr->get_param_expr(1))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected error", K(expr), K(left_expr), K(right_expr), K(ret));
      } else {
        if (!left_expr->get_relation_ids().is_subset(left_table_set)) {
          std::swap(left_expr, right_expr);
O
oceanbase-admin 已提交
4946
        }
W
wangzelin.wzl 已提交
4947 4948 4949 4950 4951
        if (OB_FAIL(left_exch_info.hash_dist_exprs_.push_back(
                    ObExchangeInfo::HashExpr(left_expr,
                                             expr->get_result_type().get_calc_meta())))) {
          LOG_WARN("failed to push back expr", K(ret));
        } else if (OB_FAIL(right_exch_info.hash_dist_exprs_.push_back(
O
obdev 已提交
4952 4953
                    ObExchangeInfo::HashExpr(right_expr,
                                             expr->get_result_type().get_calc_meta())))) {
W
wangzelin.wzl 已提交
4954
          LOG_WARN("failed to push back expr", K(ret));
O
oceanbase-admin 已提交
4955 4956 4957
        }
      }
    }
O
obdev 已提交
4958

O
oceanbase-admin 已提交
4959
    if (OB_SUCC(ret)) {
O
obdev 已提交
4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025
      // for now, only support hybrid hash DM with only 1 base column join condition
      // after DSQ supported, we can do better with more scenarios.
      if (enable_hybrid_hash_dm && right_exch_info.hash_dist_exprs_.count() > 0) {
        if (OB_FAIL(check_if_use_hybrid_hash_distribution(
                    optimizer_context_,
                    get_stmt(),
                    join_type,
                    *right_exch_info.hash_dist_exprs_.at(0).expr_,
                    right_exch_info.popular_values_))) {
          LOG_WARN("fail check use hybrid hash dist", K(ret));
        } else if (OB_FAIL(left_exch_info.popular_values_.assign(right_exch_info.popular_values_))) {
          LOG_WARN("fail assign exch info", K(ret));
        } else {
          left_exch_info.dist_method_ = ObPQDistributeMethod::HYBRID_HASH_BROADCAST;
          right_exch_info.dist_method_ = ObPQDistributeMethod::HYBRID_HASH_RANDOM;
        }
      } else {
        left_exch_info.dist_method_ = ObPQDistributeMethod::HASH;
        right_exch_info.dist_method_ = ObPQDistributeMethod::HASH;
      }
    }
  }
  return ret;
}

int ObLogPlan::compute_single_side_hash_distribution_info(const EqualSets &equal_sets,
                                                          const ObIArray<ObRawExpr*> &src_keys,
                                                          const ObIArray<ObRawExpr*> &target_keys,
                                                          const Path &target_path,
                                                          ObExchangeInfo &exch_info)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(target_path.log_op_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(compute_single_side_hash_distribution_info(equal_sets,
                                                                src_keys,
                                                                target_keys,
                                                                *target_path.log_op_,
                                                                exch_info))) {
    LOG_WARN("failed to compute single side hash distribution info", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::compute_single_side_hash_distribution_info(const EqualSets &equal_sets,
                                                          const ObIArray<ObRawExpr*> &src_keys,
                                                          const ObIArray<ObRawExpr*> &target_keys,
                                                          const ObLogicalOperator &target_op,
                                                          ObExchangeInfo &exch_info)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr*, 4> hash_dist_exprs;
  if (OB_ISNULL(target_op.get_strong_sharding())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(get_repartition_keys(equal_sets,
                                          src_keys,
                                          target_keys,
                                          target_op.get_strong_sharding()->get_partition_keys(),
                                          hash_dist_exprs))) {
    LOG_WARN("failed to get hash dist keys", K(ret));
  } else if (OB_FAIL(exch_info.append_hash_dist_expr(hash_dist_exprs))) {
    LOG_WARN("failed to append hash dist expr", K(ret));
  } else {
    exch_info.dist_method_ = ObPQDistributeMethod::HASH;
O
oceanbase-admin 已提交
5026 5027 5028 5029
  }
  return ret;
}

W
wangzelin.wzl 已提交
5030 5031 5032 5033 5034
int ObLogPlan::compute_repartition_distribution_info(const EqualSets &equal_sets,
                                                     const ObIArray<ObRawExpr*> &src_keys,
                                                     const ObIArray<ObRawExpr*> &target_keys,
                                                     const Path &target_path,
                                                     ObExchangeInfo &exch_info)
O
oceanbase-admin 已提交
5035 5036
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5037
  if (OB_ISNULL(target_path.log_op_)) {
O
oceanbase-admin 已提交
5038
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5039 5040 5041 5042 5043 5044 5045 5046
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(compute_repartition_distribution_info(equal_sets,
                                                           src_keys,
                                                           target_keys,
                                                           *target_path.log_op_,
                                                           exch_info))) {
    LOG_WARN("failed to compute repartition distribution info", K(ret));
  } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5047 5048 5049
  return ret;
}

W
wangzelin.wzl 已提交
5050 5051 5052 5053 5054
int ObLogPlan::compute_repartition_distribution_info(const EqualSets &equal_sets,
                                                     const ObIArray<ObRawExpr*> &src_keys,
                                                     const ObIArray<ObRawExpr*> &target_keys,
                                                     const ObLogicalOperator &target_op,
                                                     ObExchangeInfo &exch_info)
O
oceanbase-admin 已提交
5055 5056
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5057 5058 5059 5060
  ObString table_name;
  uint64_t ref_table_id = OB_INVALID_ID;
  uint64_t table_id = OB_INVALID_ID;
  if (OB_ISNULL(target_op.get_strong_sharding())) {
O
oceanbase-admin 已提交
5061
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(get_repartition_table_info(target_op,
                                                table_name,
                                                ref_table_id,
                                                table_id))) {
    LOG_WARN("failed to get repartition table info", K(ret));
  } else if (OB_FAIL(compute_repartition_distribution_info(equal_sets,
                                                           src_keys,
                                                           target_keys,
                                                           ref_table_id,
                                                           table_id,
                                                           table_name,
                                                           *target_op.get_strong_sharding(),
                                                           exch_info))) {
    LOG_WARN("failed to compute repartition distribution info", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

O
obdev 已提交
5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106
int ObLogPlan::find_table_scan_with_sharding_info(const ObLogicalOperator &op,
                                                  const ObShardingInfo *sharding,
                                                  const ObLogTableScan *&tsc)
{
  int ret = OB_SUCCESS;
  tsc = NULL;
  if (op.get_strong_sharding() != sharding) {
    // return null tsc.
  } else if (LOG_TABLE_SCAN == op.get_type()) {
    tsc = static_cast<const ObLogTableScan*>(&op);
  } else {
    const bool is_subplan_scan = LOG_SUBPLAN_SCAN == op.get_type();
    for (int64_t i = 0; i < op.get_num_of_child() && NULL == tsc && OB_SUCC(ret); i++) {
      if (OB_ISNULL(op.get_child(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL((SMART_CALL(find_table_scan_with_sharding_info(*op.get_child(i),
                  is_subplan_scan ? op.get_child(i)->get_strong_sharding() : sharding,
                  tsc))))) {
        LOG_WARN("find table scan failed", K(ret));
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5107 5108 5109 5110 5111 5112 5113 5114
int ObLogPlan::get_repartition_table_info(const ObLogicalOperator &op,
                                          ObString &table_name,
                                          uint64_t &ref_table_id,
                                          uint64_t &table_id)
{
  int ret = OB_SUCCESS;
  const ObLogicalOperator *cur_op = &op;
  const ObLogTableScan *table_scan = NULL;
O
obdev 已提交
5115 5116 5117
  if (OB_FAIL(find_table_scan_with_sharding_info(op, op.get_strong_sharding(), table_scan))) {
    LOG_WARN("find table scan failed", K(ret));
  } else if (OB_ISNULL(table_scan)) {
O
oceanbase-admin 已提交
5118
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5119
    LOG_WARN("get unexpected null", K(ret));
O
oceanbase-admin 已提交
5120
  } else {
W
wangzelin.wzl 已提交
5121 5122 5123
    table_name = table_scan->get_table_name();
    table_id = table_scan->get_table_id();
    ref_table_id = table_scan->get_index_table_id();
O
oceanbase-admin 已提交
5124 5125 5126 5127
  }
  return ret;
}

W
wangzelin.wzl 已提交
5128 5129 5130 5131 5132 5133 5134 5135
int ObLogPlan::compute_repartition_distribution_info(const EqualSets &equal_sets,
                                                     const ObIArray<ObRawExpr*> &src_keys,
                                                     const ObIArray<ObRawExpr*> &target_keys,
                                                     const uint64_t ref_table_id,
                                                     const uint64_t table_id,
                                                     const ObString &table_name,
                                                     const ObShardingInfo &target_sharding,
                                                     ObExchangeInfo &exch_info)
O
oceanbase-admin 已提交
5136 5137
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148
  ObSQLSessionInfo *session = NULL;
  if (OB_ISNULL(session = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(session), K(ret));
  } else if (OB_FAIL(compute_repartition_func_info(equal_sets,
                                                   src_keys,
                                                   target_keys,
                                                   target_sharding,
                                                   get_optimizer_context().get_expr_factory(),
                                                   exch_info))) {
    LOG_WARN("failed to compute repartition func info", K(ret));
O
oceanbase-admin 已提交
5149
  } else {
W
wangzelin.wzl 已提交
5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167
    exch_info.dist_method_ = ObPQDistributeMethod::PARTITION;
    exch_info.repartition_ref_table_id_ = ref_table_id;
    exch_info.repartition_table_id_ = table_id;
    exch_info.repartition_table_name_ = table_name;
    exch_info.slice_count_ = target_sharding.get_part_cnt();
    if (share::schema::PARTITION_LEVEL_ONE == target_sharding.get_part_level()) {
      exch_info.repartition_type_ = OB_REPARTITION_ONE_SIDE_ONE_LEVEL;
    } else if (share::schema::PARTITION_LEVEL_TWO == target_sharding.get_part_level()) {
      if (target_sharding.is_partition_single()) {
        exch_info.repartition_type_ = OB_REPARTITION_ONE_SIDE_ONE_LEVEL_SUB;
      } else if (target_sharding.is_subpartition_single()) {
        exch_info.repartition_type_ = OB_REPARTITION_ONE_SIDE_ONE_LEVEL_FIRST;
      } else {
        exch_info.repartition_type_ = OB_REPARTITION_ONE_SIDE_TWO_LEVEL;
      }
    } else {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected partition level", K(target_sharding.get_part_level()));
O
oceanbase-admin 已提交
5168
    }
W
wangzelin.wzl 已提交
5169 5170 5171 5172 5173
    if (OB_FAIL(ret)) {
      /*do nothing*/
    } else if (OB_FAIL(exch_info.init_calc_part_id_expr(get_optimizer_context()))) {
      LOG_WARN("failed to init calc part id expr", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5174 5175 5176 5177
  }
  return ret;
}

W
wangzelin.wzl 已提交
5178 5179 5180 5181 5182 5183
int ObLogPlan::compute_repartition_func_info(const EqualSets &equal_sets,
                                             const ObIArray<ObRawExpr *> &src_keys,
                                             const ObIArray<ObRawExpr *> &target_keys,
                                             const ObShardingInfo &target_sharding,
                                             ObRawExprFactory &expr_factory,
                                             ObExchangeInfo &exch_info)
O
oceanbase-admin 已提交
5184 5185
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5186 5187 5188 5189 5190 5191 5192 5193 5194
  ObSQLSessionInfo *session_info = NULL;
  ObSEArray<ObRawExpr*, 4> repart_exprs;
  ObSEArray<ObRawExpr*, 4> repart_sub_exprs;
  ObSEArray<ObRawExpr*, 4> repart_func_exprs;
  ObRawExprCopier copier(expr_factory);
  // get repart exprs
  bool skip_part = target_sharding.is_partition_single();
  bool skip_subpart = target_sharding.is_subpartition_single();
  if (OB_ISNULL(session_info = get_optimizer_context().get_session_info())) {
O
oceanbase-admin 已提交
5195
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216
    LOG_WARN("get unexpected null", K(session_info), K(ret));
  } else if (!skip_part && OB_FAIL(get_repartition_keys(equal_sets,
                                                        src_keys,
                                                        target_keys,
                                                        target_sharding.get_partition_keys(),
                                                        repart_exprs))) {
    LOG_WARN("failed to get repartition keys", K(ret));
  } else if (!skip_subpart && OB_FAIL(get_repartition_keys(equal_sets,
                                                           src_keys,
                                                           target_keys,
                                                           target_sharding.get_sub_partition_keys(),
                                                           repart_sub_exprs))) {
    LOG_WARN("failed to get repartition keys", K(ret));
  } else if (!skip_part &&
             OB_FAIL(copier.add_replaced_expr(target_sharding.get_partition_keys(),
                                              repart_exprs))) {
    LOG_WARN("failed to add replace pair", K(ret));
  } else if (!skip_subpart &&
             OB_FAIL(copier.add_replaced_expr(target_sharding.get_sub_partition_keys(),
                                              repart_sub_exprs))) {
    LOG_WARN("failed to add replace pair", K(ret));
O
oceanbase-admin 已提交
5217
  } else {
W
wangzelin.wzl 已提交
5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249
    for (int64_t i = 0; OB_SUCC(ret) && i < target_sharding.get_partition_func().count(); i++) {
      ObRawExpr *repart_func_expr = NULL;
      ObRawExpr *target_func_expr = target_sharding.get_partition_func().at(i);
      if ((0 == i && skip_part) || (1 == i && skip_subpart)) {
        // 对于只涉及到一个一级(二级)分区的二级分区表,做repart重分区并不需要生成一级(二级)分区
        // 的repart function。但对于二级分区表要求repart_func_exprs的数量必须为两个,因此在对应
        // 的位置放一个常量作为dummy repart function
        ObConstRawExpr *const_expr = NULL;
        ObRawExpr *dummy_expr = NULL;
        int64_t const_value = 1;
        if (OB_FAIL(ObRawExprUtils::build_const_int_expr(get_optimizer_context().get_expr_factory(),
                                                         ObIntType,
                                                         const_value,
                                                         const_expr))) {
          LOG_WARN("Failed to build const expr", K(ret));
        } else if (OB_ISNULL(dummy_expr = const_expr)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(ret));
        } else if (OB_FAIL(dummy_expr->formalize(session_info))) {
          LOG_WARN("Failed to formalize a new expr", K(ret));
        } else if (OB_FAIL(repart_func_exprs.push_back(dummy_expr))) {
          LOG_WARN("failed to push back expr", K(ret));
        }
      } else if (OB_FAIL(copier.copy_on_replace(target_func_expr,
                                                repart_func_expr))) {
        LOG_WARN("failed to copy on replace expr", K(ret));
      } else if (OB_ISNULL(repart_func_expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(repart_func_exprs.push_back(repart_func_expr))) {
        LOG_WARN("failed to push back expr", K(ret));
      } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5250
    }
W
wangzelin.wzl 已提交
5251 5252 5253 5254 5255 5256
    if (OB_SUCC(ret)) {
      if (OB_FAIL(exch_info.repartition_keys_.assign(repart_exprs)) ||
          OB_FAIL(exch_info.repartition_sub_keys_.assign(repart_sub_exprs)) ||
          OB_FAIL(exch_info.repartition_func_exprs_.assign(repart_func_exprs))) {
        LOG_WARN("failed to set repartition keys", K(ret));
      } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5257 5258 5259 5260 5261
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5262 5263 5264 5265 5266
int ObLogPlan::get_repartition_keys(const EqualSets &equal_sets,
                                    const ObIArray<ObRawExpr*> &src_keys,
                                    const ObIArray<ObRawExpr*> &target_keys,
                                    const ObIArray<ObRawExpr*> &target_part_keys,
                                    ObIArray<ObRawExpr *> &src_part_keys)
O
oceanbase-admin 已提交
5267 5268
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5269 5270 5271 5272
  if (OB_UNLIKELY(src_keys.count() != target_keys.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected array count",
        K(src_keys.count()), K(target_keys.count()), K(ret));
O
oceanbase-admin 已提交
5273
  } else {
W
wangzelin.wzl 已提交
5274 5275
    for (int64_t i = 0; OB_SUCC(ret) && i < target_part_keys.count(); i++) {
      if (OB_ISNULL(target_part_keys.at(i))) {
O
oceanbase-admin 已提交
5276
        ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5277
        LOG_WARN("get unexpected null", K(ret));
O
oceanbase-admin 已提交
5278
      } else {
W
wangzelin.wzl 已提交
5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305
        bool is_find = false;
        for (int64_t j = 0; OB_SUCC(ret) && !is_find && j < target_keys.count(); j++) {
          if (OB_ISNULL(target_keys.at(j)) || OB_ISNULL(src_keys.at(j))) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("get unexpected null", K(target_keys.at(j)), K(src_keys.at(j)), K(ret));
          } else if (ObOptimizerUtil::is_expr_equivalent(target_part_keys.at(i),
              target_keys.at(j), equal_sets)
              && target_part_keys.at(i)->get_result_type().get_type_class()
                  == src_keys.at(j)->get_result_type().get_type_class()
              && target_part_keys.at(i)->get_result_type().get_collation_type()
                  == src_keys.at(j)->get_result_type().get_collation_type()
              && !ObObjCmpFuncs::is_otimestamp_cmp(target_part_keys.at(i)->get_result_type().get_type(),
                  src_keys.at(j)->get_result_type().get_type())
              && !ObObjCmpFuncs::is_datetime_timestamp_cmp(
                  target_part_keys.at(i)->get_result_type().get_type(),
                  src_keys.at(j)->get_result_type().get_type())) {
            if (OB_FAIL(src_part_keys.push_back(src_keys.at(j)))) {
              LOG_WARN("failed to push back keys", K(ret));
            } else {
              is_find = true;
            }
          } else { /*do nothing*/ }
        }
        if (OB_SUCC(ret) && !is_find) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("can not find part expr", K(target_part_keys.at(i)),
              K(src_keys), K(target_keys), K(ret));
O
oceanbase-admin 已提交
5306 5307 5308 5309 5310 5311 5312
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5313 5314
int ObLogPlan::set_connect_by_property(JoinPath *join_path,
                                       ObLogJoin &join_op)
O
oceanbase-admin 已提交
5315 5316
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370
  if (OB_ISNULL(join_path) || OB_ISNULL(get_stmt()) ||
      OB_ISNULL(join_path->left_path_) || OB_ISNULL(join_path->left_path_->parent_) ||
      OB_ISNULL(join_path->right_path_) || OB_ISNULL(join_path->right_path_->parent_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(get_stmt()), K(join_path), K(ret));
  } else if (OB_UNLIKELY(!get_stmt()->is_select_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected stmt type", K(get_stmt()->get_stmt_type()), K(ret));
  } else {
    ObSEArray<ObRawExpr*, 8> connect_by_extra_exprs;
    const ObSelectStmt *select_stmt = static_cast<const ObSelectStmt *>(get_stmt());
    if (OB_FAIL(select_stmt->get_column_exprs(join_path->left_path_->parent_->get_table_id(),
                                              connect_by_extra_exprs))) {
      LOG_WARN("failed to get left table columns", K(ret));
    } else if (OB_FAIL(select_stmt->get_column_exprs(join_path->right_path_->parent_->get_table_id(),
                                                     connect_by_extra_exprs))) {
      LOG_WARN("failed to get right table columns", K(ret));
    } else if (OB_FAIL(join_op.set_connect_by_extra_exprs(connect_by_extra_exprs))) {
      LOG_WARN("failed to set connect by extra exprs", K(ret));
    } else if (OB_FAIL(join_op.set_connect_by_prior_exprs(select_stmt->get_connect_by_prior_exprs()))) {
      LOG_WARN("fail to set connect by priro expr", K(ret));
    } else if (OB_FAIL(select_stmt->get_connect_by_pseudo_exprs(join_op.get_connect_by_pseudo_columns()))) {
      LOG_WARN("failed to get connect by pseudo exprs", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::allocate_subquery_path(SubQueryPath *subpath,
                                      ObLogicalOperator *&out_subquery_path_op)
{
  int ret = OB_SUCCESS;
  ObLogicalOperator *root = NULL;
  ObLogSubPlanScan *subplan_scan = NULL;
  const TableItem *table_item = NULL;
  if (OB_ISNULL(subpath) || OB_ISNULL(root = subpath->root_) || OB_ISNULL(get_stmt()) ||
      OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(subpath->subquery_id_))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(subpath), K(root), K(get_stmt()), K(table_item), K(ret));
  } else if (OB_ISNULL(subplan_scan = static_cast<ObLogSubPlanScan*>
                      (get_log_op_factory().allocate(*this, LOG_SUBPLAN_SCAN)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate subquery operator", K(ret));
  } else {
    subplan_scan->set_subquery_id(subpath->subquery_id_);
    subplan_scan->set_child(ObLogicalOperator::first_child, root);
    subplan_scan->get_subquery_name().assign_ptr(table_item->table_name_.ptr(),
                                                 table_item->table_name_.length());
    if (OB_FAIL(append(subplan_scan->get_filter_exprs(), subpath->filter_))) {
      LOG_WARN("failed to allocate_filter", K(ret));
    } else if (OB_FAIL(append(subplan_scan->get_pushdown_filter_exprs(), subpath->pushdown_filters_))) {
      LOG_WARN("failed to append pushdown filters", K(ret));
    } else if (OB_FAIL(subplan_scan->compute_property(subpath))) {
      LOG_WARN("failed to compute property", K(ret));
O
oceanbase-admin 已提交
5371
    } else {
W
wangzelin.wzl 已提交
5372
      out_subquery_path_op = subplan_scan;
O
oceanbase-admin 已提交
5373 5374 5375 5376 5377
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5378
int ObLogPlan::allocate_material_as_top(ObLogicalOperator *&old_top)
O
oceanbase-admin 已提交
5379 5380
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5381 5382 5383 5384 5385
  ObLogMaterial *material_op = NULL;
  if (OB_ISNULL(old_top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(old_top));
  } else if (OB_ISNULL(material_op = static_cast<ObLogMaterial*>(get_log_op_factory().allocate(*this, LOG_MATERIAL)))) {
O
oceanbase-admin 已提交
5386
    ret = OB_ALLOCATE_MEMORY_FAILED;
W
wangzelin.wzl 已提交
5387
    LOG_WARN("failed to allocate material operator", K(ret));
O
oceanbase-admin 已提交
5388
  } else {
W
wangzelin.wzl 已提交
5389 5390
    material_op->set_child(ObLogicalOperator::first_child, old_top);
    if (OB_FAIL(material_op->compute_property())) {
O
oceanbase-admin 已提交
5391 5392
      LOG_WARN("failed to compute property", K(ret));
    } else {
W
wangzelin.wzl 已提交
5393
      old_top = material_op;
O
oceanbase-admin 已提交
5394 5395 5396 5397 5398
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5399 5400
int ObLogPlan::create_plan_tree_from_path(Path *path,
                                          ObLogicalOperator *&out_plan_tree)
O
oceanbase-admin 已提交
5401 5402
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5403 5404
  ObLogicalOperator *op = NULL;
  if (OB_ISNULL(path)) {
O
oceanbase-admin 已提交
5405
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5406 5407 5408
    LOG_WARN("get unexpected null", K(ret), K(path));
  } else if (NULL != path->log_op_) {
    out_plan_tree = path->log_op_;
O
oceanbase-admin 已提交
5409
  } else {
W
wangzelin.wzl 已提交
5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424
    if (path->is_access_path()) {
      AccessPath *access_path = static_cast<AccessPath *>(path);
      if (OB_FAIL(allocate_access_path(access_path, op))) {
        LOG_WARN("failed to allocate access path", K(ret));
      } else { /*do nothing*/ }
    } else if (path->is_cte_path()) {
      CteTablePath *cte_table_path = static_cast<CteTablePath*>(path);
      if (OB_FAIL(allocate_cte_table_path(cte_table_path, op))) {
        LOG_WARN("failed to allocate cte table path", K(ret));
      } else { /*do nothing*/ }
    } else if (path->is_function_table_path()) {
      FunctionTablePath *func_table_path = static_cast<FunctionTablePath *>(path);
      if (OB_FAIL(allocate_function_table_path(func_table_path, op))) {
        LOG_WARN("failed to allocate function table path", K(ret));
      } else { /* Do nothing */ }
O
obdev 已提交
5425 5426 5427 5428 5429
    } else if (path->is_json_table_path()) {
      JsonTablePath *json_table_path = static_cast<JsonTablePath *>(path);
      if (OB_FAIL(allocate_json_table_path(json_table_path, op))) {
        LOG_WARN("failed to allocate json table path", K(ret));
      } else { /* Do nothing */ }
W
wangzelin.wzl 已提交
5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454
    } else if (path->is_temp_table_path()) {
      TempTablePath *temp_table_path = static_cast<TempTablePath *>(path);
      if (OB_FAIL(allocate_temp_table_path(temp_table_path, op))) {
        LOG_WARN("failed to allocate access path", K(ret));
      } else { /* Do nothing */ }
    } else if (path->is_join_path()) {
      JoinPath *join_path = static_cast<JoinPath *>(path);
      if (OB_FAIL(allocate_join_path(join_path, op))) {
        LOG_WARN("failed to allocate join path", K(ret));
      } else {/* do nothing */ }
    } else if (path->is_subquery_path()) {
      SubQueryPath *subquery_path = static_cast<SubQueryPath *>(path);
      if (OB_FAIL(allocate_subquery_path(subquery_path, op))) {
        LOG_WARN("failed to allocate subquery path", K(ret));
      } else { /* Do nothing */ }
    } else {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected path type");
    }
    if (OB_SUCC(ret)) {
      if (OB_FAIL(allocate_subplan_filter_for_on_condition(path->subquery_exprs_, op))) {
        LOG_WARN("failed to allocate subplan filter", K(ret));
      } else if (OB_FAIL(append(op->equal_param_constraints_,
                                path->equal_param_constraints_))) {
        LOG_WARN("failed to append param constraints", K(ret));
O
obdev 已提交
5455 5456 5457
      } else if (OB_FAIL(append(op->const_param_constraints_,
                                path->const_param_constraints_))) {
        LOG_WARN("failed to append param constraints", K(ret));
W
wangzelin.wzl 已提交
5458 5459 5460
      } else if (OB_FAIL(append(op->expr_constraints_,
                                path->expr_constraints_))) {
        LOG_WARN("failed to append expr constraints", K(ret));
O
oceanbase-admin 已提交
5461
      } else {
W
wangzelin.wzl 已提交
5462 5463
        path->log_op_ = op;
        out_plan_tree = op;
O
oceanbase-admin 已提交
5464 5465
      }
    }
W
wangzelin.wzl 已提交
5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506
  }
  return ret;
}

int ObLogPlan::init_candidate_plans()
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(join_order_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(join_order_));
  } else {
    int64_t total_usage = allocator_.total();
    LOG_TRACE("memory usage after generating join order", K(total_usage));
    ObSEArray<CandidatePlan, 8> candi_plans;
    for (int64_t i = 0; OB_SUCC(ret) && i < join_order_->get_interesting_paths().count(); i++) {
      ObLogicalOperator *root = NULL;
      if (OB_ISNULL(join_order_->get_interesting_paths().at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret), K(i));
      } else if (OB_FAIL(create_plan_tree_from_path(join_order_->get_interesting_paths().at(i),
                                                    root))) {
        LOG_WARN("failed to create a path", K(ret));
      } else if (OB_ISNULL(root)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret), K(root));
      } else if (OB_FAIL(append(root->get_filter_exprs(),
                                get_special_exprs()))) {
        LOG_WARN("failed to append special to filter", K(ret));
      } else if (OB_FAIL(append_array_no_dup(root->get_startup_exprs(),
                                             get_startup_filters()))) {
        LOG_WARN("failed to append startup filters", K(ret));
      } else if (OB_FAIL(candi_plans.push_back(CandidatePlan(root)))) {
        LOG_WARN("failed to push back candidate plan", K(ret));
      } else {
        int64_t plan_usage = allocator_.total() - total_usage;
        total_usage = allocator_.total();
        LOG_TRACE("memory usage after generate a candidate", K(total_usage), K(plan_usage));
        total_usage = allocator_.total();
      }
    } // for join orders end

O
oceanbase-admin 已提交
5507
    if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
5508 5509 5510 5511
      if (OB_FAIL(init_candidate_plans(candi_plans))) {
        LOG_WARN("failed to init candidates", K(ret));
      } else {
        LOG_TRACE("succeed to init candidate plans", K(candidates_.candidate_plans_.count()));
O
oceanbase-admin 已提交
5512 5513 5514 5515 5516 5517
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5518
int ObLogPlan::init_candidate_plans(ObIArray<CandidatePlan> &candi_plans)
O
oceanbase-admin 已提交
5519 5520
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536
  if (OB_FAIL(candidates_.candidate_plans_.assign(candi_plans))) {
    LOG_WARN("failed to push back candi plans", K(ret));
  } else {
    candidates_.is_final_sort_ = false;
    candidates_.plain_plan_.first = 0;
    candidates_.plain_plan_.second = -1;
    for (int64_t i = 0; OB_SUCC(ret) && i < candi_plans.count(); i++) {
      if (OB_ISNULL(candi_plans.at(i).plan_tree_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (candidates_.plain_plan_.second == -1 ||
                 candi_plans.at(i).plan_tree_->get_cost() < candidates_.plain_plan_.first) {
        candidates_.plain_plan_.second = i;
        candidates_.plain_plan_.first = candi_plans.at(i).plan_tree_->get_cost();
      } else { /* do nothing*/ }
    }
O
oceanbase-admin 已提交
5537 5538 5539 5540
  }
  return ret;
}

W
wangzelin.wzl 已提交
5541
int ObLogPlan::candi_allocate_err_log(const ObDelUpdStmt *del_upd_stmt)
O
oceanbase-admin 已提交
5542 5543
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560
  CandidatePlan candidate_plan;
  ObSEArray<CandidatePlan, 4> error_log_plans;
  for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); ++i) {
    candidate_plan = candidates_.candidate_plans_.at(i);
    if (OB_ISNULL(candidate_plan.plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(allocate_err_log_as_top(del_upd_stmt, candidate_plan.plan_tree_))) {
      LOG_WARN("failed to allocate select into", K(ret));
    } else if (OB_FAIL(error_log_plans.push_back(candidate_plan))) {
      LOG_WARN("failed to push back candidate plan", K(ret));
    } else { /*do nothing*/ }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(prune_and_keep_best_plans(error_log_plans))) {
      LOG_WARN("failed to prune and keep best plans", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5561 5562 5563 5564
  }
  return ret;
}

W
wangzelin.wzl 已提交
5565
int ObLogPlan::allocate_err_log_as_top(const ObDelUpdStmt *del_upd_stmt, ObLogicalOperator *&top)
O
oceanbase-admin 已提交
5566 5567
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5568 5569 5570 5571 5572 5573
  ObLogErrLog *err_log_op = NULL;
  if (OB_ISNULL(del_upd_stmt) || OB_ISNULL(top)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("get unexpected null", K(ret), K(top), K(del_upd_stmt));
  } else if (OB_ISNULL(err_log_op = static_cast<ObLogErrLog *>(get_log_op_factory().
                       allocate(*this, LOG_ERR_LOG)))) {
O
oceanbase-admin 已提交
5574
    ret = OB_ALLOCATE_MEMORY_FAILED;
W
wangzelin.wzl 已提交
5575
    LOG_WARN("failed to allocate sequence operator", K(ret));
O
oceanbase-admin 已提交
5576
  } else {
W
wangzelin.wzl 已提交
5577 5578 5579 5580 5581
    err_log_op->set_del_upd_stmt(del_upd_stmt);
    err_log_op->set_child(ObLogicalOperator::first_child, top);
    if (OB_FAIL(err_log_op->extract_err_log_info())) {
      LOG_WARN("failed to extract err log info", K(ret));
    } else if (OB_FAIL(err_log_op->compute_property())) {
O
oceanbase-admin 已提交
5582 5583
      LOG_WARN("failed to compute property", K(ret));
    } else {
W
wangzelin.wzl 已提交
5584
      top = err_log_op;
O
oceanbase-admin 已提交
5585 5586 5587 5588 5589
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5590
int ObLogPlan::candi_allocate_sequence()
O
oceanbase-admin 已提交
5591 5592
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5593 5594 5595
  ObExchangeInfo exch_info;
  CandidatePlan candidate_plan;
  ObSEArray<CandidatePlan, 4> sequence_plans;
5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608
  ObDMLStmt *root_stmt = NULL;
  bool will_use_parallel_sequence = false;
  if (OB_ISNULL(root_stmt = get_optimizer_context().get_root_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(root_stmt), K(ret));
  } else if (root_stmt->is_explain_stmt() &&
             OB_ISNULL(root_stmt=static_cast<ObExplainStmt*>(root_stmt)->get_explain_query_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(root_stmt), K(ret));
  } else {
    will_use_parallel_sequence = get_optimizer_context().is_online_ddl() ||
                                 (root_stmt->is_insert_stmt() && get_optimizer_context().use_pdml());
  }
W
wangzelin.wzl 已提交
5609 5610 5611 5612 5613
  for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); ++i) {
    candidate_plan = candidates_.candidate_plans_.at(i);
    if (OB_ISNULL(candidate_plan.plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
5614 5615
    } else if (!will_use_parallel_sequence &&
               candidate_plan.plan_tree_->is_sharding() &&
W
wangzelin.wzl 已提交
5616 5617 5618 5619 5620 5621 5622
               allocate_exchange_as_top(candidate_plan.plan_tree_, exch_info)) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_FAIL(allocate_sequence_as_top(candidate_plan.plan_tree_))) {
      LOG_WARN("failed to allocate sequence as top", K(ret));
    } else if (OB_FAIL(sequence_plans.push_back(candidate_plan))) {
      LOG_WARN("failed to push back candidate plan", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5623 5624
  }
  if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
5625 5626 5627
    if (OB_FAIL(prune_and_keep_best_plans(sequence_plans))) {
      LOG_WARN("failed to prune and keep best plans", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5628 5629 5630 5631 5632
  }
  return ret;
}

/*
W
wangzelin.wzl 已提交
5633 5634 5635 5636 5637 5638
 * for sequence, old_top may be null
 * |ID|OPERATOR    |NAME|EST. ROWS|COST|
 * -------------------------------------
 * |0 |INSERT      |    |0        |1   |
 * |1 | EXPRESSION |    |1        |1   |
 * |2 |  SEQUENCE  |    |1        |1   |
O
oceanbase-admin 已提交
5639
 */
W
wangzelin.wzl 已提交
5640
int ObLogPlan::allocate_sequence_as_top(ObLogicalOperator *&old_top)
O
oceanbase-admin 已提交
5641 5642
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5643 5644
  ObLogSequence *sequence = NULL;
  if (OB_ISNULL(get_stmt())) {
O
oceanbase-admin 已提交
5645
    ret = OB_INVALID_ARGUMENT;
W
wangzelin.wzl 已提交
5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656
    LOG_WARN("Get unexpected null", K(ret), K(old_top), K(get_stmt()));
  } else if (OB_ISNULL(sequence = static_cast<ObLogSequence *>(get_log_op_factory().
                                  allocate(*this, LOG_SEQUENCE)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate sequence operator", K(ret));
  } else if (OB_FAIL(append_array_no_dup(sequence->get_sequence_ids(),
                                         get_stmt()->get_nextval_sequence_ids()))) {
    LOG_WARN("failed to append array no dup", K(ret));
  } else {
    if (NULL != old_top) {
      sequence->set_child(ObLogicalOperator::first_child, old_top);
O
oceanbase-admin 已提交
5657
    }
W
wangzelin.wzl 已提交
5658 5659
    if (OB_FAIL(sequence->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
O
oceanbase-admin 已提交
5660
    } else {
W
wangzelin.wzl 已提交
5661
      old_top = sequence;
O
oceanbase-admin 已提交
5662 5663 5664 5665 5666 5667
    }
  }
  return ret;
}

/*
W
wangzelin.wzl 已提交
5668
 * for expr values, old top may be null
O
oceanbase-admin 已提交
5669
 */
W
wangzelin.wzl 已提交
5670 5671
int ObLogPlan::allocate_expr_values_as_top(ObLogicalOperator *&old_top,
                                           const ObIArray<ObRawExpr*> *filter_exprs)
O
oceanbase-admin 已提交
5672 5673
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685
  ObLogExprValues *expr_values = NULL;
  if (OB_ISNULL(expr_values = static_cast<ObLogExprValues *>(get_log_op_factory().
                                  allocate(*this, LOG_EXPR_VALUES)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate expr-values operator", K(ret));
  } else if (NULL != filter_exprs &&
             OB_FAIL(expr_values->get_filter_exprs().assign(*filter_exprs))) {
    LOG_WARN("failed to assign exprs", K(ret));
  } else {
    expr_values->set_parallel(get_optimizer_context().get_parallel());
    if (NULL != old_top) {
      expr_values->set_child(ObLogicalOperator::first_child, old_top);
O
oceanbase-admin 已提交
5686
    }
W
wangzelin.wzl 已提交
5687 5688
    if (OB_FAIL(expr_values->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
O
oceanbase-admin 已提交
5689
    } else {
W
wangzelin.wzl 已提交
5690
      old_top = expr_values;
O
oceanbase-admin 已提交
5691 5692
    }
  }
W
wangzelin.wzl 已提交
5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709
  return ret;
}

int ObLogPlan::allocate_values_as_top(ObLogicalOperator *&old_top)
{
  int ret = OB_SUCCESS;
  ObLogValues *values = NULL;
  if (OB_ISNULL(values = static_cast<ObLogValues *>(get_log_op_factory().
                                  allocate(*this, LOG_VALUES)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate expr-values operator", K(ret));
  } else {
    if (NULL != old_top) {
      values->set_child(ObLogicalOperator::first_child, old_top);
    }
    if (OB_FAIL(values->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
O
oceanbase-admin 已提交
5710
    } else {
W
wangzelin.wzl 已提交
5711
      old_top = values;
O
oceanbase-admin 已提交
5712 5713 5714 5715 5716
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5717 5718
int ObLogPlan::allocate_temp_table_insert_as_top(ObLogicalOperator *&top,
                                                 const ObSqlTempTableInfo *temp_table_info)
O
oceanbase-admin 已提交
5719 5720
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5721 5722
  ObLogicalOperator *op = NULL;
  if (OB_ISNULL(top) || OB_ISNULL(temp_table_info)) {
O
oceanbase-admin 已提交
5723
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5724 5725 5726 5727
    LOG_WARN("get unexpected null", K(top), K(temp_table_info), K(get_stmt()), K(ret));
  } else if (OB_ISNULL(op = log_op_factory_.allocate(*this, LOG_TEMP_TABLE_INSERT))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate temp table operator", K(ret));
O
oceanbase-admin 已提交
5728
  } else {
W
wangzelin.wzl 已提交
5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739
    top->mark_is_plan_root();
    ObLogTempTableInsert *temp_table_insert = static_cast<ObLogTempTableInsert*>(op);
    temp_table_insert->set_temp_table_id(temp_table_info->temp_table_id_);
    temp_table_insert->get_table_name().assign_ptr(temp_table_info->table_name_.ptr(),
                                                   temp_table_info->table_name_.length());
    if (OB_FAIL(temp_table_insert->add_child(top))) {
      LOG_WARN("failed to add one children", K(ret));
    } else if (OB_FAIL(temp_table_insert->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      top = temp_table_insert;
O
oceanbase-admin 已提交
5740 5741 5742 5743 5744
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5745
int ObLogPlan::candi_allocate_temp_table_transformation()
O
oceanbase-admin 已提交
5746 5747
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5748 5749 5750 5751 5752 5753 5754 5755
  ObExchangeInfo exch_info;
  CandidatePlan candidate_plan;
  ObSEArray<CandidatePlan, 8> temp_table_trans_plans;
  ObSEArray<ObLogicalOperator*, 8> temp_table_insert;
  ObIArray<ObSqlTempTableInfo*> &temp_table_infos = get_optimizer_context().get_temp_table_infos();
  for (int64_t i = 0; OB_SUCC(ret) && i < temp_table_infos.count(); i++) {
    ObLogicalOperator *temp_table_plan = NULL;
    if (OB_ISNULL(temp_table_plan = temp_table_infos.at(i)->table_plan_)) {
O
oceanbase-admin 已提交
5756
      ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777
      LOG_WARN("get unexpected null", K(ret), K(temp_table_plan));
    } else if (OB_FAIL(allocate_temp_table_insert_as_top(temp_table_plan, temp_table_infos.at(i)))) {
      LOG_WARN("failed to allocate temp table insert", K(ret));
    } else if (OB_FAIL(temp_table_insert.push_back(temp_table_plan))) {
      LOG_WARN("failed to push back temp table plan", K(ret));
    } else { /*do nothing*/ }
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); ++i) {
    candidate_plan = candidates_.candidate_plans_.at(i);
    if (OB_FAIL(create_temp_table_transformation_plan(candidate_plan.plan_tree_,
                                                      temp_table_insert))) {
      LOG_WARN("failed to allocate temp table transformation", K(ret));
    } else if (OB_FAIL(temp_table_trans_plans.push_back(candidate_plan))) {
      LOG_WARN("failed to push back temp table transformation", K(ret));
    } else { /*do nothing*/ }
  }
  // choose the best plan
  if (OB_SUCC(ret)) {
    if (OB_FAIL(prune_and_keep_best_plans(temp_table_trans_plans))) {
      LOG_WARN("failed to prune and keep best plans", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5778
  }
W
wangzelin.wzl 已提交
5779

O
oceanbase-admin 已提交
5780 5781 5782
  return ret;
}

W
wangzelin.wzl 已提交
5783 5784
int ObLogPlan::create_temp_table_transformation_plan(ObLogicalOperator *&top,
                                                     const ObIArray<ObLogicalOperator*> &temp_table_insert)
O
oceanbase-admin 已提交
5785 5786
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800
  bool is_basic = false;
  ObIArray<ObSqlTempTableInfo*> &temp_table_infos = get_optimizer_context().get_temp_table_infos();
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(top), K(ret));
  } else if (OB_FAIL(check_basic_sharding_for_temp_table(top,
                                                        temp_table_insert,
                                                        is_basic))) {
    LOG_WARN("failed to check basic temp table transform plan", K(ret));
  } else if (is_basic) {
    if (OB_FAIL(allocate_temp_table_transformation_as_top(top, temp_table_insert))) {
      LOG_WARN("failed to allocate temp-table transformation", K(ret));
    } else { /*do nothing*/ }
  } else if (temp_table_infos.count() != temp_table_insert.count()) {
O
oceanbase-admin 已提交
5801
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815
    LOG_WARN("unexpect temp table info count", K(ret));
  } else {
    ObExchangeInfo exch_info;
    ObSEArray<ObLogicalOperator*, 16> child_ops;
    for (int64_t i = 0; OB_SUCC(ret) && i < temp_table_insert.count(); i++) {
      ObLogicalOperator *temp = temp_table_insert.at(i);
      ObSqlTempTableInfo* info = temp_table_infos.at(i);
      if (OB_ISNULL(temp) || OB_ISNULL(info)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (temp->is_sharding() && OB_FAIL(allocate_exchange_as_top(temp, exch_info))) {
        LOG_WARN("failed to allocate exchange as top", K(ret));
      } else if (OB_FAIL(child_ops.push_back(temp))) {
        LOG_WARN("failed to push back child ops", K(ret));
O
oceanbase-admin 已提交
5816 5817
      }
    }
W
wangzelin.wzl 已提交
5818 5819 5820 5821 5822 5823 5824
    if (OB_FAIL(ret)) {
      /*do nothing*/
    } else if (top->is_sharding() && OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
      LOG_WARN("failed to allocate exchange info", K(ret));
    } else if (OB_FAIL(allocate_temp_table_transformation_as_top(top, child_ops))) {
      LOG_WARN("failed to allocate temp-table transformation as top", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5825 5826 5827 5828
  }
  return ret;
}

W
wangzelin.wzl 已提交
5829 5830 5831
int ObLogPlan::check_basic_sharding_for_temp_table(ObLogicalOperator *&top,
                                                  const ObIArray<ObLogicalOperator*> &temp_table_insert,
                                                  bool &is_basic)
O
oceanbase-admin 已提交
5832 5833
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854
  is_basic = false;
  ObSEArray<ObLogicalOperator*, 8> child_ops;
  ObAddr &local_addr = get_optimizer_context().get_local_server_addr();
  if (OB_FAIL(append(child_ops, temp_table_insert))) {
    LOG_WARN("failed to append array", K(ret));
  } else if (OB_FAIL(child_ops.push_back(top))) {
    LOG_WARN("failed to push back array", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::check_basic_sharding_info(local_addr,
                                                                child_ops,
                                                                is_basic))) {
    LOG_WARN("failed to check basic sharding info", K(ret));
  } else if (!is_basic) {
    //do nothing
  }
  for (int64_t i = 0; OB_SUCC(ret) && is_basic && i < child_ops.count(); ++i) {
    ObLogicalOperator *op = child_ops.at(i);
    if (OB_ISNULL(op)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null operator", K(ret));
    } else if (op->is_exchange_allocated()) {
      is_basic = false;
O
oceanbase-admin 已提交
5855
    } else {
W
wangzelin.wzl 已提交
5856
      is_basic = true;
O
oceanbase-admin 已提交
5857 5858 5859 5860 5861
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5862 5863
int ObLogPlan::allocate_temp_table_transformation_as_top(ObLogicalOperator *&top,
                                                         const ObIArray<ObLogicalOperator*> &temp_table_insert)
O
oceanbase-admin 已提交
5864 5865
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5866 5867
  ObLogicalOperator *temp_table_transformation = NULL;
  if (OB_ISNULL(top)) {
O
oceanbase-admin 已提交
5868
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879
    LOG_WARN("get unexpected null", K(top));
  } else if (OB_ISNULL(temp_table_transformation =
             log_op_factory_.allocate(*this, LOG_TEMP_TABLE_TRANSFORMATION))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate temp table operator", K(ret));
  } else if (OB_FAIL(temp_table_transformation->add_child(temp_table_insert))) {
    LOG_WARN("failed to add child ops", K(ret));
  } else if (OB_FAIL(temp_table_transformation->add_child(top))) {
    LOG_WARN("failed to add children", K(ret));
  } else if (OB_FAIL(temp_table_transformation->compute_property())) {
    LOG_WARN("failed to compute property", K(ret));
O
oceanbase-admin 已提交
5880
  } else {
W
wangzelin.wzl 已提交
5881 5882 5883 5884
    top = temp_table_transformation;
  }
  return ret;
}
O
oceanbase-admin 已提交
5885

W
wangzelin.wzl 已提交
5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906
int ObLogPlan::candi_allocate_root_exchange()
{
  int ret = OB_SUCCESS;
  ObSEArray<CandidatePlan, 8> best_candidates;
  if (OB_FAIL(get_minimal_cost_candidates(candidates_.candidate_plans_, best_candidates))) {
    LOG_WARN("failed to get minimal cost candidates", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < best_candidates.count(); i++) {
      ObExchangeInfo exch_info;
      if (OB_ISNULL(best_candidates.at(i).plan_tree_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (best_candidates.at(i).plan_tree_->get_phy_plan_type() == ObPhyPlanType::OB_PHY_PLAN_REMOTE) {
        exch_info.is_remote_ = true;
        if (OB_FAIL(allocate_exchange_as_top(best_candidates.at(i).plan_tree_, exch_info))) {
          LOG_WARN("failed to allocate exchange as top", K(ret));
        } else { /*do nothing*/ }
      } else if (best_candidates.at(i).plan_tree_->is_sharding() &&
                 OB_FAIL(allocate_exchange_as_top(best_candidates.at(i).plan_tree_, exch_info))) {
        LOG_WARN("failed to allocate exchange as top", K(ret));
      } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5907 5908
    }
    if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
5909 5910 5911 5912 5913
      ObLogicalOperator *best_plan = NULL;
      if (OB_FAIL(init_candidate_plans(best_candidates))) {
        LOG_WARN("failed to do candi into", K(ret));
      } else if (OB_FAIL(candidates_.get_best_plan(best_plan))) {
        LOG_WARN("failed to get best plan", K(ret));
O
oceanbase-admin 已提交
5914
      } else {
W
wangzelin.wzl 已提交
5915 5916 5917 5918 5919
        set_plan_root(best_plan);
        best_plan->mark_is_plan_root();
        get_optimizer_context().set_plan_type(best_plan->get_phy_plan_type(),
                                            best_plan->get_location_type(),
                                            best_plan->is_exchange_allocated());
O
oceanbase-admin 已提交
5920 5921 5922
      }
    }
  }
W
wangzelin.wzl 已提交
5923 5924
  return ret;
}
O
oceanbase-admin 已提交
5925

W
wangzelin.wzl 已提交
5926 5927 5928 5929 5930 5931 5932 5933
int ObLogPlan::candi_allocate_scala_group_by(const ObIArray<ObAggFunRawExpr*> &agg_items)
{
  int ret = OB_SUCCESS;
  bool is_from_povit = false;
  ObSEArray<ObRawExpr*, 1> dummy_having_exprs;
  if (OB_FAIL(candi_allocate_scala_group_by(agg_items, dummy_having_exprs, is_from_povit))) {
    LOG_WARN("failed to allocate scala group by", K(ret));
  } else { /*do nothing*/ }
O
oceanbase-admin 已提交
5934 5935 5936
  return ret;
}

W
wangzelin.wzl 已提交
5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983
int ObLogPlan::prepare_three_stage_info(const ObIArray<ObRawExpr *> &group_by_exprs,
                                        const ObIArray<ObRawExpr *> &rollup_exprs,
                                        GroupingOpHelper &helper)
{
  int ret = OB_SUCCESS;
  ObIArray<ObAggFunRawExpr *> &aggr_items = helper.distinct_aggr_items_;
  UNUSED(group_by_exprs);
  if (OB_ISNULL(get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("session info is invalid", K(ret));
  } else if (OB_FAIL(ObRawExprUtils::build_inner_aggr_code_expr(
                       get_optimizer_context().get_expr_factory(),
                       *get_optimizer_context().get_session_info(),
                       helper.aggr_code_expr_))) {
    LOG_WARN("failed to build inner aggr code expr", K(ret));
  } else if (!rollup_exprs.empty() &&
             OB_FAIL(ObRawExprUtils::build_pseudo_rollup_id(
                       get_optimizer_context().get_expr_factory(),
                       *get_optimizer_context().get_session_info(),
                       helper.rollup_id_expr_))) {
    LOG_WARN("failed to build inner aggr code expr", K(ret));
  }


  for (int64_t i = 0; OB_SUCC(ret) && i < aggr_items.count(); ++i) {
    ObAggFunRawExpr *aggr = aggr_items.at(i);
    if (OB_ISNULL(aggr) || OB_UNLIKELY(!aggr->is_param_distinct())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("aggr item is null", K(ret), K(aggr));
    } else if (OB_FAIL(generate_three_stage_aggr_expr(get_optimizer_context().get_expr_factory(),
                                                      *get_optimizer_context().get_session_info(),
                                                      !rollup_exprs.empty(),
                                                      aggr,
                                                      helper.distinct_aggr_batch_,
                                                      helper.distinct_params_))) {
      LOG_WARN("failed generate three stage aggr expr", K(ret));
    }
  }
  if (OB_SUCC(ret)) {
    helper.distinct_aggr_items_.reuse();
    for (int64_t i = 0; OB_SUCC(ret) && i < helper.distinct_aggr_batch_.count(); ++i) {
      const ObDistinctAggrBatch &batch = helper.distinct_aggr_batch_.at(i);
      for (int64_t j = 0; OB_SUCC(ret) && j < batch.mocked_aggrs_.count(); ++j) {
        if (OB_FAIL(helper.distinct_aggr_items_.push_back(batch.mocked_aggrs_.at(j).first))) {
          LOG_WARN("failed to push back mocked aggr exprs", K(ret));
        }
      }
O
oceanbase-admin 已提交
5984 5985 5986 5987 5988
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5989 5990 5991 5992 5993 5994
int ObLogPlan::generate_three_stage_aggr_expr(ObRawExprFactory &expr_factory,
                                              ObSQLSessionInfo &session_info,
                                              const bool is_rollup,
                                              ObAggFunRawExpr *aggr,
                                              ObIArray<ObDistinctAggrBatch> &batch_distinct_aggrs,
                                              ObIArray<ObRawExpr *> &distinct_params)
O
oceanbase-admin 已提交
5995 5996
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5997 5998 5999 6000 6001
  bool find_same = false;
  ObAggFunRawExpr *new_aggr = NULL;
  std::pair<ObAggFunRawExpr *, ObAggFunRawExpr *> mocked_aggr;
  // 1. create a mock aggr expr
  if (OB_ISNULL(aggr)) {
O
oceanbase-admin 已提交
6002
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
6003 6004 6005 6006 6007 6008 6009 6010
    LOG_WARN("aggregation expr is null", K(ret), K(aggr));
  } else if (OB_FAIL(expr_factory.create_raw_expr(aggr->get_expr_type(), new_aggr))) {
    LOG_WARN("failed to create raw expr", K(ret));
  } else if (OB_ISNULL(new_aggr)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("new aggr is null", K(ret));
  } else if (OB_FAIL(new_aggr->assign(*aggr))) {
    LOG_WARN("failed to assign aggr expr", K(ret));
O
oceanbase-admin 已提交
6011
  } else {
W
wangzelin.wzl 已提交
6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058
    mocked_aggr.first = aggr;
    mocked_aggr.second = new_aggr;
    if (!is_rollup) {
      new_aggr->set_param_distinct(false);
    }
  }
  // 2. check whether the aggr share the same distinct with others.
  for (int64_t i = 0; OB_SUCC(ret) && !find_same && i < batch_distinct_aggrs.count(); ++i) {
    ObDistinctAggrBatch &batch = batch_distinct_aggrs.at(i);
    find_same = batch.mocked_params_.count() == new_aggr->get_real_param_count();
    for (int64_t j = 0; find_same && j < new_aggr->get_real_param_count(); ++j) {
      find_same = (batch.mocked_params_.at(j).first == new_aggr->get_real_param_exprs().at(j));
    }
    if (find_same) {
      for (int64_t j = 0; j < new_aggr->get_real_param_count(); ++j) {
        new_aggr->get_real_param_exprs_for_update().at(j) = batch.mocked_params_.at(j).second;
      }
      if (OB_FAIL(batch.mocked_aggrs_.push_back(mocked_aggr))) {
        LOG_WARN("failed to push back mocked aggr", K(ret));
      }
    }
  }
  // 3. the aggr does not share distinct exprs with others, create a new batch here
  if (OB_SUCC(ret) && !find_same) {
    ObDistinctAggrBatch batch;
    for (int64_t i = 0; OB_SUCC(ret) && i < new_aggr->get_real_param_exprs().count(); ++i) {
      ObRawExpr *real_param = new_aggr->get_real_param_exprs().at(i);
      ObRawExpr *new_real_param = NULL;
      if (OB_FAIL(ObRawExprUtils::build_dup_data_expr(expr_factory,
                                                      real_param,
                                                      new_real_param))) {
        LOG_WARN("failed to create dup data expr", K(ret));
      } else if (OB_FAIL(batch.mocked_params_.push_back(
                           std::pair<ObRawExpr *, ObRawExpr *>(real_param, new_real_param)))) {
        LOG_WARN("failed to push back the mocked param pair", K(ret));
      } else if (OB_FAIL(distinct_params.push_back(new_real_param))) {
        LOG_WARN("failed to push new real param", K(ret));
      } else {
        new_aggr->get_real_param_exprs_for_update().at(i) = new_real_param;
      }
    }
    if (OB_SUCC(ret)) {
      if (OB_FAIL(batch.mocked_aggrs_.push_back(mocked_aggr))) {
        LOG_WARN("failed to push back mocked aggr", K(ret));
      } else if (OB_FAIL(batch_distinct_aggrs.push_back(batch))) {
        LOG_WARN("failed to push back batch distinct funcs", K(ret));
      }
O
oceanbase-admin 已提交
6059 6060 6061 6062 6063
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
6064
bool ObLogPlan::disable_hash_groupby_in_second_stage()
O
oceanbase-admin 已提交
6065
{
W
wangzelin.wzl 已提交
6066 6067 6068 6069 6070 6071
  int ret = OB_SUCCESS;
  ObSQLSessionInfo *session_info = NULL;
  bool disable_hash_groupby_in_second = false;
  if (OB_ISNULL(session_info = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("session_info get unexpected null", K(ret), K(lbt()));
O
oceanbase-admin 已提交
6072
  } else {
W
wangzelin.wzl 已提交
6073 6074 6075 6076 6077 6078 6079 6080 6081
    omt::ObTenantConfigGuard tenant_config(TENANT_CONF(session_info->get_effective_tenant_id()));
    if (tenant_config.is_valid()) {
      disable_hash_groupby_in_second = tenant_config->_sqlexec_disable_hash_based_distagg_tiv;
      LOG_TRACE("trace disable hash groupby in second stage for three-stage",
        K(disable_hash_groupby_in_second));
    } else {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("failed to init tenant config", K(lbt()));
    }
O
oceanbase-admin 已提交
6082
  }
W
wangzelin.wzl 已提交
6083
  return disable_hash_groupby_in_second;
O
oceanbase-admin 已提交
6084 6085
}

W
wangzelin.wzl 已提交
6086 6087 6088 6089 6090
int ObLogPlan::create_three_stage_group_plan(const ObIArray<ObRawExpr*> &group_by_exprs,
                                             const ObIArray<ObRawExpr*> &rollup_exprs,
                                             const ObIArray<ObRawExpr*> &having_exprs,
                                             GroupingOpHelper &helper,
                                             ObLogicalOperator *&top)
O
oceanbase-admin 已提交
6091 6092
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120
  ObLogGroupBy *first_group_by = NULL;
  ObLogGroupBy *second_group_by = NULL;
  ObLogGroupBy *third_group_by = NULL;
  ObArray<ObRawExpr *> dummy_exprs;

  ObSEArray<OrderItem, 4> second_sort_keys;
  ObSEArray<ObRawExpr *, 8> rd_second_sort_exprs;
  ObSEArray<OrderItem, 4> rd_second_sort_keys;
  OrderItem encode_sort_key;
  bool enable_encode_sort = false;
  ObExchangeInfo second_exch_info;

  ObSEArray<OrderItem, 4> third_sort_keys;
  ObExchangeInfo third_exch_info;

  ObSEArray<ObRawExpr *, 8> first_group_by_exprs;
  ObSEArray<ObRawExpr *, 8> second_group_by_exprs;
  ObSEArray<ObRawExpr *, 8> third_group_by_exprs;
  ObSEArray<ObRawExpr *, 8> second_exch_exprs;
  ObSEArray<ObRawExpr *, 8> third_exch_exprs;
  ObSEArray<ObAggFunRawExpr *, 8> second_aggr_items;
  ObSEArray<ObAggFunRawExpr *, 8> third_aggr_items;
  ObSEArray<ObRawExpr *, 8> third_sort_exprs;

  ObRollupStatus second_rollup_status;
  ObRollupStatus third_rollup_status;
  AggregateAlgo second_aggr_algo;
  AggregateAlgo third_aggr_algo;
O
obdev 已提交
6121
  bool can_sort_opt = true;
W
wangzelin.wzl 已提交
6122 6123 6124

  // 1. prepare to allocate the first group by
  if (OB_ISNULL(top)) {
O
oceanbase-admin 已提交
6125
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160
    LOG_WARN("get unexpected null", K(ret), K(top));
  } else if (OB_FAIL(append(first_group_by_exprs, group_by_exprs)) ||
             OB_FAIL(append(first_group_by_exprs, rollup_exprs)) ||
             OB_FAIL(first_group_by_exprs.push_back(helper.aggr_code_expr_)) ||
             OB_FAIL(append(first_group_by_exprs, helper.distinct_params_))) {
    LOG_WARN("failed to construct first group by exprs", K(ret));
  } else if (OB_FAIL(allocate_group_by_as_top(top,
                                              HASH_AGGREGATE,
                                              first_group_by_exprs,
                                              dummy_exprs,
                                              helper.non_distinct_aggr_items_,
                                              dummy_exprs,
                                              false,
                                              helper.group_distinct_ndv_,
                                              top->get_card(),
                                              false,
                                              true))) {
    LOG_WARN("failed to allocate group by as top", K(ret));
  } else if (OB_UNLIKELY(LOG_GROUP_BY != top->get_type()) ||
             OB_ISNULL(first_group_by = static_cast<ObLogGroupBy *>(top))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("first group by is invalid", K(ret), KP(top));
  } else if (OB_FAIL(first_group_by->set_first_stage_info(helper.aggr_code_expr_,
                                                          helper.distinct_aggr_batch_))) {
    LOG_WARN("failed to set first stage info", K(ret));
  }

  // 2. prepare to allocate the second group by
  if (OB_SUCC(ret)) {
    if (!rollup_exprs.empty()) {
      second_aggr_algo = MERGE_AGGREGATE;
    } else if (helper.force_use_hash_) {
      second_aggr_algo = HASH_AGGREGATE;
    } else if (helper.force_use_merge_ || disable_hash_groupby_in_second_stage()) {
      second_aggr_algo = MERGE_AGGREGATE;
O
oceanbase-admin 已提交
6161
    } else {
W
wangzelin.wzl 已提交
6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191
      second_aggr_algo = HASH_AGGREGATE;
    }
    second_rollup_status = !rollup_exprs.empty() ? ROLLUP_DISTRIBUTOR : NONE_ROLLUP;

    if (OB_FAIL(append(second_group_by_exprs, group_by_exprs)) ||
        OB_FAIL(second_group_by_exprs.push_back(helper.aggr_code_expr_))) {
      LOG_WARN("failed to construct second group by exprs", K(ret));
    } else if (OB_FAIL(append(second_aggr_items, helper.distinct_aggr_items_)) ||
               OB_FAIL(append(second_aggr_items, helper.non_distinct_aggr_items_))) {
      LOG_WARN("failed to construct second aggr items", K(ret));
    } else if (OB_FAIL(append(second_exch_exprs, group_by_exprs)) ||
                // Ensure that the rows of the same distinct columns are in the same thread
               OB_FAIL(second_exch_exprs.push_back(helper.aggr_code_expr_)) ||
               OB_FAIL(append(second_exch_exprs, helper.distinct_params_))) {
      LOG_WARN("failed to construct second exchange exprs", K(ret));
    } else if (OB_FAIL(get_grouping_style_exchange_info(second_exch_exprs,
                                                        top->get_output_equal_sets(),
                                                        second_exch_info))) {
      LOG_WARN("failed to get grouping style exchange info", K(ret));
    } else if (second_aggr_algo != MERGE_AGGREGATE ||
               second_rollup_status == ROLLUP_DISTRIBUTOR) {
      // ROLLUP_DISTRIBUTOR has inner sort
      if (second_rollup_status != ROLLUP_DISTRIBUTOR || second_aggr_algo != MERGE_AGGREGATE) {
      } else if (OB_FAIL(append(rd_second_sort_exprs, second_group_by_exprs)) ||
                OB_FAIL(append(rd_second_sort_exprs, rollup_exprs))) {
        LOG_WARN("failed to append rollup distributor sort keys", K(ret));
      } else if (OB_FAIL(ObOptimizerUtil::make_sort_keys(rd_second_sort_exprs,
                                                        default_asc_direction(),
                                                        rd_second_sort_keys))) {
        LOG_WARN("failed to make sort keys", K(ret));
O
obdev 已提交
6192 6193 6194 6195
      } else if (OB_FAIL(ObOptimizerUtil::check_can_encode_sortkey(rd_second_sort_keys,
                                                                    can_sort_opt, *this))) {
        LOG_WARN("failed to check encode sortkey expr", K(ret));
      } else if (false
W
wangzelin.wzl 已提交
6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209
          && (OB_FAIL(ObSQLUtils::create_encode_sortkey_expr(get_optimizer_context().get_expr_factory(),
                                                            get_optimizer_context().get_exec_ctx(),
                                                            rd_second_sort_keys,
                                                            0,
                                                            encode_sort_key)
          || FALSE_IT(rd_second_sort_keys.reset())
          || FALSE_IT(enable_encode_sort = true)
          || OB_FAIL(rd_second_sort_keys.push_back(encode_sort_key))))) {
        LOG_WARN("failed to create encode sortkey expr", K(ret));
      }
    } else if (OB_FAIL(ObOptimizerUtil::make_sort_keys(first_group_by_exprs,
                                                       default_asc_direction(),
                                                       second_sort_keys))) {
      LOG_WARN("failed to make sort keys", K(ret));
O
oceanbase-admin 已提交
6210
    }
W
wangzelin.wzl 已提交
6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(allocate_sort_and_exchange_as_top(top,
                                                  second_exch_info,
                                                  second_sort_keys,
                                                  true,
                                                  0,
                                                  top->get_is_local_order()))) {
      LOG_WARN("failed to allocate sort and exchange as top", K(ret));
    } else if (OB_FAIL(allocate_group_by_as_top(top,
                                                second_aggr_algo,
                                                second_group_by_exprs,
                                                rollup_exprs,
                                                second_aggr_items,
                                                dummy_exprs,
                                                false,
                                                helper.group_ndv_ * helper.distinct_aggr_items_.count(),
                                                top->get_card(),
                                                false,
                                                true,
                                                false,
                                                second_rollup_status))) {
      LOG_WARN("failed to allocate group by as top", K(ret));
    } else if (OB_UNLIKELY(LOG_GROUP_BY != top->get_type()) ||
               OB_ISNULL(second_group_by = static_cast<ObLogGroupBy *>(top))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("second group by is invalid", K(ret), KP(top));
    } else if (OB_FAIL(second_group_by->set_second_stage_info(helper.aggr_code_expr_,
                                                              helper.distinct_aggr_batch_,
                                                              helper.distinct_params_))) {
      LOG_WARN("failed to set aggr info", K(ret));
    } else if (OB_FAIL(second_group_by->set_rollup_info(second_rollup_status,
                                                        helper.rollup_id_expr_,
                                                        rd_second_sort_keys,
                                                        enable_encode_sort))) {
      LOG_WARN("failed to set rollup parallel info", K(ret));
O
oceanbase-admin 已提交
6247 6248
    }
  }
W
wangzelin.wzl 已提交
6249 6250 6251

  // 3. prepare to allocate the third group by
  if (OB_SUCC(ret)) {
6252 6253 6254 6255 6256 6257 6258
    if (helper.is_scalar_group_by_) {
      third_aggr_algo = SCALAR_AGGREGATE;
    } else if (group_by_exprs.empty()) {
      third_aggr_algo = MERGE_AGGREGATE;
    } else {
      third_aggr_algo = second_aggr_algo;
    }
W
wangzelin.wzl 已提交
6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277
    third_rollup_status = !rollup_exprs.empty() ? ROLLUP_COLLECTOR : NONE_ROLLUP;
    third_exch_info.is_rollup_hybrid_ = !rollup_exprs.empty();

    if (OB_FAIL(append(third_group_by_exprs, group_by_exprs))) {
      LOG_WARN("failed to append third group by expr", K(ret));
    } else if (!rollup_exprs.empty() && OB_FAIL(third_group_by_exprs.push_back(helper.rollup_id_expr_))) {
      LOG_WARN("failed to append rollup id expr", K(ret));
    } else if (OB_FAIL(append(third_aggr_items, helper.distinct_aggr_items_))) {
      LOG_WARN("failed to construct third aggregate function exprs", K(ret));
    } else if (!rollup_exprs.empty() && OB_FAIL(append(third_aggr_items, helper.non_distinct_aggr_items_))) {
      LOG_WARN("failed to construct third aggregate function exprs", K(ret));
    } else if (OB_FAIL(append(third_exch_exprs, third_group_by_exprs)) ||
               OB_FAIL(append(third_exch_exprs, rollup_exprs))) {
      LOG_WARN("failed to append to third sort exprs", K(ret));
    } else if (OB_FAIL(get_grouping_style_exchange_info(third_exch_exprs,
                                                        top->get_output_equal_sets(),
                                                        third_exch_info))) {
      LOG_WARN("failed to get grouping style exchange info", K(ret));
    } else if (third_aggr_algo != MERGE_AGGREGATE) {
O
oceanbase-admin 已提交
6278
      // do nothing
W
wangzelin.wzl 已提交
6279 6280 6281 6282 6283 6284 6285 6286
    } else if (OB_FAIL(append(third_sort_exprs, third_group_by_exprs)) ||
               OB_FAIL(append(third_sort_exprs, rollup_exprs)) ||
               OB_FAIL(third_sort_exprs.push_back(helper.aggr_code_expr_))) {
      LOG_WARN("failed to create third sort keys", K(ret));
    } else if (OB_FAIL(ObOptimizerUtil::make_sort_keys(third_sort_exprs,
                                                       default_asc_direction(),
                                                       third_sort_keys))) {
      LOG_WARN("failed to make sort keys", K(ret));
O
oceanbase-admin 已提交
6287 6288
    }
  }
W
wangzelin.wzl 已提交
6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323

  if (OB_SUCC(ret)) {
    if (OB_FAIL(allocate_sort_and_exchange_as_top(top,
                                                  third_exch_info,
                                                  third_sort_keys,
                                                  0 < rollup_exprs.count() ? true: false,
                                                  true,
                                                  false,
                                                  0,
                                                  top->get_is_local_order()))) {
      LOG_WARN("failed to allocate sort and exchange as top", K(ret));
    } else if (OB_FAIL(allocate_group_by_as_top(top,
                                                third_aggr_algo,
                                                third_group_by_exprs,
                                                rollup_exprs,
                                                third_aggr_items,
                                                having_exprs,
                                                false,
                                                helper.group_ndv_,
                                                top->get_card(),
                                                false,
                                                false,
                                                false,
                                                third_rollup_status))) {
      LOG_WARN("failed to allocate group by as top", K(ret));
    } else if (OB_UNLIKELY(LOG_GROUP_BY != top->get_type()) ||
               OB_ISNULL(third_group_by = static_cast<ObLogGroupBy *>(top))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("second group by is invalid", K(ret), KP(top));
    } else if (OB_FAIL(third_group_by->set_third_stage_info(helper.aggr_code_expr_,
                                                            helper.distinct_aggr_batch_))) {
      LOG_WARN("failed to set aggr info", K(ret));
    } else if (OB_FAIL(third_group_by->set_rollup_info(third_rollup_status,
                                                       helper.rollup_id_expr_))) {
      LOG_WARN("failed to set rollup parallel info", K(ret));
O
obdev 已提交
6324 6325
    } else {
      third_group_by->set_group_by_outline_info(HASH_AGGREGATE == second_aggr_algo, true);
O
oceanbase-admin 已提交
6326
    }
W
wangzelin.wzl 已提交
6327 6328 6329
  }
  return ret;
}
O
oceanbase-admin 已提交
6330

O
obdev 已提交
6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372
// old : old wf expr with aggr_expr(param of aggr_expr is orig expr)
// new : new wf expr with aggr_expr(param of aggr_expr is the res of old wf expr)
int ObLogPlan::perform_window_function_pushdown(ObLogicalOperator *op)
{
  int ret = OB_SUCCESS;
  ObLogWindowFunction *window_function = NULL;
  if (NULL != (window_function = dynamic_cast<ObLogWindowFunction *>(op))) {
    ObIArray<ObWinFunRawExpr *> &window_exprs = window_function->get_window_exprs();
    if (window_function->is_consolidator()) {
      for (int64_t i = 0; OB_SUCC(ret) && i < window_exprs.count(); ++i) {
        ObRawExpr *new_wf_expr = NULL;
        ObAggFunRawExpr *new_aggr_expr = NULL;
        if (OB_FAIL(get_optimizer_context().get_expr_factory().create_raw_expr(
            window_exprs.at(i)->get_expr_class(),
            window_exprs.at(i)->get_expr_type(),
            new_wf_expr))) {
          LOG_WARN("failed to create new_wf_expr", K(ret));
        } else if (OB_FAIL(new_wf_expr->assign(*window_exprs.at(i)))) {
          LOG_WARN("failed to assign to new_wf_expr", K(ret));
        } else if (OB_FAIL(ObRawExprUtils::build_common_aggr_expr(
            get_optimizer_context().get_expr_factory(), get_optimizer_context().get_session_info(),
            T_FUN_COUNT == static_cast<ObWinFunRawExpr*>(new_wf_expr)->get_agg_expr()->get_expr_type()
              ? T_FUN_COUNT_SUM
              : static_cast<ObWinFunRawExpr*>(new_wf_expr)->get_agg_expr()->get_expr_type(),
            window_exprs.at(i),
            new_aggr_expr))) {
          LOG_WARN("failed to build_common_aggr_expr", K(ret));
        } else if (FALSE_IT(static_cast<ObWinFunRawExpr*>(new_wf_expr)->set_agg_expr(
                            new_aggr_expr))) {
        } else if (OB_FAIL(window_function_replaced_exprs_.push_back(
                           std::pair<ObRawExpr *, ObRawExpr *>(window_exprs.at(i), new_wf_expr)))) {
          LOG_WARN("failed to push back pushdown aggr", K(ret));
        }
      }
    }
  }
  if (OB_SUCC(ret) && OB_FAIL(op->replace_op_exprs(window_function_replaced_exprs_))) {
    LOG_WARN("failed to replace generated aggr expr", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383
int ObLogPlan::perform_group_by_pushdown(ObLogicalOperator *op)
{
  int ret = OB_SUCCESS;
  ObLogTableScan *table_scan = NULL;
  ObLogGroupBy *group_by = NULL;
  if (NULL != (table_scan = dynamic_cast<ObLogTableScan *>(op))) {
    for (int64_t i = 0; OB_SUCC(ret) && i < table_scan->get_pushdown_aggr_exprs().count(); ++i) {
      ObAggFunRawExpr *old_aggr = table_scan->get_pushdown_aggr_exprs().at(i);
      if (OB_FAIL(group_replaced_exprs_.push_back(
                    std::pair<ObRawExpr *, ObRawExpr *>(old_aggr, old_aggr)))) {
        LOG_WARN("failed to push back scalar aggr replace pair", K(ret));
O
oceanbase-admin 已提交
6384 6385
      }
    }
W
wangzelin.wzl 已提交
6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419
  } else {
    if (NULL != (group_by = dynamic_cast<ObLogGroupBy *>(op))) {
      for (int64_t i = 0; OB_SUCC(ret) && i < group_by->get_aggr_funcs().count(); ++i) {
        ObRawExpr *expr = group_by->get_aggr_funcs().at(i);
        ObAggFunRawExpr *old_aggr = static_cast<ObAggFunRawExpr *>(expr);
        ObAggFunRawExpr *new_aggr = NULL;
        if (OB_ISNULL(expr) || OB_UNLIKELY(!expr->is_aggr_expr())) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid aggr expr", K(ret));
        } else if (OB_FAIL(try_to_generate_pullup_aggr(old_aggr, new_aggr))) {
          LOG_WARN("failed to generate pullup aggr", K(ret));
        } else if (!group_by->is_push_down() || new_aggr != NULL) {
          // do nothing if
          // 1. the group by is not a pushdown operator or
          // 2. the group by is responsible for merging partial aggregations.
        } else if (OB_FAIL(group_replaced_exprs_.push_back(
                             std::pair<ObRawExpr *, ObRawExpr *>(old_aggr, old_aggr)))) {
          LOG_WARN("failed to push back pushdown aggr", K(ret));
        }
      }
      if (group_by->is_second_stage()) {
        for (int64_t i = 0; i < group_by->get_distinct_aggr_batch().count(); ++i) {
          const ObDistinctAggrBatch &batch = group_by->get_distinct_aggr_batch().at(i);
          for (int64_t j = 0; j < batch.mocked_aggrs_.count(); ++j) {
            ObRawExpr *from = batch.mocked_aggrs_.at(j).first;
            ObRawExpr *to = batch.mocked_aggrs_.at(j).second;

            for (int64_t k = 0; k < group_replaced_exprs_.count(); ++k) {
              if (group_replaced_exprs_.at(k).first == from) {
                group_replaced_exprs_.at(k).second = to;
                break;
              }
            }
          }
O
oceanbase-admin 已提交
6420 6421 6422
        }
      }
    }
O
obdev 已提交
6423
    if (OB_SUCC(ret) && OB_FAIL(op->replace_op_exprs(group_replaced_exprs_))) {
W
wangzelin.wzl 已提交
6424 6425
      LOG_WARN("failed to replace generated aggr expr", K(ret));
    }
O
oceanbase-admin 已提交
6426 6427 6428 6429
  }
  return ret;
}

W
wangzelin.wzl 已提交
6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442
/**
 * @brief ObLogPlan::try_to_generate_pullup_aggr
 * 1. If the old_aggr exists in the group_replaced_exprs_,
 * it means that the aggr is pre-aggregated by a child group-by operator.
 * therefore, the current group-by is responsible for merging partial aggregation results.
 *
 * 2. If the old_aggr does not exists in the group_replaced_exprs_,
 * the current group-by is the first one to generate the aggregation.
 *
 * @return
 */
int ObLogPlan::try_to_generate_pullup_aggr(ObAggFunRawExpr *old_aggr,
                                           ObAggFunRawExpr *&new_aggr)
O
oceanbase-admin 已提交
6443 6444
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461
  new_aggr = NULL;
  for (int64_t i = 0; OB_SUCC(ret) && i < group_replaced_exprs_.count(); ++i) {
    if (group_replaced_exprs_.at(i).first != old_aggr) {
      // do nothing
    } else if (OB_ISNULL(group_replaced_exprs_.at(i).second) ||
               OB_UNLIKELY(!group_replaced_exprs_.at(i).second->is_aggr_expr())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("the group replaced expr is expected to be a aggregation", K(ret));
    } else if (OB_FAIL(ObOptimizerUtil::generate_pullup_aggr_expr(
                         get_optimizer_context().get_expr_factory(),
                         get_optimizer_context().get_session_info(),
                         static_cast<ObAggFunRawExpr *>(group_replaced_exprs_.at(i).second),
                         new_aggr))) {
      LOG_WARN("failed to generate pullup aggr expr", K(ret));
    } else {
      group_replaced_exprs_.at(i).second = new_aggr;
      break;
O
oceanbase-admin 已提交
6462
    }
W
wangzelin.wzl 已提交
6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479
  }
  return ret;
}

int ObLogPlan::candi_allocate_scala_group_by(const ObIArray<ObAggFunRawExpr*> &agg_items,
                                             const ObIArray<ObRawExpr*> &having_exprs,
                                             const bool is_from_povit)
{
  int ret = OB_SUCCESS;
  ObSEArray<CandidatePlan, 4> best_plans;
  ObSEArray<ObRawExpr*, 1> dummy_exprs;
  SMART_VAR(GroupingOpHelper, groupby_helper) {
    if (OB_FAIL(init_groupby_helper(dummy_exprs, dummy_exprs, agg_items,
                                    is_from_povit, groupby_helper))) {
      LOG_WARN("failed to init group by helper", K(ret));
    } else if (OB_FAIL(get_minimal_cost_candidates(candidates_.candidate_plans_, best_plans))) {
      LOG_WARN("failed to get minimal cost candidate", K(ret));
O
oceanbase-admin 已提交
6480
    } else {
W
wangzelin.wzl 已提交
6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500
      for (int64_t i = 0; OB_SUCC(ret) && i < best_plans.count(); i++) {
        if (OB_FAIL(create_scala_group_plan(agg_items,
                                            having_exprs,
                                            is_from_povit,
                                            groupby_helper,
                                            best_plans.at(i).plan_tree_))) {
          LOG_WARN("failed to create scala group by plan", K(ret));
        } else { /*do nothing*/ }
      }
      if (OB_SUCC(ret)) {
        int64_t check_scope = OrderingCheckScope::CHECK_WINFUNC |
                              OrderingCheckScope::CHECK_DISTINCT |
                              OrderingCheckScope::CHECK_SET |
                              OrderingCheckScope::CHECK_ORDERBY;
        if (OB_FAIL(update_plans_interesting_order_info(best_plans, check_scope))) {
          LOG_WARN("failed to update plans interesting order info", K(ret));
        } else if (OB_FAIL(prune_and_keep_best_plans(best_plans))) {
          LOG_WARN("failed to add plan", K(ret));
        } else { /*do nothing*/ }
      }
O
oceanbase-admin 已提交
6501 6502 6503 6504 6505
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
6506 6507 6508 6509 6510
int ObLogPlan::create_scala_group_plan(const ObIArray<ObAggFunRawExpr*> &aggr_items,
                                       const ObIArray<ObRawExpr*> &having_exprs,
                                       const bool is_from_povit,
                                       GroupingOpHelper &groupby_helper,
                                       ObLogicalOperator *&top)
O
oceanbase-admin 已提交
6511 6512
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
6513 6514 6515 6516 6517 6518
  bool is_partition_wise = false;
  ObSEArray<ObRawExpr*, 1> dummy_exprs;
  ObSEArray<ObAggFunRawExpr*, 1> dummy_aggrs;
  double origin_child_card = 0.0;
  ObExchangeInfo exch_info;
  if (OB_ISNULL(top)) {
O
oceanbase-admin 已提交
6519
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FALSE_IT(origin_child_card = top->get_card())) {
  } else if (groupby_helper.can_scalar_pushdown_ &&
             OB_FAIL(try_push_aggr_into_table_scan(top, aggr_items))) {
    LOG_WARN("failed to push group by into table scan", K(ret));
  } else if (!top->is_distributed()) {
    if (OB_FAIL(allocate_scala_group_by_as_top(top,
                                               aggr_items,
                                               having_exprs,
                                               is_from_povit,
                                               origin_child_card))) {
      LOG_WARN("failed to allocate scala group by as top", K(ret));
O
obdev 已提交
6532 6533 6534
    } else {
      static_cast<ObLogGroupBy*>(top)->set_group_by_outline_info(false, false);
    }
W
wangzelin.wzl 已提交
6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572
  } else if (!groupby_helper.distinct_exprs_.empty() &&
             OB_FAIL(top->check_sharding_compatible_with_reduce_expr(groupby_helper.distinct_exprs_,
                                                                     is_partition_wise))) {
    LOG_WARN("failed to check if sharding compatible with distinct expr", K(ret));
  } else if (groupby_helper.can_three_stage_pushdown_ && !is_partition_wise) {
    if (NULL == groupby_helper.aggr_code_expr_ &&
        OB_FAIL(prepare_three_stage_info(dummy_exprs, dummy_exprs, groupby_helper))) {
      LOG_WARN("failed to prepare three stage info", K(ret));
    } else if (OB_FAIL(create_three_stage_group_plan(dummy_exprs,
                                                    dummy_exprs,
                                                    having_exprs,
                                                    groupby_helper,
                                                    top))) {
      LOG_WARN("failed to create three stage group plan", K(ret));
    }
  } else {
    if ((groupby_helper.can_basic_pushdown_ || is_partition_wise) &&
        OB_FAIL(allocate_group_by_as_top(top,
                                         AggregateAlgo::MERGE_AGGREGATE,
                                         dummy_exprs,
                                         dummy_exprs,
                                         aggr_items,
                                         dummy_exprs,
                                         is_from_povit,
                                         groupby_helper.group_ndv_,
                                         origin_child_card,
                                         is_partition_wise,
                                         true,
                                         is_partition_wise))) {
      LOG_WARN("failed to allocate scala group by as top", K(ret));
    } else if (OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_FAIL(allocate_scala_group_by_as_top(top,
                                                      aggr_items,
                                                      having_exprs,
                                                      is_from_povit,
                                                      origin_child_card))) {
      LOG_WARN("failed to allocate scala group by as top", K(ret));
O
obdev 已提交
6573 6574 6575
    } else {
      static_cast<ObLogGroupBy*>(top)->set_group_by_outline_info(false, groupby_helper.can_basic_pushdown_ || is_partition_wise); //zzydebug
    }
W
wangzelin.wzl 已提交
6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619
  }

  return ret;
}

int ObLogPlan::try_push_aggr_into_table_scan(ObLogicalOperator *top,
                                             const ObIArray<ObAggFunRawExpr *> &aggr_items)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(top));
  } else if (log_op_def::LOG_TABLE_SCAN == top->get_type()) {
    ObLogTableScan *scan_op = static_cast<ObLogTableScan*>(top);
    if (scan_op->get_index_back() ||
        scan_op->is_sample_scan()) {
      // can not push down
    } else if (OB_FAIL(scan_op->get_pushdown_aggr_exprs().assign(aggr_items))) {
      LOG_WARN("failed to assign group exprs", K(ret));
    }
  }
  return ret;
}

int ObLogPlan::get_grouping_style_exchange_info(const ObIArray<ObRawExpr*> &partition_exprs,
                                                const EqualSets &equal_sets,
                                                ObExchangeInfo &exch_info)
{
  int ret = OB_SUCCESS;
  if (!partition_exprs.empty()) {
    ObShardingInfo *sharding_info = NULL;
    if (OB_FAIL(get_cached_hash_sharding_info(partition_exprs, equal_sets, sharding_info))) {
      LOG_WARN("failed to get cached sharding info", K(ret));
    } else if (NULL != sharding_info) {
      if (OB_FAIL(exch_info.append_hash_dist_expr(partition_exprs))) {
        LOG_WARN("failed to append hash dist exprs", K(ret));
      } else {
        exch_info.dist_method_ = ObPQDistributeMethod::HASH;
        exch_info.strong_sharding_ = sharding_info;
      }
    } else if (OB_ISNULL(sharding_info = reinterpret_cast<ObShardingInfo*>(
                         allocator_.alloc(sizeof(ObShardingInfo))))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("failed to allocate memory", K(ret));
O
oceanbase-admin 已提交
6620
    } else {
W
wangzelin.wzl 已提交
6621 6622 6623 6624 6625
      sharding_info = new(sharding_info) ObShardingInfo();
      if (OB_FAIL(exch_info.append_hash_dist_expr(partition_exprs))) {
        LOG_WARN("append hash dist expr failed", K(ret));
      } else if (OB_FAIL(sharding_info->get_partition_keys().assign(partition_exprs))) {
        LOG_WARN("failed to assign expr", K(ret));
O
oceanbase-admin 已提交
6626
      } else {
W
wangzelin.wzl 已提交
6627 6628 6629 6630 6631 6632
        sharding_info->set_distributed();
        exch_info.dist_method_ = ObPQDistributeMethod::HASH;
        exch_info.strong_sharding_ = sharding_info;
        if (OB_FAIL(get_hash_dist_info().push_back(sharding_info))) {
          LOG_WARN("failed to push back sharding info", K(ret));
        } else { /*do nothing*/ }
O
oceanbase-admin 已提交
6633 6634 6635
      }
    }
  } else {
W
wangzelin.wzl 已提交
6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649
    exch_info.dist_method_ = ObPQDistributeMethod::LOCAL;
  }
  return ret;
}

int ObLogPlan::init_groupby_helper(const ObIArray<ObRawExpr*> &group_exprs,
                                   const ObIArray<ObRawExpr*> &rollup_exprs,
                                   const ObIArray<ObAggFunRawExpr*> &aggr_items,
                                   const bool is_from_povit,
                                   GroupingOpHelper &groupby_helper)
{
  int ret = OB_SUCCESS;
  ObSQLSessionInfo *session_info = NULL;
  ObLogicalOperator *best_plan = NULL;
6650
  const ObDMLStmt* stmt = NULL;
W
wangzelin.wzl 已提交
6651 6652
  ObSEArray<ObRawExpr*, 4> group_rollup_exprs;
  bool push_group = false;
6653
  groupby_helper.is_scalar_group_by_ = true;
W
wangzelin.wzl 已提交
6654 6655
  if (OB_FAIL(candidates_.get_best_plan(best_plan))) {
    LOG_WARN("failed to get best plan", K(ret));
6656
  } else if (OB_ISNULL(best_plan) ||
6657
             OB_ISNULL(stmt = get_stmt())) {
W
wangzelin.wzl 已提交
6658 6659
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
6660 6661 6662
  } else if (stmt->is_select_stmt() &&
             OB_FALSE_IT(groupby_helper.is_scalar_group_by_ =
                         static_cast<const ObSelectStmt*>(stmt)->is_scala_group_by())) {
W
wangzelin.wzl 已提交
6663 6664 6665
  } else if (OB_FAIL(append(group_rollup_exprs, group_exprs)) ||
             OB_FAIL(append(group_rollup_exprs, rollup_exprs))) {
    LOG_WARN("failed to append group rollup exprs", K(ret));
O
obdev 已提交
6666 6667 6668 6669 6670
  } else if (OB_FAIL(get_log_plan_hint().get_aggregation_info(groupby_helper.force_use_hash_,
                                                              groupby_helper.force_use_merge_,
                                                              groupby_helper.force_part_sort_,
                                                              groupby_helper.force_normal_sort_))) {
    LOG_WARN("failed to get aggregation info from hint", K(ret));
W
wangzelin.wzl 已提交
6671 6672 6673 6674
  } else if (OB_FAIL(check_scalar_groupby_pushdown(aggr_items,
                                                   groupby_helper.can_scalar_pushdown_))) {
    LOG_WARN("failed to check scalar group by pushdown", K(ret));
  } else if (get_log_plan_hint().no_pushdown_group_by()) {
O
obdev 已提交
6675
    OPT_TRACE("hint disable pushdown group by");
W
wangzelin.wzl 已提交
6676 6677 6678 6679 6680 6681
  } else if (OB_ISNULL(session_info = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(session_info), K(ret));
  } else if (OB_FAIL(session_info->if_aggr_pushdown_allowed(push_group))) {
    LOG_WARN("fail to get aggr_pushdown_allowed", K(ret));
  } else if (!push_group && !get_log_plan_hint().pushdown_group_by()) {
O
obdev 已提交
6682
    OPT_TRACE("session info disable pushdown group by");
W
wangzelin.wzl 已提交
6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737
  } else if (OB_FAIL(check_rollup_pushdown(session_info,
                                           aggr_items,
                                           groupby_helper.can_rollup_pushdown_))) {
    LOG_WARN("failed to check rollup pushdown", K(ret));
  } else if (OB_FAIL(check_basic_groupby_pushdown(
                       aggr_items,
                       best_plan->get_output_equal_sets(),
                       groupby_helper.can_basic_pushdown_))) {
    LOG_WARN("failed to check whether aggr can be pushed", K(ret));
  } else if (groupby_helper.can_basic_pushdown_ || is_from_povit) {
    // do nothing
  } else if (OB_FAIL(check_three_stage_groupby_pushdown(
                       rollup_exprs,
                       aggr_items,
                       groupby_helper.non_distinct_aggr_items_,
                       groupby_helper.distinct_aggr_items_,
                       best_plan->get_output_equal_sets(),
                       groupby_helper.distinct_exprs_,
                       groupby_helper.can_three_stage_pushdown_))) {
    LOG_WARN("failed to check use three stage push down", K(ret));
  }

  if (OB_SUCC(ret)) {
    get_selectivity_ctx().init_op_ctx(&best_plan->get_output_equal_sets(), best_plan->get_card());
    if (group_rollup_exprs.empty()) {
      groupby_helper.group_ndv_ = 1.0;
    } else if (OB_FAIL(ObOptSelectivity::calculate_distinct(get_update_table_metas(),
                                                            get_selectivity_ctx(),
                                                            group_rollup_exprs,
                                                            best_plan->get_card(),
                                                            groupby_helper.group_ndv_))) {
      LOG_WARN("failed to calculate distinct", K(ret));
    } else { /* do nothing */ }
  }

  if (OB_SUCC(ret) && groupby_helper.can_three_stage_pushdown_) {
    double total_ndv = 0;
    for (int64_t i = 0; OB_SUCC(ret) && i < groupby_helper.distinct_aggr_items_.count(); ++i) {
      ObSEArray<ObRawExpr*, 8> group_distinct_exprs;
      ObAggFunRawExpr *aggr = NULL;
      double ndv = 0;
      if (OB_ISNULL(aggr = groupby_helper.distinct_aggr_items_.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("distinct aggr item is null", K(ret));
      } else if (OB_FAIL(append(group_distinct_exprs, group_rollup_exprs)) ||
                 OB_FAIL(append(group_distinct_exprs, aggr->get_real_param_exprs()))) {
        LOG_WARN("failed to append group distinct exprs", K(ret));
      } else if (OB_FAIL(ObOptSelectivity::calculate_distinct(get_update_table_metas(),
                                                              get_selectivity_ctx(),
                                                              group_distinct_exprs,
                                                              best_plan->get_card(),
                                                              ndv))) {
        LOG_WARN("failed to calculate distinct", K(ret));
      } else {
        total_ndv += ndv;
O
oceanbase-admin 已提交
6738 6739
      }
    }
W
wangzelin.wzl 已提交
6740
    groupby_helper.group_distinct_ndv_ = total_ndv;
O
oceanbase-admin 已提交
6741
  }
W
wangzelin.wzl 已提交
6742
  LOG_TRACE("succeed to check whether aggr can be pushed", K(groupby_helper));
O
oceanbase-admin 已提交
6743 6744 6745
  return ret;
}

W
wangzelin.wzl 已提交
6746 6747
int ObLogPlan::init_distinct_helper(const ObIArray<ObRawExpr*> &distinct_exprs,
                                    GroupingOpHelper &distinct_helper)
O
oceanbase-admin 已提交
6748 6749
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
6750 6751 6752 6753 6754 6755 6756 6757 6758
  ObLogicalOperator *best_plan = NULL;
  ObSQLSessionInfo *session_info = NULL;
  bool push_distinct = false;
  distinct_helper.can_basic_pushdown_ = false;
  distinct_helper.force_use_hash_ = get_log_plan_hint().use_hash_distinct();
  distinct_helper.force_use_merge_ = get_log_plan_hint().use_merge_distinct();
  if (OB_FAIL(candidates_.get_best_plan(best_plan))) {
    LOG_WARN("failed to get best plan", K(ret));
  } else if (OB_ISNULL(best_plan)) {
O
oceanbase-admin 已提交
6759
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
6760 6761
    LOG_WARN("get unexpected null", K(ret));
  } else if (get_log_plan_hint().no_pushdown_distinct()) {
O
obdev 已提交
6762
    OPT_TRACE("hint disable pushdown distinct");
W
wangzelin.wzl 已提交
6763 6764 6765 6766 6767 6768
  } else if (OB_ISNULL(session_info = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(session_info), K(ret));
  } else if (OB_FAIL(session_info->if_aggr_pushdown_allowed(push_distinct))) {
    LOG_WARN("fail to get aggr_pushdown_allowed", K(ret));
  } else if (!push_distinct && !get_log_plan_hint().pushdown_distinct()) {
O
obdev 已提交
6769
    OPT_TRACE("session info disable pushdown distinct");
O
oceanbase-admin 已提交
6770
  } else {
W
wangzelin.wzl 已提交
6771
    distinct_helper.can_basic_pushdown_ = true;
O
obdev 已提交
6772
    OPT_TRACE("try pushdown distinct");
W
wangzelin.wzl 已提交
6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789
  }

  if (OB_SUCC(ret)) {
    get_selectivity_ctx().init_op_ctx(&best_plan->get_output_equal_sets(), best_plan->get_card());
    if (distinct_exprs.empty()) {
      distinct_helper.group_ndv_ = 1.0;
    } else if (OB_FAIL(ObOptSelectivity::calculate_distinct(get_update_table_metas(),
                                                            get_selectivity_ctx(),
                                                            distinct_exprs,
                                                            best_plan->get_card(),
                                                            distinct_helper.group_ndv_))) {
      LOG_WARN("failed to calculate distinct", K(ret));
    } else { /* do nothing */ }
  }

  if (OB_SUCC(ret)) {
    LOG_TRACE("succeed to init distinct helper", K(distinct_helper));
O
obdev 已提交
6790 6791
    OPT_TRACE("hint force use hash:", distinct_helper.force_use_hash_);
    OPT_TRACE("hint force use merge:", distinct_helper.force_use_merge_);
W
wangzelin.wzl 已提交
6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822
  }
  return ret;
}

int ObLogPlan::check_three_stage_groupby_pushdown(const ObIArray<ObRawExpr *> &rollup_exprs,
                                                  const ObIArray<ObAggFunRawExpr *> &aggr_items,
                                                  ObIArray<ObAggFunRawExpr *> &non_distinct_aggrs,
                                                  ObIArray<ObAggFunRawExpr *> &distinct_aggrs,
                                                  const EqualSets &equal_sets,
                                                  ObIArray<ObRawExpr *> &distinct_exprs,
                                                  bool &can_push)
{
  int ret = OB_SUCCESS;
  bool is_rollup = !rollup_exprs.empty();
  can_push = true;
  bool has_one_distinct = true;
  ObSQLSessionInfo *session = NULL;
  if (OB_ISNULL(session = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(session), K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && can_push && i < aggr_items.count(); ++i) {
    ObAggFunRawExpr *aggr_expr = aggr_items.at(i);
    if (OB_ISNULL(aggr_expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("aggr expr is null", K(ret), K(aggr_expr));
    } else if (aggr_expr->get_expr_type() != T_FUN_MIN &&
               aggr_expr->get_expr_type() != T_FUN_MAX &&
               aggr_expr->get_expr_type() != T_FUN_SUM &&
               aggr_expr->get_expr_type() != T_FUN_COUNT &&
               aggr_expr->get_expr_type() != T_FUN_GROUPING &&
O
obdev 已提交
6823 6824 6825 6826 6827
               aggr_expr->get_expr_type() != T_FUN_APPROX_COUNT_DISTINCT_SYNOPSIS &&
               aggr_expr->get_expr_type() != T_FUN_APPROX_COUNT_DISTINCT_SYNOPSIS_MERGE &&
               aggr_expr->get_expr_type() != T_FUN_SYS_BIT_AND &&
               aggr_expr->get_expr_type() != T_FUN_SYS_BIT_OR &&
               aggr_expr->get_expr_type() != T_FUN_SYS_BIT_XOR) {
W
wangzelin.wzl 已提交
6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838
      can_push = false;
    } else if (is_rollup && aggr_expr->get_expr_type() == T_FUN_GROUPING) {
      can_push = false;
    } else if (aggr_expr->is_param_distinct()) {
      if (OB_FAIL(distinct_aggrs.push_back(aggr_expr))) {
        LOG_WARN("failed to push back distinct aggr", K(ret));
      } else if (!has_one_distinct) {
        /* do nothing */
      } else if (distinct_exprs.empty()) {
        if (OB_FAIL(append(distinct_exprs, aggr_expr->get_real_param_exprs()))) {
          LOG_WARN("failed to append expr", K(ret));
O
oceanbase-admin 已提交
6839
        }
W
wangzelin.wzl 已提交
6840 6841 6842 6843
      } else {
        has_one_distinct = ObOptimizerUtil::same_exprs(distinct_exprs,
                                                       aggr_expr->get_real_param_exprs(),
                                                       equal_sets);
O
oceanbase-admin 已提交
6844
      }
W
wangzelin.wzl 已提交
6845 6846 6847 6848 6849 6850 6851 6852 6853
    } else if (OB_FAIL(non_distinct_aggrs.push_back(aggr_expr))) {
      LOG_WARN("failed to push back non distinct aggr", K(ret));
    }
  }
  if (OB_SUCC(ret) && can_push) {
    // if aggregate function has distinct arguments, then use 3 stage aggregate algorithm
    can_push = 0 < distinct_aggrs.count();
    if (can_push) {
      // only for test
O
obdev 已提交
6854
      ret = OB_E(EventTable::EN_ENABLE_THREE_STAGE_AGGREGATE) ret;
W
wangzelin.wzl 已提交
6855 6856 6857 6858 6859 6860 6861
      if (OB_FAIL(ret)) {
        // by default disable three stage aggregate
        int64_t xx = -ret;
        if (xx % 2 == 0) {
          can_push = false;
        } else {
          can_push = true;
O
oceanbase-admin 已提交
6862 6863
        }
      }
W
wangzelin.wzl 已提交
6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902
      ret = OB_SUCCESS;
    }
  }
  if (OB_SUCC(ret) && can_push && is_rollup) {
    int64_t partial_rollup_pushdown = 0;
    if (OB_FAIL(session->get_distinct_agg_partial_rollup_pushdown(
                  partial_rollup_pushdown))) {
      LOG_WARN("get force parallel ddl dop failed", K(ret));
    } else {
      can_push = (0 < partial_rollup_pushdown) && !aggr_items.empty();
    }
  }
  if (OB_SUCC(ret) && (!has_one_distinct || !can_push)) {
    distinct_exprs.reuse();
  }
  return ret;
}

int ObLogPlan::check_basic_groupby_pushdown(const ObIArray<ObAggFunRawExpr*> &aggr_items,
                                            const EqualSets &equal_sets,
                                            bool &can_push)
{
  int ret = OB_SUCCESS;
  can_push = true;
  // check whether contain agg expr can not be pushed down
  for (int64_t i = 0; OB_SUCC(ret) && can_push && i < aggr_items.count(); ++i) {
    ObAggFunRawExpr *aggr_expr = aggr_items.at(i);
    if (OB_ISNULL(aggr_expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (T_FUN_MAX != aggr_expr->get_expr_type() &&
               T_FUN_MIN != aggr_expr->get_expr_type() &&
               T_FUN_SUM != aggr_expr->get_expr_type() &&
               T_FUN_COUNT != aggr_expr->get_expr_type() &&
               T_FUN_COUNT_SUM != aggr_expr->get_expr_type() &&
               T_FUN_APPROX_COUNT_DISTINCT_SYNOPSIS != aggr_expr->get_expr_type() &&
               T_FUN_APPROX_COUNT_DISTINCT_SYNOPSIS_MERGE != aggr_expr->get_expr_type() &&
               !(T_FUN_GROUPING == aggr_expr->get_expr_type() &&
                 aggr_expr->get_real_param_count() == 1) &&
O
obdev 已提交
6903 6904 6905 6906
               T_FUN_TOP_FRE_HIST != aggr_expr->get_expr_type() &&
               T_FUN_SYS_BIT_AND != aggr_expr->get_expr_type() &&
               T_FUN_SYS_BIT_OR != aggr_expr->get_expr_type() &&
               T_FUN_SYS_BIT_XOR != aggr_expr->get_expr_type()) {
W
wangzelin.wzl 已提交
6907 6908 6909 6910
      can_push = false;
    } else if (aggr_expr->is_param_distinct()) {
      can_push = false;
    }
O
oceanbase-admin 已提交
6911 6912 6913 6914 6915
  }

  return ret;
}

W
wangzelin.wzl 已提交
6916 6917 6918
int ObLogPlan::check_rollup_pushdown(const ObSQLSessionInfo *info,
                                     const ObIArray<ObAggFunRawExpr *> &aggr_items,
                                     bool &can_push)
O
oceanbase-admin 已提交
6919 6920
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
6921 6922 6923
  int64_t enable_rollup_pushdown = 0;
  can_push = false;
  if (OB_ISNULL(info)) {
O
oceanbase-admin 已提交
6924
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
6925 6926 6927 6928 6929 6930 6931 6932 6933 6934
    LOG_WARN("session info is null", K(ret), K(info));
  } else if (OB_FAIL(info->get_partial_rollup_pushdown(enable_rollup_pushdown))) {
    LOG_WARN("failed to get partial rollup pushdown", K(ret));
  } else {
    can_push = (enable_rollup_pushdown > 0) && !aggr_items.empty();
  }
  for (int64_t i = 0; OB_SUCC(ret) && can_push && i < aggr_items.count(); ++i) {
    if (aggr_items.at(i)->get_expr_type() != T_FUN_MIN &&
        aggr_items.at(i)->get_expr_type() != T_FUN_MAX &&
        aggr_items.at(i)->get_expr_type() != T_FUN_SUM &&
O
obdev 已提交
6935 6936 6937 6938
        aggr_items.at(i)->get_expr_type() != T_FUN_COUNT &&
        aggr_items.at(i)->get_expr_type() != T_FUN_SYS_BIT_AND &&
        aggr_items.at(i)->get_expr_type() != T_FUN_SYS_BIT_OR &&
        aggr_items.at(i)->get_expr_type() != T_FUN_SYS_BIT_XOR) {
W
wangzelin.wzl 已提交
6939 6940 6941 6942
      can_push = false;
    } else if (aggr_items.at(i)->is_param_distinct()) {
      can_push = false;
    }
O
oceanbase-admin 已提交
6943 6944 6945 6946
  }
  return ret;
}

W
wangzelin.wzl 已提交
6947
bool ObLogPlan::is_tenant_enable_aggr_push_down(ObSQLSessionInfo &session_info)
O
oceanbase-admin 已提交
6948
{
W
wangzelin.wzl 已提交
6949 6950 6951 6952 6953 6954 6955 6956
  bool enabled = false;
  uint64_t tenant_id = session_info.get_effective_tenant_id();
  omt::ObTenantConfigGuard tenant_config(TENANT_CONF(tenant_id));
  if (tenant_config.is_valid()) {
    enabled = ObPushdownFilterUtils::is_aggregate_pushdown_enabled(tenant_config->_pushdown_storage_level);
  }
  return enabled;
}
O
oceanbase-admin 已提交
6957

W
wangzelin.wzl 已提交
6958 6959 6960
int ObLogPlan::check_scalar_groupby_pushdown(const ObIArray<ObAggFunRawExpr *> &aggrs,
                                             bool &can_push)
{
O
oceanbase-admin 已提交
6961
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974
  const ObDMLStmt *stmt = NULL;
  const TableItem *table_item = NULL;
  ObSQLSessionInfo *session_info = NULL;
  ObAggFunRawExpr *cur_aggr = NULL;
  ObRawExpr *first_param = NULL;
  bool has_virtual_col = false;
  can_push = false;
  if (OB_ISNULL(stmt = get_stmt()) ||
      OB_ISNULL(session_info = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (!is_tenant_enable_aggr_push_down(*session_info) ||
             !stmt->is_select_stmt()) {
O
obdev 已提交
6975
   OPT_TRACE("tenant disable aggregation push down");
W
wangzelin.wzl 已提交
6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991
  } else if (!static_cast<const ObSelectStmt*>(stmt)->is_scala_group_by() ||
             stmt->has_for_update() ||
             !stmt->is_single_table_stmt()) {
    /*do nothing*/
  } else if (OB_ISNULL(table_item = stmt->get_table_item(0))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(table_item));
  } else if (!table_item->is_basic_table() ||
             table_item->is_link_table() ||
             is_sys_table(table_item->ref_id_) ||
             is_virtual_table(table_item->ref_id_)) {
    /*do nothing*/
  } else if (OB_FAIL(stmt->has_virtual_generated_column(table_item->table_id_, has_virtual_col))) {
    LOG_WARN("failed to check has virtual generated column", K(ret), K(*table_item));
  } else if (has_virtual_col) {
    /* do not push down when exists virtual generated column */
O
oceanbase-admin 已提交
6992
  } else {
O
obdev 已提交
6993
    const ObIArray<ObRawExpr *> &filters = stmt->get_condition_exprs();
W
wangzelin.wzl 已提交
6994
    can_push = true;
O
obdev 已提交
6995 6996 6997 6998 6999 7000 7001 7002 7003
    /*do not push down when filters contain pl udf*/
    for (int64_t i = 0; OB_SUCC(ret) && can_push && i < filters.count(); i++) {
      if (OB_ISNULL(filters.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (filters.at(i)->has_flag(ObExprInfoFlag::CNT_PL_UDF)) {
        can_push = false;
      }
    }
W
wangzelin.wzl 已提交
7004 7005 7006 7007 7008
  }
  for (int64_t i = 0; OB_SUCC(ret) && can_push && i < aggrs.count(); ++i) {
    if (OB_ISNULL(cur_aggr = aggrs.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
7009 7010 7011
    } else if (T_FUN_COUNT != cur_aggr->get_expr_type()
               && T_FUN_MIN != cur_aggr->get_expr_type()
               && T_FUN_MAX != cur_aggr->get_expr_type()) {
W
wangzelin.wzl 已提交
7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025
      can_push = false;
    } else if (cur_aggr->is_param_distinct() || 1 < cur_aggr->get_real_param_count()) {
      /* mysql mode, support count(distinct c1, c2). if this distinct can be eliminated,
           the count(c1, c2) can not push down*/
      can_push = false;
    } else if (cur_aggr->get_real_param_exprs().empty()) {
      /* do nothing */
    } else if (OB_ISNULL(first_param = cur_aggr->get_param_expr(0))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (!first_param->is_column_ref_expr() ||
               table_item->table_id_ != static_cast<ObColumnRefRawExpr*>(first_param)->get_table_id()) {
      can_push = false;
    }
O
oceanbase-admin 已提交
7026 7027 7028 7029
  }
  return ret;
}

W
wangzelin.wzl 已提交
7030 7031 7032 7033
int ObLogPlan::check_can_pullup_gi(ObLogicalOperator &top,
                                   bool is_partition_wise,
                                   bool need_sort,
                                   bool &can_pullup)
O
oceanbase-admin 已提交
7034
{
W
wangzelin.wzl 已提交
7035 7036 7037 7038 7039 7040 7041 7042 7043
  int ret = OB_SUCCESS;
  can_pullup = false;
  bool has_win_func = false;
  if (is_partition_wise) {
    can_pullup = true;
  } else if (need_sort || !top.get_is_local_order() || top.is_exchange_allocated()) {
    /* do nothing */
  } else if (OB_FAIL(top.has_window_function_below(has_win_func))) {
    LOG_WARN("failed to check has window function below", K(ret));
O
oceanbase-admin 已提交
7044
  } else {
W
wangzelin.wzl 已提交
7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063
    can_pullup = !has_win_func;
  }
  return ret;
}

/**
 *  @brief  adjust_sort_expr_ordering
 *  调整需要排序的expr的顺序。像group by a, b 既可以按a, b排序,也可以按照b, a排序。
 *  先看能不能利用下层算子的序,如果不能再根据窗口函数或stmt order by调整顺序。
 */
int ObLogPlan::adjust_sort_expr_ordering(ObIArray<ObRawExpr*> &sort_exprs,
                                         ObIArray<ObOrderDirection> &sort_directions,
                                         ObLogicalOperator &child_op,
                                         bool check_win_func)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = NULL;
  const EqualSets &equal_sets = child_op.get_output_equal_sets();
  const ObIArray<ObRawExpr *> &const_exprs = child_op.get_output_const_exprs();
7064
  int64_t prefix_count = -1;
W
wangzelin.wzl 已提交
7065 7066 7067 7068 7069 7070 7071 7072 7073
  bool input_ordering_all_used = false;
  if (OB_ISNULL(stmt = child_op.get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get null stmt", K(ret), K(stmt));
  } else if (!child_op.get_op_ordering().empty() &&
             OB_FAIL(ObOptimizerUtil::adjust_exprs_by_ordering(sort_exprs,
                                                               child_op.get_op_ordering(),
                                                               equal_sets,
                                                               const_exprs,
O
obdev 已提交
7074
                                                               onetime_query_refs_,
7075
                                                               prefix_count,
W
wangzelin.wzl 已提交
7076 7077 7078
                                                               input_ordering_all_used,
                                                               sort_directions))) {
    LOG_WARN("failed to adjust exprs by ordering", K(ret));
7079 7080
  } else if (input_ordering_all_used) {
    /* sort_exprs use input ordering, need not sort */
W
wangzelin.wzl 已提交
7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092
  } else {
    bool adjusted = false;
    if (stmt->is_select_stmt() && check_win_func) {
      const ObSelectStmt *sel_stmt = static_cast<const ObSelectStmt *>(stmt);
      for (int64_t i = 0; OB_SUCC(ret) && !adjusted && i < sel_stmt->get_window_func_count(); ++i) {
        const ObWinFunRawExpr *cur_expr = sel_stmt->get_window_func_expr(i);
        if (OB_ISNULL(cur_expr)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get null window function expr", K(ret));
        } else if (cur_expr->get_partition_exprs().count() == 0 &&
                   cur_expr->get_order_items().count() == 0) {
          // win_func over(), do nothing
7093 7094 7095
        } else if (prefix_count > 0) {
          /* used part of input ordering, do not adjust now*/
          adjusted = true;
W
wangzelin.wzl 已提交
7096 7097 7098 7099 7100 7101 7102
        } else if (OB_FAIL(adjust_exprs_by_win_func(sort_exprs,
                                                    *cur_expr,
                                                    equal_sets,
                                                    const_exprs,
                                                    sort_directions))) {
            LOG_WARN("failed to adjust exprs by win func", K(ret));
        } else {
7103
          /* use no input ordering, adjusted by win func*/
W
wangzelin.wzl 已提交
7104 7105 7106 7107 7108
          adjusted = true;
        }
      }
    }
    if (OB_SUCC(ret) && !adjusted && stmt->get_order_item_size() > 0) {
7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123
      if (prefix_count > 0) {
        /* used part of input ordering, try adjust sort_exprs after prefix_count by order item */
        if (OB_FAIL(adjust_postfix_sort_expr_ordering(stmt->get_order_items(),
                                                      child_op.get_fd_item_set(),
                                                      equal_sets,
                                                      const_exprs,
                                                      prefix_count,
                                                      sort_exprs,
                                                      sort_directions))) {
          LOG_WARN("failed to adjust exprs by ordering", K(ret));
        }
      } else if (OB_FAIL(ObOptimizerUtil::adjust_exprs_by_ordering(sort_exprs,
                                                                   stmt->get_order_items(),
                                                                   equal_sets,
                                                                   const_exprs,
O
obdev 已提交
7124
                                                                   onetime_query_refs_,
7125 7126 7127
                                                                   prefix_count,
                                                                   input_ordering_all_used,
                                                                   sort_directions))) {
W
wangzelin.wzl 已提交
7128 7129 7130 7131 7132 7133 7134
        LOG_WARN("failed to adjust exprs by ordering", K(ret));
      }
    }
  }
  return ret;
}

7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166
int ObLogPlan::adjust_postfix_sort_expr_ordering(const ObIArray<OrderItem> &ordering,
                                                  const ObFdItemSet &fd_item_set,
                                                  const EqualSets &equal_sets,
                                                  const ObIArray<ObRawExpr*> &const_exprs,
                                                  const int64_t prefix_count,
                                                  ObIArray<ObRawExpr*> &sort_exprs,
                                                  ObIArray<ObOrderDirection> &sort_directions)
{
  int ret = OB_SUCCESS;
  LOG_DEBUG("begin adjust postfix sort expr ordering", K(prefix_count), K(fd_item_set), K(equal_sets),
                                              K(sort_exprs), K(sort_directions), K(ordering));
  if (OB_UNLIKELY(prefix_count < 0 || prefix_count >= sort_exprs.count())
      || OB_UNLIKELY(sort_directions.count() != sort_exprs.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected params", K(ret), K(prefix_count), K(sort_exprs.count()),
                                          K(sort_directions.count()));
  } else if (ordering.count() < prefix_count) {
    /* do nothing */
  } else {
    ObSEArray<ObRawExpr*, 5> new_sort_exprs;
    ObSEArray<ObOrderDirection, 5> new_sort_directions;
    bool check_next = false;
    bool can_adjust = true;
    int64_t idx = 0;
    for (int64_t i = 0; OB_SUCC(ret) && can_adjust && i < prefix_count; ++i) {
      check_next = true;
      while (OB_SUCC(ret) && check_next && idx < ordering.count()) {
        // after ObOptimizerUtil::adjust_exprs_by_ordering, there is not const exprs in sort_exprs.
        if (sort_directions.at(i) == ordering.at(idx).order_type_
            && ObOptimizerUtil::is_expr_equivalent(sort_exprs.at(i), ordering.at(idx).expr_, equal_sets)) {
          check_next = false;
        } else if (OB_FAIL(ObOptimizerUtil::is_const_or_equivalent_expr(ordering, equal_sets,
O
obdev 已提交
7167 7168
                                                                  const_exprs, onetime_query_refs_,
                                                                  idx, check_next))) {
7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208
          LOG_WARN("failed to check is const or equivalent exprs", K(ret));
        } else if (!check_next &&
                   OB_FAIL(ObOptimizerUtil::is_expr_is_determined(new_sort_exprs, fd_item_set,
                                                                  equal_sets, const_exprs,
                                                                  ordering.at(idx).expr_,
                                                                  check_next))) {
          LOG_WARN("failed to check is expr is determined", K(ret));
        } else if (check_next) {
          ++idx;
        }
      }
      if (OB_FAIL(ret)) {
      } else if (check_next) {
        can_adjust = false;
      } else if (OB_FAIL(new_sort_exprs.push_back(sort_exprs.at(i)))
                 || OB_FAIL(new_sort_directions.push_back(sort_directions.at(i)))) {
        LOG_WARN("failed to add prefix expr/direction", K(ret));
      } else {
        ++idx;
      }
    }
    if (OB_SUCC(ret) && idx < ordering.count() && can_adjust) {
      ObSqlBitSet<> added_sort_exprs;
      for (int64_t i = idx; OB_SUCC(ret) && can_adjust && i < ordering.count(); ++i) {
        can_adjust = false;
        for (int64_t j = prefix_count; OB_SUCC(ret) && !can_adjust && j <  sort_exprs.count(); ++j) {
          if (ObOptimizerUtil::is_expr_equivalent(sort_exprs.at(j), ordering.at(i).expr_, equal_sets)) {
            can_adjust = true;
            if (added_sort_exprs.has_member(j)) {
              /* do nothing */
            } else if (OB_FAIL(added_sort_exprs.add_member(j))) {
              LOG_WARN("failed to add bit set", K(ret));
            } else if (OB_FAIL(new_sort_exprs.push_back(sort_exprs.at(j)))
                       || OB_FAIL(new_sort_directions.push_back(ordering.at(i).order_type_))) {
              LOG_WARN("Failed to add prefix expr/direction", K(ret));
            }
          }
        }
        if (OB_FAIL(ret) || can_adjust) {
        } else if (OB_FAIL(ObOptimizerUtil::is_const_or_equivalent_expr(ordering, equal_sets,
O
obdev 已提交
7209 7210 7211
                                                                        const_exprs,
                                                                        onetime_query_refs_,
                                                                        i, can_adjust))) {
7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244
          LOG_WARN("failed to check is const or equivalent exprs", K(ret));
        } else if (!can_adjust && OB_FAIL(ObOptimizerUtil::is_expr_is_determined(new_sort_exprs,
                                                                                fd_item_set,
                                                                                equal_sets,
                                                                                const_exprs,
                                                                                ordering.at(i).expr_,
                                                                                can_adjust))) {
          LOG_WARN("failed to check is expr is determined", K(ret));
        }
      }
      if (OB_SUCC(ret) && can_adjust) {
        for (int64_t i = prefix_count; OB_SUCC(ret) && i < sort_exprs.count(); ++i) {
          if (added_sort_exprs.has_member(i)) {
            /* do nothing */
          } else if (OB_FAIL(new_sort_exprs.push_back(sort_exprs.at(i)))
                     || OB_FAIL(new_sort_directions.push_back(sort_directions.at(i)))) {
            LOG_WARN("failed to add prefix expr / direction", K(ret));
          }
        }
        LOG_DEBUG("adjusted postfix sort expr ordering", K(new_sort_exprs), K(new_sort_directions));
        if (OB_SUCC(ret)) {
          if (OB_FAIL(sort_exprs.assign(new_sort_exprs))) {
            LOG_WARN("assign adjusted exprs failed", K(ret));
          } else if (OB_FAIL(sort_directions.assign(new_sort_directions))) {
            LOG_WARN("failed to assign order types", K(ret));
          }
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299
/**
 * @brief  adjust_exprs_by_win_func
 * 根据 window function 调整 exprs 的顺序。先匹配 window function 的
 * partition by exprs, 如果 partition by exprs 能够完全匹配, 再匹配
 * window function 的 order by exprs。
 * 其中 partition by exprs 不要求严格的前缀匹配, order by exprs 要求严
 * 格的前缀匹配, 因为 partition by exprs 也是可以调整顺序的。
 */
int ObLogPlan::adjust_exprs_by_win_func(ObIArray<ObRawExpr *> &exprs,
                                        const ObWinFunRawExpr &win_expr,
                                        const EqualSets &equal_sets,
                                        const ObIArray<ObRawExpr*> &const_exprs,
                                        ObIArray<ObOrderDirection> &directions)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr *, 8> adjusted_exprs;
  ObSEArray<ObOrderDirection, 8> order_types;
  ObSEArray<ObRawExpr *, 8> rest_exprs;
  ObSEArray<ObOrderDirection, 8> rest_order_types;
  ObBitSet<64> expr_idxs;
  bool all_part_used = true;
  for (int64_t i = 0; OB_SUCC(ret) && i < win_expr.get_partition_exprs().count(); ++i) {
    bool find = false;
    const ObRawExpr *cur_expr = win_expr.get_partition_exprs().at(i);
    for (int64_t j = 0; OB_SUCC(ret) && !find && j < exprs.count(); ++j) {
      if (expr_idxs.has_member(j)) {
        // already add into adjusted_exprs
      } else if (ObOptimizerUtil::is_expr_equivalent(cur_expr, exprs.at(j), equal_sets)) {
        find = true;
        if (OB_FAIL(adjusted_exprs.push_back(exprs.at(j)))) {
          LOG_WARN("store ordered expr failed", K(ret), K(i), K(j));
        } else if (OB_FAIL(order_types.push_back(directions.at(j)))) {
          LOG_WARN("failed to push back order type");
        } else if (OB_FAIL(expr_idxs.add_member(j))) {
          LOG_WARN("add expr idxs member failed", K(ret), K(j));
        }
      }
    }
    if (!find) {
      all_part_used = false;
    }
  }

  for (int64_t i = 0; OB_SUCC(ret) && i < exprs.count(); ++i) {
    if (expr_idxs.has_member(i)) {
      // already add into adjusted_exprs
    } else if (OB_FAIL(rest_exprs.push_back(exprs.at(i)))) {
      LOG_WARN("store ordered expr failed", K(ret), K(i));
    } else if (OB_FAIL(rest_order_types.push_back(directions.at(i)))) {
      LOG_WARN("failed to push back order type", K(ret));
    }
  }
  if (OB_SUCC(ret) && all_part_used &&
      win_expr.get_order_items().count() > 0 &&
      rest_exprs.count() > 0) {
7300
    int64_t prefix_count = -1;
W
wangzelin.wzl 已提交
7301 7302 7303 7304 7305
    bool input_ordering_all_used = false;
    if (OB_FAIL(ObOptimizerUtil::adjust_exprs_by_ordering(rest_exprs,
                                                          win_expr.get_order_items(),
                                                          equal_sets,
                                                          const_exprs,
O
obdev 已提交
7306
                                                          onetime_query_refs_,
7307
                                                          prefix_count,
W
wangzelin.wzl 已提交
7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328
                                                          input_ordering_all_used,
                                                          rest_order_types))) {
      LOG_WARN("failed to adjust exprs by ordering", K(ret));
    }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(append(adjusted_exprs, rest_exprs))) {
      LOG_WARN("failed to append expr", K(ret));
    } else if (OB_FAIL(append(order_types, rest_order_types))) {
      LOG_WARN("failed to append order direction", K(ret));
    } else if (adjusted_exprs.count() != exprs.count() ||
               order_types.count() != exprs.count()) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("exprs don't covered completely",
               K(adjusted_exprs.count()), K(exprs.count()), K(order_types.count()));
    } else {
      exprs.reuse();
      if (OB_FAIL(exprs.assign(adjusted_exprs))) {
        LOG_WARN("assign adjusted exprs failed", K(ret));
      } else if (OB_FAIL(directions.assign(order_types))) {
        LOG_WARN("failed to assign order types", K(ret));
O
oceanbase-admin 已提交
7329 7330 7331
      }
    }
  }
W
wangzelin.wzl 已提交
7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469
  return ret;
}

int ObLogPlan::generate_plan_tree()
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(get_stmt()) || OB_ISNULL(get_optimizer_context().get_query_ctx())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("Get unexpected null", K(ret), K(get_stmt()));
  } else {
    // 1.1 generate access paths
    /* random exprs should be split from condition exprs to avoid being pushed down
     * random exprs will be added back in function candi_init*/
    if (OB_FAIL(generate_join_orders())) {
      LOG_WARN("failed to generate the access path for the single-table query",
               K(ret), K(get_optimizer_context().get_query_ctx()->get_sql_stmt()));
    } else if (OB_FAIL(init_candidate_plans())) {
      LOG_WARN("failed to initialized the plan candidates from the join order", K(ret));
    } else {
      LOG_TRACE("plan candidates is initialized from the join order",
                  "# of candidates", candidates_.candidate_plans_.count());
    }
  }
  return ret;
}

int ObLogPlan::get_minimal_cost_candidates(const ObIArray<CandidatePlan> &candidates,
                                           ObIArray<CandidatePlan> &best_candidates)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObSEArray<CandidatePlan, 16>, 8> candidate_list;
  if (OB_FAIL(classify_candidates_based_on_sharding(candidates,
                                                    candidate_list))) {
    LOG_WARN("failed to classify candidates based on sharding", K(ret));
  } else if (OB_FAIL(get_minimal_cost_candidates(candidate_list,
                                                 best_candidates))) {
    LOG_WARN("failed to get minimal cost candidates", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::check_join_legal(const ObRelIds &left_set,
                                const ObRelIds &right_set,
                                const ObRelIds &combined_set,
                                ConflictDetector *detector,
                                bool delay_cross_product,
                                bool &legal)
{
  int ret = OB_SUCCESS;
  legal = true;
  if (OB_ISNULL(detector)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null detector", K(ret));
  } else if (INNER_JOIN == detector->join_info_.join_type_) {
    if (!detector->join_info_.table_set_.is_subset(combined_set)) {
      //对于inner join来说只需要检查SES是否包含于left_set u right_set
      legal = false;
    }
  } else {
    if (detector->L_TES_.is_subset(left_set) &&
        detector->R_TES_.is_subset(right_set)) {
      //do nothing
    } else if (!detector->is_commutative_) {
      legal = false;
    } else if (detector->R_TES_.is_subset(left_set) &&
               detector->L_TES_.is_subset(right_set)) {
      //do nothing
    } else {
      legal = false;
    }
    if (legal && !detector->is_commutative_) {
      if (left_set.overlap(detector->R_DS_) ||
          right_set.overlap(detector->L_DS_)) {
        legal = false;
      }
    }
  }
  //如果连接谓词是退化谓词,例如t1 left join t2 on 1=t2.c1,需要额外的检查
  if (OB_FAIL(ret) || !legal) {
    //do nothing
  } else if (detector->is_degenerate_pred_) {
    //check T(left(o)) n S1 != empty ^ T(right(o)) n S2 != empty
    if (detector->L_DS_.overlap(left_set) &&
        detector->R_DS_.overlap(right_set)) {
      //do nothing
    } else if (!detector->is_commutative_) {
      legal = false;
    } else if (detector->R_DS_.overlap(left_set) &&
               detector->L_DS_.overlap(right_set)) {
      //do nothing
    } else {
      legal = false;
    }
  }
  //冲突规则检查
  if (OB_FAIL(ret) || !legal) {
    //do nothing
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && legal && i < detector->CR_.count(); ++i) {
      const ObRelIds& T1 = detector->CR_.at(i).first;
      const ObRelIds& T2 = detector->CR_.at(i).second;
      if (T1.overlap(combined_set) && !T2.is_subset(combined_set)) {
        legal = false;
      }
    }
    //检查笛卡尔积的约束
    if (OB_SUCC(ret) && legal) {
      for (int64_t i = 0; OB_SUCC(ret) && legal && i < detector->cross_product_rule_.count(); ++i) {
        const ObRelIds& T1 = detector->cross_product_rule_.at(i).first;
        const ObRelIds& T2 = detector->cross_product_rule_.at(i).second;
        if (T1.overlap(left_set) && !T2.is_subset(left_set)) {
          legal = false;
        } else if (T1.overlap(right_set) && !T2.is_subset(right_set)) {
          legal = false;
        }
      }
    }
    //如果需要延迟笛卡尔积,需要检查是否满足延迟条件
    if (OB_SUCC(ret) && delay_cross_product && legal) {
      for (int64_t i = 0; OB_SUCC(ret) && legal && i < detector->delay_cross_product_rule_.count(); ++i) {
        const ObRelIds& T1 = detector->delay_cross_product_rule_.at(i).first;
        const ObRelIds& T2 = detector->delay_cross_product_rule_.at(i).second;
        if (T1.overlap(left_set) && !T2.is_subset(left_set)) {
          legal = false;
        } else if (T1.overlap(right_set) && !T2.is_subset(right_set)) {
          legal = false;
        }
      }
    }
    //检查dependent function table的约束
    for (int64_t i = 0; OB_SUCC(ret) && legal && i < function_table_depend_infos_.count(); ++i) {
      FunctionTableDependInfo &info = function_table_depend_infos_.at(i);
      if (left_set.has_member(info.table_idx_)) {
        legal = info.depend_table_set_.is_subset(left_set);
      } else if (right_set.has_member(info.table_idx_)) {
        legal = info.depend_table_set_.is_subset(left_set) || info.depend_table_set_.is_subset(right_set);
      }
    }
O
obdev 已提交
7470 7471 7472 7473 7474 7475 7476 7477 7478

    for (int64_t i = 0; OB_SUCC(ret) && legal && i < json_table_depend_infos_.count(); ++i) {
      JsonTableDependInfo &info = json_table_depend_infos_.at(i);
      if (left_set.has_member(info.table_idx_)) {
        legal = info.depend_table_set_.is_subset(left_set);
      } else if (right_set.has_member(info.table_idx_)) {
        legal = info.depend_table_set_.is_subset(left_set) || info.depend_table_set_.is_subset(right_set);
      }
    }
W
wangzelin.wzl 已提交
7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599
  }
  return ret;
}

int ObLogPlan::get_minimal_cost_candidates(
    const ObIArray<ObSEArray<CandidatePlan, 16>> &candidate_list,
    ObIArray<CandidatePlan> &best_candidates)
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < candidate_list.count(); i++) {
    CandidatePlan best_candidate;
    if (OB_FAIL(get_minimal_cost_candidate(candidate_list.at(i),
                                           best_candidate))) {
      LOG_WARN("failed to get minimal cost candidate", K(ret));
    } else if (OB_FAIL(best_candidates.push_back(best_candidate))) {
      LOG_WARN("failed to push back candidate", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::get_minimal_cost_candidate(const ObIArray<CandidatePlan> &candidates,
                                          CandidatePlan &candidate)
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < candidates.count(); i++) {
    if (OB_ISNULL(candidates.at(i).plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (NULL == candidate.plan_tree_ ||
               candidates.at(i).plan_tree_->get_cost() < candidate.plan_tree_->get_cost()) {
      candidate = candidates.at(i);
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::classify_candidates_based_on_sharding(
    const ObIArray<CandidatePlan> &candidates,
    ObIArray<ObSEArray<CandidatePlan, 16>> &candidate_list)
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < candidates.count(); i++) {
    if (OB_ISNULL(candidates.at(i).plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else {
      bool is_find = false;
      for (int64_t j = 0; OB_SUCC(ret) && !is_find && j < candidate_list.count(); j++) {
        bool is_equal = false;
        ObIArray<CandidatePlan> &temp_candidate = candidate_list.at(j);
        if (OB_UNLIKELY(temp_candidate.empty()) ||
            OB_ISNULL(temp_candidate.at(0).plan_tree_)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected error", K(ret));
        } else if (OB_FAIL(ObShardingInfo::is_sharding_equal(
                            candidates.at(i).plan_tree_->get_strong_sharding(),
                            candidates.at(i).plan_tree_->get_weak_sharding(),
                            candidate_list.at(j).at(0).plan_tree_->get_strong_sharding(),
                            candidate_list.at(j).at(0).plan_tree_->get_weak_sharding(),
                            candidates.at(i).plan_tree_->get_output_equal_sets(),
                            is_equal))) {
          LOG_WARN("failed to check whether sharding is equal", K(ret));
        } else if (!is_equal) {
          /*do nothing*/
        } else if (OB_FAIL(temp_candidate.push_back(candidates.at(i).plan_tree_))) {
          LOG_WARN("failed to push back candidate plan", K(ret));
        } else {
          is_find = true;
        }
      }
      if (OB_SUCC(ret) && !is_find) {
        ObSEArray<CandidatePlan, 16> temp_candidate;
        if (OB_FAIL(temp_candidate.push_back(candidates.at(i)))) {
          LOG_WARN("failed to push back candidate plan", K(ret));
        } else if (OB_FAIL(candidate_list.push_back(temp_candidate))) {
          LOG_WARN("failed to push back candidate plan", K(ret));
        } else { /*do nothing*/ }
      }
    }
  }
  return ret;
}

int ObLogPlan::candi_allocate_order_by(bool &need_limit,
                                       ObIArray<OrderItem> &order_items)
{
  int ret = OB_SUCCESS;
  ObLogicalOperator *best_plan = NULL;
  ObSEArray<ObRawExpr*, 4> order_by_exprs;
  ObSEArray<ObOrderDirection, 4> directions;
  ObSEArray<CandidatePlan, 8> limit_plans;
  ObSEArray<CandidatePlan, 8> order_by_plans;
  ObSEArray<OrderItem, 8> candi_order_items;
  ObSEArray<ObRawExpr*, 4> candi_subquery_exprs;
  ObRawExpr *topn_expr = NULL;
  bool is_fetch_with_ties = false;
  need_limit = false;
  if (OB_ISNULL(get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret));
  } else if (FALSE_IT(need_limit = get_stmt()->has_limit())) {
    /*do nothing*/
  } else if (OB_FAIL(get_stmt()->get_order_exprs(candi_subquery_exprs))) {
    LOG_WARN("failed to get exprs", K(ret));
  } else if (OB_FAIL(candi_allocate_subplan_filter_for_exprs(candi_subquery_exprs))) {
    LOG_WARN("failed to allocate subplan filter for exprs", K(ret));
  } else if (OB_FAIL(candidates_.get_best_plan(best_plan))) {
    LOG_WARN("failed to get best plan", K(ret));
  } else if (OB_ISNULL(best_plan)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(get_order_by_exprs(best_plan, order_by_exprs, &directions))) {
    LOG_WARN("failed to get order by columns", K(ret));
  } else if (order_by_exprs.empty()) {
    /*do nothing*/
  } else if (OB_FAIL(make_order_items(order_by_exprs, directions, candi_order_items))) {
    LOG_WARN("Failed to make order items", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::simplify_ordered_exprs(best_plan->get_fd_item_set(),
                                                             best_plan->get_output_equal_sets(),
                                                             best_plan->get_output_const_exprs(),
O
obdev 已提交
7600
                                                             onetime_query_refs_,
W
wangzelin.wzl 已提交
7601 7602 7603 7604
                                                             candi_order_items,
                                                             order_items))) {
    LOG_WARN("failed to simplify exprs", K(ret));
  } else if (order_items.empty()) {
O
obdev 已提交
7605
    OPT_TRACE("this plan has interesting order, no need allocate order by");
W
wangzelin.wzl 已提交
7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662
  } else if (OB_FAIL(get_order_by_topn_expr(best_plan->get_card(),
                                            topn_expr,
                                            is_fetch_with_ties,
                                            need_limit))) {
    LOG_WARN("failed to get order by top-n expr", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); i++) {
      bool is_reliable = false;
      CandidatePlan candidate_plan = candidates_.candidate_plans_.at(i);
      if (OB_FAIL(create_order_by_plan(candidate_plan.plan_tree_,
                                       order_items,
                                       topn_expr,
                                       is_fetch_with_ties))) {
        LOG_WARN("failed to create order by plan", K(ret));
      } else if (NULL != topn_expr && OB_FAIL(is_plan_reliable(candidate_plan.plan_tree_,
                                                               is_reliable))) {
        LOG_WARN("failed to check if plan is reliable", K(ret));
      } else if (is_reliable) {
        ret = limit_plans.push_back(candidate_plan);
      } else {
        ret = order_by_plans.push_back(candidate_plan);
      }
    }
    // keep minimal cost plan or interesting plan
    if (OB_SUCC(ret)) {
      int64_t check_scope = OrderingCheckScope::CHECK_SET;
      if (limit_plans.empty() && OB_FAIL(limit_plans.assign(order_by_plans))) {
        LOG_WARN("failed to assign candidate plans", K(ret));
      } else if (OB_FAIL(update_plans_interesting_order_info(limit_plans, check_scope))) {
        LOG_WARN("failed to update plans interesting order info", K(ret));
      } else if (OB_FAIL(prune_and_keep_best_plans(limit_plans))) {
        LOG_WARN("failed to prune and keep best plans", K(ret));
      } else { /*do nothing*/ }
    }
  }
  return ret;
}

int ObLogPlan::create_order_by_plan(ObLogicalOperator *&top,
                                    const ObIArray<OrderItem> &order_items,
                                    ObRawExpr *topn_expr,
                                    bool is_fetch_with_ties)
{
  int ret = OB_SUCCESS;
  bool need_sort = false;
  int64_t prefix_pos = 0;
  ObExchangeInfo exch_info;
  exch_info.dist_method_ = (NULL != top && top->is_single()) ?
                           ObPQDistributeMethod::NONE : ObPQDistributeMethod::LOCAL;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::check_need_sort(order_items,
                                                      top->get_op_ordering(),
                                                      top->get_fd_item_set(),
                                                      top->get_output_equal_sets(),
                                                      top->get_output_const_exprs(),
O
obdev 已提交
7663
                                                      onetime_query_refs_,
W
wangzelin.wzl 已提交
7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699
                                                      top->get_is_at_most_one_row(),
                                                      need_sort,
                                                      prefix_pos))) {
    LOG_WARN("failed to check need sort", K(ret));
  } else if (OB_FAIL(allocate_sort_and_exchange_as_top(top,
                                                       exch_info,
                                                       order_items,
                                                       need_sort,
                                                       prefix_pos,
                                                       top->get_is_local_order(),
                                                       topn_expr,
                                                       is_fetch_with_ties))) {
    LOG_WARN("failed to allocate sort as top", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::get_order_by_exprs(const ObLogicalOperator *top,
                                  ObIArray<ObRawExpr *> &order_by_exprs,
                                  ObIArray<ObOrderDirection> *directions)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(get_stmt()) || OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(get_stmt()), K(top));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < get_stmt()->get_order_item_size(); i++) {
      const OrderItem &order_item = get_stmt()->get_order_item(i);
      bool is_const = false;
      bool has_null_reject = false;
      if (OB_ISNULL(order_item.expr_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(ObOptimizerUtil::is_const_expr(order_item.expr_,
                                                        top->get_output_equal_sets(),
                                                        top->get_output_const_exprs(),
O
obdev 已提交
7700
                                                        onetime_query_refs_,
W
wangzelin.wzl 已提交
7701 7702
                                                        is_const))) {
        LOG_WARN("check is const expr failed", K(ret));
O
obdev 已提交
7703
      } else if (is_const) {
W
wangzelin.wzl 已提交
7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063
        /**
         * orderby后面的const都已经被替换成了SelectItem里的expr,所以一般这里是不会出现const的。
         * 不过如果SelectItem里的expr本身是个const,那么这里会出现const,如:SELECT 1 FROM t1 ORDER BY 1;
         * 遇到const,跳过即可。
         */
      } else if (OB_FAIL(order_by_exprs.push_back(order_item.expr_))) {
        LOG_WARN("failed to add order by expr", K(ret));
      } else if (NULL != directions) {
        if (OB_FAIL(ObTransformUtils::has_null_reject_condition(get_stmt()->get_condition_exprs(),
                                                                order_item.expr_,
                                                                has_null_reject))) {
          LOG_WARN("failed to check null rejection", K(ret));
        } else if (!has_null_reject) {
          ret = directions->push_back(order_item.order_type_);
        } else if (is_ascending_direction(order_item.order_type_)) {
          ret = directions->push_back(default_asc_direction());
        } else {
          ret = directions->push_back(default_desc_direction());
        }
      }
    }
  }
  return ret;
}

int ObLogPlan::make_order_items(const common::ObIArray<ObRawExpr*> &exprs,
                                const ObIArray<ObOrderDirection> *dirs,
                                ObIArray<OrderItem> &items)
{
  int ret = OB_SUCCESS;
  if (NULL == dirs) {
    if (OB_FAIL(make_order_items(exprs, items))) {
      LOG_WARN("Failed to make order items", K(ret));
    }
  } else {
    if (OB_FAIL(make_order_items(exprs, *dirs, items))) {
    LOG_WARN("Failed to make order items", K(ret));
    }
  }
  return ret;
}

int ObLogPlan::make_order_items(const common::ObIArray<ObRawExpr *> &exprs,
                                common::ObIArray<OrderItem> &items)
{
  int ret = OB_SUCCESS;

  if (OB_ISNULL(get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("Get unexpected null", K(ret), K(get_stmt()));
  } else {
    ObOrderDirection direction = default_asc_direction();
    if (get_stmt()->get_order_item_size() > 0) {
      direction = get_stmt()->get_order_item(0).order_type_;
    } else { /* Do nothing */ }
    int64_t N = exprs.count();
    for (int64_t i = 0; OB_SUCC(ret) && i < N; ++i) {
      OrderItem key;
      key.expr_ = exprs.at(i);
      key.order_type_ = direction;
      ret = items.push_back(key);
    }
  }
  return ret;
}

int ObLogPlan::make_order_items(const ObIArray<ObRawExpr *> &exprs,
                                const ObIArray<ObOrderDirection> &dirs,
                                ObIArray<OrderItem> &items)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(exprs.count() != dirs.count())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("expr and dir count not match", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < exprs.count(); ++i) {
      OrderItem key;
      if (OB_ISNULL(exprs.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret), K(exprs.at(i)));
      } else if (exprs.at(i)->is_const_expr()) {
      //do nothing
      } else {
        key.expr_ = exprs.at(i);
        key.order_type_ = dirs.at(i);
        if (OB_FAIL(items.push_back(key))) {
          LOG_WARN("Failed to push array", K(ret));
        }
      }
    }
  }
  return ret;
}

int ObLogPlan::get_order_by_topn_expr(int64_t input_card,
                                      ObRawExpr *&topn_expr,
                                      bool &is_fetch_with_ties,
                                      bool &need_limit)
{
  int ret = OB_SUCCESS;
  int64_t limit_count = 0;
  int64_t limit_offset = 0;
  const ObDMLStmt *stmt = NULL;
  bool is_null_value = false;
  need_limit = true;
  topn_expr = NULL;
  is_fetch_with_ties = false;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(stmt), K(ret));
  } else if (!get_stmt()->has_limit()) {
    need_limit = false;
  } else if (get_stmt()->is_calc_found_rows() ||
             NULL == get_stmt()->get_limit_expr() ||
             NULL != get_stmt()->get_limit_percent_expr()) {
    need_limit = true;
  } else if (OB_FAIL(ObTransformUtils::get_limit_value(stmt->get_limit_expr(),
                                                       get_optimizer_context().get_params(),
                                                       get_optimizer_context().get_exec_ctx(),
                                                       &get_optimizer_context().get_allocator(),
                                                       limit_count,
                                                       is_null_value))) {
    LOG_WARN("failed to get limit value", K(ret));
  } else if (!is_null_value &&
             OB_FAIL(ObTransformUtils::get_limit_value(stmt->get_offset_expr(),
                                                       get_optimizer_context().get_params(),
                                                       get_optimizer_context().get_exec_ctx(),
                                                       &get_optimizer_context().get_allocator(),
                                                       limit_offset,
                                                       is_null_value))) {
    LOG_WARN("failed to get limit value", K(ret));
  } else {
    if (NULL != stmt->get_offset_expr()) {
      if (OB_FAIL(ObTransformUtils::make_pushdown_limit_count(
                                            get_optimizer_context().get_expr_factory(),
                                            *get_optimizer_context().get_session_info(),
                                            stmt->get_limit_expr(),
                                            stmt->get_offset_expr(),
                                            topn_expr))) {
        LOG_WARN("failed to make push down limit count", K(ret));
      } else if (OB_ISNULL(topn_expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else {
        need_limit = true;
        is_fetch_with_ties = stmt->is_fetch_with_ties();
      }
    } else {
      topn_expr = stmt->get_limit_expr();
      is_fetch_with_ties = stmt->is_fetch_with_ties();
      need_limit = false;
    }
  }
  return ret;
}

int ObLogPlan::allocate_exchange_as_top(ObLogicalOperator *&top,
                                        const ObExchangeInfo &exch_info)
{
  int ret = OB_SUCCESS;
  ObLogExchange *producer = NULL;
  ObLogExchange *consumer = NULL;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_ISNULL(producer = static_cast<ObLogExchange*>(
                       get_log_op_factory().allocate(*this, LOG_EXCHANGE))) ||
             OB_ISNULL(consumer = static_cast<ObLogExchange*>(
                       get_log_op_factory().allocate(*this, LOG_EXCHANGE)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate sort for order by", K(producer), K(consumer), K(ret));
  } else {
    producer->set_child(ObLogicalOperator::first_child, top);
    consumer->set_child(ObLogicalOperator::first_child, producer);
    producer->set_to_producer();
    consumer->set_to_consumer();
    producer->set_sample_type(exch_info.sample_type_);
    if (OB_FAIL(producer->set_exchange_info(exch_info))) {
      LOG_WARN("failed to set exchange info", K(ret));
    } else if (OB_FAIL(producer->compute_property())) {
      LOG_WARN("failed to compute propery", K(ret));
    } else if (OB_FAIL(consumer->set_exchange_info(exch_info))) {
      LOG_WARN("failed to set exchange info", K(ret));
    } else if (OB_FAIL(consumer->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      top = consumer;
    }
  }
  return ret;
}

int ObLogPlan::allocate_stat_collector_as_top(ObLogicalOperator *&top,
                                              ObStatCollectorType stat_type,
                                              const ObIArray<OrderItem> &sort_keys,
                                              share::schema::ObPartitionLevel part_level)
{
  int ret = OB_SUCCESS;
  if (stat_type == SAMPLE_SORT) {
    ObLogStatCollector *stat_collector = NULL;
    if (OB_ISNULL(top)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(top), K(ret));
    } else if (OB_ISNULL(stat_collector =
        static_cast<ObLogStatCollector*>(get_log_op_factory().allocate(*this, LOG_STAT_COLLECTOR)))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_ERROR("failed to allocate sort for order by", K(ret));
    } else {
      stat_collector->set_child(ObLogicalOperator::first_child, top);
      stat_collector->set_is_none_partition(PARTITION_LEVEL_ZERO == part_level);
      stat_collector->set_stat_collector_type(stat_type);
      if (OB_FAIL(stat_collector->set_sort_keys(sort_keys))) {
        LOG_WARN("failed to set sort keys", K(ret));
      } else if (OB_FAIL(stat_collector->compute_property())) {
        LOG_WARN("failed to compute property", K(ret));
      } else {
        top = stat_collector;
      }
    }
  } else {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("not supported stat type", K(ret));
  }
  return ret;
}

/**
 * 检查当前枚举的join order是否满足leading hint要求
 * match hint是否受leading hint控制
 * is_legal是否与leading hint冲突
 */
int ObLogPlan::check_join_hint(const ObRelIds &left_set,
                              const ObRelIds &right_set,
                              bool &match_hint,
                              bool &is_legal,
                              bool &is_strict_order)
{
  int ret = OB_SUCCESS;
  const ObRelIds &leading_tables = get_leading_tables();
  if (!left_set.overlap(leading_tables) && !right_set.overlap(leading_tables)) {
    //没有涉及leading hint的表,不需要额外的检查
    match_hint = false;
    is_legal = true;
    is_strict_order = true;
  } else if (left_set.is_subset(leading_tables) && right_set.is_subset(leading_tables)) {
    //正在枚举leading hint内部表
    bool found = false;
    //查找是否有满足的hint
    ObIArray<LeadingInfo> &leading_infos = log_plan_hint_.join_order_.leading_infos_;
    for (int64_t i = 0; !found && i < leading_infos.count(); ++i) {
      const LeadingInfo &info = leading_infos.at(i);
      if (left_set.equal(info.left_table_set_) && right_set.equal(info.right_table_set_)) {
        is_strict_order = true;
        found = true;
      } else if (right_set.equal(info.left_table_set_) && left_set.equal(info.right_table_set_)) {
        is_strict_order = false;
        found = true;
      }
    }
    if (!found) {
      //枚举的join order尝试打乱leading hint
      is_legal = false;
    } else {
      match_hint = true;
      is_legal = true;
    }
  } else if (leading_tables.is_subset(left_set)) {
    //处理完所有leading hint表之后的枚举过程
    match_hint = true;
    is_legal = true;
    is_strict_order = true;
  } else {
    //使用部分leading hint的表,非法枚举
    is_legal = false;
  }
  return ret;
}

int ObLogPlan::allocate_scala_group_by_as_top(ObLogicalOperator *&top,
                                              const ObIArray<ObAggFunRawExpr*> &agg_items,
                                              const ObIArray<ObRawExpr*> &having_exprs,
                                              const bool from_pivot,
                                              const double origin_child_card)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr*, 1> dummy_group_by_exprs;
  ObSEArray<ObRawExpr*, 1> dummy_rollup_exprs;
  if (OB_FAIL(allocate_group_by_as_top(top,
                                       AggregateAlgo::SCALAR_AGGREGATE,
                                       dummy_group_by_exprs,
                                       dummy_rollup_exprs,
                                       agg_items,
                                       having_exprs,
                                       from_pivot,
                                       1.0,
                                       origin_child_card))) {
    LOG_WARN("failed to allocate group by as top", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::allocate_group_by_as_top(ObLogicalOperator *&top,
                                        const AggregateAlgo algo,
                                        const ObIArray<ObRawExpr*> &group_by_exprs,
                                        const ObIArray<ObRawExpr*> &rollup_exprs,
                                        const ObIArray<ObAggFunRawExpr*> &agg_items,
                                        const ObIArray<ObRawExpr*> &having_exprs,
                                        const bool from_pivot,
                                        const double total_ndv,
                                        const double origin_child_card,
                                        const bool is_partition_wise,
                                        const bool is_push_down,
                                        const bool is_partition_gi,
                                        const ObRollupStatus rollup_status)
{
  int ret = OB_SUCCESS;
  ObLogGroupBy *group_by = NULL;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(top));
  } else if (OB_ISNULL(group_by = static_cast<ObLogGroupBy*>(
                       get_log_op_factory().allocate(*this, LOG_GROUP_BY)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate group by operator", K(ret));
  } else {
    group_by->set_child(ObLogicalOperator::first_child, top);
    group_by->set_algo_type(algo);
    group_by->set_from_pivot(from_pivot);
    group_by->set_push_down(is_push_down);
    group_by->set_partition_gi(is_partition_gi);
    group_by->set_total_ndv(total_ndv);
    group_by->set_origin_child_card(origin_child_card);
    group_by->set_rollup_status(rollup_status);
    group_by->set_is_partition_wise(is_partition_wise);
    group_by->set_force_push_down(FORCE_GPD & get_optimizer_context().get_aggregation_optimization_settings());
    if (OB_FAIL(group_by->set_group_by_exprs(group_by_exprs))) {
      LOG_WARN("failed to set group by columns", K(ret));
    } else if (OB_FAIL(group_by->set_rollup_exprs(rollup_exprs))) {
      LOG_WARN("failed to set rollup columns", K(ret));
    } else if (OB_FAIL(group_by->set_aggr_exprs(agg_items))) {
      LOG_WARN("failed to set aggregation exprs", K(ret));
    } else if (OB_FAIL(group_by->get_filter_exprs().assign(having_exprs))) {
      LOG_WARN("failed to set filter exprs", K(ret));
    } else if (OB_FAIL(group_by->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      top = group_by;
    }
  }
  return ret;
}

int ObLogPlan::allocate_sort_and_exchange_as_top(ObLogicalOperator *&top,
                                                 ObExchangeInfo &exch_info,
                                                 const ObIArray<OrderItem> &sort_keys,
                                                 const bool need_sort,
                                                 const int64_t prefix_pos,
                                                 const bool is_local_order,
                                                 ObRawExpr *topn_expr,
                                                 bool is_fetch_with_ties,
O
obdev 已提交
8064
                                                 OrderItem *hash_sortkey)
W
wangzelin.wzl 已提交
8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (exch_info.is_pq_local() && NULL == topn_expr && GCONF._enable_px_ordered_coord) {
    if (OB_FAIL(allocate_dist_range_sort_as_top(top, sort_keys, need_sort, is_local_order))) {
      LOG_WARN("failed to allocate dist range sort as top", K(ret));
    } else { /*do nothing*/ }
  } else {
    // allocate push down limit if necessary
    if (NULL != topn_expr && !need_sort) {
      bool is_pushed = false;
      if (!is_fetch_with_ties &&
          OB_FAIL(try_push_limit_into_table_scan(top, topn_expr, topn_expr, NULL, is_pushed))) {
        LOG_WARN("failed to push limit into table scan", K(ret));
      } else if (!is_local_order && (!is_pushed || top->is_distributed()) &&
                 OB_FAIL(allocate_limit_as_top(top,
                                               topn_expr,
                                               NULL,
                                               NULL,
                                               false,
                                               false,
                                               is_fetch_with_ties,
                                               &sort_keys))) {
        LOG_WARN("failed to allocate limit as top", K(ret));
      } else { /*do nothing*/ }
    }

    // allocate push down sort if necessary
    if ((exch_info.is_pq_local() || !exch_info.need_exchange()) && !sort_keys.empty() &&
        (need_sort || is_local_order)) {
      int64_t real_prefix_pos = need_sort && !is_local_order ? prefix_pos : 0;
      bool real_local_order = need_sort ? false : is_local_order;
      if (OB_FAIL(allocate_sort_as_top(top,
                                       sort_keys,
                                       real_prefix_pos,
                                       real_local_order,
                                       topn_expr,
                                       is_fetch_with_ties,
O
obdev 已提交
8105
                                       hash_sortkey))) {
W
wangzelin.wzl 已提交
8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117
        LOG_WARN("failed to allocate sort as top", K(ret));
      } else if (OB_ISNULL(top)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else { /*do nothing*/ }
    }

    // allocate exchange if necessary
    if (OB_SUCC(ret) && exch_info.need_exchange()) {
      if (!sort_keys.empty() &&
         (top->is_distributed() || is_local_order) &&
         (!need_sort || exch_info.is_pq_local())) {
O
obdev 已提交
8118 8119 8120 8121 8122 8123 8124 8125 8126 8127
        if (hash_sortkey != NULL) {
          if (OB_FAIL(exch_info.sort_keys_.push_back(*hash_sortkey))) {
            LOG_WARN("failed to add hash sort key", K(ret));
          }
          for (int64_t i = 0; OB_SUCC(ret) && i < sort_keys.count(); ++i) {
            if (OB_FAIL(exch_info.sort_keys_.push_back(sort_keys.at(i)))) {
              LOG_WARN("failed to add sort key", K(ret));
            }
          }
        } else if (OB_FAIL(exch_info.sort_keys_.assign(sort_keys))) {
W
wangzelin.wzl 已提交
8128
          LOG_WARN("failed to allocate sort keys", K(ret));
O
obdev 已提交
8129 8130
        }
        if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156
          exch_info.is_merge_sort_ = true;
          if (exch_info.is_pq_local()) {
            exch_info.is_sort_local_order_ = false;
          } else {
            exch_info.is_sort_local_order_ = is_local_order;
          }
        }
      }
      if (OB_FAIL(ret)) {
        /*do nothing*/
      } else if (OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
        LOG_WARN("failed to allocate exchange as top", K(ret));
      } else { /*do nothing*/ }
    }

    // allocate final sort if necessary
    if (OB_SUCC(ret) && need_sort && !sort_keys.empty() &&
        exch_info.need_exchange() && !exch_info.is_pq_local()) {
      int64_t real_prefix_pos = 0;
      bool real_local_order = false;
      if (OB_FAIL(allocate_sort_as_top(top,
                                       sort_keys,
                                       real_prefix_pos,
                                       real_local_order,
                                       NULL,
                                       false,
O
obdev 已提交
8157
                                       hash_sortkey))) {
W
wangzelin.wzl 已提交
8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227
        LOG_WARN("failed to allocate sort as top", K(ret));
      } else { /*do nothing*/ }
    }

    // allocate final limit if necessary
    if (OB_SUCC(ret) && NULL != topn_expr && exch_info.is_pq_local()) {
      if (OB_FAIL(allocate_limit_as_top(top,
                                        topn_expr,
                                        NULL,
                                        NULL,
                                        false,
                                        false,
                                        is_fetch_with_ties,
                                        &sort_keys))) {
        LOG_WARN("failed to allocate limit as top", K(ret));
      } else { /*do nothing*/ }
    }
  }
  return ret;
}

int ObLogPlan::allocate_dist_range_sort_as_top(ObLogicalOperator *&top,
                                               const ObIArray<OrderItem> &sort_keys,
                                               const bool need_sort,
                                               const bool is_local_order)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else {
    // allocate range exchange info
    ObExchangeInfo range_exch_info;
    range_exch_info.dist_method_ = ObPQDistributeMethod::RANGE;
    range_exch_info.sample_type_ = HEADER_INPUT_SAMPLE;
    if (OB_FAIL(range_exch_info.sort_keys_.assign(sort_keys))) {
      LOG_WARN("failed to assign sort keys", K(ret));
    } else if (OB_FAIL(allocate_exchange_as_top(top, range_exch_info))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    }

    // allocate sort
    if (OB_SUCC(ret)) {
      bool prefix_pos = 0;
      bool is_local_merge_sort = !need_sort && is_local_order;
      if (OB_FAIL(allocate_sort_as_top(top, sort_keys, prefix_pos, is_local_merge_sort))) {
        LOG_WARN("failed to allocate sort as top", K(ret));
      } else { /*do nothing*/ }
    }
    // allocate final exchange
    if (OB_SUCC(ret)) {
      ObExchangeInfo temp_exch_info;
      temp_exch_info.is_task_order_ = true;
      if (OB_FAIL(temp_exch_info.sort_keys_.assign(sort_keys))) {
        LOG_WARN("failed to assign sort keys", K(ret));
      } else if (OB_FAIL(allocate_exchange_as_top(top, temp_exch_info))) {
        LOG_WARN("failed to allocate exchange as top", K(ret));
      } else { /*do nothing*/ }
    }
  }
  return ret;
}

int ObLogPlan::try_allocate_sort_as_top(ObLogicalOperator *&top,
                                        const ObIArray<OrderItem> &sort_keys,
                                        const bool need_sort,
                                        const int64_t prefix_pos,
                                        const int64_t part_cnt)
{
  int ret = OB_SUCCESS;
O
obdev 已提交
8228
  OrderItem hash_sortkey;
W
wangzelin.wzl 已提交
8229 8230 8231
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
O
obdev 已提交
8232 8233 8234
  } else if (need_sort && part_cnt > 0 &&
            OB_FAIL(create_hash_sortkey(part_cnt, sort_keys, hash_sortkey))) {
    LOG_WARN("failed to create hash sort key", K(ret), K(part_cnt), K(sort_keys));
W
wangzelin.wzl 已提交
8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247
  } else {
    bool is_local_order = top->get_is_local_order()
        && (top->is_single() || (top->is_distributed() && top->is_exchange_allocated()));
    ObExchangeInfo exch_info;
    exch_info.dist_method_ = ObPQDistributeMethod::NONE;
    if (OB_FAIL(allocate_sort_and_exchange_as_top(top,
                                                  exch_info,
                                                  sort_keys,
                                                  need_sort,
                                                  prefix_pos,
                                                  is_local_order,
                                                  NULL,
                                                  false,
O
obdev 已提交
8248
                                                  (need_sort && part_cnt > 0) ? &hash_sortkey : NULL))) {
W
wangzelin.wzl 已提交
8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::allocate_sort_as_top(ObLogicalOperator *&top,
                                    const ObIArray<OrderItem> &sort_keys,
                                    const int64_t prefix_pos,
                                    const bool is_local_merge_sort,
                                    ObRawExpr *topn_expr,
                                    bool is_fetch_with_ties,
O
obdev 已提交
8261
                                    OrderItem *hash_sortkey)
W
wangzelin.wzl 已提交
8262 8263 8264
{
  int ret = OB_SUCCESS;
  ObLogSort *sort = NULL;
O
obdev 已提交
8265
  int64_t part_cnt = 0;
W
wangzelin.wzl 已提交
8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(top), K(ret));
  } else if (OB_ISNULL(sort = static_cast<ObLogSort*>(get_log_op_factory().allocate(*this, LOG_SORT)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate sort for order by", K(ret));
  } else {
    sort->set_child(ObLogicalOperator::first_child, top);
    sort->set_prefix_pos(prefix_pos);
    sort->set_local_merge_sort(is_local_merge_sort);
    sort->set_topn_expr(topn_expr);
    sort->set_fetch_with_ties(is_fetch_with_ties);
O
obdev 已提交
8278 8279 8280 8281 8282
    if (hash_sortkey != NULL &&
        hash_sortkey->expr_ != NULL &&
        hash_sortkey->expr_->get_expr_type() == T_FUN_SYS_HASH) {
      part_cnt = hash_sortkey->expr_->get_children_count();
    }
W
wangzelin.wzl 已提交
8283 8284 8285 8286
    sort->set_part_cnt(part_cnt);

    if (OB_FAIL(sort->set_sort_keys(sort_keys))) {
      LOG_WARN("failed to set sort keys", K(ret));
O
obdev 已提交
8287
    } else if (part_cnt > 0 && FALSE_IT(sort->set_hash_sortkey(*hash_sortkey))) {
W
wangzelin.wzl 已提交
8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481
    } else if (OB_FAIL(sort->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      top = sort;
    }
  }
  return ret;
}

/*
 * Limit clause will trigger a cost re-estimation phase based on a uniform distribution assumption.
 * For certain plans, this assumption may result in bad plans (https://aone.alibaba-inc.com/issue/18668063).
 * instead of choosing minimal-cost plans, we prefer more reliable plans.
 */
int ObLogPlan::candi_allocate_limit(const ObIArray<OrderItem> &order_items)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = NULL;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("get unexpected null", K(get_stmt()), K(ret));
  } else if (OB_FAIL(candi_allocate_limit(stmt->get_limit_expr(),
                                          stmt->get_offset_expr(),
                                          stmt->get_limit_percent_expr(),
                                          stmt->is_calc_found_rows(),
                                          stmt->has_top_limit(),
                                          stmt->is_fetch_with_ties(),
                                          &order_items))) {
    LOG_WARN("failed to allocate limit operator", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::candi_allocate_limit(ObRawExpr *limit_expr,
                                    ObRawExpr *offset_expr,
                                    ObRawExpr *percent_expr,
                                    const bool is_calc_found_rows,
                                    const bool is_top_limit,
                                    const bool is_fetch_with_ties,
                                    const ObIArray<OrderItem> *ties_ordering)
{
  int ret = OB_SUCCESS;
  ObRawExpr *pushed_expr = NULL;
  if (NULL != limit_expr &&
      OB_FAIL(ObTransformUtils::make_pushdown_limit_count(
                                       get_optimizer_context().get_expr_factory(),
                                       *get_optimizer_context().get_session_info(),
                                       limit_expr,
                                       offset_expr,
                                       pushed_expr))) {
    LOG_WARN("failed to make push down limit count", K(ret));
  } else {
    ObSEArray<CandidatePlan, 8> non_reliable_plans;
    ObSEArray<CandidatePlan, 8> reliable_plans;
    for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); ++i) {
      bool is_reliable = false;
      CandidatePlan &plain_plan = candidates_.candidate_plans_.at(i);
      if (OB_ISNULL(plain_plan.plan_tree_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(create_limit_plan(plain_plan.plan_tree_,
                                           limit_expr,
                                           pushed_expr,
                                           offset_expr,
                                           percent_expr,
                                           is_calc_found_rows,
                                           is_top_limit,
                                           is_fetch_with_ties,
                                           ties_ordering))) {
        LOG_WARN("failed to create limit plan", K(ret));
      } else if (NULL == percent_expr &&
                 OB_FAIL(is_plan_reliable(plain_plan.plan_tree_, is_reliable))) {
        LOG_WARN("failed to check plan is reliable", K(ret));
      } else if (is_reliable) {
        ret = reliable_plans.push_back(plain_plan);
      } else {
        ret = non_reliable_plans.push_back(plain_plan);
      }
    }
    if (OB_SUCC(ret)) {
      int64_t check_scope = OrderingCheckScope::NOT_CHECK;
      if (reliable_plans.empty() && OB_FAIL(reliable_plans.assign(non_reliable_plans))) {
        LOG_WARN("failed to assign plans", K(ret));
      } else if (OB_FAIL(update_plans_interesting_order_info(reliable_plans, check_scope))) {
        LOG_WARN("failed to update plans interesting order info", K(ret));
      } else if (OB_FAIL(prune_and_keep_best_plans(reliable_plans))) {
        LOG_WARN("failed to prune and keep best plans", K(ret));
      } else { /*do nothing*/ }
    }
  }
  return ret;
}

int ObLogPlan::create_limit_plan(ObLogicalOperator *&top,
                                 ObRawExpr *limit_expr,
                                 ObRawExpr *pushed_expr,
                                 ObRawExpr *offset_expr,
                                 ObRawExpr *percent_expr,
                                 const bool is_calc_found_rows,
                                 const bool is_top_limit,
                                 const bool is_fetch_with_ties,
                                 const ObIArray<OrderItem> *ties_ordering)
{
  int ret = OB_SUCCESS;
  ObExchangeInfo exch_info;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (NULL != percent_expr) {
    // for percent case
    if (top->is_distributed() && OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_ISNULL(top)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (LOG_MATERIAL != top->get_type() &&
              (LOG_SORT != top->get_type() || !top->is_block_op()) &&
               OB_FAIL(allocate_material_as_top(top))) {
      LOG_WARN("failed to allocate material as top", K(ret));
    } else if (OB_FAIL(allocate_limit_as_top(top,
                                             limit_expr,
                                             offset_expr,
                                             percent_expr,
                                             is_calc_found_rows,
                                             is_top_limit,
                                             is_fetch_with_ties,
                                             ties_ordering)) ) {
      LOG_WARN("failed to allocate limit as top", K(ret));
    } else { /*do nothing*/ }
  } else {
    bool is_pushed = false;
    // for normal limit-offset case
    if (NULL != limit_expr && !is_calc_found_rows && !is_fetch_with_ties &&
        OB_FAIL(try_push_limit_into_table_scan(top,
                                               limit_expr,
                                               pushed_expr,
                                               offset_expr,
                                               is_pushed))) {
      LOG_WARN("failed to push limit into table scan", K(ret));
    } else if (top->is_single() && is_pushed) {
      // pushed into table-scan
    } else if (top->is_distributed() && !is_calc_found_rows && NULL != pushed_expr &&
               OB_FAIL(allocate_limit_as_top(top,
                                             pushed_expr,
                                             NULL,
                                             NULL,
                                             false,
                                             false,
                                             false,
                                             NULL))) {
      LOG_WARN("failed to allocate limit as top", K(ret));
    } else if (top->is_distributed() &&
               OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_FAIL(allocate_limit_as_top(top,
                                             limit_expr,
                                             offset_expr,
                                             percent_expr,
                                             is_calc_found_rows,
                                             is_top_limit,
                                             is_fetch_with_ties,
                                             ties_ordering))) {
      LOG_WARN("failed to allocate limit as top", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::try_push_limit_into_table_scan(ObLogicalOperator *top,
                                              ObRawExpr *limit_expr,
                                              ObRawExpr *pushed_expr,
                                              ObRawExpr *offset_expr,
                                              bool &is_pushed)
{
  int ret = OB_SUCCESS;
  is_pushed = false;
  if (OB_ISNULL(top) || OB_ISNULL(limit_expr) || OB_ISNULL(pushed_expr) || OB_ISNULL(get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(top), K(limit_expr), K(get_stmt()), K(ret));
  } else if (log_op_def::LOG_TABLE_SCAN == top->get_type()) {
    ObLogTableScan *table_scan = static_cast<ObLogTableScan *>(top);
    ObRawExpr *new_limit_expr = NULL;
    ObRawExpr *new_offset_expr = NULL;

    bool contain_udf = false;
    common::ObIArray<ObRawExpr *> &filters = table_scan->get_filter_exprs();
    for(int i = 0; OB_SUCC(ret) && !contain_udf && i < filters.count(); i++) {
      if(OB_ISNULL(filters.at(i))) {
        //do nothing
      } else if(filters.at(i)->has_flag(ObExprInfoFlag::CNT_PL_UDF)) {
        contain_udf = true;
      }
    }

O
obdev 已提交
8482 8483
    if (OB_SUCC(ret) && !contain_udf && !is_virtual_table(table_scan->get_ref_table_id()) &&
        !(OB_INVALID_ID != table_scan->get_dblink_id() && NULL != offset_expr) &&
W
wangzelin.wzl 已提交
8484
        !get_stmt()->is_calc_found_rows() && !table_scan->is_sample_scan() &&
O
obdev 已提交
8485
        !(table_scan->get_is_index_global() && table_scan->get_index_back() && table_scan->has_index_lookup_filter()) &&
W
wangzelin.wzl 已提交
8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647
        (NULL == table_scan->get_limit_expr() ||
         ObOptimizerUtil::is_point_based_sub_expr(limit_expr, table_scan->get_limit_expr()))) {
      if (!top->is_distributed()) {
        new_limit_expr = limit_expr;
        new_offset_expr = offset_expr;
      } else {
        new_limit_expr = pushed_expr;
      }
      if (OB_FAIL(table_scan->set_limit_offset(new_limit_expr, new_offset_expr))) {
        LOG_WARN("failed to set limit-offset", K(ret));
      } else {
        is_pushed = true;
      }
    }
  } else { /*do nothing*/ }
  return ret;
}

/*
 * A plan is reliable if it does not make any uniform assumption during the cost re-estimation phase.
 * In other words, it should satisfy the following two requirements:
 * 1 no operator in the plan has more than 1 children
 * 2 all operators in the plan is pipelinable and does not have any filters.
 */
int ObLogPlan::is_plan_reliable(const ObLogicalOperator *root,
                                bool &is_reliable)
{
  int ret = OB_SUCCESS;
  is_reliable = false;
  if (OB_ISNULL(root)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(ret));
  } else if (log_op_def::LOG_TABLE_SCAN == root->get_type()) {
    const ObCostTableScanInfo *cost_info = static_cast<const ObLogTableScan*>(root)->get_est_cost_info();
    if (OB_ISNULL(cost_info)) {
      /* cost_info could be null if limit has been pushed down into cte table scan */
      is_reliable = false;
    } else {
      is_reliable = cost_info->table_filters_.empty() && cost_info->postfix_filters_.empty();
    }
  } else if (root->get_filter_exprs().count() == 0 && !root->is_block_op()) {
    is_reliable = true;
  } else {
    is_reliable = false;
  }
  if (OB_SUCC(ret) && is_reliable) {
    bool is_child_reliable = false;
    if (root->get_num_of_child() > 1) {
      is_reliable = false;
    } else if (root->get_num_of_child() == 0) {
      is_reliable = true;
    } else if (OB_ISNULL(root->get_child(0))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(is_plan_reliable(root->get_child(0),
                                        is_child_reliable))) {
      LOG_WARN("failed to check plan is reliable", K(ret));
    } else {
      is_reliable &= is_child_reliable;
    }
  }
  if (OB_SUCC(ret)) {
    LOG_TRACE("succeed to check plan is reliable", K(is_reliable), K(root));
  }
  return ret;
}

int ObLogPlan::allocate_limit_as_top(ObLogicalOperator *&old_top,
                                     ObRawExpr *limit_expr,
                                     ObRawExpr *offset_expr,
                                     ObRawExpr *percent_expr,
                                     const bool is_calc_found_rows,
                                     const bool is_top_limit,
                                     const bool is_fetch_with_ties,
                                     const ObIArray<OrderItem> *ties_ordering)
{
  int ret = OB_SUCCESS;
  ObLogLimit *limit = NULL;
  if (OB_ISNULL(old_top) || OB_ISNULL(get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("get unexpected null", K(old_top), K(get_stmt()), K(ret));
  } else if (log_op_def::LOG_LIMIT == old_top->get_type() &&
             ObOptimizerUtil::is_point_based_sub_expr(limit_expr,
                   static_cast<ObLogLimit*>(old_top)->get_limit_expr())) {
    limit = static_cast<ObLogLimit*>(old_top);
    limit->set_limit_expr(limit_expr);
    limit->set_offset_expr(offset_expr);
    limit->set_percent_expr(percent_expr);
    limit->set_is_calc_found_rows(is_calc_found_rows);
    limit->set_top_limit(is_top_limit);
    limit->set_fetch_with_ties(is_fetch_with_ties);
    if (OB_FAIL(limit->est_cost())) {
      LOG_WARN("failed to estimate cost", K(ret));
    } else { /*do nothing*/ }
  } else if (OB_ISNULL(limit = static_cast<ObLogLimit *>
                               (get_log_op_factory().allocate(*this, LOG_LIMIT)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate memory for limit op", K(ret));
  } else {
    limit->set_limit_expr(limit_expr);
    limit->set_offset_expr(offset_expr);
    limit->set_percent_expr(percent_expr);
    limit->set_child(ObLogicalOperator::first_child, old_top);
    limit->set_is_calc_found_rows(is_calc_found_rows);
    limit->set_top_limit(is_top_limit);
    limit->set_fetch_with_ties(is_fetch_with_ties);
    //支持with ties功能,需要保存对应的order items,由于存在order by会保存在expected_ordering中,所以直接共用
    //但是直接将get_order_items()放入到expected ordering是不对的,可能会导致在分布式计划中多生成一个sort算子,
    //因此需要按照设置order by item方式设置, 这里主要是防止后续消除order by语义. order by的SORT可能不需要分配
    if (NULL != ties_ordering && is_fetch_with_ties &&
        OB_FAIL(limit->set_ties_ordering(*ties_ordering))) {
      LOG_WARN("failed to set ties ordering", K(ret));
    } else if (OB_FAIL(limit->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      old_top = limit;
    }
  }
  return ret;
}

int ObLogPlan::candi_allocate_select_into()
{
  int ret = OB_SUCCESS;
  ObExchangeInfo exch_info;
  CandidatePlan candidate_plan;
  ObSEArray<CandidatePlan, 4> select_into_plans;
  for (int64_t i = 0 ; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); ++i) {
    candidate_plan = candidates_.candidate_plans_.at(i);
    if (OB_ISNULL(candidate_plan.plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (candidate_plan.plan_tree_->is_sharding() &&
               OB_FAIL((allocate_exchange_as_top(candidate_plan.plan_tree_, exch_info)))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_FAIL(allocate_select_into_as_top(candidate_plan.plan_tree_))) {
      LOG_WARN("failed to allocate select into", K(ret));
    } else if (OB_FAIL(select_into_plans.push_back(candidate_plan))) {
      LOG_WARN("failed to push back candidate plan", K(ret));
    } else { /*do nothing*/ }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(prune_and_keep_best_plans(select_into_plans))) {
      LOG_WARN("failed to prune and keep best plans", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::allocate_select_into_as_top(ObLogicalOperator *&old_top)
{
  int ret = OB_SUCCESS;
  ObLogSelectInto *select_into = NULL;
  const ObSelectStmt *stmt = static_cast<const ObSelectStmt *>(get_stmt());
  if (OB_ISNULL(old_top) || OB_ISNULL(get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("Get unexpected null", K(ret), K(old_top), K(get_stmt()));
  } else if (OB_ISNULL(select_into = static_cast<ObLogSelectInto *>(
                       get_log_op_factory().allocate(*this, LOG_SELECT_INTO)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("allocate memory for ObLogSelectInto failed", K(ret));
  } else {
Z
zzg19950727 已提交
8648 8649 8650
    ObSelectIntoItem *into_item = stmt->get_select_into();
    ObSEArray<ObRawExpr*, 4> select_exprs;
    ObRawExpr *to_outfile_expr = NULL;
W
wangzelin.wzl 已提交
8651 8652 8653
    if (OB_ISNULL(into_item)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("into item is null", K(ret));
Z
zzg19950727 已提交
8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669
    } else if (OB_FAIL(stmt->get_select_exprs(select_exprs))) {
      LOG_WARN("failed to get select exprs", K(ret));
    } else if (T_INTO_OUTFILE == into_item->into_type_ &&
               OB_FAIL(ObRawExprUtils::build_to_outfile_expr(
                                    get_optimizer_context().get_expr_factory(),
                                    get_optimizer_context().get_session_info(),
                                    into_item,
                                    select_exprs,
                                    to_outfile_expr))) {
      LOG_WARN("failed to build_to_outfile_expr", K(*into_item), K(ret));
    } else if (T_INTO_OUTFILE == into_item->into_type_ &&
               OB_FAIL(select_into->get_select_exprs().push_back(to_outfile_expr))) {
      LOG_WARN("failed to add into outfile expr", K(ret));
    } else if (T_INTO_OUTFILE != into_item->into_type_ &&
               OB_FAIL(select_into->get_select_exprs().assign(select_exprs))) {
      LOG_WARN("failed to get select exprs", K(ret));
W
wangzelin.wzl 已提交
8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738
    } else {
      select_into->set_into_type(into_item->into_type_);
      select_into->set_outfile_name(into_item->outfile_name_);
      select_into->set_filed_str(into_item->filed_str_);
      select_into->set_line_str(into_item->line_str_);
      select_into->set_user_vars(into_item->user_vars_);
      select_into->set_is_optional(into_item->is_optional_);
      select_into->set_closed_cht(into_item->closed_cht_);
      select_into->set_child(ObLogicalOperator::first_child, old_top);
      // compute property
      if (OB_FAIL(select_into->compute_property())) {
        LOG_WARN("failed to compute equal set", K(ret));
      } else {
        old_top = select_into;
      }
    }
  }
  return ret;
}

int ObLogPlan::candi_allocate_subplan_filter_for_where()
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr *, 4> filters;
  if (OB_FAIL(ObOptimizerUtil::get_subquery_exprs(get_subquery_filters(),
                                                  filters,
                                                  false))) {
    LOG_WARN("failed to get subquery exprs", K(ret));
  } else if (OB_FAIL(candi_allocate_subplan_filter(get_subquery_filters(),
                                                   filters.empty() ? NULL : &filters))) {
    LOG_WARN("failed to candi allocate subplan filter", K(ret));
  }
  return ret;
}

int ObLogPlan::candi_allocate_subplan_filter_for_exprs(ObIArray<ObRawExpr*> &exprs)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObQueryRefRawExpr*, 4> subqueries;
  ObSEArray<ObRawExpr*, 4> nested_subquery_exprs;
  if (OB_FAIL(ObTransformUtils::extract_query_ref_expr(exprs,
                                                       subqueries,
                                                       false))) {
    LOG_WARN("failed to extract query ref expr", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::get_nested_exprs(subqueries,
                                                       nested_subquery_exprs))) {
    LOG_WARN("failed to get nested subquery exprs", K(ret));
  } else if (!nested_subquery_exprs.empty() &&
             OB_FAIL(candi_allocate_subplan_filter(nested_subquery_exprs))) {
    LOG_WARN("failed to allocate subplan filter for order by exprs", K(ret));
  } else if (OB_FAIL(candi_allocate_subplan_filter(exprs))) {
    LOG_WARN("failed to allocate subplan filter for order by exprs", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::candi_allocate_subplan_filter(const ObIArray<ObRawExpr*> &subquery_exprs,
                                             const ObIArray<ObRawExpr *> *filters,
                                             const bool is_update_set,
                                             const bool for_on_condition)
{
  int ret = OB_SUCCESS;
  ObBitSet<> initplan_idxs;
  ObBitSet<> onetime_idxs;
  bool for_cursor_expr = false;
  ObSEArray<ObLogPlan*, 4> subplans;
  ObSEArray<ObQueryRefRawExpr *, 4> query_refs;
  ObSEArray<ObExecParamRawExpr *, 4> params;
  ObSEArray<ObExecParamRawExpr *, 4> onetime_exprs;
O
obdev 已提交
8739
  ObSEArray<ObRawExpr *, 4> new_filters;
W
wangzelin.wzl 已提交
8740 8741 8742 8743 8744 8745 8746 8747 8748 8749
  if (OB_FAIL(generate_subplan_filter_info(subquery_exprs,
                                           subplans,
                                           query_refs,
                                           params,
                                           onetime_exprs,
                                           initplan_idxs,
                                           onetime_idxs,
                                           for_cursor_expr,
                                           for_on_condition))) {
    LOG_WARN("failed to generated subplan filter info", K(ret));
O
obdev 已提交
8750 8751
  } else if (NULL != filters && OB_FAIL(adjust_exprs_with_onetime(*filters, new_filters))) {
    LOG_WARN("failed to transform filters with onetime", K(ret));
W
wangzelin.wzl 已提交
8752 8753
  } else if (subplans.empty()) {
    if (NULL != filters) {
O
obdev 已提交
8754
      if (OB_FAIL(candi_allocate_filter(new_filters))) {
W
wangzelin.wzl 已提交
8755 8756 8757 8758 8759 8760 8761 8762 8763 8764
        LOG_WARN("failed to allocate filter as top", K(ret));
      }
    }
  } else {
    if (OB_FAIL(inner_candi_allocate_subplan_filter(subplans,
                                                    query_refs,
                                                    params,
                                                    onetime_exprs,
                                                    initplan_idxs,
                                                    onetime_idxs,
O
obdev 已提交
8765
                                                    NULL == filters  ? NULL : &new_filters,
W
wangzelin.wzl 已提交
8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987
                                                    for_cursor_expr,
                                                    is_update_set))) {
      LOG_WARN("failed to allocate subplan filter", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::inner_candi_allocate_subplan_filter(ObIArray<ObLogPlan*> &subplans,
                                                   ObIArray<ObQueryRefRawExpr *> &query_refs,
                                                   ObIArray<ObExecParamRawExpr *> &params,
                                                   ObIArray<ObExecParamRawExpr *> &onetime_exprs,
                                                   ObBitSet<> &initplan_idxs,
                                                   ObBitSet<> &onetime_idxs,
                                                   const ObIArray<ObRawExpr *> *filters,
                                                   const bool for_cursor_expr,
                                                   const bool is_update_set)
{
  int ret = OB_SUCCESS;
  ObLogPlan *log_plan = NULL;
  const ObDMLStmt *stmt = NULL;
  CandidatePlan candidate_plan;
  ObSEArray<int64_t, 4> move_pos;
  ObSEArray<CandidatePlan, 4> temp_plans;
  ObSEArray<CandidatePlan, 4> dist_temp_plans;
  ObSEArray<CandidatePlan, 4> subquery_plans;
  ObSEArray<ObSEArray<CandidatePlan, 4>, 8> best_list;
  ObSEArray<ObSEArray<CandidatePlan, 4>, 8> dist_best_list;
  ObSEArray<ObLogicalOperator*, 4> child_ops;
  ObSEArray<ObLogicalOperator*, 4> dist_child_ops;
  ObExchangeInfo exch_info;
  // get best candidate list
  for (int64_t i = 0; OB_SUCC(ret) && i < subplans.count(); i++) {
    temp_plans.reuse();
    if (OB_ISNULL(subplans.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(get_minimal_cost_candidates(subplans.at(i)->get_candidate_plans().candidate_plans_,
                                                   temp_plans))) {
      LOG_WARN("failed to get minimal cost candidates", K(ret));
    } else if (OB_UNLIKELY(temp_plans.empty())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected error", K(ret));
    } else if (OB_FAIL(best_list.push_back(temp_plans))) {
      LOG_WARN("failed to push back temp plans", K(ret));
    } else {
      dist_temp_plans.reuse();
      for (int64_t j = 0; OB_SUCC(ret) && j < temp_plans.count(); j++) {
        candidate_plan = temp_plans.at(j);
        if (OB_ISNULL(candidate_plan.plan_tree_) ||
            OB_ISNULL(log_plan = candidate_plan.plan_tree_->get_plan()) ||
            OB_ISNULL(stmt = log_plan->get_stmt())) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(log_plan), K(stmt), K(ret));
        } else if (!candidate_plan.plan_tree_->is_sharding() ||
                   candidate_plan.plan_tree_->get_contains_fake_cte()) {
          /*do nothing*/
        } else if (OB_FAIL(log_plan->allocate_exchange_as_top(candidate_plan.plan_tree_, exch_info))) {
          LOG_WARN("failed to allocate exchange as top", K(ret));
        } else if (params.empty() && stmt->is_contains_assignment() &&
                   OB_FAIL(log_plan->allocate_material_as_top(candidate_plan.plan_tree_))) {
          LOG_WARN("failed to allocate material as top", K(ret));
        } else { /*do nothing*/ }

        if (OB_FAIL(ret)) {
          /*do nothing*/
        } else if (OB_FAIL(dist_temp_plans.push_back(candidate_plan))) {
          LOG_WARN("failed to push back temp plans", K(ret));
        } else { /*do nothing*/ }
      }
      if (OB_SUCC(ret)) {
        if (OB_FAIL(dist_best_list.push_back(dist_temp_plans))) {
          LOG_WARN("failed to push back plan list", K(ret));
        } else { /*do nothing*/ }
      }
    }
  }
  // generate subplan filter
  for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); i++) {
    candidate_plan = candidates_.candidate_plans_.at(i);
    if (OB_ISNULL(candidate_plan.plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(candidate_plan.plan_tree_), K(ret));
    } else {
      bool has_next = true;
      move_pos.reuse();
      for (int64_t j = 0; OB_SUCC(ret) && j < best_list.count(); j++) {
        ret = move_pos.push_back(0);
      }
      // get child ops to generate plan
      while (OB_SUCC(ret) && has_next) {
        child_ops.reuse();
        dist_child_ops.reuse();
        // get child ops to generate plan
        for (int64_t j = 0; OB_SUCC(ret) && j < move_pos.count(); j++) {
          int64_t size = best_list.at(j).count();
          if (OB_UNLIKELY(move_pos.at(j) < 0 || move_pos.at(j) >= size)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("get unexpected array count", K(size), K(move_pos.at(i)), K(ret));
          } else if (OB_FAIL(child_ops.push_back(best_list.at(j).at(move_pos.at(j)).plan_tree_))) {
            LOG_WARN("failed to push back child ops", K(ret));
          } else if (OB_FAIL(dist_child_ops.push_back(dist_best_list.at(j).at(move_pos.at(j)).plan_tree_))) {
            LOG_WARN("failed to push back child ops", K(ret));
          } else { /*do nothing*/ }
        }
        // create subplan filter plan
        if (OB_SUCC(ret)) {
          CandidatePlan curr_candidate_plan;
          curr_candidate_plan.plan_tree_ = candidate_plan.plan_tree_;
          if (OB_FAIL(create_subplan_filter_plan(curr_candidate_plan.plan_tree_,
                                                 child_ops,
                                                 dist_child_ops,
                                                 query_refs,
                                                 params,
                                                 onetime_exprs,
                                                 initplan_idxs,
                                                 onetime_idxs,
                                                 for_cursor_expr,
                                                 filters,
                                                 is_update_set))) {
            LOG_WARN("failed to create subplan filter plan", K(ret));
          } else if (OB_FAIL(subquery_plans.push_back(curr_candidate_plan))) {
            LOG_WARN("failed to push back subquery plans", K(ret));
          } else { /*do nothing*/ }
        }
        // reset pos for next generation
        if (OB_SUCC(ret)) {
          has_next = false;
          for (int64_t j = move_pos.count() - 1; OB_SUCC(ret) && j >= 0; j--) {
            if (move_pos.at(j) < best_list.at(j).count() - 1) {
              ++move_pos.at(j);
              has_next = true;
              for (int64_t k = j + 1; k < move_pos.count(); k++) {
                move_pos.at(k) = 0;
              }
            }
          }
        }
      }
    }
  }
  if (OB_FAIL(ret)) {
    /*do nothing*/
  } else if (OB_FAIL(prune_and_keep_best_plans(subquery_plans))) {
    LOG_WARN("failed to prune and keep best plans", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

/*
 * @param for_on_condition
 *   The subquery on the on condition will try to generate the subplan filter multiple times
 *   when generating the plan, and the subquery on the on condition does not have a shared subquery,
 *   so when generating the subplan filter, the subplan only needs to be generated once,
 *   and when generating the subplan filter operator generated subplans do not need to be ignored.
 */
int ObLogPlan::generate_subplan_filter_info(const ObIArray<ObRawExpr *> &subquery_exprs,
                                            ObIArray<ObLogPlan *> &subplans,
                                            ObIArray<ObQueryRefRawExpr *> &query_refs,
                                            ObIArray<ObExecParamRawExpr *> &exec_params,
                                            ObIArray<ObExecParamRawExpr *> &onetime_exprs,
                                            ObBitSet<> &initplan_idxs,
                                            ObBitSet<> &onetime_idxs,
                                            bool &for_cursor_expr,
                                            bool for_on_condition)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObQueryRefRawExpr *, 4> candi_query_refs;
  ObSEArray<ObQueryRefRawExpr *, 4> onetime_query_refs;
  ObSEArray<ObQueryRefRawExpr *, 4> tmp;
  int64_t idx = 0;
  for (int64_t i = 0; OB_SUCC(ret) && i < subquery_exprs.count(); ++i) {
    tmp.reuse();
    if (OB_FAIL(ObTransformUtils::extract_query_ref_expr(subquery_exprs.at(i),
                                                         candi_query_refs,
                                                         false))) {
      LOG_WARN("failed to extract query ref exprs", K(ret));
    } else if (OB_FAIL(extract_onetime_exprs(subquery_exprs.at(i),
                                             onetime_exprs,
                                             tmp,
                                             for_on_condition))) {
      LOG_WARN("failed to extract onetime exprs", K(ret));
    } else if (OB_FAIL(append(onetime_query_refs, tmp))) {
      LOG_WARN("failed to append onetime query refs", K(ret));
    } else if (OB_FAIL(append(candi_query_refs, tmp))) {
      LOG_WARN("failed to append query refs", K(ret));
    }
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < candi_query_refs.count(); ++i) {
    SubPlanInfo *info = NULL;
    if (OB_FAIL(get_subplan(candi_query_refs.at(i), info))) {
      LOG_WARN("failed to get subplan", K(ret));
    } else if (NULL != info && !for_on_condition) {
      // do nothing
    } else if (OB_FAIL(append(exec_params, candi_query_refs.at(i)->get_exec_params()))) {
      LOG_WARN("failed to append exec params", K(ret));
    } else if (NULL == info &&
               OB_FAIL(generate_subplan_for_query_ref(candi_query_refs.at(i), info))) {
      LOG_WARN("failed to generate subplan for query ref", K(ret));
    } else if (OB_FAIL(subplans.push_back(info->subplan_))) {
      LOG_WARN("failed to push back subplan", K(ret));
    } else if (OB_FAIL(query_refs.push_back(candi_query_refs.at(i)))) {
      LOG_WARN("failed to push back query ref expr", K(ret));
    } else {
      ++ idx;
      for_cursor_expr = for_cursor_expr || candi_query_refs.at(i)->is_cursor();
      if (info->init_plan_) {
        if (ObOptimizerUtil::find_item(onetime_query_refs, candi_query_refs.at(i))) {
          if (OB_FAIL(onetime_idxs.add_member(idx))) {
            LOG_WARN("failed to add onetime query ref index", K(ret));
          }
        } else {
          if (OB_FAIL(initplan_idxs.add_member(idx))) {
            LOG_WARN("failed to add onetime query ref index", K(ret));
          }
        }
      }
    }
  }
  return ret;
}

O
obdev 已提交
8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053
int ObLogPlan::adjust_expr_with_onetime(ObRawExpr *&expr)
{
  int ret = OB_SUCCESS;
  ObRawExpr *new_expr = NULL;
  ObSQLSessionInfo *session_info = NULL;
  if (OB_ISNULL(session_info = get_optimizer_context().get_session_info()) ||
      OB_ISNULL(onetime_copier_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(session_info), K(ret));
  } else if (OB_FAIL(onetime_copier_->copy_on_replace(expr, new_expr))) {
    LOG_WARN("failed to copy expr");
  } else if (OB_ISNULL(new_expr)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("expr is null", K(ret));
  } else if (new_expr == expr) {
    // do nothing
  } else if (OB_FAIL(new_expr->formalize(session_info))) {
    LOG_WARN("failed to formalize expr", K(ret));
  } else {
    expr = new_expr;
  }
  return ret;
}

int ObLogPlan::adjust_exprs_with_onetime(const ObIArray<ObRawExpr *> &exprs,
                                         ObIArray<ObRawExpr *> &new_exprs)
{
  int ret = OB_SUCCESS;
  ObSQLSessionInfo *session_info = NULL;
  if (0 == exprs.count()) {
    // do nothing
  } else if (OB_ISNULL(session_info = get_optimizer_context().get_session_info()) ||
             OB_ISNULL(onetime_copier_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(session_info), K(ret));
  } else if (OB_FAIL(onetime_copier_->copy_on_replace(exprs, new_exprs))) {
    LOG_WARN("failed to replace expr", K(ret));
  } else if (OB_UNLIKELY(exprs.count() != new_exprs.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("expr number mismatch", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < exprs.count(); ++i) {
    if (exprs.at(i) == new_exprs.at(i)) {
      // do nothing
    } else if (OB_FAIL(new_exprs.at(i)->formalize(session_info))) {
      LOG_WARN("failed to formalize expr", K(ret));
    }
  }
  return ret;
}

int ObLogPlan::adjust_exprs_with_onetime(ObIArray<ObRawExpr *> &exprs)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr *, 4> tmp_exprs;
  if (0 == exprs.count()) {
    // do nothing
  } else if (OB_FAIL(adjust_exprs_with_onetime(exprs, tmp_exprs))) {
    LOG_WARN("failed to adjust exprss with onetime", K(ret));
  } else if (OB_FAIL(exprs.assign(tmp_exprs))) {
    LOG_WARN("failed to assign exprs", K(ret));
  }
  return ret;
}


W
wangzelin.wzl 已提交
9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096
int ObLogPlan::create_subplan_filter_plan(ObLogicalOperator *&top,
                                          const ObIArray<ObLogicalOperator*> &subquery_ops,
                                          const ObIArray<ObLogicalOperator*> &dist_subquery_ops,
                                          const ObIArray<ObQueryRefRawExpr *> &query_ref_exprs,
                                          const ObIArray<ObExecParamRawExpr *> &params,
                                          const ObIArray<ObExecParamRawExpr *> &onetime_exprs,
                                          const ObBitSet<> &initplan_idxs,
                                          const ObBitSet<> &onetime_idxs,
                                          const bool for_cursor_expr,
                                          const ObIArray<ObRawExpr*> *filters,
                                          const bool is_update_set)
{
  int ret = OB_SUCCESS;
  bool is_basic = false;
  bool is_remote = false;
  bool is_recursive_cte = false;
  bool is_partition_wise = false;
  bool is_none_all = false;
  bool is_all_none = false;
  bool is_partition_none = false;
  ObSEArray<ObLogicalOperator*, 8> sf_childs;
  DistAlgo dist_algo = DistAlgo::DIST_INVALID_METHOD;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(sf_childs.push_back(top)) ||
             OB_FAIL(append(sf_childs, subquery_ops))) {
    LOG_WARN("failed to append child ops", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::check_basic_sharding_info(get_optimizer_context().get_local_server_addr(),
                                                                sf_childs,
                                                                is_basic,
                                                                is_remote))) {
    LOG_WARN("failed to check if match basic sharding info", K(ret));
  } else if ((!for_cursor_expr && is_basic) ||
             (for_cursor_expr && is_basic && !is_remote)) {
    dist_algo = DistAlgo::DIST_BASIC_METHOD;
  } else if (for_cursor_expr) {
    dist_algo = DistAlgo::DIST_PULL_TO_LOCAL;
  } else if (OB_FAIL(check_contains_recursive_cte(sf_childs,
                                                  is_recursive_cte))) {
    LOG_WARN("failed to check whether contains recursive cte", K(ret));
  } else if (is_recursive_cte) {
    dist_algo = DistAlgo::DIST_PULL_TO_LOCAL;
L
Larry955 已提交
9097 9098 9099
  } else if (!get_optimizer_context().is_var_assign_only_in_root_stmt() &&
              get_optimizer_context().has_var_assign()) {
    dist_algo = DistAlgo::DIST_PULL_TO_LOCAL;
W
wangzelin.wzl 已提交
9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365
  } else if (OB_FAIL(check_if_subplan_filter_match_partition_wise(top,
                                                                  subquery_ops,
                                                                  params,
                                                                  is_partition_wise))) {
    LOG_WARN("failed to check if match partition wise", K(ret));
  } else if (is_partition_wise) {
    dist_algo = DistAlgo::DIST_PARTITION_WISE;
  } else if (OB_FAIL(check_if_subplan_filter_match_repart(top,
                                                         subquery_ops,
                                                         params,
                                                         is_partition_none))) {
    LOG_WARN("failed to check if match repart", K(ret));
  } else if (is_partition_none) {
    dist_algo = DistAlgo::DIST_PARTITION_NONE;
  } else if (OB_FAIL(check_if_match_none_all(top,
                                             subquery_ops,
                                             is_none_all))) {
    LOG_WARN("failed to check if match none all", K(ret));
  } else if (is_none_all && onetime_idxs.is_empty()) {
    dist_algo = DistAlgo::DIST_NONE_ALL;
  } else {
    dist_algo = DistAlgo::DIST_PULL_TO_LOCAL;
  }
  if (OB_SUCC(ret)) {
    ObExchangeInfo exch_info;
    if (DistAlgo::DIST_BASIC_METHOD == dist_algo ||
        DistAlgo::DIST_PARTITION_WISE == dist_algo ||
        DistAlgo::DIST_NONE_ALL == dist_algo) {
      // is basic or is_partition_wise
      if (OB_FAIL(allocate_subplan_filter_as_top(top,
                                                 subquery_ops,
                                                 query_ref_exprs,
                                                 params,
                                                 onetime_exprs,
                                                 initplan_idxs,
                                                 onetime_idxs,
                                                 filters,
                                                 dist_algo,
                                                 is_update_set))) {
        LOG_WARN("failed to allocate subplan filter as top", K(ret));
      } else { /*do nothing*/ }
    } else if (DistAlgo::DIST_PARTITION_NONE == dist_algo) {
      if (OB_FAIL(compute_subplan_filter_repartition_distribution_info(top,
                                                                       subquery_ops,
                                                                       params,
                                                                       exch_info))) {
        LOG_WARN("failed to compute subplan filter distribution info", K(ret));
      } else if (OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
        LOG_WARN("failed to allocate exchange as top");
      } else if (OB_FAIL(allocate_subplan_filter_as_top(top,
                                                        subquery_ops,
                                                        query_ref_exprs,
                                                        params,
                                                        onetime_exprs,
                                                        initplan_idxs,
                                                        onetime_idxs,
                                                        filters,
                                                        dist_algo,
                                                        is_update_set))) {
        LOG_WARN("failed to allocate subplan filter as top", K(ret));
      } else { /*do nothing*/ }
    } else if (top->is_sharding() &&
               OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_FAIL(allocate_subplan_filter_as_top(top,
                                                      dist_subquery_ops,
                                                      query_ref_exprs,
                                                      params,
                                                      onetime_exprs,
                                                      initplan_idxs,
                                                      onetime_idxs,
                                                      filters,
                                                      dist_algo,
                                                      is_update_set))) {
      LOG_WARN("failed to allocate subplan filter as top", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::check_contains_recursive_cte(ObIArray<ObLogicalOperator*> &child_ops,
                                            bool &is_recursive_cte)
{
  int ret = OB_SUCCESS;
  is_recursive_cte = false;
  for (int64_t i = 0; OB_SUCC(ret) && !is_recursive_cte && i < child_ops.count(); i++) {
    if (OB_ISNULL(child_ops.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else {
      is_recursive_cte |= child_ops.at(i)->get_contains_fake_cte();
    }
  }
  return ret;
}

int ObLogPlan::init_subplan_filter_child_ops(const ObIArray<ObLogicalOperator*> &subquery_ops,
                                             const ObIArray<std::pair<int64_t, ObRawExpr*>> &params,
                                             ObIArray<ObLogicalOperator*> &dist_subquery_ops)
{
  int ret = OB_SUCCESS;
  ObExchangeInfo exch_info;
  for (int64 i = 0; OB_SUCC(ret) && i < subquery_ops.count(); i++) {
    bool need_rescan = false;
    ObLogicalOperator *child = NULL;
    if (OB_ISNULL(child = subquery_ops.at(i)) || OB_ISNULL(child->get_stmt())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (child->is_distributed() &&
               OB_FAIL(allocate_exchange_as_top(child, exch_info))) {
      LOG_WARN("failed to allocate exchange as top", K(ret));
    } else if (OB_ISNULL(child)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (params.empty() && child->get_stmt()->is_contains_assignment() &&
               OB_FAIL(child->check_exchange_rescan(need_rescan))) {
      LOG_WARN("failed to check exchange rescan", K(ret));
    } else if (need_rescan && OB_FAIL(allocate_material_as_top(child))) {
      LOG_WARN("failed to allocate material as top", K(ret));
    } else if (OB_ISNULL(child)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(dist_subquery_ops.push_back(child))) {
      LOG_WARN("failed to push back op", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::check_if_match_none_all(ObLogicalOperator *top,
                                       const ObIArray<ObLogicalOperator*> &child_ops,
                                       bool &is_none_all)
{
  int ret = OB_SUCCESS;
  is_none_all = true;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid top", K(ret));
  } else if (!top->is_distributed()) {
    is_none_all = false;
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && is_none_all && i < child_ops.count(); i ++) {
      ObLogicalOperator *child = child_ops.at(i);
      if (OB_ISNULL(child)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("invalid child", K(ret));
      } else if (!child->is_match_all()) {
        is_none_all = false;
      }
    }
  }
  return ret;
}

int ObLogPlan::check_if_subplan_filter_match_partition_wise(ObLogicalOperator *top,
                                                            const ObIArray<ObLogicalOperator*> &subquery_ops,
                                                            const ObIArray<ObExecParamRawExpr *> &params,
                                                            bool &is_partition_wise)
{
  int ret = OB_SUCCESS;
  EqualSets input_esets;
  is_partition_wise = false;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (!top->is_distributed()) {
    is_partition_wise = false;
  } else if (OB_FAIL(append(input_esets, top->get_output_equal_sets()))) {
    LOG_WARN("failed to append equal sets", K(ret));
  } else {
    ObLogicalOperator *child = NULL;
    ObSEArray<ObRawExpr*, 4> left_keys;
    ObSEArray<ObRawExpr*, 4> right_keys;
    ObSEArray<bool, 4> null_safe_info;
    is_partition_wise = true;
    for (int64_t i = 0; OB_SUCC(ret) && i < subquery_ops.count(); i++) {
      if (OB_ISNULL(child = subquery_ops.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(append(input_esets, child->get_output_equal_sets()))) {
        LOG_WARN("failed to append input equal sets", K(ret));
      } else { /*do nothing*/ }
    }
    for (int64_t i = 0; OB_SUCC(ret) && is_partition_wise && i < subquery_ops.count(); i++) {
      left_keys.reuse();
      right_keys.reuse();
      null_safe_info.reuse();
      if (OB_ISNULL(child = subquery_ops.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (!child->is_distributed() || child->is_exchange_allocated()) {
        is_partition_wise = false;
      } else if (OB_FAIL(get_subplan_filter_equal_keys(child,
                                                       params,
                                                       left_keys,
                                                       right_keys,
                                                       null_safe_info))) {
        LOG_WARN("failed to get equal join key", K(ret));
      } else if (OB_FAIL(ObShardingInfo::check_if_match_partition_wise(
                                        input_esets,
                                        left_keys,
                                        right_keys,
                                        null_safe_info,
                                        top->get_strong_sharding(),
                                        top->get_weak_sharding(),
                                        child->get_strong_sharding(),
                                        child->get_weak_sharding(),
                                        is_partition_wise))) {
        LOG_WARN("failed to check match partition wise join", K(ret));
      } else { /*do nothing*/}
    }
  }
  return ret;
}

int ObLogPlan::check_if_subplan_filter_match_repart(ObLogicalOperator *top,
                                                   const ObIArray<ObLogicalOperator*> &subquery_ops,
                                                   const ObIArray<ObExecParamRawExpr *> &params,
                                                   bool &is_match_repart)
{
  int ret = OB_SUCCESS;
  EqualSets input_esets;
  bool is_partition_wise = false;
  is_match_repart = false;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (!top->is_distributed()) {
    is_match_repart = false;
  } else if (OB_FAIL(append(input_esets, top->get_output_equal_sets()))) {
    LOG_WARN("failed to append equal sets", K(ret));
  } else {
    ObLogicalOperator *child = NULL;
    ObLogicalOperator *pre_child = NULL;
    ObSEArray<ObRawExpr *, 4> left_keys;
    ObSEArray<ObRawExpr *, 4> right_keys;
    ObSEArray<ObRawExpr *, 4> pre_child_keys;
    ObSEArray<ObRawExpr*, 4> target_part_keys;
    ObSEArray<bool, 4> null_safe_info;
    is_match_repart = true;
    for (int64_t i = 0; OB_SUCC(ret) && i < subquery_ops.count(); i++) {
      if (OB_ISNULL(child = subquery_ops.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(append(input_esets, child->get_output_equal_sets()))) {
        LOG_WARN("failed to append input equal sets", K(ret));
      } else { /*do nothing*/ }
    }
    for (int64_t i = 0; OB_SUCC(ret) && is_match_repart && i < subquery_ops.count(); ++i) {
      left_keys.reuse();
      right_keys.reuse();
      null_safe_info.reuse();
      target_part_keys.reuse();
      if (OB_ISNULL(child = subquery_ops.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (!child->is_distributed() || child->is_exchange_allocated() || OB_ISNULL(child->get_strong_sharding())) {
        is_match_repart = false;
      } else if (OB_FAIL(get_subplan_filter_equal_keys(child,
                                                       params,
                                                       left_keys,
                                                       right_keys,
                                                       null_safe_info))) {
        LOG_WARN("failed to get equal join key", K(ret));
      } else if (child->get_strong_sharding()->get_all_partition_keys(target_part_keys, true)) {
        LOG_WARN("failed to get partition keys", K(ret));
O
obdev 已提交
9366 9367 9368 9369 9370
      } else if (OB_FAIL(ObShardingInfo::check_if_match_repart_or_rehash(input_esets,
                                                                          left_keys,
                                                                          right_keys,
                                                                          target_part_keys,
                                                                          is_match_repart))) {
W
wangzelin.wzl 已提交
9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450
        LOG_WARN("failed to check if match repartition", K(ret));
      } else if (!is_match_repart) {
        //do nothing
      } else if (i < 1) {
        if (OB_FAIL(pre_child_keys.assign(right_keys))) {
          LOG_WARN("failed to assign exprs", K(ret));
        } else {
          pre_child = child;
        }
      } else if(OB_ISNULL(pre_child)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(ObShardingInfo::check_if_match_partition_wise(
                                        input_esets,
                                        pre_child_keys,
                                        right_keys,
                                        pre_child->get_strong_sharding(),
                                        child->get_strong_sharding(),
                                        is_partition_wise))) {
        LOG_WARN("failed to check match partition wise join", K(ret));
      } else {
        is_match_repart = is_partition_wise;
      }
    }
    if (OB_SUCC(ret)) {
      LOG_TRACE("succeed to check subplan filter matchs repart", K(is_match_repart));
    }
  }
  return ret;
}

int ObLogPlan::get_subplan_filter_equal_keys(ObLogicalOperator *child,
                                             const ObIArray<ObExecParamRawExpr *> &params,
                                             ObIArray<ObRawExpr *> &left_keys,
                                             ObIArray<ObRawExpr *> &right_keys,
                                             ObIArray<bool> &null_safe_info)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(child)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(get_subplan_filter_normal_equal_keys(child,
                                                          left_keys,
                                                          right_keys,
                                                          null_safe_info))) {
    LOG_WARN("failed to get normal equal key", K(ret));
  } else if (!params.empty() &&
             OB_FAIL(get_subplan_filter_correlated_equal_keys(child, params,
                                                              left_keys, right_keys,
                                                              null_safe_info))) {
    LOG_WARN("failed to get correlated equal keys", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::get_subplan_filter_normal_equal_keys(const ObLogicalOperator *child,
                                                    ObIArray<ObRawExpr *> &left_keys,
                                                    ObIArray<ObRawExpr *> &right_keys,
                                                    ObIArray<bool> &null_safe_info)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(child) || OB_ISNULL(child->get_stmt()) ||
      OB_UNLIKELY(!child->get_stmt()->is_select_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected error", K(ret));
  } else {
    //首先在filter里寻找
    for (int64_t i = 0; OB_SUCC(ret) && i < child->get_filter_exprs().count(); ++i) {
      ObRawExpr *expr = child->get_filter_exprs().at(i);
      if (OB_ISNULL(expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("expr is null", K(ret));
      } else if (T_OP_SQ_EQ == expr->get_expr_type()
                 || T_OP_SQ_NSEQ == expr->get_expr_type()
                 || T_OP_EQ == expr->get_expr_type()
                 || T_OP_NSEQ == expr->get_expr_type()) {
        ObRawExpr *left_hand = NULL;
        ObRawExpr *right_hand = NULL;
        bool is_null_safe = (T_OP_SQ_NSEQ == expr->get_expr_type() ||
                             T_OP_NSEQ == expr->get_expr_type());
O
obdev 已提交
9451
        ObSelectStmt *right_stmt = NULL;
W
wangzelin.wzl 已提交
9452 9453 9454 9455 9456 9457
        if (OB_ISNULL(left_hand = expr->get_param_expr(0))
            || OB_ISNULL(right_hand = expr->get_param_expr(1))) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("expr is invalid", K(ret), K(left_hand), K(right_hand));
        } else if (!right_hand->is_query_ref_expr()) {
          // do nothing
O
obdev 已提交
9458 9459 9460
        } else if (OB_FALSE_IT(right_stmt = static_cast<ObQueryRefRawExpr *>(
                                            right_hand)->get_ref_stmt())) {
        } else if (child->get_plan()->get_stmt() == right_stmt) {
W
wangzelin.wzl 已提交
9461 9462 9463
          // do nothing
        } else if (T_OP_ROW == left_hand->get_expr_type()) { //向量
          ObOpRawExpr *row_expr = static_cast<ObOpRawExpr *>(left_hand);
O
obdev 已提交
9464
          if (row_expr->get_param_count() != right_stmt->get_select_item_size()) {
W
wangzelin.wzl 已提交
9465 9466
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("expr size does not match",
O
obdev 已提交
9467
                     K(ret), K(*row_expr), K(right_stmt->get_select_items()));
W
wangzelin.wzl 已提交
9468 9469 9470
          } else {
            for (int64_t j = 0; OB_SUCC(ret) && j < row_expr->get_param_count(); ++j) {
              if (OB_FAIL(left_keys.push_back(row_expr->get_param_expr(j)))
O
obdev 已提交
9471
                  || OB_FAIL(right_keys.push_back(right_stmt->get_select_item(j).expr_))
W
wangzelin.wzl 已提交
9472 9473 9474 9475 9476 9477
                  || OB_FAIL(null_safe_info.push_back(is_null_safe))) {
                LOG_WARN("push back error", K(ret));
              } else { /* Do nothing */ }
            }
          }
        } else { //单expr
C
ChangerR 已提交
9478
          if (1 != right_stmt->get_select_item_size()) {
W
wangzelin.wzl 已提交
9479
            LOG_WARN("select item size should be 1",
C
ChangerR 已提交
9480
                     K(ret), K(right_stmt->get_select_item_size()));
W
wangzelin.wzl 已提交
9481
          } else if (OB_FAIL(left_keys.push_back(left_hand))
C
ChangerR 已提交
9482
                     || OB_FAIL(right_keys.push_back(right_stmt->get_select_item(0).expr_))
W
wangzelin.wzl 已提交
9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712
                     || OB_FAIL(null_safe_info.push_back(is_null_safe))) {
            LOG_WARN("push back error", K(ret));
          } else { /* Do nothing */ }
        }
      } else { /* Do nothing */ }
    }
  }
  return ret;
}

int ObLogPlan::get_subplan_filter_correlated_equal_keys(const ObLogicalOperator *top,
                                                        const ObIArray<ObExecParamRawExpr *> &params,
                                                        ObIArray<ObRawExpr *> &left_keys,
                                                        ObIArray<ObRawExpr *> &right_keys,
                                                        ObIArray<bool> &null_safe_info)
{
  int ret = OB_SUCCESS;
  bool is_stack_overflow = false;
  ObSEArray<ObRawExpr *, 8> filters;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("op is null", K(ret));
  } else if (OB_FAIL(check_stack_overflow(is_stack_overflow))) {
    LOG_WARN("check stack overflow failed", K(ret));
  } else if (is_stack_overflow) {
    ret = OB_SIZE_OVERFLOW;
    LOG_WARN("too deep recursive", K(ret));
  } else if (OB_FAIL(append(filters, top->get_filter_exprs()))) {
    LOG_WARN("failed to append filter exprs", K(ret));
  } else if (log_op_def::LOG_TABLE_SCAN == top->get_type()) {
    const ObLogTableScan *table_scan = static_cast<const ObLogTableScan *>(top);
    if (NULL != table_scan->get_pre_query_range() &&
        OB_FAIL(append(filters, table_scan->get_pre_query_range()->get_range_exprs()))) {
      LOG_WARN("failed to append conditions", K(ret));
    }
  }
  if (OB_FAIL(ret)) {
    // do nothing
  } else if (OB_FAIL(ObOptimizerUtil::extract_equal_exec_params(filters,
                                                                params,
                                                                left_keys,
                                                                right_keys,
                                                                null_safe_info))) {
    LOG_WARN("failed to extract equal exec params", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < top->get_num_of_child(); ++i) {
      if (OB_FAIL(SMART_CALL(get_subplan_filter_correlated_equal_keys(top->get_child(i),
                                                                      params,
                                                                      left_keys,
                                                                      right_keys,
                                                                      null_safe_info)))) {
        LOG_WARN("extract_correlated_keys error", K(ret));
      } else { /* do nothing */ }
    }
  }
  return ret;
}

/*
 * 在当前算子上层分配subplan filter算子,输入的表达式都是包含子查询的表达式,
 * 其中is_filter 表示当前输入的子查询表达式是不是过滤条件,因为子查询可能出现在select语句的各个子句中,
 * 其中只有出现在where子句和having子句中的子查询是filter。
 * 分配where子句,having子句和select子句中的子查询会直接调用该函数进行算子分配
 */
int ObLogPlan::allocate_subplan_filter_as_top(ObLogicalOperator *&top_node,
                                              const ObIArray<ObRawExpr*> &subquery_exprs,
                                              const bool is_filter,
                                              const bool for_on_condition)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(top_node)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(make_candidate_plans(top_node))) {
    LOG_WARN("failed to make candidate plans", K(ret));
  } else if (OB_FAIL(candi_allocate_subplan_filter(subquery_exprs,
                                                   is_filter ? &subquery_exprs : NULL,
                                                   false,
                                                   for_on_condition))) {
    LOG_WARN("failed to allocate subplan filter", K(ret));
  } else if (OB_FAIL(candidates_.get_best_plan(top_node))) { // only get best plan, not optimizer
    LOG_WARN("failed to get best plan", K(ret));
  } else if (OB_ISNULL(top_node)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::allocate_subplan_filter_as_top(ObLogicalOperator *&top,
                                              const ObIArray<ObLogicalOperator*> &subquery_ops,
                                              const ObIArray<ObQueryRefRawExpr *> &query_ref_exprs,
                                              const ObIArray<ObExecParamRawExpr *> &params,
                                              const ObIArray<ObExecParamRawExpr *> &onetime_exprs,
                                              const ObBitSet<> &initplan_idxs,
                                              const ObBitSet<> &onetime_idxs,
                                              const ObIArray<ObRawExpr*> *filters,
                                              const DistAlgo dist_algo,
                                              const bool is_update_set)
{
  int ret = OB_SUCCESS;
  ObLogSubPlanFilter *spf_node = NULL;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(top), K(ret));
  } else if (OB_ISNULL(spf_node = static_cast<ObLogSubPlanFilter*>(
                       get_log_op_factory().allocate(*this, LOG_SUBPLAN_FILTER)))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(spf_node), K(ret));
  } else if (OB_FAIL(spf_node->add_child(top))) {
    LOG_WARN("failed to add child", K(ret));
  } else if (OB_FAIL(spf_node->add_child(subquery_ops))) {
    LOG_WARN("failed to add child", K(ret));
  } else {
    spf_node->set_distributed_algo(dist_algo);
    spf_node->set_update_set(is_update_set);
    if (NULL != filters && OB_FAIL(append(spf_node->get_filter_exprs(), *filters))) {
      LOG_WARN("failed to append filter exprs", K(ret));
    } else if (OB_FAIL(spf_node->add_subquery_exprs(query_ref_exprs))) {
      LOG_WARN("failed to add subquery exprs", K(ret));
    } else if (OB_FAIL(spf_node->add_exec_params(params))) {
      LOG_WARN("failed to add exec params", K(ret));
    } else if (OB_FAIL(spf_node->add_onetime_exprs(onetime_exprs))) {
      LOG_WARN("failed to add onetime exprs", K(ret));
    } else if (OB_FAIL(spf_node->add_initplan_idxs(initplan_idxs))) {
      LOG_WARN("failed to add init plan idxs", K(ret));
    } else if (OB_FAIL(spf_node->add_onetime_idxs(onetime_idxs))) {
      LOG_WARN("failed to add onetime idxs", K(ret));
    } else if (OB_FAIL(spf_node->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      top = spf_node;
    }
  }
  return ret;
}

int ObLogPlan::allocate_subplan_filter_for_on_condition(ObIArray<ObRawExpr*> &subquery_exprs, ObLogicalOperator* &top)
{
  int ret = OB_SUCCESS;
  ObSEArray<ObRawExpr*, 4> pushdown_subquery;
  ObSEArray<ObRawExpr*, 4> none_pushdown_subquery;
  //下推的subplan filter不需要重新计算选择率
  for (int64_t i = 0; OB_SUCC(ret) && i < subquery_exprs.count(); ++i) {
    ObRawExpr* expr = subquery_exprs.at(i);
    if (OB_ISNULL(expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpect null expr", K(ret));
    } else if (expr->has_flag(CNT_SUB_QUERY)) {
      if (OB_FAIL(none_pushdown_subquery.push_back(expr))) {
        LOG_WARN("failed to push back expr", K(ret));
      }
    } else if (OB_FAIL(pushdown_subquery.push_back(expr))) {
      LOG_WARN("failed to push back expr", K(ret));
    }
  }
  if (OB_FAIL(ret)) {
    /*do nothing*/
  } else if (!pushdown_subquery.empty() &&
              OB_FAIL(allocate_subplan_filter_as_top(top,
                                                    pushdown_subquery,
                                                    false,
                                                    true))) {
    LOG_WARN("failed to allocate subplan filter", K(ret));
  } else if (!none_pushdown_subquery.empty() &&
              OB_FAIL(allocate_subplan_filter_as_top(top,
                                                    none_pushdown_subquery,
                                                    true,
                                                    true))) {
    LOG_WARN("failed to allocate subplan filter", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::candi_allocate_filter(const ObIArray<ObRawExpr*> &filter_exprs)
{
  int ret = OB_SUCCESS;
  double sel = 1.0;
  ObLogicalOperator *best_plan = NULL;
  EqualSets equal_sets;
  if (OB_FAIL(candidates_.get_best_plan(best_plan))) {
    LOG_WARN("failed to get best plan", K(ret));
  } else if (OB_ISNULL(best_plan)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(best_plan->get_input_equal_sets(equal_sets))) {
    LOG_WARN("failed to get input equal sets", K(ret));
  } else if (OB_FALSE_IT(get_selectivity_ctx().init_op_ctx(&equal_sets, best_plan->get_card()))) {
  } else if (OB_FAIL(ObOptSelectivity::calculate_selectivity(get_update_table_metas(),
                                                             get_selectivity_ctx(),
                                                             filter_exprs,
                                                             sel,
                                                             get_predicate_selectivities()))) {
    LOG_WARN("failed to calc selectivity", K(ret));
  } else if (OB_FALSE_IT(get_selectivity_ctx().init_op_ctx(NULL, -1.0))) {
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); i++) {
      ObLogicalOperator *top = NULL;
      if (OB_ISNULL(top = candidates_.candidate_plans_.at(i).plan_tree_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(append(top->get_filter_exprs(), filter_exprs))) {
        LOG_WARN("failed to append exprs", K(ret));
      } else {
        top->set_card(top->get_card() * sel);
      }
    }
  }
  return ret;
}


int ObLogPlan::plan_tree_traverse(const TraverseOp &operation, void *ctx)
{
  int ret = OB_SUCCESS;

  if (OB_ISNULL(get_plan_root()) || OB_ISNULL(get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("Get unexpected null", K(ret), K(get_stmt()), K(get_plan_root()));
  } else {
    NumberingCtx numbering_ctx;                      // operator numbering context
    NumberingExchangeCtx numbering_exchange_ctx;     // operator numbering context
    ObAllocExprContext alloc_expr_ctx;               // expr allocation context
    uint64_t hash_seed =  0;                         // seed for plan signature
    ObBitSet<256> output_deps;                       // output expr dependencies
    AllocGIContext gi_ctx;
    ObPxPipeBlockingCtx pipe_block_ctx(get_allocator());
    ObLocationConstraintContext location_constraints;
    AllocMDContext md_ctx;
    AllocBloomFilterContext bf_ctx;
O
obdev 已提交
9713 9714 9715
    SMART_VAR(ObBatchExecParamCtx, batch_exec_param_ctx) {
      // set up context
      switch (operation) {
O
obdev 已提交
9716 9717 9718 9719
      case PX_PIPE_BLOCKING: {
        ctx = &pipe_block_ctx;
        if (OB_FAIL(get_plan_root()->init_all_traverse_ctx(pipe_block_ctx))) {
          LOG_WARN("init traverse ctx failed", K(ret));
O
obdev 已提交
9720
        }
O
obdev 已提交
9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732
        break;
      }
      case ALLOC_GI: {
        ctx = &gi_ctx;
        bool is_valid = true;
        if (get_stmt()->is_insert_stmt() &&
            !static_cast<const ObInsertStmt*>(get_stmt())->value_from_select()) {
          gi_ctx.is_valid_for_gi_ = false;
        } else if (OB_FAIL(get_plan_root()->should_allocate_gi_for_dml(is_valid))) {
          LOG_WARN("failed to check should allocate gi for dml", K(ret));
        } else {
          gi_ctx.is_valid_for_gi_ = get_stmt()->is_dml_write_stmt() && is_valid;
O
obdev 已提交
9733
        }
O
obdev 已提交
9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752
        break;
      }
      case ALLOC_MONITORING_DUMP: {
        ctx = &md_ctx;
        break;
      }
      case BLOOM_FILTER: {
        ctx = &bf_ctx;
        break;
      }
      case PROJECT_PRUNING: {
        ctx = &output_deps;
        break;
      }
      case ALLOC_EXPR: {
        if (OB_FAIL(alloc_expr_ctx.flattern_expr_map_.create(128, "ExprAlloc"))) {
          LOG_WARN("failed to init hash map", K(ret));
        } else {
          ctx = &alloc_expr_ctx;
O
obdev 已提交
9753
        }
O
obdev 已提交
9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780
        break;
      }
      case OPERATOR_NUMBERING: {
        ctx = &numbering_ctx;
        break;
      }
      case EXCHANGE_NUMBERING: {
        ctx = &numbering_exchange_ctx;
        break;
      }
      case GEN_SIGNATURE: {
        ctx = &hash_seed;
        break;
      }
      case GEN_LOCATION_CONSTRAINT: {
        ctx = &location_constraints;
        break;
      }
      case PX_ESTIMATE_SIZE:
        break;
      case COLLECT_BATCH_EXEC_PARAM: {
        ctx = &batch_exec_param_ctx;
        break;
      }
      case ALLOC_STARTUP_EXPR:
      default:
        break;
O
obdev 已提交
9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823
      }
      if (OB_SUCC(ret)) {
        if (((PX_ESTIMATE_SIZE == operation) ||
            (PX_PIPE_BLOCKING == operation) ||
            (PX_RESCAN == operation)) &&
            (get_optimizer_context().is_local_or_remote_plan())) {
          /*do nothing*/
        } else if (ALLOC_GI == operation &&
                  get_optimizer_context().is_local_or_remote_plan() &&
                  !(gi_ctx.is_valid_for_gi_ &&
                    get_optimizer_context().enable_batch_rpc())) {
          /*do nothing*/
        } else if (OB_FAIL(get_plan_root()->do_plan_tree_traverse(operation, ctx))) {
          LOG_WARN("failed to apply operation to operator", K(operation), K(ret));
        } else {
          // remember signature in plan
          if (GEN_SIGNATURE == operation) {
            if (OB_ISNULL(ctx)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_WARN("ctx is null", K(ret), K(ctx));
            } else {
              hash_value_ = *static_cast<uint64_t *>(ctx);
              LOG_TRACE("succ to generate plan hash value", "hash_value", hash_value_);
            }
          } else if (GEN_LOCATION_CONSTRAINT == operation) {
            ObSqlCtx *sql_ctx = NULL;
            if (OB_ISNULL(optimizer_context_.get_exec_ctx())
                || OB_ISNULL(sql_ctx = optimizer_context_.get_exec_ctx()->get_sql_ctx())) {
              ret = OB_INVALID_ARGUMENT;
              LOG_WARN("invalid argument", K(ret), K(optimizer_context_.get_exec_ctx()), K(sql_ctx));
            } else if (OB_FAIL(remove_duplicate_constraint(location_constraints,
                                                          *sql_ctx))) {
              LOG_WARN("fail to remove duplicate constraint", K(ret));
            } else if (OB_FAIL(calc_and_set_exec_pwj_map(location_constraints))) {
              LOG_WARN("failed to calc and set exec pwj map", K(ret));
            }
          } else if (OPERATOR_NUMBERING == operation) {
            NumberingCtx *num_ctx = static_cast<NumberingCtx *>(ctx);
            max_op_id_ = num_ctx->op_id_;
            LOG_TRACE("trace max operator id", K(max_op_id_), K(this));
          } else { /* Do nothing */ }
          LOG_TRACE("succ to apply operaion to operator", K(operation), K(ret));
        }
W
wangzelin.wzl 已提交
9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892
      }
    }
  }
  return ret;
}

int ObLogPlan::contains_limit_or_pushdown_limit(ObLogicalOperator *op,
                                                bool &contains)
{
  int ret = OB_SUCCESS;
  contains = false;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid op", K(ret));
  } else if (log_op_def::LOG_LIMIT == op->get_type()) {
    contains = true;
  } else if (log_op_def::LOG_TABLE_SCAN == op->get_type()) {
    ObLogTableScan *ts = static_cast<ObLogTableScan*>(op);
    if (NULL != ts->get_limit_expr()) {
      contains = true;
    }
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && !contains && i < op->get_num_of_child(); ++i) {
      ObLogicalOperator *child = op->get_child(i);
      if (OB_ISNULL(child)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("invalid child", K(ret));
      } else if (OB_FAIL(SMART_CALL(contains_limit_or_pushdown_limit(child, contains)))) {
        LOG_WARN("failed to check contains limit", K(ret));
      } else {/*do nothing*/}
    }
  }
  return ret;
}

int ObLogPlan::contains_startup_with_exec_param(ObLogicalOperator *op,
                                                bool &contains)
{
  int ret = OB_SUCCESS;
  contains = false;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid op", K(ret));
  } else {
    ObIArray<ObRawExpr*> &startup_exprs = op->get_startup_exprs();
    for (int64_t i = 0; OB_SUCC(ret) && !contains && i < startup_exprs.count(); ++i) {
      ObRawExpr *expr = startup_exprs.at(i);
      if (OB_ISNULL(expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpect null expr", K(ret));
      } else if (expr->has_flag(CNT_DYNAMIC_PARAM)) {
        contains = true;
      } else {/*do nothing*/}
    }
    if (OB_SUCC(ret) && !contains) {
      for (int64_t i = 0; OB_SUCC(ret) && !contains && i < op->get_num_of_child(); ++i) {
        ObLogicalOperator *child = op->get_child(i);
        if (OB_ISNULL(child)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid child", K(ret));
        } else if (OB_FAIL(SMART_CALL(contains_startup_with_exec_param(child, contains)))) {
          LOG_WARN("failed to check contains startup with exec param", K(ret));
        } else {/*do nothing*/}
      }
    }
  }
  return ret;
}

O
obdev 已提交
9893
int ObLogPlan::init_onetime_subquery_info()
W
wangzelin.wzl 已提交
9894 9895
{
  int ret = OB_SUCCESS;
O
obdev 已提交
9896 9897 9898 9899
  ObArray<ObRawExpr *> func_table_exprs;
  ObArray<ObRawExpr *> json_table_exprs;
  void *ptr = NULL;
  if (OB_ISNULL(stmt_)) {
W
wangzelin.wzl 已提交
9900
    ret = OB_ERR_UNEXPECTED;
O
obdev 已提交
9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916
    LOG_WARN("stmt is null", K(ret));
  } else if (OB_ISNULL(ptr = get_allocator().alloc(sizeof(ObRawExprCopier)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_WARN("failed to allocate memory", K(ret));
  } else {
    onetime_copier_ = new (ptr) ObRawExprCopier(get_optimizer_context().get_expr_factory());
  }

  if (OB_SUCC(ret) && stmt_->get_subquery_expr_size() > 0) {
    ObSEArray<ObRawExpr *, 4> exprs;
    if (OB_FAIL(stmt_->get_relation_exprs(exprs))) {
      LOG_WARN("failed to get relation exprs", K(ret));
    } else if (OB_FAIL(stmt_->get_table_function_exprs(func_table_exprs))) {
      LOG_WARN("failed to get table function exprs", K(ret));
    } else if (OB_FAIL(stmt_->get_json_table_exprs(json_table_exprs))) {
      LOG_WARN("failed to get json table exprs", K(ret));
W
wangzelin.wzl 已提交
9917
    }
O
obdev 已提交
9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934
    for (int64_t i = 0; OB_SUCC(ret) && i < exprs.count(); ++i) {
      bool dummy = false;
      ObRawExpr *expr = exprs.at(i);
      ObSEArray<ObRawExpr *, 4> onetime_list;
      if (OB_ISNULL(expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("expr is null", K(ret));
      } else if (ObOptimizerUtil::find_item(func_table_exprs, expr)) {
        // do nothing
      } else if (ObOptimizerUtil::find_item(json_table_exprs, expr)) {
        // do nothing
      } else if (OB_FAIL(extract_onetime_subquery(expr, onetime_list, dummy))) {
        LOG_WARN("failed to extract onetime subquery", K(ret));
      } else if (onetime_list.empty()) {
        // do nothing
      } else if (OB_FAIL(create_onetime_param(expr, onetime_list))) {
        LOG_WARN("failed to create onetime param expr", K(ret));
W
wangzelin.wzl 已提交
9935 9936 9937 9938 9939 9940
      }
    }
  }
  return ret;
}

O
obdev 已提交
9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951
/**
 * @brief ObLogPlan::extract_onetime_subquery
 * @param expr
 * @param onetime_list
 * @param is_valid: if a expr is invalid,
 *                  its parent is also invalid while its children can be valid
 * @return
 */
int ObLogPlan::extract_onetime_subquery(ObRawExpr *expr,
                                        ObIArray<ObRawExpr *> &onetime_list,
                                        bool &is_valid)
W
wangzelin.wzl 已提交
9952 9953
{
  int ret = OB_SUCCESS;
O
obdev 已提交
9954 9955
  bool is_valid_non_correlated_exists = false;
  if (OB_ISNULL(expr)) {
W
wangzelin.wzl 已提交
9956
    ret = OB_ERR_UNEXPECTED;
O
obdev 已提交
9957
    LOG_WARN("expr is null", K(ret));
W
wangzelin.wzl 已提交
9958
  } else {
O
obdev 已提交
9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984
    // if a expr contain psedu column, hierachical expr, any column
    is_valid = !ObOptimizerUtil::has_psedu_column(*expr)
              && !ObOptimizerUtil::has_hierarchical_expr(*expr)
              && !expr->has_flag(CNT_COLUMN)
              && !expr->has_flag(CNT_AGG)
              && !expr->has_flag(CNT_WINDOW_FUNC)
              && !expr->has_flag(CNT_ALIAS)
              && !expr->has_flag(CNT_SET_OP);
  }

  if (OB_SUCC(ret) && expr->is_query_ref_expr()) {
    bool has_ref_assign_user_var = false;
    if (!is_valid) {
      // do nothing
    } else if (expr->get_param_count() > 0) {
      is_valid = false;
    } else if (OB_FAIL(ObOptimizerUtil::check_subquery_has_ref_assign_user_var(
                         expr, has_ref_assign_user_var))) {
      LOG_WARN("failed to check subquery has ref assign user var", K(ret));
    } else if (has_ref_assign_user_var) {
      is_valid = false;
    } else if (expr->get_output_column() == 1 &&
               !static_cast<ObQueryRefRawExpr *>(expr)->is_set() &&
               !static_cast<ObQueryRefRawExpr *>(expr)->is_multiset() ) {
      if (OB_FAIL(onetime_list.push_back(expr))) {
        LOG_WARN("failed to push back candi onetime expr", K(ret));
W
wangzelin.wzl 已提交
9985 9986 9987 9988
      }
    }
  }

O
obdev 已提交
9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006
  if (OB_SUCC(ret) && expr->has_flag(CNT_SUB_QUERY)) {
    for (int64_t i = 0; OB_SUCC(ret) && i < expr->get_param_count(); ++i) {
      bool is_param_valid = false;
      if (OB_FAIL(extract_onetime_subquery(expr->get_param_expr(i),
                                           onetime_list,
                                           is_param_valid))) {
        LOG_WARN("failed to extract onetime subquery", K(ret));
      } else if (!is_param_valid) {
        is_valid = false;
      }
    }
    if (OB_SUCC(ret) && is_valid && (T_OP_EXISTS == expr->get_expr_type()
                                     || T_OP_NOT_EXISTS == expr->get_expr_type()
                                     || expr->has_flag(IS_WITH_ALL)
                                     || expr->has_flag(IS_WITH_ANY))) {
      if (OB_FAIL(onetime_list.push_back(expr))) {
        LOG_WARN("failed to push back candi onetime exprs", K(ret));
      }
W
wangzelin.wzl 已提交
10007 10008
    }
  }
O
obdev 已提交
10009

W
wangzelin.wzl 已提交
10010 10011 10012
  return ret;
}

O
obdev 已提交
10013 10014
int ObLogPlan::create_onetime_param(ObRawExpr *expr,
                                    const ObIArray<ObRawExpr *> &onetime_list)
W
wangzelin.wzl 已提交
10015 10016
{
  int ret = OB_SUCCESS;
O
obdev 已提交
10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052
  int64_t idx = -1;
  ObQueryCtx *query_ctx = NULL;
  if (OB_ISNULL(stmt_) || OB_ISNULL(expr) ||
      OB_ISNULL(query_ctx = get_optimizer_context().get_query_ctx()) ||
      OB_ISNULL(onetime_copier_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected null", K(ret));
  } else if (ObOptimizerUtil::find_item(onetime_query_refs_, expr)) {
    // do nothing
  } else if (ObOptimizerUtil::find_item(onetime_list, expr)) {
    ObRawExpr *new_expr = expr;
    ObExecParamRawExpr *exec_param = NULL;
    if (OB_FAIL(ObRawExprUtils::create_new_exec_param(query_ctx,
                                                      get_optimizer_context().get_expr_factory(),
                                                      new_expr,
                                                      true))) {
      LOG_WARN("failed to create new exec param", K(ret));
    } else if (OB_ISNULL(exec_param = static_cast<ObExecParamRawExpr*>(new_expr))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("new exec param is null", KPC(new_expr), K(ret));
    } else if (OB_FAIL(exec_param->formalize(get_optimizer_context().get_session_info()))) {
      LOG_WARN("failed to formalize expr", K(ret));
    } else if (OB_FAIL(onetime_query_refs_.push_back(expr))) {
      LOG_WARN("failed to add old expr", K(ret));
    } else if (OB_FAIL(onetime_params_.push_back(exec_param))) {
      LOG_WARN("failed to push back new expr", K(ret));
    } else if (OB_FAIL(onetime_copier_->add_replaced_expr(expr, exec_param))) {
      LOG_WARN("failed to add replace expr", K(ret));
    }
  } else if (expr->has_flag(CNT_SUB_QUERY)) {
    for (int64_t i = 0; OB_SUCC(ret) && i < expr->get_param_count(); ++i) {
      if (OB_FAIL(create_onetime_param(expr->get_param_expr(i),
                                       onetime_list))) {
        LOG_WARN("failed to create onetime param", K(ret));
      }
    }
W
wangzelin.wzl 已提交
10053 10054 10055 10056
  }
  return ret;
}

O
obdev 已提交
10057 10058 10059 10060
int ObLogPlan::extract_onetime_exprs(ObRawExpr *expr,
                                     ObIArray<ObExecParamRawExpr *> &onetime_exprs,
                                     ObIArray<ObQueryRefRawExpr *> &onetime_query_refs,
                                     const bool for_on_condition)
W
wangzelin.wzl 已提交
10061 10062
{
  int ret = OB_SUCCESS;
O
obdev 已提交
10063 10064
  ObExecParamRawExpr *exec_param = NULL;
  if (OB_ISNULL(expr)) {
W
wangzelin.wzl 已提交
10065
    ret = OB_ERR_UNEXPECTED;
O
obdev 已提交
10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105
    LOG_WARN("subquery is null", K(ret), K(expr));
  } else if (expr->is_exec_param_expr() && expr->has_flag(IS_ONETIME)) {
    exec_param = static_cast<ObExecParamRawExpr*>(expr);
  } else {
    int64_t idx = -1;
    if (!ObOptimizerUtil::find_item(onetime_query_refs_, expr, &idx)) {
      // do nothing
    } else if (OB_UNLIKELY(idx < 0 || idx > onetime_params_.count())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("onetime expr count mismatch", K(ret));
    } else if (OB_ISNULL(exec_param = onetime_params_.at(idx))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("onetime expr is null", K(exec_param));
    }
  }
  if (OB_FAIL(ret)) {
    // do nothing
  } else if (NULL != exec_param) {
    bool has_exists = ObOptimizerUtil::find_item(get_onetime_exprs(), exec_param);
    if (!for_on_condition && has_exists) {
      // another one has created the onetime
    } else if (!has_exists &&
               OB_FAIL(get_onetime_exprs().push_back(exec_param))) {
      LOG_WARN("failed to append onetime expr", K(ret));
    } else if (OB_FAIL(onetime_exprs.push_back(exec_param))) {
      LOG_WARN("failed to append array no dup", K(ret));
    } else if (OB_FAIL(ObTransformUtils::extract_query_ref_expr(exec_param->get_ref_expr(),
                                                                onetime_query_refs,
                                                                false))) {
      LOG_WARN("failed to extract query ref expr", K(ret));
    }
  } else if (expr->has_flag(CNT_ONETIME) || expr->has_flag(CNT_SUB_QUERY)) {
    for (int64_t i = 0; OB_SUCC(ret) && i < expr->get_param_count(); ++i) {
      if (OB_FAIL(SMART_CALL(extract_onetime_exprs(expr->get_param_expr(i),
                                                   onetime_exprs,
                                                   onetime_query_refs,
                                                   for_on_condition)))) {
        LOG_WARN("failed to extract onetime exprs", K(ret));
      }
    }
W
wangzelin.wzl 已提交
10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129
  }
  return ret;
}

double ObLogPlan::get_expr_selectivity(const ObRawExpr *expr, bool &found)
{
  double sel = 1.0;
  found = false;
  if (OB_ISNULL(expr)) {
  } else {
    for (int64_t i = 0; !found && i < pred_sels_.count(); ++i) {
      if (expr == pred_sels_.at(i).expr_) {
        found = true;
        sel = pred_sels_.at(i).sel_;
      }
    }
  }
  return sel;
}

int ObLogPlan::candi_allocate_count()
{
  int ret = OB_SUCCESS;
  ObRawExpr *limit_expr = NULL;
O
obdev 已提交
10130
  ObRawExpr *rownum_expr = NULL;
W
wangzelin.wzl 已提交
10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144
  ObSEArray<ObRawExpr*, 4> filter_exprs;
  ObSEArray<ObRawExpr*, 4> start_exprs;
  ObSEArray<ObRawExpr*, 4> subquery_exprs;
  if (OB_FAIL(ObOptimizerUtil::get_subquery_exprs(get_rownum_exprs(),
                                                  subquery_exprs))) {
    LOG_WARN("failed to get subquery exprs", K(ret));
  } else if (!subquery_exprs.empty() &&
             OB_FAIL(candi_allocate_subplan_filter(subquery_exprs))) {
    LOG_WARN("failed to allocate subplan filter", K(ret));
  } else if (OB_FAIL(classify_rownum_exprs(get_rownum_exprs(),
                                           filter_exprs,
                                           start_exprs,
                                           limit_expr))) {
    LOG_WARN("failed to classify rownum exprs", K(ret));
O
obdev 已提交
10145 10146 10147 10148 10149
  } else if (OB_ISNULL(get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("Unexpected null stmt", K(ret), K(get_stmt()));
  } else if (OB_FAIL(get_stmt()->get_rownum_expr(rownum_expr))) {
    LOG_WARN("get rownum expr failed", K(ret));
W
wangzelin.wzl 已提交
10150 10151 10152 10153 10154 10155 10156 10157
  } else {
    CandidatePlan candidate_plan;
    ObSEArray<CandidatePlan, 4> rownum_plans;
    for (int64_t i = 0; OB_SUCC(ret) && i < candidates_.candidate_plans_.count(); ++i) {
      candidate_plan = candidates_.candidate_plans_.at(i);
      if (OB_FAIL(create_rownum_plan(candidate_plan.plan_tree_,
                                     filter_exprs,
                                     start_exprs,
O
obdev 已提交
10158 10159
                                     limit_expr,
                                     rownum_expr))) {
W
wangzelin.wzl 已提交
10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176
        LOG_WARN("failed to allocate count operator", K(ret));
      } else if (OB_FAIL(rownum_plans.push_back(candidate_plan))) {
        LOG_WARN("failed to push back plan", K(ret));
      } else { /*do nothing*/ }
    }
    if (OB_SUCC(ret)) {
      if (OB_FAIL(prune_and_keep_best_plans(rownum_plans))) {
        LOG_WARN("failed to prune and keep best plans", K(ret));
      } else { /*do nothing*/ }
    }
  }
  return ret;
}

int ObLogPlan::create_rownum_plan(ObLogicalOperator *&top,
                                  const ObIArray<ObRawExpr*> &filter_exprs,
                                  const ObIArray<ObRawExpr*> &start_exprs,
O
obdev 已提交
10177 10178
                                  ObRawExpr *limit_expr,
                                  ObRawExpr *rownum_expr)
W
wangzelin.wzl 已提交
10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197
{
  int ret = OB_SUCCESS;
  bool is_pushed = false;
  ObExchangeInfo exch_info;
  if (OB_ISNULL(top)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (NULL != limit_expr && filter_exprs.empty() && !limit_expr->has_flag(CNT_DYNAMIC_PARAM) &&
             OB_FAIL(try_push_limit_into_table_scan(top, limit_expr, limit_expr, NULL, is_pushed))) {
    LOG_WARN("failed to push limit into table scan", K(ret));
  } else if (top->is_distributed() && NULL != limit_expr &&
             OB_FAIL(allocate_limit_as_top(top, limit_expr, NULL, NULL, false, false, false))) {
    LOG_WARN("failed to allocate limit as top", K(ret));
  } else if (top->is_distributed() &&
             OB_FAIL(allocate_exchange_as_top(top, exch_info))) {
    LOG_WARN("failed to allocate exchange as top", K(ret));
  } else if (OB_FAIL(allocate_count_as_top(top,
                                           filter_exprs,
                                           start_exprs,
O
obdev 已提交
10198 10199
                                           limit_expr,
                                           rownum_expr))) {
W
wangzelin.wzl 已提交
10200 10201 10202 10203 10204 10205 10206 10207
    LOG_WARN("failed to allocate count as top", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::allocate_count_as_top(ObLogicalOperator *&top,
                                     const ObIArray<ObRawExpr*> &filter_exprs,
                                     const ObIArray<ObRawExpr*> &start_exprs,
O
obdev 已提交
10208 10209
                                     ObRawExpr *limit_expr,
                                     ObRawExpr *rownum_expr)
W
wangzelin.wzl 已提交
10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224
{
  int ret = OB_SUCCESS;
  ObLogCount *count = NULL;
  if (OB_ISNULL(top) || OB_ISNULL(get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("Unexpected null stmt", K(ret), K(top), K(get_stmt()));
  } else if (OB_ISNULL(count = static_cast<ObLogCount *>(get_log_op_factory().allocate(*this, LOG_COUNT)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("Allocate memory for ObLogCount Failed", K(ret));
  } else if (OB_FAIL(append(count->get_filter_exprs(), filter_exprs))) {
    LOG_WARN("failed to append filter exprs", K(ret));
  } else if (OB_FAIL(append(count->get_startup_exprs(), start_exprs))) {
    LOG_WARN("failed to append start up exprs", K(ret));
  } else {
    count->set_rownum_limit_expr(limit_expr);
O
obdev 已提交
10225
    count->set_rownum_expr(rownum_expr);
W
wangzelin.wzl 已提交
10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318
    count->set_child(ObLogicalOperator::first_child, top);
    if (OB_FAIL(count->compute_property())) {
      LOG_WARN("failed to compute property");
    } else {
      top = count;
    }
  }
  return ret;
}

int ObLogPlan::classify_rownum_exprs(const ObIArray<ObRawExpr*> &rownum_exprs,
                                     ObIArray<ObRawExpr*> &filter_exprs,
                                     ObIArray<ObRawExpr*> &start_exprs,
                                     ObRawExpr *&limit_expr)
{
  int ret = OB_SUCCESS;
  ObItemType limit_rownum_type = T_INVALID;
  limit_expr = NULL;
  for (int64_t i = 0; OB_SUCC(ret) && i < rownum_exprs.count(); i++) {
    ObRawExpr *rownum_expr = rownum_exprs.at(i);
    ObRawExpr *const_expr = NULL;
    ObItemType expr_type = T_INVALID;
    bool dummy_flag = false;
    if (OB_FAIL(ObOptimizerUtil::get_rownum_filter_info(
                  rownum_expr, expr_type, const_expr, dummy_flag))) {
      LOG_WARN("failed to check is rownum expr used as filter", K(ret));
    } else if (OB_FAIL(classify_rownum_expr(expr_type, rownum_expr,
                                            const_expr, filter_exprs,
                                            start_exprs, limit_expr))) {
      LOG_WARN("failed to classify rownum expr", K(ret));
    } else if (const_expr == limit_expr) {
      limit_rownum_type = expr_type;
    }
  }
  if (OB_SUCC(ret) && OB_NOT_NULL(limit_expr)) {
    ObRawExpr *limit_int_expr = NULL;
    if (OB_FAIL(ObOptimizerUtil::convert_rownum_filter_as_limit(
                  get_optimizer_context().get_expr_factory(),
                  get_optimizer_context().get_session_info(),
                  limit_rownum_type, limit_expr, limit_int_expr))) {
      LOG_WARN("failed to transform rownum filter as limit", K(ret));
    } else {
      limit_expr = limit_int_expr;
    }
  }
  return ret;
}

int ObLogPlan::classify_rownum_expr(const ObItemType expr_type,
                                    ObRawExpr *rownum_expr,
                                    ObRawExpr *left_const_expr,
                                    common::ObIArray<ObRawExpr*> &filter_exprs,
                                    common::ObIArray<ObRawExpr*> &start_exprs,
                                    ObRawExpr *&limit_expr)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(rownum_expr)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("null expr", K(rownum_expr), K(ret));
  } else if ((expr_type == T_OP_LE || expr_type == T_OP_LT)
             && NULL == limit_expr && NULL != left_const_expr) {
    limit_expr = left_const_expr;
  } else if (expr_type == T_OP_GE || expr_type == T_OP_GT) {
    if (OB_FAIL(start_exprs.push_back(rownum_expr))) {
      LOG_WARN("failed to push back rownum expr", K(ret));
    } else { /*do nothing*/ }
  } else {
    if (OB_FAIL(filter_exprs.push_back(rownum_expr))) {
      LOG_WARN("failed to push back rownum expr", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::update_plans_interesting_order_info(ObIArray<CandidatePlan> &candidate_plans,
                                                   const int64_t check_scope)
{
  int ret = OB_SUCCESS;
  int64_t match_info = OrderingFlag::NOT_MATCH;
  if (check_scope == OrderingCheckScope::NOT_CHECK) {
    // do nothing
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < candidate_plans.count(); i++) {
      CandidatePlan &candidate_plan = candidate_plans.at(i);
      if (OB_ISNULL(candidate_plan.plan_tree_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(ObOptimizerUtil::compute_stmt_interesting_order(
          candidate_plan.plan_tree_->get_op_ordering(),
          get_stmt(),
          get_is_subplan_scan(),
          get_equal_sets(),
          get_const_exprs(),
O
obdev 已提交
10319
          get_is_parent_set_distinct(),
W
wangzelin.wzl 已提交
10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354
          check_scope,
          match_info))) {
        LOG_WARN("failed to update ordering match info", K(ret));
      } else {
        candidate_plan.plan_tree_->set_interesting_order_info(match_info);
      }
    }
  }
  return ret;
}

int ObLogPlan::prune_and_keep_best_plans(ObIArray<CandidatePlan> &candidate_plans)
{
  int ret = OB_SUCCESS;
  ObSEArray<CandidatePlan, 8> best_plans;
  for (int64_t i = 0; OB_SUCC(ret) && i < candidate_plans.count(); i++) {
    CandidatePlan &candidate_plan = candidate_plans.at(i);
    if (OB_FAIL(add_candidate_plan(best_plans, candidate_plan))) {
      LOG_WARN("failed to add candidate plan", K(ret));
    } else { /*do nothing*/ }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(init_candidate_plans(best_plans))) {
      LOG_WARN("failed to do candi init", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::add_candidate_plan(ObIArray<CandidatePlan> &current_plans,
                                  const CandidatePlan &new_plan)
{
  int ret = OB_SUCCESS;
  bool should_add = true;
  DominateRelation plan_rel = DominateRelation::OBJ_UNCOMPARABLE;
O
obdev 已提交
10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368
  if (OB_ISNULL(new_plan.plan_tree_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (new_plan.plan_tree_->get_type() == LOG_SET &&
             static_cast<ObLogSet*>(new_plan.plan_tree_)->is_recursive_union()) {
    ObLogicalOperator* right_child = new_plan.plan_tree_->get_child(ObLogicalOperator::second_child);
    if (OB_ISNULL(right_child)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (right_child->get_contains_match_all_fake_cte() &&
               !new_plan.plan_tree_->is_remote()) {
      should_add = false;
    }
  }
W
wangzelin.wzl 已提交
10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628
  for (int64_t i = current_plans.count() - 1;
       OB_SUCC(ret) && should_add && i >= 0; --i) {
    if (OB_FAIL(compute_plan_relationship(current_plans.at(i),
                                          new_plan,
                                          plan_rel))) {
      LOG_WARN("failed to compute plan relationship",
               K(current_plans.at(i)), K(new_plan), K(ret));
    } else if (DominateRelation::OBJ_LEFT_DOMINATE == plan_rel ||
               DominateRelation::OBJ_EQUAL == plan_rel) {
      should_add = false;
    } else if (DominateRelation::OBJ_RIGHT_DOMINATE == plan_rel) {
      if (OB_FAIL(current_plans.remove(i))) {
        LOG_WARN("failed to remove dominated plans", K(i), K(ret));
      } else { /* do nothing*/ }
    } else { /* do nothing */ }
  }
  if (OB_SUCC(ret) && should_add) {
    if (OB_FAIL(current_plans.push_back(new_plan))) {
      LOG_WARN("failed to add plan", K(ret));
    } else { /*do nothing*/ }
  }
  return ret;
}

int ObLogPlan::compute_plan_relationship(const CandidatePlan &first_candi_plan,
                                         const CandidatePlan &second_candi_plan,
                                         DominateRelation &plan_rel)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = NULL;
  const ObLogicalOperator *first_plan = NULL;
  const ObLogicalOperator *second_plan = NULL;
  plan_rel = DominateRelation::OBJ_UNCOMPARABLE;
  if (OB_ISNULL(stmt = get_stmt()) ||
      OB_ISNULL(first_plan = first_candi_plan.plan_tree_) ||
      OB_ISNULL(second_plan = second_candi_plan.plan_tree_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(stmt), K(first_plan), K(second_plan), K(ret));
  } else {
    DominateRelation temp_relation;
    int64_t left_dominated_count = 0;
    int64_t right_dominated_count = 0;
    int64_t uncompareable_count = 0;
    // compare cost
    if (fabs(first_plan->get_cost() - second_plan->get_cost()) < OB_DOUBLE_EPSINON) {
      // do nothing
    } else if (first_plan->get_cost() < second_plan->get_cost()) {
      left_dominated_count++;
    } else {
      right_dominated_count++;
    }
    // compare interesting order
    if (OB_FAIL(ObOptimizerUtil::compute_ordering_relationship(
                                 first_plan->has_any_interesting_order_info_flag(),
                                 second_plan->has_any_interesting_order_info_flag(),
                                 first_plan->get_op_ordering(),
                                 second_plan->get_op_ordering(),
                                 first_plan->get_output_equal_sets(),
                                 first_plan->get_output_const_exprs(),
                                 temp_relation))) {
      LOG_WARN("failed to compute ordering relationship", K(ret));
    } else if (temp_relation == DominateRelation::OBJ_EQUAL) {
      /*do nothing*/
    } else if (temp_relation == DominateRelation::OBJ_LEFT_DOMINATE) {
      left_dominated_count++;
    } else if (temp_relation == DominateRelation::OBJ_RIGHT_DOMINATE) {
      right_dominated_count++;
    } else {
      uncompareable_count++;
    }
    // check dominate relationship for sharding info
    if (OB_SUCC(ret)) {
      if (OB_FAIL(ObOptimizerUtil::compute_sharding_relationship(
                                   first_plan->get_strong_sharding(),
                                   first_plan->get_weak_sharding(),
                                   second_plan->get_strong_sharding(),
                                   second_plan->get_weak_sharding(),
                                   first_plan->get_output_equal_sets(),
                                   temp_relation))) {
        LOG_WARN("failed to compute sharding relationship", K(ret));
      } else if (temp_relation == DominateRelation::OBJ_EQUAL) {
        /*do nothing*/
      } else if (temp_relation == DominateRelation::OBJ_LEFT_DOMINATE) {
        left_dominated_count++;
      } else if (temp_relation == DominateRelation::OBJ_RIGHT_DOMINATE) {
        right_dominated_count++;
      } else {
        uncompareable_count++;
      }
    }

    // compare pipeline operator
    if (OB_SUCC(ret) && stmt->has_limit()) {
      if (OB_FAIL(compute_pipeline_relationship(*first_plan,
                                                *second_plan,
                                                temp_relation))) {
        LOG_WARN("failed to compute pipeline relationship", K(ret));
      } else if (temp_relation == DominateRelation::OBJ_EQUAL) {
        /*do nothing*/
      } else if (temp_relation == DominateRelation::OBJ_LEFT_DOMINATE) {
        left_dominated_count++;
      } else if (temp_relation == DominateRelation::OBJ_RIGHT_DOMINATE) {
        right_dominated_count++;
      } else {
        uncompareable_count++;
      }
    }
    // compute final result
    if (OB_SUCC(ret)) {
      if (left_dominated_count > 0 && right_dominated_count == 0
          && uncompareable_count == 0) {
        plan_rel = DominateRelation::OBJ_LEFT_DOMINATE;
        LOG_TRACE("first dominated second",
                  K(first_plan->get_cost()), K(first_plan->get_op_ordering()),
                  K(second_plan->get_cost()), K(second_plan->get_op_ordering()));
      } else if (right_dominated_count > 0 && left_dominated_count == 0
                 && uncompareable_count == 0) {
        plan_rel = DominateRelation::OBJ_RIGHT_DOMINATE;
        LOG_TRACE("second dominated first",
                  K(second_plan->get_cost()), K(second_plan->get_op_ordering()),
                  K(first_plan->get_cost()), K(first_plan->get_op_ordering()));
      } else if (left_dominated_count == 0 && right_dominated_count == 0
                 && uncompareable_count == 0) {
        plan_rel = DominateRelation::OBJ_EQUAL;
      } else {
        plan_rel = DominateRelation::OBJ_UNCOMPARABLE;
      }
    }
  }
  return ret;
}

int ObLogPlan::compute_pipeline_relationship(const ObLogicalOperator &first_plan,
                                             const ObLogicalOperator &second_plan,
                                             DominateRelation &relation)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = NULL;
  relation = DominateRelation::OBJ_UNCOMPARABLE;
  bool check_pipeline = true;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(stmt), K(ret));
  } else if (!stmt->get_order_items().empty()) {
    bool is_first_left_prefix = false;
    bool is_first_right_prefix = false;
    bool is_second_left_prefix = false;
    bool is_second_right_prefix = false;
    check_pipeline = false;
    if (OB_FAIL(ObOptimizerUtil::is_prefix_ordering(stmt->get_order_items(),
                                                    first_plan.get_op_ordering(),
                                                    first_plan.get_output_equal_sets(),
                                                    first_plan.get_output_const_exprs(),
                                                    is_first_left_prefix,
                                                    is_first_right_prefix))) {
      LOG_WARN("failed to compute prefix ordering relationship", K(ret));
    } else if (OB_FAIL(ObOptimizerUtil::is_prefix_ordering(stmt->get_order_items(),
                                                           second_plan.get_op_ordering(),
                                                           second_plan.get_output_equal_sets(),
                                                           second_plan.get_output_const_exprs(),
                                                           is_second_left_prefix,
                                                           is_second_right_prefix))) {
      LOG_WARN("failed to compute prefix ordering relationship", K(ret));
    } else if (!is_first_left_prefix && !is_second_left_prefix) {
      relation = DominateRelation::OBJ_EQUAL;
    } else if (is_first_left_prefix && !is_second_left_prefix) {
      relation = DominateRelation::OBJ_LEFT_DOMINATE;
    } else if (!is_first_left_prefix && is_second_left_prefix) {
      relation = DominateRelation::OBJ_RIGHT_DOMINATE;
    } else {
      check_pipeline = true;
    }
  } else { /*do nothing*/ }
  bool is_first_pipeline = first_plan.is_pipelined_plan();
  bool is_second_pipeline = second_plan.is_pipelined_plan();
  if (OB_FAIL(ret) || !check_pipeline) {
    //do nothing
  } else if (!is_first_pipeline && is_second_pipeline) {
    relation = DominateRelation::OBJ_RIGHT_DOMINATE;
  } else if (is_first_pipeline && !is_second_pipeline) {
    relation = DominateRelation::OBJ_LEFT_DOMINATE;
  } else if (!is_first_pipeline && !is_second_pipeline) {
    relation = DominateRelation::OBJ_EQUAL;
  } else if (is_first_pipeline && is_second_pipeline) {
    relation = DominateRelation::OBJ_UNCOMPARABLE;
  }
  return ret;
}

int ObLogPlan::add_global_table_partition_info(ObTablePartitionInfo *addr_table_partition_info)
{
  int ret = OB_SUCCESS;
  bool is_found = false;
  if (OB_NOT_NULL(addr_table_partition_info) &&
      addr_table_partition_info->get_table_location().use_das() &&
      addr_table_partition_info->get_table_location().get_has_dynamic_exec_param()) {
    // table locations maintained in physical plan will include those for px/das static partition pruning
    // don't add those for das dynamic partition pruning which maintained independently
  } else {
    ObIArray<ObTablePartitionInfo *> & table_partition_infos = optimizer_context_.get_table_partition_info();
    for (int64_t i = 0; OB_SUCC(ret) && !is_found && i < table_partition_infos.count(); ++i) {
      const ObTablePartitionInfo *tmp_info = table_partition_infos.at(i);
      if (tmp_info == addr_table_partition_info
          || (tmp_info->get_table_id() == addr_table_partition_info->get_table_id() &&
              tmp_info->get_ref_table_id() == addr_table_partition_info->get_ref_table_id())) {
        is_found = true;
      }
    }
    if (OB_SUCC(ret) && !is_found) {
      if (OB_FAIL(table_partition_infos.push_back(addr_table_partition_info))) {
        LOG_WARN("store table partition info failed", K(ret));
      }
    }
  }
  return ret;
}

/**
 * 分析location_constraint中的基表约束、严格partition wise join约束、非严格partition wise join约束
 * 对于如下计划:
 *           HJ4
 *          /   \
 *         EX   UNION_ALL
 *         |      /     \
 *         EX   TS5     TS6
 *         |
 *         HJ3
 *        /    \
 *      HJ1    HJ2
 *    /   \    /   \
 *  TS1   TS2 TS3  TS4
 *
 *    基表约束: {t1, dist}, {t2, dist}, {t3, dist}, {t4, dist}, {t5, local}, {t6, local}
 *    严格pwj约束:  [0,1], [2,3], [0,1,2,3]
 *    非严格pwj约束: [4,5]
 * 去除有重复的约束条件后
 *    基表约束: {t1, dist}, {t2, dist}, {t3, dist}, {t4, dist}, {t5, local}, {t6, local}
 *    严格pwj约束: [0,1,2,3]
 *    非严格pwj约束: [4,5]
 */
int ObLogPlan::remove_duplicate_constraint(ObLocationConstraintContext &location_constraint,
                                           ObSqlCtx &sql_ctx) const
{
  int ret = OB_SUCCESS;
  // 约束去重
  if (OB_FAIL(remove_duplicate_base_table_constraint(location_constraint))) {
    LOG_WARN("failed to remove duplicate base table constraint", K(ret));
  } else if (OB_FAIL(remove_duplicate_pwj_constraint(location_constraint.strict_constraints_))) {
    LOG_WARN("failed to remove duplicate strict pwj constraint", K(ret));
  } else if (OB_FAIL(remove_duplicate_pwj_constraint(location_constraint.non_strict_constraints_))){
    LOG_WARN("failed to remove duplicate strict pwj constraint", K(ret));
  } else if (OB_FAIL(sort_pwj_constraint(location_constraint))) {
    LOG_WARN("failed to sort pwj constraint", K(ret));
  // 将约束设置给sql_ctx
  } else if (OB_FAIL(sql_ctx.set_location_constraints(location_constraint, get_allocator()))) {
    LOG_WARN("failed to set location constraints", K(ret));
  } else {
    LOG_TRACE("duplicated constraints removed", K(location_constraint));
  }
  return ret;
O
oceanbase-admin 已提交
10629 10630
}

W
wangzelin.wzl 已提交
10631 10632 10633 10634 10635 10636 10637 10638
/**
 * 移除重复的基表约束
 * TODO yibo 理论上基表location约束不应该存在重复,先留一个检查。
 * 以下场景是一个例外:
 * 目前domain index的实现会在计划生成时mock一些log_table_scan出来,mock出来的log_table_scan直接使用了原
 * log_table_scan的table_id,会导致出现重复的基表约束。
 */
int ObLogPlan::remove_duplicate_base_table_constraint(ObLocationConstraintContext &location_constraint) const
O
oceanbase-admin 已提交
10639 10640
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
10641 10642 10643 10644 10645 10646 10647 10648
  ObLocationConstraint &base_constraints = location_constraint.base_table_constraints_;
  ObLocationConstraint unique_constraint;
  for (int64_t i = 0; OB_SUCC(ret) && i < base_constraints.count(); ++i) {
    bool find = false;
    int64_t j = 0;
    for (/* do nothing */; !find && j < unique_constraint.count(); ++j) {
      if (base_constraints.at(i) == unique_constraint.at(j)) {
        find = true;
O
oceanbase-admin 已提交
10649 10650
      }
    }
W
wangzelin.wzl 已提交
10651 10652 10653 10654 10655 10656
    if (find) {
      --j;
      if (OB_FAIL(replace_pwj_constraints(location_constraint.strict_constraints_, i, j))) {
        LOG_WARN("failed to replace pwj constraints", K(ret));
      } else if (OB_FAIL(replace_pwj_constraints(location_constraint.non_strict_constraints_, i, j))) {
        LOG_WARN("failed to replace pwj constraints", K(ret));
O
oceanbase-admin 已提交
10657
      }
W
wangzelin.wzl 已提交
10658 10659 10660
    } else if (OB_FAIL(unique_constraint.push_back(base_constraints.at(i)))) {
      LOG_WARN("failed to push back location constraint", K(ret));
      // do nothing
O
oceanbase-admin 已提交
10661 10662
    }
  }
W
wangzelin.wzl 已提交
10663 10664 10665
  if (OB_SUCC(ret) && unique_constraint.count() != base_constraints.count()) {
    if (OB_FAIL(base_constraints.assign(unique_constraint))) {
      LOG_WARN("failed to assign base constraints", K(ret));
O
oceanbase-admin 已提交
10666
    }
W
wangzelin.wzl 已提交
10667
    LOG_TRACE("inner duplicates removed", K(location_constraint));
O
oceanbase-admin 已提交
10668 10669 10670 10671 10672
  }

  return ret;
}

W
wangzelin.wzl 已提交
10673 10674 10675 10676 10677
// 发现重复的基表约束时, 替换pwj约束中重复的基表约束
// TODO yibo 理论上基表location约束不应该存在重复,这个函数应该也不需要
int ObLogPlan::replace_pwj_constraints(ObIArray<ObPwjConstraint *> &constraints,
                                       const int64_t from,
                                       const int64_t to) const
O
oceanbase-admin 已提交
10678 10679
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694
  ObPwjConstraint *cur_cons = NULL;
  ObSEArray<ObPwjConstraint *, 4> new_constraints;
  for (int64_t i = 0; OB_SUCC(ret) && i < constraints.count(); ++i) {
    if (OB_ISNULL(cur_cons = constraints.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    }

    for (int64_t j = 0; OB_SUCC(ret) && j < cur_cons->count(); ++j) {
      if (from == cur_cons->at(j)) {
        if (OB_FAIL(cur_cons->remove(j))) {
          LOG_WARN("failed to remove item", K(ret));
        } else if (OB_FAIL(add_var_to_array_no_dup(*cur_cons, to))) {
          LOG_WARN("failed to add var to array no dup");
        }
O
oceanbase-admin 已提交
10695 10696
      }
    }
W
wangzelin.wzl 已提交
10697

O
oceanbase-admin 已提交
10698
    if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
10699 10700 10701
      // 消除pwj constraint中重复的基表约束后,可能会导致新的pwj constraint中只有一个基表,此时这个约束就无效了
      if (cur_cons->count() > 1 && OB_FAIL(new_constraints.push_back(cur_cons))) {
        LOG_WARN("failed to push back pwj constraint", K(ret));
O
oceanbase-admin 已提交
10702 10703 10704
      }
    }
  }
W
wangzelin.wzl 已提交
10705 10706 10707
  if (OB_SUCC(ret) && new_constraints.count() < constraints.count()) {
    if (OB_FAIL(constraints.assign(new_constraints))) {
      LOG_WARN("failed to assign new constraints", K(ret));
O
oceanbase-admin 已提交
10708 10709 10710 10711 10712
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
10713 10714 10715
// 利用包含关系移除重复的pwj约束
// e.g. 存在约束[[0,1], [2,3], [0,1,2,3], [4,5]] 可以移除[0,1]和[2,3]
int ObLogPlan::remove_duplicate_pwj_constraint(ObIArray<ObPwjConstraint *> &pwj_constraints) const
O
oceanbase-admin 已提交
10716 10717
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748
  ObPwjConstraint *l_cons = NULL, *r_cons = NULL;
  ObBitSet<> removed_idx;
  ObLocationConstraintContext::InclusionType inclusion_result = ObLocationConstraintContext::NotSubset;

  for (int64_t i = 0; OB_SUCC(ret) && i < pwj_constraints.count(); ++i) {
    if (OB_ISNULL(l_cons = pwj_constraints.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(i));
    } else if (l_cons->count() < 2) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected constraint const", K(ret), K(*l_cons));
    } else if (removed_idx.has_member(i)) {
      // do nothing
    } else {
      for (int64_t j = i + 1; OB_SUCC(ret) && j < pwj_constraints.count(); ++j) {
        if (OB_ISNULL(r_cons = pwj_constraints.at(j))) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(ret), K(j));
        } else if (OB_FAIL(ObLocationConstraintContext::calc_constraints_inclusion(
            l_cons, r_cons, inclusion_result))) {
          LOG_WARN("failed to calculate inclusion relation between constraints",
                   K(ret), K(*l_cons), K(*r_cons));
        } else if (ObLocationConstraintContext::LeftIsSuperior == inclusion_result) {
          // Left containts all the elements of the right, remove j
          if (OB_FAIL(removed_idx.add_member(j))) {
            LOG_WARN("failed to add member", K(ret), K(j));
          }
        } else if (ObLocationConstraintContext::RightIsSuperior == inclusion_result) {
          // Right containts all the elements of the left, remove i
          if (OB_FAIL(removed_idx.add_member(i))) {
            LOG_WARN("failed to add member", K(ret), K(i));
O
oceanbase-admin 已提交
10749 10750 10751 10752
          }
        }
      }
    }
W
wangzelin.wzl 已提交
10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766
  }

  // get unique pwj constraints
  if (OB_SUCC(ret) && !removed_idx.is_empty()) {
    ObSEArray<ObPwjConstraint *, 8> tmp_constraints;
    if (OB_FAIL(tmp_constraints.assign(pwj_constraints))) {
      LOG_WARN("failed to assign strict constraints", K(ret));
    } else {
      pwj_constraints.reuse();
      for (int64_t i = 0; OB_SUCC(ret) && i < tmp_constraints.count(); ++i) {
        if (!removed_idx.has_member(i) &&
            OB_FAIL(pwj_constraints.push_back(tmp_constraints.at(i)))) {
          LOG_WARN("failed to push back pwj constraint", K(ret));
        }
O
oceanbase-admin 已提交
10767 10768 10769 10770 10771 10772
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
10773
EqualSets* ObLogPlan::create_equal_sets()
O
oceanbase-admin 已提交
10774
{
W
wangzelin.wzl 已提交
10775 10776 10777 10778
  EqualSets *esets = NULL;
  void *ptr = NULL;
  if (OB_LIKELY(NULL != (ptr = get_allocator().alloc(sizeof(EqualSets))))) {
    esets = new (ptr) EqualSets();
O
oceanbase-admin 已提交
10779
  }
W
wangzelin.wzl 已提交
10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790
  return esets;
}

ObJoinOrder* ObLogPlan::create_join_order(PathType type)
{
  void *ptr = NULL;
  ObJoinOrder *join_order = NULL;
  if (OB_LIKELY(NULL != (ptr = get_allocator().alloc(sizeof(ObJoinOrder))))) {
    join_order = new (ptr) ObJoinOrder(&get_allocator(), this, type);
  }
  return join_order;
O
oceanbase-admin 已提交
10791 10792
}

W
wangzelin.wzl 已提交
10793 10794
// 将pwj约束每一个分区中的值按照从小到大的顺序排列
int ObLogPlan::sort_pwj_constraint(ObLocationConstraintContext &location_constraint) const
O
oceanbase-admin 已提交
10795 10796
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813
  ObIArray<ObPwjConstraint *> &strict_pwj_cons = location_constraint.strict_constraints_;
  ObIArray<ObPwjConstraint *> &non_strict_pwj_cons = location_constraint.non_strict_constraints_;
  ObPwjConstraint *cur_cons = NULL;
  for (int64_t i = 0; OB_SUCC(ret) && i < strict_pwj_cons.count(); ++i) {
    if (OB_ISNULL(cur_cons = strict_pwj_cons.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(i));
    } else {
      std::sort(&cur_cons->at(0), &cur_cons->at(0) + cur_cons->count());
    }
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < non_strict_pwj_cons.count(); ++i) {
    if (OB_ISNULL(cur_cons = non_strict_pwj_cons.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret), K(i));
    } else {
      std::sort(&cur_cons->at(0), &cur_cons->at(0) + cur_cons->count());
O
oceanbase-admin 已提交
10814 10815 10816 10817 10818
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
10819
int ObLogPlan::check_enable_plan_expiration(bool &enable) const
O
oceanbase-admin 已提交
10820 10821
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
10822 10823 10824 10825
  ObSQLSessionInfo *session = NULL;
  enable = false;
  if (OB_ISNULL(get_stmt()) ||
      OB_ISNULL(session = optimizer_context_.get_session_info())) {
O
oceanbase-admin 已提交
10826
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
10827 10828 10829 10830 10831 10832
    LOG_WARN("stmt is null", K(ret));
  } else if (!get_stmt()->is_select_stmt()) {
    // do nothing
  } else if (optimizer_context_.get_phy_plan_type() != OB_PHY_PLAN_LOCAL &&
             optimizer_context_.get_phy_plan_type() != OB_PHY_PLAN_DISTRIBUTED) {
    // do nothing
O
oceanbase-admin 已提交
10833
  } else {
W
wangzelin.wzl 已提交
10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855
    enable = true;
  }
  return ret;
}

bool ObLogPlan::need_consistent_read() const
{
  bool bret = true;
  if (OB_NOT_NULL(root_) && OB_NOT_NULL(get_stmt()) && OB_NOT_NULL(get_optimizer_context().get_query_ctx())) {
    //保守起见,这里只放开对insert/replace语句的限制
    //即insert/replace中table set为空的时候代表不依赖consistent read
    if (stmt::T_INSERT == get_stmt()->get_stmt_type()) {
      const ObInsertStmt *insert_stmt = static_cast<const ObInsertStmt*>(get_stmt());
      if (!insert_stmt->is_replace() && !insert_stmt->is_insert_up()) {
        uint64_t insert_table_id = insert_stmt->get_insert_table_info().table_id_;
        bool found_other_table = false;
        for (int64_t i = 0;
            !found_other_table && i < get_optimizer_context().get_table_partition_info().count(); ++i) {
          const ObTablePartitionInfo *part_info = get_optimizer_context().get_table_partition_info().at(i);
          if (OB_NOT_NULL(part_info) && part_info->get_table_id() != insert_table_id) {
            found_other_table = true;
          }
O
oceanbase-admin 已提交
10856
        }
W
wangzelin.wzl 已提交
10857
        bret = found_other_table;
O
oceanbase-admin 已提交
10858 10859 10860
      }
    }
  }
W
wangzelin.wzl 已提交
10861
  return bret;
O
oceanbase-admin 已提交
10862 10863
}

W
wangzelin.wzl 已提交
10864 10865 10866 10867 10868 10869 10870 10871
/*
 * for update/delete/select-for-update stmt
 */
int ObLogPlan::check_need_multi_partition_dml(const ObDMLStmt &stmt,
                                              ObLogicalOperator &top,
                                              const ObIArray<IndexDMLInfo *> &index_dml_infos,
                                              bool &is_multi_part_dml,
                                              bool &is_result_local)
O
oceanbase-admin 已提交
10872 10873
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
10874 10875 10876
  is_multi_part_dml = false;
  is_result_local = false;
  if (OB_UNLIKELY(index_dml_infos.empty())) {
O
oceanbase-admin 已提交
10877
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888
    LOG_WARN("index dml info is empty", K(ret));
  } else if (stmt.has_instead_of_trigger()) {
    is_multi_part_dml = true;
    is_result_local = true;
  } else if (OB_FAIL(check_stmt_need_multi_partition_dml(stmt,
                                                         index_dml_infos,
                                                         is_multi_part_dml))) {
    LOG_WARN("failed to check stmt need multi partition dml", K(ret));
  } else if (is_multi_part_dml) {
    /*do nothing*/
  } else if (OB_UNLIKELY(index_dml_infos.empty()) || OB_ISNULL(index_dml_infos.at(0))) {
O
oceanbase-admin 已提交
10889
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940
    LOG_WARN("invalid index dml info", K(ret));
  } else if (OB_FAIL(check_location_need_multi_partition_dml(top,
                                                             index_dml_infos.at(0)->loc_table_id_,
                                                             is_multi_part_dml,
                                                             is_result_local))) {
    LOG_WARN("failed to check whether location need multi-partition dml", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

/*
 * this function is used for select-for-update/update/delete
 */
int ObLogPlan::check_stmt_need_multi_partition_dml(const ObDMLStmt &stmt,
                                                   const ObIArray<IndexDMLInfo *> &index_dml_infos,
                                                   bool &is_multi_part_dml)
{
  int ret = OB_SUCCESS;
  is_multi_part_dml = index_dml_infos.count() > 1
      || optimizer_context_.is_batched_multi_stmt()
      //ddl sql can produce a PDML plan with PL UDF,
      //some PL UDF that cannot be executed in a PDML plan
      //will be forbidden during the execution phase
      || optimizer_context_.contain_user_nested_sql();
  if (!is_multi_part_dml && stmt.is_update_stmt()) {
    const ObUpdateStmt &update_stmt = static_cast<const ObUpdateStmt&>(stmt);
    bool part_key_update = false;
    TableItem *table_item = NULL;
    ObSchemaGetterGuard *schema_guard = get_optimizer_context().get_schema_guard();
    ObSQLSessionInfo* session_info = get_optimizer_context().get_session_info();
    const ObTableSchema *table_schema = NULL;
    ObUpdateTableInfo* table_info = nullptr;
    if (OB_FAIL(update_stmt.part_key_is_updated(part_key_update))) {
      LOG_WARN("failed to check part key is updated", K(ret));
    } else if (!part_key_update) {
      // do nothing
    } else if (OB_ISNULL(schema_guard) || OB_ISNULL(session_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected error", K(schema_guard), K(session_info), K(ret));
    } else if (OB_UNLIKELY(update_stmt.get_update_table_info().count() != 1) ||
               OB_ISNULL(table_info = update_stmt.get_update_table_info().at(0))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected error", K(ret), K(update_stmt.get_update_table_info()));
    } else if (OB_FAIL(schema_guard->get_table_schema(session_info->get_effective_tenant_id(),
                                                      table_info->ref_table_id_, table_schema))) {
      LOG_WARN("get table schema failed", K(ret));
    } else if (OB_ISNULL(table_schema)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else {
      is_multi_part_dml = !ObSQLUtils::is_one_part_table_can_skip_part_calc(*table_schema);
O
oceanbase-admin 已提交
10941
    }
10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961
  } else if (!is_multi_part_dml && stmt.is_select_stmt() && stmt.has_for_update()) {
    ObSchemaGetterGuard *schema_guard = get_optimizer_context().get_schema_guard();
    ObSQLSessionInfo* session_info = get_optimizer_context().get_session_info();
    const ObTableSchema *table_schema = NULL;
    if (OB_ISNULL(index_dml_infos.at(0))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("invalid index dml info", K(ret));
    } else if (OB_ISNULL(schema_guard) || OB_ISNULL(session_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected error", K(schema_guard), K(session_info), K(ret));
    } else if (OB_FAIL(schema_guard->get_table_schema(session_info->get_effective_tenant_id(),
                                                      index_dml_infos.at(0)->ref_table_id_,
                                                      table_schema))) {
      LOG_WARN("get table schema failed", K(ret));
    } else if (OB_ISNULL(table_schema)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else {
      is_multi_part_dml = table_schema->is_partitioned_table();
    }
O
oceanbase-admin 已提交
10962 10963 10964 10965
  }
  return ret;
}

W
wangzelin.wzl 已提交
10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000
/*
 * this function is used for select-for-update/update/delete
 */
int ObLogPlan::check_location_need_multi_partition_dml(ObLogicalOperator &top,
                                                       uint64_t table_id,
                                                       bool &is_multi_part_dml,
                                                       bool &is_result_local)
{
  int ret = OB_SUCCESS;
  ObShardingInfo *source_sharding = NULL;
  ObTablePartitionInfo *source_table_part = NULL;
  ObTableLocationType source_loc_type = OB_TBL_LOCATION_UNINITIALIZED;
  is_multi_part_dml = false;
  is_result_local = false;
  if (OB_FAIL(get_source_table_info(top,
                                    table_id,
                                    source_sharding,
                                    source_table_part))) {
    LOG_WARN("failed to get dml table sharding info", K(ret), K(table_id), K(source_sharding));
  } else if (OB_ISNULL(source_sharding) || OB_ISNULL(source_table_part)) {
    is_multi_part_dml = true;
    is_result_local = true;
  } else if (OB_FAIL(source_table_part->get_location_type(
                                          get_optimizer_context().get_local_server_addr(),
                                          source_loc_type))) {
    LOG_WARN("failed get location type", K(ret));
  } else if (source_sharding->is_match_all() || OB_TBL_LOCATION_ALL == source_loc_type) {
    is_multi_part_dml = true;
    is_result_local = true;
  } else if (source_sharding->is_local()) {
    is_multi_part_dml = false;
    is_result_local = true;
  } else if (source_sharding->is_distributed() && OB_TBL_LOCATION_REMOTE == source_loc_type) {
    is_multi_part_dml = true;
    is_result_local = true;
O
oceanbase-admin 已提交
11001
  } else {
W
wangzelin.wzl 已提交
11002 11003 11004 11005 11006 11007
    // dml 开启 PX模式下决定是否使用 multi part 计划
    ObShardingInfo *top_sharding = top.get_strong_sharding();
    if (top.is_exchange_allocated() ||
        (NULL != top_sharding && top_sharding->is_distributed_without_table_location())) {
      is_multi_part_dml = true;
      is_result_local = true;
O
oceanbase-admin 已提交
11008
    } else {
W
wangzelin.wzl 已提交
11009 11010
      is_multi_part_dml = false;
      is_result_local = source_sharding->is_local();
O
oceanbase-admin 已提交
11011 11012
    }
  }
W
wangzelin.wzl 已提交
11013 11014 11015 11016
  if (OB_SUCC(ret)) {
    LOG_TRACE("succeed to check location need multi-partition update", K(table_id), K(is_multi_part_dml),
        K(is_result_local));
  }
O
oceanbase-admin 已提交
11017 11018 11019
  return ret;
}

W
wangzelin.wzl 已提交
11020 11021 11022 11023
int ObLogPlan::get_source_table_info(ObLogicalOperator &top,
                                     uint64_t source_table_id,
                                     ObShardingInfo *&source_sharding,
                                     ObTablePartitionInfo *&source_table_part)
O
oceanbase-admin 已提交
11024 11025
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038
  bool is_stack_overflow = false;
  source_sharding = NULL;
  source_table_part = NULL;
  if (OB_FAIL(check_stack_overflow(is_stack_overflow))) {
    LOG_WARN("check stack overflow failed", K(ret));
  } else if (is_stack_overflow) {
    ret = OB_SIZE_OVERFLOW;
    LOG_WARN("too deep recursive", K(ret));
  } else if (top.is_table_scan()) {
    ObLogTableScan &table_scan = static_cast<ObLogTableScan&>(top);
    if (table_scan.get_table_id() == source_table_id && !table_scan.get_is_index_global()) {
      source_sharding = table_scan.get_strong_sharding();
      source_table_part = table_scan.get_table_partition_info();
O
oceanbase-admin 已提交
11039
    }
W
wangzelin.wzl 已提交
11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065
  }
  for (int64_t i = 0; OB_SUCC(ret) && NULL == source_sharding
                      && i < top.get_num_of_child(); ++i) {
    if (OB_ISNULL(top.get_child(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(SMART_CALL(get_source_table_info(*top.get_child(i),
                                                        source_table_id,
                                                        source_sharding,
                                                        source_table_part)))) {
      LOG_WARN("get source sharding info recursive failed", K(ret), K(source_table_id));
    }
  }
  if (OB_SUCC(ret) && OB_UNLIKELY(log_op_def::ObLogOpType::LOG_SET == top.get_type()
                                  && NULL != source_sharding)) {
    int64_t total_part_cnt = 0;
    if (OB_FAIL(source_sharding->get_total_part_cnt(total_part_cnt))) {
      LOG_WARN("failed to get total part cnt", K(ret), K(*source_sharding));
    } else if (total_part_cnt > 1) {
      /*  create table t3(c1 int, c2 int, c3 int, index idx(c2)) partition by hash(c1) partitions 5;
      *  update t3 set c3 = 3  where (c1 = 1 or c2 =1);
      *  If this DML happend or expansion transform, we need multi table dml,
      *  here set source_sharding to null.
      */
      source_sharding = NULL;
      LOG_TRACE("partition table happend or expansion, need multi-table dml");
O
oceanbase-admin 已提交
11066 11067 11068 11069 11070
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
11071 11072

int ObLogPlan::collect_subq_pushdown_filter_table_relids(const ObIArray<ObRawExpr*> &conditions)
O
oceanbase-admin 已提交
11073 11074
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11075 11076 11077 11078
  const ObDMLStmt *stmt = NULL;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid stmt", K(ret));
O
oceanbase-admin 已提交
11079
  } else {
W
wangzelin.wzl 已提交
11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124
    for (int64_t i = 0; i < conditions.count(); ++i) {
      ObRawExpr *expr = conditions.at(i);
      if (OB_ISNULL(expr)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("invalid expr", K(expr));
      } else if (!expr->has_flag(CNT_DYNAMIC_PARAM) ||
                 expr->has_flag(CNT_ONETIME) ||
                 expr->has_flag(CNT_PSEUDO_COLUMN) ||
                 expr->has_flag(CNT_PRIOR) ||
                 expr->has_flag(CNT_ROWNUM) ||
                 T_OP_NE == expr->get_expr_type()) {
        // do nothing
      } else {
        for (int64_t j = 0; j < expr->get_children_count(); ++j) {
          ObRawExpr *child = expr->get_param_expr(j);
          if (OB_ISNULL(child)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("invalid child", K(child));
          } else if (!child->is_column_ref_expr()) {
            // do nothing
          } else {
            ObColumnRefRawExpr *col_expr = static_cast<ObColumnRefRawExpr*>(child);
            ObSEArray<ObColumnRefRawExpr*, 4> pushdown_col_exprs;
            bool contribute_query_range = false;
            if (OB_FAIL(ObTransformUtils::get_simple_filter_column(stmt,
                                                                   expr,
                                                                   col_expr->get_table_id(),
                                                                   pushdown_col_exprs))) {
              LOG_WARN("failed to get simple filter column", K(ret));
            } else if (!ObOptimizerUtil::find_item(pushdown_col_exprs, col_expr)) {
              // do nothing
            } else if (OB_FAIL(ObTransformUtils::is_match_index(get_optimizer_context().get_sql_schema_guard(),
                                                                stmt,
                                                                col_expr,
                                                                contribute_query_range))) {
              LOG_WARN("failed to check is match index", K(ret));
            } else if (!contribute_query_range) {
              // do nothing
            } else {
              int64_t table_index = stmt->get_table_bit_index(col_expr->get_table_id());
              if (OB_FAIL(subq_pushdown_filter_table_set_.add_member(table_index))) {
                LOG_WARN("failed to add members", K(ret));
              }
            }
          }
O
oceanbase-admin 已提交
11125 11126 11127 11128 11129 11130 11131
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
11132
int ObLogPlan::init_plan_info()
O
oceanbase-admin 已提交
11133 11134
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11135 11136 11137 11138
  ObSqlSchemaGuard *schema_guard = NULL;
  ObQueryCtx* query_ctx = NULL;
  if (OB_ISNULL(schema_guard = get_optimizer_context().get_sql_schema_guard())
      || OB_ISNULL(get_stmt()) || OB_ISNULL(query_ctx = get_optimizer_context().get_query_ctx())) {
O
oceanbase-admin 已提交
11139
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
11140 11141 11142
    LOG_WARN("get unexpected null", K(get_stmt()), K(ret));
  } else if (OB_FAIL(get_stmt()->get_stmt_equal_sets(equal_sets_,
                                                     allocator_,
O
obdev 已提交
11143
                                                     false))) {
W
wangzelin.wzl 已提交
11144 11145 11146 11147 11148 11149 11150
    LOG_WARN("failed to get stmt equal sets", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::compute_const_exprs(get_stmt()->get_condition_exprs(),
                                                          get_const_exprs()))) {
    LOG_WARN("failed to compute const equivalent exprs", K(ret));
  } else if (OB_FAIL(log_plan_hint_.init_log_plan_hint(*schema_guard, *get_stmt(),
                                                       query_ctx->get_query_hint()))) {
    LOG_WARN("failed to init log plan hint", K(ret));
O
obdev 已提交
11151 11152
  } else if (OB_FAIL(init_onetime_subquery_info())) {
    LOG_WARN("failed to extract onetime_exprs", K(ret));
O
oceanbase-admin 已提交
11153 11154 11155 11156
  }
  return ret;
}

W
wangzelin.wzl 已提交
11157
int ObLogPlan::generate_plan()
O
oceanbase-admin 已提交
11158 11159
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11160 11161
  const ObDMLStmt *stmt = NULL;
  if (OB_ISNULL(stmt = get_stmt())) {
O
oceanbase-admin 已提交
11162
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
11163 11164 11165 11166
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(generate_raw_plan())) {
    LOG_WARN("fail to generate raw plan", K(ret));
  } else if (stmt->is_explain_stmt() || stmt->is_help_stmt()) {
O
oceanbase-admin 已提交
11167
    /*do nothing*/
W
wangzelin.wzl 已提交
11168 11169
  } else if (OB_FAIL(do_post_plan_processing())) {
    LOG_WARN("failed to post plan processing", K(ret));
O
obdev 已提交
11170
  } else if (OB_FAIL(plan_traverse_loop(BLOOM_FILTER,
W
wangzelin.wzl 已提交
11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181
                                        ALLOC_GI,
                                        PX_PIPE_BLOCKING,
                                        ALLOC_MONITORING_DUMP,
                                        OPERATOR_NUMBERING,
                                        PX_RESCAN,
                                        EXCHANGE_NUMBERING,
                                        ALLOC_EXPR,
                                        PROJECT_PRUNING,
                                        GEN_SIGNATURE,
                                        GEN_LOCATION_CONSTRAINT,
                                        PX_ESTIMATE_SIZE,
O
obdev 已提交
11182 11183
                                        ALLOC_STARTUP_EXPR,
                                        COLLECT_BATCH_EXEC_PARAM))) {
W
wangzelin.wzl 已提交
11184 11185 11186 11187 11188 11189 11190
    LOG_WARN("failed to do plan traverse", K(ret));
  } else if (OB_FAIL(do_post_traverse_processing())) {
    LOG_WARN("failed to post traverse processing", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

O
obdev 已提交
11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213
int ObLogPlan::generate_raw_plan()
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = NULL;
  uint64_t dblink_id = OB_INVALID_ID;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (FALSE_IT(dblink_id = stmt->get_dblink_id())) {
  } else if (OB_INVALID_ID == dblink_id && OB_FAIL(generate_normal_raw_plan())) {
    LOG_WARN("fail to generate normal raw plan", K(ret));
  } else if (OB_INVALID_ID != dblink_id && OB_FAIL(generate_dblink_raw_plan())) {
    LOG_WARN("fail to generate dblink raw plan", K(ret));
  }
  return ret;
}

int ObLogPlan::generate_dblink_raw_plan()
{
  int ret = OB_SUCCESS;
  return ret;
}

W
wangzelin.wzl 已提交
11214 11215 11216 11217 11218
int ObLogPlan::do_post_traverse_processing()
{
  int ret = OB_SUCCESS;
  ObLogicalOperator *root = NULL;
  if (OB_ISNULL(root = get_plan_root())) {
O
oceanbase-admin 已提交
11219
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
11220
    LOG_WARN("get unexpected null", K(ret));
O
obdev 已提交
11221 11222
  } else if (OB_FAIL(replace_generate_column_exprs(root))) {
    LOG_WARN("failed to replace generate column exprs", K(ret));
W
wangzelin.wzl 已提交
11223 11224 11225
  } else if (OB_FAIL(calc_plan_resource())) {
    LOG_WARN("fail calc plan resource", K(ret));
  } else { /*do nothing*/ }
O
oceanbase-admin 已提交
11226 11227 11228
  return ret;
}

O
obdev 已提交
11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258
// replace generated column exprs.
int ObLogPlan::replace_generate_column_exprs(ObLogicalOperator *op)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid op", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); ++i) {
    ObLogicalOperator *child = op->get_child(i);
    if (OB_ISNULL(child)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("invalid child", K(ret));
    } else if (OB_FAIL(SMART_CALL(replace_generate_column_exprs(child)))) {
      LOG_WARN("failed to replace generate column expr", K(ret));
    } else {/*do nothing*/}
  }
  if (OB_FAIL(ret)) {
  } else if (op->get_type() == log_op_def::LOG_TABLE_SCAN) {
    // In the table_scan scenario, it is necessary to distinguish the three scenarios
    // of the main table, the index table and the index back table to determine whether
    // to replace the expression of the virtual generated column
    ObLogTableScan *scan_op = static_cast<ObLogTableScan*>(op);
    if (OB_FAIL(generate_tsc_replace_exprs_pair(scan_op))) {
      LOG_WARN("failed to generate replace generated tsc expr", K(ret));
    } else if (OB_FAIL(scan_op->generate_ddl_output_column_ids())) {
      LOG_WARN("fail to generate ddl output column ids");
    } else if (OB_FAIL(scan_op->replace_gen_col_op_exprs(gen_col_replaced_exprs_))) {
      LOG_WARN("failed to replace generated tsc expr", K(ret));
    }
O
obdev 已提交
11259 11260
  } else if ((op->get_type() == log_op_def::LOG_INSERT) ||
            ((op->get_type() == log_op_def::LOG_INSERT_ALL))) {
O
obdev 已提交
11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393
    ObLogDelUpd *insert_op = static_cast<ObLogDelUpd*>(op);
    if (OB_FAIL(generate_ins_replace_exprs_pair(insert_op))) {
      LOG_WARN("fail to generate insert replace exprs pair");
    } else if (OB_FAIL(generate_old_column_values_exprs(insert_op))) {
      LOG_WARN("fail to generate index dml info column old values exprs");
    } else if (OB_FAIL(insert_op->replace_op_exprs(gen_col_replaced_exprs_))) {
      LOG_WARN("failed to replace generated exprs", K(ret));
    }
  } else {
    if (OB_FAIL(generate_old_column_values_exprs(op))) {
      LOG_WARN("fail to generate index dml info column old values exprs");
    } else if (OB_FAIL(op->replace_op_exprs(gen_col_replaced_exprs_))) {
      LOG_WARN("failed to replace generated exprs", K(ret));
    }
  }
  return ret;
}

int ObLogPlan::generate_old_column_exprs(ObIArray<IndexDMLInfo*> &index_dml_infos)
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < index_dml_infos.count(); ++i) {
    if (OB_ISNULL(index_dml_infos.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("invalid index_dml_info", K(ret));
    } else if (OB_FAIL(index_dml_infos.at(i)->generate_column_old_values_exprs())) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    }
  }
  return ret;
}

// construct index_dml_info_column_old_values_exprs.
int ObLogPlan::generate_old_column_values_exprs(ObLogicalOperator *root)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(root)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid op", K(ret));
  } else if (root->get_type() == log_op_def::LOG_UPDATE ||
      root->get_type() == log_op_def::LOG_DELETE) {
    ObLogDelUpd *del_upd = static_cast<ObLogDelUpd*>(root);
    if (OB_FAIL(generate_old_column_exprs(del_upd->get_index_dml_infos()))) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    }
  } else if (root->get_type() == log_op_def::LOG_INSERT) {
    ObLogInsert *insert_op = static_cast<ObLogInsert*>(root);
    if (OB_FAIL(generate_old_column_exprs(insert_op->get_insert_up_index_dml_infos()))) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    } else if (OB_FAIL(generate_old_column_exprs(insert_op->get_replace_index_dml_infos()))) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    }
  } else if (root->get_type() == log_op_def::LOG_MERGE) {
    ObLogMerge *merge_op = static_cast<ObLogMerge*>(root);
    if (OB_FAIL(generate_old_column_exprs(merge_op->get_update_infos()))) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    } else if (OB_FAIL(generate_old_column_exprs(merge_op->get_delete_infos()))) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    }
  } else if (root->get_type() == log_op_def::LOG_FOR_UPD) {
    ObLogForUpdate *for_upd_op = static_cast<ObLogForUpdate*>(root);
    if (OB_FAIL(generate_old_column_exprs(for_upd_op->get_index_dml_infos()))) {
      LOG_WARN("failed to generate column old values exprs", K(ret));
    }
  }
  return ret;
}

int ObLogPlan::generate_tsc_replace_exprs_pair(ObLogTableScan *op)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid op", K(ret));
  } else if (op->is_index_scan() && !(op->get_index_back())) {
    //no need replace in index table non-return table scenario.
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < op->get_access_exprs().count(); ++i) {
      ObRawExpr *expr = op->get_access_exprs().at(i);
      if (expr->is_column_ref_expr() &&
          static_cast<ObColumnRefRawExpr *>(expr)->is_virtual_generated_column()) {
        ObRawExpr *&dependant_expr = static_cast<ObColumnRefRawExpr *>(
                                    expr)->get_dependant_expr();
        if (dependant_expr->is_const_expr()) {
          ObRawExpr *new_expr = NULL;
          ObSQLSessionInfo* session_info = get_optimizer_context().get_session_info();
          if (OB_ISNULL(session_info)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("get unexpected null", K(ret), K(session_info));
          } else if (OB_FAIL(ObRawExprUtils::build_remove_const_expr(
                                    get_optimizer_context().get_expr_factory(),
                                    *session_info,
                                    dependant_expr,
                                    new_expr))) {
            LOG_WARN("failed to build remove const expr", K(ret));
          } else {
            if (NULL != new_expr) {
              dependant_expr = new_expr;
            }
          }
        }
        if (OB_SUCC(ret) && OB_FAIL(gen_col_replaced_exprs_.push_back(
                    std::pair<ObRawExpr *, ObRawExpr *>(expr, dependant_expr)))) {
          LOG_WARN("failed to push back generate replace pair", K(ret));
        }
      }
    }
  }
  return ret;
}

int ObLogPlan::generate_ins_replace_exprs_pair(ObLogDelUpd *op)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid op", K(ret));
  } else if (NULL != op->get_table_columns()) {
    for (int64_t i = 0; OB_SUCC(ret) && i < op->get_table_columns()->count(); ++i) {
      ObColumnRefRawExpr *expr = op->get_table_columns()->at(i);
      if (expr->is_virtual_generated_column()) {
        ObRawExpr *dependant_expr = static_cast<ObColumnRefRawExpr *>(
                                    expr)->get_dependant_expr();
        if (OB_FAIL(gen_col_replaced_exprs_.push_back(
                    std::pair<ObRawExpr *, ObRawExpr *>(expr, dependant_expr)))) {
          LOG_WARN("failed to push back generate replace pair", K(ret));
        }
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
11394
int ObLogPlan::do_post_plan_processing()
O
oceanbase-admin 已提交
11395 11396
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424
  ObLogicalOperator *root = NULL;
  if (OB_ISNULL(root = get_plan_root())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(adjust_final_plan_info(root))) {
    LOG_WARN("failed to adjust parent-child relationship", K(ret));
  } else if (OB_FAIL(set_duplicated_table_location(root, OB_INVALID_INDEX))) {
    LOG_WARN("failed to set duplicated table location", K(ret));
  } else if (OB_FAIL(collect_table_location(root))) {
    LOG_WARN("failed to collect table location", K(ret));
  } else if (OB_FAIL(build_location_related_tablet_ids())) {
    LOG_WARN("build location related tablet ids failed", K(ret));
  } else { /*do nothing*/ }
  return ret;
}

int ObLogPlan::adjust_final_plan_info(ObLogicalOperator *&op)
{
  int ret = OB_SUCCESS;
  bool is_stack_overflow = false;
  if (OB_ISNULL(op) || OB_ISNULL(op->get_plan()) || OB_ISNULL(op->get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(check_stack_overflow(is_stack_overflow))) {
    LOG_WARN("check stack overflow failed", K(ret));
  } else if (is_stack_overflow) {
    ret = OB_SIZE_OVERFLOW;
    LOG_WARN("too deep recursive", K(ret));
O
oceanbase-admin 已提交
11425
  } else {
W
wangzelin.wzl 已提交
11426 11427 11428
    for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); i++) {
      ObLogicalOperator *child = NULL;
      if (OB_ISNULL(child = op->get_child(i)) || OB_ISNULL(child->get_plan())) {
O
oceanbase-admin 已提交
11429
        ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443
        LOG_WARN("get unexpected null", K(child), K(ret));
      } else {
        child->set_parent(op);
        op->set_child(i, child);
        if (op->get_type() == log_op_def::LOG_SET ||
            op->get_type() == log_op_def::LOG_SUBPLAN_SCAN ||
            op->get_type() == log_op_def::LOG_UNPIVOT ||
            (op->get_type() == log_op_def::LOG_SUBPLAN_FILTER && i > 0)) {
          child->mark_is_plan_root();
          child->get_plan()->set_plan_root(child);
        }
        if (OB_FAIL(SMART_CALL(adjust_final_plan_info(child)))) {
          LOG_WARN("failed to adjust parent-child relationship", K(ret));
        } else { /*do nothing*/ }
O
oceanbase-admin 已提交
11444 11445
      }
    }
W
wangzelin.wzl 已提交
11446 11447 11448 11449 11450 11451 11452
    if (OB_SUCC(ret) && op->get_type() == LOG_SUBPLAN_FILTER) {
      ObLogSubPlanFilter *subplan_filter = static_cast<ObLogSubPlanFilter *>(op);
      if (OB_FAIL(subplan_filter->allocate_subquery_id())) {
        LOG_WARN("failed to allocate subquery id", K(ret));
      } else if (!subplan_filter->is_update_set()) {
        // do nothing
      } else if (OB_UNLIKELY(!subplan_filter->get_stmt()->is_update_stmt())) {
O
oceanbase-admin 已提交
11453
        ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
11454
        LOG_WARN("update stmt is expected", K(ret));
O
oceanbase-admin 已提交
11455
      } else {
W
wangzelin.wzl 已提交
11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470
        ObUpdateLogPlan *plan = static_cast<ObUpdateLogPlan *>(op->get_plan());
        // stmt is only allowed to be modified in the function;
        ObUpdateStmt *stmt = const_cast<ObUpdateStmt* >(plan->get_stmt());
        if (OB_FAIL(plan->perform_vector_assign_expr_replacement(stmt))) {
          LOG_WARN("failed to perform vector assgin expr replace", K(ret));
        }
        for (int64_t i = 1; OB_SUCC(ret) && i < op->get_num_of_child(); ++i) {
          ObLogPlan *child_plan = NULL;
          if (OB_ISNULL(op->get_child(i)) ||
              OB_ISNULL(child_plan = op->get_child(i)->get_plan())) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("child expr is null", K(ret));
          } else if (OB_FAIL(append(plan->group_replaced_exprs_,
                                    child_plan->group_replaced_exprs_))) {
            LOG_WARN("failed to append group replaced exprs", K(ret));
O
obdev 已提交
11471 11472 11473
          } else if (OB_FAIL(append(plan->window_function_replaced_exprs_,
                                    child_plan->window_function_replaced_exprs_))) {
            LOG_WARN("failed to append window_function_replaced_exprs", K(ret));
W
wangzelin.wzl 已提交
11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523
          }
        }
      }
    }
    if (OB_SUCC(ret) && op->get_type() == LOG_INSERT && optimizer_context_.is_online_ddl()) {
      ObLogInsert *insert = static_cast<ObLogInsert *>(op);
      ObSchemaGetterGuard* schema_guard = optimizer_context_.get_schema_guard();
      ObSQLSessionInfo* session_info = optimizer_context_.get_session_info();
      IndexDMLInfo* index_dml_info = insert->get_index_dml_infos().at(0);
      TableItem* table_item = nullptr;
      const ObTableSchema *index_schema = nullptr;
      if (OB_ISNULL(get_stmt()) || OB_ISNULL(schema_guard) ||
          OB_ISNULL(session_info) || OB_ISNULL(index_dml_info) ||
          OB_ISNULL(table_item = get_stmt()->get_table_item_by_id(index_dml_info->table_id_))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret), K(schema_guard),
                    K(session_info), K(index_dml_info), K(table_item));
      } else if (OB_FAIL(schema_guard->get_table_schema(session_info->get_effective_tenant_id(),
                                                        table_item->ddl_table_id_, index_schema))) {
        LOG_WARN("failed to get table schema", K(ret));
      } else if (OB_ISNULL(index_schema)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("failed to get table schema", KPC(index_dml_info), K(ret));
      } else if (index_schema->is_index_table() && !index_schema->is_global_index_table()) {
        for (int64_t i = index_dml_info->column_exprs_.count() - 1; OB_SUCC(ret) && i >= 0; --i) {
          ObColumnRefRawExpr* column_expr = index_dml_info->column_exprs_.at(i);
          bool has_column = false;
          if (OB_ISNULL(column_expr)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("get unexpected null", K(ret));
          } else if (OB_FAIL(index_schema->has_column(column_expr->get_column_id(), has_column))) {
            LOG_WARN("failed to check table has column", K(ret));
          } else if (has_column) {
            // do nothing
          } else if (OB_FAIL(index_dml_info->column_exprs_.remove(i))) {
            LOG_WARN("failed to remove column exprs", K(ret));
          } else if (OB_FAIL(index_dml_info->column_convert_exprs_.remove(i))) {
            LOG_WARN("failed to remove column convert exprs", K(ret));
          }
        }
      }
    }
    if (OB_SUCC(ret) && NULL != (dynamic_cast<ObSelectLogPlan*>(op->get_plan()))) {
      ObSelectLogPlan *plan = static_cast<ObSelectLogPlan *>(op->get_plan());
      // stmt is only allowed to be modified in the function;
      ObSelectStmt *stmt = const_cast<ObSelectStmt* >(plan->get_stmt());
      if (!op->need_late_materialization()) {
        // do nothing
      } else if (OB_FAIL(plan->perform_late_materialization(stmt, op))) {
        LOG_WARN("failed to perform late materilization", K(ret), K(*stmt), K(*op));
O
oceanbase-admin 已提交
11524 11525
      }
    }
W
wangzelin.wzl 已提交
11526 11527 11528 11529 11530

    if (OB_SUCC(ret) && OB_NOT_NULL(get_optimizer_context().get_query_ctx())) {
      ObQueryCtx *query_ctx = get_optimizer_context().get_query_ctx();
      if (OB_FAIL(append(query_ctx->all_equal_param_constraints_, op->equal_param_constraints_))) {
        LOG_WARN("failed to push back equal param constraints", K(ret));
O
obdev 已提交
11531 11532 11533
      } else if (OB_FAIL(append(query_ctx->all_plan_const_param_constraints_,
                                op->const_param_constraints_))) {
        LOG_WARN("failed to push back equal param constraints", K(ret));
W
wangzelin.wzl 已提交
11534 11535 11536 11537 11538 11539
      } else if (OB_FAIL(append_array_no_dup(query_ctx->all_expr_constraints_,
                                             op->expr_constraints_))) {
        LOG_WARN("failed to append expr constraints", K(ret));
      }
    }

O
obdev 已提交
11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551
    if (OB_SUCC(ret) && op->get_type() == LOG_SET &&
        static_cast<ObLogSet*>(op)->is_recursive_union()) {
      ObLogicalOperator* right_child = NULL;
      if (OB_UNLIKELY(2 != op->get_num_of_child()) ||
          OB_ISNULL(right_child = op->get_child(ObLogicalOperator::second_child))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(op->get_name()));
      } else if (OB_FAIL(allocate_material_for_recursive_cte_plan(right_child->get_child_list()))) {
        LOG_WARN("faile to allocate material for recursive cte plan", K(ret));
      }
    }

Z
zzg19950727 已提交
11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564
    if (OB_SUCC(ret) && op->get_type() == LOG_SELECT_INTO && !op->is_plan_root() &&
        GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_4_1_0_0) {
      if (!op->get_stmt()->is_select_stmt()) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected stmt type", K(ret));
      } else {
        const ObSelectStmt *sel_stmt = static_cast<const ObSelectStmt*>(op->get_stmt());
        if (OB_FAIL(sel_stmt->get_select_exprs(op->get_output_exprs()))) {
          LOG_WARN("failed to get select exprs", K(ret));
        }
      }
    }

W
wangzelin.wzl 已提交
11565 11566 11567 11568 11569 11570 11571
    if (OB_SUCC(ret)) {
      if (op->is_plan_root() && OB_FAIL(op->set_plan_root_output_exprs())) {
        LOG_WARN("failed to add plan root exprs", K(ret));
      } else if (OB_FAIL(op->get_plan()->perform_group_by_pushdown(op))) {
        LOG_WARN("failed to perform group by push down", K(ret));
      } else if (OB_FAIL(op->get_plan()->perform_simplify_win_expr(op)))  {
        LOG_WARN("failed to perform simplify win expr", K(ret));
O
obdev 已提交
11572 11573 11574 11575
      } else if (OB_FAIL(op->get_plan()->perform_window_function_pushdown(op))) {
        LOG_WARN("failed to perform window function push down", K(ret));
      } else if (OB_FAIL(op->get_plan()->perform_adjust_onetime_expr(op))) {
        LOG_WARN("failed to perform adjust onetime expr", K(ret));
W
wangzelin.wzl 已提交
11576 11577 11578 11579 11580
      } else if (OB_FAIL(update_re_est_cost(op))) {
        LOG_WARN("failed to re est cost", K(ret));
      } else if (OB_FAIL(op->reorder_filter_exprs())) {
        LOG_WARN("failed to reorder filter exprs", K(ret));
      } else if (log_op_def::LOG_JOIN == op->get_type() &&
O
obdev 已提交
11581
                 OB_FAIL(static_cast<ObLogJoin*>(op)->check_and_set_use_batch())) {
W
wangzelin.wzl 已提交
11582
        LOG_WARN("failed to set use batch nlj", K(ret));
O
obdev 已提交
11583
      } else if (log_op_def::LOG_SUBPLAN_FILTER == op->get_type() &&
W
wangzelin.wzl 已提交
11584 11585 11586 11587
                 OB_FAIL(static_cast<ObLogSubPlanFilter*>(op)->check_and_set_use_batch())) {
        LOG_WARN("failed to set use batch spf", K(ret));
      } else { /*do nothing*/ }
    }
O
oceanbase-admin 已提交
11588 11589 11590 11591
  }
  return ret;
}

W
wangzelin.wzl 已提交
11592 11593 11594 11595
/*
 * re-estimate cost for limit-k
 */
int ObLogPlan::update_re_est_cost(ObLogicalOperator *op)
O
oceanbase-admin 已提交
11596 11597
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644
  EstimateCostInfo info;
  info.override_ = true;
  double cost = 0.0;
  double card = 0.0;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(op), K(ret));
  } else if (op->get_type() == log_op_def::LOG_JOIN) {
    ObLogJoin *join = static_cast<ObLogJoin*>(op);
    ObLogicalOperator *right_child = NULL;
    if (OB_ISNULL(right_child = join->get_child(ObLogicalOperator::second_child))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if ((ObJoinType::LEFT_SEMI_JOIN == join->get_join_type() ||
         ObJoinType::LEFT_ANTI_JOIN == join->get_join_type()) &&
         join->is_nlj_with_param_down()) {
      info.need_row_count_ = 1;
      if (OB_FAIL(right_child->re_est_cost(info, card, cost))) {
        LOG_WARN("failed to re-est cost", K(ret));
      } else { /*do nothing*/ }
    } else if (join->is_nlj_with_param_down() &&
               join->can_use_batch_nlj()) {
      //re est cost for inner path
      if (OB_FAIL(right_child->re_est_cost(info, card, cost))) {
        LOG_WARN("failed to re est cost", K(ret));
      }
    } else if (!join->get_join_filter_infos().empty()) {
      if (OB_FAIL(info.join_filter_infos_.assign(join->get_join_filter_infos()))) {
        LOG_WARN("failed to assign join filter infos", K(ret));
      } else if (OB_FAIL(right_child->re_est_cost(info, card, cost))) {
        LOG_WARN("failed to re est cost", K(ret));
      }
    }
  } else if (op->get_type() == log_op_def::LOG_LIMIT) {
    ObLogLimit *limit = static_cast<ObLogLimit*>(op);
    info.need_row_count_ = limit->get_card();
    if (limit->get_is_calc_found_rows() || NULL != limit->get_percent_expr()) {
      /*do nothing*/
    } else if (OB_FAIL(limit->re_est_cost(info, card, cost))) {
      LOG_WARN("failed to re-estimate cost", K(ret));
    } else { /*do nothing*/ }
  } else if (op->get_type() == log_op_def::LOG_COUNT) {
    ObLogCount *count = static_cast<ObLogCount*>(op);
    info.need_row_count_ = count->get_card();
    if (OB_FAIL(count->re_est_cost(info, card, cost))) {
      LOG_WARN("failed to re-estimate cost", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
11645 11646 11647 11648
  }
  return ret;
}

W
wangzelin.wzl 已提交
11649
int ObLogPlan::set_duplicated_table_location(ObLogicalOperator *op, int64_t dup_table_pos)
O
oceanbase-admin 已提交
11650 11651
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671
  ObLogicalOperator *child = NULL;
  bool is_stack_overflow = false;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(check_stack_overflow(is_stack_overflow))) {
    LOG_WARN("check stack overflow failed", K(ret));
  } else if (is_stack_overflow) {
    ret = OB_SIZE_OVERFLOW;
    LOG_WARN("too deep recursive", K(ret));
  } else if (log_op_def::LOG_TABLE_SCAN == op->get_type() && NULL != op->get_strong_sharding() &&
             op->get_strong_sharding()->get_can_reselect_replica() &&
             OB_INVALID_INDEX != dup_table_pos) {
    ObLogTableScan *table_scan = static_cast<ObLogTableScan*>(op);
    ObCandiTableLoc &phy_loc =
        table_scan->get_table_partition_info()->get_phy_tbl_location_info_for_update();
    for (int64_t i = 0; OB_SUCC(ret) && i < phy_loc.get_partition_cnt(); ++i) {
      ObCandiTabletLoc &phy_part_loc =
           phy_loc.get_phy_part_loc_info_list_for_update().at(i);
      phy_part_loc.set_selected_replica_idx(dup_table_pos);
O
oceanbase-admin 已提交
11672
    }
W
wangzelin.wzl 已提交
11673 11674 11675 11676 11677 11678 11679 11680
  } else {
    ObSEArray<int64_t, 8> dup_table_pos_list;
    if (op->get_dup_table_pos().empty()) {
      for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); i++) {
        if (OB_FAIL(dup_table_pos_list.push_back(dup_table_pos))) {
          LOG_WARN("failed to push back into array", K(ret));
        } else { /*do nothing*/ }
      }
O
oceanbase-admin 已提交
11681
    } else {
W
wangzelin.wzl 已提交
11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705
      for (int64_t i = 0; OB_SUCC(ret) && i < op->get_dup_table_pos().count(); i++) {
        if (OB_INVALID_INDEX == op->get_dup_table_pos().at(i)) {
          ret = dup_table_pos_list.push_back(dup_table_pos);
        } else {
          ret = dup_table_pos_list.push_back(op->get_dup_table_pos().at(i));
        }
      }
    }
    if (OB_FAIL(ret)) {
      /*do nothing*/
    } else if (OB_UNLIKELY(dup_table_pos_list.count() != op->get_num_of_child())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(dup_table_pos_list.count()),
          K(op->get_num_of_child()), K(ret));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); i++) {
        if (OB_ISNULL(child = op->get_child(i))) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(ret));
        } else if (OB_FAIL(SMART_CALL(set_duplicated_table_location(child,
                                                                    dup_table_pos_list.at(i))))) {
          LOG_WARN("failed to set duplicated table location", K(ret));
        } else { /*do nothing*/ }
      }
O
oceanbase-admin 已提交
11706 11707 11708 11709 11710
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
11711 11712
int ObLogPlan::gen_das_table_location_info(ObLogTableScan *table_scan,
                                           ObTablePartitionInfo *&table_partition_info)
O
oceanbase-admin 已提交
11713 11714
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739
  ObSqlSchemaGuard *sql_schema_guard = NULL;
  const ObDMLStmt *stmt = NULL;
  const TableItem *table_item = NULL;
  ObSEArray<ObRawExpr *, 8> all_filters;
  bool has_dppr = false;
  ObOptimizerContext *opt_ctx = &get_optimizer_context();
  if (OB_ISNULL(table_scan) ||
      OB_ISNULL(table_partition_info) ||
      OB_ISNULL(sql_schema_guard = opt_ctx->get_sql_schema_guard()) ||
      OB_ISNULL(stmt = table_scan->get_stmt()) ||
      OB_ISNULL(table_item = stmt->get_table_item_by_id(table_scan->get_table_id())) ||
      OB_ISNULL(table_scan->get_strong_sharding())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("get unexpected null", K(sql_schema_guard), K(stmt), K(ret));
  } else if (!table_scan->use_das() || !table_scan->is_match_all()) {
    // do nothing
  } else if (OB_FAIL(append_array_no_dup(all_filters, table_scan->get_range_conditions()))) {
    LOG_WARN("failed to add into all filters", K(ret));
  } else if (OB_FAIL(append_array_no_dup(all_filters, table_scan->get_filter_exprs()))) {
    LOG_WARN("failed to add into all filters", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::check_exec_param_filter_exprs(all_filters,
                                                                    has_dppr))) {
    LOG_WARN("failed to find das dppr filter exprs", K(ret));
  } else if (!has_dppr) {
    // do nothing
O
oceanbase-admin 已提交
11740
  } else {
W
wangzelin.wzl 已提交
11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763
    SMART_VAR(ObTableLocation, das_location) {
      const ObDataTypeCastParams dtc_params =
            ObBasicSessionInfo::create_dtc_params(opt_ctx->get_session_info());
      int64_t ref_table_id = table_scan->get_is_index_global() ?
                              table_scan->get_index_table_id() :
                              table_scan->get_ref_table_id();
      if (OB_FAIL(das_location.init(*sql_schema_guard,
                                    *stmt,
                                    opt_ctx->get_exec_ctx(),
                                    all_filters,
                                    table_scan->get_table_id(),
                                    ref_table_id,
                                    table_scan->get_is_index_global() ? NULL : &table_item->part_ids_,
                                    dtc_params,
                                    false))) {
        LOG_WARN("fail to init table location", K(ret), K(all_filters));
      } else if (das_location.is_all_partition()) {
        // do nothing
      } else {
        das_location.set_has_dynamic_exec_param(true);
        das_location.set_use_das(true);
        table_partition_info->set_table_location(das_location);
      }
O
oceanbase-admin 已提交
11764 11765 11766 11767 11768
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
11769
int ObLogPlan::collect_table_location(ObLogicalOperator *op)
O
oceanbase-admin 已提交
11770 11771
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11772 11773
  bool is_stack_overflow = false;
  if (OB_ISNULL(op)) {
O
oceanbase-admin 已提交
11774
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
11775 11776 11777 11778 11779 11780
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(check_stack_overflow(is_stack_overflow))) {
    LOG_WARN("check stack overflow failed", K(ret));
  } else if (is_stack_overflow) {
    ret = OB_SIZE_OVERFLOW;
    LOG_WARN("too deep recursive", K(ret));
O
obdev 已提交
11781
  } else if (LOG_LINK_SCAN == op->get_type()) {
W
wangzelin.wzl 已提交
11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793
    /*do nothing*/
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); i++) {
      if (OB_FAIL(SMART_CALL(collect_table_location(op->get_child(i))))) {
        LOG_WARN("failed to collect table location", K(ret));
      } else { /*do nothing*/ }
    }
    if (OB_FAIL(ret)) {
      /*do nothing*/
    } else if (log_op_def::LOG_TABLE_SCAN == op->get_type()) {
      ObTablePartitionInfo *table_partition_info = NULL;
      ObLogTableScan *table_scan = static_cast<ObLogTableScan*>(op);
O
obdev 已提交
11794
      if (table_scan->get_contains_fake_cte() || OB_INVALID_ID != table_scan->get_dblink_id()) {
W
wangzelin.wzl 已提交
11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840
        /*do nothing*/
      } else if (OB_ISNULL(table_partition_info = table_scan->get_table_partition_info())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(table_partition_info), K(ret));
      } else if (OB_FALSE_IT(table_partition_info->get_table_location().set_use_das(table_scan->use_das()))) {
      } else if (OB_FAIL(gen_das_table_location_info(table_scan,
                                                     table_partition_info))) {
        LOG_WARN("failed to gen das table location info", K(ret));
      } else if (OB_FAIL(table_partition_info->replace_final_location_key(
          *optimizer_context_.get_exec_ctx(),
          table_scan->get_real_index_table_id(),
          table_scan->is_index_scan() && !table_scan->get_is_index_global()))) {
        LOG_WARN("failed to set table partition info", K(ret));
      } else if (OB_FAIL(add_global_table_partition_info(table_partition_info))) {
        LOG_WARN("failed to add table partition info", K(ret));
      } else { /*do nothing*/ }
    } else if ((log_op_def::LOG_DELETE == op->get_type() ||
                log_op_def::LOG_UPDATE == op->get_type() ||
                log_op_def::LOG_INSERT == op->get_type()) &&
                static_cast<ObLogDelUpd*>(op)->is_pdml()) {
      ObTablePartitionInfo *table_partition_info =
          static_cast<ObLogDelUpd*>(op)->get_table_partition_info();
      if (OB_ISNULL(table_partition_info)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(add_global_table_partition_info(table_partition_info))) {
        LOG_WARN("failed to add table partition info", K(ret));
      } else { /*do nothing*/ }
    } else if ((log_op_def::LOG_INSERT == op->get_type() ||
                log_op_def::LOG_MERGE == op->get_type()) &&
               !static_cast<ObLogInsert*>(op)->has_instead_of_trigger() &&
               static_cast<ObLogInsert*>(op)->is_insert_select()) {
      ObLogInsert *insert_op = static_cast<ObLogInsert*>(op);
      ObTablePartitionInfo *table_partition_info = insert_op->get_table_partition_info();
      if (OB_ISNULL(table_partition_info)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(table_partition_info), K(ret));
      } else if ((!insert_op->is_multi_part_dml() ||
                 ObPhyPlanType::OB_PHY_PLAN_DISTRIBUTED == insert_op->get_phy_plan_type())) {
        if (OB_FAIL(add_global_table_partition_info(table_partition_info))) {
          LOG_WARN("failed to add table partition info", K(ret));
        } else { /*do nothing*/ }
      } else { /*do nothing*/ }
    } else { /*do nothing*/ }
    if (OB_SUCC(ret) && OB_FAIL(collect_location_related_info(*op))) {
      LOG_WARN("collect location related info failed", K(ret));
O
oceanbase-admin 已提交
11841 11842 11843 11844 11845
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
11846
int ObLogPlan::collect_location_related_info(ObLogicalOperator &op)
O
oceanbase-admin 已提交
11847 11848
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876
  ObIArray<TableLocRelInfo> &loc_rel_infos = optimizer_context_.get_loc_rel_infos();
  if (op.is_table_scan()) {
    ObLogTableScan &tsc_op = static_cast<ObLogTableScan&>(op);
    ObTablePartitionInfo *table_part_info = tsc_op.get_table_partition_info();
    ObTableID table_loc_id = tsc_op.get_table_id();
    ObTableID ref_table_id = tsc_op.get_ref_table_id();
    if (OB_NOT_NULL(optimizer_context_.get_loc_rel_info_by_id(table_loc_id, ref_table_id))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("table location related info already exists", K(ret),
               K(table_loc_id), K(ref_table_id), K(loc_rel_infos));
    } else if (!tsc_op.get_is_index_global()) {
      //global index with data table has no related tablet info
      TableLocRelInfo rel_info;
      rel_info.table_loc_id_ = tsc_op.get_table_id();
      rel_info.ref_table_id_ = tsc_op.get_real_ref_table_id();
      if (OB_FAIL(rel_info.related_ids_.push_back(tsc_op.get_real_index_table_id()))) {
        LOG_WARN("store the source table id failed", K(ret));
      } else if (table_part_info != nullptr &&
          OB_FAIL(rel_info.table_part_infos_.push_back(table_part_info))) {
        LOG_WARN("collect table partition info to relation info failed", K(ret));
      } else if (tsc_op.get_index_back()) {
        if (OB_FAIL(rel_info.related_ids_.push_back(tsc_op.get_real_ref_table_id()))) {
          LOG_WARN("store the related table id failed", K(ret));
        }
      }
      if (OB_SUCC(ret) && OB_FAIL(optimizer_context_.get_loc_rel_infos().push_back(rel_info))) {
        LOG_WARN("store location related info failed", K(ret));
      }
O
obdev 已提交
11877 11878
    } else if (tsc_op.get_is_index_global() && tsc_op.get_index_back()) {
      //for global index lookup
W
wangzelin.wzl 已提交
11879
      TableLocRelInfo rel_info;
O
obdev 已提交
11880 11881 11882
      rel_info.table_loc_id_ = tsc_op.get_table_id();
      rel_info.ref_table_id_ = tsc_op.get_ref_table_id();
      if (OB_FAIL(rel_info.related_ids_.push_back(tsc_op.get_ref_table_id()))) {
W
wangzelin.wzl 已提交
11883
        LOG_WARN("store the source table id failed", K(ret));
O
obdev 已提交
11884 11885 11886 11887
      } else if (nullptr != tsc_op.get_global_index_back_table_partition_info() && OB_FAIL(rel_info.table_part_infos_.push_back(tsc_op.get_global_index_back_table_partition_info()))) {
        LOG_WARN("collect table partition info to relation info failed", K(ret));
      }
      if (OB_SUCC(ret) && OB_FAIL(optimizer_context_.get_loc_rel_infos().push_back(rel_info))) {
W
wangzelin.wzl 已提交
11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955
        LOG_WARN("store location related info failed", K(ret));
      }
    }
  } else if (op.is_dml_operator()) {
    ObLogDelUpd &dml_op = static_cast<ObLogDelUpd&>(op);
    ObTablePartitionInfo *table_part_info = dml_op.get_table_partition_info();
    const ObIArray<IndexDMLInfo *> &index_dml_infos = dml_op.get_index_dml_infos();
    for (int64_t i = 0; OB_SUCC(ret) && i < index_dml_infos.count(); ++i) {
      const IndexDMLInfo &index_info = *index_dml_infos.at(i);
      ObTableID table_loc_id = index_info.loc_table_id_;
      ObTableID ref_table_id = index_info.ref_table_id_;
      TableLocRelInfo *loc_rel_info = nullptr;
      if (index_info.is_primary_index_) {
        if (OB_ISNULL(loc_rel_info = optimizer_context_.get_loc_rel_info_by_id(
                                       table_loc_id, ref_table_id))) {
          //init table location related info with the main table
          TableLocRelInfo rel_info;
          rel_info.table_loc_id_ = table_loc_id;
          rel_info.ref_table_id_ = ref_table_id;
          if (OB_FAIL(rel_info.related_ids_.push_back(ref_table_id))) {
            LOG_WARN("store the source table id failed", K(ret));
          } else if (OB_FAIL(loc_rel_infos.push_back(rel_info))) {
            LOG_WARN("store rel info failed", K(ret));
          } else {
            loc_rel_info = &loc_rel_infos.at(loc_rel_infos.count() - 1);
          }
        } else if (OB_FAIL(add_var_to_array_no_dup(loc_rel_info->related_ids_, ref_table_id))) {
          LOG_WARN("add ref_table_id to the related ids failed", K(ret));
        }
        if (OB_SUCC(ret) && table_part_info != nullptr
            && table_part_info->get_table_id() == table_loc_id
            && table_part_info->get_ref_table_id() == ref_table_id) {
          if (OB_FAIL(add_var_to_array_no_dup(loc_rel_info->table_part_infos_, table_part_info))) {
            LOG_WARN("store table part info failed", K(ret));
          }
        }
        if (OB_SUCC(ret)) {
          if (OB_FAIL(append_array_no_dup(loc_rel_info->related_ids_, index_info.related_index_ids_))) {
            LOG_WARN("add the ref table id to the related ids failed", K(ret));
          } else {
            LOG_DEBUG("collect dml op related table id", KPC(loc_rel_info), K(table_loc_id), K(ref_table_id));
          }
        }
      }
    }
  } else if (log_op_def::LOG_FOR_UPD == op.get_type()) {
    ObLogForUpdate &for_upd_op = static_cast<ObLogForUpdate&>(op);
    const ObIArray<IndexDMLInfo *> &index_dml_infos = for_upd_op.get_index_dml_infos();
    for (int64_t i = 0; OB_SUCC(ret) && i < index_dml_infos.count(); ++i) {
      const IndexDMLInfo &index_info = *index_dml_infos.at(i);
      ObTableID table_loc_id = index_info.loc_table_id_;
      ObTableID ref_table_id = index_info.ref_table_id_;
      TableLocRelInfo *loc_rel_info = nullptr;
      if (!index_info.is_primary_index_) {
        //do nothing
      } else if (OB_ISNULL(loc_rel_info = optimizer_context_.get_loc_rel_info_by_id(
          table_loc_id, ref_table_id))) {
        //location related info is empty, means the TSC is global index scan, so ignore it
      } else if (loc_rel_info->related_ids_.empty()) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("related table id array is empty", K(ret), KPC(loc_rel_info));
      } else if (loc_rel_info->related_ids_.at(0) == ref_table_id) {
        //the depend table id is same with the source location table id
        //does not need to add the related table id to related ids
      } else if (OB_FAIL(add_var_to_array_no_dup(loc_rel_info->related_ids_, ref_table_id))) {
        LOG_WARN("add the ref table id to the related ids failed", K(ret));
      }
    }
O
oceanbase-admin 已提交
11956 11957 11958 11959
  }
  return ret;
}

W
wangzelin.wzl 已提交
11960 11961
//restore the related table id to the loc_meta in source table location
int ObLogPlan::build_location_related_tablet_ids()
O
oceanbase-admin 已提交
11962 11963
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981
  for (int64_t i = 0; OB_SUCC(ret) && i < optimizer_context_.get_loc_rel_infos().count(); ++i) {
    TableLocRelInfo &rel_info = optimizer_context_.get_loc_rel_infos().at(i);
    if (rel_info.related_ids_.count() <= 1) {
      //the first table id is the source table, <=1 mean no dependency table
    } else {
      for (int64_t j = 0; OB_SUCC(ret) && j < rel_info.table_part_infos_.count(); ++j) {
        ObTablePartitionInfo *source_part_info = rel_info.table_part_infos_.at(j);
        ObDASTableLocMeta &source_loc_meta = source_part_info->get_table_location().get_loc_meta();
        source_loc_meta.related_table_ids_.set_capacity(rel_info.related_ids_.count() - 1);
        for (int64_t k = 0; OB_SUCC(ret) && k < rel_info.related_ids_.count(); ++k) {
          //set related table ids to loc meta
          if (rel_info.related_ids_.at(k) == source_part_info->get_ref_table_id()) {
            //ignore itself, do nothing
          } else if (OB_FAIL(source_loc_meta.related_table_ids_.push_back(rel_info.related_ids_.at(k)))) {
            LOG_WARN("store related table ids failed", K(ret));
          }
        }
      }
O
oceanbase-admin 已提交
11982 11983
    }
  }
W
wangzelin.wzl 已提交
11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001
  optimizer_context_.get_exec_ctx()->get_das_ctx().clear_all_location_info();
  for (int64_t i = 0; OB_SUCC(ret) && i < optimizer_context_.get_table_partition_info().count(); ++i) {
    ObTablePartitionInfo *table_part_info = optimizer_context_.get_table_partition_info().at(i);
    //need to call ObTableLocation::calculate_table_partition_ids() to
    //reload the related index tablet ids in DASCtx
    //because in the generate_plan stage, only the tablet_id of the data table is calculated,
    //and the tablet_id of the related index table is not calculated
    //In the execution phase,
    //DASCtx relies on the tablet mapping relationship //between the data table and the local index
    //to build the table location of the local index
    DASRelatedTabletMap *map = nullptr;
    if (OB_ISNULL(table_part_info)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("invalid partition info", K(ret));
    } else if (!table_part_info->get_table_location().use_das() &&
               OB_FAIL(ObPhyLocationGetter::build_related_tablet_info(
                       table_part_info->get_table_location(), *optimizer_context_.get_exec_ctx(), map))) {
      LOG_WARN("rebuild related tablet info failed", K(ret));
O
oceanbase-admin 已提交
12002 12003 12004 12005 12006
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12007
int ObLogPlan::calc_plan_resource()
O
oceanbase-admin 已提交
12008 12009
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030
  const ObDMLStmt *stmt = nullptr;
  ObLogicalOperator *plan_root = nullptr;
  int64_t max_parallel_thread_count = 0;
  int64_t max_parallel_group_count = 0;
  if (OB_ISNULL(stmt = get_stmt()) ||
      OB_ISNULL(plan_root = get_plan_root())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else {
    ObPxResourceAnalyzer analyzer;
    if (OB_FAIL(analyzer.analyze(*plan_root,
                                 max_parallel_thread_count,
                                 max_parallel_group_count,
                                 get_optimizer_context().get_expected_worker_map(),
                                 get_optimizer_context().get_minimal_worker_map()))) {
      LOG_WARN("fail analyze px stmt thread group reservation count", K(ret));
    } else {
      LOG_TRACE("max parallel thread group count",
               K(max_parallel_thread_count), K(max_parallel_group_count));
      get_optimizer_context().set_expected_worker_count(max_parallel_thread_count);
      get_optimizer_context().set_minimal_worker_count(max_parallel_group_count);
O
oceanbase-admin 已提交
12031
    }
W
wangzelin.wzl 已提交
12032 12033 12034
  }
  return ret;
}
O
oceanbase-admin 已提交
12035

W
wangzelin.wzl 已提交
12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046
/**
 * 按照去重后的location约束计算出执行依赖的partition wise join map并设置到exec ctx中
 * 计算逻辑与ObDistPlans::check_inner_constraints()类似,只是省略了一些计划生成过程中已经做过的检查
 */
int ObLogPlan::calc_and_set_exec_pwj_map(ObLocationConstraintContext &location_constraint) const
{
  int ret = OB_SUCCESS;
  ObExecContext *exec_ctx = get_optimizer_context().get_exec_ctx();
  if (OB_ISNULL(exec_ctx)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
O
obdev 已提交
12047
  } else if (location_constraint.strict_constraints_.count() > 0) {
W
wangzelin.wzl 已提交
12048 12049 12050 12051
    ObIArray<LocationConstraint> &base_location_cons = location_constraint.base_table_constraints_;
    ObIArray<ObPwjConstraint *> &strict_cons = location_constraint.strict_constraints_;
    const int64_t tbl_count = location_constraint.base_table_constraints_.count();
    ObSEArray<PwjTable, 4> pwj_tables;
O
obdev 已提交
12052
    SMART_VAR(ObStrictPwjComparer, strict_pwj_comparer) {
W
wangzelin.wzl 已提交
12053 12054 12055 12056 12057 12058 12059
      PWJTabletIdMap pwj_map;
      if (OB_FAIL(pwj_tables.prepare_allocate(tbl_count))) {
        LOG_WARN("failed to prepare allocate pwj tables", K(ret));
      } else if (OB_FAIL(pwj_map.create(8, ObModIds::OB_PLAN_EXECUTE))) {
        LOG_WARN("create pwj map failed", K(ret));
      }

O
obdev 已提交
12060 12061 12062 12063 12064 12065 12066 12067
      for (int64_t i = 0; OB_SUCC(ret) && i < strict_cons.count(); ++i) {
        const ObPwjConstraint *pwj_cons = strict_cons.at(i);
        if (OB_ISNULL(pwj_cons) || OB_UNLIKELY(pwj_cons->count() <= 1)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected pwj constraint", K(ret), K(pwj_cons));
        } else if (OB_FAIL(check_pwj_cons(*pwj_cons, location_constraint.base_table_constraints_,
                                          strict_pwj_comparer, pwj_map))) {
          LOG_WARN("failed to check pwj cons", K(ret));
O
oceanbase-admin 已提交
12068 12069 12070
        }
      }

W
wangzelin.wzl 已提交
12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101
      if (OB_SUCC(ret)) {
        PWJTabletIdMap *exec_pwj_map = NULL;
        if (OB_FAIL(exec_ctx->get_pwj_map(exec_pwj_map))) {
          LOG_WARN("failed to get exec pwj map", K(ret));
        } else if (OB_FAIL(exec_pwj_map->reuse())) {
          LOG_WARN("failed to reuse pwj map", K(ret));
        }
        for (int64_t i = 0; OB_SUCC(ret) && i < base_location_cons.count(); ++i) {
          if (!base_location_cons.at(i).is_multi_part_insert()) {
            TabletIdArray tablet_id_array;
            if (OB_FAIL(pwj_map.get_refactored(i, tablet_id_array))) {
              if (OB_HASH_NOT_EXIST == ret) {
                // 没找到说明当前表不需要做partition wise join
                ret = OB_SUCCESS;
              } else {
                LOG_WARN("failed to get refactored", K(ret));
              }
            } else if (OB_FAIL(exec_pwj_map->set_refactored(base_location_cons.at(i).key_.table_id_,
                                                            tablet_id_array))) {
              LOG_WARN("failed to set refactored", K(ret));
            }
          }
        }
      }

      // 释放pwj_map的内存
      if (pwj_map.created()) {
        int tmp_ret = OB_SUCCESS;
        if (OB_UNLIKELY(OB_SUCCESS != (tmp_ret = pwj_map.destroy()))) {
          LOG_WARN("failed to destroy pwj map", K(tmp_ret));
        }
O
oceanbase-admin 已提交
12102 12103 12104 12105 12106 12107
      }
    }
  }
  return ret;
}

O
obdev 已提交
12108 12109 12110 12111
int ObLogPlan::check_pwj_cons(const ObPwjConstraint &pwj_cons,
                              const ObIArray<LocationConstraint> &base_location_cons,
                              ObStrictPwjComparer &pwj_comparer,
                              PWJTabletIdMap &pwj_map) const
O
oceanbase-admin 已提交
12112 12113
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12114 12115 12116 12117 12118
  bool is_same = true;
  ObTablePartitionInfo *first_table_partition_info = base_location_cons.at(pwj_cons.at(0)).table_partition_info_;
  if (OB_ISNULL(first_table_partition_info)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(first_table_partition_info));
O
obdev 已提交
12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157
  } else if (1 == first_table_partition_info->get_phy_tbl_location_info().get_partition_cnt()) {
    // all tables in pwj constraint are local or remote
    // alreay checked, do nothing
  } else {
    // distribute partition wise join
    LOG_DEBUG("check pwj constraint", K(pwj_cons), K(base_location_cons));
    pwj_comparer.reset();
    for (int64_t i = 0; OB_SUCC(ret) && is_same && i < pwj_cons.count(); ++i) {
      const int64_t table_idx = pwj_cons.at(i);
      ObTablePartitionInfo *table_part_info = NULL;
      ObSchemaGetterGuard *schema_guard = get_optimizer_context().get_schema_guard();
      ObSQLSessionInfo *session = get_optimizer_context().get_session_info();
      const ObTableSchema *table_schema = NULL;
      PwjTable table;
      if (table_idx < 0 || table_idx >= base_location_cons.count()) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table index is invalid", K(ret), K(table_idx), K(base_location_cons.count()));
      } else if (OB_ISNULL(schema_guard) || OB_ISNULL(session) ||
                 OB_ISNULL(table_part_info = base_location_cons.at(table_idx).table_partition_info_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("invalid table part info", K(ret), K(table_part_info), K(schema_guard), K(session));
      } else if (OB_FAIL(schema_guard->get_table_schema(session->get_effective_tenant_id(),
                                                        base_location_cons.at(table_idx).key_.ref_table_id_,
                                                        table_schema))) {
        LOG_WARN("fail to get table schema", K(ret), K(table_schema),
                                             K(base_location_cons.at(table_idx).key_.ref_table_id_));
      } else if (OB_ISNULL(table_schema)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("index schema should not be null", K(table_schema), K(ret));
      } else if (OB_FAIL(table.init(*table_schema, table_part_info->get_phy_tbl_location_info()))) {
        LOG_WARN("failed to init owj table with sharding info", K(ret));
      } else if (OB_FAIL(pwj_comparer.add_table(table, is_same))) {
        LOG_WARN("failed to add table", K(ret));
      } else if (!is_same) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get not same table", KPC(first_table_partition_info), K(table));
      } else if (OB_FAIL(pwj_map.set_refactored(table_idx,
                                                pwj_comparer.get_tablet_id_group().at(i)))) {
        LOG_WARN("failed to set refactored", K(ret));
O
oceanbase-admin 已提交
12158 12159 12160 12161 12162 12163
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12164 12165 12166
int ObLogPlan::get_cached_hash_sharding_info(const ObIArray<ObRawExpr*> &hash_exprs,
                                             const EqualSets &equal_sets,
                                             ObShardingInfo *&cached_sharding)
O
oceanbase-admin 已提交
12167 12168
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179
  cached_sharding = NULL;
  for (int64_t i = 0; OB_SUCC(ret) && NULL == cached_sharding && i < hash_dist_info_.count(); i++) {
    ObShardingInfo *temp_sharding = NULL;
    if (OB_ISNULL(temp_sharding = hash_dist_info_.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (ObOptimizerUtil::same_exprs(hash_exprs,
                                           temp_sharding->get_partition_keys(),
                                           equal_sets)) {
      cached_sharding = temp_sharding;
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
12180 12181 12182 12183
  }
  return ret;
}

W
wangzelin.wzl 已提交
12184
bool ObLogPlan::has_depend_function_table(const ObRelIds& table_ids)
O
oceanbase-admin 已提交
12185
{
W
wangzelin.wzl 已提交
12186 12187 12188 12189 12190
  bool b_ret = false;
  for (int64_t i = 0; !b_ret && i < function_table_depend_infos_.count(); ++i) {
    FunctionTableDependInfo &info = function_table_depend_infos_.at(i);
    if (table_ids.has_member(info.table_idx_)) {
      b_ret = true;
O
oceanbase-admin 已提交
12191 12192
    }
  }
W
wangzelin.wzl 已提交
12193
  return b_ret;
O
oceanbase-admin 已提交
12194 12195
}

O
obdev 已提交
12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207
bool ObLogPlan::has_depend_json_table(const ObRelIds& table_ids)
{
  bool b_ret = false;
  for (int64_t i = 0; !b_ret && i < json_table_depend_infos_.count(); ++i) {
    JsonTableDependInfo &info = json_table_depend_infos_.at(i);
    if (table_ids.has_member(info.table_idx_)) {
      b_ret = true;
    }
  }
  return b_ret;
}

W
wangzelin.wzl 已提交
12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219
int ObLogPlan::allocate_output_expr_for_values_op(ObLogicalOperator &values_op)
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(optimizer_context_.get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("session is NULL", K(ret));
  } else {
    // Static typing engine need expr to output rows. We generate a const output expr
    // for values_op operator.
    ObConstRawExpr *output = NULL;
    if (OB_FAIL(optimizer_context_.get_expr_factory().create_raw_expr(T_VARCHAR, output))) {
      LOG_WARN("create const expr failed", K(ret));
O
oceanbase-admin 已提交
12220
    } else {
W
wangzelin.wzl 已提交
12221 12222 12223 12224 12225 12226 12227 12228 12229
      ObObj v;
      v.set_varchar(" ");
      v.set_collation_type(ObCharset::get_system_collation());
      output->set_param(v);
      output->set_value(v);
      if (OB_FAIL(output->formalize(optimizer_context_.get_session_info()))) {
        LOG_WARN("const expr formalize failed", K(ret));
      } else if (OB_FAIL(values_op.get_output_exprs().push_back(output))) {
        LOG_WARN("add output expr failed", K(ret));
O
oceanbase-admin 已提交
12230
      } else {
W
wangzelin.wzl 已提交
12231 12232 12233 12234 12235 12236
        values_op.set_branch_id(0);
        values_op.set_id(0);
        values_op.set_op_id(0);
        if (OB_FAIL(get_optimizer_context().get_all_exprs().append(output))) {
          LOG_WARN("failed to append output", K(ret));
        } else { /*do nothing*/ }
O
oceanbase-admin 已提交
12237 12238 12239 12240 12241 12242
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12243
int ObLogPlan::add_subquery_filter(ObRawExpr *qual)
O
oceanbase-admin 已提交
12244 12245
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12246 12247 12248 12249 12250 12251
  ObSEArray<ObExecParamRawExpr*, 4> onetime_exprs;
  if (OB_ISNULL(get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect null stmt", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::get_onetime_exprs(qual, onetime_exprs))) {
    LOG_WARN("failed to get onetime exprs", K(ret));
O
obdev 已提交
12252
  } else if (!ObOptimizerUtil::is_subset(onetime_exprs, onetime_params_)) {
W
wangzelin.wzl 已提交
12253 12254 12255
    //属于当前stmt的onetime才需要分配subplan filter
  } else if (OB_FAIL(subquery_filters_.push_back(qual))) {
    LOG_WARN("failed to push back expr", K(ret));
O
oceanbase-admin 已提交
12256 12257 12258 12259
  }
  return ret;
}

W
wangzelin.wzl 已提交
12260 12261 12262
int ObLogPlan::get_rowkey_exprs(const uint64_t table_id,
                                const uint64_t ref_table_id,
                                ObIArray<ObRawExpr*> &keys)
O
oceanbase-admin 已提交
12263 12264
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276
  const ObTableSchema *table_schema = NULL;
  ObSqlSchemaGuard *schema_guard = NULL;
  if (OB_ISNULL(schema_guard = get_optimizer_context().get_sql_schema_guard())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid argument", K(schema_guard), K(ret));
  } else if (OB_FAIL(schema_guard->get_table_schema(table_id, ref_table_id, get_stmt(), table_schema))) {
    LOG_WARN("fail to get table schema", K(ref_table_id), K(table_schema), K(ret));
  } else if (OB_ISNULL(table_schema)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("index schema should not be null", K(table_schema), K(ret));
  } else if (OB_FAIL(get_rowkey_exprs(table_id, *table_schema, keys))) {
    LOG_WARN("failed to get rowkey exprs", K(ret));
O
oceanbase-admin 已提交
12277 12278 12279 12280
  }
  return ret;
}

W
wangzelin.wzl 已提交
12281 12282 12283
int ObLogPlan::get_rowkey_exprs(const uint64_t table_id,
                                const ObTableSchema &table_schema,
                                ObIArray<ObRawExpr*> &keys)
O
oceanbase-admin 已提交
12284 12285
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298
  const ObRowkeyInfo &rowkey_info = table_schema.get_rowkey_info();
  const ObColumnSchemaV2 *column_schema = NULL;
  const ColumnItem *column_item = NULL;
  ColumnItem column_item2;
  for (int i = 0; OB_SUCC(ret) && i < rowkey_info.get_size(); ++i) {
    uint64_t  column_id = OB_INVALID_ID;
    if (OB_FAIL(rowkey_info.get_column_id(i, column_id))) {
      LOG_WARN("Failed to get column_id from rowkey_info", K(ret));
    } else if (NULL != (column_item = get_column_item_by_id(table_id, column_id))) {
      if (OB_FAIL(keys.push_back(column_item->expr_))) {
        LOG_WARN("failed to push column item", K(ret));
      }
    } else if (OB_ISNULL(column_schema = table_schema.get_column_schema(column_id))) {
O
oceanbase-admin 已提交
12299
      ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12300 12301 12302 12303 12304 12305
      LOG_WARN("failed to get column schema", K(column_id), K(ret));
    } else if (OB_FAIL(generate_column_expr(get_optimizer_context().get_expr_factory(), table_id,
                                            *column_schema, column_item2))) {
      LOG_WARN("failed to get rowkey exprs", K(ret));
    } else if (OB_FAIL(keys.push_back(column_item2.expr_))) {
      LOG_WARN("failed to push column item", K(ret));
O
oceanbase-admin 已提交
12306 12307 12308 12309 12310
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12311 12312 12313 12314
int ObLogPlan::get_index_column_items(ObRawExprFactory &expr_factory,
                                      uint64_t table_id,
                                      const share::schema::ObTableSchema &index_table_schema,
                                      common::ObIArray<ColumnItem> &index_columns)
O
oceanbase-admin 已提交
12315 12316
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370
  // get all the index keys
  const ObRowkeyInfo* rowkey_info = NULL;
  const ObColumnSchemaV2 *column_schema = NULL;
  uint64_t column_id = OB_INVALID_ID;
  if (index_table_schema.is_index_table()
      && is_virtual_table(index_table_schema.get_data_table_id())
      && !index_table_schema.is_ordered()) {
    // for virtual table and its hash index
    rowkey_info = &index_table_schema.get_index_info();
  } else {
    rowkey_info = &index_table_schema.get_rowkey_info();
  }
  const ColumnItem *column_item = NULL;
  ColumnItem column_item2;
  for (int col_idx = 0; OB_SUCC(ret) && col_idx < rowkey_info->get_size(); ++col_idx) {
    if (OB_FAIL(rowkey_info->get_column_id(col_idx, column_id))) {
      LOG_WARN("Failed to get column id", K(ret));
    } else if (OB_ISNULL(column_schema = index_table_schema.get_column_schema(column_id))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("failed to get column schema", K(column_id), K(ret));
    } else if (NULL != (column_item = get_column_item_by_id(table_id, column_id))) {
      if (OB_FAIL(index_columns.push_back(*column_item))) {
        LOG_WARN("failed to push column item", K(ret));
      }
    } else if (OB_FAIL(generate_column_expr(expr_factory, table_id,
                                            *column_schema, column_item2))) {
      LOG_WARN("failed to get rowkey exprs", K(ret));
    } else if (OB_FAIL(index_columns.push_back(column_item2))) {
      LOG_WARN("failed to push column item", K(ret));
    }
  } // for end
  if (OB_SUCC(ret)) {
    LOG_TRACE("get range columns", K(index_columns));
  }
  return ret;
}

ObColumnRefRawExpr *ObLogPlan::get_column_expr_by_id(uint64_t table_id, uint64_t column_id) const
{
  const ColumnItem *column_item = get_column_item_by_id(table_id, column_id);
  return NULL == column_item ? NULL : column_item->expr_;
}

const ColumnItem *ObLogPlan::get_column_item_by_id(uint64_t table_id, uint64_t column_id) const
{
  const ColumnItem *column_item = NULL;
  if (OB_ISNULL(get_stmt())) {
    // do nothing
  } else {
    const common::ObIArray<ColumnItem> &stmt_column_items = get_stmt()->get_column_items();
    for (int64_t i = 0; NULL == column_item && i < stmt_column_items.count(); i++) {
      if (table_id == stmt_column_items.at(i).table_id_ &&
          column_id == stmt_column_items.at(i).column_id_) {
        column_item = &stmt_column_items.at(i);
O
oceanbase-admin 已提交
12371 12372
      }
    }
W
wangzelin.wzl 已提交
12373 12374 12375 12376
    for (int64_t i = 0; NULL == column_item && i < column_items_.count(); i++) {
      if (table_id == column_items_.at(i).table_id_ &&
          column_id == column_items_.at(i).column_id_) {
        column_item = &column_items_.at(i);
O
oceanbase-admin 已提交
12377 12378 12379
      }
    }
  }
W
wangzelin.wzl 已提交
12380
  return column_item;
O
oceanbase-admin 已提交
12381 12382
}

12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402

int ObLogPlan::get_column_exprs(uint64_t table_id, ObIArray<ObColumnRefRawExpr*> &column_exprs) const
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret), K(get_stmt()));
  } else if (OB_FAIL(get_stmt()->get_column_exprs(table_id, column_exprs))) {
    LOG_WARN("failed to get column exprs", K(ret));
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < column_items_.count(); ++i) {
      if (table_id == column_items_.at(i).table_id_
          && OB_FAIL(column_exprs.push_back(column_items_.at(i).expr_))) {
        LOG_WARN("failed to push back", K(ret));
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12403 12404 12405 12406
int ObLogPlan::generate_column_expr(ObRawExprFactory &expr_factory,
                                    const uint64_t &table_id,
                                    const ObColumnSchemaV2 &column_schema,
                                    ColumnItem &column_item)
O
oceanbase-admin 已提交
12407 12408
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420
  const TableItem *table_item = NULL;
  ObColumnRefRawExpr *rowkey;
  const ObDMLStmt *stmt = NULL;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("Invalid argument passed in", K(stmt), K(ret));
  } else if (OB_FAIL(ObRawExprUtils::build_column_expr(expr_factory, column_schema, rowkey))) {
    LOG_WARN("build column expr failed", K(ret));
  } else if (OB_ISNULL(rowkey)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("failed to create raw expr for dummy output", K(ret));
  } else if (OB_ISNULL(table_item = stmt->get_table_item_by_id(table_id))) {
O
oceanbase-admin 已提交
12421
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12422
    LOG_WARN("get table item by id failed", K(table_id));
O
oceanbase-admin 已提交
12423
  } else {
W
wangzelin.wzl 已提交
12424 12425 12426 12427 12428 12429
    rowkey->set_ref_id(table_id, column_schema.get_column_id());
    rowkey->get_relation_ids().reuse();
    rowkey->set_column_attr(table_item->get_table_name(), column_schema.get_column_name_str());
    rowkey->set_database_name(table_item->database_name_);
    if (!table_item->alias_name_.empty()) {
      rowkey->set_table_alias_name();
O
oceanbase-admin 已提交
12430
    }
W
wangzelin.wzl 已提交
12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441
    column_item.table_id_ = rowkey->get_table_id();
    column_item.column_id_ = rowkey->get_column_id();
    column_item.base_tid_ = table_item->ref_id_;
    column_item.base_cid_ = rowkey->get_column_id();
    column_item.column_name_ = rowkey->get_column_name();
    column_item.set_default_value(column_schema.get_cur_default_value());
    column_item.expr_ = rowkey;
    if (OB_FAIL(rowkey->add_relation_id(stmt->get_table_bit_index(table_id)))) {
      LOG_WARN("add relation id to expr failed", K(ret));
    } else if (OB_FAIL(rowkey->formalize(NULL))) {
      LOG_WARN("formalize rowkey failed", K(ret));
O
obdev 已提交
12442
    } else if (OB_FAIL(rowkey->pull_relation_id())) {
W
wangzelin.wzl 已提交
12443 12444 12445
      LOG_WARN("failed to pullup relation ids", K(ret));
    } else if (OB_FAIL(column_items_.push_back(column_item))) {
      LOG_WARN("failed to push column item", K(ret));
O
oceanbase-admin 已提交
12446
    }
W
wangzelin.wzl 已提交
12447 12448 12449
  }
  return ret;
}
O
oceanbase-admin 已提交
12450

W
wangzelin.wzl 已提交
12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465
//mysql mode need distinguish different of for update, eg:
/*
 * create table t1(c1 int primary key, c2 int);
 * create table t2(c1 int primary key, c2 int);
 * create table t3(c1 int primary key, c2 int);
 * select * from t1 where c2 in (select t2.c1 from t2,t3 for update wait 1) for update
 * ==> for update: t1
 *     for update wait 1: t2,t3;
*/
int ObLogPlan::candi_allocate_for_update()
{
  int ret = OB_SUCCESS;
  const ObDMLStmt *stmt = NULL;
  ObSEArray<CandidatePlan, 8> best_plans;
  if (OB_ISNULL(stmt = get_stmt())) {
O
oceanbase-admin 已提交
12466
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12467 12468 12469 12470
    LOG_WARN("get unexpected null", K(stmt), K(ret));
  } else if (lib::is_oracle_mode()) {
    const ObSelectStmt *sel_stmt = static_cast<const ObSelectStmt *>(stmt);
    if (OB_UNLIKELY(!stmt->is_select_stmt())) {
O
oceanbase-admin 已提交
12471
      ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12472 12473 12474 12475 12476 12477
      LOG_WARN("stmt is expected to be select", K(ret));
    } else if (sel_stmt->has_distinct() ||
               sel_stmt->has_group_by() ||
               sel_stmt->is_set_stmt()) {
      ret = OB_ERR_FOR_UPDATE_SELECT_VIEW_CANNOT;
      LOG_WARN("for update can not exists in stmt with distint, groupby", K(ret));
O
oceanbase-admin 已提交
12478
    }
W
wangzelin.wzl 已提交
12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492
  }

  if (OB_SUCC(ret)) {
    ObSEArray<uint64_t, 4> sfu_table_list;
    for (int64_t i = 0; OB_SUCC(ret) && i < stmt->get_table_size(); ++i) {
      const TableItem *table = NULL;
      if (OB_ISNULL(table = stmt->get_table_item(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("table item is null", K(ret), K(i), K(table));
      } else if (!table->for_update_ || table_is_allocated_for_update(table->table_id_)) {
        // do nothing
      } else if (OB_FAIL(sfu_table_list.push_back(table->table_id_))) {
        LOG_WARN("failed to push back", K(ret));
      }
O
oceanbase-admin 已提交
12493
    }
W
wangzelin.wzl 已提交
12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516
    if (OB_SUCC(ret) && !sfu_table_list.empty()) {
      if (OB_FAIL(get_minimal_cost_candidates(candidates_.candidate_plans_, best_plans))) {
        LOG_WARN("failed to get minimal cost candidates", K(ret));
      } else {
        for (int64_t i = 0; OB_SUCC(ret) && i < best_plans.count(); i++) {
          ObSEArray<int64_t, 4> origin_alloc_sfu_list;
          if (i != best_plans.count() - 1 &&
              OB_FAIL(origin_alloc_sfu_list.assign(get_alloc_sfu_list()))) {
            LOG_WARN("failed to assign", K(ret));
          } else if (OB_FAIL(allocate_for_update_as_top(best_plans.at(i).plan_tree_,
                                                                   sfu_table_list))) {
            LOG_WARN("allocate for update as top", K(ret));
          } else if (i != best_plans.count() - 1 &&
                     OB_FAIL(get_alloc_sfu_list().assign(origin_alloc_sfu_list))) {
            LOG_WARN("failed to assign", K(ret));
          } else {/*do nothing*/}
        }
        if (OB_SUCC(ret)) {
          if (OB_FAIL(prune_and_keep_best_plans(best_plans))) {
            LOG_WARN("failed to prune and keep best plans", K(ret));
          } else { /*do nothing*/ }
        }
      }
O
oceanbase-admin 已提交
12517 12518 12519 12520 12521
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12522 12523
int ObLogPlan::allocate_for_update_as_top(ObLogicalOperator *&top,
                                          ObIArray<uint64_t> &sfu_table_list)
O
oceanbase-admin 已提交
12524 12525
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536
  for (int64_t i = 0; OB_SUCC(ret) && i < sfu_table_list.count(); ++i) {
    ObSEArray<uint64_t, 1> need_alloc_list;
    if (table_is_allocated_for_update(sfu_table_list.at(i))) {
      //do nothing
    } else if (OB_FAIL(need_alloc_list.push_back(sfu_table_list.at(i)))) {
      LOG_WARN("failed to push back", K(ret));
    } else if (OB_FAIL(merge_same_sfu_table_list(sfu_table_list.at(i),
                                                 i + 1,
                                                 sfu_table_list,
                                                 need_alloc_list))) {
      LOG_WARN("failed to merge same sfu table list", K(ret));
O
oceanbase-admin 已提交
12537
    } else {
W
wangzelin.wzl 已提交
12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581
      int64_t wait_ts = 0;
      bool skip_locked = false;
      ObRawExpr *lock_rownum = NULL;
      ObSEArray<IndexDMLInfo*, 1> index_dml_infos;
      for (int64_t j = 0; OB_SUCC(ret) && j < need_alloc_list.count(); ++j) {
        IndexDMLInfo *index_dml_info = NULL;
        if (OB_FAIL(get_table_for_update_info(need_alloc_list.at(j),
                                              index_dml_info,
                                              wait_ts,
                                              skip_locked))) {
          LOG_WARN("failed to get for update info", K(ret));
        } else if (OB_ISNULL(index_dml_info)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(ret), K(index_dml_info));
        } else if (OB_FAIL(index_dml_infos.push_back(index_dml_info))) {
          LOG_WARN("failed to push back", K(ret));
        } else {/*do nothing*/}
      }
      if (OB_SUCC(ret) && skip_locked) {
        ObPseudoColumnRawExpr* pseudo_expr = NULL;
        if (OB_FAIL(get_optimizer_context().get_expr_factory().create_raw_expr(
                      T_MULTI_LOCK_ROWNUM, pseudo_expr))) {
          LOG_WARN("fail to allocate rownum_expr_", K(ret));
        } else if (OB_ISNULL(pseudo_expr)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("rownum_expr_ is null");
        } else {
          lock_rownum = pseudo_expr;
          lock_rownum->set_data_type(ObIntType),
          lock_rownum->set_accuracy(ObAccuracy::MAX_ACCURACY[ObIntType]);
        }
      }
      if (OB_FAIL(ret)) {
      } else if (OB_FAIL(create_for_update_plan(top,
                                                index_dml_infos,
                                                wait_ts,
                                                skip_locked,
                                                lock_rownum))) {
        LOG_WARN("failed to create update plan", K(ret));
      } else if (OB_FAIL(append(alloc_sfu_list_, need_alloc_list))) {
        LOG_WARN("failed to append", K(ret));
      } else {
        LOG_TRACE("succced to allocate for update as top", K(sfu_table_list), K(alloc_sfu_list_));
      }
O
oceanbase-admin 已提交
12582 12583 12584 12585 12586
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12587 12588 12589 12590
int ObLogPlan::merge_same_sfu_table_list(uint64_t target_id,
                                         int64_t begin_idx,
                                         ObIArray<uint64_t> &src_table_list,
                                         ObIArray<uint64_t> &res_table_list)
O
oceanbase-admin 已提交
12591 12592
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611
  const TableItem *target_table = NULL;
  if (OB_ISNULL(get_stmt()) ||
      OB_ISNULL(target_table = get_stmt()->get_table_item_by_id(target_id)) ||
      OB_UNLIKELY(!target_table->for_update_ || begin_idx < 1)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected error", K(get_stmt()), KPC(target_table), K(target_id),
                                     K(begin_idx), K(ret));
  } else {
    for (int64_t i = begin_idx; OB_SUCC(ret) && i < src_table_list.count(); ++i) {
      const TableItem *tmp_table = NULL;
      if (OB_ISNULL(tmp_table = get_stmt()->get_table_item_by_id(src_table_list.at(i))) ||
          OB_UNLIKELY(!tmp_table->for_update_)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected error", K(ret), KPC(tmp_table));
      } else if (target_table->for_update_wait_us_ == tmp_table->for_update_wait_us_ &&
                 target_table->skip_locked_ == tmp_table->skip_locked_) {
        if (OB_FAIL(res_table_list.push_back(src_table_list.at(i)))) {
          LOG_WARN("failed to push back", K(ret));
        } else {/*do nothing*/}
O
oceanbase-admin 已提交
12612 12613 12614 12615 12616 12617
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12618 12619 12620
int ObLogPlan::get_part_column_exprs(const uint64_t table_id,
                                     const uint64_t ref_table_id,
                                     ObIArray<ObRawExpr*> &part_exprs) const
O
oceanbase-admin 已提交
12621 12622
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642
  ObRawExpr *expr = NULL;
  ObSEArray<ObRawExpr*, 8> temp_exprs;
  if (OB_ISNULL(get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("stmt is null", K(ret));
  } else if (NULL == (expr = get_stmt()->get_part_expr(table_id, ref_table_id))) {
    // do nothing
  } else if (OB_FAIL(ObRawExprUtils::extract_column_exprs(expr, temp_exprs))) {
    LOG_WARN("failed to extract column exprs", K(ret));
  } else if (OB_FAIL(part_exprs.assign(temp_exprs))) {
    LOG_WARN("failed to assign exprs", K(ret));
  } else if (NULL == (expr = get_stmt()->get_subpart_expr(table_id, ref_table_id))) {
    // do nothing
  } else if (FALSE_IT(temp_exprs.reset())) {
    /*do nothing*/
  } else if (OB_FAIL(ObRawExprUtils::extract_column_exprs(expr, temp_exprs))) {
    LOG_WARN("failed to extract column exprs", K(ret));
  } else if (OB_FAIL(append_array_no_dup(part_exprs, temp_exprs))) {
    LOG_WARN("failed to append exprs", K(ret));
  } else { /*do nothing*/ }
O
oceanbase-admin 已提交
12643 12644 12645
  return ret;
}

W
wangzelin.wzl 已提交
12646 12647 12648 12649
int ObLogPlan::get_table_for_update_info(const uint64_t table_id,
                                         IndexDMLInfo *&index_dml_info,
                                         int64_t &wait_ts,
                                         bool &skip_locked)
O
oceanbase-admin 已提交
12650 12651
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12652 12653 12654 12655 12656 12657 12658
  const TableItem *table = NULL;
  skip_locked = false;
  wait_ts = 0;
  index_dml_info = NULL;
  if (OB_ISNULL(get_stmt()) ||
      OB_ISNULL(table = get_stmt()->get_table_item_by_id(table_id)) ||
      OB_UNLIKELY(!table->for_update_)) {
O
oceanbase-admin 已提交
12659
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12660
    LOG_WARN("get unexpected error", K(get_stmt()), KPC(table), K(ret));
O
oceanbase-admin 已提交
12661
  } else {
W
wangzelin.wzl 已提交
12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697
    bool is_nullable = false;
    ObSEArray<ObRawExpr*, 4> temp_rowkeys;
    if (OB_UNLIKELY(!table->is_basic_table()) || OB_UNLIKELY(is_virtual_table(table->ref_id_))) {
      // invalid usage
      ret = OB_ERR_FOR_UPDATE_SELECT_VIEW_CANNOT;
      LOG_USER_ERROR(OB_ERR_FOR_UPDATE_SELECT_VIEW_CANNOT);
    } else if (OB_FAIL(get_rowkey_exprs(table->table_id_, table->ref_id_, temp_rowkeys))) {
      LOG_WARN("failed to generate rowkey exprs", K(ret));
    } else if (OB_FAIL(ObOptimizerUtil::is_table_on_null_side(get_stmt(),
                                                              table->table_id_,
                                                              is_nullable))) {
      LOG_WARN("failed to check is table on null side", K(ret));
    } else if (OB_ISNULL(index_dml_info = static_cast<IndexDMLInfo *>(
                       get_optimizer_context().get_allocator().alloc(sizeof(IndexDMLInfo))))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("failed to allocate memory for index dml info", K(ret));
    } else {
      index_dml_info = new (index_dml_info) IndexDMLInfo();
      index_dml_info->table_id_ = table->table_id_;
      index_dml_info->loc_table_id_ = table->get_base_table_item().table_id_;
      index_dml_info->ref_table_id_ = table->ref_id_;
      index_dml_info->distinct_algo_ = T_DISTINCT_NONE;
      index_dml_info->rowkey_cnt_ = temp_rowkeys.count();
      index_dml_info->need_filter_null_ = is_nullable;
      index_dml_info->is_primary_index_ = true;
      for (int64_t i = 0; OB_SUCC(ret) && i < temp_rowkeys.count(); ++i) {
        if (OB_ISNULL(temp_rowkeys.at(i)) ||
            OB_UNLIKELY(!temp_rowkeys.at(i)->is_column_ref_expr())) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid rowkey expr", K(ret), K(temp_rowkeys.at(i)));
        } else if (OB_FAIL(index_dml_info->column_exprs_.push_back(
                              static_cast<ObColumnRefRawExpr*>(temp_rowkeys.at(i))))) {
          LOG_WARN("failed to push back column expr", K(ret));
        } else {
          temp_rowkeys.at(i)->set_explicited_reference();
        }
O
oceanbase-admin 已提交
12698
      }
W
wangzelin.wzl 已提交
12699 12700 12701 12702 12703
      ObArray<ObRawExpr*> tmp_partkey_exprs;
      if (OB_SUCC(ret)) {
        if (OB_FAIL(get_part_column_exprs(table->table_id_, table->ref_id_, tmp_partkey_exprs))) {
          LOG_WARN("get part column exprs failed", K(ret));
        }
O
oceanbase-admin 已提交
12704
      }
W
wangzelin.wzl 已提交
12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721
      for (int i = 0; OB_SUCC(ret) && i < tmp_partkey_exprs.count(); ++i) {
        if (OB_ISNULL(tmp_partkey_exprs.at(i)) ||
            OB_UNLIKELY(!tmp_partkey_exprs.at(i)->is_column_ref_expr())) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid rowkey expr", K(ret), K(temp_rowkeys.at(i)));
        } else if (OB_FAIL(add_var_to_array_no_dup(index_dml_info->column_exprs_,
                                                   static_cast<ObColumnRefRawExpr*>(tmp_partkey_exprs.at(i))))) {
          LOG_WARN("failed to push back column expr", K(ret));
        } else {
          tmp_partkey_exprs.at(i)->set_explicited_reference();
        }
      }
      if (OB_SUCC(ret)) {
        wait_ts = table->for_update_wait_us_;
        skip_locked = table->skip_locked_;
        LOG_TRACE("Succeed to get table for update info", K(table_id), K(*index_dml_info),
                                                          K(wait_ts), K(skip_locked));
O
oceanbase-admin 已提交
12722 12723 12724 12725 12726 12727
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
12728 12729 12730 12731 12732
int ObLogPlan::create_for_update_plan(ObLogicalOperator *&top,
                                      const ObIArray<IndexDMLInfo *> &index_dml_infos,
                                      int64_t wait_ts,
                                      bool skip_locked,
                                      ObRawExpr *lock_rownum)
O
oceanbase-admin 已提交
12733 12734
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12735 12736 12737
  bool is_multi_part_dml = false;
  bool is_result_local = false;
  if (OB_ISNULL(top) || OB_ISNULL(get_stmt())) {
O
oceanbase-admin 已提交
12738
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(check_need_multi_partition_dml(*get_stmt(),
                                                    *top,
                                                    index_dml_infos,
                                                    is_multi_part_dml,
                                                    is_result_local))) {
    LOG_WARN("failed to check need multi-partition dml", K(ret));
  } else if (OB_FAIL(allocate_for_update_as_top(top,
                                                is_multi_part_dml,
                                                index_dml_infos,
                                                wait_ts,
                                                skip_locked,
                                                lock_rownum))) {
    LOG_WARN("failed to allocate delete as top", K(ret));
  } else {
    optimizer_context_.set_for_update();
O
oceanbase-admin 已提交
12755 12756 12757 12758
  }
  return ret;
}

W
wangzelin.wzl 已提交
12759 12760 12761 12762 12763 12764
int ObLogPlan::allocate_for_update_as_top(ObLogicalOperator *&top,
                                          const bool is_multi_part_dml,
                                          const ObIArray<IndexDMLInfo *> &index_dml_infos,
                                          int64_t wait_ts,
                                          bool skip_locked,
                                          ObRawExpr *lock_rownum)
O
oceanbase-admin 已提交
12765
{
W
wangzelin.wzl 已提交
12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787
  int ret = OB_SUCCESS;
  ObLogForUpdate *for_update_op = NULL;
  if (OB_ISNULL(for_update_op = static_cast<ObLogForUpdate *>(
                get_log_op_factory().allocate(*this, LOG_FOR_UPD)))) {
    ret = OB_ALLOCATE_MEMORY_FAILED;
    LOG_ERROR("failed to allocate for update operator", K(ret));
  } else if (OB_FAIL(for_update_op->add_child(top))) {
    LOG_WARN("failed to add child for for_update operator", K(ret));
  } else if (OB_FAIL(for_update_op->get_index_dml_infos().assign(index_dml_infos))) {
    LOG_WARN("failed to assign index dml info", K(ret));
  } else {
    for_update_op->set_wait_ts(wait_ts);
    for_update_op->set_skip_locked(skip_locked);
    for_update_op->set_is_multi_part_dml(is_multi_part_dml);
    for_update_op->set_lock_rownum(lock_rownum);
    if (OB_FAIL(for_update_op->compute_property())) {
      LOG_WARN("failed to compute property", K(ret));
    } else {
      top = for_update_op;
      LOG_TRACE("Succeed to allocate for update as top", K(is_multi_part_dml), K(index_dml_infos),
                                                      K(wait_ts), K(skip_locked), KPC(lock_rownum));
    }
O
oceanbase-admin 已提交
12788
  }
W
wangzelin.wzl 已提交
12789
  return ret;
O
oceanbase-admin 已提交
12790 12791
}

W
wangzelin.wzl 已提交
12792
bool ObLogPlan::table_is_allocated_for_update(const int64_t table_id)
O
oceanbase-admin 已提交
12793
{
W
wangzelin.wzl 已提交
12794 12795 12796
  bool is_allocated = false;
  for (int64_t i = 0; !is_allocated && i < alloc_sfu_list_.count(); ++i) {
    is_allocated = table_id == alloc_sfu_list_.at(i);
O
oceanbase-admin 已提交
12797
  }
W
wangzelin.wzl 已提交
12798
  return is_allocated;
O
oceanbase-admin 已提交
12799 12800
}

W
wangzelin.wzl 已提交
12801 12802
int ObLogPlan::get_cache_calc_part_id_expr(int64_t table_id, int64_t ref_table_id,
    CalcPartIdType calc_type, ObRawExpr* &expr)
O
oceanbase-admin 已提交
12803
{
W
wangzelin.wzl 已提交
12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814
  int ret = OB_SUCCESS;
  bool find = false;
  expr = NULL;
  for (int64_t i = 0; !find && i < cache_part_id_exprs_.count(); ++i) {
    PartIdExpr &part_id_expr = cache_part_id_exprs_.at(i);
    if (part_id_expr.table_id_ == table_id &&
        part_id_expr.ref_table_id_ == ref_table_id &&
        calc_type == part_id_expr.calc_type_) {
      expr = part_id_expr.calc_part_id_expr_;
      find = true;
    }
O
oceanbase-admin 已提交
12815
  }
W
wangzelin.wzl 已提交
12816
  return ret;
O
oceanbase-admin 已提交
12817 12818
}

W
wangzelin.wzl 已提交
12819 12820 12821 12822 12823
int ObLogPlan::get_part_exprs(uint64_t table_id,
                              uint64_t ref_table_id,
                              share::schema::ObPartitionLevel &part_level,
                              ObRawExpr *&part_expr,
                              ObRawExpr *&subpart_expr)
O
oceanbase-admin 已提交
12824 12825
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12826 12827 12828 12829 12830 12831 12832 12833
  part_expr = NULL;
  subpart_expr = NULL;
  const ObDMLStmt *stmt = NULL;
  share::schema::ObSchemaGetterGuard *schema_guard = NULL;
  const share::schema::ObTableSchema *table_schema = NULL;
  ObSQLSessionInfo *session = NULL;
  if (OB_ISNULL(stmt = get_stmt())
      || OB_INVALID_ID == ref_table_id) {
O
oceanbase-admin 已提交
12834
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845
    LOG_WARN("invalid id", K(ref_table_id), K(ret));
  } else if (OB_ISNULL(schema_guard = get_optimizer_context().get_schema_guard()) ||
             OB_ISNULL(session = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("NULL ptr", K(ret));
  } else if (OB_FAIL(schema_guard->get_table_schema(session->get_effective_tenant_id(),
                                                    ref_table_id, table_schema))) {
    LOG_WARN("get table schema failed", K(ref_table_id), K(ret));
  } else if (OB_ISNULL(table_schema)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("table schema is null", K(ret), K(table_schema));
O
oceanbase-admin 已提交
12846
  } else {
W
wangzelin.wzl 已提交
12847 12848 12849 12850 12851 12852 12853 12854 12855
    part_level = table_schema->get_part_level();
    part_expr = stmt->get_part_expr(table_id, ref_table_id);
    subpart_expr = stmt->get_subpart_expr(table_id, ref_table_id);
    if (NULL != part_expr) {
      part_expr->set_explicited_reference();
    }
    if (NULL != subpart_expr) {
      subpart_expr->set_explicited_reference();
    }
O
oceanbase-admin 已提交
12856
  }
W
wangzelin.wzl 已提交
12857

O
oceanbase-admin 已提交
12858 12859 12860
  return ret;
}

O
obdev 已提交
12861 12862 12863 12864 12865 12866 12867 12868 12869 12870
int ObLogPlan::create_hash_sortkey(const int64_t part_cnt,
                                   const common::ObIArray<OrderItem> &order_keys,
                                   OrderItem &hash_sortkey)
{
  int ret = OB_SUCCESS;
  ObOpRawExpr *hash_expr = NULL;
  ObRawExprFactory &expr_factory = get_optimizer_context().get_expr_factory();
  ObExecContext *exec_ctx = get_optimizer_context().get_exec_ctx();
  if (OB_FAIL(expr_factory.create_raw_expr(T_FUN_SYS_HASH, hash_expr))) {
    LOG_WARN("failed to create raw expr", K(ret));
12871 12872 12873
  } else if (OB_UNLIKELY(part_cnt > order_keys.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected order_keys count", K(ret), K(part_cnt), K(order_keys));
O
obdev 已提交
12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < part_cnt; ++i) {
      if (OB_FAIL(hash_expr->add_param_expr(order_keys.at(i).expr_))) {
        LOG_WARN("failed to add param expr", K(ret));
      }
    }
  }
  if (OB_FAIL(ret)) {
    //do nothing
  } else if (OB_FAIL(hash_expr->formalize(exec_ctx->get_my_session()))) {
    LOG_WARN("failed to formalize expr", K(ret));
  } else {
    hash_sortkey.expr_ = hash_expr;
    hash_sortkey.order_type_ = default_asc_direction();
  }
  return ret;
}

W
wangzelin.wzl 已提交
12892 12893 12894 12895
int ObLogPlan::gen_calc_part_id_expr(uint64_t table_id,
                                     uint64_t ref_table_id,
                                     CalcPartIdType calc_id_type,
                                     ObRawExpr *&expr)
O
oceanbase-admin 已提交
12896
{
W
wangzelin.wzl 已提交
12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957
  int ret = OB_SUCCESS;
  expr = NULL;
  ObSQLSessionInfo *session = NULL;
  share::schema::ObPartitionLevel part_level = share::schema::PARTITION_LEVEL_MAX;
  ObRawExpr *part_expr = NULL;
  ObRawExpr *subpart_expr = NULL;
  if (OB_FAIL(get_cache_calc_part_id_expr(table_id, ref_table_id, calc_id_type, expr))) {
    LOG_WARN("failed to get cache calc part id expr", K(ret));
  } else if (NULL != expr) {
    //do nothing
  } else if (OB_INVALID_ID == ref_table_id) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpect table if", K(ret));
  } else if (OB_ISNULL(session = get_optimizer_context().get_session_info())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("session info is null");
  } else if (OB_FAIL(get_part_exprs(table_id,
                                    ref_table_id,
                                    part_level,
                                    part_expr,
                                    subpart_expr))) {
    LOG_WARN("fail to get part exprs", K(ret));
  } else {
    ObRawExprFactory &expr_factory = get_optimizer_context().get_expr_factory();
    if (CALC_TABLET_ID == calc_id_type) {
      if (OB_FAIL(ObRawExprUtils::build_calc_tablet_id_expr(expr_factory,
                                                            *session,
                                                            ref_table_id,
                                                            part_level,
                                                            part_expr,
                                                            subpart_expr,
                                                            expr))) {
        LOG_WARN("fil to build table location expr", K(ret));
      }
    } else if (CALC_PARTITION_ID == calc_id_type) {
      if (OB_FAIL(ObRawExprUtils::build_calc_part_id_expr(expr_factory,
                                                          *session,
                                                          ref_table_id,
                                                          part_level,
                                                          part_expr,
                                                          subpart_expr,
                                                          expr))) {
        LOG_WARN("fail to build table location expr", K(ret));
      }
    } else if (OB_FAIL(ObRawExprUtils::build_calc_partition_tablet_id_expr(expr_factory,
                                                                           *session,
                                                                           ref_table_id,
                                                                           part_level,
                                                                           part_expr,
                                                                           subpart_expr,
                                                                           expr))) {
      LOG_WARN("fail to build table location expr", K(ret));
    }
    if (OB_SUCC(ret)) {
      PartIdExpr part_id_expr;
      part_id_expr.table_id_ = table_id;
      part_id_expr.ref_table_id_ = ref_table_id;
      part_id_expr.calc_part_id_expr_ = expr;
      part_id_expr.calc_type_ = calc_id_type;
      if (OB_FAIL(cache_part_id_exprs_.push_back(part_id_expr))) {
        LOG_WARN("failed to push back part id expr", K(ret));
O
oceanbase-admin 已提交
12958 12959 12960
      }
    }
  }
W
wangzelin.wzl 已提交
12961
  return ret;
O
oceanbase-admin 已提交
12962 12963
}

12964 12965
// this function is used to allocate the material operator to the for-update operator
int ObLogPlan::candi_allocate_for_update_material()
O
oceanbase-admin 已提交
12966 12967
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
12968
  ObSEArray<CandidatePlan, 8> best_plans;
12969
  ObExchangeInfo exch_info;
W
wangzelin.wzl 已提交
12970 12971 12972 12973 12974 12975 12976
  if (OB_FAIL(get_minimal_cost_candidates(candidates_.candidate_plans_, best_plans))) {
    LOG_WARN("failed to get minimal cost candidates", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < best_plans.count(); i++) {
    if (OB_ISNULL(best_plans.at(i).plan_tree_)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null pointer", K(ret));
12977 12978 12979
    } else if (best_plans.at(i).plan_tree_->is_distributed() &&
              OB_FAIL(allocate_exchange_as_top(best_plans.at(i).plan_tree_, exch_info))) {
      LOG_WARN("failed to allocate exchange op", K(ret));
W
wangzelin.wzl 已提交
12980 12981 12982 12983 12984 12985 12986 12987
    } else if (OB_FAIL(allocate_material_as_top(best_plans.at(i).plan_tree_))) {
      LOG_WARN("fail to allocate material as top", K(ret));
    }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(prune_and_keep_best_plans(best_plans))) {
      LOG_WARN("failed to prune and keep best plans", K(ret));
    } else { /*do nothing*/ }
O
oceanbase-admin 已提交
12988 12989 12990 12991
  }
  return ret;
}

W
wangzelin.wzl 已提交
12992 12993 12994 12995 12996 12997
int ObLogPlan::add_extra_dependency_table() const
{
  return OB_SUCCESS;
}

int ObLogPlan::simplify_win_expr(ObLogicalOperator* child_op, ObWinFunRawExpr &win_expr)
O
oceanbase-admin 已提交
12998 12999
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
13000 13001 13002 13003
  if (OB_FAIL(simplify_win_partition_exprs(child_op, win_expr))) {
    LOG_WARN("failed to simplify win partition exprs", K(ret));
  } else if(OB_FAIL(simplify_win_order_items(child_op, win_expr))) {
    LOG_WARN("failed to simplify win order items", K(ret));
O
oceanbase-admin 已提交
13004 13005 13006 13007
  }
  return ret;
}

W
wangzelin.wzl 已提交
13008
int ObLogPlan::perform_simplify_win_expr(ObLogicalOperator *op)
O
oceanbase-admin 已提交
13009 13010
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021
  ObLogWindowFunction *win_func = NULL;
  if (OB_NOT_NULL(win_func = dynamic_cast<ObLogWindowFunction *>(op))) {
    for (int64_t i = 0; OB_SUCC(ret) && i < win_func->get_window_exprs().count(); ++i) {
      ObWinFunRawExpr *win_expr = win_func->get_window_exprs().at(i);
      if (OB_UNLIKELY(op->get_num_of_child() == 0)) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("window function op should have child", K(ret));
      } else if (OB_FAIL(simplify_win_expr(op->get_child(ObLogicalOperator::first_child), *win_expr))) {
        LOG_WARN("transform win func failed", K(ret));
      } else if (OB_FAIL(win_expr->formalize(get_optimizer_context().get_session_info()))) {
        LOG_WARN("formalize win func expr failed", K(ret));
O
oceanbase-admin 已提交
13022
      }
W
wangzelin.wzl 已提交
13023 13024 13025 13026
    }
  }
  return ret;
}
O
oceanbase-admin 已提交
13027

W
wangzelin.wzl 已提交
13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042
int ObLogPlan::simplify_win_partition_exprs(ObLogicalOperator* child_op,
                                               ObWinFunRawExpr& win_expr)
{
  int ret = OB_SUCCESS;
  bool is_const = false;
  ObIArray<ObRawExpr *>& partition_exprs = win_expr.get_partition_exprs();
  ObSEArray<ObRawExpr *, 4> new_partition_exprs;
  for (int64_t i = 0; OB_SUCC(ret) && i < partition_exprs.count(); ++i) {
    ObRawExpr *part_expr = partition_exprs.at(i);
    if (OB_ISNULL(part_expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("part expr is null", K(ret));
    } else if (OB_FAIL(ObOptimizerUtil::is_const_expr(part_expr,
                                                      child_op->get_output_equal_sets(),
                                                      child_op->get_output_const_exprs(),
O
obdev 已提交
13043
                                                      onetime_query_refs_,
W
wangzelin.wzl 已提交
13044 13045 13046 13047 13048
                                                      is_const))) {
      LOG_WARN("check is const expr failed", K(ret));
    } else if (is_const) {
    } else if (OB_FAIL(new_partition_exprs.push_back(part_expr))) {
      LOG_WARN("failed to push back expr", K(ret));
O
oceanbase-admin 已提交
13049
    }
W
wangzelin.wzl 已提交
13050
  }
O
oceanbase-admin 已提交
13051

W
wangzelin.wzl 已提交
13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084
  if (OB_FAIL(ret)) {
  } else if (OB_FALSE_IT(partition_exprs.reuse())) {
  } else if (OB_UNLIKELY(new_partition_exprs.empty())) {
    // do nothing, item is empty, no need simplify
  } else if (OB_FAIL(ObOptimizerUtil::simplify_exprs(child_op->get_fd_item_set(),
                                                     child_op->get_output_equal_sets(),
                                                     child_op->get_output_const_exprs(),
                                                     new_partition_exprs,
                                                     partition_exprs))) {
    LOG_WARN("failed to simplify exprs", K(ret));
  } else { /*do nothing*/ }

  return ret;
}

int ObLogPlan::simplify_win_order_items(ObLogicalOperator* child_op,
                                          ObWinFunRawExpr& win_expr
                                           )
{
  int ret = OB_SUCCESS;
  ObRawExpr* first_order_expr = NULL;
  bool is_const = false;
  ObIArray<OrderItem> &order_items = win_expr.get_order_items();
  ObSEArray<OrderItem, 4> new_order_items;
  for (int64_t i = 0; OB_SUCC(ret) && i < order_items.count(); ++i) {
    ObRawExpr *order_expr = order_items.at(i).expr_;
    if (OB_ISNULL(order_expr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("order expr is null", K(ret));
    } else if (i == 0 && OB_FALSE_IT(first_order_expr = order_expr))  {
    } else if (OB_FAIL(ObOptimizerUtil::is_const_expr(order_expr,
                                                      child_op->get_output_equal_sets(),
                                                      child_op->get_output_const_exprs(),
O
obdev 已提交
13085
                                                      onetime_query_refs_,
W
wangzelin.wzl 已提交
13086 13087 13088 13089 13090
                                                      is_const))) {
      LOG_WARN("check is const expr failed", K(ret));
    } else if (is_const) {
    } else if (OB_FAIL(new_order_items.push_back(order_items.at(i)))) {
      LOG_WARN("failed to push back expr", K(ret));
O
oceanbase-admin 已提交
13091
    }
W
wangzelin.wzl 已提交
13092
  }
O
oceanbase-admin 已提交
13093

W
wangzelin.wzl 已提交
13094 13095 13096 13097 13098 13099 13100
  if (OB_FAIL(ret)) {
  } else if (OB_FALSE_IT(order_items.reuse())) {
  } else if (OB_UNLIKELY(new_order_items.empty())) {
    // do nothing, item is empty, no need simplify
  } else if (OB_FAIL(ObOptimizerUtil::simplify_ordered_exprs(child_op->get_fd_item_set(),
                                                             child_op->get_output_equal_sets(),
                                                             child_op->get_output_const_exprs(),
O
obdev 已提交
13101
                                                             onetime_query_refs_,
W
wangzelin.wzl 已提交
13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115
                                                             new_order_items,
                                                             order_items))) {
    LOG_WARN("failed to simplify ordered exprs", K(ret));
  }

  if (OB_SUCC(ret)
      && order_items.count() == 0
      && OB_NOT_NULL(first_order_expr)) {
    // for computing range frame
    // at least one order item when executing
    if (win_expr.win_type_ == WINDOW_RANGE &&
        OB_FAIL(ObTransformUtils::rebuild_win_compare_range_expr(&get_optimizer_context().get_expr_factory(),
                                                                 win_expr, first_order_expr))) {
      LOG_WARN("failed to rebuild win compare range expr", K(ret));
O
oceanbase-admin 已提交
13116 13117 13118 13119 13120
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
13121 13122 13123 13124
int ObLogPlan::compute_subplan_filter_repartition_distribution_info(ObLogicalOperator *top,
                                                                    const ObIArray<ObLogicalOperator*> &subquery_ops,
                                                                    const ObIArray<ObExecParamRawExpr *> &params,
                                                                    ObExchangeInfo &exch_info)
O
oceanbase-admin 已提交
13125 13126
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
13127 13128
  EqualSets input_esets;
  if (OB_ISNULL(top) || OB_UNLIKELY(subquery_ops.empty())) {
O
oceanbase-admin 已提交
13129
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
13130 13131 13132
    LOG_WARN("get unexpected null", K(ret), K(top), K(subquery_ops.empty()));
  } else if (OB_FAIL(append(input_esets, top->get_output_equal_sets()))) {
    LOG_WARN("failed to append equal sets", K(ret));
O
oceanbase-admin 已提交
13133
  } else {
W
wangzelin.wzl 已提交
13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146
    ObLogicalOperator *child = NULL;
    ObLogicalOperator *right_child = subquery_ops.at(0);
    ObSEArray<ObRawExpr*, 4> left_keys;
    ObSEArray<ObRawExpr*, 4> right_keys;
    ObSEArray<bool, 4> null_safe_info;
    for (int64_t i = 0; OB_SUCC(ret) && i < subquery_ops.count(); i++) {
      if (OB_ISNULL(child = subquery_ops.at(i))) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(append(input_esets, child->get_output_equal_sets()))) {
        LOG_WARN("failed to append input equal sets", K(ret));
      } else { /*do nothing*/ }
    }
O
oceanbase-admin 已提交
13147

W
wangzelin.wzl 已提交
13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163
    if (OB_FAIL(ret)) {
    } else if (OB_FAIL(get_subplan_filter_equal_keys(right_child,
                                                     params,
                                                     left_keys,
                                                     right_keys,
                                                     null_safe_info))) {
      LOG_WARN("failed to get subplan filter equal key", K(ret));
    } else if (compute_repartition_distribution_info(input_esets,
                                                     left_keys,
                                                     right_keys,
                                                     *right_child,
                                                     exch_info)) {
      LOG_WARN("failed to compute repartition distribution info", K(ret));
    } else {
      exch_info.unmatch_row_dist_method_ = ObPQDistributeMethod::DROP;
      LOG_TRACE("succeed to compute repartition distribution info", K(exch_info));
O
oceanbase-admin 已提交
13164 13165 13166 13167
    }
  }
  return ret;
}
O
obdev 已提交
13168

O
obdev 已提交
13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202
int ObLogPlan::perform_adjust_onetime_expr(ObLogicalOperator *op)
{
  int ret = OB_SUCCESS;
  ObLogSubPlanFilter *subplan_filter = NULL;
  if (OB_ISNULL(op)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected null op", K(ret));
  } else if (OB_FAIL(init_onetime_replaced_exprs_if_needed())) {
    LOG_WARN("faile to init onetime replaced exprs", K(ret));
  } else if (NULL != (subplan_filter = dynamic_cast<ObLogSubPlanFilter *>(op))) {
    if (OB_FAIL(subplan_filter->replace_nested_subquery_exprs(onetime_replaced_exprs_))) {
      LOG_WARN("failed to replace nested subquery exprs", K(ret));
    }
  }
  if (OB_SUCC(ret) && OB_FAIL(op->replace_op_exprs(onetime_replaced_exprs_))) {
    LOG_WARN("failed to replace onetime subquery", K(ret));
  }
  return ret;
}

int ObLogPlan::init_onetime_replaced_exprs_if_needed()
{
  int ret = OB_SUCCESS;
  if (0 == onetime_params_.count() || onetime_replaced_exprs_.count() > 0) {
    // do nothing
  } else if (OB_ISNULL(onetime_copier_)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("onetime expr copier is null", K(ret));
  } else if (OB_FAIL(onetime_copier_->get_copied_exprs(onetime_replaced_exprs_))) {
    LOG_WARN("failed to get copied exprs", K(ret));
  }
  return ret;
}

O
obdev 已提交
13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233
int ObLogPlan::allocate_material_for_recursive_cte_plan(ObIArray<ObLogicalOperator*> &child_ops)
{
  int ret = OB_SUCCESS;
  ObLogPlan *log_plan = NULL;
  int64_t fake_cte_pos = -1;
  for (int64_t i = 0; OB_SUCC(ret) && fake_cte_pos == -1 && i < child_ops.count(); i++) {
    if (OB_ISNULL(child_ops.at(i))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (child_ops.at(i)->get_contains_fake_cte()) {
      fake_cte_pos = i;
    } else { /*do nothing*/ }
  }
  if (OB_SUCC(ret) && fake_cte_pos != -1) {
    for (int64_t i = 0; OB_SUCC(ret) && i < child_ops.count(); i++) {
      if (OB_ISNULL(child_ops.at(i)) || OB_ISNULL(log_plan = child_ops.at(i)->get_plan())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (i == fake_cte_pos) {
        if (OB_FAIL(SMART_CALL(allocate_material_for_recursive_cte_plan(child_ops.at(i)->get_child_list())))) {
          LOG_WARN("failed to adjust recursive cte plan", K(ret));
        } else { /*do nothing*/ }
      } else if (log_op_def::LOG_MATERIAL != child_ops.at(i)->get_type() &&
                 log_op_def::LOG_TABLE_SCAN != child_ops.at(i)->get_type() &&
                 log_op_def::LOG_EXPR_VALUES != child_ops.at(i)->get_type() &&
                 OB_FAIL(log_plan->allocate_material_as_top(child_ops.at(i)))) {
        LOG_WARN("failed to allocate materialize as top", K(ret));
      } else { /*do nothing*/ }
    }
  }
  return ret;
13234
}
O
obdev 已提交
13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574

int ObLogPlan::find_possible_join_filter_tables(ObLogicalOperator *op,
                                                const JoinFilterPushdownHintInfo &hint_info,
                                                ObRelIds &right_tables,
                                                bool is_current_dfo,
                                                bool is_fully_partition_wise,
                                                const ObIArray<ObRawExpr*> &left_join_conditions,
                                                const ObIArray<ObRawExpr*> &right_join_conditions,
                                                ObIArray<JoinFilterInfo> &join_filter_infos)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt* stmt;
  if (OB_ISNULL(op)
      || OB_ISNULL(stmt = get_stmt())
      || OB_ISNULL(stmt->get_query_ctx())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (op->get_type() == log_op_def::LOG_SET) {
    for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); ++i) {
      ObLogicalOperator* child_op;
      ObLogPlan* child_plan;
      if (OB_ISNULL(child_op = op->get_child(i)) ||
          OB_ISNULL(child_plan = child_op->get_plan())) {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("get unexpected null", K(ret));
      } else if (OB_FAIL(child_plan->pushdown_join_filter_into_subquery(stmt,
                                                                        child_op,
                                                                        ObTabletID::INVALID_TABLET_ID,
                                                                        hint_info,
                                                                        is_current_dfo,
                                                                        op->is_fully_paratition_wise(),
                                                                        left_join_conditions,
                                                                        right_join_conditions,
                                                                        join_filter_infos))) {
        LOG_WARN("failed to find pushdown join filter table", K(ret));
      }
    }
  } else if (!op->get_table_set().overlap(right_tables)) {
    /* do nothing */
  } else if (op->is_table_scan()) {
    ObLogTableScan* scan = static_cast<ObLogTableScan*>(op);
    bool can_join_filter = false;
    const ObJoinFilterHint *force_hint = NULL;
    bool can_part_join_filter = false;
    const ObJoinFilterHint *force_part_hint = NULL;
    if (scan->get_index_back()) {
      /* do nothing */
    } else if (OB_FAIL(hint_info.check_use_join_filter(*stmt,
                                                       stmt->get_query_ctx()->get_query_hint(),
                                                       scan->get_table_id(),
                                                       false,
                                                       can_join_filter,
                                                       force_hint))) {
      LOG_WARN("failed to check use join filter", K(ret));
    } else if (is_current_dfo && !is_fully_partition_wise &&
               OB_FAIL(hint_info.check_use_join_filter(*stmt,
                                                       stmt->get_query_ctx()->get_query_hint(),
                                                       scan->get_table_id(),
                                                       true,
                                                       can_part_join_filter,
                                                       force_part_hint))) {
      LOG_WARN("faile to check use join filter", K(ret));
    } else if (!can_join_filter && !can_part_join_filter) {
      //do nothing
    } else {
      JoinFilterInfo info;
      info.table_id_ = scan->get_table_id();
      info.filter_table_id_ = hint_info.filter_table_id_;
      info.ref_table_id_ = scan->get_ref_table_id();
      info.sharding_ = scan->get_strong_sharding();
      info.row_count_ = scan->get_output_row_count();
      info.can_use_join_filter_ = can_join_filter;
      info.force_filter_ = force_hint;
      info.need_partition_join_filter_ = can_part_join_filter;
      info.force_part_filter_ = is_current_dfo ? force_part_hint : NULL;
      info.in_current_dfo_ = is_current_dfo;
      if (info.can_use_join_filter_ || info.need_partition_join_filter_) {
        if (OB_FAIL(get_join_filter_exprs(left_join_conditions,
                                          right_join_conditions,
                                          info))) {
          LOG_WARN("failed to get join filter exprs", K(ret));
        } else if (OB_FAIL(fill_join_filter_info(info))) {
          LOG_WARN("failed to fill join filter info");
        } else if(OB_FAIL(join_filter_infos.push_back(info))) {
          LOG_WARN("failed to push back info", K(ret));
        }
      }
    }
  } else if (log_op_def::LOG_TEMP_TABLE_ACCESS == op->get_type()) {
    const ObLogTempTableAccess* temp_table = static_cast<const ObLogTempTableAccess*>(op);
    bool can_join_filter = false;
    const ObJoinFilterHint *force_hint = NULL;
    if (OB_FAIL(hint_info.check_use_join_filter(*stmt,
                                                stmt->get_query_ctx()->get_query_hint(),
                                                temp_table->get_table_id(),
                                                false,
                                                can_join_filter,
                                                force_hint))) {
      LOG_WARN("failed to check use join filter", K(ret));
    } else if (can_join_filter) {
      JoinFilterInfo info;
      info.table_id_ = temp_table->get_table_id();
      info.filter_table_id_ = hint_info.filter_table_id_;
      info.row_count_ = temp_table->get_card();
      info.can_use_join_filter_ = true;
      info.force_filter_ = force_hint;
      info.need_partition_join_filter_ = false;
      info.force_part_filter_ = NULL;
      info.in_current_dfo_ = is_current_dfo;
      if (OB_FAIL(get_join_filter_exprs(left_join_conditions,
                                        right_join_conditions,
                                        info))) {
        LOG_WARN("failed to get join filter exprs", K(ret));
      } else if (OB_FAIL(fill_join_filter_info(info))) {
        LOG_WARN("failed to fill join filter info");
      } else if (OB_FAIL(join_filter_infos.push_back(info))) {
      LOG_WARN("failed to push back info", K(ret));
      }
    }
  } else if (op->get_type() == log_op_def::LOG_SUBPLAN_SCAN) {
    ObLogPlan* child_plan;
    ObLogicalOperator* child_op;
    ObSEArray<ObRawExpr*, 4> pushdown_left_quals;
    ObSEArray<ObRawExpr*, 4> pushdown_right_quals;
    ObSqlBitSet<> table_set;
    uint64_t subquery_id = static_cast<ObLogSubPlanScan*>(op)->get_subquery_id();
    if (OB_UNLIKELY(op->get_num_of_child() == 0) ||
        OB_ISNULL(child_op = op->get_child(ObLogicalOperator::first_child)) ||
        OB_ISNULL(child_plan = child_op->get_plan())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected subplan scan", K(ret));
    } else if (OB_FAIL(table_set.add_member(stmt->get_table_bit_index(subquery_id)))) {
      LOG_WARN("failed to add member into table set", K(ret));
    } else if (OB_FAIL(ObOptimizerUtil::extract_pushdown_join_filter_quals(left_join_conditions,
                                                                           right_join_conditions,
                                                                           table_set,
                                                                           pushdown_left_quals,
                                                                           pushdown_right_quals))) {
      LOG_WARN("failed to extract pushdown quals", K(ret));
    } else if (OB_FAIL(child_plan->pushdown_join_filter_into_subquery(
                                   stmt,
                                   child_op,
                                   subquery_id,
                                   hint_info,
                                   is_current_dfo,
                                   is_fully_partition_wise,
                                   pushdown_left_quals,
                                   pushdown_right_quals,
                                   join_filter_infos))) {
      LOG_WARN("failed to find pushdown join filter table", K(ret));
    }
  } else if (((GET_MIN_CLUSTER_VERSION() >= CLUSTER_VERSION_4_1_0_0) || is_current_dfo) &&
              log_op_def::LOG_JOIN == op->get_type()) {
    ObLogJoin* join_op = static_cast<ObLogJoin*>(op);
    ObLogicalOperator* left_op;
    ObLogicalOperator* right_op;
    if (OB_UNLIKELY(2 != op->get_num_of_child()) ||
        OB_ISNULL(left_op = op->get_child(ObLogicalOperator::first_child)) ||
        OB_ISNULL(right_op = op->get_child(ObLogicalOperator::second_child))) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("get unexpected null", K(ret));
    } else if (OB_FAIL(SMART_CALL(find_possible_join_filter_tables(left_op,
                                                                    hint_info,
                                                                    right_tables,
                                                                    is_current_dfo,
                                                                    join_op->is_fully_paratition_wise(),
                                                                    left_join_conditions,
                                                                    right_join_conditions,
                                                                    join_filter_infos)))) {
      LOG_WARN("failed to find shuffle table scan", K(ret));
    } else if (OB_FAIL(SMART_CALL(find_possible_join_filter_tables(right_op,
                                                                    hint_info,
                                                                    right_tables,
                                                                    is_current_dfo,
                                                                    join_op->is_fully_paratition_wise(),
                                                                    left_join_conditions,
                                                                    right_join_conditions,
                                                                    join_filter_infos)))) {
      LOG_WARN("failed to find shuffle table scan", K(ret));
    }
  } else if (!is_current_dfo && log_op_def::LOG_JOIN == op->get_type()) {
    /* do nothing */
  } else if (!is_current_dfo && (log_op_def::LOG_EXCHANGE == op->get_type() &&
                                 static_cast<ObLogExchange*>(op)->is_consumer())) {
    /* do nothing */
  } else if (log_op_def::LOG_EXCHANGE == op->get_type() &&
             static_cast<ObLogExchange*>(op)->is_consumer() &&
             OB_FALSE_IT(is_current_dfo = false)) {
    /* do nothing */
  } else if (log_op_def::LOG_SUBPLAN_FILTER == op->get_type()) {
    if (OB_FAIL(SMART_CALL(find_possible_join_filter_tables(op->get_child(ObLogicalOperator::first_child),
                                                            hint_info,
                                                            right_tables,
                                                            is_current_dfo,
                                                            is_fully_partition_wise,
                                                            left_join_conditions,
                                                            right_join_conditions,
                                                            join_filter_infos)))) {
      LOG_WARN("failed to find shuffle table scan", K(ret));
    }
  } else {
    for (int64_t i = 0; OB_SUCC(ret) && i < op->get_num_of_child(); ++i) {
      if (OB_FAIL(SMART_CALL(find_possible_join_filter_tables(op->get_child(i),
                                                              hint_info,
                                                              right_tables,
                                                              is_current_dfo,
                                                              is_fully_partition_wise,
                                                              left_join_conditions,
                                                              right_join_conditions,
                                                              join_filter_infos)))) {
        LOG_WARN("failed to find shuffle table scan", K(ret));
      }
    }
  }
  return ret;
}

int ObLogPlan::pushdown_join_filter_into_subquery(const ObDMLStmt *parent_stmt,
                                                  ObLogicalOperator* child_op,
                                                  uint64_t subquery_id,
                                                  const JoinFilterPushdownHintInfo &hint_info,
                                                  bool is_current_dfo,
                                                  bool is_fully_partition_wise,
                                                  const ObIArray<ObRawExpr*> &left_join_conditions,
                                                  const ObIArray<ObRawExpr*> &right_join_conditions,
                                                  ObIArray<JoinFilterInfo> &join_filter_infos)
{
  int ret = OB_SUCCESS;
  const ObSelectStmt *child_stmt = NULL;
  ObSQLSessionInfo *session_info = NULL;
  ObRawExprFactory *expr_factory = NULL;
  ObSEArray<ObRawExpr*, 4> candi_left_filters;
  ObSEArray<ObRawExpr*, 4> candi_right_quals;
  ObSEArray<ObRawExpr*, 4> candi_right_filters;
  ObRelIds right_tables;
  bool can_pushdown = false;
  if (OB_ISNULL(child_op) ||
      OB_ISNULL(session_info = get_optimizer_context().get_session_info()) ||
      OB_ISNULL(expr_factory = &get_optimizer_context().get_expr_factory()) ||
      OB_ISNULL(child_stmt = static_cast<const ObSelectStmt*>(get_stmt()))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get unexpected null", K(ret));
  } else if (OB_FAIL(ObOptimizerUtil::pushdown_join_filter_into_subquery(*parent_stmt,
                                                                         *child_stmt,
                                                                         left_join_conditions,
                                                                         right_join_conditions,
                                                                         candi_left_filters,
                                                                         candi_right_quals,
                                                                         can_pushdown))) {
    LOG_WARN("failed to pushdown join filter into subquery", K(ret));
  } else if (!can_pushdown) {
    // do nothing
  } else if (OB_FAIL(ObOptimizerUtil::rename_pushdown_filter(*parent_stmt,
                                                             *child_stmt,
                                                             subquery_id,
                                                             session_info,
                                                             *expr_factory,
                                                             candi_right_quals,
                                                             candi_right_filters))) {
    LOG_WARN("failed to rename pushdown filter", K(ret));
  } else if (OB_FAIL(get_table_ids(candi_right_filters, right_tables))) {
    LOG_WARN("failed to get table ids", K(ret));
  } else if (OB_FAIL(find_possible_join_filter_tables(child_op,
                                                      hint_info,
                                                      right_tables,
                                                      is_current_dfo,
                                                      is_fully_partition_wise,
                                                      candi_left_filters,
                                                      candi_right_filters,
                                                      join_filter_infos))) {
    LOG_WARN("failed to find possible join filter table", K(ret));
  }
  return ret;
}

int ObLogPlan::get_join_filter_exprs(const ObIArray<ObRawExpr*> &left_join_conditions,
                                     const ObIArray<ObRawExpr*> &right_join_conditions,
                                     JoinFilterInfo &join_filter_info)
{
  int ret = OB_SUCCESS;
  ObSqlBitSet<> table_set;
  const ObDMLStmt* stmt;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected null stmt", K(ret));
  } else if (OB_UNLIKELY(left_join_conditions.count() != right_join_conditions.count())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("join condition length error", K(ret));
  } else if (OB_FAIL(table_set.add_member(stmt->get_table_bit_index(join_filter_info.table_id_)))) {
      LOG_WARN("failed to add member", K(ret));
  }
  for (int64_t j = 0; OB_SUCC(ret) && j < right_join_conditions.count(); ++j) {
    ObRawExpr *lexpr = left_join_conditions.at(j);
    ObRawExpr *rexpr = right_join_conditions.at(j);
    if (OB_ISNULL(lexpr) || OB_ISNULL(rexpr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("unexpected null expr", K(ret));
    } else if (rexpr->get_relation_ids().is_subset(table_set)) {
      if (OB_FAIL(join_filter_info.lexprs_.push_back(lexpr))) {
        LOG_WARN("failed to push back expr", K(ret));
      } else if (OB_FAIL(join_filter_info.rexprs_.push_back(rexpr))) {
        LOG_WARN("failed to push back expr", K(ret));
      }
    }
  }
  return ret;
}

int ObLogPlan::fill_join_filter_info(JoinFilterInfo &join_filter_info)
{
  int ret = OB_SUCCESS;
  const ObDMLStmt* stmt;
  ObString qb_name;
  const TableItem* table_item;
  if (OB_ISNULL(stmt = get_stmt())) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected null", K(ret), K(get_stmt()));
  } else if (OB_FAIL(stmt->get_qb_name(qb_name))) {
    LOG_WARN("failed to get qb name", K(ret));
  } else if (OB_FAIL(ObOptSelectivity::calculate_distinct(get_update_table_metas(),
                                                    get_selectivity_ctx(),
                                                    join_filter_info.rexprs_,
                                                    join_filter_info.row_count_,
                                                    join_filter_info.right_distinct_card_,
                                                    false))) {
    LOG_WARN("failed to calc distinct", K(ret));
  } else if (join_filter_info.table_id_ == join_filter_info.filter_table_id_) {
    /* do nothing */
  } else if (OB_ISNULL(table_item = stmt->get_table_item_by_id(join_filter_info.table_id_))) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("unexpected null", K(ret));
  } else {
    join_filter_info.pushdown_filter_table_.qb_name_ = qb_name;
    join_filter_info.pushdown_filter_table_.table_name_ = table_item->get_object_name();
    if (table_item->is_basic_table()) {
      join_filter_info.pushdown_filter_table_.db_name_ = table_item->database_name_;
    }
  }
  return ret;
}