sysscanoperator.c 80.0 KB
Newer Older
H
Haojun Liao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

16
#include "executorInt.h"
H
Haojun Liao 已提交
17 18 19 20 21 22 23 24 25 26 27
#include "filter.h"
#include "function.h"
#include "functionMgt.h"
#include "os.h"
#include "querynodes.h"
#include "systable.h"
#include "tname.h"

#include "tdatablock.h"
#include "tmsg.h"

28
#include "index.h"
29
#include "operator.h"
H
Haojun Liao 已提交
30
#include "query.h"
31 32
#include "querytask.h"
#include "storageapi.h"
H
Haojun Liao 已提交
33 34 35 36 37 38 39 40 41
#include "tcompare.h"
#include "thash.h"
#include "ttypes.h"

typedef int (*__optSysFilter)(void* a, void* b, int16_t dtype);
typedef int32_t (*__sys_filte)(void* pMeta, SNode* cond, SArray* result);
typedef int32_t (*__sys_check)(SNode* cond);

typedef struct SSTabFltArg {
42 43 44
  void*        pMeta;
  void*        pVnode;
  SStorageAPI* pAPI;
H
Haojun Liao 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
} SSTabFltArg;

typedef struct SSysTableIndex {
  int8_t  init;
  SArray* uids;
  int32_t lastIdx;
} SSysTableIndex;

typedef struct SSysTableScanInfo {
  SRetrieveMetaTableRsp* pRsp;
  SRetrieveTableReq      req;
  SEpSet                 epSet;
  tsem_t                 ready;
  SReadHandle            readHandle;
  int32_t                accountId;
  const char*            pUser;
  bool                   sysInfo;
  bool                   showRewrite;
K
kailixu 已提交
63
  bool                   restore;
H
Haojun Liao 已提交
64 65 66
  SNode*                 pCondition;  // db_name filter condition, to discard data that are not in current database
  SMTbCursor*            pCur;        // cursor for iterate the local table meta store.
  SSysTableIndex*        pIdx;        // idx for local table meta
K
kailixu 已提交
67
  SHashObj*              pSchema;
H
Haojun Liao 已提交
68 69 70 71 72
  SColMatchInfo          matchInfo;
  SName                  name;
  SSDataBlock*           pRes;
  int64_t                numOfBlocks;  // extract basic running information.
  SLoadRemoteDataInfo    loadInfo;
73
  SLimitInfo             limitInfo;
S
slzhou 已提交
74
  int32_t                tbnameSlotId;
75
  SStorageAPI*           pAPI;
H
Haojun Liao 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88
} SSysTableScanInfo;

typedef struct {
  const char* name;
  __sys_check chkFunc;
  __sys_filte fltFunc;
} SSTabFltFuncDef;

typedef struct MergeIndex {
  int idx;
  int len;
} MergeIndex;

H
Haojun Liao 已提交
89
typedef struct SBlockDistInfo {
90 91 92 93 94
  SSDataBlock*    pResBlock;
  STsdbReader*    pHandle;
  SReadHandle     readHandle;
  STableListInfo* pTableListInfo;
  uint64_t        uid;  // table uid
H
Haojun Liao 已提交
95 96
} SBlockDistInfo;

H
Haojun Liao 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
static int32_t sysChkFilter__Comm(SNode* pNode);
static int32_t sysChkFilter__DBName(SNode* pNode);
static int32_t sysChkFilter__VgroupId(SNode* pNode);
static int32_t sysChkFilter__TableName(SNode* pNode);
static int32_t sysChkFilter__CreateTime(SNode* pNode);
static int32_t sysChkFilter__Ncolumn(SNode* pNode);
static int32_t sysChkFilter__Ttl(SNode* pNode);
static int32_t sysChkFilter__STableName(SNode* pNode);
static int32_t sysChkFilter__Uid(SNode* pNode);
static int32_t sysChkFilter__Type(SNode* pNode);

static int32_t sysFilte__DbName(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__VgroupId(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__TableName(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__CreateTime(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Ncolumn(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Ttl(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__STableName(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Uid(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Type(void* arg, SNode* pNode, SArray* result);

const SSTabFltFuncDef filterDict[] = {
    {.name = "table_name", .chkFunc = sysChkFilter__TableName, .fltFunc = sysFilte__TableName},
    {.name = "db_name", .chkFunc = sysChkFilter__DBName, .fltFunc = sysFilte__DbName},
    {.name = "create_time", .chkFunc = sysChkFilter__CreateTime, .fltFunc = sysFilte__CreateTime},
    {.name = "columns", .chkFunc = sysChkFilter__Ncolumn, .fltFunc = sysFilte__Ncolumn},
    {.name = "ttl", .chkFunc = sysChkFilter__Ttl, .fltFunc = sysFilte__Ttl},
    {.name = "stable_name", .chkFunc = sysChkFilter__STableName, .fltFunc = sysFilte__STableName},
    {.name = "vgroup_id", .chkFunc = sysChkFilter__VgroupId, .fltFunc = sysFilte__VgroupId},
    {.name = "uid", .chkFunc = sysChkFilter__Uid, .fltFunc = sysFilte__Uid},
    {.name = "type", .chkFunc = sysChkFilter__Type, .fltFunc = sysFilte__Type}};

#define SYSTAB_FILTER_DICT_SIZE (sizeof(filterDict) / sizeof(filterDict[0]))

static int32_t buildDbTableInfoBlock(bool sysInfo, const SSDataBlock* p, const SSysTableMeta* pSysDbTableMeta,
                                     size_t size, const char* dbName);

static char* SYSTABLE_IDX_COLUMN[] = {"table_name", "db_name",     "create_time",      "columns",
                                      "ttl",        "stable_name", "vgroup_id', 'uid", "type"};

static char* SYSTABLE_SPECIAL_COL[] = {"db_name", "vgroup_id"};

X
Xiaoyu Wang 已提交
139 140 141 142
static int32_t        buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity);
static SSDataBlock*   buildInfoSchemaTableMetaBlock(char* tableName);
static void           destroySysScanOperator(void* param);
static int32_t        loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code);
dengyihao's avatar
dengyihao 已提交
143
static __optSysFilter optSysGetFilterFunc(int32_t ctype, bool* reverse, bool* equal);
H
Haojun Liao 已提交
144 145 146 147 148

static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock);

X
Xiaoyu Wang 已提交
149 150 151
static int32_t sysTableUserColsFillOneTableCols(const SSysTableScanInfo* pInfo, const char* dbname, int32_t* pNumOfRows,
                                                const SSDataBlock* dataBlock, char* tName, SSchemaWrapper* schemaRow,
                                                char* tableType);
152

H
Haojun Liao 已提交
153 154 155 156
static void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock,
                                               SFilterInfo* pFilterInfo);

int32_t sysFilte__DbName(void* arg, SNode* pNode, SArray* result) {
157 158
  SSTabFltArg* pArg = arg;
  void*        pVnode = pArg->pVnode;
H
Haojun Liao 已提交
159 160

  const char* db = NULL;
161
  pArg->pAPI->metaFn.getBasicInfo(pVnode, &db, NULL, NULL, NULL);
H
Haojun Liao 已提交
162 163 164 165 166 167 168 169 170 171 172 173

  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

  bool           reverse = false;
dengyihao's avatar
dengyihao 已提交
174 175
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
176 177 178 179 180 181 182 183 184
  if (func == NULL) return -1;

  int ret = func(dbname, pVal->datum.p, TSDB_DATA_TYPE_VARCHAR);
  if (ret == 0) return 0;

  return -2;
}

int32_t sysFilte__VgroupId(void* arg, SNode* pNode, SArray* result) {
185 186
  SSTabFltArg* pArg = arg;
  void*        pVnode = ((SSTabFltArg*)arg)->pVnode;
H
Haojun Liao 已提交
187 188

  int64_t vgId = 0;
189
  pArg->pAPI->metaFn.getBasicInfo(pVnode, NULL, (int32_t*)&vgId, NULL, NULL);
H
Haojun Liao 已提交
190 191 192 193

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
194 195 196
  bool           reverse = false;
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
197 198 199 200 201 202 203 204 205
  if (func == NULL) return -1;

  int ret = func(&vgId, &pVal->datum.i, TSDB_DATA_TYPE_BIGINT);
  if (ret == 0) return 0;

  return -1;
}

int32_t sysFilte__TableName(void* arg, SNode* pNode, SArray* result) {
206
  SSTabFltArg* pArg = arg;
H
Haojun Liao 已提交
207 208 209 210

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
211
  bool           reverse = false, equal = false;
dengyihao's avatar
dengyihao 已提交
212
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
213 214 215
  if (func == NULL) return -1;

  SMetaFltParam param = {.suid = 0,
X
Xiaoyu Wang 已提交
216 217 218 219
                         .cid = 0,
                         .type = TSDB_DATA_TYPE_VARCHAR,
                         .val = pVal->datum.p,
                         .reverse = reverse,
dengyihao's avatar
dengyihao 已提交
220
                         .equal = equal,
X
Xiaoyu Wang 已提交
221
                         .filterFunc = func};
H
Haojun Liao 已提交
222 223 224 225
  return -1;
}

int32_t sysFilte__CreateTime(void* arg, SNode* pNode, SArray* result) {
226 227
  SSTabFltArg* pArg = arg;
  SStorageAPI* pAPI = pArg->pAPI;
H
Haojun Liao 已提交
228 229 230 231

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
232
  bool           reverse = false, equal = false;
dengyihao's avatar
dengyihao 已提交
233
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
234 235 236
  if (func == NULL) return -1;

  SMetaFltParam param = {.suid = 0,
X
Xiaoyu Wang 已提交
237 238 239 240
                         .cid = 0,
                         .type = TSDB_DATA_TYPE_BIGINT,
                         .val = &pVal->datum.i,
                         .reverse = reverse,
dengyihao's avatar
dengyihao 已提交
241
                         .equal = equal,
X
Xiaoyu Wang 已提交
242
                         .filterFunc = func};
H
Haojun Liao 已提交
243

244 245
  int32_t ret = pAPI->metaFilter.metaFilterCreateTime(pArg->pVnode, &param, result);
  return ret;
H
Haojun Liao 已提交
246 247 248 249 250 251 252 253
}

int32_t sysFilte__Ncolumn(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;
dengyihao's avatar
dengyihao 已提交
254 255
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
256 257 258 259 260 261 262 263 264 265
  if (func == NULL) return -1;
  return -1;
}

int32_t sysFilte__Ttl(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;
dengyihao's avatar
dengyihao 已提交
266 267
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
268 269 270 271 272 273 274 275 276 277
  if (func == NULL) return -1;
  return -1;
}

int32_t sysFilte__STableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;
dengyihao's avatar
dengyihao 已提交
278 279
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
280 281 282 283 284 285 286 287 288 289
  if (func == NULL) return -1;
  return -1;
}

int32_t sysFilte__Uid(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;
dengyihao's avatar
dengyihao 已提交
290 291
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
292 293 294 295 296 297 298 299 300 301
  if (func == NULL) return -1;
  return -1;
}

int32_t sysFilte__Type(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;
dengyihao's avatar
dengyihao 已提交
302 303
  bool           equal = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse, &equal);
H
Haojun Liao 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  if (func == NULL) return -1;
  return -1;
}

int optSysDoCompare(__compar_fn_t func, int8_t comparType, void* a, void* b) {
  int32_t cmp = func(a, b);
  switch (comparType) {
    case OP_TYPE_LOWER_THAN:
      if (cmp < 0) return 0;
      break;
    case OP_TYPE_LOWER_EQUAL: {
      if (cmp <= 0) return 0;
      break;
    }
    case OP_TYPE_GREATER_THAN: {
      if (cmp > 0) return 0;
      break;
    }
    case OP_TYPE_GREATER_EQUAL: {
      if (cmp >= 0) return 0;
      break;
    }
    case OP_TYPE_EQUAL: {
      if (cmp == 0) return 0;
      break;
    }
    default:
      return -1;
  }
  return cmp;
}

static int optSysFilterFuncImpl__LowerThan(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_LOWER_THAN, a, b);
}
static int optSysFilterFuncImpl__LowerEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_LOWER_EQUAL, a, b);
}
static int optSysFilterFuncImpl__GreaterThan(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_GREATER_THAN, a, b);
}
static int optSysFilterFuncImpl__GreaterEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_GREATER_EQUAL, a, b);
}
static int optSysFilterFuncImpl__Equal(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_EQUAL, a, b);
}

