ob_basic_session_info.cpp 216.6 KB
Newer Older
O
oceanbase-admin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/**
 * 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_SESSION

#include "sql/session/ob_basic_session_info.h"

#include "lib/string/ob_sql_string.h"
#include "lib/timezone/ob_oracle_format_models.h"
#include "common/sql_mode/ob_sql_mode_utils.h"
#include "common/ob_smart_call.h"
#include "share/config/ob_server_config.h"
#include "share/schema/ob_schema_getter_guard.h"
#include "share/schema/ob_sys_variable_mgr.h"
#include "sql/engine/ob_exec_context.h"
#include "sql/plan_cache/ob_plan_cache_util.h"
#include "sql/plan_cache/ob_prepare_stmt_struct.h"
#include "sql/ob_sql_trans_util.h"
#include "observer/ob_server_struct.h"
#include "sql/engine/ob_physical_plan.h"
W
wangzelin.wzl 已提交
30 31
#include "storage/tx/wrs/ob_weak_read_util.h"       //ObWeakReadUtil
#include "storage/tx/ob_trans_service.h"
O
oceanbase-admin 已提交
32
#include "observer/omt/ob_tenant_timezone_mgr.h"
33
#include "observer/omt/ob_tenant_config_mgr.h"
W
wangzelin.wzl 已提交
34 35 36 37 38
#include "share/ob_label_security.h"
#include "share/system_variable/ob_nls_system_variable.h"
#include "share/rc/ob_tenant_base.h"
#include "pl/sys_package/ob_dbms_sql.h"
#include "pl/ob_pl_package_state.h"
O
oceanbase-admin 已提交
39 40 41 42 43

using namespace oceanbase::common;
using namespace oceanbase::share;
using namespace oceanbase::share::schema;
using namespace oceanbase::transaction;
W
wangzelin.wzl 已提交
44
using oceanbase::omt::ObTenantConfigMgr;
O
oceanbase-admin 已提交
45

W
wangzelin.wzl 已提交
46 47 48 49 50 51
namespace oceanbase
{
namespace sql
{

ObBasicSessionInfo::SysVarsCacheData ObBasicSessionInfo::SysVarsCache::base_data_;
O
oceanbase-admin 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

ObBasicSessionInfo::ObBasicSessionInfo()
    : query_mutex_(),
      thread_data_mutex_(),
      is_valid_(true),
      is_deserialized_(false),
      tenant_id_(OB_INVALID_ID),
      effective_tenant_id_(OB_INVALID_ID),
      rpc_tenant_id_(0),
      is_changed_to_temp_tenant_(false),
      user_id_(OB_INVALID_ID),
      client_version_(),
      driver_version_(),
      sessid_(0),
      master_sessid_(INVALID_SESSID),
      proxy_sessid_(VALID_PROXY_SESSID),
      variables_last_modify_time_(0),
      global_vars_version_(0),
      sys_var_base_version_(OB_INVALID_VERSION),
W
wangzelin.wzl 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
      tx_desc_(NULL),
      tx_result_(),
      read_snapshot_version_(-1),
      xid_(),
      associated_xa_(false),
      sess_bt_buff_pos_(0),
      sess_ref_cnt_(0),
      sess_ref_seq_(0),
      block_allocator_(SMALL_BLOCK_SIZE, common::OB_MALLOC_NORMAL_BLOCK_SIZE - 32,
                       //这里减32是为了适配ObMalloc对齐规则, 防止超8k的内存分配
                       ObMalloc(ObModIds::OB_SQL_SESSION_SBLOCK)),
      ps_session_info_allocator_(sizeof(ObPsSessionInfo), common::OB_MALLOC_NORMAL_BLOCK_SIZE - 32,
                                 //这里减32是为了适配ObMalloc对齐规则, 防止超8k的内存分配
                                 ObMalloc("PsSessionInfo")),
      cursor_info_allocator_(sizeof(pl::ObDbmsCursorInfo), common::OB_MALLOC_NORMAL_BLOCK_SIZE - 32,
                             ObMalloc("SessCursorInfo")),
      package_info_allocator_(sizeof(pl::ObPLPackageState), common::OB_MALLOC_NORMAL_BLOCK_SIZE - 32,
                              ObMalloc("SessPackageInfo")),
O
oceanbase-admin 已提交
89 90
      name_pool_(ObModIds::OB_SQL_SESSION, OB_MALLOC_NORMAL_BLOCK_SIZE),
      trans_flags_(),
W
wangzelin.wzl 已提交
91 92 93
      sql_scope_flags_(),
      base_sys_var_alloc_(ObModIds::OB_SQL_SESSION, OB_MALLOC_NORMAL_BLOCK_SIZE),
      inc_sys_var_alloc_(ObModIds::OB_SQL_SESSION, OB_MALLOC_NORMAL_BLOCK_SIZE),
O
oceanbase-admin 已提交
94 95 96 97
      bucket_allocator_wrapper_(&block_allocator_),
      user_var_val_map_(SMALL_BLOCK_SIZE, ObWrapperAllocator(&block_allocator_)),
      influence_plan_var_indexs_(),
      is_first_gen_(true),
W
wangzelin.wzl 已提交
98
      is_first_gen_config_(true),
O
oceanbase-admin 已提交
99
      sys_var_fac_(),
W
wangzelin.wzl 已提交
100
      next_frag_mem_point_(OB_MALLOC_NORMAL_BLOCK_SIZE), // 8KB
101
      sys_vars_encode_max_size_(0),
O
oceanbase-admin 已提交
102 103 104
      consistency_level_(INVALID_CONSISTENCY),
      tz_info_wrap_(),
      next_tx_read_only_(-1),
W
wangzelin.wzl 已提交
105
      next_tx_isolation_(transaction::ObTxIsolationLevel::INVALID),
O
oceanbase-admin 已提交
106 107
      log_id_level_map_valid_(false),
      cur_phy_plan_(NULL),
R
raywill 已提交
108
      plan_id_(0),
O
oceanbase-admin 已提交
109 110 111 112 113 114
      capability_(),
      proxy_capability_(),
      client_mode_(OB_MIN_CLIENT_MODE),
      changed_sys_vars_(),
      changed_user_vars_(),
      changed_var_pool_(ObModIds::OB_SQL_SESSION, OB_MALLOC_NORMAL_BLOCK_SIZE),
W
wangzelin.wzl 已提交
115
      extra_info_allocator_(ObModIds::OB_SQL_SESSION, OB_MALLOC_NORMAL_BLOCK_SIZE),
O
oceanbase-admin 已提交
116 117 118 119 120 121 122 123 124 125 126
      is_database_changed_(false),
      feedback_manager_(),
      trans_spec_status_(TRANS_SPEC_NOT_SET),
      debug_sync_actions_(),
      partition_hit_(),
      magic_num_(0x13572468),
      current_execution_id_(-1),
      database_id_(OB_INVALID_ID),
      retry_info_(),
      last_query_trace_id_(),
      nested_count_(-1),
W
wangzelin.wzl 已提交
127
      inf_pc_configs_(),
O
oceanbase-admin 已提交
128 129 130 131 132 133 134 135
      curr_trans_last_stmt_end_time_(0),
      check_sys_variable_(true),
      is_foreign_key_cascade_(false),
      is_foreign_key_check_exist_(false),
      acquire_from_pool_(false),
      release_to_pool_(true),
      is_tenant_killed_(0),
      reused_count_(0),
W
wangzelin.wzl 已提交
136
      first_need_txn_stmt_type_(stmt::T_NONE),
O
oceanbase-admin 已提交
137 138
      exec_min_cluster_version_(GET_MIN_CLUSTER_VERSION()),
      stmt_type_(stmt::T_NONE),
W
wangzelin.wzl 已提交
139
      labels_(),
O
oceanbase-admin 已提交
140
      thread_id_(0),
W
wangzelin.wzl 已提交
141 142
      is_password_expired_(false),
      process_query_time_(0)
O
oceanbase-admin 已提交
143
{
O
obdev 已提交
144
  thread_data_.reset();
O
oceanbase-admin 已提交
145 146 147 148 149 150
  MEMSET(sys_vars_, 0, sizeof(sys_vars_));
  log_id_level_map_.reset_level();
  CHAR_CARRAY_INIT(tenant_);
  CHAR_CARRAY_INIT(effective_tenant_);
  CHAR_CARRAY_INIT(trace_id_buff_);
  ssl_cipher_buff_[0] = '\0';
W
wangzelin.wzl 已提交
151
  sess_bt_buff_[0] = '\0';
O
oceanbase-admin 已提交
152 153 154 155 156 157 158 159 160
}

ObBasicSessionInfo::~ObBasicSessionInfo()
{
  destroy();
}

bool ObBasicSessionInfo::is_server_status_in_transaction() const
{
W
wangzelin.wzl 已提交
161 162 163 164 165 166 167 168
  bool can_free_route = tx_desc_ == NULL || tx_desc_->can_free_route();
  bool result = !can_free_route;
  /*
   * if autocommit is OFF and user has issued query which need transaction protection
   * the switch 'ob_proxy_readonly_transaction_routing_policy' control whether
   * client should assume current session is inner transaction:
   * - in transaction if switch ON
   * - out of transaction if switch is OFF
169
   */
W
wangzelin.wzl 已提交
170 171 172 173
  bool auto_commit = get_local_autocommit();
  if (can_free_route
      && !auto_commit /*  autocommit = OFF */
      && get_first_need_txn_stmt_type() != stmt::StmtType::T_NONE /* has issued transactional query */) {
174
    omt::ObTenantConfigGuard tenant_config(TENANT_CONF(get_effective_tenant_id()));
W
wangzelin.wzl 已提交
175
    result = tenant_config->ob_proxy_readonly_transaction_routing_policy; /* switch is ON */
176
  }
W
wangzelin.wzl 已提交
177 178
  LOG_TRACE("decide flag: server in transaction", K(can_free_route),
            K(result), KPC(tx_desc_), K(auto_commit), K(get_first_need_txn_stmt_type()));
O
oceanbase-admin 已提交
179 180 181
  return result;
}

W
wangzelin.wzl 已提交
182 183 184
//for test
int ObBasicSessionInfo::test_init(uint32_t sessid, uint64_t proxy_sessid,
                             common::ObIAllocator *bucket_allocator)
O
oceanbase-admin 已提交
185 186 187 188 189 190 191
{
  int ret = OB_SUCCESS;
  if (NULL != bucket_allocator) {
    bucket_allocator_wrapper_.set_alloc(bucket_allocator);
  }

  ret = user_var_val_map_.init(1024 * 1024 * 2,
W
wangzelin.wzl 已提交
192 193
                               256, // # of user variables
                               (NULL == bucket_allocator ? NULL : &bucket_allocator_wrapper_));
O
oceanbase-admin 已提交
194 195
  if (OB_FAIL(ret)) {
    LOG_WARN("fail to init user_var_val_map", K(ret));
W
wangzelin.wzl 已提交
196 197
  } else if (OB_FAIL(load_default_configs_in_pc())) {
    LOG_WARN("fail to load default config influence plan cache", K(ret));
O
oceanbase-admin 已提交
198 199 200 201
  } else if (OB_FAIL(debug_sync_actions_.init(SMALL_BLOCK_SIZE, bucket_allocator_wrapper_))) {
    LOG_WARN("fail to init debug sync actions", K(ret));
  } else if (OB_FAIL(set_session_state(SESSION_INIT))) {
    LOG_WARN("fail to set session stat", K(ret));
W
wangzelin.wzl 已提交
202 203
  } else if (OB_FAIL(set_time_zone(ObString("+8:00"), is_oracle_compatible(),
                                   true/* check_timezone_valid */))) {
O
oceanbase-admin 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217
    LOG_WARN("fail to set time zone", K(ret));
  } else {
    // tz_info_wrap_.set_tz_info_map(GCTX.tz_info_mgr_->get_tz_info_map());
    sessid_ = sessid;
    proxy_sessid_ = proxy_sessid;
  }
  return ret;
}

bool ObBasicSessionInfo::is_use_inner_allocator() const
{
  return bucket_allocator_wrapper_.get_alloc() == &block_allocator_;
}

W
wangzelin.wzl 已提交
218 219
int ObBasicSessionInfo::init(uint32_t sessid, uint64_t proxy_sessid,
                             common::ObIAllocator *bucket_allocator, const ObTZInfoMap *tz_info)
O
oceanbase-admin 已提交
220 221
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
222
  ObWrapperAllocator *user_var_allocator_wrapper = NULL;
O
oceanbase-admin 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  if (is_acquire_from_pool()) {
    reused_count_++;
    if (OB_NOT_NULL(bucket_allocator) || !is_use_inner_allocator()) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("session from pool must use inner allocator", K(ret));
    }
  } else {
    if (NULL != bucket_allocator) {
      bucket_allocator_wrapper_.set_alloc(bucket_allocator);
      user_var_allocator_wrapper = &bucket_allocator_wrapper_;
    }
  }
  if (OB_FAIL(ret)) {
  } else if (!is_acquire_from_pool() &&
             OB_FAIL(user_var_val_map_.init(1024 * 1024 * 2, 256, user_var_allocator_wrapper))) {
    LOG_WARN("fail to init user_var_val_map", K(ret));
  } else if (!is_acquire_from_pool() &&
             OB_FAIL(debug_sync_actions_.init(SMALL_BLOCK_SIZE, bucket_allocator_wrapper_))) {
    LOG_WARN("fail to init debug sync actions", K(ret));
  } else if (OB_FAIL(set_session_state(SESSION_INIT))) {
    LOG_WARN("fail to set session stat", K(ret));
W
wangzelin.wzl 已提交
244
/*  } else if (FALSE_IT(tx_result_.set_trans_desc(&trans_desc_))) { */
O
oceanbase-admin 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  } else {
    sessid_ = sessid;
    proxy_sessid_ = proxy_sessid;
    uint64_t tenant_id = tenant_id_;
    if (OB_ISNULL(tz_info)) {
      ObTZMapWrap tz_map_wrap;
      if (OB_FAIL(OTTZ_MGR.get_tenant_tz(tenant_id, tz_map_wrap))) {
        LOG_WARN("get tenant timezone map failed", K(ret));
      } else {
        tz_info_wrap_.set_tz_info_map(tz_map_wrap.get_tz_map());
      }
    } else {
      tz_info_wrap_.set_tz_info_map(tz_info);
    }
  }
  return ret;
}

void ObBasicSessionInfo::destroy()
{
  if (magic_num_ != 0x13572468) {
    LOG_ERROR("ObBasicSessionInfo may be double free!!!", K(magic_num_));
  }
W
wangzelin.wzl 已提交
268 269 270 271 272 273 274
  if (OB_NOT_NULL(tx_desc_)) {
    LOG_ERROR("tx_desc != NULL", KPC(this), KPC_(tx_desc));
  }
  tx_desc_ = NULL;
  tx_result_.reset();
  xid_.reset();
  associated_xa_ = false;
O
oceanbase-admin 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287
  magic_num_ = 0x86427531;
  if (thread_data_.cur_query_ != nullptr) {
    ob_free(thread_data_.cur_query_);
    thread_data_.cur_query_ = nullptr;
    thread_data_.cur_query_buf_len_ = 0;
  }
  total_stmt_tables_.reset();
  cur_stmt_tables_.reset();
}

void ObBasicSessionInfo::clean_status()
{
  trans_flags_.reset();
W
wangzelin.wzl 已提交
288
  sql_scope_flags_.reset();
O
oceanbase-admin 已提交
289
  trans_spec_status_ = TRANS_SPEC_NOT_SET;
W
wangzelin.wzl 已提交
290 291 292 293 294 295 296 297 298 299
  if (OB_NOT_NULL(tx_desc_)) {
    int ret = OB_SUCCESS;
    MAKE_TENANT_SWITCH_SCOPE_GUARD(guard);
    if (OB_SUCC(guard.switch_to(tx_desc_->get_tenant_id(), false))) {
      MTL(transaction::ObTransService*)->release_tx(*tx_desc_);
    }
    tx_desc_ = NULL;
  }
  xid_.reset();
  associated_xa_ = false;
O
oceanbase-admin 已提交
300 301 302
  set_valid(true);
  thread_data_.cur_query_start_time_ = 0;
  thread_data_.cur_query_len_ = 0;
303
  thread_data_.last_active_time_ = ObTimeUtility::current_time();
O
oceanbase-admin 已提交
304 305 306 307 308 309
  reset_session_changed_info();
}

void ObBasicSessionInfo::reset(bool skip_sys_var)
{
  set_valid(false);
W
wangzelin.wzl 已提交
310 311 312 313 314 315 316 317 318 319 320

  if (OB_NOT_NULL(tx_desc_)) {
    int ret = OB_SUCCESS;
    MAKE_TENANT_SWITCH_SCOPE_GUARD(guard);
    if (OB_SUCC(guard.switch_to(tx_desc_->get_tenant_id(), false))) {
      MTL(transaction::ObTransService*)->release_tx(*tx_desc_);
    }
    tx_desc_ = NULL;
  }
  xid_.reset();
  associated_xa_ = false;
O
oceanbase-admin 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  is_deserialized_ = false;
  CHAR_CARRAY_INIT(tenant_);
  tenant_id_ = OB_INVALID_ID;
  CHAR_CARRAY_INIT(effective_tenant_);
  effective_tenant_id_ = OB_INVALID_ID;
  is_changed_to_temp_tenant_ = false;
  user_id_ = OB_INVALID_ID;
  client_version_.reset();
  driver_version_.reset();
  sessid_ = 0;
  master_sessid_ = INVALID_SESSID;
  proxy_sessid_ = VALID_PROXY_SESSID;
  variables_last_modify_time_ = 0;
  global_vars_version_ = 0;

W
wangzelin.wzl 已提交
336
  tx_result_.reset();
O
oceanbase-admin 已提交
337 338 339 340 341
  total_stmt_tables_.reset();
  cur_stmt_tables_.reset();
  // reset() of user_var_val_map_ and debug_sync_actions_ will keep some memory
  // allocated from block_allocator_ / bucket_allocator_wrapper_, so we skip
  // reset() of block_allocator_ and bucket_allocator_wrapper_.
W
wangzelin.wzl 已提交
342
//block_allocator_.reset();
O
oceanbase-admin 已提交
343
  ps_session_info_allocator_.reset();
W
wangzelin.wzl 已提交
344 345
  cursor_info_allocator_.reset();
  package_info_allocator_.reset();
O
oceanbase-admin 已提交
346
  trans_flags_.reset();
W
wangzelin.wzl 已提交
347 348
  sql_scope_flags_.reset();
//bucket_allocator_wrapper_.reset();
O
oceanbase-admin 已提交
349 350 351 352 353
  user_var_val_map_.reuse();
  if (!skip_sys_var) {
    memset(sys_vars_, 0, sizeof(sys_vars_));
    influence_plan_var_indexs_.reset();
  } else {
W
wangzelin.wzl 已提交
354
    const SysVarIds &all_sys_var_ids = sys_var_inc_info_.get_all_sys_var_ids();
O
oceanbase-admin 已提交
355 356 357 358
    for (int i = 0; i < all_sys_var_ids.count(); i++) {
      int ret = OB_SUCCESS;
      int64_t store_idx = -1;
      ObSysVarClassType sys_var_id = all_sys_var_ids.at(i);
W
wangzelin.wzl 已提交
359 360 361 362
      OZ (ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, store_idx));
      OV (0 <= store_idx && store_idx < ObSysVarFactory::ALL_SYS_VARS_COUNT);
      OV (OB_NOT_NULL(sys_vars_[store_idx]));
      OX (sys_vars_[store_idx]->clean_inc_value());
O
oceanbase-admin 已提交
363
    }
W
wangzelin.wzl 已提交
364 365
    // I don't see any reason why we should reset timezone
    // reset_timezone();
O
oceanbase-admin 已提交
366
  }
W
wangzelin.wzl 已提交
367
  sys_var_inc_info_.reset();
O
oceanbase-admin 已提交
368
  sys_var_in_pc_str_.reset();
W
wangzelin.wzl 已提交
369
  config_in_pc_str_.reset();
O
oceanbase-admin 已提交
370
  is_first_gen_ = true;
W
wangzelin.wzl 已提交
371
  is_first_gen_config_ = true;
O
oceanbase-admin 已提交
372
  CHAR_CARRAY_INIT(trace_id_buff_);
W
wangzelin.wzl 已提交
373
//consistency_level_ = INVALID_CONSISTENCY;
O
oceanbase-admin 已提交
374
  next_tx_read_only_ = -1;
W
wangzelin.wzl 已提交
375
  next_tx_isolation_ = transaction::ObTxIsolationLevel::INVALID;
O
oceanbase-admin 已提交
376 377 378
  log_id_level_map_valid_ = false;
  log_id_level_map_.reset_level();
  cur_phy_plan_ = NULL;
R
raywill 已提交
379
  plan_id_ = 0;
O
oceanbase-admin 已提交
380 381 382 383
  capability_.capability_ = 0;
  proxy_capability_.capability_ = 0;
  client_mode_ = OB_MIN_CLIENT_MODE;
  reset_session_changed_info();
W
wangzelin.wzl 已提交
384
  extra_info_allocator_.reset();
O
oceanbase-admin 已提交
385 386 387
  trans_spec_status_ = TRANS_SPEC_NOT_SET;
  debug_sync_actions_.reset();
  partition_hit_.reset();
W
wangzelin.wzl 已提交
388
//magic_num_ = 0x86427531;
O
oceanbase-admin 已提交
389 390
  current_execution_id_ = -1;
  last_trace_id_.reset();
391
  curr_trace_id_.reset();
O
oceanbase-admin 已提交
392 393 394 395 396 397
  app_trace_id_.reset();
  database_id_ = OB_INVALID_ID;
  retry_info_.reset();
  last_query_trace_id_.reset();
  thread_data_.reset();
  nested_count_ = -1;
W
wangzelin.wzl 已提交
398 399
  // session 缓存的场景下,只保留 base 值,清理 inc 值
  // 去掉 sys var schema version 后,base 值即为 hardcode 值
O
oceanbase-admin 已提交
400 401
  if (!skip_sys_var) {
    sys_vars_cache_.reset();
W
wangzelin.wzl 已提交
402
    sys_var_base_version_ = OB_INVALID_VERSION;
O
oceanbase-admin 已提交
403 404
  } else {
    sys_vars_cache_.clean_inc();
W
wangzelin.wzl 已提交
405
    sys_var_base_version_ = CACHED_SYS_VAR_VERSION;
O
oceanbase-admin 已提交
406 407 408 409 410 411 412
  }
  curr_trans_last_stmt_end_time_ = 0;
  read_snapshot_version_ = OB_INVALID_VERSION;
  check_sys_variable_ = true;
  is_foreign_key_cascade_ = false;
  is_foreign_key_check_exist_ = false;
  acquire_from_pool_ = false;
W
wangzelin.wzl 已提交
413
  // 不要重置release_to_pool_,原因见属性声明位置的注释。
O
oceanbase-admin 已提交
414
  is_tenant_killed_ = 0;
W
wangzelin.wzl 已提交
415
  first_need_txn_stmt_type_ = stmt::T_NONE;
O
oceanbase-admin 已提交
416
  exec_min_cluster_version_ = GET_MIN_CLUSTER_VERSION();
W
wangzelin.wzl 已提交
417
  labels_.reuse();
O
oceanbase-admin 已提交
418 419
  thread_id_ = 0;
  is_password_expired_ = false;
W
wangzelin.wzl 已提交
420 421 422 423 424
  process_query_time_ = 0;
  sess_bt_buff_pos_ = 0;
  ATOMIC_SET(&sess_ref_cnt_ , 0);
  // 最后再重置所有allocator
  // 否则thread_data_.user_name_之类的属性会有野指针,在session_mgr的foreach接口遍历时可能core掉。
O
oceanbase-admin 已提交
425
  name_pool_.reset();
W
wangzelin.wzl 已提交
426
  inc_sys_var_alloc_.reset();
O
oceanbase-admin 已提交
427 428 429 430
  if (!skip_sys_var) {
    base_sys_var_alloc_.reset();
    sys_var_fac_.destroy();
  }
W
wangzelin.wzl 已提交
431
  client_identifier_.reset();
O
oceanbase-admin 已提交
432 433
}

W
wangzelin.wzl 已提交
434
int ObBasicSessionInfo::reset_timezone()
O
oceanbase-admin 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
{
  int ret = OB_SUCCESS;
  ObObj tmp_obj1;
  if (OB_FAIL(get_sys_variable(SYS_VAR_TIME_ZONE, tmp_obj1))) {
    LOG_WARN("get sys var failed", K(ret));
  } else if (OB_FAIL(process_session_time_zone_value(tmp_obj1, false))) {
    LOG_WARN("set time zone failed", K(ret));
  }

  ObObj tmp_obj2;
  if (OB_FAIL(get_sys_variable(SYS_VAR_ERROR_ON_OVERLAP_TIME, tmp_obj2))) {
    LOG_WARN("get sys var failed", K(ret));
  } else if (OB_FAIL(process_session_overlap_time_value(tmp_obj2))) {
    LOG_WARN("process session overlap time value failed", K(ret), K(tmp_obj2));
  }
W
wangzelin.wzl 已提交
450
  return ret;
O
oceanbase-admin 已提交
451 452
}

W
wangzelin.wzl 已提交
453
int ObBasicSessionInfo::init_tenant(const ObString &tenant_name, const uint64_t tenant_id)
O
oceanbase-admin 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(!is_valid_tenant_id(tenant_id))) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid tenant id", K(tenant_id), K(ret));
  } else if (tenant_name.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("tenant name is empty", K(tenant_name), K(ret));
  } else if (tenant_name.length() > OB_MAX_TENANT_NAME_LENGTH) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("tenant name too long", K(tenant_name), K(ret));
  } else if (OB_FAIL(ob_cstrcopy(tenant_, sizeof(tenant_), tenant_name))) {
    LOG_WARN("failed to copy tenant name", K(tenant_name), K(ret));
  } else if (OB_FAIL(ob_cstrcopy(effective_tenant_, sizeof(effective_tenant_), tenant_name))) {
    LOG_WARN("failed to copy effective tenant name", K(tenant_name), K(ret));
  } else {
    ObTZMapWrap tz_map_wrap;
    if (OB_FAIL(OTTZ_MGR.get_tenant_tz(tenant_id, tz_map_wrap))) {
      LOG_WARN("get tenant timezone map failed", K(ret));
    } else {
      tz_info_wrap_.set_tz_info_map(tz_map_wrap.get_tz_map());
      tenant_id_ = tenant_id;
      effective_tenant_id_ = tenant_id;
      LOG_DEBUG("init session tenant", K(tenant_name), K(tenant_id));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
483
int ObBasicSessionInfo::set_tenant(const common::ObString &tenant_name, const uint64_t tenant_id)
O
oceanbase-admin 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
{
  int ret = OB_SUCCESS;
  if (!is_valid_tenant_id(tenant_id)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid tenant id", K(tenant_id), K(ret));
  } else if (tenant_name.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("tenant name is empty", K(tenant_name), K(ret));
  } else if (tenant_name.length() > OB_MAX_TENANT_NAME_LENGTH) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("tenant name too long", K(tenant_name), K(ret));
  } else if (OB_FAIL(ob_cstrcopy(tenant_, sizeof(tenant_), tenant_name))) {
    LOG_WARN("tenant name too long", K(tenant_name));
  } else {
    tenant_id_ = tenant_id;
    LOG_TRACE("set tenant", K(tenant_name), K(tenant_id));
  }
  return ret;
}

W
wangzelin.wzl 已提交
504 505 506 507 508
int ObBasicSessionInfo::set_tenant(const common::ObString &tenant_name,
                                   const uint64_t tenant_id,
                                   char *ori_tenant_name,
                                   const uint64_t length,
                                   uint64_t &ori_tenant_id)
O
oceanbase-admin 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
{
  int ret = OB_SUCCESS;
  if (!is_valid_tenant_id(tenant_id)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid tenant id", K(tenant_id), K(ret));
  } else if (OB_ISNULL(ori_tenant_name)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("ori_tenant_name is NULL", K(ret));
  } else if (length < OB_MAX_TENANT_NAME_LENGTH + 1) {
    ret = OB_INVALID_ARGUMENT_FOR_LENGTH;
    LOG_WARN("tenant_name length is not enough ");
  } else if (tenant_name.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("tenant name is empty", K(tenant_name), K(ret));
  } else if (tenant_name.length() > OB_MAX_TENANT_NAME_LENGTH) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("tenant name too long", K(tenant_name), K(ret));
  } else if (OB_FAIL(ob_cstrcopy(ori_tenant_name, length, tenant_, strlen(tenant_)))) {
    LOG_ERROR("tenant_name is longer than ori_tenant_name", K(length), K(strlen(tenant_)));
  } else if (OB_FAIL(ob_cstrcopy(tenant_, sizeof(tenant_), tenant_name))) {
    LOG_ERROR("tenant name too long", K(tenant_name));
  } else {
    ori_tenant_id = tenant_id_;
    tenant_id_ = tenant_id;
  }
  return ret;
}

int ObBasicSessionInfo::switch_tenant(uint64_t effective_tenant_id)
{
  int ret = OB_SUCCESS;
  if (OB_SYS_TENANT_ID != tenant_id_) {
    ret = OB_NOT_SUPPORTED;
W
wangzelin.wzl 已提交
542
    LOG_USER_ERROR(OB_NOT_SUPPORTED, "switching tenant from a non-sys tenant");
O
oceanbase-admin 已提交
543 544 545 546
    LOG_WARN("only support sys tenant switch tenant", K(ret), K(tenant_id_), K(effective_tenant_id_));
  } else if (effective_tenant_id <= 0) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid tenant_id", K(ret), K(effective_tenant_id));
W
wangzelin.wzl 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  } else if (OB_NOT_NULL(tx_desc_) && effective_tenant_id != effective_tenant_id_) {
    if (!tx_desc_->can_free_route()) {
      ret = OB_NOT_SUPPORTED;
      // only inner-SQL goes switch_tenant and may fall into such state
      // print out error to easy trouble-shot
      LOG_USER_ERROR(OB_NOT_SUPPORTED, 
                  "try to switch to another tenant without commit/rollback in a transaction");
      LOG_ERROR("try to switch another tenant while session has active txn,"
                " you must commit/rollback first", K(ret),
                "current_effective_tenant_id", effective_tenant_id_,
                "target_effective_tenant_id", effective_tenant_id,
                KPC(tx_desc_), KPC(this));
    } else if (OB_FAIL(ObSqlTransControl::reset_session_tx_state(this))) {
      LOG_WARN("reset session tx state fail", K(ret), KPC(this));
    }
  }
  if (OB_SUCC(ret)) {
O
oceanbase-admin 已提交
564 565
#ifndef NDEBUG
    if (effective_tenant_id_ != effective_tenant_id) {
W
wangzelin.wzl 已提交
566 567 568 569 570
      LOG_INFO("switch tenant",
               "target_effective_tenant_id", effective_tenant_id,
               "current_effective_tenant_id", effective_tenant_id_,
               "priv_tenant_id", tenant_id_,
               K(lbt()));
O
oceanbase-admin 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    }
#endif
    effective_tenant_id_ = effective_tenant_id;
  }
  return ret;
}

const common::ObString ObBasicSessionInfo::get_tenant_name() const
{
  return ObString::make_string(tenant_);
}

const common::ObString ObBasicSessionInfo::get_effective_tenant_name() const
{
  return ObString::make_string(effective_tenant_);
}

W
wangzelin.wzl 已提交
588
int ObBasicSessionInfo::set_user(const ObString &user_name, const ObString &host_name, const uint64_t user_id)
O
oceanbase-admin 已提交
589 590
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
591 592
  if (OB_UNLIKELY(user_name.length() > common::OB_MAX_USER_NAME_LENGTH)
      || OB_UNLIKELY(host_name.length() > common::OB_MAX_HOST_NAME_LENGTH)) {
O
oceanbase-admin 已提交
593 594 595 596
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("name length invalid_", K(user_name), K(host_name), K(ret));
  } else {
    char tmp_buf[common::OB_MAX_USER_NAME_LENGTH + common::OB_MAX_HOST_NAME_LENGTH + 2] = {};
W
wangzelin.wzl 已提交
597 598
    snprintf(tmp_buf, sizeof(tmp_buf), "%.*s@%.*s", user_name.length(), user_name.ptr(),
                                                    host_name.length(), host_name.ptr());
O
oceanbase-admin 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    ObString tmp_string(tmp_buf);
    LockGuard lock_guard(thread_data_mutex_);
    if (OB_FAIL(name_pool_.write_string(user_name, &thread_data_.user_name_))) {
      LOG_WARN("fail to write username to string_buf_", K(user_name), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(host_name, &thread_data_.host_name_))) {
      LOG_WARN("fail to write hostname to string_buf_", K(host_name), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(tmp_string, &thread_data_.user_at_host_name_))) {
      LOG_WARN("fail to write user_at_host_name to string_buf_", K(tmp_string), K(ret));
    } else {
      user_id_ = user_id;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
614
int ObBasicSessionInfo::set_real_client_ip(const common::ObString &client_ip)
O
oceanbase-admin 已提交
615 616 617
{
  int ret = OB_SUCCESS;
  char tmp_buf[common::OB_MAX_USER_NAME_LENGTH + common::OB_MAX_HOST_NAME_LENGTH + 2] = {};
W
wangzelin.wzl 已提交
618 619 620 621
  snprintf(tmp_buf, sizeof(tmp_buf), "%.*s@%.*s", thread_data_.user_name_.length(),
                                                  thread_data_.user_name_.ptr(),
                                                  client_ip.length(),
                                                  client_ip.ptr());
O
oceanbase-admin 已提交
622 623 624 625 626 627 628 629 630 631 632 633
  ObString tmp_string(tmp_buf);
  LockGuard lock_guard(thread_data_mutex_);
  if (OB_FAIL(name_pool_.write_string(client_ip, &thread_data_.client_ip_))) {
    LOG_WARN("fail to write client_ip to string_buf_", K(client_ip), K(ret));
  } else if (OB_FAIL(name_pool_.write_string(tmp_string, &thread_data_.user_at_client_ip_))) {
    LOG_WARN("fail to write user_at_host_name to string_buf_", K(tmp_string), K(ret));
  } else {
    thread_data_.user_client_addr_.set_ip_addr(client_ip, 0);
  }
  return ret;
}

W
wangzelin.wzl 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
int ObBasicSessionInfo::set_client_identifier(const common::ObString &client_identifier)
{
  int ret = OB_SUCCESS;
  int max_size = OB_MAX_CONTEXT_CLIENT_IDENTIFIER_LENGTH_IN_SESSION;
  if (OB_FAIL(init_client_identifier())) {
    LOG_WARN("failed to init client identifier", K(ret));
  } else {
    //reset curr identifier
    client_identifier_.set_length(0);
    //write new string
    int64_t write_len = std::min(client_identifier_.size(), client_identifier.length());
    if (write_len != client_identifier_.write(client_identifier.ptr(), write_len)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("failed to write client identifier", K(ret), K(client_identifier_), K(write_len));
    }
  }
  return ret;
}

int ObBasicSessionInfo::init_client_identifier()
{
  int ret = OB_SUCCESS;
  int max_size = OB_MAX_CONTEXT_CLIENT_IDENTIFIER_LENGTH_IN_SESSION;
  if (OB_ISNULL(client_identifier_.ptr())) {
    char *ptr = nullptr;
    if (OB_ISNULL(ptr = static_cast<char *> (get_session_allocator().alloc(max_size)))) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("failed to alloc mem for client identifier", K(ret));
    } else {
      client_identifier_.assign_buffer(ptr, max_size);
    }
  } else if (max_size != client_identifier_.size()) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("get wrong client identifier", K(ret), K(client_identifier_.size()));
  }
  return ret;
}

int ObBasicSessionInfo::check_and_init_retry_info(const ObCurTraceId::TraceId &cur_trace_id,
                                                  const ObString &sql)
O
oceanbase-admin 已提交
674 675
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
676 677
  // 下面这段判断影响太大,害怕出问题,所以打了ERROR之后还是继续执行,仅仅影响retry info,还是可以正常执行的
  if (last_query_trace_id_.equals(cur_trace_id)) { // 是重试query的包
O
oceanbase-admin 已提交
678 679
    if (OB_UNLIKELY(!retry_info_.is_inited())) {
      LOG_ERROR("is retry packet, but retry info is not inited, will init it",
W
wangzelin.wzl 已提交
680
                K(last_query_trace_id_), K(cur_trace_id), K(retry_info_), K(get_sessid()), K(sql));
O
oceanbase-admin 已提交
681 682 683 684 685
      if (OB_FAIL(retry_info_.init())) {
        LOG_WARN("fail to init retry info", K(ret), K(retry_info_), K(sql));
      }
    }
  } else {
W
wangzelin.wzl 已提交
686 687 688
    //@TODO: 不是重试query的包,在正常语句结束的时候,不做清空重试信息逻辑,后续这个地方会做成按需初始化,
    //减少正常语句的执行开销,所以如果是上一条语句初始化了重试信息,这里直接清空掉,
    //因为对于异步执行而言,在控制端线程结束的时候判断无法判断其重试状态,所以不能做清空重试信息操作
O
oceanbase-admin 已提交
689 690 691
    if (OB_UNLIKELY(retry_info_.is_inited())) {
      retry_info_.reset();
    }
W
wangzelin.wzl 已提交
692
    // 不是重试query的包都要init retry info
O
oceanbase-admin 已提交
693 694 695 696 697 698 699 700 701
    if (OB_FAIL(retry_info_.init())) {
      LOG_WARN("fail to init retry info", K(ret), K(retry_info_), K(sql));
    } else {
      last_query_trace_id_.set(cur_trace_id);
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
702
const ObLogIdLevelMap *ObBasicSessionInfo::get_log_id_level_map() const
O
oceanbase-admin 已提交
703 704 705 706
{
  return (log_id_level_map_valid_ ? (&log_id_level_map_) : NULL);
}

W
wangzelin.wzl 已提交
707
int ObBasicSessionInfo::set_client_version(const ObString &client_version)
O
oceanbase-admin 已提交
708 709 710 711 712 713 714
{
  int ret = OB_SUCCESS;
  if (client_version.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("client version is empty", K(client_version), K(ret));
  } else if (OB_FAIL(name_pool_.write_string(client_version, &client_version_))) {
    LOG_WARN("failed to write client_version to string_buf_", K(ret));
W
wangzelin.wzl 已提交
715
  } else {}
O
oceanbase-admin 已提交
716 717 718
  return ret;
}

W
wangzelin.wzl 已提交
719
int ObBasicSessionInfo::set_driver_version(const ObString &driver_version)
O
oceanbase-admin 已提交
720 721 722 723 724 725 726
{
  int ret = OB_SUCCESS;
  if (driver_version.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("driver version is empty", K(driver_version), K(ret));
  } else if (OB_FAIL(name_pool_.write_string(driver_version, &driver_version_))) {
    LOG_WARN("failed to write driver_version to string_buf_", K(ret));
W
wangzelin.wzl 已提交
727
  } else {}
O
oceanbase-admin 已提交
728 729 730
  return ret;
}

W
wangzelin.wzl 已提交
731 732
int ObBasicSessionInfo::set_default_database(const ObString &database_name,
                                             const ObCollationType coll_type/*= CS_TYPE_INVALID */)
O
oceanbase-admin 已提交
733 734
{
  int ret = OB_SUCCESS;
735
  if (database_name.length() > OB_MAX_DATABASE_NAME_LENGTH * OB_MAX_CHAR_LEN) {
O
oceanbase-admin 已提交
736 737 738 739 740 741 742 743 744
    ret = OB_INVALID_ARGUMENT_FOR_LENGTH;
    LOG_WARN("invalid length for database_name", K(database_name), K(ret));
  } else {
    if (CS_TYPE_INVALID != coll_type) {
      const int64_t coll_val = static_cast<int64_t>(coll_type);
      if (OB_FAIL(update_sys_variable(SYS_VAR_CHARACTER_SET_DATABASE, coll_val))) {
        LOG_WARN("failed to update variable", K(ret));
      } else if (OB_FAIL(update_sys_variable(SYS_VAR_COLLATION_DATABASE, coll_val))) {
        LOG_WARN("failed to update variable", K(ret));
W
wangzelin.wzl 已提交
745
      } else {}
O
oceanbase-admin 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759
    }

    if (OB_SUCC(ret)) {
      LockGuard lock_guard(thread_data_mutex_);
      MEMCPY(thread_data_.database_name_, database_name.ptr(), database_name.length());
      thread_data_.database_name_[database_name.length()] = '\0';
      if (is_track_session_info()) {
        is_database_changed_ = true;
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
760
int ObBasicSessionInfo::update_database_variables(ObSchemaGetterGuard *schema_guard)
O
oceanbase-admin 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(schema_guard)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid schema guard is NULL", K(ret));
  } else {
    if ('\0' == thread_data_.database_name_[0]) {
      // no default database
      ObObj val;
      if (OB_FAIL(get_sys_variable(SYS_VAR_CHARACTER_SET_SERVER, val))) {
        LOG_WARN("failed to get sys variable", K(ret));
      } else if (OB_FAIL(update_sys_variable(SYS_VAR_CHARACTER_SET_DATABASE, val))) {
        LOG_WARN("failed to update sys variable", K(ret));
      } else if (OB_FAIL(get_sys_variable(SYS_VAR_COLLATION_SERVER, val))) {
        LOG_WARN("failed to get sys variable", K(ret));
      } else if (OB_FAIL(update_sys_variable(SYS_VAR_COLLATION_DATABASE, val))) {
        LOG_WARN("failed to update sys variable", K(ret));
W
wangzelin.wzl 已提交
778
      } else {}
O
oceanbase-admin 已提交
779
    } else {
W
wangzelin.wzl 已提交
780
      const share::schema::ObDatabaseSchema *db_schema = NULL;
O
oceanbase-admin 已提交
781
      ObString db_name(thread_data_.database_name_);
W
wangzelin.wzl 已提交
782 783 784 785
      if (OB_FAIL(schema_guard->get_database_schema(effective_tenant_id_, db_name,
                                                    db_schema))) {
        LOG_WARN("get database schema failed",
                 K(effective_tenant_id_), K(db_name), K(ret));
O
oceanbase-admin 已提交
786 787
      } else if (NULL == db_schema) {
        ret = OB_ERR_BAD_DATABASE;
W
wangzelin.wzl 已提交
788 789
        LOG_WARN("database not exist",
                 K(effective_tenant_id_), K(db_name), K(ret));
O
oceanbase-admin 已提交
790 791 792 793 794 795 796
        LOG_USER_ERROR(OB_ERR_BAD_DATABASE, db_name.length(), db_name.ptr());
      } else {
        const int64_t db_coll = static_cast<int64_t>(db_schema->get_collation_type());
        if (OB_FAIL(update_sys_variable(SYS_VAR_CHARACTER_SET_DATABASE, db_coll))) {
          LOG_WARN("failed to update sys variable", K(ret));
        } else if (OB_FAIL(update_sys_variable(SYS_VAR_COLLATION_DATABASE, db_coll))) {
          LOG_WARN("failed to update sys variable", K(ret));
W
wangzelin.wzl 已提交
797
        } else {}
O
oceanbase-admin 已提交
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
      }
    }
  }

  return ret;
}

int ObBasicSessionInfo::update_max_packet_size()
{
  int ret = OB_SUCCESS;
  int64_t max_allowed_pkt = 0;
  int64_t net_buffer_len = 0;
  if (OB_FAIL(get_max_allowed_packet(max_allowed_pkt))) {
    LOG_WARN("fail to get_max_allowed_packet", K(ret));
  } else if (OB_FAIL(get_net_buffer_length(net_buffer_len))) {
    LOG_WARN("fail to get_net_buffer_length", K(ret));
  } else {
    thread_data_.max_packet_size_ = std::max(max_allowed_pkt, net_buffer_len);
  }
  return ret;
}

const ObString ObBasicSessionInfo::get_database_name() const
{
  ObString str_ret;
W
wangzelin.wzl 已提交
823 824
  str_ret.assign_ptr(const_cast<char*>(thread_data_.database_name_),
                 static_cast<int32_t>(strlen(thread_data_.database_name_)));
O
oceanbase-admin 已提交
825 826 827
  return str_ret;
}

W
wangzelin.wzl 已提交
828 829
//// FIXME: xiyu
//int ObBasicSessionInfo::get_database_id(
O
oceanbase-admin 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
//    ObSchemaGetterGuard *schema_guard,
//    uint64_t &db_id) const
//{
//  int ret = OB_SUCCESS;
//  db_id = OB_INVALID_ID;
//  if (get_database_name().empty()) {
//    //do nothing
//  } else if (OB_UNLIKELY(NULL == schema_guard)) {
//    ret = OB_INVALID_ARGUMENT;
//    LOG_WARN("Schema guard should not be NULL", K(ret));
//  } else if (OB_FAIL(schema_guard->get_database_id(get_effective_tenant_id(), get_database_name(),
//                                                     db_id))) {
//    db_id = OB_INVALID_ID;
//    LOG_WARN("failed to get database id", K(db_id), K(ret));
//  } else { }//do nothing
//  return ret;
//}

////////////////////////////////////////////////////////////////
W
wangzelin.wzl 已提交
849 850 851 852
int ObBasicSessionInfo::get_global_sys_variable(const ObBasicSessionInfo *session,
                                                ObIAllocator &calc_buf,
                                                const ObString &var_name,
                                                ObObj &val)
O
oceanbase-admin 已提交
853 854 855 856 857 858
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(session)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("session is NULL", K(ret), K(var_name));
  } else {
W
wangzelin.wzl 已提交
859
    //const ObDataTypeCastParams dtc_params(session->get_timezone_info(),
O
oceanbase-admin 已提交
860 861 862 863
    //                                      session->get_local_nls_formats(),
    //                                      session->get_nls_collation(),
    //                                      session->get_nls_collation_nation());
    ObDataTypeCastParams dtc_params = session->get_dtc_params();
W
wangzelin.wzl 已提交
864 865
    if (OB_FAIL(get_global_sys_variable(session->get_effective_tenant_id(),
                                        calc_buf, dtc_params, var_name, val))) {
O
oceanbase-admin 已提交
866 867 868 869 870 871
      LOG_WARN("fail to get global sys variable", K(ret), K(var_name));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
872 873 874 875 876
int ObBasicSessionInfo::get_global_sys_variable(const uint64_t actual_tenant_id, // 为了处理租户已经切掉的情况
                                                ObIAllocator &calc_buf,
                                                const ObDataTypeCastParams &dtc_params,
                                                const ObString &var_name,
                                                ObObj &val)
O
oceanbase-admin 已提交
877 878 879
{
  int ret = OB_SUCCESS;
  ObSchemaGetterGuard schema_guard;
W
wangzelin.wzl 已提交
880 881 882
  const ObTenantSchema *tenant_schema = NULL;
  const ObSysVarSchema *sysvar_schema = NULL;
  const ObSysVariableSchema *sys_variable_schema = NULL;
O
oceanbase-admin 已提交
883 884 885 886 887
  if (OB_UNLIKELY(!is_valid_tenant_id(actual_tenant_id))) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid tenant id", K(actual_tenant_id), K(ret));
  } else if (OB_ISNULL(GCTX.schema_service_)) {
    ret = OB_INVALID_ARGUMENT;
W
wangzelin.wzl 已提交
888 889 890 891
    OB_LOG(WARN,"invalid argument", K(GCTX.schema_service_));
  } else if (OB_FAIL(GCTX.schema_service_->get_tenant_schema_guard(
              actual_tenant_id,
              schema_guard))) {
O
oceanbase-admin 已提交
892
    ret = OB_SCHEMA_ERROR;
W
wangzelin.wzl 已提交
893
    OB_LOG(WARN,"fail get schema guard", K(ret));
O
oceanbase-admin 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
  } else if (OB_FAIL(schema_guard.get_tenant_info(actual_tenant_id, tenant_schema))) {
    LOG_WARN("get tenant info failed", K(ret), K(actual_tenant_id));
  } else if (OB_ISNULL(tenant_schema)) {
    ret = OB_SCHEMA_ERROR;
    LOG_WARN("tenant_schema is NULL", K(ret));
  } else if (OB_FAIL(schema_guard.get_sys_variable_schema(actual_tenant_id, sys_variable_schema))) {
    LOG_WARN("get sys variable schema failed", K(ret));
  } else if (OB_ISNULL(sys_variable_schema)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("sys variable schema is null", K(ret));
  } else if (OB_FAIL(sys_variable_schema->get_sysvar_schema(var_name, sysvar_schema))) {
    ret = OB_ERR_SYS_VARIABLE_UNKNOWN;
    LOG_WARN("failed to get sysvar", K(ret), K(var_name));
  } else if (OB_ISNULL(sysvar_schema)) {
    ret = OB_SCHEMA_ERROR;
    LOG_WARN("tenant_schema is NULL", K(ret));
  } else if (OB_FAIL(sysvar_schema->get_value(&calc_buf, dtc_params, val))) {
    LOG_WARN("failed to get value", K(ret), K(var_name));
W
wangzelin.wzl 已提交
912 913
  } else if (OB_FAIL(ObBasicSessionInfo::change_value_for_special_sys_var(
                         var_name, val, val))) {
O
oceanbase-admin 已提交
914 915 916 917 918 919 920
    LOG_ERROR("fail to change value for special sys var", K(ret), K(var_name), K(val));
  } else {
    LOG_DEBUG("get global sysvar", K(var_name), K(val));
  }
  return ret;
}

W
wangzelin.wzl 已提交
921
const ObBasicSysVar *ObBasicSessionInfo::get_sys_var(const int64_t idx) const
O
oceanbase-admin 已提交
922
{
W
wangzelin.wzl 已提交
923
  const ObBasicSysVar *var = NULL;
O
oceanbase-admin 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
  if (idx >= 0 && idx < ObSysVarFactory::ALL_SYS_VARS_COUNT) {
    var = sys_vars_[idx];
  }
  return var;
}

int ObBasicSessionInfo::init_system_variables(const bool print_info_log, const bool is_sys_tenant)
{
  int ret = OB_SUCCESS;
  ObString name;
  ObObj type;
  ObObj value;
  ObObj min_val;
  ObObj max_val;
  ObObjType var_type = ObNullType;
  int64_t var_flag = ObSysVarFlag::NONE;
  int64_t var_amount = ObSysVariables::get_amount();
  ObObj casted_value;
  ObArenaAllocator calc_buf(ObModIds::OB_SQL_SESSION);
  ObCastCtx cast_ctx(&calc_buf, NULL, CM_NONE, ObCharset::get_system_collation());
  for (int64_t i = 0; OB_SUCC(ret) && i < var_amount; ++i) {
    name.assign_ptr(const_cast<char*>(ObSysVariables::get_name(i).ptr()),
W
wangzelin.wzl 已提交
946
                    static_cast<ObString::obstr_size_t>(strlen(ObSysVariables::get_name(i).ptr())));
O
oceanbase-admin 已提交
947 948 949 950
    bool is_exist = false;
    if (OB_FAIL(sys_variable_exists(name, is_exist))) {
      LOG_WARN("failed to check if sys variable exists", K(name), K(ret));
    } else if (!is_exist) {
W
wangzelin.wzl 已提交
951
      // Note: 如果已经初始化过 base value,则下面的流程不会执行
O
oceanbase-admin 已提交
952 953 954 955 956 957 958 959 960
      var_type = ObSysVariables::get_type(i);
      var_flag = ObSysVariables::get_flags(i);
      value.set_varchar(ObSysVariables::get_value(i));
      value.set_collation_type(ObCharset::get_system_collation());
      min_val.set_varchar(ObSysVariables::get_min(i));
      min_val.set_collation_type(ObCharset::get_system_collation());
      max_val.set_varchar(ObSysVariables::get_max(i));
      max_val.set_collation_type(ObCharset::get_system_collation());
      type.set_type(var_type);
W
wangzelin.wzl 已提交
961
      if(is_sys_tenant) {
O
oceanbase-admin 已提交
962
        if (OB_FAIL(process_variable_for_tenant(name, value))) {
W
wangzelin.wzl 已提交
963
          LOG_WARN("process system variable for tenant error",  K(name), K(value), K(ret));
O
oceanbase-admin 已提交
964 965 966
        }
      }
      if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
967
        if (OB_FAIL(load_sys_variable(calc_buf, name, type, value, min_val, max_val, var_flag, false))) {
O
oceanbase-admin 已提交
968
          LOG_WARN("fail to load default system variable", K(name), K(ret));
W
wangzelin.wzl 已提交
969 970
        } else if (OB_NOT_NULL(sys_vars_[i]) &&
                   sys_vars_[i]->is_influence_plan() &&
O
oceanbase-admin 已提交
971 972
                   OB_FAIL(influence_plan_var_indexs_.push_back(i))) {
          LOG_WARN("fail to add influence plan sys var", K(name), K(ret));
W
wangzelin.wzl 已提交
973
        } else if(print_info_log) {
O
oceanbase-admin 已提交
974 975 976 977 978
          LOG_INFO("load default system variable", name.ptr(), value.get_string().ptr());
        }
      }
    }
  }  // end for
979
  release_to_pool_ = OB_SUCC(ret);
O
oceanbase-admin 已提交
980 981

  if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
982
    if (OB_FAIL(gen_sys_var_in_pc_str())) { //将影响plan的系统变量序列化并缓存
O
oceanbase-admin 已提交
983
      LOG_INFO("fail to generate system variables in pc str");
984 985
    } else if (OB_FAIL(gen_configs_in_pc_str())) {
      LOG_INFO("fail to generate system config in pc str");
O
oceanbase-admin 已提交
986 987 988 989 990 991 992
    } else {
      global_vars_version_ = 0;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
993
int ObBasicSessionInfo::update_query_sensitive_system_variable(ObSchemaGetterGuard &schema_guard)
O
oceanbase-admin 已提交
994 995
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
996
  const ObSysVarSchema *sysvar = NULL;
O
oceanbase-admin 已提交
997
  int64_t schema_version = -1;
W
wangzelin.wzl 已提交
998
  const ObSimpleSysVariableSchema *sys_variable_schema = NULL;
O
oceanbase-admin 已提交
999 1000 1001
  const uint64_t tenant_id = get_effective_tenant_id();
  int64_t refreshed_schema_version = OB_INVALID_VERSION;
  if (!check_sys_variable_) {
W
wangzelin.wzl 已提交
1002
    // 为了避免获取租户系统变量的SQL触发update_query_sensitive_system_variable形成循环依赖,这里直接跳过
O
oceanbase-admin 已提交
1003 1004 1005
  } else if (OB_FAIL(schema_guard.get_schema_version(tenant_id, refreshed_schema_version))) {
    LOG_WARN("fail to get tenant schema version", K(ret), K(tenant_id));
  } else if (OB_CORE_SCHEMA_VERSION >= refreshed_schema_version) {
W
wangzelin.wzl 已提交
1006
    // 建租户过程 or 建租户失败 or 本地schema未刷新出来的场景,大概率获取不到系统变量,此时跳过
O
oceanbase-admin 已提交
1007 1008 1009 1010 1011 1012 1013
  } else if (OB_FAIL(schema_guard.get_sys_variable_schema(tenant_id, sys_variable_schema))) {
    LOG_WARN("get tenant schema version failed", K(ret), K(tenant_id));
  } else if (OB_ISNULL(sys_variable_schema)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("sys variable schema should not be null", K(ret), K(tenant_id));
  } else if (FALSE_IT(schema_version = sys_variable_schema->get_schema_version())) {
    ret = OB_ERR_UNEXPECTED;
W
wangzelin.wzl 已提交
1014 1015 1016
  } else if (schema_version > get_global_vars_version()
             && schema_version > OB_CORE_SCHEMA_VERSION) { //系统变量schema_version有效才更新
    const ObTenantSchema *tenant_info = NULL;
O
oceanbase-admin 已提交
1017
    bool need_update_version = false;
W
wangzelin.wzl 已提交
1018
    const ObSysVariableSchema *sys_variable_schema = NULL;
O
oceanbase-admin 已提交
1019 1020 1021 1022
    if (OB_FAIL(schema_guard.get_tenant_info(get_effective_tenant_id(), tenant_info))) {
      LOG_WARN("get tenant info from schema guard failed", K(ret));
    } else if (OB_FAIL(schema_guard.get_sys_variable_schema(get_effective_tenant_id(), sys_variable_schema))) {
      if (OB_TENANT_NOT_EXIST == ret) {
W
wangzelin.wzl 已提交
1023
        // 新建租户过程可能获取不到sys_variable_schema,此时先暂时忽略
O
oceanbase-admin 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        LOG_INFO("tenant maybe creating, just skip", K(ret), K(ret));
        ret = OB_SUCCESS;
      } else {
        LOG_WARN("get sys variable schema failed", K(ret));
      }
    } else if (OB_ISNULL(sys_variable_schema)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("sys variable schema is null", K(ret));
    } else {
      for (int64_t i = 0; OB_SUCC(ret) && i < sys_variable_schema->get_sysvar_count(); ++i) {
        sysvar = sys_variable_schema->get_sysvar_schema(i);
        if (sysvar != NULL && sysvar->is_query_sensitive()) {
          if (OB_FAIL(update_sys_variable(sysvar->get_name(), sysvar->get_value()))) {
            if (OB_ERR_SYS_VARIABLE_UNKNOWN == ret) {
W
wangzelin.wzl 已提交
1038
              //刷出来的variable可能是来自于一个更高的版本,本地没有,忽略掉
O
oceanbase-admin 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
              ret = OB_SUCCESS;
            } else {
              LOG_WARN("update system variable failed", K(ret), K(*sysvar));
            }
          } else {
            need_update_version = true;
          }
        }
      }
      if (OB_SUCC(ret) && need_update_version) {
        set_global_vars_version(schema_version);
      }
    }
  }
  return ret;
}

int ObBasicSessionInfo::load_default_sys_variable(const bool print_info_log, const bool is_sys_tenant)
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1059 1060 1061
  if (OB_FAIL(sys_var_fac_.create_all_sys_vars())) {
    LOG_WARN("fail create all sys variables", K(ret));
  } else if (OB_FAIL(init_system_variables(print_info_log, is_sys_tenant))) {
O
oceanbase-admin 已提交
1062 1063 1064 1065 1066 1067 1068
    LOG_WARN("Init system variables failed !", K(ret));
  } else {
    variables_last_modify_time_ = ObTimeUtility::current_time();
  }
  return ret;
}

W
wangzelin.wzl 已提交
1069 1070 1071
//这个函数使用时机: 在升级期间从低版本session发至高版本后, 可能会补充某个系统变量值.
//用于session反序列化
int ObBasicSessionInfo::load_default_sys_variable(ObIAllocator &calc_buf, int64_t var_idx)
O
oceanbase-admin 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
{
  int ret = OB_SUCCESS;
  ObString name;
  ObObj type;
  ObObj value;
  ObObj min_val;
  ObObj max_val;
  ObObjType var_type = ObNullType;
  int64_t var_flag = ObSysVarFlag::NONE;
  if (var_idx < 0 || var_idx >= ObSysVarFactory::ALL_SYS_VARS_COUNT) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("the value of var_idx is unexpected", K(ret));
  } else {
    name.assign_ptr(const_cast<char*>(ObSysVariables::get_name(var_idx).ptr()),
W
wangzelin.wzl 已提交
1086
                    static_cast<ObString::obstr_size_t>(strlen(ObSysVariables::get_name(var_idx).ptr())));
O
oceanbase-admin 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095
    var_type = ObSysVariables::get_type(var_idx);
    var_flag = ObSysVariables::get_flags(var_idx);
    value.set_varchar(ObSysVariables::get_value(var_idx));
    value.set_collation_type(ObCharset::get_system_collation());
    min_val.set_varchar(ObSysVariables::get_min(var_idx));
    min_val.set_collation_type(ObCharset::get_system_collation());
    max_val.set_varchar(ObSysVariables::get_max(var_idx));
    max_val.set_collation_type(ObCharset::get_system_collation());
    type.set_type(var_type);
W
wangzelin.wzl 已提交
1096
    if (OB_FAIL(load_sys_variable(calc_buf, name, type, value, min_val, max_val, var_flag, false))) {
O
oceanbase-admin 已提交
1097 1098 1099 1100 1101 1102
      LOG_WARN("fail to load default system variable", K(name), K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
// Time to use this function:
//        pre calculation for empty session
int ObBasicSessionInfo::load_default_configs_in_pc()
{
  int ret = OB_SUCCESS;
  inf_pc_configs_.pushdown_storage_level_ = ObConfigInfoInPC::DEFAULT_PUSHDOWN_STORAGE_LEVEL;
  return ret;
}

int ObBasicSessionInfo::process_variable_for_tenant(const ObString &var, ObObj &val)
O
oceanbase-admin 已提交
1113 1114
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1115
  if(0 == var.compare(OB_SV_LOWER_CASE_TABLE_NAMES)) {
O
oceanbase-admin 已提交
1116 1117 1118 1119 1120 1121
    val.set_varchar("2");
    val.set_collation_type(ObCharset::get_system_collation());
  }
  return ret;
}

W
wangzelin.wzl 已提交
1122 1123
int ObBasicSessionInfo::create_sys_var(ObSysVarClassType sys_var_id,
                                       int64_t store_idx, ObBasicSysVar *&sys_var)
O
oceanbase-admin 已提交
1124 1125
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1126 1127
  OV (0 <= store_idx && store_idx < ObSysVarFactory::ALL_SYS_VARS_COUNT,
      OB_ERR_UNEXPECTED, sys_var_id, store_idx);
O
oceanbase-admin 已提交
1128
  if (OB_NOT_NULL(sys_vars_[store_idx])) {
W
wangzelin.wzl 已提交
1129 1130 1131
    OV (sys_vars_[store_idx]->get_type() == sys_var_id,
        OB_ERR_UNEXPECTED, sys_var_id, store_idx, sys_vars_[store_idx]->get_type());
    OX (sys_var = sys_vars_[store_idx]);
O
oceanbase-admin 已提交
1132
  } else {
W
wangzelin.wzl 已提交
1133 1134 1135
    OZ (sys_var_fac_.create_sys_var(sys_var_id, sys_var), sys_var_id);
    OV (OB_NOT_NULL(sys_var), OB_ERR_UNEXPECTED, sys_var_id, store_idx);
    OX (sys_vars_[store_idx] = sys_var);
O
oceanbase-admin 已提交
1136 1137 1138 1139
  }
  return ret;
}

W
wangzelin.wzl 已提交
1140 1141 1142
int ObBasicSessionInfo::inner_get_sys_var(const ObString &sys_var_name,
                                          int64_t &store_idx,
                                          ObBasicSysVar *&sys_var) const
O
oceanbase-admin 已提交
1143 1144 1145
{
  int ret = OB_SUCCESS;
  ObSysVarClassType sys_var_id = SYS_VAR_INVALID;
W
wangzelin.wzl 已提交
1146 1147
  if (OB_UNLIKELY(SYS_VAR_INVALID == (
              sys_var_id = ObSysVarFactory::find_sys_var_id_by_name(sys_var_name)))) {
O
oceanbase-admin 已提交
1148 1149 1150 1151
    ret = OB_ERR_SYS_VARIABLE_UNKNOWN;
    LOG_WARN("fail to find sys var id by name", K(ret), K(sys_var_name), K(lbt()));
  } else if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, store_idx))) {
    LOG_WARN("fail to calc sys var store idx", K(ret), K(sys_var_id), K(sys_var_name), K(lbt()));
W
wangzelin.wzl 已提交
1152 1153
  } else if (OB_UNLIKELY(store_idx < 0) ||
             OB_UNLIKELY(store_idx >= ObSysVarFactory::ALL_SYS_VARS_COUNT)) {
O
oceanbase-admin 已提交
1154 1155 1156 1157
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("got store_idx is invalid", K(ret), K(store_idx));
  } else if (OB_ISNULL(sys_vars_[store_idx])) {
    ret = OB_ENTRY_NOT_EXIST;
Q
qianchanger 已提交
1158
    LOG_WARN("sys var is NULL", K(ret), K(store_idx), K(sys_var_name));
O
oceanbase-admin 已提交
1159 1160 1161 1162 1163 1164
  } else {
    sys_var = sys_vars_[store_idx];
  }
  return ret;
}

W
wangzelin.wzl 已提交
1165 1166 1167
int ObBasicSessionInfo::inner_get_sys_var(const ObSysVarClassType sys_var_id,
                                          int64_t &store_idx,
                                          ObBasicSysVar *&sys_var) const
O
oceanbase-admin 已提交
1168 1169 1170 1171 1172 1173 1174
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(SYS_VAR_INVALID == sys_var_id)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_ERROR("invalid sys var id", K(ret), K(sys_var_id), K(lbt()));
  } else if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, store_idx))) {
    LOG_WARN("fail to calc sys var store idx", K(ret), K(sys_var_id), K(lbt()));
W
wangzelin.wzl 已提交
1175 1176
  } else if (OB_UNLIKELY(store_idx < 0) ||
             OB_UNLIKELY(store_idx >= ObSysVarFactory::ALL_SYS_VARS_COUNT)) {
O
oceanbase-admin 已提交
1177 1178 1179 1180
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("got store_idx is invalid", K(ret), K(store_idx));
  } else if (OB_ISNULL(sys_vars_[store_idx])) {
    ret = OB_ENTRY_NOT_EXIST;
Q
qianchanger 已提交
1181
    LOG_WARN("sys var is NULL", K(ret), K(store_idx));
O
oceanbase-admin 已提交
1182 1183 1184 1185 1186 1187
  } else {
    sys_var = sys_vars_[store_idx];
  }
  return ret;
}

W
wangzelin.wzl 已提交
1188 1189 1190
int ObBasicSessionInfo::change_value_for_special_sys_var(const ObString &sys_var_name,
                                                         const ObObj &ori_val,
                                                         ObObj &new_val)
O
oceanbase-admin 已提交
1191 1192 1193 1194 1195
{
  int ret = OB_SUCCESS;
  ObSysVarClassType sys_var_id = ObSysVarFactory::find_sys_var_id_by_name(sys_var_name);
  if (OB_UNLIKELY(SYS_VAR_INVALID == sys_var_id)) {
    LOG_WARN("fail to find sys var id by name", K(ret), K(sys_var_name));
W
wangzelin.wzl 已提交
1196 1197 1198 1199
  } else if (OB_FAIL(ObBasicSessionInfo::change_value_for_special_sys_var(
              sys_var_id, ori_val, new_val))) {
    LOG_WARN("fail to change value for special sys var", K(ret),
             K(sys_var_name), K(sys_var_id), K(ori_val));
O
oceanbase-admin 已提交
1200 1201 1202 1203
  }
  return ret;
}

W
wangzelin.wzl 已提交
1204 1205 1206
int ObBasicSessionInfo::change_value_for_special_sys_var(const ObSysVarClassType sys_var_id,
                                                         const ObObj &ori_val,
                                                         ObObj &new_val)
O
oceanbase-admin 已提交
1207 1208 1209
{
  int ret = OB_SUCCESS;
  int64_t sys_var_store_idx = -1;
W
wangzelin.wzl 已提交
1210 1211 1212
  if (SYS_VAR_VERSION_COMMENT == sys_var_id
      || (SYS_VAR_VERSION == sys_var_id && 0 == ori_val.val_len_) //version not changed by user
      || SYS_VAR_SYSTEM_TIME_ZONE == sys_var_id) {
O
oceanbase-admin 已提交
1213 1214
    if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, sys_var_store_idx))) {
      LOG_WARN("fail to calc sys var store idx", K(ret), K(sys_var_id));
W
wangzelin.wzl 已提交
1215 1216 1217 1218
    } else if (SYS_VAR_VERSION == sys_var_id && 0 == ori_val.val_len_) {
      new_val.set_varchar(ObSpecialSysVarValues::version_);
      new_val.set_collation_type(CS_TYPE_UTF8MB4_GENERAL_CI);
      new_val.set_collation_level(CS_LEVEL_SYSCONST);
O
oceanbase-admin 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227
    } else {
      new_val = ObSysVariables::get_default_value(sys_var_store_idx);
    }
  } else {
    new_val = ori_val;
  }
  return ret;
}

W
wangzelin.wzl 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

// 此函数中会调用ObBasicSessionInfo::change_value_for_special_sys_var改变一些值,
// 仅用于ObMPBase::load_system_variables中,
// 其他地方慎用
int ObBasicSessionInfo::load_sys_variable(ObIAllocator &calc_buf,
                                          const ObString &name,
                                          const ObObj &type,
                                          const ObObj &value,
                                          const ObObj &min_val,
                                          const ObObj &max_val,
                                          const int64_t flags,
                                          bool is_from_sys_table)
O
oceanbase-admin 已提交
1240 1241 1242
{
  int ret = OB_SUCCESS;
  ObObj casted_cell;
W
wangzelin.wzl 已提交
1243
  ObBasicSysVar *sys_var = NULL;
O
oceanbase-admin 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
  ObSysVarClassType var_id = SYS_VAR_INVALID;
  ObObj real_val;
  ObObj val_ptr;
  ObObj min_ptr;
  ObObj max_ptr;
  ObObj val_type;
  ObObj tmp_type;
  int64_t store_idx = -1;
  if (SYS_VAR_INVALID == (var_id = ObSysVarFactory::find_sys_var_id_by_name(name, is_from_sys_table))) {
    if (is_from_sys_table) {
      ret = OB_SUCCESS;
    } else {
      ret = OB_ERR_SYS_VARIABLE_UNKNOWN;
      LOG_ERROR("failed to find system variable", K(ret), K(name));
    }
  } else if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(var_id, store_idx))) {
    LOG_WARN("fail to calc sys var store idx", K(ret), K(var_id));
W
wangzelin.wzl 已提交
1261 1262 1263
  } else if (OB_FAIL(cast_sys_variable(calc_buf, false, var_id, type, value, flags, val_type, val_ptr))) {
    LOG_WARN("fail to cast system variable", K(var_id), K(type), K(value), K(flags),K(val_ptr), K(ret));
  } else if (OB_FAIL(cast_sys_variable(calc_buf, true, var_id, type, min_val, flags, tmp_type, min_ptr))) {
O
oceanbase-admin 已提交
1264
    LOG_WARN("fail to cast system variable", K(var_id), K(type), K(min_val), K(flags), K(min_val), K(min_ptr), K(ret));
W
wangzelin.wzl 已提交
1265
  } else if (OB_FAIL(cast_sys_variable(calc_buf, true, var_id, type, max_val, flags, tmp_type, max_ptr))) {
O
oceanbase-admin 已提交
1266 1267 1268 1269 1270 1271
    LOG_WARN("fail to cast system variable", K(var_id), K(type), K(max_val), K(flags), K(max_ptr), K(ret));
  } else if (OB_FAIL(create_sys_var(var_id, store_idx, sys_var))) {
    LOG_WARN("fail to create sys var", K(name), K(value), K(ret));
  } else if (OB_ISNULL(sys_var)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("sys var is NULL", K(name), K(value), K(ret));
W
wangzelin.wzl 已提交
1272 1273
  } else if (OB_FAIL(ObBasicSessionInfo::change_value_for_special_sys_var(
              var_id, val_ptr, real_val))) {
O
oceanbase-admin 已提交
1274 1275
    LOG_WARN("fail to change value for special sys var", K(ret), K(var_id), K(val_ptr));
  } else if (OB_FAIL(sys_var->init(real_val, min_ptr, max_ptr, val_type.get_type(), flags))) {
W
wangzelin.wzl 已提交
1276 1277 1278
    LOG_WARN("fail to init sys var", K(ret), K(sys_var->get_type()),
             K(real_val), K(name), K(value));
  } else if (OB_FAIL(process_session_variable(var_id, real_val,
1279 1280
                                              false /*check_timezone_valid*/,
                                              false /*is_update_sys_var*/))) {
W
wangzelin.wzl 已提交
1281
    LOG_WARN("process system variable error",  K(name), K(type), K(real_val), K(value), K(ret));
O
oceanbase-admin 已提交
1282 1283 1284 1285 1286 1287
  } else {
    variables_last_modify_time_ = ObTimeUtility::current_time();
  }
  return ret;
}

W
wangzelin.wzl 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
// 此函数中会调用ObBasicSessionInfo::change_value_for_special_sys_var改变一些值,
// 仅用于ObMPBase::load_system_variables中,
// 其他地方慎用
int ObBasicSessionInfo::load_sys_variable(ObIAllocator &calc_buf,
                                          const ObString &name,
                                          const int64_t dtype,
                                          const ObString &value_str,
                                          const ObString &min_val_str,
                                          const ObString &max_val_str,
                                          const int64_t flags,
                                          bool is_from_sys_table /*= false*/)
O
oceanbase-admin 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
{
  int ret = OB_SUCCESS;
  ObObj value, min_val, max_val;
  ObObj otype;
  value.set_varchar(value_str);
  value.set_collation_type(ObCharset::get_system_collation());
  min_val.set_varchar(min_val_str);
  min_val.set_collation_type(ObCharset::get_system_collation());
  max_val.set_varchar(max_val_str);
  max_val.set_collation_type(ObCharset::get_system_collation());
  otype.set_type(static_cast<ObObjType>(dtype));
W
wangzelin.wzl 已提交
1310 1311 1312 1313
  if (OB_FAIL(load_sys_variable(calc_buf, name, otype, value, min_val, max_val,
                                flags, is_from_sys_table))) {
    LOG_WARN("fail to load system variable", K(name), K(otype), K(value),
             K(min_val), K(max_val), K(flags), K(is_from_sys_table), K(ret));
O
oceanbase-admin 已提交
1314 1315 1316 1317
  }
  return ret;
}

W
wangzelin.wzl 已提交
1318 1319 1320 1321 1322 1323 1324 1325
int ObBasicSessionInfo::cast_sys_variable(ObIAllocator &calc_buf,
                                          bool is_range_value,
                                          const ObSysVarClassType sys_var_id,
                                          const ObObj &type,
                                          const ObObj &value,
                                          int64_t flags,
                                          ObObj &out_type,
                                          ObObj &out_value)