static int optSysFilterFuncImpl__NoEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_NOT_EQUAL, a, b);
}

static int32_t optSysTabFilte(void* arg, SNode* cond, SArray* result);
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result);
static int32_t optSysCheckOper(SNode* pOpear);
static int32_t optSysMergeRslt(SArray* mRslt, SArray* rslt);

S
slzhou 已提交
367 368 369
static SSDataBlock* sysTableScanFromMNode(SOperatorInfo* pOperator, SSysTableScanInfo* pInfo, const char* name,
                                          SExecTaskInfo* pTaskInfo);
void                extractTbnameSlotId(SSysTableScanInfo* pInfo, const SScanPhysiNode* pScanNode);
X
Xiaoyu Wang 已提交
370 371 372 373

static void sysTableScanFillTbName(SOperatorInfo* pOperator, const SSysTableScanInfo* pInfo, const char* name,
                                   SSDataBlock* pBlock);

dengyihao's avatar
dengyihao 已提交
374
__optSysFilter optSysGetFilterFunc(int32_t ctype, bool* reverse, bool* equal) {
H
Haojun Liao 已提交
375 376 377
  if (ctype == OP_TYPE_LOWER_EQUAL || ctype == OP_TYPE_LOWER_THAN) {
    *reverse = true;
  }
dengyihao's avatar
dengyihao 已提交
378 379 380
  if (ctype == OP_TYPE_EQUAL) {
    *equal = true;
  }
H
Haojun Liao 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  if (ctype == OP_TYPE_LOWER_THAN)
    return optSysFilterFuncImpl__LowerThan;
  else if (ctype == OP_TYPE_LOWER_EQUAL)
    return optSysFilterFuncImpl__LowerEqual;
  else if (ctype == OP_TYPE_GREATER_THAN)
    return optSysFilterFuncImpl__GreaterThan;
  else if (ctype == OP_TYPE_GREATER_EQUAL)
    return optSysFilterFuncImpl__GreaterEqual;
  else if (ctype == OP_TYPE_EQUAL)
    return optSysFilterFuncImpl__Equal;
  else if (ctype == OP_TYPE_NOT_EQUAL)
    return optSysFilterFuncImpl__NoEqual;
  return NULL;
}

static bool sysTableIsOperatorCondOnOneTable(SNode* pCond, char* condTable) {
  SOperatorNode* node = (SOperatorNode*)pCond;
  if (node->opType == OP_TYPE_EQUAL) {
    if (nodeType(node->pLeft) == QUERY_NODE_COLUMN &&
        strcasecmp(nodesGetNameFromColumnNode(node->pLeft), "table_name") == 0 &&
        nodeType(node->pRight) == QUERY_NODE_VALUE) {
      SValueNode* pValue = (SValueNode*)node->pRight;
      if (pValue->node.resType.type == TSDB_DATA_TYPE_NCHAR || pValue->node.resType.type == TSDB_DATA_TYPE_VARCHAR ||
          pValue->node.resType.type == TSDB_DATA_TYPE_BINARY) {
        char* value = nodesGetValueFromNode(pValue);
        strncpy(condTable, varDataVal(value), TSDB_TABLE_NAME_LEN);
        return true;
      }
    }
  }
  return false;
}

static bool sysTableIsCondOnOneTable(SNode* pCond, char* condTable) {
  if (pCond == NULL) {
    return false;
  }
  if (nodeType(pCond) == QUERY_NODE_LOGIC_CONDITION) {
    SLogicConditionNode* node = (SLogicConditionNode*)pCond;
    if (LOGIC_COND_TYPE_AND == node->condType) {
      SNode* pChild = NULL;
      FOREACH(pChild, node->pParameterList) {
        if (QUERY_NODE_OPERATOR == nodeType(pChild) && sysTableIsOperatorCondOnOneTable(pChild, condTable)) {
          return true;
        }
      }
    }
  }

  if (QUERY_NODE_OPERATOR == nodeType(pCond)) {
    return sysTableIsOperatorCondOnOneTable(pCond, condTable);
  }

  return false;
}

437
static SSDataBlock* sysTableScanUserCols(SOperatorInfo* pOperator) {
438 439 440
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;

441 442 443 444 445 446 447 448 449
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;

  SSDataBlock* dataBlock = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_COLS);
450
  blockDataEnsureCapacity(dataBlock, pOperator->resultInfo.capacity);
451 452 453

  const char* db = NULL;
  int32_t     vgId = 0;
454
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
455 456 457 458 459 460 461 462 463

  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));

  // optimize when sql like where table_name='tablename' and xxx.