O
oceanbase-admin 已提交
1326 1327 1328 1329 1330 1331 1332 1333
{
  UNUSED(sys_var_id);
  int ret = OB_SUCCESS;
  ObObj casted_cell;
  if (ObVarcharType != value.get_type()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid type", K(value), K(ret));
  } else {
W
wangzelin.wzl 已提交
1334 1335 1336
    // 为max_val和min_val进行判断,variable的value值不会进入此判断
    if (is_range_value
        && value.get_varchar() == ObString::make_string(ObBasicSysVar::EMPTY_STRING)) {
O
oceanbase-admin 已提交
1337 1338 1339 1340 1341 1342
      out_value.set_null();
    } else if (ObBasicSysVar::is_null_value(value.get_varchar(), flags)) {
      out_value.set_null();
    } else {
      ObDataTypeCastParams dtc_params = get_dtc_params();
      ObCastCtx cast_ctx(&calc_buf, &dtc_params, CM_NONE, ObCharset::get_system_collation());
W
wangzelin.wzl 已提交
1343 1344 1345 1346 1347
      if (OB_FAIL(ObObjCaster::to_type(type.get_type(),
                                       ObCharset::get_system_collation(),
                                       cast_ctx,
                                       value,
                                       casted_cell))) {
O
oceanbase-admin 已提交
1348
        _LOG_WARN("failed to cast object, cell=%s from_type=%s to_type=%s ret=%d ",
W
wangzelin.wzl 已提交
1349 1350
                  to_cstring(value), ob_obj_type_str(value.get_type()),
                  ob_obj_type_str(type.get_type()), ret);
O
oceanbase-admin 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
      } else if (OB_FAIL(base_sys_var_alloc_.write_obj(casted_cell, &out_value))) {
        LOG_WARN("fail to store variable value", K(casted_cell), K(value), K(ret));
      } else {
        if (ob_is_string_type(out_value.get_type())) {
          out_value.set_collation_level(CS_LEVEL_SYSCONST);
          if (CS_TYPE_INVALID == out_value.get_collation_type()) {
            out_value.set_collation_type(ObCharset::get_system_collation());
          }
        }
      }
    }
    if (OB_SUCC(ret)) {
      out_type.set_type(type.get_type());
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1369
bool sys_var_compare(const SysVarNameVal &left,const SysVarNameVal &right)
O
oceanbase-admin 已提交
1370 1371 1372 1373 1374
{
  return left.name_ < right.name_;
}

/*
W
wangzelin.wzl 已提交
1375 1376 1377
 *获取影响physical plan的系统变量,以下系统变量会影响plan cache正确命中plan,需要在plan cache中进行处理
 *read_only:
    ObSql中在resolver之后,生成逻辑计划之前用来判断db和table是否为只读,其变化会影响plan cache正确命中。
O
oceanbase-admin 已提交
1378
 *ob_enable_transformation
W
wangzelin.wzl 已提交
1379
    ObSql中在resolver之后,生成逻辑计划前判断是否进行改写,会影响生成plan的结构。
O
oceanbase-admin 已提交
1380
 *binlog_row_image
W
wangzelin.wzl 已提交
1381
    在resolver中会使用,对生成的plan有影响。
O
oceanbase-admin 已提交
1382
 *collation_connection
W
wangzelin.wzl 已提交
1383 1384 1385
    在resolver中使用,对plan有影响。
 * sql_auto_is_null
    在resolver中使用,对plan有影响。
O
oceanbase-admin 已提交
1386
 *div_precision_increment
W
wangzelin.wzl 已提交
1387
    expr的类型推导中会使用,暂时未将该变量传进去,使用的是hard coding, bug:1043693;
O
oceanbase-admin 已提交
1388
 *ob_enable_aggregation_pushdown
W
wangzelin.wzl 已提交
1389
    在优化器中使用,会影响生成的plan。
O
oceanbase-admin 已提交
1390
 *ob_enable_index_direct_select
W
wangzelin.wzl 已提交
1391
    在resolver中使用,判断是否可以使用索引表,影响plan cache正确命中。
O
oceanbase-admin 已提交
1392
 *sql_mode
W
wangzelin.wzl 已提交
1393
    在resolver中有使用,会影响生成的plan。
O
oceanbase-admin 已提交
1394
 *ob_route_policy
W
wangzelin.wzl 已提交
1395 1396
    影响副本的类型的选项,进而影响决定是local还是remote的计划。plan cache当一次执行成功的local 语句,这次默认仍旧按照local执行
    并不会去判断location,如果期间更改了ob_route_policy,则会导致无法从新选择副本。
O
oceanbase-admin 已提交
1397
 *ob_read_consistency
W
wangzelin.wzl 已提交
1398
    会影响replica的选择,进行影响plan
O
oceanbase-admin 已提交
1399
 */
W
wangzelin.wzl 已提交
1400 1401 1402
//内部连接与外部连接获取到的sys_val顺序不一致,内部连接与外部连接执行同一sql不能命中同一plan,
//暂不影响线上的plan cache命中率
int ObBasicSessionInfo::get_influence_plan_sys_var(ObSysVarInPC &sys_vars) const
O
oceanbase-admin 已提交
1403 1404
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1405
  //get influence_plan_sys_var from sys_var_val_map
O
oceanbase-admin 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  int64_t index = 0;
  for (int64_t i = 0; OB_SUCC(ret) && i < get_influence_plan_var_count(); ++i) {
    index = influence_plan_var_indexs_.at(i);
    if (index >= ObSysVarFactory::ALL_SYS_VARS_COUNT) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("influence plan system var indexs out of range", K(i), K(ret));
    } else if (NULL == sys_vars_[index]) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("influence plan system var is NULL", K(i), K(ret));
    } else if (OB_FAIL(sys_vars.push_back(sys_vars_[index]->get_value()))) {
      LOG_WARN("influence plan system variables push failed", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
/*
 **内部session与用户session对应的影响plan的系统变量的顺序
 *
 *    inner_session                                           user_session
 *
 * 45,4194304,2,4,1,0,0,32,1,0,1,1,0,10485760,1            2,45,4,1,10485760,1,0,1,0,1,32,1,0,0,4194304
 *
 *1  collation_connection,                                   binlog_row_image,
 *2  sql_mode,                                               collation_connection,
 *3  binlog_row_image,                                       div_precision_increment,
 *4  div_precision_increment,                                explicit_defaults_for_timestamp,
 *5  explicit_defaults_for_timestamp,                        ob_bnl_join_cache_size,
 *6  read_only,                                              ob_enable_aggregation_pushdown,
 *7  ql_auto_is_null,                                        ob_enable_blk_nestedloop_join,
 *8  ,                                                       ob_enable_hash_group_by,
 *9  ob_enable_transformation,                               ob_enable_index_direct_select,
 *10 ob_enable_index_direct_select,                          b_enable_transformation,
 *11 ob_enable_aggregation_pushdown,                         ,
 *12 ob_enable_hash_group_by,                                ,
 *13 ob_enable_blk_nestedloop_join,                          read_only,
 *14 ob_bnl_join_cache_size,                                 sql_auto_is_null,
 *15 ,                                                       sql_mode,
*/
O
oceanbase-admin 已提交
1445 1446 1447
int ObBasicSessionInfo::gen_sys_var_in_pc_str()
{
  int ret = OB_SUCCESS;
O
obdev 已提交
1448
  const int64_t MAX_SYS_VARS_STR_SIZE = 1024;
O
oceanbase-admin 已提交
1449
  ObSysVarInPC sys_vars;
W
wangzelin.wzl 已提交
1450
  char *buf = NULL;
O
oceanbase-admin 已提交
1451 1452
  int64_t pos = 0;
  if (is_first_gen_) {
W
wangzelin.wzl 已提交
1453 1454
    //如果是第一次则需要分配内存
    if (NULL == (buf = (char *)name_pool_.alloc(MAX_SYS_VARS_STR_SIZE))) {
O
oceanbase-admin 已提交
1455 1456
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("fail to allocator memory", K(ret), K(MAX_SYS_VARS_STR_SIZE));
1457 1458 1459
    } else {
      set_sys_vars_encode_max_size(MAX_SYS_VARS_STR_SIZE);
      is_first_gen_ = false;
O
oceanbase-admin 已提交
1460 1461 1462 1463 1464 1465
    }
  } else {
    buf = sys_var_in_pc_str_.ptr();
    MEMSET(buf, 0, sys_var_in_pc_str_.length());
    sys_var_in_pc_str_.reset();
  }
1466
  int64_t sys_var_encode_max_size = get_sys_vars_encode_max_size();
O
oceanbase-admin 已提交
1467 1468 1469
  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(get_influence_plan_sys_var(sys_vars))) {
    LOG_WARN("fail to get influence plan system variables", K(ret));
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
  } else if (OB_FAIL(sys_vars.serialize_sys_vars(buf, sys_var_encode_max_size, pos))) {
    if (OB_BUF_NOT_ENOUGH == ret || OB_SIZE_OVERFLOW ==ret) {
      ret = OB_SUCCESS;
      // expand MAX_SYS_VARS_STR_SIZE 3 times.
      for (int64_t i = 0; OB_SUCC(ret) && i < 3; ++i) {
        sys_var_encode_max_size = 2 * sys_var_encode_max_size;
        if (NULL == (buf = (char *)name_pool_.alloc(sys_var_encode_max_size))) {
          ret = OB_ALLOCATE_MEMORY_FAILED;
          LOG_WARN("fail to allocator memory", K(ret), K(sys_var_encode_max_size));
        } else if (OB_FAIL(sys_vars.serialize_sys_vars(buf, sys_var_encode_max_size, pos))) {
          if (i != 2 && (OB_BUF_NOT_ENOUGH == ret || OB_SIZE_OVERFLOW ==ret)) {
            ret = OB_SUCCESS;
          } else {
            LOG_WARN("fail to serialize system vars", K(ret));
          }
        } else {
          break;
        }
      }
    } else {
      LOG_WARN("fail to serialize system vars", K(ret));
    }
    if (OB_SUCC(ret)) {
      set_sys_vars_encode_max_size(sys_var_encode_max_size);
      (void)sys_var_in_pc_str_.assign(buf, int32_t(pos));
    }
O
oceanbase-admin 已提交
1496
  } else {
O
obdev 已提交
1497
    (void)sys_var_in_pc_str_.assign(buf, int32_t(pos));
O
oceanbase-admin 已提交
1498 1499 1500 1501 1502
  }

  return ret;
}

W
wangzelin.wzl 已提交
1503
int ObBasicSessionInfo::update_sys_variable_by_name(const ObString &var, const ObObj &val)
O
oceanbase-admin 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
{
  int ret = OB_SUCCESS;
  ObSysVarClassType var_id = SYS_VAR_INVALID;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(val), K(ret));
  } else if (SYS_VAR_INVALID == (var_id = ObSysVarFactory::find_sys_var_id_by_name(var))) {
    ret = OB_ERR_SYS_VARIABLE_UNKNOWN;
    LOG_WARN("unknown variable", K(var), K(val), K(ret));
  } else if (OB_FAIL(update_sys_variable(var_id, val))) {
    LOG_WARN("failed to update sys variable", K(var), K(val), K(ret));
W
wangzelin.wzl 已提交
1515
  } else {}
O
oceanbase-admin 已提交
1516 1517 1518
  return ret;
}

W
wangzelin.wzl 已提交
1519
int ObBasicSessionInfo::update_sys_variable_by_name(const common::ObString &var, int64_t val)
O
oceanbase-admin 已提交
1520 1521 1522 1523 1524 1525
{
  ObObj obj;
  obj.set_int(val);
  return update_sys_variable_by_name(var, obj);
}

W
wangzelin.wzl 已提交
1526
int ObBasicSessionInfo::update_sys_variable(const ObSysVarClassType sys_var_id, const ObString &val)
O
oceanbase-admin 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
{
  ObObj obj;
  obj.set_varchar(val);
  obj.set_collation_type(ObCharset::get_system_collation());
  return update_sys_variable(sys_var_id, obj);
}

int ObBasicSessionInfo::update_sys_variable(const ObSysVarClassType sys_var_id, const int64_t val)
{
  ObObj obj;
  obj.set_int(val);
  return update_sys_variable(sys_var_id, obj);
}

W
wangzelin.wzl 已提交
1541
int ObBasicSessionInfo::update_sys_variable(const ObString &var, const ObString &val)
O
oceanbase-admin 已提交
1542 1543 1544
{
  int ret = OB_SUCCESS;
  ObSysVarClassType sys_var_id = SYS_VAR_INVALID;
W
wangzelin.wzl 已提交
1545
  ObBasicSysVar *sys_var = NULL;
O
oceanbase-admin 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
  if (OB_UNLIKELY(SYS_VAR_INVALID == (sys_var_id = ObSysVarFactory::find_sys_var_id_by_name(var)))) {
    ret = OB_ERR_SYS_VARIABLE_UNKNOWN;
    LOG_WARN("unknown variable", K(var), K(val), K(ret));
  } else if (OB_FAIL(inner_get_sys_var(sys_var_id, sys_var))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(var), K(val));
  } else if (OB_ISNULL(sys_var)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(var));
  } else {
    // trim quotation marks
    ObString tmp_val;
W
wangzelin.wzl 已提交
1557 1558 1559 1560
    if (val.length() > 1 && (('\'' == val[0]
        && '\'' == val[val.length() - 1])
        || ('\"' == val[0]
        && '\"' == val[val.length() - 1]))) {
O
oceanbase-admin 已提交
1561 1562 1563 1564
      tmp_val.assign_ptr(val.ptr() + 1, val.length() - 2);
    } else {
      tmp_val.assign_ptr(val.ptr(), val.length());
    }
W
wangzelin.wzl 已提交
1565
    // 将varchar类型转换为实际类型
O
oceanbase-admin 已提交
1566 1567 1568
    ObObj in_obj;
    in_obj.set_varchar(tmp_val);
    in_obj.set_collation_type(ObCharset::get_system_collation());
W
wangzelin.wzl 已提交
1569
    const ObObj *out_obj = NULL;
O
oceanbase-admin 已提交
1570 1571 1572 1573 1574
    ObObj buf_obj;
    ObArenaAllocator calc_buf(ObModIds::OB_SQL_SESSION);
    ObDataTypeCastParams dtc_params = get_dtc_params();
    ObCastCtx cast_ctx(&calc_buf, &dtc_params, CM_NONE, ObCharset::get_system_collation());
    if (OB_FAIL(ObObjCaster::to_type(sys_var->get_data_type(), cast_ctx, in_obj, buf_obj, out_obj))) {
W
wangzelin.wzl 已提交
1575 1576
      LOG_WARN("failed to cast obj", "expected type", sys_var->get_meta_type(),
               K(ret), K(var), K(in_obj));
O
oceanbase-admin 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
    } else if (OB_ISNULL(out_obj)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("casted success, but out_obj is NULL", K(in_obj), K(ret));
    } else if (OB_FAIL(update_sys_variable(sys_var_id, *out_obj))) {
      LOG_WARN("fail to update sys variable", K(ret), K(var), K(*out_obj));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1587
int ObBasicSessionInfo::update_sys_variable(const ObSysVarClassType sys_var_id, const ObObj &val)
O
oceanbase-admin 已提交
1588 1589 1590
{
  int ret = OB_SUCCESS;
  ObObj obj;
W
wangzelin.wzl 已提交
1591 1592 1593
  ObBasicSysVar *sys_var = NULL;
  int64_t sys_var_idx = 0;
  // 首先track变量的修改, 这样如果变量修改失败, 也不会造成客户端与服务端不一致的情况
O
oceanbase-admin 已提交
1594 1595 1596
  if (SYS_VAR_INVALID == sys_var_id) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid sys_var_id", K(sys_var_id), K(ret));
W
wangzelin.wzl 已提交
1597
  } else if (OB_FAIL(inner_get_sys_var(sys_var_id, sys_var_idx, sys_var))) {
O
oceanbase-admin 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606
    LOG_WARN("failed to inner get sys var", K(ret), K(sys_var_id), K(val));
  } else if (OB_ISNULL(sys_var)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("failed to inner get sys var, sys var is null", K(ret), K(sys_var_id), K(val));
  } else if (is_track_session_info()) {
    if (OB_FAIL(track_sys_var(sys_var_id, sys_var->get_value()))) {
      LOG_WARN("failed to track sys var", K(ret), K(sys_var_id), K(val));
    } else {
      variables_last_modify_time_ = ObTimeUtility::current_time();
W
wangzelin.wzl 已提交
1607 1608
      LOG_DEBUG("succ to track system variable",
                K(ret), K(sys_var_id), K(val), K(sys_var->get_value()));
O
oceanbase-admin 已提交
1609 1610
    }
  }
W
wangzelin.wzl 已提交
1611
  // 更新变量
O
oceanbase-admin 已提交
1612
  if (OB_SUCC(ret)) {
1613 1614
    if (OB_FAIL(process_session_variable(sys_var_id, val, false /*check_timezone_valid*/,
                                        true /*is_update_sys_var*/))) {
W
wangzelin.wzl 已提交
1615
      LOG_WARN("process system variable error",  K(sys_var_id), K(val), K(ret));
O
oceanbase-admin 已提交
1616
    } else if (OB_FAIL(sys_var_inc_info_.add_sys_var_id(sys_var_id))) {
W
wangzelin.wzl 已提交
1617
      LOG_WARN("add sys var id error",  K(sys_var_id), K(ret));
O
oceanbase-admin 已提交
1618
    } else {
W
wangzelin.wzl 已提交
1619 1620
      // 如果设置的time_zone是一个offset而不是时区,那么对其做formalize,固定格式为 +/-HH:MM
      if (OB_UNLIKELY(SYS_VAR_TIME_ZONE == sys_var_id && ! tz_info_wrap_.is_position_class())) {
O
oceanbase-admin 已提交
1621 1622 1623 1624 1625 1626 1627
        const int64_t buf_len = 16;
        char tmp_buf[buf_len] = {0};
        int64_t pos = 0;
        ObObj tmp_obj = val;
        if (OB_ISNULL(tz_info_wrap_.get_time_zone_info())) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("time zone info is null", K(ret));
W
wangzelin.wzl 已提交
1628 1629
        } else if (OB_FAIL(tz_info_wrap_.get_time_zone_info()->timezone_to_str(
                                              tmp_buf, buf_len, pos))) {
O
oceanbase-admin 已提交
1630 1631 1632
          LOG_WARN("timezone to str failed", K(ret));
        } else {
          tmp_obj.set_common_value(ObString(pos, tmp_buf));
W
wangzelin.wzl 已提交
1633
          if (OB_FAIL(deep_copy_sys_variable(*sys_var, sys_var_id, tmp_obj))) {
O
oceanbase-admin 已提交
1634 1635 1636
            LOG_WARN("deep copy sys var failed", K(ret));
          }
        }
W
wangzelin.wzl 已提交
1637 1638 1639 1640
      } else {
        if (ob_is_string_type(val.get_type())) {
          if (OB_FAIL(deep_copy_sys_variable(*sys_var, sys_var_id, val))) {
            LOG_WARN("fail to update system variable", K(sys_var_id), K(val), K(ret));
O
oceanbase-admin 已提交
1641
          }
W
wangzelin.wzl 已提交
1642 1643 1644 1645 1646 1647 1648
        } else if (ob_is_number_tc(val.get_type())) {
          if (OB_FAIL(deep_copy_sys_variable(*sys_var, sys_var_id, val))) {
            LOG_WARN("fail to update system variable", K(sys_var_id), K(val), K(ret));
          }
        } else {
          // int, bool, enum, uint do not need to do deep copy
          sys_var->set_value(val);
O
oceanbase-admin 已提交
1649 1650 1651 1652
        }
      }
    }
  }
W
wangzelin.wzl 已提交
1653 1654 1655 1656 1657
  // 处理PLAN_CHACHE相关的变量
  if (OB_SUCC(ret)
			&& !is_deserialized_
      && sys_var->is_influence_plan()
      && OB_FAIL(gen_sys_var_in_pc_str())) {
O
oceanbase-admin 已提交
1658 1659 1660 1661 1662
    LOG_ERROR("fail to gen sys var in pc str", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
1663 1664 1665 1666 1667 1668
int ObBasicSessionInfo::gen_configs_in_pc_str()
{
  int ret = OB_SUCCESS;
  const int64_t MAX_CONFIG_STR_SIZE = 512;
  char *buf = NULL;
  int64_t pos = 0;
1669 1670
  if (!GCONF.is_valid()) {
    // do nothing
W
wangzelin.wzl 已提交
1671
  } else {
1672 1673 1674 1675 1676 1677
    int64_t cluster_config_version = GCONF.get_current_version();
    int64_t tenant_config_version = (::oceanbase::omt::ObTenantConfigMgr::get_instance()).get_tenant_config_version(tenant_id_);

    if (!config_in_pc_str_.empty() &&
          !inf_pc_configs_.is_out_of_date(cluster_config_version, tenant_config_version)) {
      // unupdated configs do nothing
W
wangzelin.wzl 已提交
1678
    } else {
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
      // update out-dated cached configs
      // first time to generate configuaration strings, init allocator
      if (is_first_gen_config_) {
        inf_pc_configs_.init(tenant_id_);
        if (NULL == (buf = (char *)name_pool_.alloc(MAX_CONFIG_STR_SIZE))) {
          ret = OB_ALLOCATE_MEMORY_FAILED;
          LOG_WARN("fail to allocate memory", K(ret), K(MAX_CONFIG_STR_SIZE));
        }
        is_first_gen_config_ = false;
      } else {
        // reuse memory
        buf = config_in_pc_str_.ptr();
        MEMSET(buf, 0, config_in_pc_str_.length());
        config_in_pc_str_.reset();
      }

      // update configs
      if (OB_FAIL(ret)) {
      } else if (OB_FAIL(inf_pc_configs_.load_influence_plan_config())) {
        LOG_WARN("failed to load configurations that will influence executions plan.", K(ret));
      } else if (OB_FAIL(inf_pc_configs_.serialize_configs(buf, MAX_CONFIG_STR_SIZE, pos))) {
        LOG_WARN("failed to serialize configs", K(ret));
      } else {
        (void)config_in_pc_str_.assign(buf, int32_t(pos));
        inf_pc_configs_.update_version(cluster_config_version, tenant_config_version);
      }
W
wangzelin.wzl 已提交
1705 1706 1707 1708 1709 1710 1711
    }
  }
  return ret;
}

int ObBasicSessionInfo::deep_copy_trace_id_var(const ObObj &src_val,
                                               ObObj *dest_val_ptr)
O
oceanbase-admin 已提交
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(dest_val_ptr)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("dest val ptr is NULL", K(ret));
  } else {
    *dest_val_ptr = src_val;
    ObString new_str;
    ObString src_str;
    const int64_t STR_BUFF_LEN = sizeof(trace_id_buff_);
    int64_t src_str_len = 0;
    if (OB_FAIL(src_val.get_varchar(src_str))) {
      LOG_WARN("fail to get varchar", K(src_val), K(ret));
    } else if (OB_UNLIKELY((src_str_len = src_str.length()) == 0)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("invalid string", K(src_str), K(ret));
    } else if (STR_BUFF_LEN <= src_str_len) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("invalid src str len", K(src_str_len), K(ret));
    } else {
      MEMCPY(trace_id_buff_, src_str.ptr(), src_str_len);
      trace_id_buff_[src_str_len] = '\0';
      new_str.assign_ptr(trace_id_buff_, static_cast<ObString::obstr_size_t>(src_str_len));
      dest_val_ptr->set_varchar(new_str);
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1741 1742 1743 1744
//该接口中使用的name_pool_是一个只申请不释放的内存,暂时仅对会频繁更新的trace_id做优化
int ObBasicSessionInfo::deep_copy_sys_variable(ObBasicSysVar &sys_var,
                                               const ObSysVarClassType sys_var_id,
                                               const ObObj &src_val)
O
oceanbase-admin 已提交
1745 1746
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1747 1748 1749
  ObObj dest_val;
  if (OB_UNLIKELY(sys_var_id == SYS_VAR_OB_STATEMENT_TRACE_ID)) {
    if (OB_FAIL(deep_copy_trace_id_var(src_val, &dest_val))) {
O
oceanbase-admin 已提交
1750
      LOG_WARN("fail to deep copy trace id", K(ret));
W
wangzelin.wzl 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
    } else {
      sys_var.set_value(dest_val);
    }
  } else {
    if (OB_FAIL(inc_sys_var_alloc_.write_obj(src_val, &dest_val))) {
      LOG_WARN("fail to write obj", K(src_val), K(ret));
    } else {
      if (ob_is_string_type(src_val.get_type())) {
        dest_val.set_collation_level(CS_LEVEL_SYSCONST);
        if (CS_TYPE_INVALID == src_val.get_collation_type()) {
          dest_val.set_collation_type(ObCharset::get_default_collation(ObCharset::get_default_charset()));
        }
      }
      sys_var.set_value(dest_val);
    }

    // defragment.
    // https://work.aone.alibaba-inc.com/issue/39958139
    if (OB_SUCC(ret)) {
      if (inc_sys_var_alloc_.used() > next_frag_mem_point_) {
        // Note: this defrag impl. algrothim is not efficient.
        // howerver, considering it is not the common path, we don't expect to be here very often.
        // for an efficient impl. please refer https://yuque.antfin-inc.com/xiaochu.yh/doc/oa9az6
        common::ObStringBuf tmp_buf(ObModIds::OB_SQL_SESSION, OB_MALLOC_NORMAL_BLOCK_SIZE);
        if (OB_FAIL(defragment_sys_variable_to(tmp_buf))) {
          LOG_WARN("fail to defrag sys variable memory to temp alloc", K(ret));
        } else {
          LOG_INFO("Too much memory used for system variable values. do defragment",
                    "before", inc_sys_var_alloc_.used(), "after", tmp_buf.used());
          inc_sys_var_alloc_.reset();
          if (OB_FAIL(defragment_sys_variable_to(inc_sys_var_alloc_))) {
            LOG_WARN("fail to defrag sys variable memory to base sys var alloc", K(ret));
          } else {
            next_frag_mem_point_ = std::max(2 * inc_sys_var_alloc_.used(), OB_MALLOC_NORMAL_BLOCK_SIZE);
          }
        }
      }
    }
  }
  return ret;
}

int ObBasicSessionInfo::defragment_sys_variable_to(common::ObStringBuf &allocator)
{
  int ret = OB_SUCCESS;
  const SysVarIds &all_sys_var_ids = sys_var_inc_info_.get_all_sys_var_ids();
  for (int i = 0; i < all_sys_var_ids.count(); i++) {
    int64_t store_idx = -1;
    ObSysVarClassType sys_var_id = all_sys_var_ids.at(i);
    OZ (ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, store_idx));
    OV (0 <= store_idx && store_idx < ObSysVarFactory::ALL_SYS_VARS_COUNT);
    OV (OB_NOT_NULL(sys_vars_[store_idx]));
    if (OB_SUCC(ret)) {
      const ObObj &src_val = sys_vars_[store_idx]->get_value();
      if (ob_is_string_type(src_val.get_type()) || ob_is_number_tc(src_val.get_type())) {
        ObObj dest_val;
        if (OB_FAIL(allocator.write_obj(src_val, &dest_val))) {
          LOG_WARN("fail to write obj", K(src_val), K(ret));
        } else {
          sys_vars_[store_idx]->set_value(dest_val);
        }
      }
O
oceanbase-admin 已提交
1813 1814 1815 1816 1817
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1818 1819 1820
int ObBasicSessionInfo::update_session_sys_variable(ObExecContext &ctx,
                                                    const ObString &var,
                                                    const ObObj &val)
O
oceanbase-admin 已提交
1821 1822
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1823
  ObBasicSysVar *sys_var = NULL;
O
oceanbase-admin 已提交
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(ret), K(var));
  } else if (OB_FAIL(inner_get_sys_var(var, sys_var))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(var), K(val));
  } else if (OB_ISNULL(sys_var)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(var), K(val));
  } else {
    ObMySQLProxy sql_proxy;
    ObSetVar set_var(var, ObSetVar::SET_SCOPE_SESSION, false, OB_INVALID_ID, ctx.get_allocator(), sql_proxy);
    if (OB_FAIL(sys_var->session_update(ctx, set_var, val))) {
      LOG_WARN("session update system variable failed", K(ret), K(set_var));
    } else if (OB_FAIL(sys_var->update(ctx, set_var, val))) {
      LOG_WARN("fail to update sys var", K(ret), K(var), K(val));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
1844
int ObBasicSessionInfo::get_sys_variable_by_name(const ObString &var, ObBasicSysVar *&val) const
O
oceanbase-admin 已提交
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(var.empty())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else if (OB_FAIL(inner_get_sys_var(var, val))) {
    LOG_WARN("fail to inner get sys var", K(var), K(ret));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(var));
W
wangzelin.wzl 已提交
1855
  } else {}
O
oceanbase-admin 已提交
1856 1857 1858
  return ret;
}

W
wangzelin.wzl 已提交
1859
int ObBasicSessionInfo::get_sys_variable_by_name(const ObString &var, ObObj &val) const
O
oceanbase-admin 已提交
1860 1861
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1862
  ObBasicSysVar *sys_var = NULL;
O
oceanbase-admin 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
  if (OB_UNLIKELY(var.empty())) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else if (OB_FAIL(inner_get_sys_var(var, sys_var))) {
    LOG_WARN("fail to get sys var", K(ret), K(var));
  } else if (OB_ISNULL(sys_var)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to get sys var, but sys var is NULL", K(ret), K(var));
  } else {
    val = sys_var->get_value();
  }
  return ret;
}

W
wangzelin.wzl 已提交
1877
int ObBasicSessionInfo::get_sys_variable_by_name(const common::ObString &var, int64_t &val) const
O
oceanbase-admin 已提交
1878 1879 1880 1881 1882
{
  int ret = OB_SUCCESS;
  ObObj obj;
  if (OB_FAIL(get_sys_variable_by_name(var, obj))) {
  } else if (OB_FAIL(obj.get_int(val))) {
W
wangzelin.wzl 已提交
1883 1884
    LOG_WARN("wrong obj type for system variable", K(var), K(obj), K(ret), K(obj.get_meta().is_int()), K(obj.get_meta().get_type()));
  } else {}
O
oceanbase-admin 已提交
1885 1886 1887
  return ret;
}

W
wangzelin.wzl 已提交
1888 1889
int ObBasicSessionInfo::get_sys_variable(const ObSysVarClassType sys_var_id,
                                         common::ObObj &val) const
O
oceanbase-admin 已提交
1890 1891
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
1892
  ObBasicSysVar *var = NULL;
O
oceanbase-admin 已提交
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
  if (OB_UNLIKELY(SYS_VAR_INVALID == sys_var_id)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid sys_var_id", K(ret), K(sys_var_id));
  } else if (OB_FAIL(inner_get_sys_var(sys_var_id, var))) {
    LOG_WARN("fail to get sys var", K(ret), K(var));
  } else if (OB_ISNULL(var)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to get sys var, but sys var is NULL", K(ret), K(var));
  } else {
    val = var->get_value();
  }
  return ret;
}

W
wangzelin.wzl 已提交
1907 1908
int ObBasicSessionInfo::get_sys_variable(const ObSysVarClassType sys_var_id,
                                         common::ObString &val) const
O
oceanbase-admin 已提交
1909 1910 1911 1912 1913 1914 1915 1916
{
  int ret = OB_SUCCESS;
  ObObj obj;
  if (SYS_VAR_INVALID == sys_var_id) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid sys_var_id", K(sys_var_id), K(ret));
  } else if (OB_FAIL(get_sys_variable(sys_var_id, obj))) {
    LOG_WARN("failed to get system variable", K(sys_var_id), K(ret));
W
wangzelin.wzl 已提交
1917
  } else if (OB_FAIL(obj.get_varchar(val))) { //这里不用考虑sql_mode兼容转换,因为sql_mode取值不通过这里,而是通过sql_mode_manager_
O
oceanbase-admin 已提交
1918
    LOG_WARN("wrong obj type for system variable", K(sys_var_id), K(obj), K(ret));
W
wangzelin.wzl 已提交
1919
  } else {}
O
oceanbase-admin 已提交
1920 1921 1922
  return ret;
}

W
wangzelin.wzl 已提交
1923
int ObBasicSessionInfo::get_sys_variable(const ObSysVarClassType sys_var_id, int64_t &val) const
O
oceanbase-admin 已提交
1924 1925 1926 1927 1928 1929 1930
{
  int ret = OB_SUCCESS;
  ObObj obj;
  if (OB_FAIL(get_sys_variable(sys_var_id, obj))) {
    LOG_WARN("failed to get system variable", K(sys_var_id), K(obj), K(ret));
  } else if (OB_FAIL(obj.get_int(val))) {
    LOG_WARN("wrong obj type for system variable", K(sys_var_id), K(obj), K(ret));
W
wangzelin.wzl 已提交
1931
  } else {}
O
oceanbase-admin 已提交
1932 1933 1934
  return ret;
}

W
wangzelin.wzl 已提交
1935
int ObBasicSessionInfo::get_sys_variable(const ObSysVarClassType sys_var_id, uint64_t &val) const
O
oceanbase-admin 已提交
1936 1937 1938 1939 1940 1941 1942
{
  int ret = OB_SUCCESS;
  ObObj obj;
  if (OB_FAIL(get_sys_variable(sys_var_id, obj))) {
    LOG_WARN("failed to get system variable", K(sys_var_id), K(obj), K(ret));
  } else if (OB_FAIL(obj.get_uint64(val))) {
    LOG_WARN("wrong obj type for system variable", K(ret), K(sys_var_id), K(obj));
W
wangzelin.wzl 已提交
1943
  } else {}
O
oceanbase-admin 已提交
1944 1945 1946
  return ret;
}

W
wangzelin.wzl 已提交
1947
int ObBasicSessionInfo::sys_variable_exists(const ObString &var, bool &is_exists) const
O
oceanbase-admin 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
{
  int ret = OB_SUCCESS;
  is_exists = false;
  ObSysVarClassType sys_var_id = SYS_VAR_INVALID;
  int64_t store_idx = -1;
  if (SYS_VAR_INVALID == (sys_var_id = ObSysVarFactory::find_sys_var_id_by_name(var))) {
    LOG_DEBUG("sys var is not exist", K(var), K(ret));
  } else if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, store_idx))) {
    LOG_WARN("fail to calc sys var store idx", K(sys_var_id), K(var), K(ret));
  } else if (store_idx < 0 || store_idx >= ObSysVarFactory::ALL_SYS_VARS_COUNT) {
    ret = OB_ERR_UNEXPECTED;
    LOG_ERROR("got store_idx is invalid", K(store_idx), K(ret));
  } else {
    is_exists = (NULL != sys_vars_[store_idx]);
  }
  return ret;
}

R
raywill 已提交
1966
// for query and DML
1967
int ObBasicSessionInfo::set_cur_phy_plan(ObPhysicalPlan *cur_phy_plan)
O
oceanbase-admin 已提交
1968 1969 1970 1971 1972 1973 1974
{
  int ret = OB_SUCCESS;
  if (OB_ISNULL(cur_phy_plan)) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("current physical plan is NULL", K(lbt()), K(ret));
  } else {
    cur_phy_plan_ = cur_phy_plan;
R
raywill 已提交
1975
    plan_id_ = cur_phy_plan->get_plan_id();
W
wangzelin.wzl 已提交
1976 1977 1978
    int64_t len = cur_phy_plan->stat_.sql_id_.length();
    MEMCPY(sql_id_, cur_phy_plan->stat_.sql_id_.ptr(), len);
    sql_id_[len] = '\0';
O
oceanbase-admin 已提交
1979 1980 1981 1982
  }
  return ret;
}

R
raywill 已提交
1983
// for cmd only
W
wangzelin.wzl 已提交
1984
void ObBasicSessionInfo::set_cur_sql_id(char *sql_id)
O
oceanbase-admin 已提交
1985
{
W
wangzelin.wzl 已提交
1986 1987 1988 1989 1990
  if (nullptr == sql_id) {
    sql_id_[0] = '\0';
  } else {
    MEMCPY(sql_id_, sql_id, common::OB_MAX_SQL_ID_LENGTH + 1);
  }
O
oceanbase-admin 已提交
1991 1992
}

1993 1994 1995 1996 1997 1998 1999 2000 2001
void ObBasicSessionInfo::get_cur_sql_id(char *sql_id_buf, int64_t sql_id_buf_size) const
{
  if (common::OB_MAX_SQL_ID_LENGTH + 1 <= sql_id_buf_size) {
    MEMCPY(sql_id_buf, sql_id_, common::OB_MAX_SQL_ID_LENGTH + 1);
  } else {
    sql_id_buf[0] = '\0';
  }
}

W
wangzelin.wzl 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
int ObBasicSessionInfo::set_flt_trace_id(ObString trace_id)
{
  int ret = OB_SUCCESS;
  MEMSET(flt_trace_id_, 0x00, common::OB_MAX_UUID_LENGTH + 1);
  flt_trace_id_[0] = 0xFF;
  MEMCPY(flt_trace_id_+1, trace_id.ptr(), common::OB_MAX_UUID_LENGTH);
  return ret;
}

int ObBasicSessionInfo::set_flt_span_id(ObString span_id)
{
  int ret = OB_SUCCESS;
  MEMSET(flt_span_id_, 0x00, common::OB_MAX_UUID_LENGTH + 1);
  flt_span_id_[0] = 0xFF;
  MEMCPY(flt_span_id_+1, span_id.ptr(), common::OB_MAX_UUID_LENGTH);
  return ret;
}

void ObBasicSessionInfo::get_flt_trace_id(ObString &trace_id) const
{
  if (flt_trace_id_[0] == '\0') {
    trace_id.reset();
  } else {
    trace_id.assign(const_cast<char *>(&flt_trace_id_[1]), common::OB_MAX_UUID_LENGTH);
  }
}

void ObBasicSessionInfo::get_flt_span_id(ObString &span_id) const
{
  if (flt_span_id_[0] == '\0') {
    span_id.reset();
  } else {
    span_id.assign(const_cast<char *>(&flt_span_id_[1]), common::OB_MAX_UUID_LENGTH);
  }
}

ObObjType ObBasicSessionInfo::get_sys_variable_type(const ObString &var_name) const
O
oceanbase-admin 已提交
2039 2040 2041
{
  int ret = OB_SUCCESS;
  ObObjType obj_type = ObMaxType;
W
wangzelin.wzl 已提交
2042
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
  if (OB_FAIL(inner_get_sys_var(var_name, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(var_name));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(var_name));
  } else {
    obj_type = val->get_data_type();
  }
  return obj_type;
}

W
wangzelin.wzl 已提交
2054 2055
// select @@XXX的时候meta data中的type
ObObjType ObBasicSessionInfo::get_sys_variable_meta_type(const ObString &var_name) const
O
oceanbase-admin 已提交
2056 2057 2058
{
  int ret = OB_SUCCESS;
  ObObjType obj_type = ObMaxType;
W
wangzelin.wzl 已提交
2059
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
  if (OB_FAIL(inner_get_sys_var(var_name, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(var_name));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(var_name));
  } else {
    obj_type = val->get_meta_type();
  }
  return obj_type;
}