wmmhello's avatar
wmmhello 已提交
464
  if (pInfo->req.filterTb[0]) {
465
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
wmmhello's avatar
wmmhello 已提交
466
    STR_TO_VARSTR(tableName, pInfo->req.filterTb);
467

468
    SMetaReader smrTable = {0};
H
Haojun Liao 已提交
469
    pAPI->metaReaderFn.initReader(&smrTable, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
470
    int32_t code = pAPI->metaReaderFn.getTableEntryByName(&smrTable, pInfo->req.filterTb);
471
    if (code != TSDB_CODE_SUCCESS) {
472 473
      // terrno has been set by pAPI->metaReaderFn.getTableEntryByName, therefore, return directly
      pAPI->metaReaderFn.clearReader(&smrTable);
474 475 476 477 478
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
      return NULL;
    }

wmmhello's avatar
wmmhello 已提交
479
    if (smrTable.me.type == TSDB_SUPER_TABLE) {
480
      pAPI->metaReaderFn.clearReader(&smrTable);
481 482 483 484 485
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
      return NULL;
    }

wmmhello's avatar
wmmhello 已提交
486 487
    if (smrTable.me.type == TSDB_CHILD_TABLE) {
      int64_t suid = smrTable.me.ctbEntry.suid;
488
      pAPI->metaReaderFn.clearReader(&smrTable);
H
Haojun Liao 已提交
489
      pAPI->metaReaderFn.initReader(&smrTable, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
490
      code = pAPI->metaReaderFn.getTableEntryByUid(&smrTable, suid);
wmmhello's avatar
wmmhello 已提交
491
      if (code != TSDB_CODE_SUCCESS) {
492 493
        // terrno has been set by pAPI->metaReaderFn.getTableEntryByName, therefore, return directly
        pAPI->metaReaderFn.clearReader(&smrTable);
wmmhello's avatar
wmmhello 已提交
494 495 496 497 498 499
        blockDataDestroy(dataBlock);
        pInfo->loadInfo.totalRows = 0;
        return NULL;
      }
    }

X
Xiaoyu Wang 已提交
500 501 502 503
    char            typeName[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
    SSchemaWrapper* schemaRow = NULL;
    if (smrTable.me.type == TSDB_SUPER_TABLE) {
      schemaRow = &smrTable.me.stbEntry.schemaRow;
wmmhello's avatar
wmmhello 已提交
504
      STR_TO_VARSTR(typeName, "CHILD_TABLE");
X
Xiaoyu Wang 已提交
505 506
    } else if (smrTable.me.type == TSDB_NORMAL_TABLE) {
      schemaRow = &smrTable.me.ntbEntry.schemaRow;
wmmhello's avatar
wmmhello 已提交
507 508 509 510
      STR_TO_VARSTR(typeName, "NORMAL_TABLE");
    }

    sysTableUserColsFillOneTableCols(pInfo, dbname, &numOfRows, dataBlock, tableName, schemaRow, typeName);
511
    pAPI->metaReaderFn.clearReader(&smrTable);
512 513 514 515 516 517 518 519 520 521 522 523 524

    if (numOfRows > 0) {
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
      numOfRows = 0;
    }
    blockDataDestroy(dataBlock);
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
    setOperatorCompleted(pOperator);
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  }

  int32_t ret = 0;
  if (pInfo->pCur == NULL) {
525
    pInfo->pCur = pAPI->metaFn.openTableMetaCursor(pInfo->readHandle.vnode);
526 527
  }

K
kailixu 已提交
528 529 530 531 532
  if (pInfo->pSchema == NULL) {
    pInfo->pSchema = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
    taosHashSetFreeFp(pInfo->pSchema, tDeleteSSchemaWrapperForHash);
  }

K
kailixu 已提交
533 534 535 536 537 538 539 540
  if (!pInfo->pCur || !pInfo->pSchema) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    qError("sysTableScanUserCols failed since %s", terrstr(terrno));
    blockDataDestroy(dataBlock);
    pInfo->loadInfo.totalRows = 0;
    return NULL;
  }

K
kailixu 已提交
541 542
  int32_t restore = pInfo->restore;
  pInfo->restore = false;
543

544 545 546 547
  while (restore || ((ret = pAPI->metaFn.cursorNext(pInfo->pCur, TSDB_TABLE_MAX)) == 0)) {
    if (restore) {
      restore = false;
    }
548

wmmhello's avatar
wmmhello 已提交
549 550 551
    char typeName[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};

X
Xiaoyu Wang 已提交
552
    SSchemaWrapper* schemaRow = NULL;
wmmhello's avatar
wmmhello 已提交
553

X
Xiaoyu Wang 已提交
554
    if (pInfo->pCur->mr.me.type == TSDB_SUPER_TABLE) {
wmmhello's avatar
wmmhello 已提交
555
      qDebug("sysTableScanUserCols cursor get super table");
K
kailixu 已提交
556
      void* schema = taosHashGet(pInfo->pSchema, &pInfo->pCur->mr.me.uid, sizeof(int64_t));
X
Xiaoyu Wang 已提交
557 558
      if (schema == NULL) {
        SSchemaWrapper* schemaWrapper = tCloneSSchemaWrapper(&pInfo->pCur->mr.me.stbEntry.schemaRow);
K
kailixu 已提交
559
        taosHashPut(pInfo->pSchema, &pInfo->pCur->mr.me.uid, sizeof(int64_t), &schemaWrapper, POINTER_BYTES);
wmmhello's avatar
wmmhello 已提交
560 561
      }
      continue;
X
Xiaoyu Wang 已提交
562
    } else if (pInfo->pCur->mr.me.type == TSDB_CHILD_TABLE) {
wmmhello's avatar
wmmhello 已提交
563
      qDebug("sysTableScanUserCols cursor get child table");
wmmhello's avatar
wmmhello 已提交
564 565 566
      STR_TO_VARSTR(typeName, "CHILD_TABLE");
      STR_TO_VARSTR(tableName, pInfo->pCur->mr.me.name);
      int64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
K
kailixu 已提交
567
      void*   schema = taosHashGet(pInfo->pSchema, &pInfo->pCur->mr.me.ctbEntry.suid, sizeof(int64_t));
X
Xiaoyu Wang 已提交
568 569 570
      if (schema != NULL) {
        schemaRow = *(SSchemaWrapper**)schema;
      } else {
K
kailixu 已提交
571
        SMetaReader smrSuperTable = {0};
H
Haojun Liao 已提交
572
        pAPI->metaReaderFn.initReader(&smrSuperTable, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
573
        int code = pAPI->metaReaderFn.getTableEntryByUid(&smrSuperTable, suid);
wmmhello's avatar
wmmhello 已提交
574
        if (code != TSDB_CODE_SUCCESS) {
575
          // terrno has been set by pAPI->metaReaderFn.getTableEntryByName, therefore, return directly
X
Xiaoyu Wang 已提交
576
          qError("sysTableScanUserCols get meta by suid:%" PRId64 " error, code:%d", suid, code);
577
          pAPI->metaReaderFn.clearReader(&smrSuperTable);
wmmhello's avatar
wmmhello 已提交
578 579 580 581
          blockDataDestroy(dataBlock);
          pInfo->loadInfo.totalRows = 0;
          return NULL;
        }
K
kailixu 已提交
582
        SSchemaWrapper* schemaWrapper = tCloneSSchemaWrapper(&smrSuperTable.me.stbEntry.schemaRow);
K
kailixu 已提交
583 584
        taosHashPut(pInfo->pSchema, &suid, sizeof(int64_t), &schemaWrapper, POINTER_BYTES);
        schemaRow = schemaWrapper;
585
        pAPI->metaReaderFn.clearReader(&smrSuperTable);
wmmhello's avatar
wmmhello 已提交
586
      }
X
Xiaoyu Wang 已提交
587
    } else if (pInfo->pCur->mr.me.type == TSDB_NORMAL_TABLE) {
wmmhello's avatar
wmmhello 已提交
588
      qDebug("sysTableScanUserCols cursor get normal table");
X
Xiaoyu Wang 已提交
589
      schemaRow = &pInfo->pCur->mr.me.ntbEntry.schemaRow;
wmmhello's avatar
wmmhello 已提交
590 591
      STR_TO_VARSTR(typeName, "NORMAL_TABLE");
      STR_TO_VARSTR(tableName, pInfo->pCur->mr.me.name);
X
Xiaoyu Wang 已提交
592
    } else {
wmmhello's avatar
wmmhello 已提交
593
      qDebug("sysTableScanUserCols cursor get invalid table");
594 595 596
      continue;
    }

K
kailixu 已提交
597
    if ((numOfRows + schemaRow->nCols) > pOperator->resultInfo.capacity) {
598 599
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
      numOfRows = 0;
K
kailixu 已提交
600
      pInfo->restore = true;
601

602 603 604
      if (pInfo->pRes->info.rows > 0) {
        break;
      }
K
kailixu 已提交
605 606
    } else {
      sysTableUserColsFillOneTableCols(pInfo, dbname, &numOfRows, dataBlock, tableName, schemaRow, typeName);
607 608 609 610 611 612 613 614 615 616
    }
  }

  if (numOfRows > 0) {
    relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
    numOfRows = 0;
  }

  blockDataDestroy(dataBlock);
  if (ret != 0) {
617
    pAPI->metaFn.closeTableMetaCursor(pInfo->pCur);
618 619 620 621 622
    pInfo->pCur = NULL;
    setOperatorCompleted(pOperator);
  }

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
wmmhello's avatar
wmmhello 已提交
623 624
  qDebug("sysTableScanUserCols get cols success, rows:%" PRIu64, pInfo->loadInfo.totalRows);

625 626 627
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

H
Haojun Liao 已提交
628
static SSDataBlock* sysTableScanUserTags(SOperatorInfo* pOperator) {
629 630
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;
631

H
Haojun Liao 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;

  SSDataBlock* dataBlock = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TAGS);
  blockDataEnsureCapacity(dataBlock, pOperator->resultInfo.capacity);

  const char* db = NULL;
  int32_t     vgId = 0;
645
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
H
Haojun Liao 已提交
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));

  char condTableName[TSDB_TABLE_NAME_LEN] = {0};
  // optimize when sql like where table_name='tablename' and xxx.
  if (pInfo->pCondition && sysTableIsCondOnOneTable(pInfo->pCondition, condTableName)) {
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tableName, condTableName);

    SMetaReader smrChildTable = {0};
H
Haojun Liao 已提交
661
    pAPI->metaReaderFn.initReader(&smrChildTable, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
662
    int32_t code = pAPI->metaReaderFn.getTableEntryByName(&smrChildTable, condTableName);
H
Haojun Liao 已提交
663
    if (code != TSDB_CODE_SUCCESS) {
664 665
      // terrno has been set by pAPI->metaReaderFn.getTableEntryByName, therefore, return directly
      pAPI->metaReaderFn.clearReader(&smrChildTable);
H
Haojun Liao 已提交
666 667
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
H
Haojun Liao 已提交
668 669 670 671
      return NULL;
    }

    if (smrChildTable.me.type != TSDB_CHILD_TABLE) {
672
      pAPI->metaReaderFn.clearReader(&smrChildTable);
H
Haojun Liao 已提交
673 674 675 676 677 678
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
      return NULL;
    }

    SMetaReader smrSuperTable = {0};
H
Haojun Liao 已提交
679
    pAPI->metaReaderFn.initReader(&smrSuperTable, pInfo->readHandle.vnode, META_READER_NOLOCK, &pAPI->metaFn);
680
    code = pAPI->metaReaderFn.getTableEntryByUid(&smrSuperTable, smrChildTable.me.ctbEntry.suid);
H
Haojun Liao 已提交
681
    if (code != TSDB_CODE_SUCCESS) {
682 683 684
      // terrno has been set by pAPI->metaReaderFn.getTableEntryByUid
      pAPI->metaReaderFn.clearReader(&smrSuperTable);
      pAPI->metaReaderFn.clearReader(&smrChildTable);
H
Haojun Liao 已提交
685
      blockDataDestroy(dataBlock);
H
Haojun Liao 已提交
686 687 688 689
      return NULL;
    }

    sysTableUserTagsFillOneTableTags(pInfo, &smrSuperTable, &smrChildTable, dbname, tableName, &numOfRows, dataBlock);
690 691
    pAPI->metaReaderFn.clearReader(&smrSuperTable);
    pAPI->metaReaderFn.clearReader(&smrChildTable);
H
Haojun Liao 已提交
692

H
Haojun Liao 已提交
693 694 695 696 697 698 699 700 701 702 703 704
    if (numOfRows > 0) {
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
      numOfRows = 0;
    }
    blockDataDestroy(dataBlock);
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
    setOperatorCompleted(pOperator);
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  }

  int32_t ret = 0;
  if (pInfo->pCur == NULL) {
705
    pInfo->pCur = pAPI->metaFn.openTableMetaCursor(pInfo->readHandle.vnode);
H
Haojun Liao 已提交
706 707
  }

708
  bool blockFull = false;
709
  while ((ret = pAPI->metaFn.cursorNext(pInfo->pCur, TSDB_SUPER_TABLE)) == 0) {
H
Haojun Liao 已提交
710 711 712 713 714 715 716 717
    if (pInfo->pCur->mr.me.type != TSDB_CHILD_TABLE) {
      continue;
    }

    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tableName, pInfo->pCur->mr.me.name);

    SMetaReader smrSuperTable = {0};
H
Haojun Liao 已提交
718
    pAPI->metaReaderFn.initReader(&smrSuperTable, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
H
Haojun Liao 已提交
719
    uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
720
    int32_t  code = pAPI->metaReaderFn.getTableEntryByUid(&smrSuperTable, suid);
H
Haojun Liao 已提交
721 722 723
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get super table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
724
      pAPI->metaReaderFn.clearReader(&smrSuperTable);
725
      pAPI->metaFn.closeTableMetaCursor(pInfo->pCur);
H
Haojun Liao 已提交
726 727 728 729
      pInfo->pCur = NULL;
      T_LONG_JMP(pTaskInfo->env, terrno);
    }

730
    if ((smrSuperTable.me.stbEntry.schemaTag.nCols + numOfRows) > pOperator->resultInfo.capacity) {
731
      pAPI->metaFn.cursorPrev(pInfo->pCur, TSDB_TABLE_MAX);
732 733
      blockFull = true;
    } else {
X
Xiaoyu Wang 已提交
734 735
      sysTableUserTagsFillOneTableTags(pInfo, &smrSuperTable, &pInfo->pCur->mr, dbname, tableName, &numOfRows,
                                       dataBlock);
736
    }
H
Haojun Liao 已提交
737

738
    pAPI->metaReaderFn.clearReader(&smrSuperTable);
H
Haojun Liao 已提交
739

740
    if (blockFull || numOfRows >= pOperator->resultInfo.capacity) {
H
Haojun Liao 已提交
741 742 743 744 745 746
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
      numOfRows = 0;

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
747 748

      blockFull = false;
H
Haojun Liao 已提交
749 750 751 752 753 754 755 756 757 758
    }
  }

  if (numOfRows > 0) {
    relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
    numOfRows = 0;
  }

  blockDataDestroy(dataBlock);
  if (ret != 0) {
759
    pAPI->metaFn.closeTableMetaCursor(pInfo->pCur);
H
Haojun Liao 已提交
760 761 762 763 764 765 766 767 768 769 770 771 772 773
    pInfo->pCur = NULL;
    setOperatorCompleted(pOperator);
  }

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock,
                                        SFilterInfo* pFilterInfo) {
  dataBlock->info.rows = numOfRows;
  pInfo->pRes->info.rows = numOfRows;

  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, dataBlock->pDataBlock, false);
774
  doFilter(pInfo->pRes, pFilterInfo, NULL);
H
Haojun Liao 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 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 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
  blockDataCleanup(dataBlock);
}

int32_t convertTagDataToStr(char* str, int type, void* buf, int32_t bufSize, int32_t* len) {
  int32_t n = 0;

  switch (type) {
    case TSDB_DATA_TYPE_NULL:
      n = sprintf(str, "null");
      break;

    case TSDB_DATA_TYPE_BOOL:
      n = sprintf(str, (*(int8_t*)buf) ? "true" : "false");
      break;

    case TSDB_DATA_TYPE_TINYINT:
      n = sprintf(str, "%d", *(int8_t*)buf);
      break;

    case TSDB_DATA_TYPE_SMALLINT:
      n = sprintf(str, "%d", *(int16_t*)buf);
      break;

    case TSDB_DATA_TYPE_INT:
      n = sprintf(str, "%d", *(int32_t*)buf);
      break;

    case TSDB_DATA_TYPE_BIGINT:
    case TSDB_DATA_TYPE_TIMESTAMP:
      n = sprintf(str, "%" PRId64, *(int64_t*)buf);
      break;

    case TSDB_DATA_TYPE_FLOAT:
      n = sprintf(str, "%.5f", GET_FLOAT_VAL(buf));
      break;

    case TSDB_DATA_TYPE_DOUBLE:
      n = sprintf(str, "%.9f", GET_DOUBLE_VAL(buf));
      break;

    case TSDB_DATA_TYPE_BINARY:
      if (bufSize < 0) {
        return TSDB_CODE_TSC_INVALID_VALUE;
      }

      memcpy(str, buf, bufSize);
      n = bufSize;
      break;
    case TSDB_DATA_TYPE_NCHAR:
      if (bufSize < 0) {
        return TSDB_CODE_TSC_INVALID_VALUE;
      }

      int32_t length = taosUcs4ToMbs((TdUcs4*)buf, bufSize, str);
      if (length <= 0) {
        return TSDB_CODE_TSC_INVALID_VALUE;
      }
      n = length;
      break;
    case TSDB_DATA_TYPE_UTINYINT:
      n = sprintf(str, "%u", *(uint8_t*)buf);
      break;

    case TSDB_DATA_TYPE_USMALLINT:
      n = sprintf(str, "%u", *(uint16_t*)buf);
      break;

    case TSDB_DATA_TYPE_UINT:
      n = sprintf(str, "%u", *(uint32_t*)buf);
      break;

    case TSDB_DATA_TYPE_UBIGINT:
      n = sprintf(str, "%" PRIu64, *(uint64_t*)buf);
      break;

    default:
      return TSDB_CODE_TSC_INVALID_VALUE;
  }

  if (len) *len = n;

  return TSDB_CODE_SUCCESS;
}

static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock) {
  char stableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
  STR_TO_VARSTR(stableName, (*smrSuperTable).me.name);

  int32_t numOfRows = *pNumOfRows;

  int32_t numOfTags = (*smrSuperTable).me.stbEntry.schemaTag.nCols;
  for (int32_t i = 0; i < numOfTags; ++i) {
    SColumnInfoData* pColInfoData = NULL;

    // table name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 0);
873
    colDataSetVal(pColInfoData, numOfRows, tableName, false);
H
Haojun Liao 已提交
874 875 876

    // database name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 1);
877
    colDataSetVal(pColInfoData, numOfRows, dbname, false);
H
Haojun Liao 已提交
878 879 880

    // super table name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 2);
881
    colDataSetVal(pColInfoData, numOfRows, stableName, false);
H
Haojun Liao 已提交
882 883 884 885 886

    // tag name
    char tagName[TSDB_COL_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tagName, (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].name);
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 3);
887
    colDataSetVal(pColInfoData, numOfRows, tagName, false);
H
Haojun Liao 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

    // tag type
    int8_t tagType = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].type;
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 4);
    char tagTypeStr[VARSTR_HEADER_SIZE + 32];
    int  tagTypeLen = sprintf(varDataVal(tagTypeStr), "%s", tDataTypes[tagType].name);
    if (tagType == TSDB_DATA_TYPE_VARCHAR) {
      tagTypeLen += sprintf(varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
                            (int32_t)((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE));
    } else if (tagType == TSDB_DATA_TYPE_NCHAR) {
      tagTypeLen += sprintf(
          varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
          (int32_t)(((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE));
    }
    varDataSetLen(tagTypeStr, tagTypeLen);
903
    colDataSetVal(pColInfoData, numOfRows, (char*)tagTypeStr, false);
H
Haojun Liao 已提交
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

    STagVal tagVal = {0};
    tagVal.cid = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].colId;
    char*    tagData = NULL;
    uint32_t tagLen = 0;

    if (tagType == TSDB_DATA_TYPE_JSON) {
      tagData = (char*)smrChildTable->me.ctbEntry.pTags;
    } else {
      bool exist = tTagGet((STag*)smrChildTable->me.ctbEntry.pTags, &tagVal);
      if (exist) {
        if (IS_VAR_DATA_TYPE(tagType)) {
          tagData = (char*)tagVal.pData;
          tagLen = tagVal.nData;
        } else {
          tagData = (char*)&tagVal.i64;
          tagLen = tDataTypes[tagType].bytes;
        }
      }
    }

    char* tagVarChar = NULL;
    if (tagData != NULL) {
      if (tagType == TSDB_DATA_TYPE_JSON) {
        char* tagJson = parseTagDatatoJson(tagData);
        tagVarChar = taosMemoryMalloc(strlen(tagJson) + VARSTR_HEADER_SIZE);
        memcpy(varDataVal(tagVarChar), tagJson, strlen(tagJson));
        varDataSetLen(tagVarChar, strlen(tagJson));
        taosMemoryFree(tagJson);
      } else {
        int32_t bufSize = IS_VAR_DATA_TYPE(tagType) ? (tagLen + VARSTR_HEADER_SIZE)
                                                    : (3 + DBL_MANT_DIG - DBL_MIN_EXP + VARSTR_HEADER_SIZE);
        tagVarChar = taosMemoryMalloc(bufSize);
        int32_t len = -1;
        convertTagDataToStr(varDataVal(tagVarChar), tagType, tagData, tagLen, &len);
        varDataSetLen(tagVarChar, len);
      }
    }
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 5);
943
    colDataSetVal(pColInfoData, numOfRows, tagVarChar,
H
Haojun Liao 已提交
944 945 946 947 948 949 950 951 952 953
                  (tagData == NULL) || (tagType == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(tagData)));
    taosMemoryFree(tagVarChar);
    ++numOfRows;
  }

  *pNumOfRows = numOfRows;

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
954 955 956 957
static int32_t sysTableUserColsFillOneTableCols(const SSysTableScanInfo* pInfo, const char* dbname, int32_t* pNumOfRows,
                                                const SSDataBlock* dataBlock, char* tName, SSchemaWrapper* schemaRow,
                                                char* tableType) {
  if (schemaRow == NULL) {
wmmhello's avatar
wmmhello 已提交
958 959
    qError("sysTableUserColsFillOneTableCols schemaRow is NULL");
    return TSDB_CODE_SUCCESS;
960 961 962
  }
  int32_t numOfRows = *pNumOfRows;

wmmhello's avatar
wmmhello 已提交
963
  int32_t numOfCols = schemaRow->nCols;
964 965 966 967 968
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pColInfoData = NULL;

    // table name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 0);
wmmhello's avatar
wmmhello 已提交
969
    colDataAppend(pColInfoData, numOfRows, tName, false);
970

wmmhello's avatar
wmmhello 已提交
971
    // database name
972
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 1);
wmmhello's avatar
wmmhello 已提交
973
    colDataAppend(pColInfoData, numOfRows, dbname, false);
wmmhello's avatar
wmmhello 已提交
974 975

    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 2);
wmmhello's avatar
wmmhello 已提交
976
    colDataAppend(pColInfoData, numOfRows, tableType, false);
977 978 979

    // col name
    char colName[TSDB_COL_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
wmmhello's avatar
wmmhello 已提交
980 981
    STR_TO_VARSTR(colName, schemaRow->pSchema[i].name);
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 3);
982 983 984
    colDataAppend(pColInfoData, numOfRows, colName, false);

    // col type
wmmhello's avatar
wmmhello 已提交
985 986
    int8_t colType = schemaRow->pSchema[i].type;
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 4);
987 988 989 990
    char colTypeStr[VARSTR_HEADER_SIZE + 32];
    int  colTypeLen = sprintf(varDataVal(colTypeStr), "%s", tDataTypes[colType].name);
    if (colType == TSDB_DATA_TYPE_VARCHAR) {
      colTypeLen += sprintf(varDataVal(colTypeStr) + colTypeLen, "(%d)",
wmmhello's avatar
wmmhello 已提交
991
                            (int32_t)(schemaRow->pSchema[i].bytes - VARSTR_HEADER_SIZE));
992
    } else if (colType == TSDB_DATA_TYPE_NCHAR) {
X
Xiaoyu Wang 已提交
993 994
      colTypeLen += sprintf(varDataVal(colTypeStr) + colTypeLen, "(%d)",
                            (int32_t)((schemaRow->pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE));
995 996 997 998 999
    }
    varDataSetLen(colTypeStr, colTypeLen);
    colDataAppend(pColInfoData, numOfRows, (char*)colTypeStr, false);

    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 5);
wmmhello's avatar
wmmhello 已提交
1000
    colDataAppend(pColInfoData, numOfRows, (const char*)&schemaRow->pSchema[i].bytes, false);
1001

wmmhello's avatar
wmmhello 已提交
1002 1003
    for (int32_t j = 6; j <= 8; ++j) {
      pColInfoData = taosArrayGet(dataBlock->pDataBlock, j);
X
Xiaoyu Wang 已提交
1004
      colDataSetNULL(pColInfoData, numOfRows);
wmmhello's avatar
wmmhello 已提交
1005
    }
1006 1007 1008 1009 1010 1011 1012 1013
    ++numOfRows;
  }

  *pNumOfRows = numOfRows;

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
static SSDataBlock* buildInfoSchemaTableMetaBlock(char* tableName) {
  size_t               size = 0;
  const SSysTableMeta* pMeta = NULL;
  getInfosDbMeta(&pMeta, &size);

  int32_t index = 0;
  for (int32_t i = 0; i < size; ++i) {
    if (strcmp(pMeta[i].name, tableName) == 0) {
      index = i;
      break;
    }
  }

  SSDataBlock* pBlock = createDataBlock();
  for (int32_t i = 0; i < pMeta[index].colNum; ++i) {
    SColumnInfoData colInfoData =
        createColumnInfoData(pMeta[index].schema[i].type, pMeta[index].schema[i].bytes, i + 1);
    blockDataAppendColInfo(pBlock, &colInfoData);
  }

  return pBlock;
}

int32_t buildDbTableInfoBlock(bool sysInfo, const SSDataBlock* p, const SSysTableMeta* pSysDbTableMeta, size_t size,
                              const char* dbName) {
  char    n[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  int32_t numOfRows = p->info.rows;

  for (int32_t i = 0; i < size; ++i) {
    const SSysTableMeta* pm = &pSysDbTableMeta[i];
    if (!sysInfo && pm->sysInfo) {
      continue;
    }

    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);

    STR_TO_VARSTR(n, pm->name);
1051
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1052 1053 1054 1055

    // database name
    STR_TO_VARSTR(n, dbName);
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
1056
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1057 1058 1059

    // create time
    pColInfoData = taosArrayGet(p->pDataBlock, 2);
1060
    colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1061 1062 1063

    // number of columns
    pColInfoData = taosArrayGet(p->pDataBlock, 3);
1064
    colDataSetVal(pColInfoData, numOfRows, (char*)&pm->colNum, false);
H
Haojun Liao 已提交
1065 1066 1067

    for (int32_t j = 4; j <= 8; ++j) {
      pColInfoData = taosArrayGet(p->pDataBlock, j);
1068
      colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1069 1070 1071 1072 1073
    }

    STR_TO_VARSTR(n, "SYSTEM_TABLE");

    pColInfoData = taosArrayGet(p->pDataBlock, 9);
1074
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

    numOfRows += 1;
  }

  return numOfRows;
}

int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity) {
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
  blockDataEnsureCapacity(p, capacity);

  size_t               size = 0;
  const SSysTableMeta* pSysDbTableMeta = NULL;

  getInfosDbMeta(&pSysDbTableMeta, &size);
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_INFORMATION_SCHEMA_DB);

  getPerfDbMeta(&pSysDbTableMeta, &size);
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_PERFORMANCE_SCHEMA_DB);

  pInfo->pRes->info.rows = p->info.rows;
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
  blockDataDestroy(p);

  return pInfo->pRes->info.rows;
}