W
wangzelin.wzl 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
#define PROCESS_SESSION_INT_VARIABLE(sys_var)                                             \
    do {                                                                                  \
      ObArenaAllocator allocator(ObModIds::OB_SQL_SESSION);                             \
      int64_t val_int = 0;                                                                    \
      ObCastCtx cast_ctx(&allocator, NULL, CM_NONE, CS_TYPE_INVALID);                   \
      EXPR_GET_INT64_V2(val, val_int);                                                    \
      if (OB_SUCC(ret)) {                                                            \
        sys_var = val_int;                                                                \
      }                                                                                   \
    } while(0)
O
oceanbase-admin 已提交
2081

W
wangzelin.wzl 已提交
2082
OB_INLINE int ObBasicSessionInfo::process_session_variable(ObSysVarClassType var, const ObObj &val,
2083
    const bool check_timezone_valid/*true*/, const bool is_update_sys_var/*false*/)
O
oceanbase-admin 已提交
2084 2085 2086 2087
{
  int ret = OB_SUCCESS;
  switch (var) {
    case SYS_VAR_OB_LOG_LEVEL: {
W
wangzelin.wzl 已提交
2088
      OZ (process_session_log_level(val), val);
O
oceanbase-admin 已提交
2089 2090 2091
      break;
    }
    case SYS_VAR_OB_COMPATIBILITY_MODE: {
W
wangzelin.wzl 已提交
2092
      OZ (process_session_compatibility_mode_value(val), val);
O
oceanbase-admin 已提交
2093 2094 2095
      break;
    }
    case SYS_VAR_SQL_MODE: {
W
wangzelin.wzl 已提交
2096
      OZ (process_session_sql_mode_value(val), val);
O
oceanbase-admin 已提交
2097 2098 2099
      break;
    }
    case SYS_VAR_TIME_ZONE: {
W
wangzelin.wzl 已提交
2100
      OZ (process_session_time_zone_value(val, check_timezone_valid));
O
oceanbase-admin 已提交
2101 2102 2103
      break;
    }
    case SYS_VAR_ERROR_ON_OVERLAP_TIME: {
W
wangzelin.wzl 已提交
2104
      OZ (process_session_overlap_time_value(val));
O
oceanbase-admin 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113
      break;
    }
    case SYS_VAR_WAIT_TIMEOUT: {
      LockGuard lock_guard(thread_data_mutex_);
      PROCESS_SESSION_INT_VARIABLE(thread_data_.wait_timeout_);
      break;
    }
    case SYS_VAR_DEBUG_SYNC: {
      const bool is_global = false;
2114
      ret = process_session_debug_sync(val, is_global, is_update_sys_var);
O
oceanbase-admin 已提交
2115 2116 2117 2118
      break;
    }
    case SYS_VAR_OB_GLOBAL_DEBUG_SYNC: {
      const bool is_global = true;
2119
      ret = process_session_debug_sync(val, is_global, is_update_sys_var);
O
oceanbase-admin 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
      break;
    }
    case SYS_VAR_OB_READ_CONSISTENCY: {
      int64_t consistency = 0;
      PROCESS_SESSION_INT_VARIABLE(consistency);
      if (OB_SUCC(ret)) {
        consistency_level_ = static_cast<ObConsistencyLevel>(consistency);
      }
      break;
    }
    case SYS_VAR_AUTO_INCREMENT_INCREMENT: {
      uint64_t uint_val = 0;
W
wangzelin.wzl 已提交
2132 2133
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache_.set_auto_increment_increment(uint_val));
O
oceanbase-admin 已提交
2134 2135 2136 2137
      break;
    }
    case SYS_VAR_SQL_THROTTLE_CURRENT_PRIORITY: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2138 2139
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_sql_throttle_current_priority(int_val));
O
oceanbase-admin 已提交
2140 2141 2142 2143
      break;
    }
    case SYS_VAR_OB_LAST_SCHEMA_VERSION: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2144 2145
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_last_schema_version(int_val));
O
oceanbase-admin 已提交
2146 2147 2148 2149
      break;
    }
    case SYS_VAR_SQL_SELECT_LIMIT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2150 2151
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_sql_select_limit(int_val));
O
oceanbase-admin 已提交
2152 2153 2154 2155
      break;
    }
    case SYS_VAR_AUTO_INCREMENT_OFFSET: {
      uint64_t uint_val = 0;
W
wangzelin.wzl 已提交
2156 2157
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache_.set_auto_increment_offset(uint_val));
O
oceanbase-admin 已提交
2158 2159 2160 2161
      break;
    }
    case SYS_VAR_LAST_INSERT_ID: {
      uint64_t uint_val = 0;
W
wangzelin.wzl 已提交
2162 2163
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache_.set_last_insert_id(uint_val));
O
oceanbase-admin 已提交
2164 2165 2166 2167
      break;
    }
    case SYS_VAR_BINLOG_ROW_IMAGE: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2168 2169
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_binlog_row_image(int_val));
O
oceanbase-admin 已提交
2170 2171 2172 2173
      break;
    }
    case SYS_VAR_FOREIGN_KEY_CHECKS: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2174 2175
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_foreign_key_checks(int_val));
O
oceanbase-admin 已提交
2176 2177
      break;
    }
W
wangzelin.wzl 已提交
2178 2179 2180 2181 2182 2183 2184
    case SYS_VAR_DEFAULT_PASSWORD_LIFETIME: {
      uint64_t uint_val = 0;
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache_.set_default_password_lifetime(uint_val));
      break;
    }
    case SYS_VAR_TX_ISOLATION : {
O
oceanbase-admin 已提交
2185
      ObString str_val;
W
wangzelin.wzl 已提交
2186 2187 2188 2189 2190 2191
      ObTxIsolationLevel isolation = ObTxIsolationLevel::INVALID;
      OZ (val.get_string(str_val));
      OX (isolation = tx_isolation_from_str(str_val));
      OV (isolation != ObTxIsolationLevel::INVALID, OB_ERR_UNEXPECTED,
          str_val, isolation);
      OX (sys_vars_cache_.set_tx_isolation(isolation));
O
oceanbase-admin 已提交
2192 2193 2194 2195
      break;
    }
    case SYS_VAR_TX_READ_ONLY: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2196 2197
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_tx_read_only(int_val != 0));
O
oceanbase-admin 已提交
2198 2199 2200 2201
      break;
    }
    case SYS_VAR_OB_ENABLE_PLAN_CACHE: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2202 2203
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_enable_plan_cache(int_val != 0));
O
oceanbase-admin 已提交
2204 2205 2206 2207
      break;
    }
    case SYS_VAR_OPTIMIZER_USE_SQL_PLAN_BASELINES: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2208 2209
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_optimizer_use_sql_plan_baselines(int_val != 0));
O
oceanbase-admin 已提交
2210 2211 2212 2213
      break;
    }
    case SYS_VAR_OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2214 2215
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_optimizer_capture_sql_plan_baselines(int_val != 0));
O
oceanbase-admin 已提交
2216 2217 2218 2219
      break;
    }
    case SYS_VAR_IS_RESULT_ACCURATE: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2220 2221
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_is_result_accurate(int_val != 0));
O
oceanbase-admin 已提交
2222 2223
      break;
    }
W
wangzelin.wzl 已提交
2224 2225 2226 2227
    case SYS_VAR_OB_ENABLE_TRANSMISSION_CHECKSUM: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_enable_transmission_checksum(int_val != 0));
O
oceanbase-admin 已提交
2228 2229 2230 2231
      break;
    }
    case SYS_VAR_CHARACTER_SET_RESULTS: {
      int64_t coll_int64 = 0;
W
wangzelin.wzl 已提交
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
      // 无效的character type,用户获取过程中,也需要保证返回NULL
      if (val.is_null()) {
        OX (sys_vars_cache_.set_character_set_results(CHARSET_INVALID));
      } else if (OB_FAIL(val.get_int(coll_int64))) {
        LOG_WARN("fail to get int from value", K(val), K(ret));
      } else if (OB_UNLIKELY(false == ObCharset::is_valid_collation(coll_int64))) {
        // 这里不设置错误码
        LOG_WARN("invalid collation", K(coll_int64), K(val));
        OX (sys_vars_cache_.set_character_set_results(CHARSET_INVALID));
      } else {
        OX (sys_vars_cache_.set_character_set_results(
            ObCharset::charset_type_by_coll(static_cast<ObCollationType>(coll_int64))));
      }
      break;
    }
    case SYS_VAR_CHARACTER_SET_CONNECTION: {
      int64_t coll_int64 = 0;
      // 无效的character type,用户获取过程中,也需要保证返回NULL
O
oceanbase-admin 已提交
2250
      if (val.is_null()) {
W
wangzelin.wzl 已提交
2251
        OX (sys_vars_cache_.set_character_set_connection(CHARSET_INVALID));
O
oceanbase-admin 已提交
2252 2253 2254
      } else if (OB_FAIL(val.get_int(coll_int64))) {
        LOG_WARN("fail to get int from value", K(val), K(ret));
      } else if (OB_UNLIKELY(false == ObCharset::is_valid_collation(coll_int64))) {
W
wangzelin.wzl 已提交
2255
        // 这里不设置错误码
O
oceanbase-admin 已提交
2256
        LOG_WARN("invalid collation", K(coll_int64), K(val));
W
wangzelin.wzl 已提交
2257
        OX (sys_vars_cache_.set_character_set_connection(CHARSET_INVALID));
O
oceanbase-admin 已提交
2258
      } else {
W
wangzelin.wzl 已提交
2259 2260
        OX (sys_vars_cache_.set_character_set_connection(
            ObCharset::charset_type_by_coll(static_cast<ObCollationType>(coll_int64))));
O
oceanbase-admin 已提交
2261 2262 2263
      }
      break;
    }
W
wangzelin.wzl 已提交
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
    case SYS_VAR_OB_ENABLE_JIT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_enable_jit(static_cast<ObJITEnableMode>(int_val)));
      break;
    }
    case SYS_VAR_CURSOR_SHARING: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_cursor_sharing_mode(static_cast<ObCursorSharingMode>(int_val)));
      break;
    }
O
oceanbase-admin 已提交
2276 2277
    case SYS_VAR_OB_ENABLE_SQL_AUDIT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2278 2279
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_enable_sql_audit(int_val != 0));
O
oceanbase-admin 已提交
2280 2281 2282 2283 2284
      break;
    }
    case SYS_VAR_NLS_LENGTH_SEMANTICS: {
      ObString str_val;
      ObLengthSemantics nls_length_semantics = LS_BYTE;
W
wangzelin.wzl 已提交
2285 2286 2287 2288
      OZ (val.get_string(str_val));
      OX (nls_length_semantics = get_length_semantics(str_val));
      OV (nls_length_semantics != LS_INVALIED, OB_ERR_UNEXPECTED, nls_length_semantics);
      OX (sys_vars_cache_.set_nls_length_semantics(nls_length_semantics));
O
oceanbase-admin 已提交
2289 2290 2291 2292
      break;
    }
    case SYS_VAR_AUTOCOMMIT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2293 2294
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_autocommit(int_val != 0));
O
oceanbase-admin 已提交
2295 2296
      break;
    }
O
obdev 已提交
2297
    case SYS_VAR_OB_ENABLE_SHOW_TRACE: {
O
oceanbase-admin 已提交
2298
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2299 2300
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_enable_trace_log(int_val != 0));
O
oceanbase-admin 已提交
2301 2302 2303 2304
      break;
    }
    case SYS_VAR_OB_ORG_CLUSTER_ID: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2305 2306
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_org_cluster_id(int_val));
O
oceanbase-admin 已提交
2307 2308 2309 2310
      break;
    }
    case SYS_VAR_OB_QUERY_TIMEOUT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2311 2312
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_query_timeout(int_val));
O
oceanbase-admin 已提交
2313 2314 2315 2316
      break;
    }
    case SYS_VAR_OB_PL_BLOCK_TIMEOUT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2317 2318 2319 2320 2321 2322 2323 2324
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_pl_block_timeout(int_val));
      break;
    }
    case SYS_VAR_PLSQL_CCFLAGS: {
      ObString plsql_ccflags;
      OZ (val.get_string(plsql_ccflags));
      OX (sys_vars_cache_.set_plsql_ccflags(plsql_ccflags));
O
oceanbase-admin 已提交
2325 2326 2327 2328
      break;
    }
    case SYS_VAR_OB_TRX_TIMEOUT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2329 2330
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_trx_timeout(int_val));
O
oceanbase-admin 已提交
2331 2332 2333 2334
      break;
    }
    case SYS_VAR_OB_TRX_IDLE_TIMEOUT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2335 2336
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_trx_idle_timeout(int_val));
O
oceanbase-admin 已提交
2337 2338 2339 2340
      break;
    }
    case SYS_VAR_OB_TRX_LOCK_TIMEOUT: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2341 2342
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_ob_trx_lock_timeout(int_val));
O
oceanbase-admin 已提交
2343 2344 2345 2346
      break;
    }
    case SYS_VAR_COLLATION_CONNECTION: {
      int64_t int_val = 0;
W
wangzelin.wzl 已提交
2347 2348
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache_.set_collation_connection(int_val));
O
oceanbase-admin 已提交
2349 2350 2351
      break;
    }
    case SYS_VAR_TIMESTAMP: {
W
wangzelin.wzl 已提交
2352 2353 2354 2355
      //系统变脸timestamp默认值为0,是number类型, 设置单位是s。
      //当该系统变量设置为非0后, 则内部now()等时间函数会使用设置的值。
      //由于设置的单位是s, 内部是用us为单位的int64描述, 如果是用设置的
      //timestamp, 会先将设置的量转为us并四舍五入
O
oceanbase-admin 已提交
2356
      if (val.get_number().is_zero()) {
W
wangzelin.wzl 已提交
2357
        sys_vars_cache_.set_timestamp(0);
O
oceanbase-admin 已提交
2358
      } else {
W
wangzelin.wzl 已提交
2359
        const ObObj *res_obj = NULL;
O
oceanbase-admin 已提交
2360 2361 2362
        ObArenaAllocator allocator(common::ObModIds::OB_SQL_EXPR_CALC);
        number::ObNumber value;
        number::ObNumber unit;
W
wangzelin.wzl 已提交
2363 2364
        if (OB_FAIL(unit.from(static_cast<int64_t>(USECS_PER_SEC * 10),
                              allocator))) {
O
oceanbase-admin 已提交
2365 2366 2367 2368 2369 2370
          LOG_WARN("failed to get the number", K(ret));
        } else if (OB_FAIL(val.get_number().mul(unit, value, allocator))) {
          LOG_WARN("failed to get the result of timestamp to microsecond", K(ret));
        } else {
          ObObj param_obj;
          param_obj.set_number(value);
W
wangzelin.wzl 已提交
2371 2372 2373
          ObCollationType cast_coll_type = static_cast<ObCollationType>(
                                           get_local_collation_connection());
          //const ObDataTypeCastParams dtc_params(TZ_INFO(this), GET_NLS_FORMATS(this), get_nls_collation(), get_nls_collation_nation());;
O
oceanbase-admin 已提交
2374 2375
          ObDataTypeCastParams dtc_params = get_dtc_params();
          ObCastCtx cast_ctx(&allocator,
W
wangzelin.wzl 已提交
2376 2377 2378 2379 2380
                             &dtc_params,
                             0, /*number_int 该变量无用*/
                             CM_NONE,
                             cast_coll_type,
                             NULL /* time zone info */);
O
oceanbase-admin 已提交
2381 2382 2383 2384 2385 2386
          EXPR_CAST_OBJ_V2(ObIntType, param_obj, res_obj);
          if (OB_SUCC(ret)) {
            if (OB_ISNULL(res_obj)) {
              ret = OB_ERR_UNEXPECTED;
              LOG_WARN("result obj is null");
            } else {
W
wangzelin.wzl 已提交
2387 2388 2389
              //处理四舍五入 int64_t 最大值为9,223,372,036,854,775,807
              //而9999-12-31到1970之间差值为2,469,899,520,000,000,000因此足够转换
              sys_vars_cache_.set_timestamp((res_obj->get_int() + 5) / 10);
O
oceanbase-admin 已提交
2390 2391 2392 2393 2394 2395 2396 2397
            }
          } else {
            LOG_WARN("failed to convert the number to int", K(ret));
          }
        }
      }
      break;
    }
W
wangzelin.wzl 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
    case SYS_VAR_NLS_ISO_CURRENCY: {
      ObString country_str;
      ObString currency_str;
      if (OB_FAIL(val.get_string(country_str))) {
        LOG_WARN("fail to get iso_nls_currency str value", K(ret), K(var));
      } else if (OB_FAIL(IsoCurrencyUtils::get_currency_by_country_name(country_str,
                 currency_str))) {
        ret = OB_ERR_WRONG_VALUE_FOR_VAR;
        LOG_WARN("failed to get currency by country name", K(ret));
      } else {
        sys_vars_cache_.set_iso_nls_currency(currency_str);
      }
      break;
    }
O
oceanbase-admin 已提交
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
    case SYS_VAR_NLS_DATE_FORMAT:
    case SYS_VAR_NLS_TIMESTAMP_FORMAT:
    case SYS_VAR_NLS_TIMESTAMP_TZ_FORMAT: {
      ObString format;
      if (OB_FAIL(val.get_string(format))) {
        LOG_WARN("fail to get nls_date_format str value", K(ret), K(var));
      } else {
        int64_t nls_enum = ObNLSFormatEnum::NLS_DATE;
        ObDTMode mode = DT_TYPE_DATETIME;
        if (SYS_VAR_NLS_TIMESTAMP_FORMAT == var) {
          mode |= DT_TYPE_ORACLE;
          nls_enum = ObNLSFormatEnum::NLS_TIMESTAMP;
        } else if (SYS_VAR_NLS_TIMESTAMP_TZ_FORMAT == var) {
          mode |= DT_TYPE_ORACLE;
          mode |= DT_TYPE_TIMEZONE;
          nls_enum = ObNLSFormatEnum::NLS_TIMESTAMP_TZ;
        }
        ObSEArray<ObDFMElem, ObDFMUtil::COMMON_ELEMENT_NUMBER> dfm_elems;
W
wangzelin.wzl 已提交
2430 2431 2432 2433
        ObFixedBitSet<OB_DEFAULT_BITSET_SIZE_FOR_DFM> elem_flags;
        //1. parse and check semantic of format string
        if (OB_FAIL(ObDFMUtil::parse_datetime_format_string(format, dfm_elems,
                                                            false/* support double-quotes */))) {
O
oceanbase-admin 已提交
2434 2435 2436 2437 2438
          LOG_WARN("fail to parse oracle datetime format string", K(ret), K(format));
        } else if (OB_FAIL(ObDFMUtil::check_semantic(dfm_elems, elem_flags, mode))) {
          LOG_WARN("check semantic of format string failed", K(ret), K(format));
        } else {
          switch (nls_enum) {
W
wangzelin.wzl 已提交
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
          case ObNLSFormatEnum::NLS_DATE:
            sys_vars_cache_.set_nls_date_format(format);
            break;
          case ObNLSFormatEnum::NLS_TIMESTAMP:
            sys_vars_cache_.set_nls_timestamp_format(format);
            break;
          case ObNLSFormatEnum::NLS_TIMESTAMP_TZ:
            sys_vars_cache_.set_nls_timestamp_tz_format(format);
            break;
          default:
            break;
O
oceanbase-admin 已提交
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
          }
        }
        LOG_DEBUG("succ to set SYS_VAR_NLS_FORMAT", K(ret), K(var), K(nls_enum), K(format));
      }
      break;
    }
    case SYS_VAR_NLS_NCHAR_CHARACTERSET:
    case SYS_VAR_NLS_CHARACTERSET: {
      ObString str_val;
      ObCharsetType charset = CHARSET_INVALID;
      ObCollationType collation = CS_TYPE_INVALID;
W
wangzelin.wzl 已提交
2461 2462 2463 2464 2465
      OZ (val.get_string(str_val), val);
      OX (charset = ObCharset::charset_type_by_name_oracle(str_val));
      OX (collation = ObCharset::get_default_collation_oracle(charset));
      OV (ObCharset::is_valid_charset(charset) && ObCharset::is_valid_collation(collation),
          OB_ERR_INVALID_CHARACTER_STRING, str_val, charset, collation);
O
oceanbase-admin 已提交
2466
      if (var == SYS_VAR_NLS_CHARACTERSET) {
W
wangzelin.wzl 已提交
2467
        OX (sys_vars_cache_.set_nls_collation(collation));
O
oceanbase-admin 已提交
2468
      } else {
W
wangzelin.wzl 已提交
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
        OX (sys_vars_cache_.set_nls_nation_collation(collation));
      }
      break;
    }
    case SYS_VAR__OB_OLS_POLICY_SESSION_LABELS: {
      ObString serialized_data;
      if (OB_FAIL(val.get_string(serialized_data))) {
        LOG_WARN("fail to get str value", K(ret), K(var));
      } else if (OB_FAIL(ObLabelSeResolver::deserialize_session_labels(serialized_data,
                                                                       labels_))) {
        LOG_WARN("fail to deserialize_session_labels", K(ret), K(serialized_data));
O
oceanbase-admin 已提交
2480 2481 2482 2483 2484 2485 2486 2487
      }
      break;
    }
    case SYS_VAR_OB_TRACE_INFO: {
      ObString trace_info;
      if (OB_FAIL(val.get_string(trace_info))) {
        LOG_WARN("fail to get str value", K(ret), K(var));
      } else {
W
wangzelin.wzl 已提交
2488
        sys_vars_cache_.set_ob_trace_info(trace_info);
O
oceanbase-admin 已提交
2489 2490 2491 2492
      }
      break;
    }
    default: {
W
wangzelin.wzl 已提交
2493
      //do nothing
O
oceanbase-admin 已提交
2494 2495 2496 2497 2498
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2499 2500
// for debug purpose, not used for now
int ObBasicSessionInfo::dump_all_sys_vars() const
O
oceanbase-admin 已提交
2501 2502
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2503 2504 2505 2506 2507 2508 2509 2510 2511
  int64_t store_idx = OB_INVALID_INDEX_INT64;
  ObBasicSessionInfo::SysVarsCache sys_vars_cache;
  int64_t var_amount = ObSysVariables::get_amount();
  for (int64_t i = 0; OB_SUCC(ret) && i < var_amount; ++i) {
    store_idx = ObSysVarsToIdxMap::get_store_idx((int64_t)ObSysVariables::get_sys_var_id(i));
    OV (0 <= store_idx && store_idx < ObSysVarFactory::ALL_SYS_VARS_COUNT);
    OV (OB_NOT_NULL(sys_vars_[store_idx]));
    if (OB_SUCC(ret)) {
      LOG_INFO("DUMP sys vars", K(i), K(store_idx), KP(this), KP(sys_vars_[store_idx]), "info", *sys_vars_[store_idx]);
O
oceanbase-admin 已提交
2512 2513 2514 2515 2516
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
2517
int ObBasicSessionInfo::init_sys_vars_cache_base_values()
O
oceanbase-admin 已提交
2518 2519
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2520 2521 2522 2523 2524 2525 2526 2527 2528
  int64_t store_idx = OB_INVALID_INDEX_INT64;
  ObBasicSessionInfo::SysVarsCache sys_vars_cache;
  int64_t var_amount = ObSysVariables::get_amount();
  for (int64_t i = 0; OB_SUCC(ret) && i < var_amount; ++i) {
    store_idx = ObSysVarsToIdxMap::get_store_idx((int64_t)ObSysVariables::get_sys_var_id(i));
    OX (fill_sys_vars_cache_base_value(
            ObSysVariables::get_sys_var_id(i),
            sys_vars_cache,
            ObSysVariables::get_default_value(store_idx) ));
O
oceanbase-admin 已提交
2529 2530 2531 2532
  }
  return ret;
}

W
wangzelin.wzl 已提交
2533 2534 2535 2536
int ObBasicSessionInfo::fill_sys_vars_cache_base_value(
    ObSysVarClassType var,
    ObBasicSessionInfo::SysVarsCache &sys_vars_cache,
    const ObObj &val)
O
oceanbase-admin 已提交
2537 2538
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
2539 2540 2541 2542 2543 2544 2545
  switch (var) {
    case SYS_VAR_SQL_MODE: {
      ObSQLMode sql_mode = static_cast<ObSQLMode>(val.get_uint64());
      ObSQLMode real_sql_mode = (sql_mode & (~ALL_SMO_COMPACT_MODE)) |
          (sys_vars_cache.get_sql_mode() & ALL_SMO_COMPACT_MODE);
      sys_vars_cache.set_base_sql_mode(real_sql_mode);
      break;
O
oceanbase-admin 已提交
2546
    }
W
wangzelin.wzl 已提交
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 2594 2595 2596 2597 2598 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 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 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 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
    case SYS_VAR_OB_COMPATIBILITY_MODE: {
      uint64_t uint_val = 0;
      ObCompatibilityMode comp_mode = static_cast<ObCompatibilityMode>(val.get_uint64());
      ObSQLMode real_sql_mode = ob_compatibility_mode_to_sql_mode(comp_mode) |
          (sys_vars_cache.get_sql_mode() & ~ALL_SMO_COMPACT_MODE);
      sys_vars_cache.set_base_sql_mode(real_sql_mode);
      break;
    }
    case SYS_VAR_AUTO_INCREMENT_INCREMENT: {
      uint64_t uint_val = 0;
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache.set_base_auto_increment_increment(uint_val));
      break;
    }
    case SYS_VAR_SQL_THROTTLE_CURRENT_PRIORITY: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_sql_throttle_current_priority(int_val));
      break;
    }
    case SYS_VAR_OB_LAST_SCHEMA_VERSION: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_last_schema_version(int_val));
      break;
    }
    case SYS_VAR_SQL_SELECT_LIMIT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_sql_select_limit(int_val));
      break;
    }
    case SYS_VAR_AUTO_INCREMENT_OFFSET: {
      uint64_t uint_val = 0;
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache.set_base_auto_increment_offset(uint_val));
      break;
    }
    case SYS_VAR_LAST_INSERT_ID: {
      uint64_t uint_val = 0;
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache.set_base_last_insert_id(uint_val));
      break;
    }
    case SYS_VAR_BINLOG_ROW_IMAGE: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_binlog_row_image(int_val));
      break;
    }
    case SYS_VAR_FOREIGN_KEY_CHECKS: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_foreign_key_checks(int_val));
      break;
    }
    case SYS_VAR_DEFAULT_PASSWORD_LIFETIME: {
      uint64_t uint_val = 0;
      OZ (val.get_uint64(uint_val), val);
      OX (sys_vars_cache.set_base_default_password_lifetime(uint_val));
      break;
    }
    case SYS_VAR_TX_ISOLATION : {
      ObString str_val;
      ObTxIsolationLevel isolation = ObTxIsolationLevel::INVALID;
      OZ (val.get_string(str_val));
      OX (isolation = tx_isolation_from_str(str_val));
      OV (isolation != ObTxIsolationLevel::INVALID, OB_ERR_UNEXPECTED,
          str_val, isolation);
      OX (sys_vars_cache.set_base_tx_isolation(isolation));
      break;
    }
    case SYS_VAR_TX_READ_ONLY: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_tx_read_only(int_val != 0));
      break;
    }
    case SYS_VAR_OB_ENABLE_PLAN_CACHE: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_enable_plan_cache(int_val != 0));
      break;
    }
    case SYS_VAR_OPTIMIZER_USE_SQL_PLAN_BASELINES: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_optimizer_use_sql_plan_baselines(int_val != 0));
      break;
    }
    case SYS_VAR_OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_optimizer_capture_sql_plan_baselines(int_val != 0));
      break;
    }
    case SYS_VAR_IS_RESULT_ACCURATE: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_is_result_accurate(int_val != 0));
      break;
    }
    case SYS_VAR_OB_ENABLE_TRANSMISSION_CHECKSUM: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_enable_transmission_checksum(int_val != 0));
      break;
    }
    case SYS_VAR_CHARACTER_SET_RESULTS: {
      int64_t coll_int64 = 0;
      // 无效的character type,用户获取过程中,也需要保证返回NULL
      if (val.is_null()) {
        OX (sys_vars_cache.set_base_character_set_results(CHARSET_INVALID));
      } else if (OB_FAIL(val.get_int(coll_int64))) {
        LOG_WARN("fail to get int from value", K(val), K(ret));
      } else if (OB_UNLIKELY(false == ObCharset::is_valid_collation(coll_int64))) {
        // 这里不设置错误码
        LOG_WARN("invalid collation", K(coll_int64), K(val));
        OX (sys_vars_cache.set_base_character_set_results(CHARSET_INVALID));
      } else {
        OX (sys_vars_cache.set_base_character_set_results(
            ObCharset::charset_type_by_coll(static_cast<ObCollationType>(coll_int64))));
      }
      break;
    }
    case SYS_VAR_CHARACTER_SET_CONNECTION: {
      int64_t coll_int64 = 0;
      // 无效的character type,用户获取过程中,也需要保证返回NULL
      if (val.is_null()) {
        OX (sys_vars_cache.set_base_character_set_connection(CHARSET_INVALID));
      } else if (OB_FAIL(val.get_int(coll_int64))) {
        LOG_WARN("fail to get int from value", K(val), K(ret));
      } else if (OB_UNLIKELY(false == ObCharset::is_valid_collation(coll_int64))) {
        // 这里不设置错误码
        LOG_WARN("invalid collation", K(coll_int64), K(val));
        OX (sys_vars_cache.set_base_character_set_connection(CHARSET_INVALID));
      } else {
        OX (sys_vars_cache.set_base_character_set_connection(
            ObCharset::charset_type_by_coll(static_cast<ObCollationType>(coll_int64))));
      }
      break;
    }
    case SYS_VAR_OB_ENABLE_JIT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_enable_jit(static_cast<ObJITEnableMode>(int_val)));
      break;
    }
    case SYS_VAR_CURSOR_SHARING: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_cursor_sharing_mode(static_cast<ObCursorSharingMode>(int_val)));
      break;
    }
    case SYS_VAR_OB_ENABLE_SQL_AUDIT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_enable_sql_audit(int_val != 0));
      break;
    }
    case SYS_VAR_NLS_LENGTH_SEMANTICS: {
      ObString str_val;
      ObLengthSemantics nls_length_semantics = LS_BYTE;
      OZ (val.get_string(str_val));
      OX (nls_length_semantics = get_length_semantics(str_val));
      OV (nls_length_semantics != LS_INVALIED, OB_ERR_UNEXPECTED, nls_length_semantics);
      OX (sys_vars_cache.set_base_nls_length_semantics(nls_length_semantics));
      break;
    }
    case SYS_VAR_AUTOCOMMIT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_autocommit(int_val != 0));
      break;
    }
O
obdev 已提交
2722
    case SYS_VAR_OB_ENABLE_SHOW_TRACE: {
W
wangzelin.wzl 已提交
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 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 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 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
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_enable_trace_log(int_val != 0));
      break;
    }
    case SYS_VAR_OB_ORG_CLUSTER_ID: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_org_cluster_id(int_val));
      break;
    }
    case SYS_VAR_OB_QUERY_TIMEOUT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_query_timeout(int_val));
      break;
    }
    case SYS_VAR_OB_PL_BLOCK_TIMEOUT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_pl_block_timeout(int_val));
      break;
    }
    case SYS_VAR_PLSQL_CCFLAGS: {
      ObString plsql_ccflags;
      OZ (val.get_string(plsql_ccflags));
      OX (sys_vars_cache.set_base_plsql_ccflags(plsql_ccflags));
      break;
    }
    case SYS_VAR_OB_TRX_TIMEOUT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_trx_timeout(int_val));
      break;
    }
    case SYS_VAR_OB_TRX_IDLE_TIMEOUT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_trx_idle_timeout(int_val));
      break;
    }
    case SYS_VAR_OB_TRX_LOCK_TIMEOUT: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_ob_trx_lock_timeout(int_val));
      break;
    }
    case SYS_VAR_COLLATION_CONNECTION: {
      int64_t int_val = 0;
      OZ (val.get_int(int_val), val);
      OX (sys_vars_cache.set_base_collation_connection(int_val));
      break;
    }
    case SYS_VAR_TIMESTAMP: {
      //系统变脸timestamp默认值为0,是number类型, 设置单位是s。
      //当该系统变量设置为非0后, 则内部now()等时间函数会使用设置的值。
      //由于设置的单位是s, 内部是用us为单位的int64描述, 如果是用设置的
      //timestamp, 会先将设置的量转为us并四舍五入
      if (val.get_number().is_zero()) {
        sys_vars_cache.set_base_timestamp(0);
      } else {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected default timestamp value. must be zero", K(ret), K(val));
      }
      break;
    }
    case SYS_VAR_NLS_ISO_CURRENCY: {
      ObString country_str;
      ObString currency_str;
      if (OB_FAIL(val.get_string(country_str))) {
        LOG_WARN("fail to get iso_nls_currency str value", K(ret), K(var));
      } else if (OB_FAIL(IsoCurrencyUtils::get_currency_by_country_name(country_str,
                 currency_str))) {
        ret = OB_ERR_WRONG_VALUE_FOR_VAR;
        LOG_WARN("failed to get currency by country name", K(ret));
      } else {
        sys_vars_cache.set_base_iso_nls_currency(currency_str);
      }
      break;
    }
    case SYS_VAR_NLS_DATE_FORMAT:
    case SYS_VAR_NLS_TIMESTAMP_FORMAT:
    case SYS_VAR_NLS_TIMESTAMP_TZ_FORMAT: {
      ObString format;
      if (OB_FAIL(val.get_string(format))) {
        LOG_WARN("fail to get nls_date_format str value", K(ret), K(var));
      } else {
        int64_t nls_enum = ObNLSFormatEnum::NLS_DATE;
        ObDTMode mode = DT_TYPE_DATETIME;
        if (SYS_VAR_NLS_TIMESTAMP_FORMAT == var) {
          mode |= DT_TYPE_ORACLE;
          nls_enum = ObNLSFormatEnum::NLS_TIMESTAMP;
        } else if (SYS_VAR_NLS_TIMESTAMP_TZ_FORMAT == var) {
          mode |= DT_TYPE_ORACLE;
          mode |= DT_TYPE_TIMEZONE;
          nls_enum = ObNLSFormatEnum::NLS_TIMESTAMP_TZ;
        }
        ObSEArray<ObDFMElem, ObDFMUtil::COMMON_ELEMENT_NUMBER> dfm_elems;
        ObFixedBitSet<OB_DEFAULT_BITSET_SIZE_FOR_DFM> elem_flags;
        //1. parse and check semantic of format string
        if (OB_FAIL(ObDFMUtil::parse_datetime_format_string(format, dfm_elems,
                                                            false/* support double-quotes */))) {
          LOG_WARN("fail to parse oracle datetime format string", K(ret), K(format));
        } else if (OB_FAIL(ObDFMUtil::check_semantic(dfm_elems, elem_flags, mode))) {
          LOG_WARN("check semantic of format string failed", K(ret), K(format));
        } else {
          switch (nls_enum) {
          case ObNLSFormatEnum::NLS_DATE:
            sys_vars_cache.set_base_nls_date_format(format);
            break;
          case ObNLSFormatEnum::NLS_TIMESTAMP:
            sys_vars_cache.set_base_nls_timestamp_format(format);
            break;
          case ObNLSFormatEnum::NLS_TIMESTAMP_TZ:
            sys_vars_cache.set_base_nls_timestamp_tz_format(format);
            break;
          default:
            break;
          }
        }
        LOG_DEBUG("succ to set SYS_VAR_NLS_FORMAT", K(ret), K(var), K(nls_enum), K(format));
      }
      break;
    }
    case SYS_VAR_NLS_NCHAR_CHARACTERSET:
    case SYS_VAR_NLS_CHARACTERSET: {
      ObString str_val;
      ObCharsetType charset = CHARSET_INVALID;
      ObCollationType collation = CS_TYPE_INVALID;
      OZ (val.get_string(str_val), val);
      OX (charset = ObCharset::charset_type_by_name_oracle(str_val));
      OX (collation = ObCharset::get_default_collation_oracle(charset));
      OV (ObCharset::is_valid_charset(charset) && ObCharset::is_valid_collation(collation),
          OB_ERR_INVALID_CHARACTER_STRING, str_val, charset, collation);
      if (var == SYS_VAR_NLS_CHARACTERSET) {
        OX (sys_vars_cache.set_base_nls_collation(collation));
      } else {
        OX (sys_vars_cache.set_base_nls_nation_collation(collation));
      }
      break;
    }
    case SYS_VAR_OB_TRACE_INFO: {
      ObString trace_info;
      if (OB_FAIL(val.get_string(trace_info))) {
        LOG_WARN("fail to get str value", K(ret), K(var));
      } else {
        sys_vars_cache.set_base_ob_trace_info(trace_info);
      }
      break;
    }
    default: {
      //do nothing
    }
  }
  return ret;
}


int ObBasicSessionInfo::process_session_variable_fast()
{
  int ret = OB_SUCCESS;
  int64_t store_idx = -1;
  // SYS_VAR_OB_LOG_LEVEL
  OZ (ObSysVarFactory::calc_sys_var_store_idx(SYS_VAR_OB_LOG_LEVEL, store_idx));
  OV (ObSysVarFactory::is_valid_sys_var_store_idx(store_idx));
  OZ (process_session_log_level(sys_vars_[store_idx]->get_value()));
  // SYS_VAR_DEBUG_SYNC
  OZ (ObSysVarFactory::calc_sys_var_store_idx(SYS_VAR_DEBUG_SYNC, store_idx));
  OV (ObSysVarFactory::is_valid_sys_var_store_idx(store_idx));
2892
  OZ (process_session_debug_sync(sys_vars_[store_idx]->get_value(), false, false));
W
wangzelin.wzl 已提交
2893 2894 2895
  // SYS_VAR_OB_GLOBAL_DEBUG_SYNC
  OZ (ObSysVarFactory::calc_sys_var_store_idx(SYS_VAR_OB_GLOBAL_DEBUG_SYNC, store_idx));
  OV (ObSysVarFactory::is_valid_sys_var_store_idx(store_idx));
2896
  OZ (process_session_debug_sync(sys_vars_[store_idx]->get_value(), true, false));
W
wangzelin.wzl 已提交
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
  // SYS_VAR_OB_READ_CONSISTENCY
  // 这个系统变量对应consistency_level_,该属性只能通过常规途径修改,所以适合加入sys_vars_cache_,
  // 但这样涉及到的相关修改比较大,稳妥起见保留现有的序列化操作,只在本接口里执行,保证主线程正确初始化。
  OZ (ObSysVarFactory::calc_sys_var_store_idx(SYS_VAR_OB_READ_CONSISTENCY, store_idx));
  OV (ObSysVarFactory::is_valid_sys_var_store_idx(store_idx));
  if (OB_SUCC(ret)) {
    const ObObj &val = sys_vars_[store_idx]->get_value();
    int64_t consistency = 0;
    PROCESS_SESSION_INT_VARIABLE(consistency);
    OX (consistency_level_ = static_cast<ObConsistencyLevel>(consistency));
  }
  // SYS_VAR_WAIT_TIMEOUT
  {
    LockGuard lock_guard(thread_data_mutex_);
    get_int64_sys_var(SYS_VAR_WAIT_TIMEOUT, thread_data_.wait_timeout_);
  }

  // SYS_VAR_TIME_ZONE / SYS_VAR_ERROR_ON_OVERLAP_TIME
  // 这两个系统变量对应tz_info_wrap_,但该属性还有非系统变量方式的修改途径(update_timezone_info接口),
  // 所以tz_info_wrap_不适合加入sys_vars_cache_,但需要序列化。
  // 主线程申请session时,会在process_single_stmt接口中调用update_timezone_info接口,所以也能得到恰当的初始化。
  OZ (reset_timezone());
  return ret;
}

int ObBasicSessionInfo::process_session_sql_mode_value(const ObObj &value)
{
  int ret = OB_SUCCESS;
  ObSQLMode sql_mode = 0;
  if (value.is_string_type()) {
    const ObString &sql_mode_str = value.get_string();
    if (OB_FAIL(ob_str_to_sql_mode(sql_mode_str, sql_mode))) {
      LOG_WARN("failed to get sql mode", K(sql_mode_str), K(value), K(ret));
    }
  } else if (ObUInt64Type == value.get_type()) {
    sql_mode = value.get_uint64();
  } else if (ObIntType == value.get_type()) {
    sql_mode = static_cast<ObSQLMode>(value.get_int());
  } else {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid sql mode val type", K(value.get_type()), K(value), K(ret));
  }
  if (OB_FAIL(ret)) {
  } else if (!is_sql_mode_supported(sql_mode)) {
    ret = OB_NOT_SUPPORTED;
    LOG_USER_ERROR(OB_NOT_SUPPORTED, "Value for sql_mode");
    LOG_WARN("invalid sql mode val", K(value.get_type()), K(value), K(ret));
  } else {
    set_sql_mode(sql_mode);
  }
  return ret;
}

// 检查使用is_oracle_mode与compatibility_mode是否一致,如果不一致,则说明此处不能直接用is_oracle_mode替代
int ObBasicSessionInfo::check_compatibility_mode() const {
  int ret = OB_SUCCESS;
  ObCompatibilityMode mode = get_compatibility_mode();
  if (ORACLE_MODE == mode && is_oracle_mode()) {
  } else if (MYSQL_MODE == mode && is_mysql_mode()) {
  } else {
    // 有时mode还没有赋值,是OCEANBASE_MODE,所以这里暂时不强一致认为一定一样,但至少需要保证oracle一致
    if (ORACLE_MODE == mode && !is_oracle_mode()) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("compatibility mode is not match", K(mode), K(is_oracle_mode()), K(lbt()), K(ret));
    }
  }
  return ret;
}

int ObBasicSessionInfo::process_session_compatibility_mode_value(const ObObj &value)
{
  int ret = OB_SUCCESS;
  ObCompatibilityMode comp_mode = ObCompatibilityMode::OCEANBASE_MODE;
  if (value.is_string_type()) {
    const ObString &comp_mode_str = value.get_string();
    if (comp_mode_str.case_compare("ORACLE")) {
      comp_mode = ObCompatibilityMode::ORACLE_MODE;
    } else if (comp_mode_str.case_compare("MYSQL")) {
      comp_mode = ObCompatibilityMode::MYSQL_MODE;
    } else {
      ret = OB_NOT_SUPPORTED;
      LOG_USER_ERROR(OB_NOT_SUPPORTED, "compatibility mode");
      LOG_WARN("not supported sql mode", K(ret), K(value), K(comp_mode_str));
    }
  } else if (ObUInt64Type == value.get_type()) {
    comp_mode = static_cast<ObCompatibilityMode>(value.get_uint64());
  } else if (ObIntType == value.get_type()) {
    comp_mode = static_cast<ObCompatibilityMode>(value.get_int());
O
oceanbase-admin 已提交
2985 2986 2987 2988 2989 2990
  } else {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("invalid sql mode val type", K(value.get_type()), K(value), K(ret));
  }

  if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
2991
    set_compatibility_mode(comp_mode);
O
oceanbase-admin 已提交
2992 2993 2994 2995 2996
    LOG_DEBUG("set compatibility mode", K(ret), K(comp_mode), K(value), K(get_compatibility_mode()), K(lbt()));
  }
  return ret;
}

W
wangzelin.wzl 已提交
2997 2998
int ObBasicSessionInfo::process_session_time_zone_value(const ObObj &value,
                                                        const bool check_timezone_valid)
O
oceanbase-admin 已提交
2999 3000 3001 3002 3003 3004 3005
{
  int ret = OB_SUCCESS;
  ObString str_val;
  const bool is_oralce_mode = is_oracle_compatible();
  if (OB_FAIL(value.get_string(str_val))) {
    LOG_WARN("fail to get string value", K(value), K(ret));
  } else if (OB_FAIL(set_time_zone(str_val, is_oralce_mode, check_timezone_valid))) {
W
wangzelin.wzl 已提交
3006
    LOG_WARN("failed to set time zone", K(str_val), K(is_oralce_mode), "is_oracle_compatible", is_oracle_compatible(), K(ret));
O
oceanbase-admin 已提交
3007 3008 3009 3010
  }
  return ret;
}