static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) {
1103 1104
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;
1105

H
Haojun Liao 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
  SSysTableScanInfo* pInfo = pOperator->info;

  SSysTableIndex* pIdx = pInfo->pIdx;
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;

  int ret = 0;

  const char* db = NULL;
  int32_t     vgId = 0;
1116
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
H
Haojun Liao 已提交
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));

  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
  blockDataEnsureCapacity(p, pOperator->resultInfo.capacity);

  char    n[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
  int32_t i = pIdx->lastIdx;
  for (; i < taosArrayGetSize(pIdx->uids); i++) {
    tb_uid_t* uid = taosArrayGet(pIdx->uids, i);

    SMetaReader mr = {0};
H
Haojun Liao 已提交
1134
    pAPI->metaReaderFn.initReader(&mr, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
1135
    ret = pAPI->metaReaderFn.getTableEntryByUid(&mr, *uid);
H
Haojun Liao 已提交
1136
    if (ret < 0) {
1137
      pAPI->metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
1138 1139 1140 1141 1142 1143
      continue;
    }
    STR_TO_VARSTR(n, mr.me.name);

    // table name
    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);
1144
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1145 1146 1147

    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
1148
    colDataSetVal(pColInfoData, numOfRows, dbname, false);
H
Haojun Liao 已提交
1149 1150 1151

    // vgId
    pColInfoData = taosArrayGet(p->pDataBlock, 6);
1152
    colDataSetVal(pColInfoData, numOfRows, (char*)&vgId, false);
H
Haojun Liao 已提交
1153 1154 1155 1156 1157 1158

    int32_t tableType = mr.me.type;
    if (tableType == TSDB_CHILD_TABLE) {
      // create time
      int64_t ts = mr.me.ctbEntry.ctime;
      pColInfoData = taosArrayGet(p->pDataBlock, 2);
1159
      colDataSetVal(pColInfoData, numOfRows, (char*)&ts, false);
H
Haojun Liao 已提交
1160 1161

      SMetaReader mr1 = {0};
H
Haojun Liao 已提交
1162
      pAPI->metaReaderFn.initReader(&mr1, pInfo->readHandle.vnode, META_READER_NOLOCK, &pAPI->metaFn);
H
Haojun Liao 已提交
1163 1164

      int64_t suid = mr.me.ctbEntry.suid;
1165
      int32_t code = pAPI->metaReaderFn.getTableEntryByUid(&mr1, suid);
H
Haojun Liao 已提交
1166 1167 1168
      if (code != TSDB_CODE_SUCCESS) {
        qError("failed to get super table meta, cname:%s, suid:0x%" PRIx64 ", code:%s, %s", pInfo->pCur->mr.me.name,
               suid, tstrerror(terrno), GET_TASKID(pTaskInfo));
1169 1170
        pAPI->metaReaderFn.clearReader(&mr1);
        pAPI->metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
1171 1172 1173
        T_LONG_JMP(pTaskInfo->env, terrno);
      }
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
1174
      colDataSetVal(pColInfoData, numOfRows, (char*)&mr1.me.stbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
1175 1176 1177 1178

      // super table name
      STR_TO_VARSTR(n, mr1.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
1179
      colDataSetVal(pColInfoData, numOfRows, n, false);
1180
      pAPI->metaReaderFn.clearReader(&mr1);
H
Haojun Liao 已提交
1181 1182 1183 1184 1185 1186

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
      if (mr.me.ctbEntry.commentLen > 0) {
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, mr.me.ctbEntry.comment);
1187
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1188 1189 1190
      } else if (mr.me.ctbEntry.commentLen == 0) {
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
1191
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1192
      } else {
1193
        colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1194 1195 1196 1197
      }

      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
1198
      colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.uid, false);
H
Haojun Liao 已提交
1199 1200 1201

      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
1202
      colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.ctbEntry.ttlDays, false);
H
Haojun Liao 已提交
1203 1204 1205 1206 1207 1208

      STR_TO_VARSTR(n, "CHILD_TABLE");

    } else if (tableType == TSDB_NORMAL_TABLE) {
      // create time
      pColInfoData = taosArrayGet(p->pDataBlock, 2);
1209
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false);
H
Haojun Liao 已提交
1210 1211 1212

      // number of columns
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
1213
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
1214 1215 1216

      // super table name
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
1217
      colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1218 1219 1220 1221 1222 1223

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
      if (mr.me.ntbEntry.commentLen > 0) {
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, mr.me.ntbEntry.comment);
1224
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1225 1226 1227
      } else if (mr.me.ntbEntry.commentLen == 0) {
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
1228
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1229
      } else {
1230
        colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1231 1232 1233 1234
      }

      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
1235
      colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.uid, false);
H
Haojun Liao 已提交
1236 1237 1238

      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
1239
      colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.ntbEntry.ttlDays, false);
H
Haojun Liao 已提交
1240 1241 1242 1243 1244

      STR_TO_VARSTR(n, "NORMAL_TABLE");
      // impl later
    }

1245
    pAPI->metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
1246 1247

    pColInfoData = taosArrayGet(p->pDataBlock, 9);
1248
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1249 1250 1251 1252 1253 1254

    if (++numOfRows >= pOperator->resultInfo.capacity) {
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
1255
      doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
H
Haojun Liao 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270

      blockDataCleanup(p);
      numOfRows = 0;

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
    }
  }

  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;

    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
1271
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
H
Haojun Liao 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

    blockDataCleanup(p);
    numOfRows = 0;
  }

  if (i >= taosArrayGetSize(pIdx->uids)) {
    setOperatorCompleted(pOperator);
  } else {
    pIdx->lastIdx = i + 1;
  }

  blockDataDestroy(p);

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) {
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1291 1292
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;
  int8_t         firstMetaCursor = 0;
H
Haojun Liao 已提交
1293 1294 1295

  SSysTableScanInfo* pInfo = pOperator->info;
  if (pInfo->pCur == NULL) {
1296
    pInfo->pCur = pAPI->metaFn.openTableMetaCursor(pInfo->readHandle.vnode);
1297 1298 1299 1300
    firstMetaCursor = 1;
  }
  if (!firstMetaCursor) {
    pAPI->metaFn.resumeTableMetaCursor(pInfo->pCur, 0);
H
Haojun Liao 已提交
1301 1302 1303 1304 1305 1306 1307
  }

  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;

  const char* db = NULL;
  int32_t     vgId = 0;
1308
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
H
Haojun Liao 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));

  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
  blockDataEnsureCapacity(p, pOperator->resultInfo.capacity);

  char n[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};

  int32_t ret = 0;
1323
  while ((ret = pAPI->metaFn.cursorNext(pInfo->pCur, TSDB_SUPER_TABLE)) == 0) {
H
Haojun Liao 已提交
1324 1325 1326 1327
    STR_TO_VARSTR(n, pInfo->pCur->mr.me.name);

    // table name
    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);
1328
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1329 1330 1331

    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
1332
    colDataSetVal(pColInfoData, numOfRows, dbname, false);
H
Haojun Liao 已提交
1333 1334 1335

    // vgId
    pColInfoData = taosArrayGet(p->pDataBlock, 6);
1336
    colDataSetVal(pColInfoData, numOfRows, (char*)&vgId, false);
H
Haojun Liao 已提交
1337 1338 1339 1340 1341 1342

    int32_t tableType = pInfo->pCur->mr.me.type;
    if (tableType == TSDB_CHILD_TABLE) {
      // create time
      int64_t ts = pInfo->pCur->mr.me.ctbEntry.ctime;
      pColInfoData = taosArrayGet(p->pDataBlock, 2);
1343
      colDataSetVal(pColInfoData, numOfRows, (char*)&ts, false);
H
Haojun Liao 已提交
1344 1345

      SMetaReader mr = {0};
H
Haojun Liao 已提交
1346
      pAPI->metaReaderFn.initReader(&mr, pInfo->readHandle.vnode, META_READER_NOLOCK, &pAPI->metaFn);
H
Haojun Liao 已提交
1347 1348

      uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
1349
      int32_t  code = pAPI->metaReaderFn.getTableEntryByUid(&mr, suid);
H
Haojun Liao 已提交
1350 1351 1352
      if (code != TSDB_CODE_SUCCESS) {
        qError("failed to get super table meta, cname:%s, suid:0x%" PRIx64 ", code:%s, %s", pInfo->pCur->mr.me.name,
               suid, tstrerror(terrno), GET_TASKID(pTaskInfo));
1353
        pAPI->metaReaderFn.clearReader(&mr);
1354
        pAPI->metaFn.closeTableMetaCursor(pInfo->pCur);
H
Haojun Liao 已提交
1355 1356 1357 1358 1359 1360
        pInfo->pCur = NULL;
        T_LONG_JMP(pTaskInfo->env, terrno);
      }

      // number of columns
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
1361
      colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.stbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
1362 1363 1364 1365

      // super table name
      STR_TO_VARSTR(n, mr.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
1366
      colDataSetVal(pColInfoData, numOfRows, n, false);
1367
      pAPI->metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
1368 1369 1370 1371 1372 1373

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
      if (pInfo->pCur->mr.me.ctbEntry.commentLen > 0) {
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ctbEntry.comment);
1374
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1375 1376 1377
      } else if (pInfo->pCur->mr.me.ctbEntry.commentLen == 0) {
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
1378
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1379
      } else {
1380
        colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1381 1382 1383 1384
      }

      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
1385
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false);
H
Haojun Liao 已提交
1386 1387 1388

      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
1389
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ctbEntry.ttlDays, false);
H
Haojun Liao 已提交
1390 1391 1392 1393 1394

      STR_TO_VARSTR(n, "CHILD_TABLE");
    } else if (tableType == TSDB_NORMAL_TABLE) {
      // create time
      pColInfoData = taosArrayGet(p->pDataBlock, 2);
1395
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false);
H
Haojun Liao 已提交
1396 1397 1398

      // number of columns
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
1399
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
1400 1401 1402

      // super table name
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
1403
      colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1404 1405 1406 1407 1408 1409

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
      if (pInfo->pCur->mr.me.ntbEntry.commentLen > 0) {
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ntbEntry.comment);
1410
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1411 1412 1413
      } else if (pInfo->pCur->mr.me.ntbEntry.commentLen == 0) {
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
1414
        colDataSetVal(pColInfoData, numOfRows, comment, false);
H
Haojun Liao 已提交
1415
      } else {
1416
        colDataSetNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
1417 1418 1419 1420
      }

      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
1421
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false);
H
Haojun Liao 已提交
1422 1423 1424

      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
1425
      colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ttlDays, false);
H
Haojun Liao 已提交
1426 1427 1428 1429 1430

      STR_TO_VARSTR(n, "NORMAL_TABLE");
    }

    pColInfoData = taosArrayGet(p->pDataBlock, 9);
1431
    colDataSetVal(pColInfoData, numOfRows, n, false);
H
Haojun Liao 已提交
1432 1433 1434 1435 1436 1437

    if (++numOfRows >= pOperator->resultInfo.capacity) {
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
1438
      doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
H
Haojun Liao 已提交
1439 1440 1441 1442 1443

      blockDataCleanup(p);
      numOfRows = 0;

      if (pInfo->pRes->info.rows > 0) {
1444
        pAPI->metaFn.pauseTableMetaCursor(pInfo->pCur);
H
Haojun Liao 已提交
1445 1446 1447 1448 1449 1450
        break;
      }
    }
  }

  if (numOfRows > 0) {
1451
    pAPI->metaFn.pauseTableMetaCursor(pInfo->pCur);
H
Haojun Liao 已提交
1452 1453 1454 1455
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;

    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
1456
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
H
Haojun Liao 已提交
1457 1458 1459 1460 1461 1462 1463 1464 1465

    blockDataCleanup(p);
    numOfRows = 0;
  }

  blockDataDestroy(p);

  // todo temporarily free the cursor here, the true reason why the free is not valid needs to be found
  if (ret != 0) {
1466
    pAPI->metaFn.closeTableMetaCursor(pInfo->pCur);
H
Haojun Liao 已提交
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
    pInfo->pCur = NULL;
    setOperatorCompleted(pOperator);
  }

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