W
wangzelin.wzl 已提交
3011
int ObBasicSessionInfo::process_session_overlap_time_value(const ObObj &value)
O
oceanbase-admin 已提交
3012 3013 3014 3015 3016 3017 3018 3019
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(tz_info_wrap_.set_error_on_overlap_time(value.get_bool()))) {
    LOG_WARN("fail to set error on overlap time", K(value), K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
3020
int ObBasicSessionInfo::process_session_log_level(const ObObj &val)
O
oceanbase-admin 已提交
3021 3022 3023 3024 3025 3026 3027 3028
{
  int ret = OB_SUCCESS;
  int32_t valid_length = 0;
  ObString val_str;
  if (OB_SUCC(val.get_varchar(val_str))) {
    if (0 == val_str.case_compare("disabled")) {
      log_id_level_map_valid_ = false;
      log_id_level_map_.reset_level();
W
wangzelin.wzl 已提交
3029 3030
    } else if (OB_FAIL(OB_LOGGER.parse_set(val_str.ptr(), val_str.length(), valid_length,
                                           log_id_level_map_))) {
O
oceanbase-admin 已提交
3031 3032 3033 3034 3035 3036 3037 3038
      LOG_WARN("Failed to parse set log_level", K(ret), "log_level", val_str);
    } else {
      log_id_level_map_valid_ = true;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3039
int ObBasicSessionInfo::process_session_debug_sync(const ObObj &val,
3040 3041
                                                   const bool is_global,
                                                   const bool is_update_sys_var)
O
oceanbase-admin 已提交
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054
{
  int ret = OB_SUCCESS;
  if (OB_SYS_TENANT_ID == tenant_id_ && GCONF.is_debug_sync_enabled()) {
    ObString debug_sync;
    if (OB_FAIL(val.get_varchar(debug_sync))) {
      LOG_WARN("varchar expected", K(ret));
    } else {
      if (!debug_sync.empty()) {
        if (OB_FAIL(GDS.add_debug_sync(debug_sync, is_global, debug_sync_actions_))) {
          LOG_WARN("set debug sync string failed", K(debug_sync), K(ret));
        }
      }
    }
3055 3056 3057 3058 3059 3060
  } else {
    if (is_update_sys_var) {
      ret = OB_NOT_SUPPORTED;
      LOG_USER_ERROR(OB_NOT_SUPPORTED,
                    "Non-system tenant or debug_sync is turned off, set debug_sync is");
    }
O
oceanbase-admin 已提交
3061 3062 3063 3064
  }
  return ret;
}

W
wangzelin.wzl 已提交
3065 3066
int ObBasicSessionInfo::get_int64_sys_var(const ObSysVarClassType sys_var_id,
                                          int64_t &int64_val) const
O
oceanbase-admin 已提交
3067 3068
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3069
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
  if (OB_FAIL(inner_get_sys_var(sys_var_id, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(sys_var_id));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(sys_var_id));
  } else {
    int64_t int_val = 0;
    if (OB_FAIL(val->get_value().get_int(int_val))) {
      LOG_WARN("fail to get int from value", K(*val), K(ret));
    } else {
      int64_val = int_val;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3086 3087
int ObBasicSessionInfo::get_uint64_sys_var(const ObSysVarClassType sys_var_id,
                                           uint64_t &uint64_val) const
O
oceanbase-admin 已提交
3088 3089
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3090
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
  if (OB_FAIL(inner_get_sys_var(sys_var_id, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(sys_var_id));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(sys_var_id));
  } else {
    uint64_t uint_val = 0;
    if (OB_FAIL(val->get_value().get_uint64(uint_val))) {
      LOG_ERROR("fail to get uint64 from value", K(*val), K(ret));
    } else {
      uint64_val = uint_val;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3107 3108
int ObBasicSessionInfo::get_bool_sys_var(const ObSysVarClassType sys_var_id,
                                         bool &bool_val) const
O
oceanbase-admin 已提交
3109 3110
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3111
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
  if (OB_FAIL(inner_get_sys_var(sys_var_id, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(sys_var_id));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(sys_var_id));
  } else {
    int64_t int_val = 0;
    if (OB_SUCCESS != (ret = val->get_value().get_int(int_val))) {
      LOG_ERROR("fail to get int from value", K(*val), K(ret));
    } else {
      bool_val = (0 != int_val);
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3128 3129
int ObBasicSessionInfo::get_charset_sys_var(const ObSysVarClassType sys_var_id,
                                            ObCharsetType &cs_type) const
O
oceanbase-admin 已提交
3130 3131
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3132
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
  if (OB_FAIL(inner_get_sys_var(sys_var_id, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(sys_var_id));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret), K(sys_var_id));
  } else {
    int64_t coll_int64 = 0;
    if (val->get_value().is_null()) {
      cs_type = CHARSET_INVALID;
    } else if (OB_FAIL(val->get_value().get_int(coll_int64))) {
      LOG_ERROR("fail to get int from value", K(*val), K(ret));
    } else if (OB_UNLIKELY(false == ObCharset::is_valid_collation(coll_int64))) {
      LOG_ERROR("invalid collation", K(sys_var_id), K(coll_int64), K(*val));
    } else {
      cs_type = ObCharset::charset_type_by_coll(static_cast<ObCollationType>(coll_int64));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3153 3154
int ObBasicSessionInfo::get_collation_sys_var(ObSysVarClassType sys_var_id,
                                              ObCollationType &coll_type) const
O
oceanbase-admin 已提交
3155 3156
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3157
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
  if (OB_FAIL(inner_get_sys_var(sys_var_id, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(sys_var_id));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get sys var, but sys var is NULL", K(ret));
  } else {
    int64_t coll_int64 = 0;
    if (OB_FAIL(val->get_value().get_int(coll_int64))) {
      LOG_ERROR("fail to get int from value", K(ret), K(*val));
    } else if (OB_UNLIKELY(false == ObCharset::is_valid_collation(coll_int64))) {
      LOG_ERROR("invalid collation", K(sys_var_id), K(coll_int64), K(*val));
    } else {
      coll_type = static_cast<ObCollationType>(coll_int64);
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3176 3177
int ObBasicSessionInfo::get_string_sys_var(ObSysVarClassType sys_var_id,
                                            ObString &str) const
O
oceanbase-admin 已提交
3178 3179
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3180
  ObBasicSysVar *val = NULL;
O
oceanbase-admin 已提交
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
  if (OB_FAIL(inner_get_sys_var(sys_var_id, val))) {
    LOG_WARN("fail to inner get sys var", K(ret), K(sys_var_id));
  } else if (OB_ISNULL(val)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("succ to inner get says var, but sys var is NULL", K(ret));
  } else {
    if (OB_FAIL(val->get_value().get_string(str))) {
      LOG_ERROR("fail to get int from value", K(ret), K(*val));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3194
int ObBasicSessionInfo::if_aggr_pushdown_allowed(bool &aggr_pushdown_allowed) const
O
oceanbase-admin 已提交
3195 3196 3197 3198
{
  return get_bool_sys_var(SYS_VAR_OB_ENABLE_AGGREGATION_PUSHDOWN, aggr_pushdown_allowed);
}

W
wangzelin.wzl 已提交
3199
int ObBasicSessionInfo::is_use_transmission_checksum(bool &use_transmission_checksum) const
O
oceanbase-admin 已提交
3200
{
W
wangzelin.wzl 已提交
3201
  use_transmission_checksum = sys_vars_cache_.get_ob_enable_transmission_checksum();
O
oceanbase-admin 已提交
3202 3203 3204
  return OB_SUCCESS;
}

W
wangzelin.wzl 已提交
3205
int ObBasicSessionInfo::get_name_case_mode(ObNameCaseMode &case_mode) const
O
oceanbase-admin 已提交
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
{
  int ret = OB_SUCCESS;
  int64_t int64_val = -1;
  if (OB_FAIL(get_sys_variable(SYS_VAR_LOWER_CASE_TABLE_NAMES, int64_val))) {
    LOG_WARN("failed to load sys param", "var_name", OB_SV_LOWER_CASE_TABLE_NAMES, K(ret));
  } else {
    int32_t value = static_cast<int32_t>(int64_val);
    if (value <= OB_NAME_CASE_INVALID || value >= OB_NAME_CASE_MAX) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("invalid value", "var_name", OB_SV_LOWER_CASE_TABLE_NAMES, K(value), K(ret));
    } else {
      case_mode = static_cast<ObNameCaseMode>(value);
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3223
int ObBasicSessionInfo::get_init_connect(ObString &str) const
O
oceanbase-admin 已提交
3224 3225 3226 3227
{
  return get_string_sys_var(SYS_VAR_INIT_CONNECT, str);
}

W
wangzelin.wzl 已提交
3228
int ObBasicSessionInfo::is_transformation_enabled(bool &transformation_enabled) const
O
oceanbase-admin 已提交
3229 3230 3231 3232
{
  return get_bool_sys_var(SYS_VAR_OB_ENABLE_TRANSFORMATION, transformation_enabled);
}

W
wangzelin.wzl 已提交
3233
int ObBasicSessionInfo::is_select_index_enabled(bool &select_index_enabled) const
O
oceanbase-admin 已提交
3234 3235 3236 3237 3238 3239
{
  return get_bool_sys_var(SYS_VAR_OB_ENABLE_INDEX_DIRECT_SELECT, select_index_enabled);
}

void ObBasicSessionInfo::set_autocommit(bool autocommit)
{
W
wangzelin.wzl 已提交
3240
  sys_vars_cache_.set_autocommit(autocommit);
O
oceanbase-admin 已提交
3241 3242
}

W
wangzelin.wzl 已提交
3243 3244
int ObBasicSessionInfo::get_explicit_defaults_for_timestamp(
    bool &explicit_defaults_for_timestamp) const
O
oceanbase-admin 已提交
3245
{
W
wangzelin.wzl 已提交
3246 3247
  return get_bool_sys_var(SYS_VAR_EXPLICIT_DEFAULTS_FOR_TIMESTAMP,
                          explicit_defaults_for_timestamp);
O
oceanbase-admin 已提交
3248 3249
}

W
wangzelin.wzl 已提交
3250
int ObBasicSessionInfo::get_sql_auto_is_null(bool &sql_auto_is_null) const
O
oceanbase-admin 已提交
3251 3252 3253 3254
{
  return get_bool_sys_var(SYS_VAR_SQL_AUTO_IS_NULL, sql_auto_is_null);
}

W
wangzelin.wzl 已提交
3255
int ObBasicSessionInfo::get_div_precision_increment(int64_t &div_precision_increment) const
O
oceanbase-admin 已提交
3256 3257 3258 3259 3260
{
  int ret = get_int64_sys_var(SYS_VAR_DIV_PRECISION_INCREMENT, div_precision_increment);
  return ret;
}

W
wangzelin.wzl 已提交
3261
int64_t ObBasicSessionInfo::get_query_timeout_ts() const
O
oceanbase-admin 已提交
3262
{
W
wangzelin.wzl 已提交
3263
  return sys_vars_cache_.get_ob_query_timeout() + get_query_start_time();
O
oceanbase-admin 已提交
3264 3265
}

W
wangzelin.wzl 已提交
3266
int ObBasicSessionInfo::get_pl_block_timeout(int64_t &pl_block_timeout) const
O
oceanbase-admin 已提交
3267 3268 3269 3270 3271
{
  pl_block_timeout = sys_vars_cache_.get_ob_pl_block_timeout();
  return OB_SUCCESS;
}

W
wangzelin.wzl 已提交
3272
int ObBasicSessionInfo::get_ob_read_consistency(int64_t &ob_read_consistency) const
O
oceanbase-admin 已提交
3273 3274 3275 3276
{
  return get_int64_sys_var(SYS_VAR_OB_READ_CONSISTENCY, ob_read_consistency);
}

W
wangzelin.wzl 已提交
3277
int ObBasicSessionInfo::get_group_concat_max_len(uint64_t &group_concat_max_len) const
O
oceanbase-admin 已提交
3278 3279 3280 3281
{
  return get_uint64_sys_var(SYS_VAR_GROUP_CONCAT_MAX_LEN, group_concat_max_len);
}

W
wangzelin.wzl 已提交
3282
int ObBasicSessionInfo::get_ob_interm_result_mem_limit(int64_t &ob_interm_result_mem_limit) const
O
oceanbase-admin 已提交
3283 3284 3285 3286
{
  return get_int64_sys_var(SYS_VAR_OB_INTERM_RESULT_MEM_LIMIT, ob_interm_result_mem_limit);
}

W
wangzelin.wzl 已提交
3287 3288 3289
// 参数max_allowed_pkt和net_buffer_len的命名之所以不为max_allowed_packet和net_buffer_length,
// 是为了规避lib/regex/include/mysql.h中的命名重复,使得编译能通过
int ObBasicSessionInfo::get_max_allowed_packet(int64_t &max_allowed_pkt) const
O
oceanbase-admin 已提交
3290 3291 3292 3293
{
  return get_int64_sys_var(SYS_VAR_MAX_ALLOWED_PACKET, max_allowed_pkt);
}

W
wangzelin.wzl 已提交
3294
int ObBasicSessionInfo::get_net_buffer_length(int64_t &net_buffer_len) const
O
oceanbase-admin 已提交
3295 3296 3297 3298 3299
{
  return get_int64_sys_var(SYS_VAR_NET_BUFFER_LENGTH, net_buffer_len);
}

////////////////////////////////////////////////////////////////
W
wangzelin.wzl 已提交
3300
int ObBasicSessionInfo::replace_user_variables(const ObSessionValMap &user_var_map)
O
oceanbase-admin 已提交
3301 3302 3303
{
  int ret = OB_SUCCESS;
  if (user_var_map.size() > 0) {
W
wangzelin.wzl 已提交
3304
    const sql::ObSessionValMap::VarNameValMap &new_map = user_var_map.get_val_map();
O
oceanbase-admin 已提交
3305
    for (sql::ObSessionValMap::VarNameValMap::const_iterator iter = new_map.begin();
W
wangzelin.wzl 已提交
3306 3307 3308
         OB_SUCC(ret) && iter != new_map.end(); iter++) {
      const common::ObString &key = iter->first;
      const sql::ObSessionVariable &value = iter->second;
O
oceanbase-admin 已提交
3309 3310 3311 3312 3313 3314 3315 3316
      if (OB_FAIL(replace_user_variable(key, value))) {
        LOG_WARN("fail to replace user var", K(ret), K(key), K(value));
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3317
int ObBasicSessionInfo::replace_user_variable(const ObString &var, const ObSessionVariable &val)
O
oceanbase-admin 已提交
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
{
  int ret = OB_SUCCESS;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid var name", K(var), K(ret));
  } else if (OB_FAIL(user_var_val_map_.set_refactored(var, val))) {
    LOG_ERROR("fail to add variable", K(var), K(ret));
  } else {
    if (is_track_session_info()) {
      if (OB_FAIL(track_user_var(var))) {
        LOG_WARN("fail to track user var", K(var), K(ret));
      }
    }
    if (OB_SUCC(ret)) {
      variables_last_modify_time_ = ObTimeUtility::current_time();
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
3338
int ObBasicSessionInfo::remove_user_variable(const ObString &var)
O
oceanbase-admin 已提交
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
{
  int ret = OB_SUCCESS;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else if (OB_SUCCESS != user_var_val_map_.erase_refactored(var)) {
    ret = OB_ERR_USER_VARIABLE_UNKNOWN;
    LOG_WARN("unknown variable", K(var), K(ret));
  } else {
    variables_last_modify_time_ = ObTimeUtility::current_time();
  }
  return ret;
}

W
wangzelin.wzl 已提交
3353
int ObBasicSessionInfo::get_user_variable(const ObString &var, ObSessionVariable &val) const
O
oceanbase-admin 已提交
3354 3355 3356
{
  int ret = OB_SUCCESS;
  if (var.empty()) {
W
wangzelin.wzl 已提交
3357 3358 3359 3360 3361
   /* bugfix:https://work.aone.alibaba-inc.com/issue/37171897
    * select @; return NULL;
    * select @""; select @''; select @``; return NULL;
    */
   if (lib::is_oracle_mode()) {
O
oceanbase-admin 已提交
3362 3363
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
W
wangzelin.wzl 已提交
3364
   }
O
oceanbase-admin 已提交
3365 3366 3367 3368 3369 3370 3371 3372
  } else if (OB_SUCCESS != user_var_val_map_.get_refactored(var, val)) {
    ret = OB_ERR_USER_VARIABLE_UNKNOWN;
    LOG_WARN("unknown user variable", K(var), K(ret));
  } else {
  }
  return ret;
}

W
wangzelin.wzl 已提交
3373
int ObBasicSessionInfo::get_user_variable_value(const ObString &var, common::ObObj &val) const
O
oceanbase-admin 已提交
3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
{
  int ret = OB_SUCCESS;
  ObSessionVariable sess_var;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else if (OB_SUCCESS != user_var_val_map_.get_refactored(var, sess_var)) {
    ret = OB_ERR_USER_VARIABLE_UNKNOWN;
    LOG_WARN("unknown user variable", K(var), K(ret));
  } else {
    val = sess_var.value_;
  }
  return ret;
}

W
wangzelin.wzl 已提交
3389
int ObBasicSessionInfo::get_user_variable_meta(const ObString &var, ObObjMeta &meta) const
O
oceanbase-admin 已提交
3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404
{
  int ret = OB_SUCCESS;
  ObSessionVariable val;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else if (OB_SUCCESS != user_var_val_map_.get_refactored(var, val)) {
    ret = OB_ERR_USER_VARIABLE_UNKNOWN;
    LOG_WARN("unknown user variable", K(var), K(ret));
  } else {
    meta = val.meta_;
  }
  return ret;
}

W
wangzelin.wzl 已提交
3405
bool ObBasicSessionInfo::user_variable_exists(const ObString &var) const
O
oceanbase-admin 已提交
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
{
  ObSessionVariable val;
  bool exist = false;
  int ret = OB_SUCCESS;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else {
    exist = (OB_SUCCESS == user_var_val_map_.get_refactored(var, val));
  }
  return exist;
}

W
wangzelin.wzl 已提交
3419
const ObSessionVariable *ObBasicSessionInfo::get_user_variable(const common::ObString &var) const
O
oceanbase-admin 已提交
3420
{
W
wangzelin.wzl 已提交
3421
  const ObSessionVariable *sess_var = NULL;
O
oceanbase-admin 已提交
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
  int ret = OB_SUCCESS;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else {
    sess_var = user_var_val_map_.get(var);
  }
  return sess_var;
}

W
wangzelin.wzl 已提交
3432
const common::ObObj *ObBasicSessionInfo::get_user_variable_value(const ObString &var) const
O
oceanbase-admin 已提交
3433
{
W
wangzelin.wzl 已提交
3434 3435
  const ObObj *val_obj = NULL;
  const ObSessionVariable *sess_var = NULL;
O
oceanbase-admin 已提交
3436 3437 3438 3439 3440 3441
  int ret = OB_SUCCESS;
  if (var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid variable name", K(var), K(ret));
  } else if (NULL != (sess_var = user_var_val_map_.get(var))) {
    val_obj = &(sess_var->value_);
W
wangzelin.wzl 已提交
3442
  } else {}//just return NULL
O
oceanbase-admin 已提交
3443 3444 3445
  return val_obj;
}

W
wangzelin.wzl 已提交
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
int ObBasicSessionInfo::get_session_label(uint64_t policy_id, ObLabelSeSessionLabel &session_label) const
{
  int ret = OB_ENTRY_NOT_EXIST;
  for (int64_t i = 0; ret != OB_SUCCESS && i < labels_.count(); ++i) {
    if (labels_[i].get_policy_id() == policy_id) {
      ret = OB_SUCCESS;
      session_label = labels_[i];
    }
  }
  return ret;
}

int ObBasicSessionInfo::replace_new_session_label(uint64_t policy_id, const ObLabelSeSessionLabel &new_session_label)
{
  int ret = OB_SUCCESS;
  ObArenaAllocator allocator;
  ObString serialized_data;
  bool found = false;
  for (int64_t i = 0; !found && i < labels_.count(); ++i) {
    if (labels_[i].get_policy_id() == policy_id) {
      found = true;
      labels_.at(i) = new_session_label;
    }
  }
  if (OB_SUCC(ret) && !found) {
    OZ (labels_.push_back(new_session_label));
  }
  OZ (ObLabelSeResolver::serialize_session_labels(labels_, allocator, serialized_data));
  OZ (update_sys_variable(SYS_VAR__OB_OLS_POLICY_SESSION_LABELS, serialized_data));
  return ret;
}

O
oceanbase-admin 已提交
3478
////////////////////////////////////////////////////////////////
W
wangzelin.wzl 已提交
3479
int64_t ObBasicSessionInfo::to_string(char *buf, const int64_t buf_len) const
O
oceanbase-admin 已提交
3480 3481
{
  int64_t pos = 0;
W
wangzelin.wzl 已提交
3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
  J_OBJ_START();
  J_KV(KP(this), "id", sessid_,
       N_TENANT, get_tenant_name(), "tenant_id", tenant_id_,
       N_EFFECTIVE_TENANT, get_effective_tenant_name(), "effective_tenant_id", effective_tenant_id_,
       N_DATABASE, get_database_name(),
       N_USER, (lib::is_oracle_mode() ? get_user_name() : get_user_at_host()),
       "consistency_level", consistency_level_,
       "session_state", thread_data_.state_,
       "tx", OB_P(tx_desc_));
  J_OBJ_END();
O
oceanbase-admin 已提交
3492 3493 3494
  return pos;
}

W
wangzelin.wzl 已提交
3495 3496
int ObBasicSessionInfo::calc_need_serialize_vars(ObIArray<ObSysVarClassType> &sys_var_ids,
                                                 ObIArray<ObString> &user_var_names) const
O
oceanbase-admin 已提交
3497 3498 3499 3500
{
  int ret = OB_SUCCESS;
  sys_var_ids.reset();
  user_var_names.reset();
W
wangzelin.wzl 已提交
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513
  // 默认需要序列化的系统变量
  // 普通租户,序列化和 hardcode 不一致的变量
  const ObIArray<ObSysVarClassType> &ids = sys_var_inc_info_.get_all_sys_var_ids();
  for (int64_t i = 0; OB_SUCC(ret) && i < ids.count(); ++i) {
    int64_t sys_var_idx = -1;
    if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(ids.at(i), sys_var_idx))) {
      LOG_WARN("fail to calc sys var store idx", K(i), K(sys_var_idx), K(ids.at(i)), K(ret));
    } else if ((ObSysVariables::get_flags(sys_var_idx) &
                (ObSysVarFlag::SESSION_SCOPE | // "delta compare algorithm"
                 ObSysVarFlag::NEED_SERIALIZE |
                 ObSysVarFlag::QUERY_SENSITIVE))) {
      if (OB_FAIL(sys_var_ids.push_back(ids.at(i)))) {
        LOG_WARN("fail to push back sys var id", K(i), K(ids.at(i)), K(sys_var_ids), K(ret));
O
oceanbase-admin 已提交
3514 3515 3516 3517
      }
    }
  }

W
wangzelin.wzl 已提交
3518 3519 3520
  if (OB_SUCC(ret) && cur_phy_plan_ != nullptr) {
    // 处理该语句用到的需要序列化的用户变量和系统变量
    const ObIArray<ObVarInfo> &extra_serialize_vars = cur_phy_plan_->get_vars();
O
oceanbase-admin 已提交
3521
    for (int64_t i = 0; OB_SUCC(ret) && i < extra_serialize_vars.count(); ++i) {
W
wangzelin.wzl 已提交
3522
      const ObVarInfo &var_info = extra_serialize_vars.at(i);
O
oceanbase-admin 已提交
3523
      if (USER_VAR == var_info.type_) {
W
wangzelin.wzl 已提交
3524
        // 用户变量
O
oceanbase-admin 已提交
3525 3526 3527 3528
        if (OB_FAIL(user_var_names.push_back(var_info.name_))) {
          LOG_WARN("fail to push user var name", K(var_info), K(user_var_names), K(ret));
        }
      } else if (SYS_VAR == var_info.type_) {
W
wangzelin.wzl 已提交
3529
        // 系统变量
O
oceanbase-admin 已提交
3530 3531 3532 3533 3534
        ObSysVarClassType sys_var_id = ObSysVarFactory::find_sys_var_id_by_name(var_info.name_);
        if (SYS_VAR_INVALID == sys_var_id) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("invalid sys var id", K(sys_var_id), K(var_info), K(ret));
        } else {
W
wangzelin.wzl 已提交
3535
          // 去重
O
oceanbase-admin 已提交
3536 3537 3538 3539 3540 3541 3542 3543
          bool sys_var_exist = false;
          for (int64_t j = 0; OB_SUCC(ret) && !sys_var_exist && j < sys_var_ids.count(); ++j) {
            if (sys_var_id == sys_var_ids.at(j)) {
              sys_var_exist = true;
            }
          }
          if (OB_SUCCESS == ret && !sys_var_exist) {
            if (OB_FAIL(sys_var_ids.push_back(sys_var_id))) {
W
wangzelin.wzl 已提交
3544 3545
              LOG_WARN("fail to push back sys var id", K(sys_var_id), K(var_info), K(sys_var_ids),
                       K(ret));
O
oceanbase-admin 已提交
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
            }
          }
        }
      } else {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("invalid var info type", K(var_info.type_), K(var_info), K(ret));
      }
    }
  }
  return ret;
}

OB_SERIALIZE_MEMBER(ObBasicSessionInfo::TableStmtType, table_id_, stmt_type_);

OB_DEF_SERIALIZE(ObBasicSessionInfo::SysVarsCacheData)
{
  int ret = OB_SUCCESS;
  LST_DO_CODE(OB_UNIS_ENCODE,
W
wangzelin.wzl 已提交
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
              autocommit_,
              ob_enable_trace_log_,
              ob_org_cluster_id_,
              ob_query_timeout_,
              ob_trx_timeout_,
              collation_connection_,
              sql_mode_,
              ob_trx_idle_timeout_,
              nls_collation_,
              nls_nation_collation_,
              ob_enable_sql_audit_,
              nls_length_semantics_,
              nls_formats_[NLS_DATE],
              nls_formats_[NLS_TIMESTAMP],
              nls_formats_[NLS_TIMESTAMP_TZ],
              ob_trx_lock_timeout_,
              ob_trace_info_,
              ob_plsql_ccflags_);
O
oceanbase-admin 已提交
3582 3583 3584 3585 3586 3587 3588
  return ret;
}

OB_DEF_DESERIALIZE(ObBasicSessionInfo::SysVarsCacheData)
{
  int ret = OB_SUCCESS;
  LST_DO_CODE(OB_UNIS_DECODE,
W
wangzelin.wzl 已提交
3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
              autocommit_,
              ob_enable_trace_log_,
              ob_org_cluster_id_,
              ob_query_timeout_,
              ob_trx_timeout_,
              collation_connection_,
              sql_mode_,
              ob_trx_idle_timeout_,
              nls_collation_,
              nls_nation_collation_,
              ob_enable_sql_audit_,
              nls_length_semantics_,
              nls_formats_[NLS_DATE],
              nls_formats_[NLS_TIMESTAMP],
              nls_formats_[NLS_TIMESTAMP_TZ],
              ob_trx_lock_timeout_,
              ob_trace_info_,
              ob_plsql_ccflags_);
O
oceanbase-admin 已提交
3607 3608 3609 3610
  set_nls_date_format(nls_formats_[NLS_DATE]);
  set_nls_timestamp_format(nls_formats_[NLS_TIMESTAMP]);
  set_nls_timestamp_tz_format(nls_formats_[NLS_TIMESTAMP_TZ]);
  set_ob_trace_info(ob_trace_info_);
W
wangzelin.wzl 已提交
3611
  set_plsql_ccflags(ob_plsql_ccflags_);
O
oceanbase-admin 已提交
3612 3613 3614 3615 3616 3617 3618
  return ret;
}

OB_DEF_SERIALIZE_SIZE(ObBasicSessionInfo::SysVarsCacheData)
{
  int64_t len = 0;
  LST_DO_CODE(OB_UNIS_ADD_LEN,
W
wangzelin.wzl 已提交
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
              autocommit_,
              ob_enable_trace_log_,
              ob_org_cluster_id_,
              ob_query_timeout_,
              ob_trx_timeout_,
              collation_connection_,
              sql_mode_,
              ob_trx_idle_timeout_,
              nls_collation_,
              nls_nation_collation_,
              ob_enable_sql_audit_,
              nls_length_semantics_,
              nls_formats_[NLS_DATE],
              nls_formats_[NLS_TIMESTAMP],
              nls_formats_[NLS_TIMESTAMP_TZ],
              ob_trx_lock_timeout_,
              ob_trace_info_,
              ob_plsql_ccflags_);
O
oceanbase-admin 已提交
3637 3638 3639 3640 3641 3642
  return len;
}

OB_DEF_SERIALIZE(ObBasicSessionInfo)
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3643
  ObTimeZoneInfo tmp_tz_info;//为了兼容老版本,创建临时time zone info 占位
O
oceanbase-admin 已提交
3644 3645 3646 3647 3648
  // To be compatible with old version which store sql_mode and compatibility mode in ObSQLModeManager;
  int64_t compatibility_mode_index = 0;
  if (OB_FAIL(compatibility_mode2index(get_compatibility_mode(), compatibility_mode_index))) {
    LOG_WARN("convert compatibility mode to index failed", K(ret));
  }
W
wangzelin.wzl 已提交
3649 3650 3651 3652 3653 3654
  bool has_tx_desc = tx_desc_ != NULL;
  OB_UNIS_ENCODE(has_tx_desc);
  if (has_tx_desc) {
    OB_UNIS_ENCODE(*tx_desc_);
    LOG_TRACE("serialize txDesc", KPC_(tx_desc));
  }
O
oceanbase-admin 已提交
3655
  LST_DO_CODE(OB_UNIS_ENCODE,
W
wangzelin.wzl 已提交
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
              consistency_level_,
              compatibility_mode_index,
              tmp_tz_info,
              // NOTE: rpc_tenant_id may cause compatability problem,
              // But only in diagnose tenant, so keep the stupid hack as it is.
              tenant_id_ | (rpc_tenant_id_ << 32),
              effective_tenant_id_,
              is_changed_to_temp_tenant_,
              user_id_,
              is_master_session() ? sessid_ : master_sessid_,
              capability_.capability_,
              thread_data_.database_name_);
  // 序列化需要序列化的用户变量和系统变量
  ObSEArray<ObSysVarClassType, 64> sys_var_ids;
O
oceanbase-admin 已提交
3670 3671
  ObSEArray<ObString, 32> user_var_names;
  if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
3672
  } else if (OB_FAIL(calc_need_serialize_vars(sys_var_ids, user_var_names))) {
O
oceanbase-admin 已提交
3673 3674 3675 3676 3677 3678
    LOG_WARN("fail to calc need serialize vars", K(ret));
  } else {
    ObSEArray<std::pair<ObString, ObSessionVariable>, 32> actual_ser_user_vars;
    ObSessionVariable user_var_val;
    for (int64_t i = 0; OB_SUCC(ret) && i < user_var_names.count(); ++i) {
      user_var_val.reset();
W
wangzelin.wzl 已提交
3679
      const ObString &user_var_name = user_var_names.at(i);
O
oceanbase-admin 已提交
3680 3681
      ret = user_var_val_map_.get_refactored(user_var_name, user_var_val);
      if (OB_SUCCESS != ret && OB_HASH_NOT_EXIST != ret) {
W
wangzelin.wzl 已提交
3682 3683
        LOG_WARN("fail to get user var from session user var map", K(i), K(user_var_name),
                 K(user_var_val_map_.size()), K(ret));
O
oceanbase-admin 已提交
3684
      } else {
W
wangzelin.wzl 已提交
3685 3686 3687 3688
        if (OB_SUCCESS == ret
            && OB_FAIL(actual_ser_user_vars.push_back(std::make_pair(user_var_name, user_var_val)))) {
          LOG_WARN("fail to push back pair(user_var_name, user_var_val)", K(buf_len),
                   K(pos), K(user_var_name), K(user_var_val), K(ret));
O
oceanbase-admin 已提交
3689 3690 3691 3692 3693 3694 3695 3696
        } else {
          ret = OB_SUCCESS;
        }
      }
    }

    if (OB_SUCC(ret)) {
      if (OB_FAIL(serialization::encode(buf, buf_len, pos, actual_ser_user_vars.count()))) {
W
wangzelin.wzl 已提交
3697 3698
        LOG_WARN("fail to serialize user var count", K(ret), K(buf_len), K(pos),
                 K(actual_ser_user_vars.count()));
O
oceanbase-admin 已提交
3699 3700
      } else {
        for (int64_t i = 0; OB_SUCC(ret) && i < actual_ser_user_vars.count(); ++i) {
W
wangzelin.wzl 已提交
3701 3702
          const ObString &user_var_name = actual_ser_user_vars.at(i).first;
          const ObSessionVariable &user_var_val = actual_ser_user_vars.at(i).second;
O
oceanbase-admin 已提交
3703
          if (OB_FAIL(serialization::encode(buf, buf_len, pos, user_var_name))) {
W
wangzelin.wzl 已提交
3704 3705
            LOG_WARN("fail to serialize user var name", K(buf_len), K(pos), K(user_var_name),
                     K(ret));
O
oceanbase-admin 已提交
3706
          } else if (OB_FAIL(serialization::encode(buf, buf_len, pos, user_var_val.meta_))) {
W
wangzelin.wzl 已提交
3707 3708
            LOG_WARN("fail to serialize user var val meta", K(buf_len), K(pos),
                     K(user_var_val.meta_), K(ret));
O
oceanbase-admin 已提交
3709
          } else if (OB_FAIL(serialization::encode(buf, buf_len, pos, user_var_val.value_))) {
W
wangzelin.wzl 已提交
3710 3711 3712
            LOG_WARN("fail to serialize user var val value", K(buf_len), K(pos),
                     K(user_var_val.value_), K(ret));
          } else {}
O
oceanbase-admin 已提交
3713 3714 3715 3716 3717
        }
      }
    }
  }

W
wangzelin.wzl 已提交
3718 3719
  // split function, make stack checker happy
  [&](){
O
oceanbase-admin 已提交
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738
  if (OB_SUCC(ret)) {
    if (OB_FAIL(serialization::encode(buf, buf_len, pos, sys_var_ids.count()))) {
      LOG_WARN("fail to serialize sys var count", K(buf_len), K(pos), K(sys_var_ids.count()), K(ret));
    }
    for (int64_t i = 0; OB_SUCC(ret) && i < sys_var_ids.count(); ++i) {
      int64_t sys_var_idx = -1;
      if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(sys_var_ids.at(i), sys_var_idx))) {
        LOG_WARN("fail to calc sys var store idx", K(i), K(sys_var_idx), K(sys_var_ids.at(i)), K(ret));
      } else if (sys_var_idx < 0 || get_sys_var_count() <= sys_var_idx) {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("sys var idx is invalid", K(sys_var_idx), K(get_sys_var_count()), K(ret));
      } else if (OB_ISNULL(sys_vars_[sys_var_idx])) {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("sys var is NULL", K(ret), K(sys_var_idx), K(get_sys_var_count()));
      } else {
        int16_t sys_var_id = static_cast<int16_t>(sys_vars_[sys_var_idx]->get_type());
        if (OB_FAIL(serialization::encode(buf, buf_len, pos, sys_var_id))) {
          LOG_ERROR("fail to serialize sys var id", K(buf_len), K(pos), K(sys_var_id), K(ret));
        } else if (OB_FAIL(sys_vars_[sys_var_idx]->serialize(buf, buf_len, pos))) {
W
wangzelin.wzl 已提交
3739 3740 3741 3742 3743 3744 3745
          LOG_ERROR("fail to serialize sys var", K(buf_len), K(pos), K(i), K(sys_var_idx),
                    K(*sys_vars_[sys_var_idx]), K(ret));
        } else {
          LOG_DEBUG("serialize sys vars", K(sys_var_idx),
                    "name", ObSysVariables::get_name(sys_var_idx),
                    "val", sys_vars_[sys_var_idx]->get_value(),
                    "def", ObSysVariables::get_default_value(sys_var_idx));
O
oceanbase-admin 已提交
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
        }
      }
    }
  }

  if (OB_FAIL(ret)) {
    LOG_WARN("fail to encode session info", K(ret));
  } else {
    bool tx_read_only = get_tx_read_only();
    if (OB_FAIL(serialization::encode_bool(buf, buf_len, pos, tx_read_only))) {
      LOG_WARN("fail to encode tx_read_only", K(ret));
    }
  }

W
wangzelin.wzl 已提交
3760
  // 不再有意义字段,为了兼容性考虑
O
oceanbase-admin 已提交
3761
  bool unused_literal_query = false;
W
wangzelin.wzl 已提交
3762 3763 3764
  int64_t unused_inner_safe_weak_read_snapshot = 0;
  int64_t unused_weak_read_snapshot_source = 0;
  int64_t unused_safe_weak_read_snapshot = 0;
O
oceanbase-admin 已提交
3765 3766

  bool need_serial_exec = trans_flags_.need_serial_exec();
W
wangzelin.wzl 已提交
3767
  uint64_t sql_scope_flags = sql_scope_flags_.get_flags();
O
oceanbase-admin 已提交
3768
  LST_DO_CODE(OB_UNIS_ENCODE,
W
wangzelin.wzl 已提交
3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
              sys_vars_cache_.inc_data_,
              unused_safe_weak_read_snapshot,
              unused_inner_safe_weak_read_snapshot,
              unused_literal_query,
              tz_info_wrap_,
              app_trace_id_,
              proxy_capability_.capability_,
              client_mode_,
              proxy_sessid_,
              nested_count_,
              thread_data_.user_name_,
              next_tx_isolation_,
              read_snapshot_version_,
              check_sys_variable_,
              unused_weak_read_snapshot_source,
              database_id_,
              thread_data_.user_at_host_name_,
              thread_data_.user_at_client_ip_,
              current_execution_id_,
              labels_,
              total_stmt_tables_,
              cur_stmt_tables_,
              is_foreign_key_cascade_,
              sys_var_in_pc_str_,
              config_in_pc_str_,
              is_foreign_key_check_exist_,
              need_serial_exec,
              sql_scope_flags,
              stmt_type_,
              thread_data_.client_addr_,
              thread_data_.user_client_addr_,
              process_query_time_);
  }();
O
oceanbase-admin 已提交
3802 3803 3804 3805 3806 3807
  return ret;
}

OB_DEF_DESERIALIZE(ObBasicSessionInfo)
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
3808
  ObTimeZoneInfo tmp_tz_info;//为了兼容老版本,创建临时time zone info 占位
O
oceanbase-admin 已提交
3809 3810
  int64_t compatibility_mode_index = 0;
  is_deserialized_ = true;
W
wangzelin.wzl 已提交
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823
  bool has_tx_desc = 0;
  if (OB_FAIL(serialization::decode(buf, data_len, pos, has_tx_desc))) {
    LOG_WARN("fail to deserialize has_tx_desc_", K(data_len), K(pos), K(ret));
  } else if (has_tx_desc) {
    auto txs = MTL(transaction::ObTransService*);
    if (OB_FAIL(txs->acquire_tx(buf, data_len, pos, tx_desc_))) {
      LOG_WARN("acquire tx by deserialize fail", K(data_len), K(pos), K(ret));
    } else {
      LOG_TRACE("deserialize txDesc from session", KPC_(tx_desc));
    }
  } else {
    tx_desc_ = NULL;
  }
O
oceanbase-admin 已提交
3824
  LST_DO_CODE(OB_UNIS_DECODE,
W
wangzelin.wzl 已提交
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834
              consistency_level_,
              compatibility_mode_index,
              tmp_tz_info,
              tenant_id_,
              effective_tenant_id_,
              is_changed_to_temp_tenant_,
              user_id_,
              master_sessid_,
              capability_.capability_,
              thread_data_.database_name_);
O
oceanbase-admin 已提交
3835 3836
  rpc_tenant_id_ = (tenant_id_ >> 32);
  tenant_id_ = (tenant_id_ << 32 >> 32);
W
wangzelin.wzl 已提交
3837
  // 反序列化需要序列化的用户变量和系统变量
O
oceanbase-admin 已提交
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
  int64_t deserialize_user_var_count = 0;
  int64_t deserialize_sys_var_count = 0;

  if (OB_FAIL(ret)) {
  } else if (OB_FAIL(serialization::decode(buf, data_len, pos, deserialize_user_var_count))) {
    LOG_WARN("fail to deserialize user var count", K(data_len), K(pos), K(ret));
  } else {
    ObSessionVariable user_var_val;
    for (int64_t i = 0; OB_SUCC(ret) && i < deserialize_user_var_count; ++i) {
      ObString user_var_name;
      user_var_val.reset();
      if (OB_FAIL(serialization::decode(buf, data_len, pos, user_var_name))) {
        LOG_WARN("fail to deserialize user var name", K(i), K(data_len), K(pos), K(ret));
3851 3852
      } else if (OB_FAIL(name_pool_.write_string(user_var_name, &user_var_name))) {
        LOG_WARN("fail to write user_var_name to string_buf_", K(user_var_name), K(ret));
O
oceanbase-admin 已提交
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
      } else if (OB_FAIL(serialization::decode(buf, data_len, pos, user_var_val.meta_))) {
        LOG_WARN("fail to deserialize user var val meta", K(i), K(data_len), K(pos), K(ret));
      } else if (OB_FAIL(serialization::decode(buf, data_len, pos, user_var_val.value_))) {
        LOG_WARN("fail to deserialize user var val value", K(i), K(data_len), K(pos), K(ret));
      } else {
        if (OB_FAIL(user_var_val_map_.set_refactored(user_var_name, user_var_val))) {
          LOG_WARN("Insert value into map failed", K(user_var_name), K(user_var_val), K(ret));
        } else {
          ret = OB_SUCCESS;
        }
      }
    }
  }

W
wangzelin.wzl 已提交
3867 3868 3869 3870 3871 3872 3873 3874
  sys_var_inc_info_.reset();
  // 当 sys_var_base_version_ == CACHED_SYS_VAR_VERSION 时说明有缓存,不需要 load 默认值
  // 否则说明没有缓存,需要 load 默认值,然后打补丁
  if (CACHED_SYS_VAR_VERSION != sys_var_base_version_) {
    OZ (load_all_sys_vars_default());
  } else {
    // cached already, skip load default vars
    OZ (process_session_variable_fast());
O
oceanbase-admin 已提交
3875
  }
W
wangzelin.wzl 已提交
3876

O
oceanbase-admin 已提交
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888
  if (OB_SUCC(ret)) {
    ObTZMapWrap tz_map_wrap;
    if (OB_FAIL(OTTZ_MGR.get_tenant_tz(tenant_id_, tz_map_wrap))) {
      LOG_WARN("get tenant timezone map failed", K(ret));
    } else {
      tz_info_wrap_.set_tz_info_map(tz_map_wrap.get_tz_map());
    }
  }
  if (OB_SUCC(ret)) {
    if (OB_FAIL(serialization::decode(buf, data_len, pos, deserialize_sys_var_count))) {
      LOG_WARN("fail to deserialize sys var count", K(data_len), K(pos), K(ret));
    } else {
W
wangzelin.wzl 已提交
3889
      LOG_DEBUG("total des sys vars", K(deserialize_sys_var_count));
O
oceanbase-admin 已提交
3890 3891 3892
      const bool check_timezone_valid = false;
      for (int64_t i = 0; OB_SUCC(ret) && i < deserialize_sys_var_count; ++i) {
        ObObj tmp_val;
W
wangzelin.wzl 已提交
3893
        ObBasicSysVar *sys_var = NULL;
O
oceanbase-admin 已提交
3894 3895 3896 3897 3898 3899
        ObSysVarClassType sys_var_id = SYS_VAR_INVALID;
        int16_t tmp_sys_var_id = -1;
        int64_t store_idx = -1;
        if (OB_FAIL(serialization::decode(buf, data_len, pos, tmp_sys_var_id))) {
          LOG_WARN("fail to deserialize sys var id", K(data_len), K(pos), K(ret));
        } else if (FALSE_IT(sys_var_id = static_cast<ObSysVarClassType>(tmp_sys_var_id))) {
W
wangzelin.wzl 已提交
3900
        } else if (OB_FAIL(sys_var_inc_info_.add_sys_var_id(sys_var_id))) {
O
oceanbase-admin 已提交
3901 3902 3903
          LOG_WARN("fail to add sys var id", K(sys_var_id), K(ret));
        } else if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(sys_var_id, store_idx))) {
          if (OB_SYS_VARS_MAYBE_DIFF_VERSION == ret) {
W
wangzelin.wzl 已提交
3904
            // 可能是版本不同,为了兼容,跳过这段数据,并继续循环
O
oceanbase-admin 已提交
3905 3906 3907 3908 3909 3910
            ret = OB_SUCCESS;
            int64_t sys_var_version = 0;
            int64_t sys_var_len = 0;
            OB_UNIS_DECODEx(sys_var_version);
            OB_UNIS_DECODEx(sys_var_len);
            if (OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
3911
              pos += sys_var_len; // 跳过这段数据
O
oceanbase-admin 已提交
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
              LOG_WARN("invalid sys var id, maybe version is different, skip it", K(sys_var_id));
            }
          } else {
            LOG_ERROR("invalid sys var id", K(sys_var_id), K(ret));
          }
        } else if (OB_FAIL(create_sys_var(sys_var_id, store_idx, sys_var))) {
          LOG_WARN("fail to create sys var", K(sys_var_id), K(ret));
        } else if (OB_ISNULL(sys_var)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("create sys var is NULL", K(ret));
        } else if (OB_FAIL(sys_var->deserialize(buf, data_len, pos))) {
          LOG_WARN("fail to deserialize sys var", K(data_len), K(pos), K(sys_var_id), K(ret));
W
wangzelin.wzl 已提交
3924
        } else if (OB_FAIL(deep_copy_sys_variable(*sys_var, sys_var_id, sys_var->get_value()))) {
O
oceanbase-admin 已提交
3925
          LOG_WARN("fail to update system variable", K(sys_var_id), K(sys_var->get_value()), K(ret));
W
wangzelin.wzl 已提交
3926
        } else if (OB_FAIL(process_session_variable(sys_var_id, sys_var->get_value(),
3927 3928 3929
                                                    check_timezone_valid,
                                                    false /*is_update_sys_var*/))) {
          LOG_WARN("process system variable error",  K(ret), K(*sys_var));
O
oceanbase-admin 已提交
3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944
        }
      }
    }

    if (OB_SUCC(ret)) {
      bool tx_read_only = false;
      if (OB_FAIL(serialization::decode_bool(buf, data_len, pos, &tx_read_only))) {
        LOG_WARN("fail to decode tx_read_only", K(ret));
      } else {
        // direct assignment because in this case we won't track trans_specified_status
        next_tx_read_only_ = tx_read_only;
      }
    }
  }

W
wangzelin.wzl 已提交
3945 3946
  // split function, make stack checker happy
  [&]() {
O
oceanbase-admin 已提交
3947
  int64_t unused_inner_safe_weak_read_snapshot = 0;
W
wangzelin.wzl 已提交
3948 3949
  int64_t unused_weak_read_snapshot_source = 0;
  int64_t unused_safe_weak_read_snapshot = 0;
O
oceanbase-admin 已提交
3950 3951
  bool unused_literal_query = false;
  bool need_serial_exec = false;
O
obdev 已提交
3952
  uint64_t sql_scope_flags = 0;
O
oceanbase-admin 已提交
3953

W
wangzelin.wzl 已提交
3954 3955 3956
  sys_var_in_pc_str_.reset(); //sys_var_in_pc_str_在反序列化系统变量阶段可能会被污染,需要reset掉
  config_in_pc_str_.reset();
  const ObTZInfoMap *tz_info_map = tz_info_wrap_.get_tz_info_offset().get_tz_info_map();
O
oceanbase-admin 已提交
3957
  LST_DO_CODE(OB_UNIS_DECODE,
W
wangzelin.wzl 已提交
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989
              sys_vars_cache_.inc_data_,
              unused_safe_weak_read_snapshot,
              unused_inner_safe_weak_read_snapshot,
              unused_literal_query,
              tz_info_wrap_,
              app_trace_id_,
              proxy_capability_.capability_,
              client_mode_,
              proxy_sessid_,
              nested_count_,
              thread_data_.user_name_,
              next_tx_isolation_,
              read_snapshot_version_,
              check_sys_variable_,
              unused_weak_read_snapshot_source,
              database_id_,
              thread_data_.user_at_host_name_,
              thread_data_.user_at_client_ip_,
              current_execution_id_,
              labels_,
              total_stmt_tables_,
              cur_stmt_tables_,
              is_foreign_key_cascade_,
              sys_var_in_pc_str_,
              config_in_pc_str_,
              is_foreign_key_check_exist_,
              need_serial_exec,
              sql_scope_flags,
              stmt_type_,
              thread_data_.client_addr_,
              thread_data_.user_client_addr_,
              process_query_time_);
3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010
  // deep copy string.
  if (OB_SUCC(ret)) {
    if (OB_FAIL(name_pool_.write_string(app_trace_id_, &app_trace_id_))) {
      LOG_WARN("fail to write app_trace_id to string_buf_", K(app_trace_id_), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(thread_data_.user_name_,
                                              &thread_data_.user_name_))) {
      LOG_WARN("fail to write username to string_buf_", K(thread_data_.user_name_), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(thread_data_.user_at_host_name_,
                                              &thread_data_.user_at_host_name_))) {
      LOG_WARN("fail to write user_at_host_name to string_buf_",
                K(thread_data_.user_at_host_name_), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(thread_data_.user_at_client_ip_,
                                              &thread_data_.user_at_client_ip_))) {
      LOG_WARN("fail to write user_at_client_ip to string_buf_",
                K(thread_data_.user_at_client_ip_), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(sys_var_in_pc_str_, &sys_var_in_pc_str_))) {
      LOG_WARN("fail to write sys_var_in_pc_str to string_buf_", K(sys_var_in_pc_str_), K(ret));
    } else if (OB_FAIL(name_pool_.write_string(config_in_pc_str_, &config_in_pc_str_))) {
      LOG_WARN("fail to write config_in_pc_str_ to string_buf_", K(config_in_pc_str_), K(ret));
    }
  }
O
oceanbase-admin 已提交
4011
  trans_flags_.set_need_serial_exec(need_serial_exec);
W
wangzelin.wzl 已提交
4012
  sql_scope_flags_.set_flags(sql_scope_flags);
O
oceanbase-admin 已提交
4013 4014 4015
  is_deserialized_ = true;
  tz_info_wrap_.set_tz_info_map(tz_info_map);

W
wangzelin.wzl 已提交
4016 4017 4018
  //在升级过程中,由于版本差异,高版本server如果收到低版本server发来的session变量,需要兼容处理
  //反序列化完成后, 由于后面存在再次序列化给其他server的场景, 所以需要补齐需要序列化的系统变量
  //fix以下场景   A(2.1)->B(2.2)->C(2.2)-> ret = -4016
O
oceanbase-admin 已提交
4019
  if (OB_SUCC(ret) && GET_MIN_CLUSTER_VERSION() < CLUSTER_CURRENT_VERSION) {
W
wangzelin.wzl 已提交
4020
    ObArenaAllocator calc_buf(ObModIds::OB_SQL_SESSION);
O
oceanbase-admin 已提交
4021
    for (int64_t i = 0; OB_SUCC(ret) && i < get_sys_var_count(); ++i) {
W
wangzelin.wzl 已提交
4022 4023 4024
      if ((ObSysVariables::get_flags(i) & ObSysVarFlag::NEED_SERIALIZE)
          && OB_ISNULL(sys_vars_[i])) {
        if (OB_FAIL(load_default_sys_variable(calc_buf, i))) {
O
oceanbase-admin 已提交
4025 4026 4027 4028 4029 4030
          LOG_WARN("fail to load default sys variable", K(ret), K(i));
        }
      }
    }
  }
  release_to_pool_ = OB_SUCC(ret);
W
wangzelin.wzl 已提交
4031
  }();
O
oceanbase-admin 已提交
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
  return ret;
}

OB_DEF_SERIALIZE(ObBasicSessionInfo::SysVarIncInfo)
{
  int ret = OB_SUCCESS;
  OB_UNIS_ENCODE(all_sys_var_ids_);
  return ret;
}

OB_DEF_DESERIALIZE(ObBasicSessionInfo::SysVarIncInfo)
{
  int ret = OB_SUCCESS;
  OB_UNIS_DECODE(all_sys_var_ids_);
  return ret;
}

OB_DEF_SERIALIZE_SIZE(ObBasicSessionInfo::SysVarIncInfo)
{
  int64_t len = 0;
  OB_UNIS_ADD_LEN(all_sys_var_ids_);
  return len;
}

W
wangzelin.wzl 已提交
4056 4057
ObBasicSessionInfo::SysVarIncInfo::SysVarIncInfo()
  : all_sys_var_ids_()
O
oceanbase-admin 已提交
4058 4059 4060 4061 4062 4063 4064 4065
{}

ObBasicSessionInfo::SysVarIncInfo::~SysVarIncInfo()
{}

int ObBasicSessionInfo::SysVarIncInfo::add_sys_var_id(ObSysVarClassType sys_var_id)
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4066
  OZ (add_var_to_array_no_dup(all_sys_var_ids_, sys_var_id), all_sys_var_ids_, sys_var_id);
O
oceanbase-admin 已提交
4067 4068 4069
  return ret;
}

W
wangzelin.wzl 已提交
4070 4071
int ObBasicSessionInfo::SysVarIncInfo::get_des_sys_var_id(int64_t idx,
                                                          ObSysVarClassType &sys_var_id) const
O
oceanbase-admin 已提交
4072 4073
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4074 4075
  OV (0 <= idx && idx < all_sys_var_ids_.count());
  OX (sys_var_id = all_sys_var_ids_.at(idx));
O
oceanbase-admin 已提交
4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088
  return ret;
}

bool ObBasicSessionInfo::SysVarIncInfo::all_has_sys_var_id(ObSysVarClassType sys_var_id) const
{
  return has_exist_in_array(all_sys_var_ids_, sys_var_id);
}

int64_t ObBasicSessionInfo::SysVarIncInfo::all_count() const
{
  return all_sys_var_ids_.count();
}

W
wangzelin.wzl 已提交
4089
const ObBasicSessionInfo::SysVarIds &ObBasicSessionInfo::SysVarIncInfo::get_all_sys_var_ids() const
O
oceanbase-admin 已提交
4090 4091 4092 4093
{
  return all_sys_var_ids_;
}

W
wangzelin.wzl 已提交
4094
int ObBasicSessionInfo::SysVarIncInfo::assign(const SysVarIncInfo &other)
O
oceanbase-admin 已提交
4095 4096 4097
{
  int ret = OB_SUCCESS;
  if (this != &other) {
W
wangzelin.wzl 已提交
4098
    OZ (all_sys_var_ids_.assign(other.all_sys_var_ids_));
O
oceanbase-admin 已提交
4099 4100 4101 4102 4103 4104 4105
  }
  return ret;
}

int ObBasicSessionInfo::SysVarIncInfo::reset()
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4106
  OX (all_sys_var_ids_.reset());
O
oceanbase-admin 已提交
4107 4108 4109 4110 4111 4112
  return ret;
}

int ObBasicSessionInfo::load_all_sys_vars_default()
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4113 4114
  OZ (clean_all_sys_vars());
  OZ (load_default_sys_variable(false, false));
O
oceanbase-admin 已提交
4115 4116 4117 4118 4119 4120 4121 4122
  return ret;
}

int ObBasicSessionInfo::clean_all_sys_vars()
{
  int ret = OB_SUCCESS;
  for (int64_t i = 0; OB_SUCC(ret) && i < get_sys_var_count(); ++i) {
    if (OB_NOT_NULL(sys_vars_[i])) {
W
wangzelin.wzl 已提交
4123
      OX (sys_vars_[i]->clean_value());
O
oceanbase-admin 已提交
4124 4125
    }
  }
W
wangzelin.wzl 已提交
4126 4127
  OX (base_sys_var_alloc_.reset());
  OX (inc_sys_var_alloc_.reset());
O
oceanbase-admin 已提交
4128 4129 4130
  return ret;
}

W
wangzelin.wzl 已提交
4131
int ObBasicSessionInfo::load_all_sys_vars(ObSchemaGetterGuard &schema_guard)
O
oceanbase-admin 已提交
4132 4133
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4134 4135 4136 4137 4138
  const ObSysVariableSchema *sys_var_schema = NULL;
  OZ (sys_var_fac_.create_all_sys_vars());
  OZ (schema_guard.get_sys_variable_schema(effective_tenant_id_, sys_var_schema));
  OV (OB_NOT_NULL(sys_var_schema));
  OZ (load_all_sys_vars(*sys_var_schema, true));
O
oceanbase-admin 已提交
4139 4140 4141
  return ret;
}

W
wangzelin.wzl 已提交
4142
int ObBasicSessionInfo::load_all_sys_vars(const ObSysVariableSchema &sys_var_schema, bool sys_var_created)
O
oceanbase-admin 已提交
4143 4144
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158
  OZ (clean_all_sys_vars());
  if (!sys_var_created) {
    OZ (sys_var_fac_.create_all_sys_vars());
  }
  OX (influence_plan_var_indexs_.reset());
  ObArenaAllocator calc_buf(ObModIds::OB_SQL_SESSION);
  for (int64_t i = 0; OB_SUCC(ret) && i < get_sys_var_count(); i++) {
    ObSysVarClassType sys_var_id = ObSysVariables::get_sys_var_id(i);
    const ObSysVarSchema *sys_var = NULL;
    OZ (sys_var_schema.get_sysvar_schema(sys_var_id, sys_var), sys_var_id, i);
    OV (OB_NOT_NULL(sys_var));
    OZ (load_sys_variable(calc_buf, sys_var->get_name(), sys_var->get_data_type(),
                          sys_var->get_value(), sys_var->get_min_val(),
                          sys_var->get_max_val(), sys_var->get_flags(), true));
O
obdev 已提交
4159
    if (OB_NOT_NULL(sys_vars_[i]) && OB_SUCC(ret)) {
W
wangzelin.wzl 已提交
4160 4161 4162 4163 4164 4165 4166
      if (sys_vars_[i]->is_influence_plan()) {
        OZ (influence_plan_var_indexs_.push_back(i));
      }
      if (ObSysVariables::get_default_value(i) != sys_vars_[i]->get_value()) {
        OZ (sys_var_inc_info_.add_sys_var_id(sys_var_id));
        LOG_DEBUG("schema and def not identical", K(sys_var_id), "val", sys_vars_[i]->get_value(),
                  "def", ObSysVariables::get_default_value(i));
O
oceanbase-admin 已提交
4167 4168 4169
      }
    }
  }
4170
  release_to_pool_ = OB_SUCC(ret);
O
oceanbase-admin 已提交
4171
  if (!is_deserialized_) {
W
wangzelin.wzl 已提交
4172
    OZ (gen_sys_var_in_pc_str());
4173
    OZ (gen_configs_in_pc_str());
O
oceanbase-admin 已提交
4174 4175 4176 4177 4178 4179 4180
  }
  return ret;
}

OB_DEF_SERIALIZE_SIZE(ObBasicSessionInfo)
{
  int64_t len = 0;
W
wangzelin.wzl 已提交
4181
  ObTimeZoneInfo tmp_tz_info;//为了兼容老版本,创建临时time zone info 占位
O
oceanbase-admin 已提交
4182 4183 4184 4185 4186 4187
  int ret = OB_SUCCESS;
  // To be compatible with old version which store sql_mode and compatibility mode in ObSQLModeManager;
  int64_t compatibility_mode_index = 0;
  if (OB_FAIL(compatibility_mode2index(get_compatibility_mode(), compatibility_mode_index))) {
    LOG_WARN("convert compatibility mode to index failed", K(ret));
  }
W
wangzelin.wzl 已提交
4188 4189 4190 4191 4192
  char has_tx_desc = tx_desc_ != NULL ? 1 : 0;
  OB_UNIS_ADD_LEN(has_tx_desc);
  if (has_tx_desc) {
    OB_UNIS_ADD_LEN(*tx_desc_);
  }
O
oceanbase-admin 已提交
4193
  LST_DO_CODE(OB_UNIS_ADD_LEN,
W
wangzelin.wzl 已提交
4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
              consistency_level_,
              compatibility_mode_index,
              tmp_tz_info,
              tenant_id_ | (rpc_tenant_id_<<32),
              effective_tenant_id_,
              is_changed_to_temp_tenant_,
              user_id_,
              is_master_session() ? sessid_ : master_sessid_,
              capability_.capability_,
              thread_data_.database_name_);

  // 计算需要序列化的用户变量和系统变量的序列化长度
O
oceanbase-admin 已提交
4206 4207 4208
  ObSEArray<ObSysVarClassType, 128> sys_var_ids;
  ObSEArray<ObString, 32> user_var_names;
  if (OB_FAIL(ret)) {
W
wangzelin.wzl 已提交
4209
  } else if (OB_FAIL(calc_need_serialize_vars(sys_var_ids, user_var_names))) {
O
oceanbase-admin 已提交
4210 4211 4212 4213 4214 4215
    LOG_WARN("fail to calc need serialize vars", K(ret));
  } else {
    int64_t actual_ser_user_var_count = 0;
    ObSessionVariable user_var_val;
    for (int64_t i = 0; OB_SUCC(ret) && i < user_var_names.count(); ++i) {
      user_var_val.reset();
W
wangzelin.wzl 已提交
4216
      const ObString &user_var_name = user_var_names.at(i);
O
oceanbase-admin 已提交
4217 4218
      ret = user_var_val_map_.get_refactored(user_var_name, user_var_val);
      if (OB_SUCCESS != ret && OB_HASH_NOT_EXIST != ret) {
W
wangzelin.wzl 已提交
4219 4220
        LOG_WARN("fail to get user var from session user var map", K(i), K(user_var_name),
                 K(user_var_val_map_.size()), K(ret));
O
oceanbase-admin 已提交
4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
      } else {
        if (OB_SUCCESS == ret) {
          actual_ser_user_var_count++;
          len += serialization::encoded_length(user_var_name);
          len += serialization::encoded_length(user_var_val.meta_);
          len += serialization::encoded_length(user_var_val.value_);
        }
        ret = OB_SUCCESS;
      }
    }
    len += serialization::encoded_length(actual_ser_user_var_count);
  }
  if (OB_SUCC(ret)) {
    len += serialization::encoded_length(sys_var_ids.count());
    for (int64_t i = 0; OB_SUCC(ret) && i < sys_var_ids.count(); ++i) {
      int64_t sys_var_idx = -1;
W
wangzelin.wzl 已提交
4237
      ObSysVarClassType &type = sys_var_ids.at(i);
O
oceanbase-admin 已提交
4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
      if (OB_FAIL(ObSysVarFactory::calc_sys_var_store_idx(type, sys_var_idx))) {
        LOG_WARN("fail to calc sys var store idx", K(i), K(sys_var_idx), K(type), K(ret));
      } else if (sys_var_idx < 0 || get_sys_var_count() <= sys_var_idx) {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("sys var idx is invalid", K(sys_var_idx), K(get_sys_var_count()), K(ret));
      } else if (OB_ISNULL(sys_vars_[sys_var_idx])) {
        ret = OB_ERR_UNEXPECTED;
        LOG_ERROR("sys var is NULL", K(ret), K(sys_var_idx), K(get_sys_var_count()));
      } else {
        int16_t sys_var_id = static_cast<int16_t>(sys_vars_[sys_var_idx]->get_type());
        len += serialization::encoded_length(sys_var_id);
        len += sys_vars_[sys_var_idx]->get_serialize_size();
      }
    }
  }
  if (OB_SUCC(ret)) {
    bool tx_read_only = get_tx_read_only();
    len += serialization::encoded_length_bool(tx_read_only);
  }
  bool unused_literal_query = false;
W
wangzelin.wzl 已提交
4258 4259 4260
  int64_t unused_inner_safe_weak_read_snapshot = 0;
  int64_t unused_weak_read_snapshot_source = 0;
  int64_t unused_safe_weak_read_snapshot = 0;
O
oceanbase-admin 已提交
4261
  bool need_serial_exec = trans_flags_.need_serial_exec();
W
wangzelin.wzl 已提交
4262
  uint64_t sql_scope_flags = sql_scope_flags_.get_flags();
O
oceanbase-admin 已提交
4263 4264

  LST_DO_CODE(OB_UNIS_ADD_LEN,
W
wangzelin.wzl 已提交
4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
              sys_vars_cache_.inc_data_,
              unused_safe_weak_read_snapshot,
              unused_inner_safe_weak_read_snapshot,
              unused_literal_query,
              tz_info_wrap_,
              app_trace_id_,
              proxy_capability_.capability_,
              client_mode_,
              proxy_sessid_,
              nested_count_,
              thread_data_.user_name_,
              next_tx_isolation_,
              read_snapshot_version_,
              check_sys_variable_,
              unused_weak_read_snapshot_source,
              database_id_,
              thread_data_.user_at_host_name_,
              thread_data_.user_at_client_ip_,
              current_execution_id_,
              labels_,
              total_stmt_tables_,
              cur_stmt_tables_,
              is_foreign_key_cascade_,
              sys_var_in_pc_str_,
              config_in_pc_str_,
              is_foreign_key_check_exist_,
              need_serial_exec,
              sql_scope_flags,
              stmt_type_,
              thread_data_.client_addr_,
              thread_data_.user_client_addr_,
              process_query_time_);
O
oceanbase-admin 已提交
4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309
  return len;
}

////////////////////////////////////////////////////////////////
void ObBasicSessionInfo::reset_session_changed_info()
{
  changed_sys_vars_.reset();
  changed_user_vars_.reset();
  is_database_changed_ = false;
  changed_var_pool_.reset();
  feedback_manager_.reset();
}

W
wangzelin.wzl 已提交
4310 4311
bool ObBasicSessionInfo::is_already_tracked(const ObSysVarClassType &sys_var_id,
                                            const ObIArray<ChangedVar> &array) const
O
oceanbase-admin 已提交
4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322
{
  bool found = false;
  for (int64_t i = 0; !found && i < array.count(); ++i) {
    if (array.at(i).id_ == sys_var_id) {
      found = true;
      break;
    }
  }
  return found;
}

W
wangzelin.wzl 已提交
4323 4324
bool ObBasicSessionInfo::is_already_tracked(const ObString& name,
                                            const ObIArray<ObString> &array) const
O
oceanbase-admin 已提交
4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335
{
  bool found = false;
  for (int64_t i = 0; !found && i < array.count(); ++i) {
    if (array.at(i) == name) {
      found = true;
      break;
    }
  }
  return found;
}

W
wangzelin.wzl 已提交
4336 4337 4338
int ObBasicSessionInfo::add_changed_sys_var(const ObSysVarClassType &sys_var_id,
                                            const ObObj &old_val,
                                            ObIArray<ChangedVar> &array)
O
oceanbase-admin 已提交
4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352
{
  int ret = OB_SUCCESS;
  ObObj val;
  if (SYS_VAR_INVALID == sys_var_id) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid input value", K(sys_var_id), K(old_val), K(ret));
  } else if (OB_FAIL(deep_copy_obj(changed_var_pool_, old_val, val))) {
    LOG_WARN("failed to deep copy system var old value", K(ret), K(old_val));
  } else if (OB_FAIL(array.push_back(ChangedVar(sys_var_id, val)))) {
    LOG_WARN("fail to push back", K(sys_var_id), K(old_val), K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
4353 4354
int ObBasicSessionInfo::add_changed_user_var(const ObString &name,
                                             common::ObIArray<common::ObString> &array)
O
oceanbase-admin 已提交
4355 4356 4357 4358
{
  return array.push_back(name);
}

W
wangzelin.wzl 已提交
4359 4360
int ObBasicSessionInfo::track_sys_var(const ObSysVarClassType &sys_var_id,
                                      const ObObj& old_val)
O
oceanbase-admin 已提交
4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375
{
  int ret = OB_SUCCESS;
  if (SYS_VAR_INVALID == sys_var_id) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid input value", K(sys_var_id), K(ret));
  } else if (!is_already_tracked(sys_var_id, changed_sys_vars_)) {
    if (OB_FAIL(add_changed_sys_var(sys_var_id, old_val, changed_sys_vars_))) {
      LOG_WARN("fail to add changed system var", K(sys_var_id), K(old_val), K(ret));
    } else {
      LOG_DEBUG("add changed var success", K(sys_var_id), K(old_val), K(changed_sys_vars_));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4376
int ObBasicSessionInfo::track_user_var(const common::ObString &user_var)
O
oceanbase-admin 已提交
4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
{
  int ret = OB_SUCCESS;
  if (user_var.empty()) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid input value", K(user_var), K(ret));
  } else if (!is_already_tracked(user_var, changed_user_vars_)) {
    ObString name;
    if (OB_FAIL(ob_write_string(changed_var_pool_, user_var, name))) {
      LOG_WARN("fail to write string", K(user_var), K(ret));
    } else if (OB_FAIL(add_changed_user_var(name, changed_user_vars_))) {
      LOG_WARN("fail to add changed user var", K(name), K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4393 4394 4395 4396
int ObBasicSessionInfo::is_sys_var_actully_changed(const ObSysVarClassType &sys_var_id,
                                                   const ObObj &old_val,
                                                   ObObj &new_val,
                                                   bool &changed)
O
oceanbase-admin 已提交
4397 4398
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4399 4400 4401
  // 部分系统变量除了设置标志位外还做了其他的工作
  // 因此这里仅CHECK只设置了标志位的系统变量
  // 变量的设置参考函数 process_session_variable
O
oceanbase-admin 已提交
4402
  changed = true;
W
wangzelin.wzl 已提交
4403
  OZ (get_sys_variable(sys_var_id, new_val));
O
oceanbase-admin 已提交
4404 4405 4406 4407 4408 4409 4410 4411 4412
  if (OB_SUCC(ret)) {
    switch (sys_var_id) {
      case SYS_VAR_AUTO_INCREMENT_INCREMENT:
      case SYS_VAR_AUTO_INCREMENT_OFFSET:
      case SYS_VAR_LAST_INSERT_ID:
      case SYS_VAR_TX_READ_ONLY:
      case SYS_VAR_OB_ENABLE_PLAN_CACHE:
      case SYS_VAR_OB_ENABLE_SQL_AUDIT:
      case SYS_VAR_AUTOCOMMIT:
O
obdev 已提交
4413
      case SYS_VAR_OB_ENABLE_SHOW_TRACE:
O
oceanbase-admin 已提交
4414 4415 4416 4417 4418 4419
      case SYS_VAR_OB_ORG_CLUSTER_ID:
      case SYS_VAR_OB_QUERY_TIMEOUT:
      case SYS_VAR_OB_TRX_TIMEOUT:
      case SYS_VAR_OB_TRX_IDLE_TIMEOUT:
      case SYS_VAR_COLLATION_CONNECTION:
      case SYS_VAR_OB_PL_BLOCK_TIMEOUT:
B
bf0 已提交
4420
      case SYS_VAR_OB_COMPATIBILITY_MODE:
W
wangzelin.wzl 已提交
4421
      case SYS_VAR__OB_OLS_POLICY_SESSION_LABELS:
B
bf0 已提交
4422
      case SYS_VAR__OB_PROXY_SESSION_TEMPORARY_TABLE_USED: {
W
wangzelin.wzl 已提交
4423 4424 4425
       changed = old_val.get_meta() == new_val.get_meta() ? old_val != new_val : true;
      }
      break;
O
oceanbase-admin 已提交
4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441
      default: {
        break;
      }
    }
  }
  LOG_DEBUG("is_sys_var_actully_changed", K(sys_var_id), K(changed), K(old_val), K(new_val));
  return ret;
}

int ObBasicSessionInfo::set_partition_hit(const bool is_hit)
{
  int ret = OB_SUCCESS;
  ObObj obj;
  obj.set_bool(is_hit);
  if (OB_FAIL(update_sys_variable(SYS_VAR_OB_PROXY_PARTITION_HIT, obj))) {
    LOG_WARN("fail to update_system_variable", K(ret));
W
wangzelin.wzl 已提交
4442
  } else {}
O
oceanbase-admin 已提交
4443 4444 4445 4446 4447 4448 4449 4450 4451 4452
  return ret;
}

int ObBasicSessionInfo::set_proxy_user_privilege(const int64_t user_priv_set)
{
  int ret = OB_SUCCESS;
  ObObj obj;
  obj.set_int(user_priv_set);
  if (OB_FAIL(update_sys_variable(SYS_VAR_OB_PROXY_USER_PRIVILEGE, obj))) {
    LOG_WARN("fail to update_system_variable", K(SYS_VAR_OB_PROXY_USER_PRIVILEGE), K(user_priv_set), K(ret));
W
wangzelin.wzl 已提交
4453
  } else {}
O
oceanbase-admin 已提交
4454 4455 4456
  return ret;
}

W
wangzelin.wzl 已提交
4457
int ObBasicSessionInfo::update_last_trace_id(const ObCurTraceId::TraceId &trace_id)
O
oceanbase-admin 已提交
4458 4459 4460 4461
{
  int ret = OB_SUCCESS;
  const int64_t TEMP_STR_BUF_LEN = 128;
  // 128 is enough to tracd_id, or will be truncated
W
wangzelin.wzl 已提交
4462
  char tmp_str_buf[TEMP_STR_BUF_LEN]; // no need init
O
oceanbase-admin 已提交
4463 4464 4465 4466 4467
  int64_t pos = trace_id.to_string(tmp_str_buf, TEMP_STR_BUF_LEN);
  ObString trace_id_str(static_cast<ObString::obstr_size_t>(pos), tmp_str_buf);

  ObObj obj;
  obj.set_string(ObVarcharType, trace_id_str);
W
wangzelin.wzl 已提交
4468 4469
  obj.set_collation_type(ObCharset::get_system_collation());
  if (OB_FAIL(update_sys_variable(SYS_VAR_OB_STATEMENT_TRACE_ID , obj))) {
O
oceanbase-admin 已提交
4470
    LOG_WARN("fail to update_system_variable", K(SYS_VAR_OB_STATEMENT_TRACE_ID), K(trace_id_str), K(ret));
W
wangzelin.wzl 已提交
4471
  } else {}
O
oceanbase-admin 已提交
4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
  return ret;
}

int ObBasicSessionInfo::set_proxy_capability(const uint64_t cap)
{
  int ret = OB_SUCCESS;
  ObObj obj;
  obj.set_int(cap);
  if (OB_FAIL(update_sys_variable(SYS_VAR_OB_CAPABILITY_FLAG, obj))) {
    LOG_WARN("fail to update_system_variable", K(SYS_VAR_OB_CAPABILITY_FLAG), K(cap), K(ret));
W
wangzelin.wzl 已提交
4482
  } else {}
O
oceanbase-admin 已提交
4483 4484 4485 4486 4487 4488 4489 4490
  return ret;
}

int ObBasicSessionInfo::set_trans_specified(const bool is_spec)
{
  int ret = OB_SUCCESS;
  ObObj obj;
  obj.set_bool(is_spec);
W
wangzelin.wzl 已提交
4491
  if (OB_FAIL(update_sys_variable(SYS_VAR_OB_PROXY_SET_TRX_EXECUTED, obj))) {
B
bf0 已提交
4492
    LOG_WARN("fail to update_system_variable", K(ret));
W
wangzelin.wzl 已提交
4493
  } else {}
B
bf0 已提交
4494 4495 4496
  return ret;
}

W
wangzelin.wzl 已提交
4497
int ObBasicSessionInfo::set_session_temp_table_used(const bool is_used)
O
oceanbase-admin 已提交
4498 4499 4500
{
  int ret = OB_SUCCESS;
  ObObj obj;
W
wangzelin.wzl 已提交
4501 4502 4503
  obj.set_int(is_used);
  if (OB_FAIL(update_sys_variable(SYS_VAR__OB_PROXY_SESSION_TEMPORARY_TABLE_USED, obj))) {
    LOG_WARN("fail to update_system_variable", K(ret));
O
oceanbase-admin 已提交
4504 4505 4506 4507
  }
  return ret;
}

W
wangzelin.wzl 已提交
4508
int ObBasicSessionInfo::set_init_connect(const ObString &init_sql)
O
oceanbase-admin 已提交
4509 4510 4511 4512
{
  int ret = OB_SUCCESS;
  ObObj obj;
  obj.set_string(ObVarcharType, init_sql);
W
wangzelin.wzl 已提交
4513
  obj.set_collation_type(ObCharset::get_system_collation());
O
oceanbase-admin 已提交
4514 4515
  if (OB_FAIL(update_sys_variable(SYS_VAR_INIT_CONNECT, obj))) {
    LOG_WARN("fail to update_system_variable", K(ret));
W
wangzelin.wzl 已提交
4516
  } else {}
O
oceanbase-admin 已提交
4517 4518 4519 4520 4521 4522
  return ret;
}

int ObBasicSessionInfo::save_trans_status()
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4523
  switch(trans_spec_status_) {
O
oceanbase-admin 已提交
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541
    case TRANS_SPEC_SET:
      ret = set_trans_specified(true);
      break;
    case TRANS_SPEC_COMMIT:
      ret = set_trans_specified(false);
      trans_spec_status_ = TRANS_SPEC_NOT_SET;
      break;
    case TRANS_SPEC_NOT_SET:
      // do nothing
      break;
    default:
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("Unknown trans specified status", K(trans_spec_status_), K(ret));
      break;
  }
  return ret;
}

W
wangzelin.wzl 已提交
4542
int ObBasicSessionInfo::get_character_set_client(ObCharsetType &character_set_client) const
O
oceanbase-admin 已提交
4543 4544 4545 4546
{
  return get_charset_sys_var(SYS_VAR_CHARACTER_SET_CLIENT, character_set_client);
}

W
wangzelin.wzl 已提交
4547
int ObBasicSessionInfo::get_character_set_connection(ObCharsetType &character_set_connection) const
O
oceanbase-admin 已提交
4548
{
W
wangzelin.wzl 已提交
4549 4550 4551 4552
  if (CHARSET_INVALID == (character_set_connection = sys_vars_cache_.get_character_set_connection())) {
    get_charset_sys_var(SYS_VAR_CHARACTER_SET_CONNECTION, character_set_connection);
  }
  return OB_SUCCESS;
O
oceanbase-admin 已提交
4553 4554
}

W
wangzelin.wzl 已提交
4555
int ObBasicSessionInfo::get_character_set_database(ObCharsetType &character_set_database) const
O
oceanbase-admin 已提交
4556 4557 4558 4559
{
  return get_charset_sys_var(SYS_VAR_CHARACTER_SET_DATABASE, character_set_database);
}

W
wangzelin.wzl 已提交
4560
int ObBasicSessionInfo::get_character_set_results(ObCharsetType &character_set_results) const
O
oceanbase-admin 已提交
4561 4562 4563 4564 4565 4566 4567
{
  if (CHARSET_INVALID == (character_set_results = sys_vars_cache_.get_character_set_results())) {
    get_charset_sys_var(SYS_VAR_CHARACTER_SET_RESULTS, character_set_results);
  }
  return OB_SUCCESS;
}

W
wangzelin.wzl 已提交
4568
int ObBasicSessionInfo::get_character_set_server(ObCharsetType &character_set_server) const
O
oceanbase-admin 已提交
4569 4570 4571 4572
{
  return get_charset_sys_var(SYS_VAR_CHARACTER_SET_SERVER, character_set_server);
}

W
wangzelin.wzl 已提交
4573
int ObBasicSessionInfo::get_character_set_system(ObCharsetType &character_set_system) const
O
oceanbase-admin 已提交
4574 4575 4576 4577
{
  return get_charset_sys_var(SYS_VAR_CHARACTER_SET_SYSTEM, character_set_system);
}

W
wangzelin.wzl 已提交
4578
int ObBasicSessionInfo::get_character_set_filesystem(ObCharsetType &character_set_filesystem) const
O
oceanbase-admin 已提交
4579 4580 4581 4582
{
  return get_charset_sys_var(SYS_VAR_CHARACTER_SET_FILESYSTEM, character_set_filesystem);
}

W
wangzelin.wzl 已提交
4583
int ObBasicSessionInfo::get_collation_database(ObCollationType &collation_database) const
O
oceanbase-admin 已提交
4584 4585 4586 4587
{
  return get_collation_sys_var(SYS_VAR_COLLATION_DATABASE, collation_database);
}

W
wangzelin.wzl 已提交
4588
int ObBasicSessionInfo::get_collation_server(ObCollationType &collation_server) const
O
oceanbase-admin 已提交
4589 4590 4591 4592
{
  return get_collation_sys_var(SYS_VAR_COLLATION_SERVER, collation_server);
}

W
wangzelin.wzl 已提交
4593
int ObBasicSessionInfo::get_capture_plan_baseline(bool &v)  const
O
oceanbase-admin 已提交
4594
{
W
wangzelin.wzl 已提交
4595
  v = sys_vars_cache_.get_optimizer_capture_sql_plan_baselines();
O
oceanbase-admin 已提交
4596 4597 4598
  return OB_SUCCESS;
}

W
wangzelin.wzl 已提交
4599
int ObBasicSessionInfo::get_nlj_batching_enabled(bool &v) const
O
oceanbase-admin 已提交
4600 4601 4602 4603
{
  return get_bool_sys_var(SYS_VAR__NLJ_BATCHING_ENABLED, v);
}

W
wangzelin.wzl 已提交
4604
int ObBasicSessionInfo::get_auto_increment_cache_size(int64_t &auto_increment_cache_size)
O
oceanbase-admin 已提交
4605 4606 4607 4608 4609 4610 4611 4612
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(get_sys_variable(SYS_VAR_AUTO_INCREMENT_CACHE_SIZE, auto_increment_cache_size))) {
    LOG_WARN("fail to get variables", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
4613
int ObBasicSessionInfo::get_enable_parallel_dml(bool &v) const
O
oceanbase-admin 已提交
4614 4615 4616 4617
{
  return get_bool_sys_var(SYS_VAR__ENABLE_PARALLEL_DML, v);
}

W
wangzelin.wzl 已提交
4618
int ObBasicSessionInfo::get_enable_parallel_query(bool &v) const
O
oceanbase-admin 已提交
4619 4620 4621 4622
{
  return get_bool_sys_var(SYS_VAR__ENABLE_PARALLEL_QUERY, v);
}

W
wangzelin.wzl 已提交
4623 4624 4625 4626 4627 4628
int ObBasicSessionInfo::get_enable_parallel_ddl(bool &v) const
{
  return get_bool_sys_var(SYS_VAR__ENABLE_PARALLEL_DDL, v);
}

int ObBasicSessionInfo::get_force_parallel_query_dop(uint64_t &v) const
O
oceanbase-admin 已提交
4629 4630 4631 4632 4633 4634 4635 4636 4637 4638
{
  int ret = OB_SUCCESS;
  if (exec_min_cluster_version_ >= CLUSTER_VERSION_3100) {
    ret = get_uint64_sys_var(SYS_VAR__FORCE_PARALLEL_QUERY_DOP, v);
  } else {
    v = 1;
  }
  return ret;
}

W
wangzelin.wzl 已提交
4639
int ObBasicSessionInfo::get_force_parallel_dml_dop(uint64_t &v) const
O
oceanbase-admin 已提交
4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
{
  int ret = OB_SUCCESS;
  if (exec_min_cluster_version_ >= CLUSTER_VERSION_3100) {
    ret = get_uint64_sys_var(SYS_VAR__FORCE_PARALLEL_DML_DOP, v);
  } else {
    v = 1;
  }
  return ret;
}

W
wangzelin.wzl 已提交
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 4686 4687 4688 4689
int ObBasicSessionInfo::get_force_parallel_ddl_dop(uint64_t &v) const
{
  int ret = OB_SUCCESS;
  if (exec_min_cluster_version_ >= CLUSTER_VERSION_3200) {
    ret = get_uint64_sys_var(SYS_VAR__FORCE_PARALLEL_DDL_DOP, v);
  } else {
    v = 1;
  }
  return ret;
}

int ObBasicSessionInfo::get_partial_rollup_pushdown(int64_t &partial_rollup) const
{
  int ret = OB_SUCCESS;
  ret = get_sys_variable(SYS_VAR__PX_PARTIAL_ROLLUP_PUSHDOWN, partial_rollup);
  return ret;
}

int ObBasicSessionInfo::get_distinct_agg_partial_rollup_pushdown(int64_t &partial_rollup) const
{
  int ret = OB_SUCCESS;
  ret = get_sys_variable(SYS_VAR__PX_DIST_AGG_PARTIAL_ROLLUP_PUSHDOWN, partial_rollup);
  return ret;
}

int ObBasicSessionInfo::get_px_shared_hash_join(bool &shared_hash_join) const
{
  int ret = OB_SUCCESS;
  ret = get_bool_sys_var(SYS_VAR__PX_SHARED_HASH_JOIN, shared_hash_join);
  return ret;
}

int ObBasicSessionInfo::get_sql_notes(bool &sql_notes) const
{
  int ret = OB_SUCCESS;
  ret = get_bool_sys_var(SYS_VAR_SQL_NOTES, sql_notes);
  return ret;
}

int ObBasicSessionInfo::get_secure_file_priv(ObString &v) const
O
oceanbase-admin 已提交
4690 4691 4692 4693
{
  return get_string_sys_var(SYS_VAR_SECURE_FILE_PRIV, v);
}

W
wangzelin.wzl 已提交
4694
int ObBasicSessionInfo::get_sql_safe_updates(bool &v) const
O
oceanbase-admin 已提交
4695 4696 4697 4698
{
  return get_bool_sys_var(SYS_VAR_SQL_SAFE_UPDATES, v);
}

W
wangzelin.wzl 已提交
4699
int ObBasicSessionInfo::get_session_temp_table_used(bool &is_used) const
B
bf0 已提交
4700 4701 4702
{
  return get_bool_sys_var(SYS_VAR__OB_PROXY_SESSION_TEMPORARY_TABLE_USED, is_used);
}
W
wangzelin.wzl 已提交
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715

int ObBasicSessionInfo::get_enable_optimizer_null_aware_antijoin(bool &is_enabled) const
{
  return get_bool_sys_var(SYS_VAR__OPTIMIZER_NULL_AWARE_ANTIJOIN, is_enabled);
}

// 重置事务相关变量
// 调用时机:end_trans阶段
//
// 注意:
// 1. 该函数需要保证幂等,可能在多处调用
// 2. trans_desc不能够在这里重置,end_trans过程中可能还会用到相关变量,
//    它由事务层在ObTransService::start_trans()中reset()
O
oceanbase-admin 已提交
4716 4717
void ObBasicSessionInfo::reset_tx_variable()
{
W
wangzelin.wzl 已提交
4718
  LOG_DEBUG("reset tx variable", K(lbt()));
O
oceanbase-admin 已提交
4719 4720 4721 4722 4723 4724
  reset_tx_isolation();
  reset_tx_read_only();
  reset_trans_flags();
  clear_app_trace_id();
}

W
wangzelin.wzl 已提交
4725
ObTxIsolationLevel ObBasicSessionInfo::get_tx_isolation() const
O
oceanbase-admin 已提交
4726
{
W
wangzelin.wzl 已提交
4727 4728
  ObTxIsolationLevel isolation;
  if (next_tx_isolation_ != ObTxIsolationLevel::INVALID) {
O
oceanbase-admin 已提交
4729 4730
    isolation = next_tx_isolation_;
  } else {
W
wangzelin.wzl 已提交
4731
    // 这里只会在本机调用,因此使用sys_vars_cache_data_的系统变量
O
oceanbase-admin 已提交
4732 4733 4734 4735 4736 4737 4738
    isolation = sys_vars_cache_.get_tx_isolation();
  }
  return isolation;
}

bool ObBasicSessionInfo::is_isolation_serializable() const
{
W
wangzelin.wzl 已提交
4739
  return ObTxIsolationLevel::SERIAL == get_tx_isolation();
O
oceanbase-admin 已提交
4740 4741
}

W
wangzelin.wzl 已提交
4742
void ObBasicSessionInfo::set_tx_isolation(ObTxIsolationLevel isolation)
O
oceanbase-admin 已提交
4743
{
W
wangzelin.wzl 已提交
4744 4745 4746
  if (isolation == ObTxIsolationLevel::INVALID) {
    LOG_ERROR("set invalid tx isolation", K(isolation), KPC(this));
  }
O
oceanbase-admin 已提交
4747 4748 4749 4750 4751 4752
  next_tx_isolation_ = isolation;
  trans_spec_status_ = TRANS_SPEC_SET;
}

void ObBasicSessionInfo::reset_tx_isolation()
{
W
wangzelin.wzl 已提交
4753 4754
  next_tx_isolation_ = transaction::ObTxIsolationLevel::INVALID;
  if (TRANS_SPEC_SET == trans_spec_status_ ) {
O
oceanbase-admin 已提交
4755 4756 4757 4758
    trans_spec_status_ = TRANS_SPEC_COMMIT;
  }
}

W
wangzelin.wzl 已提交
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777
/*
 这里为什么每次都要设置next_tx_read_only?

 set session transaction read only;
 set transaction read write;
 start transaction;
 insert into tt values(5);
 insert into tt values(6);
 start transaction;        //隐式提交上面的事务,开启本事务,read_only=false;
 insert into tt values(8); //对于这种case,这条语句需要执行成功,与mysql保持兼容
 commit;

 为了保持上述行为跟mysql一致,不能做如下处理:
 if (last_tx_read_only != cur_tx_read_only) {
   next_tx_read_only_ = cur_tx_read_only;
   trans_spec_status_ = TRANS_SPEC_SET;
 }
 */
void ObBasicSessionInfo::set_tx_read_only(const bool last_tx_read_only, bool cur_tx_read_only)
O
oceanbase-admin 已提交
4778
{
W
wangzelin.wzl 已提交
4779 4780 4781 4782
  next_tx_read_only_ = cur_tx_read_only;
  if (last_tx_read_only != cur_tx_read_only) {
    trans_spec_status_ = TRANS_SPEC_SET;
  }
O
oceanbase-admin 已提交
4783 4784 4785 4786 4787
}

void ObBasicSessionInfo::reset_tx_read_only()
{
  next_tx_read_only_ = -1;
W
wangzelin.wzl 已提交
4788
  if (TRANS_SPEC_SET == trans_spec_status_ ) {
O
oceanbase-admin 已提交
4789 4790 4791 4792
    trans_spec_status_ = TRANS_SPEC_COMMIT;
  }
}

W
wangzelin.wzl 已提交
4793 4794

int ObBasicSessionInfo::check_tx_read_only_privilege(const ObSqlTraits &sql_traits)
O
oceanbase-admin 已提交
4795 4796 4797 4798
{
  int ret = OB_SUCCESS;
  if (sql_traits.is_cause_implicit_commit_) {
    reset_tx_read_only();
W
wangzelin.wzl 已提交
4799 4800 4801 4802 4803 4804
  } else {}
  // pl call stmt and anonymous does not check here,
  // will be check in ObTransService::start_stmt_sanity_check_
  if (get_tx_read_only() && !sql_traits.is_readonly_stmt_
      && sql_traits.stmt_type_ != ObItemType::T_SP_CALL_STMT
      && sql_traits.stmt_type_ != ObItemType::T_SP_ANONYMOUS_BLOCK) {
O
oceanbase-admin 已提交
4805 4806
    ret = OB_ERR_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION;

W
wangzelin.wzl 已提交
4807
  } else {}
O
oceanbase-admin 已提交
4808 4809 4810 4811 4812 4813
  return ret;
}

int ObBasicSessionInfo::reset_tx_variable_if_remote_trans(const ObPhyPlanType& type)
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4814
  if (ObSqlTransUtil::is_remote_trans(get_local_autocommit(), is_in_transaction(), type)) {
O
oceanbase-admin 已提交
4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828
    reset_tx_variable();
  } else {
    // nothing to do
  }
  return ret;
}

bool ObBasicSessionInfo::get_tx_read_only() const
{
  bool tx_read_only = false;
  const int32_t TX_NOT_SET = -1;
  if (next_tx_read_only_ != TX_NOT_SET) {
    tx_read_only = next_tx_read_only_;
  } else {
W
wangzelin.wzl 已提交
4829
    // 这里只会在本机调用,因此使用sys_vars_cache_data_的系统变量
O
oceanbase-admin 已提交
4830 4831 4832 4833 4834
    tx_read_only = sys_vars_cache_.get_tx_read_only();
  }
  return tx_read_only;
}

W
wangzelin.wzl 已提交
4835
int ObBasicSessionInfo::store_query_string(const ObString &stmt)
O
oceanbase-admin 已提交
4836 4837 4838 4839 4840
{
  LockGuard lock_guard(thread_data_mutex_);
  return store_query_string_(stmt);
}

W
wangzelin.wzl 已提交
4841
int ObBasicSessionInfo::store_query_string_(const ObString &stmt)
O
oceanbase-admin 已提交
4842 4843
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
4844 4845
  int64_t truncated_len = std::min(MAX_QUERY_STRING_LEN - 1,
                                   static_cast<int64_t>(stmt.length()));
O
oceanbase-admin 已提交
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855
  if (truncated_len < 0) {
    ret = OB_INVALID_ARGUMENT;
    LOG_WARN("invalid str length", K(ret), K(truncated_len));
  } else if (thread_data_.cur_query_buf_len_ - 1 < truncated_len) {
    if (thread_data_.cur_query_ != nullptr) {
      ob_free(thread_data_.cur_query_);
      thread_data_.cur_query_ = NULL;
      thread_data_.cur_query_buf_len_ = 0;
    }
    int64_t len = MAX(MIN_CUR_QUERY_LEN, truncated_len + 1);
W
wangzelin.wzl 已提交
4856
     char *buf = reinterpret_cast<char*>(ob_malloc(len, ObModIds::OB_SQL_SESSION_QUERY_SQL));
O
oceanbase-admin 已提交
4857 4858 4859 4860 4861 4862 4863 4864 4865 4866
    if (OB_ISNULL(buf)) {
      ret = OB_ALLOCATE_MEMORY_FAILED;
      LOG_WARN("alloc memory failed", K(ret));
    } else {
      thread_data_.cur_query_ = buf;
      thread_data_.cur_query_buf_len_ = len;
    }
  }
  if (OB_SUCC(ret)) {
    MEMCPY(thread_data_.cur_query_, stmt.ptr(), truncated_len);
W
wangzelin.wzl 已提交
4867
    //char cur_query_[MAX_QUERY_STRING_LEN] 不存在越界风险,且不需要判空
O
oceanbase-admin 已提交
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
    thread_data_.cur_query_[truncated_len] = '\0';
    thread_data_.cur_query_len_ = truncated_len;
  }
  return ret;
}

void ObBasicSessionInfo::reset_query_string()
{
  thread_data_.cur_query_[0] = '\0';
  thread_data_.cur_query_len_ = 0;
}

int ObBasicSessionInfo::update_session_timeout()
{
  int ret = OB_SUCCESS;
  ObObj val;
  if (thread_data_.is_interactive_) {
    val.set_int(thread_data_.interactive_timeout_);
    if (OB_FAIL(update_sys_variable(SYS_VAR_WAIT_TIMEOUT, val))) {
      LOG_WARN("failed to update session_timeout", K(ret));
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4893
const char *ObBasicSessionInfo::get_session_state_str()const
O
oceanbase-admin 已提交
4894
{
W
wangzelin.wzl 已提交
4895
  const char *str_ret = NULL;
O
oceanbase-admin 已提交
4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908
  switch (thread_data_.state_) {
    case SESSION_INIT:
      str_ret = "INIT";
      break;
    case SESSION_SLEEP:
      str_ret = "SLEEP";
      break;
    case QUERY_ACTIVE:
      str_ret = "ACTIVE";
      break;
    case QUERY_KILLED:
      str_ret = "QUERY_KILLED";
      break;
W
wangzelin.wzl 已提交
4909 4910 4911
    case QUERY_DEADLOCKED:
      str_ret = "QUERY_DEADLOCKED";
      break;
O
oceanbase-admin 已提交
4912 4913 4914 4915 4916 4917 4918 4919 4920 4921
    case SESSION_KILLED:
      str_ret = "SESSION_KILLED";
      break;
    default:
      str_ret = "INVALID SESSION STATE";
      break;
  }
  return str_ret;
}

W
wangzelin.wzl 已提交
4922
int ObBasicSessionInfo::is_timeout(bool &is_timeout)
O
oceanbase-admin 已提交
4923 4924 4925 4926 4927
{
  int ret = OB_SUCCESS;
  int64_t timeout = 0;
  is_timeout = false;
  if (SESSION_SLEEP == thread_data_.state_) {
W
wangzelin.wzl 已提交
4928 4929
    timeout = thread_data_.is_interactive_ ?
        thread_data_.interactive_timeout_ : thread_data_.wait_timeout_;
O
oceanbase-admin 已提交
4930 4931 4932 4933 4934 4935 4936 4937 4938
    int64_t cur_time = ::oceanbase::common::ObTimeUtility::current_time();
    if (OB_UNLIKELY(timeout < 0)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("session timeout setting is invalid", K(ret), K(timeout));
    } else if (OB_UNLIKELY(timeout > INT64_MAX / 1000 / 1000)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_ERROR("session timeout setting is too larger, skip check timeout", K(ret), K(timeout));
    } else if (0 == timeout) {
      // no timeout check for timeout == 0
W
wangzelin.wzl 已提交
4939 4940 4941
    } else if (SESSION_SLEEP == thread_data_.state_
               && thread_data_.last_active_time_ + timeout * 1000 * 1000 < cur_time) {
      const ObString &user_name = get_user_name();
O
oceanbase-admin 已提交
4942
      char addr_buf[common::OB_IP_PORT_STR_BUFF];
W
wangzelin.wzl 已提交
4943 4944
      if (OB_FAIL(get_peer_addr().ip_port_to_string(addr_buf,
                                                    OB_IP_PORT_STR_BUFF))) {
O
oceanbase-admin 已提交
4945 4946 4947
        LOG_WARN("failed to get peer addr string", K(ret), K(get_peer_addr()), K(addr_buf));
      } else {
        _LOG_INFO("sessionkey %u, proxy_sessid %lu: %.*s from %s timeout: last active time=%s, cur=%s, timeout=%lds",
W
wangzelin.wzl 已提交
4948 4949
                  sessid_, proxy_sessid_, user_name.length(), user_name.ptr(), addr_buf,
                  time2str(thread_data_.last_active_time_), time2str(cur_time), timeout);
O
oceanbase-admin 已提交
4950 4951 4952 4953 4954 4955 4956
      }
      is_timeout = true;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978
// is_trx_commit_timeout - check txn committing reach either commit stmt's timeout or txn's timeout
//
// @callback: the callback supplied when call commit, it is canceled and return via this argument
// @retcode: timeout type, either OB_TRANS_STMT_TIMEOUT or OB_TRANS_TIMEOUT
int ObBasicSessionInfo::is_trx_commit_timeout(transaction::ObITxCallback *&callback, int &retcode)
{
  int ret = OB_SUCCESS;
  int64_t cur_time = ::oceanbase::common::ObTimeUtility::current_time();
  if (is_in_transaction() && tx_desc_->is_committing()) {
    if (tx_desc_->is_tx_timeout()) {
      callback = tx_desc_->cancel_commit_cb();
      retcode = OB_TRANS_TIMEOUT;
    } else if (tx_desc_->is_tx_commit_timeout()) {
      callback = tx_desc_->cancel_commit_cb();
      retcode = OB_TRANS_STMT_TIMEOUT;
    }
  }
  return ret;
}

// 检查事务内部的语句间隔超时
int ObBasicSessionInfo::is_trx_idle_timeout(bool &timeout)
O
oceanbase-admin 已提交
4979 4980 4981
{
  int ret = OB_SUCCESS;
  int64_t cur_time = ::oceanbase::common::ObTimeUtility::current_time();
W
wangzelin.wzl 已提交
4982 4983 4984
  LOG_DEBUG("check trx_idle_timeout : ", K_(sessid),
            K(curr_trans_last_stmt_end_time_),
            K(cur_time), "start_time", get_query_start_time());
O
oceanbase-admin 已提交
4985
  if (get_query_start_time() < curr_trans_last_stmt_end_time_) {
W
wangzelin.wzl 已提交
4986 4987 4988 4989 4990
    int64_t ob_trx_idle_timeout = sys_vars_cache_.get_ob_trx_idle_timeout() > 0
      ? sys_vars_cache_.get_ob_trx_idle_timeout() : 120 * 1000 * 1000;
    if (is_in_transaction() &&
        !tx_desc_->is_committing() &&
        curr_trans_last_stmt_end_time_ > 0 &&
O
oceanbase-admin 已提交
4991 4992
        curr_trans_last_stmt_end_time_ + ob_trx_idle_timeout < cur_time) {
      LOG_WARN("ob_trx_idle_timeout happen", K_(sessid), K_(curr_trans_last_stmt_end_time), K(ob_trx_idle_timeout));
W
wangzelin.wzl 已提交
4993
      curr_trans_last_stmt_end_time_ = 0; // flip
O
oceanbase-admin 已提交
4994 4995 4996 4997 4998 4999
      timeout = true;
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5000
int ObBasicSessionInfo::get_pc_mem_conf(ObPCMemPctConf &pc_mem_conf)
O
oceanbase-admin 已提交
5001 5002 5003
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(get_sys_variable(SYS_VAR_OB_PLAN_CACHE_PERCENTAGE, pc_mem_conf.limit_pct_))) {
W
wangzelin.wzl 已提交
5004
    LOG_WARN("fail to get plan cache system variables",K(pc_mem_conf.limit_pct_), K(ret));
O
oceanbase-admin 已提交
5005
  } else if (OB_FAIL(get_sys_variable(SYS_VAR_OB_PLAN_CACHE_EVICT_HIGH_PERCENTAGE, pc_mem_conf.high_pct_))) {
W
wangzelin.wzl 已提交
5006
    LOG_WARN("fail to get plan cache system variables",K(pc_mem_conf.high_pct_), K(ret));
O
oceanbase-admin 已提交
5007
  } else if (OB_FAIL(get_sys_variable(SYS_VAR_OB_PLAN_CACHE_EVICT_LOW_PERCENTAGE, pc_mem_conf.low_pct_))) {
W
wangzelin.wzl 已提交
5008
    LOG_WARN("fail to get plan cache system variables",K(pc_mem_conf.low_pct_), K(ret));
O
oceanbase-admin 已提交
5009 5010 5011 5012
  }
  return ret;
}

W
wangzelin.wzl 已提交
5013
int ObBasicSessionInfo::get_sql_audit_mem_conf(int64_t &mem_pct)
O
oceanbase-admin 已提交
5014 5015 5016 5017 5018 5019 5020 5021
{
  int ret = OB_SUCCESS;
  if (OB_FAIL(get_sys_variable(SYS_VAR_OB_SQL_AUDIT_PERCENTAGE, mem_pct))) {
    LOG_WARN("failed to get memory percentage for sql audit", K(ret));
  }
  return ret;
}

W
wangzelin.wzl 已提交
5022 5023 5024
//session 当前的query处于非retry的packet处理时
//  1)如果thread_data_.state_ == SESSION_KILLED时,调用该接口直接返回OB_ERR_SESSION_INTERRUPTED错误;
//  2)如果thread_data_.state_ != SESSION_KILLED时,进行session state的设置
O
oceanbase-admin 已提交
5025

W
wangzelin.wzl 已提交
5026 5027 5028 5029 5030 5031
//session 当前的query处于retry的packet处理时
//  1)如果thread_data_.state_ == SESSION_KILLED时,调用该接口直接返回OB_ERR_SESSION_INTERRUPTED错误;
//  2)如果thread_data_.state_ != SESSION_KILLED时,则进一步判断
//     2.1)如果QUERY_KILLED == thread_data_.state_ && state != SESSION_KILLED, 则返回OB_ERR_QUERY_INTERRUPTED错误
//     2.2)如果QUERY_DEADLOCKED == thread_data_.state_ && state != SESSION_KILLED, 则返回OB_DEAD_LOCK错误
//     2.3)其他情况则进行session state的设置
O
oceanbase-admin 已提交
5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042
int ObBasicSessionInfo::set_session_state(ObSQLSessionState state)
{
  LockGuard lock_guard(thread_data_mutex_);
  return set_session_state_(state);
}

int ObBasicSessionInfo::set_session_state_(ObSQLSessionState state)
{
  int ret = OB_SUCCESS;
  if (OB_UNLIKELY(SESSION_KILLED == thread_data_.state_)) {
    ret = OB_ERR_SESSION_INTERRUPTED;
W
wangzelin.wzl 已提交
5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056
    LOG_WARN("session is killed", K(ret), K(sessid_), K(proxy_sessid_), K(state));
  } else if (OB_UNLIKELY(SESS_NOT_IN_RETRY != thread_data_.is_in_retry_
                         && is_query_killed()
                         && SESSION_KILLED != state)) {
    if (QUERY_DEADLOCKED == thread_data_.state_) {
      ret = OB_DEAD_LOCK;
      LOG_WARN("query is deadlocked", K(ret), K(sessid_), K(proxy_sessid_), K(state));
    } else if (QUERY_KILLED == thread_data_.state_) {
      ret = OB_ERR_QUERY_INTERRUPTED;
      LOG_WARN("query is killed", K(ret), K(sessid_), K(proxy_sessid_), K(state));
    } else {
      ret = OB_ERR_UNEXPECTED;;
      LOG_WARN("session state is unknown", K(ret), K(sessid_), K(proxy_sessid_), K(state));
    }
O
oceanbase-admin 已提交
5057 5058 5059 5060 5061 5062 5063
  } else {
    thread_data_.state_ = state;
    thread_data_.cur_state_start_time_ = ::oceanbase::common::ObClockGenerator::getClock();
  }
  return ret;
}

W
wangzelin.wzl 已提交
5064 5065 5066 5067
// check the status of the session
// ATTENTION: the function only focus on the state
// will cause the query and session to be killed.
int ObBasicSessionInfo::check_session_status()
O
oceanbase-admin 已提交
5068 5069 5070
{
  int ret = OB_SUCCESS;

W
wangzelin.wzl 已提交
5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
  if (OB_UNLIKELY(SESSION_KILLED == thread_data_.state_)) {
    ret = OB_ERR_SESSION_INTERRUPTED;
    LOG_WARN("session is killed", K(ret), K(sessid_), K(proxy_sessid_));
  } else if (OB_UNLIKELY(QUERY_KILLED == thread_data_.state_)) {
    ret = OB_ERR_QUERY_INTERRUPTED;
    LOG_WARN("query is killed", K(ret), K(sessid_), K(proxy_sessid_));
  } else if (OB_UNLIKELY(QUERY_DEADLOCKED == thread_data_.state_)) {
    ret = OB_DEAD_LOCK;
    LOG_WARN("query is deadlocked", K(ret), K(sessid_), K(proxy_sessid_));
  }

  return ret;
}

bool ObBasicSessionInfo::is_query_killed() const
{
  return QUERY_KILLED == get_session_state()
    || QUERY_DEADLOCKED == get_session_state();
}

int ObBasicSessionInfo::set_session_active(const ObString &sql,
                                           const int64_t query_receive_ts,
                                           const int64_t last_active_time_ts,
                                           obmysql::ObMySQLCmd cmd)
{
  int ret = OB_SUCCESS;
O
oceanbase-admin 已提交
5097 5098 5099 5100 5101 5102 5103 5104 5105
  LockGuard lock_guard(thread_data_mutex_);
  if (OB_FAIL(store_query_string_(sql))) {
    LOG_WARN("store query string fail", K(ret));
  } else if (OB_FAIL(set_session_state_(QUERY_ACTIVE))) {
    LOG_WARN("fail to set session state", K(ret));
  } else {
    thread_data_.cur_query_start_time_ = query_receive_ts;
    thread_data_.mysql_cmd_ = cmd;
    thread_data_.last_active_time_ = last_active_time_ts;
W
wangzelin.wzl 已提交
5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122
    ObActiveSessionGuard::setup_ash(ash_stat_);
  }
  return ret;
}

int ObBasicSessionInfo::set_session_active(const ObString &label,
                                           obmysql::ObMySQLCmd cmd)
{
  int ret = OB_SUCCESS;
  LockGuard lock_guard(thread_data_mutex_);
  if (OB_FAIL(store_query_string_(label))) {
    LOG_WARN("store query string fail", K(ret));
  } else if (OB_FAIL(set_session_state_(QUERY_ACTIVE))) {
    LOG_WARN("fail to set session state", K(ret));
  } else {
    thread_data_.mysql_cmd_ = cmd;
    ObActiveSessionGuard::setup_ash(ash_stat_);
O
oceanbase-admin 已提交
5123 5124 5125 5126
  }
  return ret;
}

W
wangzelin.wzl 已提交
5127 5128 5129 5130 5131 5132 5133 5134 5135
void ObBasicSessionInfo::set_session_sleep()
{
  LockGuard lock_guard(thread_data_mutex_);
  set_session_state_(SESSION_SLEEP);
  thread_data_.mysql_cmd_ = obmysql::COM_SLEEP;
  thread_id_ = 0;
}

int ObBasicSessionInfo::base_save_session(BaseSavedValue &saved_value, bool skip_cur_stmt_tables)
O
oceanbase-admin 已提交
5136 5137
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5138 5139
  OX (saved_value.cur_phy_plan_ = cur_phy_plan_);
  OX (cur_phy_plan_ = NULL);
O
oceanbase-admin 已提交
5140 5141
  int len = MIN(thread_data_.cur_query_len_, static_cast<int64_t>(sizeof(saved_value.cur_query_) - 1));
  if (thread_data_.cur_query_ != nullptr) {
W
wangzelin.wzl 已提交
5142 5143 5144 5145 5146 5147
    OX (MEMCPY(&saved_value.cur_query_, thread_data_.cur_query_, len));
    OX (thread_data_.cur_query_[0] = 0);
  }
  OX (saved_value.cur_query_len_ = len);
  OX (thread_data_.cur_query_len_ = 0);
  OZ (saved_value.total_stmt_tables_.assign(total_stmt_tables_));
O
oceanbase-admin 已提交
5148
  if (!skip_cur_stmt_tables) {
W
wangzelin.wzl 已提交
5149
    OZ (merge_stmt_tables(), total_stmt_tables_, cur_stmt_tables_);
O
oceanbase-admin 已提交
5150
  }
W
wangzelin.wzl 已提交
5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162
  OZ (saved_value.cur_stmt_tables_.assign(cur_stmt_tables_));
  OX (cur_stmt_tables_.reset());
  OX (sys_vars_cache_.get_autocommit_info(saved_value.inc_autocommit_));
  OX (sys_vars_cache_.set_autocommit_info(false));
  OX (saved_value.is_foreign_key_cascade_ = is_foreign_key_cascade_);
  OX (is_foreign_key_cascade_ = false);
  OX (saved_value.is_foreign_key_check_exist_ = is_foreign_key_check_exist_);
  OX (is_foreign_key_check_exist_ = false);
  OX (saved_value.need_serial_exec_ = trans_flags_.need_serial_exec());
  if (OB_NOT_NULL(saved_value.cur_phy_plan_) &&
      saved_value.cur_phy_plan_->get_need_serial_exec()) {
    OX (trans_flags_.set_need_serial_exec(true));
O
oceanbase-admin 已提交
5163 5164 5165 5166
  }
  return ret;
}

W
wangzelin.wzl 已提交
5167
int ObBasicSessionInfo::stmt_save_session(StmtSavedValue &saved_value, bool skip_cur_stmt_tables)
O
oceanbase-admin 已提交
5168 5169
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5170 5171 5172 5173 5174 5175
  OZ (base_save_session(saved_value, skip_cur_stmt_tables));
  OZ (saved_value.tx_result_.assign(tx_result_));
  OX (tx_result_.reset());
  OX (saved_value.cur_query_start_time_ = thread_data_.cur_query_start_time_);
  OX (thread_data_.cur_query_start_time_ = 0);
  OX (saved_value.stmt_type_ = stmt_type_);
O
oceanbase-admin 已提交
5176 5177 5178
  return ret;
}

W
wangzelin.wzl 已提交
5179
int ObBasicSessionInfo::save_basic_session(StmtSavedValue &saved_value, bool skip_cur_stmt_tables)
O
oceanbase-admin 已提交
5180 5181 5182 5183
{
  return stmt_save_session(saved_value, skip_cur_stmt_tables);
}

W
wangzelin.wzl 已提交
5184
int ObBasicSessionInfo::begin_nested_session(StmtSavedValue &saved_value, bool skip_cur_stmt_tables)
O
oceanbase-admin 已提交
5185 5186
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5187
  OZ (SMART_CALL(save_basic_session(saved_value, skip_cur_stmt_tables)));
O
oceanbase-admin 已提交
5188 5189 5190
  return ret;
}

W
wangzelin.wzl 已提交
5191
int ObBasicSessionInfo::base_restore_session(BaseSavedValue &saved_value)
O
oceanbase-admin 已提交
5192 5193
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5194 5195 5196 5197 5198 5199 5200
  OX (trans_flags_.set_need_serial_exec(saved_value.need_serial_exec_));
  OX (is_foreign_key_check_exist_ = saved_value.is_foreign_key_check_exist_);
  OX (is_foreign_key_cascade_ = saved_value.is_foreign_key_cascade_);
  OX (sys_vars_cache_.set_autocommit_info(saved_value.inc_autocommit_));
  OZ (cur_stmt_tables_.assign(saved_value.cur_stmt_tables_));
  OZ (total_stmt_tables_.assign(saved_value.total_stmt_tables_));
//OX (thread_data_.cur_query_start_time_ = saved_value.cur_query_start_time_);
O
oceanbase-admin 已提交
5201
  int64_t len = MIN(saved_value.cur_query_len_, thread_data_.cur_query_buf_len_ - 1);
W
wangzelin.wzl 已提交
5202
  OX (thread_data_.cur_query_len_ = len);
O
oceanbase-admin 已提交
5203
  if (thread_data_.cur_query_ != nullptr) {
W
wangzelin.wzl 已提交
5204
    OX (MEMCPY(thread_data_.cur_query_, saved_value.cur_query_, len));
O
oceanbase-admin 已提交
5205 5206
    thread_data_.cur_query_[len] = '\0';
  }
W
wangzelin.wzl 已提交
5207
  OX (cur_phy_plan_ = saved_value.cur_phy_plan_);
O
oceanbase-admin 已提交
5208 5209 5210
  return ret;
}

W
wangzelin.wzl 已提交
5211
int ObBasicSessionInfo::stmt_restore_session(StmtSavedValue &saved_value)
O
oceanbase-admin 已提交
5212 5213
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5214 5215 5216 5217
  OX (thread_data_.cur_query_start_time_ = saved_value.cur_query_start_time_);
  OZ (tx_result_.merge_result(saved_value.tx_result_));
  OZ (base_restore_session(saved_value));
  OX (stmt_type_ = saved_value.stmt_type_);
O
oceanbase-admin 已提交
5218 5219 5220
  return ret;
}

W
wangzelin.wzl 已提交
5221
int ObBasicSessionInfo::restore_basic_session(StmtSavedValue &saved_value)
O
oceanbase-admin 已提交
5222 5223 5224 5225
{
  return stmt_restore_session(saved_value);
}

W
wangzelin.wzl 已提交
5226
int ObBasicSessionInfo::end_nested_session(StmtSavedValue &saved_value)
O
oceanbase-admin 已提交
5227 5228
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5229 5230
  OZ (SMART_CALL(restore_basic_session(saved_value)));
  OX (saved_value.reset());
O
oceanbase-admin 已提交
5231 5232 5233
  return ret;
}

W
wangzelin.wzl 已提交
5234
int ObBasicSessionInfo::trans_save_session(TransSavedValue &saved_value)
O
oceanbase-admin 已提交
5235 5236
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248
  OZ (base_save_session(saved_value, false));
  /*
   * save transaction context
   */
  OX (saved_value.tx_desc_ = tx_desc_);
  OX (tx_desc_ = NULL);
  OZ (saved_value.tx_result_.assign(tx_result_));
  OX (tx_result_.reset());
  OX (saved_value.trans_flags_ = trans_flags_);
  OX (trans_flags_.reset());
  OX (saved_value.nested_count_ = nested_count_);
  OX (nested_count_ = -1);
O
oceanbase-admin 已提交
5249 5250 5251
  return ret;
}

W
wangzelin.wzl 已提交
5252
int ObBasicSessionInfo::trans_restore_session(TransSavedValue &saved_value)
O
oceanbase-admin 已提交
5253 5254
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5255 5256 5257 5258 5259 5260 5261 5262
  OX (nested_count_ = saved_value.nested_count_);
  OX (trans_flags_ = saved_value.trans_flags_);
  /*
   * restore means switch to saved transaction context, drop current one.
   */
  OZ (tx_result_.assign(saved_value.tx_result_));
  OX (tx_desc_ = saved_value.tx_desc_);
  OZ (base_restore_session(saved_value));
O
oceanbase-admin 已提交
5263 5264 5265
  return ret;
}

W
wangzelin.wzl 已提交
5266
int ObBasicSessionInfo::begin_autonomous_session(TransSavedValue &saved_value)
O
oceanbase-admin 已提交
5267 5268 5269 5270
{
  return trans_save_session(saved_value);
}

W
wangzelin.wzl 已提交
5271
int ObBasicSessionInfo::end_autonomous_session(TransSavedValue &saved_value)
O
oceanbase-admin 已提交
5272 5273 5274 5275 5276 5277 5278
{
  return trans_restore_session(saved_value);
}

int ObBasicSessionInfo::set_start_stmt()
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5279 5280
  OV (nested_count_ == -1, OB_ERR_UNEXPECTED, nested_count_);
  OX (nested_count_ = 0);
O
oceanbase-admin 已提交
5281 5282 5283 5284 5285 5286
  return ret;
}

int ObBasicSessionInfo::set_end_stmt()
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5287 5288
  OV (nested_count_ == 0, OB_ERR_UNEXPECTED, nested_count_);
  OX (nested_count_ = -1);
O
oceanbase-admin 已提交
5289 5290 5291
  return ret;
}

W
wangzelin.wzl 已提交
5292
int ObBasicSessionInfo::init_stmt_tables()
O
oceanbase-admin 已提交
5293 5294
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5295
  if (!is_nested_session() && !is_fast_select()) {
O
oceanbase-admin 已提交
5296 5297 5298 5299
    // cur stmt is top stmt.
    total_stmt_tables_.reset();
    cur_stmt_tables_.reset();
  }
W
wangzelin.wzl 已提交
5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325
  return ret;
}

int ObBasicSessionInfo::check_stmt_table(uint64_t table_id, stmt::StmtType stmt_type)
{
  int ret = OB_SUCCESS;
  TableStmtType table_stmt_type(table_id, stmt_type);
  int64_t idx = -1;
  if (!is_nested_session() && !is_fast_select()) {
    // check nested stmt and fast select only, skip for top stmt.
    // fast select is used by cursor only NOW
  } else if (!is_foreign_key_cascade() && !is_foreign_key_check_exist()) {
    if (has_exist_in_array(total_stmt_tables_, table_stmt_type, &idx) &&
        0 <= idx && idx < total_stmt_tables_.count()) {
      if (total_stmt_tables_.at(idx).is_mutating()) {
        ObSchemaGetterGuard schema_guard;
        const ObTableSchema *table_schema = NULL;
        OZ (GCTX.schema_service_->get_tenant_schema_guard(
            effective_tenant_id_, schema_guard));
        OZ (schema_guard.get_table_schema(effective_tenant_id_, table_id, table_schema));
        CK (OB_NOT_NULL(table_schema));
        if (OB_SUCC(ret) && lib::is_mysql_mode()) {
          LOG_MYSQL_USER_ERROR(OB_ERR_MUTATING_TABLE_OPERATION, table_schema->get_table_name());
        }
        ret = OB_ERR_MUTATING_TABLE_OPERATION;
        LOG_WARN("table is mutating", K(table_stmt_type), K(ret));
O
oceanbase-admin 已提交
5326 5327 5328
      }
    }
  }
W
wangzelin.wzl 已提交
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 5371 5372 5373 5374 5375 5376 5377 5378 5379
  if (!need_serial_exec()) {
    // skip those stmts which will NOT execute nested stmt.
    // ps: need_serial_exec flag is introduced for nested stmt rollback.
  } else if (has_exist_in_array(cur_stmt_tables_, table_stmt_type, &idx) &&
             0 <= idx && idx < cur_stmt_tables_.count()) {
    // in dml plan, dml op and table scan op have same table_id, and they will both
    // call check_stmt_table(), so we need rewrite stmt_type if current is SELECT.
    if (cur_stmt_tables_.at(idx).get_stmt_type() == stmt::T_SELECT) {
      OX (cur_stmt_tables_.at(idx).set_stmt_type(stmt_type));
    }
  } else {
    OZ (cur_stmt_tables_.push_back(table_stmt_type), table_id, stmt_type);
  }
  return ret;
}

int ObBasicSessionInfo::merge_stmt_tables()
{
  int ret = OB_SUCCESS;
  int64_t idx = -1;
  for (int i = 0; OB_SUCC(ret) && i < cur_stmt_tables_.count(); i++) {
    idx = -1;
    OZ (add_var_to_array_no_dup(total_stmt_tables_, cur_stmt_tables_.at(i), &idx));
    if (0 <= idx && idx < total_stmt_tables_.count()) {
      OX (total_stmt_tables_.at(idx).set_stmt_type(cur_stmt_tables_.at(i).get_stmt_type()));
    }
  }
  return ret;
}

int ObBasicSessionInfo::skip_mutating(uint64_t table_id, stmt::StmtType &saved_stmt_type)
{
  int ret = OB_SUCCESS;
  int64_t idx = -1;
  TableStmtType table_stmt_type(table_id);
  if (has_exist_in_array(cur_stmt_tables_, table_stmt_type, &idx) &&
      0 <= idx && idx < cur_stmt_tables_.count()) {
    OX (cur_stmt_tables_.at(idx).skip_mutating(saved_stmt_type));
  }
  return ret;
}

int ObBasicSessionInfo::restore_mutating(uint64_t table_id, stmt::StmtType saved_stmt_type)
{
  int ret = OB_SUCCESS;
  int64_t idx = -1;
  TableStmtType table_stmt_type(table_id);
  if (has_exist_in_array(cur_stmt_tables_, table_stmt_type, &idx) &&
      0 <= idx && idx < cur_stmt_tables_.count()) {
    OX (cur_stmt_tables_.at(idx).restore_mutating(saved_stmt_type));
  }
O
oceanbase-admin 已提交
5380 5381 5382
  return ret;
}

W
wangzelin.wzl 已提交
5383 5384
int ObBasicSessionInfo::set_time_zone(const ObString &str_val, const bool is_oralce_mode,
                                     const bool check_timezone_valid)
O
oceanbase-admin 已提交
5385 5386 5387 5388
{
  int ret = OB_SUCCESS;
  int32_t offset = 0;
  int ret_more = OB_SUCCESS;
W
wangzelin.wzl 已提交
5389 5390 5391

  if (OB_FAIL(ObTimeConverter::str_to_offset(str_val, offset, ret_more,
                                                    is_oralce_mode, check_timezone_valid))) {
O
oceanbase-admin 已提交
5392 5393 5394 5395 5396 5397 5398 5399 5400
    if (ret != OB_ERR_UNKNOWN_TIME_ZONE) {
      LOG_WARN("fail to convert time zone", K(str_val), K(ret));
    }
  } else {
    tz_info_wrap_.set_tz_info_offset(offset);
  }

  if (OB_ERR_UNKNOWN_TIME_ZONE == ret) {
    ObTZMapWrap tz_map_wrap;
W
wangzelin.wzl 已提交
5401
    ObTimeZoneInfoManager *tz_info_mgr = NULL;
O
oceanbase-admin 已提交
5402 5403 5404 5405 5406
    if (OB_FAIL(OTTZ_MGR.get_tenant_timezone(tenant_id_, tz_map_wrap, tz_info_mgr))) {
      LOG_WARN("get tenant timezone with lock failed", K(ret));
    } else if (OB_ISNULL(tz_info_mgr)) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("tenant timezone mgr is null", K(tz_info_mgr));
W
wangzelin.wzl 已提交
5407
    } else {//此处需要先更新version,这样可以保证find到的tz_info version >= cur_version
O
oceanbase-admin 已提交
5408 5409 5410
      const int64_t orig_version = tz_info_wrap_.get_cur_version();
      tz_info_wrap_.set_cur_version(tz_info_mgr->get_version());
      ObCollationType coll_type = ObCharset::get_default_collation(ObCharset::get_default_charset());
W
wangzelin.wzl 已提交
5411 5412 5413
      int32_t no_sp_len = static_cast<int32_t>(ObCharset::strlen_byte_no_sp(coll_type,
                                                                            str_val.ptr(),
                                                                            str_val.length()));
O
oceanbase-admin 已提交
5414 5415 5416 5417
      ObString val_no_sp(no_sp_len, str_val.ptr());
      if (is_oralce_mode) {
        val_no_sp = val_no_sp.trim();
      }
W
wangzelin.wzl 已提交
5418
      //note:要先获取start service time;如果先find再获取start_service_time,start_service_time可能在这个时间窗口中被更改
O
oceanbase-admin 已提交
5419
      int64_t start_service_time = GCTX.start_service_time_;
W
wangzelin.wzl 已提交
5420 5421
      if (OB_FAIL(tz_info_mgr->find_time_zone_info(val_no_sp,
                                                   tz_info_wrap_.get_tz_info_pos()))) {
O
oceanbase-admin 已提交
5422 5423 5424 5425 5426 5427 5428 5429
        LOG_WARN("fail to find time zone", K(str_val), K(val_no_sp), K(ret));
        tz_info_wrap_.set_cur_version(orig_version);
      } else {
        tz_info_wrap_.set_tz_info_position();
      }

      if (OB_ERR_UNKNOWN_TIME_ZONE == ret) {
        if (0 == start_service_time) {
W
wangzelin.wzl 已提交
5430 5431 5432
          //代码执行到这里有两种情况:1)session的反序列化逻辑;2)系统租户的登陆流程
          //对于第二中情况,期待该session上的后续query会促使session更新timezone info,因此这里对timezone信息进行设置
          LOG_INFO("ignore unknow time zone, perhaps in remote/distribute task processer when server start_time is zero", K(str_val));
S
st0 已提交
5433 5434 5435 5436 5437 5438
          offset = 0;
          if (OB_FAIL(ObTimeConverter::str_to_offset(ObString("+8:00"), offset, ret_more,
                                                    is_oralce_mode, check_timezone_valid))) {
            if (ret != OB_ERR_UNKNOWN_TIME_ZONE) {
              LOG_WARN("fail to convert time zone", K(str_val), K(ret));
            }
O
oceanbase-admin 已提交
5439
          } else {
S
st0 已提交
5440
            tz_info_wrap_.set_tz_info_offset(offset);
O
oceanbase-admin 已提交
5441 5442 5443
          }
        }
      }
W
wangzelin.wzl 已提交
5444

O
oceanbase-admin 已提交
5445 5446 5447 5448 5449 5450 5451 5452 5453
    }
  }
  return ret;
}

int ObBasicSessionInfo::update_timezone_info()
{
  int ret = OB_SUCCESS;
  ObTZMapWrap tz_map_wrap;
W
wangzelin.wzl 已提交
5454
  ObTimeZoneInfoManager *tz_info_mgr = NULL;
O
oceanbase-admin 已提交
5455 5456 5457 5458 5459
  if (OB_FAIL(OTTZ_MGR.get_tenant_timezone(tenant_id_, tz_map_wrap, tz_info_mgr))) {
    LOG_WARN("get tenant timezone with lock failed", K(ret));
  } else if (OB_ISNULL(tz_info_mgr)) {
    ret = OB_ERR_UNEXPECTED;
    LOG_WARN("tenant timezone mgr is null", K(tz_info_mgr));
W
wangzelin.wzl 已提交
5460 5461
  } else if (OB_UNLIKELY(tz_info_wrap_.is_position_class()
              && tz_info_mgr->get_version() > tz_info_wrap_.get_cur_version())) {
O
oceanbase-admin 已提交
5462 5463 5464 5465 5466 5467
    ObString tz_name;
    if (OB_UNLIKELY(!tz_info_wrap_.get_tz_info_pos().is_valid())) {
      ret = OB_ERR_UNEXPECTED;
      LOG_WARN("time zone info is invalid", K(tz_info_wrap_.get_tz_info_pos()), K(ret));
    } else if (OB_FAIL(tz_info_wrap_.get_tz_info_pos().get_tz_name(tz_name))) {
      LOG_WARN("fal to get time zone name", K(tz_info_wrap_.get_tz_info_pos()), K(ret));
W
wangzelin.wzl 已提交
5468
    } else {//此处需要先更新version,这样可以保证find到的tz_info version >= cur_version
O
oceanbase-admin 已提交
5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489
      int64_t orig_version = tz_info_wrap_.get_cur_version();
      tz_info_wrap_.set_cur_version(tz_info_mgr->get_version());
      if (OB_FAIL(tz_info_mgr->find_time_zone_info(tz_name, tz_info_wrap_.get_tz_info_pos()))) {
        LOG_WARN("fail to find time zone info", K(tz_name), K(ret));
        tz_info_wrap_.set_cur_version(orig_version);
      } else {
        tz_info_wrap_.get_tz_info_pos().set_error_on_overlap_time(tz_info_wrap_.is_error_on_overlap_time());
      }
    }
  }
  return ret;
}

constexpr ObSysVarClassType ObExecEnv::ExecEnvMap[MAX_ENV + 1];

void ObExecEnv::reset()
{
  sql_mode_ = DEFAULT_OCEANBASE_MODE;
  charset_client_ = CS_TYPE_INVALID;
  collation_connection_ = CS_TYPE_INVALID;
  collation_database_ = CS_TYPE_INVALID;
W
wangzelin.wzl 已提交
5490
  plsql_ccflags_.reset();
O
oceanbase-admin 已提交
5491 5492
}

W
wangzelin.wzl 已提交
5493
bool ObExecEnv::operator==(const ObExecEnv &other) const
O
oceanbase-admin 已提交
5494
{
W
wangzelin.wzl 已提交
5495 5496 5497 5498 5499
  return sql_mode_ == other.sql_mode_
      && charset_client_ == other.charset_client_
      && collation_connection_ == other.collation_connection_
      && collation_database_ == other.collation_database_
      && plsql_ccflags_ == other.plsql_ccflags_;
O
oceanbase-admin 已提交
5500 5501
}

W
wangzelin.wzl 已提交
5502
bool ObExecEnv::operator!=(const ObExecEnv &other) const
O
oceanbase-admin 已提交
5503 5504 5505 5506
{
  return !(*this == other);
}

W
wangzelin.wzl 已提交
5507
int ObExecEnv::gen_exec_env(const ObBasicSessionInfo &session, char* buf, int64_t len, int64_t &pos)
O
oceanbase-admin 已提交
5508 5509 5510 5511
{
  int ret = OB_SUCCESS;
  ObObj val;
  for (int64_t i = 0; OB_SUCC(ret) && i < MAX_ENV; ++i) {
W
wangzelin.wzl 已提交
5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551
    switch (i) {
      case PLSQL_CCFLAGS: {
        if (lib::is_oracle_mode()) { // plsql_ccflags only in oracle mode!
          int64_t size = 0;
          val.reset();
          OZ (session.get_sys_variable(ExecEnvMap[i], val));
          // note: plsql_ccflags max length is 256 bytes, buffer size is 2048 bytes.
          ObString plsql_ccflags = val.get_varchar();
          // print length of plsql_ccflags
          OZ (databuff_printf(
            buf + pos, len - pos, size, "%d", static_cast<int32_t>(plsql_ccflags.length())));
          OX (pos += size);
          CK (pos < len);
          OX (buf[pos++] = ',');
          // print content of plsql_ccflags
          OX (size = 0);
          OZ (databuff_printf(buf + pos, len - pos, size, "%.*s",
                              static_cast<int32_t>(plsql_ccflags.length()), plsql_ccflags.ptr()));
          OX (pos += size);
          CK (pos < len);
          OX (buf[pos++] = ',');
        }
      } break;
      case SQL_MODE:
      case CHARSET_CLIENT:
      case COLLATION_CONNECTION:
      case COLLATION_DATABASE: {
        int64_t size = 0;
        val.reset();
        OZ (session.get_sys_variable(ExecEnvMap[i], val));
        OZ (val.print_plain_str_literal(buf + pos, len - pos, size));
        //输出间隔符
        OX (pos += size);
        CK (pos < len);
        OX (buf[pos++] = ',');
      } break;
      default: {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected evn type found!", K(ret), K(i));
      }
O
oceanbase-admin 已提交
5552 5553 5554 5555 5556
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5557 5558 5559 5560
int ObExecEnv::gen_exec_env(const share::schema::ObSysVariableSchema &sys_variable,
                            char* buf,
                            int64_t len,
                            int64_t &pos)
O
oceanbase-admin 已提交
5561 5562
{
  int ret = OB_SUCCESS;
W
wangzelin.wzl 已提交
5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620
  ObObj val;
  bool is_oracle_mode = false;
  if (OB_FAIL(sys_variable.get_oracle_mode(is_oracle_mode))) {
    LOG_WARN("failed to get oracle mode", K(ret));
  }
  for (int64_t i = 0; OB_SUCC(ret) && i < MAX_ENV; ++i) {
    const ObSysVarSchema *sysvar_schema = nullptr;
    switch (i) {
      case PLSQL_CCFLAGS: {
        if (is_oracle_mode) { // plsql_ccflags only in oracle mode!
          int64_t size = 0;
          if (OB_FAIL(sys_variable.get_sysvar_schema(ExecEnvMap[i], sysvar_schema))) {
            LOG_WARN("failed to get sysvar schema", K(ret));
          } else if (OB_ISNULL(sysvar_schema)) {
            ret = OB_ERR_UNEXPECTED;
            LOG_WARN("get unexpected null", K(ret), K(sysvar_schema));
          } else {
            ObString plsql_ccflags = sysvar_schema->get_value();
            // print length of plsql_ccflags
            OZ (databuff_printf(buf + pos, len - pos, size, "%d",
                                static_cast<int32_t>(plsql_ccflags.length())));
            OX (pos += size);
            CK (pos < len);
            OX (buf[pos++] = ',');
            // print content of plsql_ccflags
            OX (size = 0);
            OZ (databuff_printf(buf + pos, len - pos, size, "%.*s",
                                static_cast<int32_t>(plsql_ccflags.length()), plsql_ccflags.ptr()));
            OX (pos += size);
            CK (pos < len);
            OX (buf[pos++] = ',');
          }
        }
      } break;
      case SQL_MODE:
      case CHARSET_CLIENT:
      case COLLATION_CONNECTION:
      case COLLATION_DATABASE: {
        int64_t size = 0;
        if (OB_FAIL(sys_variable.get_sysvar_schema(ExecEnvMap[i], sysvar_schema))) {
          LOG_WARN("failed to get sysvar schema", K(ret));
        } else if (OB_ISNULL(sysvar_schema)) {
          ret = OB_ERR_UNEXPECTED;
          LOG_WARN("get unexpected null", K(ret), K(sysvar_schema));
        } else {
          ObString val = sysvar_schema->get_value();
          OZ (databuff_printf(buf + pos, len - pos, size, "%.*s",
                                                    static_cast<int32_t>(val.length()), val.ptr()));
          OX (pos += size);
          //输出间隔符
          CK (pos < len);
          OX (buf[pos++] = ',');
        }
      } break;
      default: {
        ret = OB_ERR_UNEXPECTED;
        LOG_WARN("unexpected evn type found!", K(ret), K(i));
      }
O
oceanbase-admin 已提交
5621 5622 5623 5624 5625
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636
#define GET_ENV_VALUE(start, value)                                           \
  do {                                                                        \
    const char *end = NULL;                                                   \
    value_str.reset();                                                        \
    if (!start.empty()) {                                                     \
      OX (end = start.find(','));                                             \
      CK (end != NULL);                                                       \
      OX (value.assign(                                                       \
        start.ptr(), static_cast<ObString::obstr_size_t>(end - start.ptr())));\
      OX (start = start.after(','));                                          \
    }                                                                         \
O
oceanbase-admin 已提交
5637 5638
  } while (0)

W
wangzelin.wzl 已提交
5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651
#define SET_ENV_VALUE(env, type)                                              \
  do {                                                                        \
    int64_t value = 0;                                                        \
    int64_t pos = 0;                                                          \
    if (OB_FAIL(ret)) {                                                       \
    } else if (OB_FAIL(extract_int(value_str, 0, pos, value))) {              \
      LOG_WARN("Failed to extract int", K(value_str), K(ret));                \
    } else {                                                                  \
      env = static_cast<type>(value);                                         \
    }                                                                         \
  } while (0)

int ObExecEnv::init(const ObString &exec_env)
O
oceanbase-admin 已提交
5652 5653 5654
{
  int ret = OB_SUCCESS;
  ObString value_str;
W
wangzelin.wzl 已提交
5655
  ObString start = exec_env;
O
oceanbase-admin 已提交
5656
  for (int64_t i = 0; OB_SUCC(ret) && i < MAX_ENV; ++i) {
W
wangzelin.wzl 已提交
5657 5658
    GET_ENV_VALUE(start, value_str);
    if (OB_SUCC(ret)) {
O
oceanbase-admin 已提交
5659
      switch (i) {
W
wangzelin.wzl 已提交
5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694
      case SQL_MODE: {
        SET_ENV_VALUE(sql_mode_, ObSQLMode);
      }
      break;
      case CHARSET_CLIENT: {
        SET_ENV_VALUE(charset_client_, ObCollationType);
      }
      break;
      case COLLATION_CONNECTION: {
        SET_ENV_VALUE(collation_connection_, ObCollationType);
      }
      break;
      case COLLATION_DATABASE: {
        SET_ENV_VALUE(collation_database_, ObCollationType);
      }
      break;
      case PLSQL_CCFLAGS: {
        if (start.empty()) {
          // do nothing, old routine object version do not have plsql_ccflags.
        } else {
          int32_t plsql_ccflags_length = 0;
          SET_ENV_VALUE(plsql_ccflags_length, int32_t);
          if (OB_FAIL(ret)) {
          } else if (plsql_ccflags_length > 0) {
            plsql_ccflags_.assign(start.ptr(), plsql_ccflags_length);
            start += plsql_ccflags_length + 1;// 1 for ','
          }
        }
      }
      break;
      default: {
        ret = common::OB_ERR_UNEXPECTED;
        LOG_WARN("Invalid env type", K(exec_env), K(i), K(ret));
      }
      break;
O
oceanbase-admin 已提交
5695 5696 5697 5698 5699 5700
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5701 5702 5703 5704
#undef SET_ENV_VALUE
#undef GET_ENV_VALUE

int ObExecEnv::load(ObBasicSessionInfo &session)
O
oceanbase-admin 已提交
5705 5706 5707 5708 5709
{
  int ret = OB_SUCCESS;
  ObObj val;
  for (int64_t i = 0; OB_SUCC(ret) && i < MAX_ENV; ++i) {
    val.reset();
W
wangzelin.wzl 已提交
5710 5711 5712
    if (lib::is_mysql_mode() && PLSQL_CCFLAGS == i) {
      // do nothing ...
    } else if (OB_FAIL(session.get_sys_variable(ExecEnvMap[i], val))) {
O
oceanbase-admin 已提交
5713 5714 5715
      LOG_WARN("failed to get sys_variable", K(ExecEnvMap[i]), K(ret));
    } else {
      switch (i) {
W
wangzelin.wzl 已提交
5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740
      case SQL_MODE: {
        sql_mode_ = static_cast<ObSQLMode>(val.get_int());
      }
      break;
      case CHARSET_CLIENT: {
        charset_client_ = static_cast<ObCollationType>(val.get_int());
      }
      break;
      case COLLATION_CONNECTION: {
        collation_connection_ = static_cast<ObCollationType>(val.get_int());
      }
      break;
      case COLLATION_DATABASE: {
        collation_database_ = static_cast<ObCollationType>(val.get_int());
      }
      break;
      case PLSQL_CCFLAGS: {
        plsql_ccflags_ = val.get_varchar();
      }
      break;
      default: {
        ret = common::OB_ERR_UNEXPECTED;
        LOG_WARN("Invalid env type", K(i), K(ret));
      }
      break;
O
oceanbase-admin 已提交
5741 5742 5743 5744 5745 5746
      }
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5747
int ObExecEnv::store(ObBasicSessionInfo &session)
O
oceanbase-admin 已提交
5748 5749 5750 5751 5752 5753
{
  int ret = OB_SUCCESS;
  ObObj val;
  for (int64_t i = 0; OB_SUCC(ret) && i < MAX_ENV; ++i) {
    val.reset();
    switch (i) {
W
wangzelin.wzl 已提交
5754 5755
    case SQL_MODE: {
      val.set_uint64(sql_mode_);
O
oceanbase-admin 已提交
5756
    }
W
wangzelin.wzl 已提交
5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785
    break;
    case CHARSET_CLIENT: {
      val.set_int(charset_client_);
    }
    break;
    case COLLATION_CONNECTION: {
      val.set_int(collation_connection_);
    }
    break;
    case COLLATION_DATABASE: {
      val.set_int(collation_database_);
    }
    break;
    case PLSQL_CCFLAGS: {
      val.set_varchar(plsql_ccflags_);
      val.set_collation_type(ObCharset::get_system_collation());
    }
    break;
    default: {
      ret = common::OB_ERR_UNEXPECTED;
      LOG_WARN("Invalid env type", K(i), K(ret));
    }
    break;
    }
    if (OB_FAIL(ret)) {
    } else if (lib::is_mysql_mode() && PLSQL_CCFLAGS == i) {
      // do nothing ...
    } else if (OB_FAIL(session.update_sys_variable(ExecEnvMap[i], val))) {
      LOG_WARN("failed to get sys_variable", K(ExecEnvMap[i]), K(ret));
O
oceanbase-admin 已提交
5786 5787 5788 5789 5790
    }
  }
  return ret;
}

W
wangzelin.wzl 已提交
5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808
void ObBasicSessionInfo::on_get_session()
{
  const char *str = lbt();
  int len = STRLEN(str);
  if (sess_bt_buff_pos_ + len + 2 < MAX_SESS_BT_BUFF_SIZE) {
    MEMCPY(sess_bt_buff_ + sess_bt_buff_pos_, str, len);
    sess_bt_buff_pos_ += len;
    sess_bt_buff_[sess_bt_buff_pos_] = ';';
    sess_bt_buff_pos_ += 1;
    sess_bt_buff_[sess_bt_buff_pos_] = '\0';
  }
  (void)ATOMIC_AAF(&sess_ref_cnt_, 1);
  (void)ATOMIC_AAF(&sess_ref_seq_, 1);
  LOG_INFO("on get session", KP(this), K(sess_ref_cnt_), K(sess_ref_seq_),
                             K(sessid_), "backtrace", ObString(len, str));
}

void ObBasicSessionInfo::on_revert_session()
5809
{
W
wangzelin.wzl 已提交
5810 5811 5812 5813
  int32_t v = ATOMIC_AAF(&sess_ref_cnt_, -1);
  if (v <= 0) {
    sess_bt_buff_pos_ = 0;
    sess_bt_buff_[0] = '\0';
5814
  }
W
wangzelin.wzl 已提交
5815 5816
  LOG_INFO("on revert session", KP(this), K(sess_ref_cnt_), K(sess_ref_seq_),
                                K(sessid_), "backtrace", lbt());
5817 5818
}

W
wangzelin.wzl 已提交
5819 5820
}//end of namespace sql
}//end of namespace oceanbase