static SSDataBlock* sysTableScanUserTables(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;

  SNode* pCondition = pInfo->pCondition;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  // the retrieve is executed on the mnode, so return tables that belongs to the information schema database.
  if (pInfo->readHandle.mnd != NULL) {
    buildSysDbTableInfo(pInfo, pOperator->resultInfo.capacity);
1487
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
H
Haojun Liao 已提交
1488 1489 1490 1491 1492 1493 1494
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;

    setOperatorCompleted(pOperator);
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  } else {
    if (pInfo->showRewrite == false) {
      if (pCondition != NULL && pInfo->pIdx == NULL) {
1495 1496
        SSTabFltArg arg = {
            .pMeta = pInfo->readHandle.vnode, .pVnode = pInfo->readHandle.vnode, .pAPI = &pTaskInfo->storageAPI};
H
Haojun Liao 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509

        SSysTableIndex* idx = taosMemoryMalloc(sizeof(SSysTableIndex));
        idx->init = 0;
        idx->uids = taosArrayInit(128, sizeof(int64_t));
        idx->lastIdx = 0;

        pInfo->pIdx = idx;  // set idx arg

        int flt = optSysTabFilte(&arg, pCondition, idx->uids);
        if (flt == 0) {
          pInfo->pIdx->init = 1;
          SSDataBlock* blk = sysTableBuildUserTablesByUids(pOperator);
          return blk;
1510
        } else if ((flt == -1) || (flt == -2)) {
H
Haojun Liao 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
          qDebug("%s failed to get sys table info by idx, scan sys table one by one", GET_TASKID(pTaskInfo));
        }
      } else if (pCondition != NULL && (pInfo->pIdx != NULL && pInfo->pIdx->init == 1)) {
        SSDataBlock* blk = sysTableBuildUserTablesByUids(pOperator);
        return blk;
      }
    }

    return sysTableBuildUserTables(pOperator);
  }
  return NULL;
}

static SSDataBlock* sysTableScanUserSTables(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  pInfo->pRes->info.rows = 0;
  pOperator->status = OP_EXEC_DONE;

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

static int32_t getSysTableDbNameColId(const char* pTable) {
  // if (0 == strcmp(TSDB_INS_TABLE_INDEXES, pTable)) {
  //   return 1;
  // }
  return TSDB_INS_USER_STABLES_DBNAME_COLID;
}

static EDealRes getDBNameFromConditionWalker(SNode* pNode, void* pContext) {
  int32_t   code = TSDB_CODE_SUCCESS;
  ENodeType nType = nodeType(pNode);

  switch (nType) {
    case QUERY_NODE_OPERATOR: {
      SOperatorNode* node = (SOperatorNode*)pNode;
      if (OP_TYPE_EQUAL == node->opType) {
        *(int32_t*)pContext = 1;
        return DEAL_RES_CONTINUE;
      }

      *(int32_t*)pContext = 0;
      return DEAL_RES_IGNORE_CHILD;
    }
    case QUERY_NODE_COLUMN: {
      if (1 != *(int32_t*)pContext) {
        return DEAL_RES_CONTINUE;
      }

      SColumnNode* node = (SColumnNode*)pNode;
      if (getSysTableDbNameColId(node->tableName) == node->colId) {
        *(int32_t*)pContext = 2;
        return DEAL_RES_CONTINUE;
      }

      *(int32_t*)pContext = 0;
      return DEAL_RES_CONTINUE;
    }
    case QUERY_NODE_VALUE: {
      if (2 != *(int32_t*)pContext) {
        return DEAL_RES_CONTINUE;
      }

      SValueNode* node = (SValueNode*)pNode;
      char*       dbName = nodesGetValueFromNode(node);
      strncpy(pContext, varDataVal(dbName), varDataLen(dbName));
      *((char*)pContext + varDataLen(dbName)) = 0;
      return DEAL_RES_END;  // stop walk
    }
    default:
      break;
  }
  return DEAL_RES_CONTINUE;
}

static void getDBNameFromCondition(SNode* pCondition, const char* dbName) {
  if (NULL == pCondition) {
    return;
  }
  nodesWalkExpr(pCondition, getDBNameFromConditionWalker, (char*)dbName);
}

static SSDataBlock* doSysTableScan(SOperatorInfo* pOperator) {
  // build message and send to mnode to fetch the content of system tables.
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  char               dbName[TSDB_DB_NAME_LEN] = {0};

  const char* name = tNameGetTableName(&pInfo->name);
  if (pInfo->showRewrite) {
    getDBNameFromCondition(pInfo->pCondition, dbName);
    sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
X
Xiaoyu Wang 已提交
1608
  } else if (strncasecmp(name, TSDB_INS_TABLE_COLS, TSDB_TABLE_FNAME_LEN) == 0) {
wmmhello's avatar
wmmhello 已提交
1609
    getDBNameFromCondition(pInfo->pCondition, dbName);
X
Xiaoyu Wang 已提交
1610
    if (dbName[0]) sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
wmmhello's avatar
wmmhello 已提交
1611
    sysTableIsCondOnOneTable(pInfo->pCondition, pInfo->req.filterTb);
H
Haojun Liao 已提交
1612
  }
wmmhello's avatar
wmmhello 已提交
1613

S
slzhou 已提交
1614
  SSDataBlock* pBlock = NULL;
H
Haojun Liao 已提交
1615
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
S
slzhou 已提交
1616
    pBlock = sysTableScanUserTables(pOperator);
H
Haojun Liao 已提交
1617
  } else if (strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
S
slzhou 已提交
1618
    pBlock = sysTableScanUserTags(pOperator);
wmmhello's avatar
wmmhello 已提交
1619
  } else if (strncasecmp(name, TSDB_INS_TABLE_COLS, TSDB_TABLE_FNAME_LEN) == 0 && pInfo->readHandle.mnd == NULL) {
1620
    pBlock = sysTableScanUserCols(pOperator);
H
Haojun Liao 已提交
1621 1622
  } else if (strncasecmp(name, TSDB_INS_TABLE_STABLES, TSDB_TABLE_FNAME_LEN) == 0 && pInfo->showRewrite &&
             IS_SYS_DBNAME(dbName)) {
S
slzhou 已提交
1623
    pBlock = sysTableScanUserSTables(pOperator);
H
Haojun Liao 已提交
1624
  } else {  // load the meta from mnode of the given epset
S
slzhou 已提交
1625 1626
    pBlock = sysTableScanFromMNode(pOperator, pInfo, name, pTaskInfo);
  }
H
Haojun Liao 已提交
1627

1628
  sysTableScanFillTbName(pOperator, pInfo, name, pBlock);
S
slzhou 已提交
1629
  if (pBlock != NULL) {
1630 1631 1632
    bool limitReached = applyLimitOffset(&pInfo->limitInfo, pBlock, pTaskInfo);
    if (limitReached) {
      setOperatorCompleted(pOperator);
S
slzhou 已提交
1633
    }
1634

X
Xiaoyu Wang 已提交
1635
    return pBlock->info.rows > 0 ? pBlock : NULL;
S
slzhou 已提交
1636 1637 1638 1639
  } else {
    return NULL;
  }
}
H
Haojun Liao 已提交
1640

1641 1642 1643 1644 1645 1646 1647 1648
static void sysTableScanFillTbName(SOperatorInfo* pOperator, const SSysTableScanInfo* pInfo, const char* name,
                                   SSDataBlock* pBlock) {
  if (pBlock == NULL) {
    return;
  }

  if (pInfo->tbnameSlotId != -1) {
    SColumnInfoData* pColumnInfoData = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, pInfo->tbnameSlotId);
X
Xiaoyu Wang 已提交
1649
    char             varTbName[TSDB_TABLE_FNAME_LEN - 1 + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
1650
    STR_TO_VARSTR(varTbName, name);
1651

D
dapan1121 已提交
1652
    colDataSetNItems(pColumnInfoData, 0, varTbName, pBlock->info.rows, true);
1653 1654 1655 1656 1657
  }

  doFilter(pBlock, pOperator->exprSupp.pFilterInfo, NULL);
}

S
slzhou 已提交
1658 1659 1660 1661 1662
static SSDataBlock* sysTableScanFromMNode(SOperatorInfo* pOperator, SSysTableScanInfo* pInfo, const char* name,
                                          SExecTaskInfo* pTaskInfo) {
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
H
Haojun Liao 已提交
1663

S
slzhou 已提交
1664 1665 1666 1667
  while (1) {
    int64_t startTs = taosGetTimestampUs();
    tstrncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));
    tstrncpy(pInfo->req.user, pInfo->pUser, tListLen(pInfo->req.user));
H
Haojun Liao 已提交
1668

S
slzhou 已提交
1669 1670 1671
    int32_t contLen = tSerializeSRetrieveTableReq(NULL, 0, &pInfo->req);
    char*   buf1 = taosMemoryCalloc(1, contLen);
    tSerializeSRetrieveTableReq(buf1, contLen, &pInfo->req);
H
Haojun Liao 已提交
1672

S
slzhou 已提交
1673 1674 1675 1676 1677 1678 1679
    // send the fetch remote task result reques
    SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
    if (NULL == pMsgSendInfo) {
      qError("%s prepare message %d failed", GET_TASKID(pTaskInfo), (int32_t)sizeof(SMsgSendInfo));
      pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
      return NULL;
    }
H
Haojun Liao 已提交
1680

S
slzhou 已提交
1681 1682
    int32_t msgType = (strcasecmp(name, TSDB_INS_TABLE_DNODE_VARIABLES) == 0) ? TDMT_DND_SYSTABLE_RETRIEVE
                                                                              : TDMT_MND_SYSTABLE_RETRIEVE;
H
Haojun Liao 已提交
1683

S
slzhou 已提交
1684 1685 1686 1687 1688 1689
    pMsgSendInfo->param = pOperator;
    pMsgSendInfo->msgInfo.pData = buf1;
    pMsgSendInfo->msgInfo.len = contLen;
    pMsgSendInfo->msgType = msgType;
    pMsgSendInfo->fp = loadSysTableCallback;
    pMsgSendInfo->requestId = pTaskInfo->id.queryId;
H
Haojun Liao 已提交
1690

S
slzhou 已提交
1691 1692 1693 1694
    int64_t transporterId = 0;
    int32_t code =
        asyncSendMsgToServer(pInfo->readHandle.pMsgCb->clientRpc, &pInfo->epSet, &transporterId, pMsgSendInfo);
    tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
1695

S
slzhou 已提交
1696
    if (pTaskInfo->code) {
wmmhello's avatar
wmmhello 已提交
1697
      qError("%s load meta data from mnode failed, totalRows:%" PRIu64 ", code:%s", GET_TASKID(pTaskInfo),
S
slzhou 已提交
1698 1699 1700
             pInfo->loadInfo.totalRows, tstrerror(pTaskInfo->code));
      return NULL;
    }
H
Haojun Liao 已提交
1701

S
slzhou 已提交
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
    pInfo->req.showId = pRsp->handle;

    if (pRsp->numOfRows == 0 || pRsp->completed) {
      pOperator->status = OP_EXEC_DONE;
      qDebug("%s load meta data from mnode completed, rowsOfSource:%d, totalRows:%" PRIu64, GET_TASKID(pTaskInfo),
             pRsp->numOfRows, pInfo->loadInfo.totalRows);

      if (pRsp->numOfRows == 0) {
        taosMemoryFree(pRsp);
H
Haojun Liao 已提交
1712 1713 1714
        return NULL;
      }
    }
S
slzhou 已提交
1715 1716 1717 1718 1719 1720

    char* pStart = pRsp->data;
    extractDataBlockFromFetchRsp(pInfo->pRes, pRsp->data, pInfo->matchInfo.pList, &pStart);
    updateLoadRemoteInfo(&pInfo->loadInfo, pRsp->numOfRows, pRsp->compLen, startTs, pOperator);

    // todo log the filter info
1721
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
S
slzhou 已提交
1722 1723 1724 1725 1726 1727
    taosMemoryFree(pRsp);
    if (pInfo->pRes->info.rows > 0) {
      return pInfo->pRes;
    } else if (pOperator->status == OP_EXEC_DONE) {
      return NULL;
    }
H
Haojun Liao 已提交
1728 1729 1730 1731 1732
  }
}

SOperatorInfo* createSysTableScanOperatorInfo(void* readHandle, SSystemTableScanPhysiNode* pScanPhyNode,
                                              const char* pUser, SExecTaskInfo* pTaskInfo) {
1733
  int32_t            code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
  SSysTableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

  SScanPhysiNode*     pScanNode = &pScanPhyNode->scan;
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

  int32_t num = 0;
1744
  code = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
1745 1746 1747 1748
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

S
slzhou 已提交
1749 1750
  extractTbnameSlotId(pInfo, pScanNode);

1751 1752
  pInfo->pAPI = &pTaskInfo->storageAPI;

H
Haojun Liao 已提交
1753
  pInfo->accountId = pScanPhyNode->accountId;
1754
  pInfo->pUser = taosStrdup((void*)pUser);
H
Haojun Liao 已提交
1755 1756
  pInfo->sysInfo = pScanPhyNode->sysInfo;
  pInfo->showRewrite = pScanPhyNode->showRewrite;
H
Haojun Liao 已提交
1757
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
H
Haojun Liao 已提交
1758 1759 1760 1761 1762 1763
  pInfo->pCondition = pScanNode->node.pConditions;
  code = filterInitFromNode(pScanNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

1764
  initLimitInfo(pScanPhyNode->scan.node.pLimit, pScanPhyNode->scan.node.pSlimit, &pInfo->limitInfo);
H
Haojun Liao 已提交
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
  initResultSizeInfo(&pOperator->resultInfo, 4096);
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

  tNameAssign(&pInfo->name, &pScanNode->tableName);
  const char* name = tNameGetTableName(&pInfo->name);

  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0 ||
      strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
    pInfo->readHandle = *(SReadHandle*)readHandle;
  } else {
    tsem_init(&pInfo->ready, 0, 0);
    pInfo->epSet = pScanPhyNode->mgmtEpSet;
    pInfo->readHandle = *(SReadHandle*)readHandle;
  }

  setOperatorInfo(pOperator, "SysTableScanOperator", QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
X
Xiaoyu Wang 已提交
1783 1784
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, doSysTableScan, NULL, destroySysScanOperator, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
1785 1786
  return pOperator;

X
Xiaoyu Wang 已提交
1787
_error:
H
Haojun Liao 已提交
1788 1789 1790 1791 1792 1793 1794 1795
  if (pInfo != NULL) {
    destroySysScanOperator(pInfo);
  }
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
  return NULL;
}

S
slzhou 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
void extractTbnameSlotId(SSysTableScanInfo* pInfo, const SScanPhysiNode* pScanNode) {
  pInfo->tbnameSlotId = -1;
  if (pScanNode->pScanPseudoCols != NULL) {
    SNode* pNode = NULL;
    FOREACH(pNode, pScanNode->pScanPseudoCols) {
      STargetNode* pTargetNode = NULL;
      if (nodeType(pNode) == QUERY_NODE_TARGET) {
        pTargetNode = (STargetNode*)pNode;
        SNode* expr = pTargetNode->pExpr;
        if (nodeType(expr) == QUERY_NODE_FUNCTION) {
          SFunctionNode* pFuncNode = (SFunctionNode*)expr;
          if (pFuncNode->funcType == FUNCTION_TYPE_TBNAME) {
            pInfo->tbnameSlotId = pTargetNode->slotId;
          }
        }
      }
    }
  }
}

H
Haojun Liao 已提交
1816 1817 1818 1819 1820 1821 1822
void destroySysScanOperator(void* param) {
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*)param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

  const char* name = tNameGetTableName(&pInfo->name);
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0 ||
1823
      strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0 ||
X
Xiaoyu Wang 已提交
1824
      strncasecmp(name, TSDB_INS_TABLE_COLS, TSDB_TABLE_FNAME_LEN) == 0 || pInfo->pCur != NULL) {
H
Haojun Liao 已提交
1825 1826 1827 1828
    if (pInfo->pAPI->metaFn.closeTableMetaCursor != NULL) {
      pInfo->pAPI->metaFn.closeTableMetaCursor(pInfo->pCur);
    }

H
Haojun Liao 已提交
1829 1830
    pInfo->pCur = NULL;
  }
H
Haojun Liao 已提交
1831

H
Haojun Liao 已提交
1832 1833 1834 1835 1836 1837
  if (pInfo->pIdx) {
    taosArrayDestroy(pInfo->pIdx->uids);
    taosMemoryFree(pInfo->pIdx);
    pInfo->pIdx = NULL;
  }

1838
  if (pInfo->pSchema) {
K
kailixu 已提交
1839 1840 1841 1842
    taosHashCleanup(pInfo->pSchema);
    pInfo->pSchema = NULL;
  }

H
Haojun Liao 已提交
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 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 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
  taosArrayDestroy(pInfo->matchInfo.pList);
  taosMemoryFreeClear(pInfo->pUser);

  taosMemoryFreeClear(param);
}

int32_t loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code) {
  SOperatorInfo*     operator=(SOperatorInfo*) param;
  SSysTableScanInfo* pScanResInfo = (SSysTableScanInfo*)operator->info;
  if (TSDB_CODE_SUCCESS == code) {
    pScanResInfo->pRsp = pMsg->pData;

    SRetrieveMetaTableRsp* pRsp = pScanResInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
    pRsp->useconds = htobe64(pRsp->useconds);
    pRsp->handle = htobe64(pRsp->handle);
    pRsp->compLen = htonl(pRsp->compLen);
  } else {
    operator->pTaskInfo->code = code;
  }

  tsem_post(&pScanResInfo->ready);
  return TSDB_CODE_SUCCESS;
}

static int32_t sysChkFilter__Comm(SNode* pNode) {
  // impl
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  EOperatorType  opType = pOper->opType;
  if (opType != OP_TYPE_EQUAL && opType != OP_TYPE_LOWER_EQUAL && opType != OP_TYPE_LOWER_THAN &&
      opType != OP_TYPE_GREATER_EQUAL && opType != OP_TYPE_GREATER_THAN) {
    return -1;
  }
  return 0;
}

static int32_t sysChkFilter__DBName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;

  if (pOper->opType != OP_TYPE_EQUAL && pOper->opType != OP_TYPE_NOT_EQUAL) {
    return -1;
  }

  SValueNode* pVal = (SValueNode*)pOper->pRight;
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
    return -1;
  }

  return 0;
}
static int32_t sysChkFilter__VgroupId(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t sysChkFilter__TableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t sysChkFilter__CreateTime(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

  if (!IS_TIMESTAMP_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}

static int32_t sysChkFilter__Ncolumn(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t sysChkFilter__Ttl(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t sysChkFilter__STableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t sysChkFilter__Uid(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t sysChkFilter__Type(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
    return -1;
  }
  return sysChkFilter__Comm(pNode);
}
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result) {
  if (optSysCheckOper(cond) != 0) return -1;

  SOperatorNode* pNode = (SOperatorNode*)cond;

  int8_t i = 0;
  for (; i < SYSTAB_FILTER_DICT_SIZE; i++) {
    if (strcmp(filterDict[i].name, ((SColumnNode*)(pNode->pLeft))->colName) == 0) {
      break;
    }
  }
  if (i >= SYSTAB_FILTER_DICT_SIZE) return -1;

  if (filterDict[i].chkFunc(cond) != 0) return -1;

  return filterDict[i].fltFunc(arg, cond, result);
}

static int32_t optSysCheckOper(SNode* pOpear) {
  if (nodeType(pOpear) != QUERY_NODE_OPERATOR) return -1;

  SOperatorNode* pOper = (SOperatorNode*)pOpear;
  if (pOper->opType < OP_TYPE_GREATER_THAN || pOper->opType > OP_TYPE_NOT_EQUAL) {
    return -1;
  }

  if (nodeType(pOper->pLeft) != QUERY_NODE_COLUMN || nodeType(pOper->pRight) != QUERY_NODE_VALUE) {
    return -1;
  }
  return 0;
}

static FORCE_INLINE int optSysBinarySearch(SArray* arr, int s, int e, uint64_t k) {
  uint64_t v;
  int32_t  m;
  while (s <= e) {
    m = s + (e - s) / 2;
    v = *(uint64_t*)taosArrayGet(arr, m);
    if (v >= k) {
      e = m - 1;
    } else {
      s = m + 1;
    }
  }
  return s;
}

void optSysIntersection(SArray* in, SArray* out) {
  int32_t sz = (int32_t)taosArrayGetSize(in);
  if (sz <= 0) {
    return;
  }
  MergeIndex* mi = taosMemoryCalloc(sz, sizeof(MergeIndex));
  for (int i = 0; i < sz; i++) {
    SArray* t = taosArrayGetP(in, i);
    mi[i].len = (int32_t)taosArrayGetSize(t);
    mi[i].idx = 0;
  }

  SArray* base = taosArrayGetP(in, 0);
  for (int i = 0; i < taosArrayGetSize(base); i++) {
    uint64_t tgt = *(uint64_t*)taosArrayGet(base, i);
    bool     has = true;
    for (int j = 1; j < taosArrayGetSize(in); j++) {
      SArray* oth = taosArrayGetP(in, j);
      int     mid = optSysBinarySearch(oth, mi[j].idx, mi[j].len - 1, tgt);
      if (mid >= 0 && mid < mi[j].len) {
        uint64_t val = *(uint64_t*)taosArrayGet(oth, mid);
        has = (val == tgt ? true : false);
        mi[j].idx = mid;
      } else {
        has = false;
      }
    }
    if (has == true) {
      taosArrayPush(out, &tgt);
    }
  }
  taosMemoryFreeClear(mi);
}

static int tableUidCompare(const void* a, const void* b) {
  int64_t u1 = *(int64_t*)a;
  int64_t u2 = *(int64_t*)b;
  if (u1 == u2) {
    return 0;
  }
  return u1 < u2 ? -1 : 1;
}

static int32_t optSysMergeRslt(SArray* mRslt, SArray* rslt) {
  // TODO, find comm mem from mRslt
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
    SArray* arslt = taosArrayGetP(mRslt, i);
    taosArraySort(arslt, tableUidCompare);
  }
  optSysIntersection(mRslt, rslt);
  return 0;
}

static int32_t optSysSpecialColumn(SNode* cond) {
  SOperatorNode* pOper = (SOperatorNode*)cond;
  SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
  for (int i = 0; i < sizeof(SYSTABLE_SPECIAL_COL) / sizeof(SYSTABLE_SPECIAL_COL[0]); i++) {
    if (0 == strcmp(pCol->colName, SYSTABLE_SPECIAL_COL[i])) {
      return 1;
    }
  }
  return 0;
}

static int32_t optSysTabFilte(void* arg, SNode* cond, SArray* result) {
  int ret = -1;
  if (nodeType(cond) == QUERY_NODE_OPERATOR) {
    ret = optSysTabFilteImpl(arg, cond, result);
    if (ret == 0) {
      SOperatorNode* pOper = (SOperatorNode*)cond;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
      if (0 == strcmp(pCol->colName, "create_time")) {
        return 0;
      }
      return -1;
    }
    return ret;
  }

  if (nodeType(cond) != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
    return ret;
  }

  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;

  int32_t len = LIST_LENGTH(pList);

  bool    hasIdx = false;
  bool    hasRslt = true;
  SArray* mRslt = taosArrayInit(len, POINTER_BYTES);

  SListCell* cell = pList->pHead;
  for (int i = 0; i < len; i++) {
    if (cell == NULL) break;

    SArray* aRslt = taosArrayInit(16, sizeof(int64_t));

    ret = optSysTabFilteImpl(arg, cell->pNode, aRslt);
    if (ret == 0) {
      // has index
      hasIdx = true;
      if (optSysSpecialColumn(cell->pNode) == 0) {
        taosArrayPush(mRslt, &aRslt);
      } else {
        // db_name/vgroup not result
        taosArrayDestroy(aRslt);
      }
    } else if (ret == -2) {
      // current vg
      hasIdx = true;
      hasRslt = false;
      taosArrayDestroy(aRslt);
      break;
    } else {
      taosArrayDestroy(aRslt);
    }
    cell = cell->pNext;
  }
  if (hasRslt && hasIdx) {
    optSysMergeRslt(mRslt, result);
  }

  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
    SArray* aRslt = taosArrayGetP(mRslt, i);
    taosArrayDestroy(aRslt);
  }
  taosArrayDestroy(mRslt);
  if (hasRslt == false) {
    return -2;
  }
  if (hasRslt && hasIdx) {
    cell = pList->pHead;
    for (int i = 0; i < len; i++) {
      if (cell == NULL) break;
      SOperatorNode* pOper = (SOperatorNode*)cell->pNode;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
      if (0 == strcmp(pCol->colName, "create_time")) {
        return 0;
      }
      cell = cell->pNext;
    }
    return -1;
  }
  return -1;
H
Haojun Liao 已提交
2153 2154
}

2155
static int32_t doGetTableRowSize(SReadHandle* pHandle, uint64_t uid, int32_t* rowLen, const char* idstr) {
H
Haojun Liao 已提交
2156 2157 2158
  *rowLen = 0;

  SMetaReader mr = {0};
H
Haojun Liao 已提交
2159
  pHandle->api.metaReaderFn.initReader(&mr, pHandle->vnode, 0, &pHandle->api.metaFn);
2160
  int32_t code = pHandle->api.metaReaderFn.getTableEntryByUid(&mr, uid);
H
Haojun Liao 已提交
2161 2162
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", uid, tstrerror(terrno), idstr);
2163
    pHandle->api.metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    return terrno;
  }

  if (mr.me.type == TSDB_SUPER_TABLE) {
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;
    for (int32_t i = 0; i < numOfCols; ++i) {
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
    }
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    uint64_t suid = mr.me.ctbEntry.suid;
    tDecoderClear(&mr.coder);
2175
    code = pHandle->api.metaReaderFn.getTableEntryByUid(&mr, suid);
H
Haojun Liao 已提交
2176 2177
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno), idstr);
2178
      pHandle->api.metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
      return terrno;
    }

    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;

    for (int32_t i = 0; i < numOfCols; ++i) {
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
    }
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
    int32_t numOfCols = mr.me.ntbEntry.schemaRow.nCols;
    for (int32_t i = 0; i < numOfCols; ++i) {
      (*rowLen) += mr.me.ntbEntry.schemaRow.pSchema[i].bytes;
    }
  }

2194
  pHandle->api.metaReaderFn.clearReader(&mr);
H
Haojun Liao 已提交
2195 2196 2197 2198
  return TSDB_CODE_SUCCESS;
}

static SSDataBlock* doBlockInfoScan(SOperatorInfo* pOperator) {
2199 2200 2201
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
H
Haojun Liao 已提交
2202

2203 2204
  SBlockDistInfo* pBlockScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
2205
  SStorageAPI*    pAPI = &pTaskInfo->storageAPI;
H
Haojun Liao 已提交
2206

2207
  STableBlockDistInfo blockDistInfo = {.minRows = INT_MAX, .maxRows = INT_MIN};
2208 2209
  int32_t code = doGetTableRowSize(&pBlockScanInfo->readHandle, pBlockScanInfo->uid, (int32_t*)&blockDistInfo.rowSize,
                                   GET_TASKID(pTaskInfo));
2210 2211 2212
  if (code != TSDB_CODE_SUCCESS) {
    T_LONG_JMP(pTaskInfo->env, code);
  }
H
Haojun Liao 已提交
2213

2214
  pAPI->tsdReader.tsdReaderGetDataBlockDistInfo(pBlockScanInfo->pHandle, &blockDistInfo);
2215
  blockDistInfo.numOfInmemRows = (int32_t)pAPI->tsdReader.tsdReaderGetNumOfInMemRows(pBlockScanInfo->pHandle);
H
Haojun Liao 已提交
2216

2217
  SSDataBlock* pBlock = pBlockScanInfo->pResBlock;
H
Haojun Liao 已提交
2218

2219 2220
  int32_t          slotId = pOperator->exprSupp.pExprInfo->base.resSchema.slotId;
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, slotId);
H
Haojun Liao 已提交
2221

2222 2223 2224 2225
  int32_t len = tSerializeBlockDistInfo(NULL, 0, &blockDistInfo);
  char*   p = taosMemoryCalloc(1, len + VARSTR_HEADER_SIZE);
  tSerializeBlockDistInfo(varDataVal(p), len, &blockDistInfo);
  varDataSetLen(p, len);
H
Haojun Liao 已提交
2226

2227
  colDataSetVal(pColInfo, 0, p, false);
2228
  taosMemoryFree(p);
H
Haojun Liao 已提交
2229

2230 2231 2232
  // make the valgrind happy that all memory buffer has been initialized already.
  if (slotId != 0) {
    SColumnInfoData* p1 = taosArrayGet(pBlock->pDataBlock, 0);
X
Xiaoyu Wang 已提交
2233
    int64_t          v = 0;
2234
    colDataSetInt64(p1, 0, &v);
2235 2236
  }

2237 2238 2239
  pBlock->info.rows = 1;
  pOperator->status = OP_EXEC_DONE;
  return pBlock;
H
Haojun Liao 已提交
2240 2241 2242
}

static void destroyBlockDistScanOperatorInfo(void* param) {
X
Xiaoyu Wang 已提交
2243 2244
  SBlockDistInfo* pDistInfo = (SBlockDistInfo*)param;
  blockDataDestroy(pDistInfo->pResBlock);
2245
  pDistInfo->readHandle.api.tsdReader.tsdReaderClose(pDistInfo->pHandle);
H
Haojun Liao 已提交
2246
  tableListDestroy(pDistInfo->pTableListInfo);
X
Xiaoyu Wang 已提交
2247
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2248 2249 2250
}

static int32_t initTableblockDistQueryCond(uint64_t uid, SQueryTableDataCond* pCond) {
2251 2252 2253 2254 2255 2256 2257
  memset(pCond, 0, sizeof(SQueryTableDataCond));

  pCond->order = TSDB_ORDER_ASC;
  pCond->numOfCols = 1;
  pCond->colList = taosMemoryCalloc(1, sizeof(SColumnInfo));
  pCond->pSlotList = taosMemoryMalloc(sizeof(int32_t));
  if (pCond->colList == NULL || pCond->pSlotList == NULL) {
S
Shengliang Guan 已提交
2258
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2259 2260
    return terrno;
  }
H
Haojun Liao 已提交
2261

2262 2263 2264
  pCond->colList->colId = 1;
  pCond->colList->type = TSDB_DATA_TYPE_TIMESTAMP;
  pCond->colList->bytes = sizeof(TSKEY);
H
Haojun Liao 已提交
2265

2266
  pCond->pSlotList[0] = 0;
H
Haojun Liao 已提交
2267

2268 2269 2270 2271 2272 2273 2274
  pCond->twindows = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
  pCond->suid = uid;
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
  pCond->startVersion = -1;
  pCond->endVersion = -1;

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2275 2276 2277
}

SOperatorInfo* createDataBlockInfoScanOperator(SReadHandle* readHandle, SBlockDistScanPhysiNode* pBlockScanNode,
2278
                                               STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
2279 2280 2281 2282 2283 2284
  SBlockDistInfo* pInfo = taosMemoryCalloc(1, sizeof(SBlockDistInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }
H
Haojun Liao 已提交
2285

H
Haojun Liao 已提交
2286 2287
  pInfo->pResBlock = createDataBlockFromDescNode(pBlockScanNode->node.pOutputDataBlockDesc);
  blockDataEnsureCapacity(pInfo->pResBlock, 1);
H
Haojun Liao 已提交
2288

H
Haojun Liao 已提交
2289 2290 2291 2292 2293 2294
  {
    SQueryTableDataCond cond = {0};
    int32_t             code = initTableblockDistQueryCond(pBlockScanNode->suid, &cond);
    if (code != TSDB_CODE_SUCCESS) {
      goto _error;
    }
H
Haojun Liao 已提交
2295

2296
    pInfo->pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
2297 2298
    size_t num = tableListGetSize(pTableListInfo);
    void*  pList = tableListGetInfo(pTableListInfo, 0);
H
Haojun Liao 已提交
2299

2300 2301
    code = readHandle->api.tsdReader.tsdReaderOpen(readHandle->vnode, &cond, pList, num, pInfo->pResBlock,
                                                   (void**)&pInfo->pHandle, pTaskInfo->id.str, false, NULL);
H
Haojun Liao 已提交
2302 2303 2304
    cleanupQueryTableDataCond(&cond);
    if (code != 0) {
      goto _error;
H
Haojun Liao 已提交
2305
    }
H
Haojun Liao 已提交
2306
  }
H
Haojun Liao 已提交
2307

H
Haojun Liao 已提交
2308
  pInfo->readHandle = *readHandle;
dengyihao's avatar
dengyihao 已提交
2309
  pInfo->uid = (pBlockScanNode->suid != 0) ? pBlockScanNode->suid : pBlockScanNode->uid;
H
Haojun Liao 已提交
2310

H
Haojun Liao 已提交
2311 2312
  int32_t    numOfCols = 0;
  SExprInfo* pExprInfo = createExprInfo(pBlockScanNode->pScanPseudoCols, NULL, &numOfCols);
2313
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfCols, &pTaskInfo->storageAPI.functionStore);
H
Haojun Liao 已提交
2314 2315 2316
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2317

H
Haojun Liao 已提交
2318 2319
  setOperatorInfo(pOperator, "DataBlockDistScanOperator", QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN, false,
                  OP_NOT_OPENED, pInfo, pTaskInfo);
X
Xiaoyu Wang 已提交
2320 2321
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doBlockInfoScan, NULL, destroyBlockDistScanOperatorInfo,
                                         optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
2322
  return pOperator;
H
Haojun Liao 已提交
2323

H
Haojun Liao 已提交
2324 2325 2326 2327
_error:
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
2328
}