scanoperator.c 38.2 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 <common/ttime.h>
H
Haojun Liao 已提交
17 18
#include "filter.h"
#include "function.h"
19
#include "functionMgt.h"
H
Haojun Liao 已提交
20 21
#include "os.h"
#include "querynodes.h"
22
#include "tglobal.h"
H
Haojun Liao 已提交
23 24 25 26 27 28 29 30 31 32 33
#include "tname.h"
#include "vnode.h"

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

#include "executorimpl.h"
#include "query.h"
#include "tcompare.h"
#include "thash.h"
#include "ttypes.h"
34
#include "vnode.h"
H
Haojun Liao 已提交
35 36

#define SET_REVERSE_SCAN_FLAG(_info) ((_info)->scanFlag = REVERSE_SCAN)
37
#define SWITCH_ORDER(n)              (((n) = ((n) == TSDB_ORDER_ASC) ? TSDB_ORDER_DESC : TSDB_ORDER_ASC))
38

H
Haojun Liao 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
void switchCtxOrder(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SWITCH_ORDER(pCtx[i].order);
  }
}

static void setupQueryRangeForReverseScan(STableScanInfo* pTableScanInfo) {
#if 0
  int32_t numOfGroups = (int32_t)(GET_NUM_OF_TABLEGROUP(pRuntimeEnv));
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray *group = GET_TABLEGROUP(pRuntimeEnv, i);
    SArray *tableKeyGroup = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t t = taosArrayGetSize(group);
    for (int32_t j = 0; j < t; ++j) {
      STableQueryInfo *pCheckInfo = taosArrayGetP(group, j);
      updateTableQueryInfoForReverseScan(pCheckInfo);

      // update the last key in tableKeyInfo list, the tableKeyInfo is used to build the tsdbQueryHandle and decide
      // the start check timestamp of tsdbQueryHandle
//      STableKeyInfo *pTableKeyInfo = taosArrayGet(tableKeyGroup, j);
//      pTableKeyInfo->lastKey = pCheckInfo->lastKey;
//
//      assert(pCheckInfo->pTable == pTableKeyInfo->pTable);
    }
  }
#endif
}

H
Haojun Liao 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
// relocated the column data according to the slotId
static void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols) {
  int32_t numOfCols = pBlock->info.numOfCols;
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* p = taosArrayGet(pCols, i);
    SColMatchInfo*   pmInfo = taosArrayGet(pColMatchInfo, i);
    if (!pmInfo->output) {
      continue;
    }

    ASSERT(pmInfo->colId == p->info.colId);
    taosArraySet(pBlock->pDataBlock, pmInfo->targetSlotId, p);
  }
}

83 84 85 86 87 88 89 90 91
static void getNextTimeWindow(SInterval* pInterval, STimeWindow* tw, int32_t order) {
  int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
  if (pInterval->intervalUnit != 'n' && pInterval->intervalUnit != 'y') {
    tw->skey += pInterval->sliding * factor;
    tw->ekey = tw->skey + pInterval->interval - 1;
    return;
  }

  int64_t key = tw->skey, interval = pInterval->interval;
92
  // convert key to second
93 94 95 96 97 98 99
  key = convertTimePrecision(key, pInterval->precision, TSDB_TIME_PRECISION_MILLI) / 1000;

  if (pInterval->intervalUnit == 'y') {
    interval *= 12;
  }

  struct tm tm;
100
  time_t    t = (time_t)key;
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
  taosLocalTime(&t, &tm);

  int mon = (int)(tm.tm_year * 12 + tm.tm_mon + interval * factor);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, pInterval->precision);

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
  tw->ekey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, pInterval->precision);

  tw->ekey -= 1;
}

static bool overlapWithTimeWindow(SInterval* pInterval, SDataBlockInfo* pBlockInfo) {
  STimeWindow w = {0};

  // 0 by default, which means it is not a interval operator of the upstream operator.
  if (pInterval->interval == 0) {
    return false;
  }

  // todo handle the time range case
  TSKEY sk = INT64_MIN;
  TSKEY ek = INT64_MAX;
127 128
  //  TSKEY sk = MIN(pQueryAttr->window.skey, pQueryAttr->window.ekey);
  //  TSKEY ek = MAX(pQueryAttr->window.skey, pQueryAttr->window.ekey);
129 130

  if (true) {
131
    getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.skey, &w);
132 133 134 135 136 137
    assert(w.ekey >= pBlockInfo->window.skey);

    if (w.ekey < pBlockInfo->window.ekey) {
      return true;
    }

138
    while (1) {  // todo handle the desc order scan case
139 140 141 142 143 144 145 146 147 148 149
      getNextTimeWindow(pInterval, &w, TSDB_ORDER_ASC);
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

      assert(w.ekey > pBlockInfo->window.ekey);
      if (w.skey <= pBlockInfo->window.ekey && w.skey > pBlockInfo->window.skey) {
        return true;
      }
    }
  } else {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
    //    assert(w.skey <= pBlockInfo->window.ekey);
    //
    //    if (w.skey > pBlockInfo->window.skey) {
    //      return true;
    //    }
    //
    //    while(1) {
    //      getNextTimeWindow(pQueryAttr, &w);
    //      if (w.ekey < pBlockInfo->window.skey) {
    //        break;
    //      }
    //
    //      assert(w.skey < pBlockInfo->window.skey);
    //      if (w.ekey < pBlockInfo->window.ekey && w.ekey >= pBlockInfo->window.skey) {
    //        return true;
    //      }
    //    }
168 169 170 171 172
  }

  return false;
}

173
int32_t loadDataBlock(SOperatorInfo* pOperator, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, uint32_t* status) {
174
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
175 176
  STableScanInfo* pInfo = pOperator->info;

H
Haojun Liao 已提交
177 178 179
  STaskCostInfo* pCost = &pTaskInfo->cost;

  pCost->totalBlocks += 1;
180
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
181

182
  *status = pInfo->dataBlockLoadFlag;
183
  if (pTableScanInfo->pFilterNode != NULL || overlapWithTimeWindow(&pTableScanInfo->interval, &pBlock->info)) {
184 185 186 187
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

  SDataBlockInfo* pBlockInfo = &pBlock->info;
188
  taosMemoryFreeClear(pBlock->pBlockAgg);
189 190

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
191 192
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
193 194 195
    pCost->filterOutBlocks += 1;
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
196 197
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
198 199 200 201 202
    pCost->skipBlocks += 1;
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_STATIS_LOAD) {
    pCost->loadBlockStatis += 1;

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    SColumnDataAgg* pColAgg = NULL;
    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->dataReader, &pColAgg);

    if (pColAgg != NULL) {
      int32_t numOfCols = pBlock->info.numOfCols;

      // todo create this buffer during creating operator
      pBlock->pBlockAgg = taosMemoryCalloc(numOfCols, sizeof(SColumnDataAgg));
      for (int32_t i = 0; i < numOfCols; ++i) {
        SColMatchInfo* pColMatchInfo = taosArrayGet(pTableScanInfo->pColMatchInfo, i);
        if (!pColMatchInfo->output) {
          continue;
        }
        pBlock->pBlockAgg[pColMatchInfo->targetSlotId] = pColAgg[i];
      }
H
Haojun Liao 已提交
218

219
      return TSDB_CODE_SUCCESS;
220
    } else {  // failed to load the block sma data, data block statistics does not exist, load data block instead
H
Haojun Liao 已提交
221
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
222
    }
H
Haojun Liao 已提交
223
  }
224

225
  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);
226

H
Haojun Liao 已提交
227 228 229 230 231 232 233 234 235 236
  // todo filter data block according to the block sma data firstly
#if 0
  if (!doFilterByBlockStatistics(pBlock->pBlockStatis, pTableScanInfo->pCtx, pBlockInfo->rows)) {
    pCost->filterOutBlocks += 1;
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo), pBlockInfo->window.skey,
           pBlockInfo->window.ekey, pBlockInfo->rows);
    (*status) = FUNC_DATA_REQUIRED_FILTEROUT;
    return TSDB_CODE_SUCCESS;
  }
#endif
H
Haojun Liao 已提交
237

H
Haojun Liao 已提交
238 239
  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;
240

H
Haojun Liao 已提交
241 242 243
  SArray* pCols = tsdbRetrieveDataBlock(pTableScanInfo->dataReader, NULL);
  if (pCols == NULL) {
    return terrno;
H
Haojun Liao 已提交
244 245
  }

H
Haojun Liao 已提交
246 247
  relocateColumnData(pBlock, pTableScanInfo->pColMatchInfo, pCols);

248 249
  // reset the block to be 0 by default, this blockId is assigned by physical plan and is used by direct upstream
  // operator.
250 251
  pBlock->info.blockId = 0;

252
  doFilter(pTableScanInfo->pFilterNode, pBlock);
253 254
  if (pBlock->info.rows == 0) {
    pCost->filterOutBlocks += 1;
255 256
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
257 258
  }

H
Haojun Liao 已提交
259 260 261
  return TSDB_CODE_SUCCESS;
}

262
static void prepareForDescendingScan(STableScanInfo* pTableScanInfo, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
263 264 265
  SET_REVERSE_SCAN_FLAG(pTableScanInfo);

  switchCtxOrder(pCtx, numOfOutput);
266
  //  setupQueryRangeForReverseScan(pTableScanInfo);
H
Haojun Liao 已提交
267

268 269 270
  STimeWindow* pTWindow = &pTableScanInfo->cond.twindow;
  TSWAP(pTWindow->skey, pTWindow->ekey, int64_t);
  pTableScanInfo->cond.order = TSDB_ORDER_DESC;
H
Haojun Liao 已提交
271 272 273 274 275
}

static SSDataBlock* doTableScanImpl(SOperatorInfo* pOperator, bool* newgroup) {
  STableScanInfo* pTableScanInfo = pOperator->info;

276
  SSDataBlock* pBlock = pTableScanInfo->pResBlock;
H
Haojun Liao 已提交
277 278 279 280 281 282 283 284 285 286
  *newgroup = false;

  while (tsdbNextDataBlock(pTableScanInfo->dataReader)) {
    if (isTaskKilled(pOperator->pTaskInfo)) {
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
    }

    pTableScanInfo->numOfBlocks += 1;
    tsdbRetrieveDataBlockInfo(pTableScanInfo->dataReader, &pBlock->info);

287
    uint32_t status = 0;
H
Haojun Liao 已提交
288
    int32_t  code = loadDataBlock(pOperator, pTableScanInfo, pBlock, &status);
H
Haojun Liao 已提交
289 290 291 292 293
    //    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pOperator->pTaskInfo->env, code);
    }

294 295
    // current block is filter out according to filter condition, continue load the next block
    if (status == FUNC_DATA_REQUIRED_FILTEROUT || pBlock->info.rows == 0) {
H
Haojun Liao 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309
      continue;
    }

    return pBlock;
  }

  return NULL;
}

static SSDataBlock* doTableScan(SOperatorInfo* pOperator, bool* newgroup) {
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;

  // The read handle is not initialized yet, since no qualified tables exists
310
  if (pTableScanInfo->dataReader == NULL || pOperator->status == OP_EXEC_DONE) {
H
Haojun Liao 已提交
311 312 313 314 315
    return NULL;
  }

  *newgroup = false;

316
  while (pTableScanInfo->current < pTableScanInfo->scanInfo.numOfAsc) {
H
Haojun Liao 已提交
317 318 319 320 321
    SSDataBlock* p = doTableScanImpl(pOperator, newgroup);
    if (p != NULL) {
      return p;
    }

322 323 324 325 326 327 328
    pTableScanInfo->current += 1;

    if (pTableScanInfo->current < pTableScanInfo->scanInfo.numOfAsc) {
      setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
      pTableScanInfo->scanFlag = REPEAT_SCAN;

      STimeWindow* pWin = &pTableScanInfo->cond.twindow;
329 330
      qDebug("%s start to repeat ascending order scan data blocks due to query func required, qrange:%" PRId64
             "-%" PRId64,
331 332 333 334
             GET_TASKID(pTaskInfo), pWin->skey, pWin->ekey);

      // do prepare for the next round table scan operation
      tsdbResetReadHandle(pTableScanInfo->dataReader, &pTableScanInfo->cond);
H
Haojun Liao 已提交
335
    }
336
  }
H
Haojun Liao 已提交
337

338 339 340 341 342 343
  int32_t total = pTableScanInfo->scanInfo.numOfAsc + pTableScanInfo->scanInfo.numOfDesc;
  if (pTableScanInfo->current < total) {
    if (pTableScanInfo->cond.order == TSDB_ORDER_ASC) {
      prepareForDescendingScan(pTableScanInfo, pTableScanInfo->pCtx, pTableScanInfo->numOfOutput);
      tsdbResetReadHandle(pTableScanInfo->dataReader, &pTableScanInfo->cond);
    }
H
Haojun Liao 已提交
344

345 346 347
    STimeWindow* pWin = &pTableScanInfo->cond.twindow;
    qDebug("%s start to descending order scan data blocks due to query func required, qrange:%" PRId64 "-%" PRId64,
           GET_TASKID(pTaskInfo), pWin->skey, pWin->ekey);
H
Haojun Liao 已提交
348

349 350 351 352 353
    while (pTableScanInfo->current < total) {
      SSDataBlock* p = doTableScanImpl(pOperator, newgroup);
      if (p != NULL) {
        return p;
      }
H
Haojun Liao 已提交
354

355
      pTableScanInfo->current += 1;
H
Haojun Liao 已提交
356

357 358 359
      if (pTableScanInfo->current < pTableScanInfo->scanInfo.numOfAsc) {
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
        pTableScanInfo->scanFlag = REPEAT_SCAN;
H
Haojun Liao 已提交
360

361 362
        qDebug("%s start to repeat descending order scan data blocks due to query func required, qrange:%" PRId64
               "-%" PRId64,
363
               GET_TASKID(pTaskInfo), pTaskInfo->window.skey, pTaskInfo->window.ekey);
H
Haojun Liao 已提交
364

365 366 367
        // do prepare for the next round table scan operation
        tsdbResetReadHandle(pTableScanInfo->dataReader, &pTableScanInfo->cond);
      }
H
Haojun Liao 已提交
368 369 370
    }
  }

371 372
  setTaskStatus(pTaskInfo, TASK_COMPLETED);
  return NULL;
H
Haojun Liao 已提交
373 374
}

375 376
SOperatorInfo* createTableScanOperatorInfo(void* pDataReader, SQueryTableDataCond* pCond, int32_t numOfOutput,
                                           int32_t dataLoadFlag, const uint8_t* scanInfo, SArray* pColMatchInfo,
H
Hongze Cheng 已提交
377 378
                                           SSDataBlock* pResBlock, SNode* pCondition, SInterval* pInterval,
                                           double sampleRatio, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
379 380 381 382 383 384 385 386 387 388
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);

    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

389 390
  pInfo->cond = *pCond;
  pInfo->scanInfo = (SScanInfo){.numOfAsc = scanInfo[0], .numOfDesc = scanInfo[1]};
391

H
Hongze Cheng 已提交
392 393 394 395 396 397 398 399 400
  pInfo->interval = *pInterval;
  pInfo->sampleRatio = sampleRatio;
  pInfo->dataBlockLoadFlag = dataLoadFlag;
  pInfo->pResBlock = pResBlock;
  pInfo->pFilterNode = pCondition;
  pInfo->dataReader = pDataReader;
  pInfo->current = 0;
  pInfo->scanFlag = MAIN_SCAN;
  pInfo->pColMatchInfo = pColMatchInfo;
401

H
Hongze Cheng 已提交
402
  pOperator->name = "TableScanOperator";
H
Haojun Liao 已提交
403 404
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN;
  pOperator->blockingOptr = false;
405 406 407
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = numOfOutput;
408
  pOperator->fpSet.getNextFn = doTableScan;
409
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
410

D
dapan1121 已提交
411 412 413 414 415
  static int32_t cost = 0;
  pOperator->cost.openCost = ++cost;
  pOperator->cost.totalCost = ++cost;
  pOperator->resultInfo.totalRows = ++cost;

H
Haojun Liao 已提交
416 417 418
  return pOperator;
}

419
SOperatorInfo* createTableSeqScanOperatorInfo(void* pTsdbReadHandle) {
H
Haojun Liao 已提交
420 421 422 423 424 425 426 427 428 429 430 431
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));

  pInfo->dataReader = pTsdbReadHandle;
  pInfo->current = 0;
  pInfo->prevGroupId = -1;

  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  pOperator->name = "TableSeqScanOperator";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SEQ_SCAN;
  pOperator->blockingOptr = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
432
  pOperator->fpSet.getNextFn = doTableScanImpl;
H
Haojun Liao 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

  return pOperator;
}

static SSDataBlock* doBlockInfoScan(SOperatorInfo* pOperator, bool* newgroup) {
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableScanInfo* pTableScanInfo = pOperator->info;
  *newgroup = false;

  STableBlockDistInfo tableBlockDist = {0};
  tableBlockDist.numOfTables = 1;  // TODO set the correct number of tables

S
Shengliang Guan 已提交
448 449
  int32_t numRowSteps = TSDB_DEFAULT_MAXROWS_FBLOCK / TSDB_BLOCK_DIST_STEP_ROWS;
  if (TSDB_DEFAULT_MAXROWS_FBLOCK % TSDB_BLOCK_DIST_STEP_ROWS != 0) {
H
Haojun Liao 已提交
450 451 452
    ++numRowSteps;
  }

453
  tableBlockDist.dataBlockInfos = taosArrayInit(numRowSteps, sizeof(SFileBlockInfo));
H
Haojun Liao 已提交
454 455 456 457 458 459
  taosArraySetSize(tableBlockDist.dataBlockInfos, numRowSteps);

  tableBlockDist.maxRows = INT_MIN;
  tableBlockDist.minRows = INT_MAX;

  tsdbGetFileBlocksDistInfo(pTableScanInfo->dataReader, &tableBlockDist);
460
  tableBlockDist.numOfRowsInMemTable = (int32_t)tsdbGetNumOfRowsInMemTable(pTableScanInfo->dataReader);
H
Haojun Liao 已提交
461

462
  SSDataBlock* pBlock = pTableScanInfo->pResBlock;
463
  pBlock->info.rows = 1;
H
Haojun Liao 已提交
464 465
  pBlock->info.numOfCols = 1;

466 467
  //  SBufferWriter bw = tbufInitWriter(NULL, false);
  //  blockDistInfoToBinary(&tableBlockDist, &bw);
H
Haojun Liao 已提交
468 469
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);

470 471 472 473 474 475
  //  int32_t len = (int32_t) tbufTell(&bw);
  //  pColInfo->pData = taosMemoryMalloc(len + sizeof(int32_t));
  //  *(int32_t*) pColInfo->pData = len;
  //  memcpy(pColInfo->pData + sizeof(int32_t), tbufGetData(&bw, false), len);
  //
  //  tbufCloseWriter(&bw);
H
Haojun Liao 已提交
476

477 478
  //  SArray* g = GET_TABLEGROUP(pOperator->, 0);
  //  pOperator->pRuntimeEnv->current = taosArrayGetP(g, 0);
H
Haojun Liao 已提交
479 480 481 482 483 484

  pOperator->status = OP_EXEC_DONE;
  return pBlock;
}

SOperatorInfo* createDataBlockInfoScanOperator(void* dataReader, SExecTaskInfo* pTaskInfo) {
485 486
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
487 488 489 490 491
  if (pInfo == NULL || pOperator == NULL) {
    pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }

492 493
  pInfo->dataReader = dataReader;
  //  pInfo->block.pDataBlock = taosArrayInit(1, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
494 495

  SColumnInfoData infoData = {0};
496
  infoData.info.type = TSDB_DATA_TYPE_BINARY;
H
Haojun Liao 已提交
497 498
  infoData.info.bytes = 1024;
  infoData.info.colId = 0;
499
  //  taosArrayPush(pInfo->block.pDataBlock, &infoData);
H
Haojun Liao 已提交
500

501
  pOperator->name = "DataBlockInfoScanOperator";
H
Haojun Liao 已提交
502
  //  pOperator->operatorType = OP_TableBlockInfoScan;
503 504
  pOperator->blockingOptr = false;
  pOperator->status = OP_NOT_OPENED;
505 506
  pOperator->fpSet._openFn = operatorDummyOpenFn;
  pOperator->fpSet.getNextFn = doBlockInfoScan;
H
Haojun Liao 已提交
507

508 509
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
510 511 512

  return pOperator;

513
_error:
H
Haojun Liao 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
}

static void doClearBufferedBlocks(SStreamBlockScanInfo* pInfo) {
  size_t total = taosArrayGetSize(pInfo->pBlockLists);

  pInfo->validBlockIndex = 0;
  for (int32_t i = 0; i < total; ++i) {
    SSDataBlock* p = taosArrayGetP(pInfo->pBlockLists, i);
    blockDataDestroy(p);
  }
  taosArrayClear(pInfo->pBlockLists);
}

static SSDataBlock* doStreamBlockScan(SOperatorInfo* pOperator, bool* newgroup) {
  // NOTE: this operator does never check if current status is done or not
  SExecTaskInfo*        pTaskInfo = pOperator->pTaskInfo;
  SStreamBlockScanInfo* pInfo = pOperator->info;

535
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
536
  if (pTaskInfo->code != TSDB_CODE_SUCCESS || pOperator->status == OP_EXEC_DONE) {
H
Haojun Liao 已提交
537 538 539 540 541 542 543
    return NULL;
  }

  if (pInfo->blockType == STREAM_DATA_TYPE_SSDATA_BLOCK) {
    size_t total = taosArrayGetSize(pInfo->pBlockLists);
    if (pInfo->validBlockIndex >= total) {
      doClearBufferedBlocks(pInfo);
544
      pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
545 546 547 548 549 550 551 552 553 554
      return NULL;
    }

    int32_t current = pInfo->validBlockIndex++;
    return taosArrayGetP(pInfo->pBlockLists, current);
  } else {
    SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
    blockDataCleanup(pInfo->pRes);

    while (tqNextDataBlock(pInfo->readerHandle)) {
555 556 557
      SArray*  pCols = NULL;
      uint64_t groupId;
      int32_t  numOfRows;
L
Liu Jicong 已提交
558 559
      int16_t  outputCol;
      int32_t  code = tqRetrieveDataBlock(&pCols, pInfo->readerHandle, &groupId, &numOfRows, &outputCol);
H
Haojun Liao 已提交
560

561 562 563
      if (code != TSDB_CODE_SUCCESS || numOfRows == 0) {
        pTaskInfo->code = code;
        return NULL;
H
Haojun Liao 已提交
564 565
      }

566 567
      pInfo->pRes->info.groupId = groupId;
      pInfo->pRes->info.rows = numOfRows;
H
Haojun Liao 已提交
568 569 570

      int32_t numOfCols = pInfo->pRes->info.numOfCols;
      for (int32_t i = 0; i < numOfCols; ++i) {
571
        SColMatchInfo* pColMatchInfo = taosArrayGet(pInfo->pColMatchInfo, i);
H
Haojun Liao 已提交
572 573 574 575
        if (!pColMatchInfo->output) {
          continue;
        }

576
        bool colExists = false;
577
        for (int32_t j = 0; j < taosArrayGetSize(pCols); ++j) {
578 579 580 581 582 583 584 585 586 587 588 589 590 591
          SColumnInfoData* pResCol = taosArrayGet(pCols, j);
          if (pResCol->info.colId == pColMatchInfo->colId) {
            taosArraySet(pInfo->pRes->pDataBlock, pColMatchInfo->targetSlotId, pResCol);
            colExists = true;
            break;
          }
        }

        // the required column does not exists in submit block, let's set it to be all null value
        if (!colExists) {
          SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->targetSlotId);
          colInfoDataEnsureCapacity(pDst, 0, pBlockInfo->rows);
          colDataAppendNNULL(pDst, 0, pBlockInfo->rows);
        }
H
Haojun Liao 已提交
592 593 594 595
      }

      if (pInfo->pRes->pDataBlock == NULL) {
        // TODO add log
596
        pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
597 598 599 600 601 602 603 604 605 606 607
        pTaskInfo->code = terrno;
        return NULL;
      }

      break;
    }

    // record the scan action.
    pInfo->numOfExec++;
    pInfo->numOfRows += pBlockInfo->rows;

608 609 610 611
    if (pBlockInfo->rows == 0) {
      pOperator->status = OP_EXEC_DONE;
    }

H
Haojun Liao 已提交
612 613 614 615
    return (pBlockInfo->rows == 0) ? NULL : pInfo->pRes;
  }
}

616 617
SOperatorInfo* createStreamScanOperatorInfo(void* streamReadHandle, SSDataBlock* pResBlock, SArray* pColList,
                                            SArray* pTableIdList, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
618 619 620 621 622 623 624 625 626 627 628 629
  SStreamBlockScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamBlockScanInfo));
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

  int32_t numOfOutput = taosArrayGetSize(pColList);

  SArray* pColIds = taosArrayInit(4, sizeof(int16_t));
630
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    int16_t* id = taosArrayGet(pColList, i);
    taosArrayPush(pColIds, id);
  }

  pInfo->pColMatchInfo = pColList;

  // set the extract column id to streamHandle
  tqReadHandleSetColIdList((STqReadHandle*)streamReadHandle, pColIds);
  int32_t code = tqReadHandleSetTbUidList(streamReadHandle, pTableIdList);
  if (code != 0) {
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
    return NULL;
  }

  pInfo->pBlockLists = taosArrayInit(4, POINTER_BYTES);
  if (pInfo->pBlockLists == NULL) {
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
    return NULL;
  }

  pInfo->readerHandle = streamReadHandle;
  pInfo->pRes = pResBlock;

656
  pOperator->name = "StreamBlockScanOperator";
H
Haojun Liao 已提交
657 658
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN;
  pOperator->blockingOptr = false;
659 660 661
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = pResBlock->info.numOfCols;
662 663 664
  pOperator->fpSet._openFn = operatorDummyOpenFn;
  pOperator->fpSet.getNextFn = doStreamBlockScan;
  pOperator->fpSet.closeFn = operatorDummyCloseFn;
665
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
666 667 668 669 670 671 672 673 674

  return pOperator;
}

static void destroySysScanOperator(void* param, int32_t numOfOutput) {
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*)param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

675 676
  const char* name = tNameGetTableName(&pInfo->name);
  if (strncasecmp(name, TSDB_INS_TABLE_USER_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
H
Haojun Liao 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    metaCloseTbCursor(pInfo->pCur);
  }
}

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 (TSDB_INS_USER_STABLES_DBNAME_COLID == 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;
721
      return DEAL_RES_END;  // stop walk
H
Haojun Liao 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734
    }
    default:
      break;
  }

  return DEAL_RES_CONTINUE;
}

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

H
Haojun Liao 已提交
735
  nodesWalkExpr(pCondition, getDBNameFromConditionWalker, dbName);
H
Haojun Liao 已提交
736 737 738 739 740 741 742 743 744 745
}

static int32_t loadSysTableContentCb(void* param, const 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);
746 747 748
    pRsp->useconds = htobe64(pRsp->useconds);
    pRsp->handle = htobe64(pRsp->handle);
    pRsp->compLen = htonl(pRsp->compLen);
H
Haojun Liao 已提交
749 750 751 752 753
  } else {
    operator->pTaskInfo->code = code;
  }

  tsem_post(&pScanResInfo->ready);
wmmhello's avatar
wmmhello 已提交
754
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
}

static SSDataBlock* doFilterResult(SSysTableScanInfo* pInfo) {
  if (pInfo->pCondition == NULL) {
    return pInfo->pRes->info.rows == 0 ? NULL : pInfo->pRes;
  }

  SFilterInfo* filter = NULL;
  int32_t      code = filterInitFromNode(pInfo->pCondition, &filter, 0);

  SFilterColumnParam param1 = {.numOfCols = pInfo->pRes->info.numOfCols, .pDataBlock = pInfo->pRes->pDataBlock};
  code = filterSetDataFromSlotId(filter, &param1);

  int8_t* rowRes = NULL;
  bool    keep = filterExecute(filter, pInfo->pRes, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
770
  filterFreeInfo(filter);
H
Haojun Liao 已提交
771

772
  SSDataBlock* px = createOneDataBlock(pInfo->pRes, false);
H
Haojun Liao 已提交
773 774 775 776 777 778 779 780
  blockDataEnsureCapacity(px, pInfo->pRes->info.rows);

  // TODO refactor
  int32_t numOfRow = 0;
  for (int32_t i = 0; i < pInfo->pRes->info.numOfCols; ++i) {
    SColumnInfoData* pDest = taosArrayGet(px->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(pInfo->pRes->pDataBlock, i);

D
dapan1121 已提交
781 782 783 784 785 786 787 788 789
    if (keep) {
      colDataAssign(pDest, pSrc, pInfo->pRes->info.rows);
      numOfRow = pInfo->pRes->info.rows;
    } else if (NULL != rowRes) {
      numOfRow = 0;
      for (int32_t j = 0; j < pInfo->pRes->info.rows; ++j) {
        if (rowRes[j] == 0) {
          continue;
        }
790

D
dapan1121 已提交
791 792
        colDataAppend(pDest, numOfRow, colDataGetData(pSrc, j), false);
        numOfRow += 1;
H
Haojun Liao 已提交
793
      }
D
dapan1121 已提交
794 795
    } else {
      numOfRow = 0;
H
Haojun Liao 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    }
  }

  px->info.rows = numOfRow;
  pInfo->pRes = px;

  return pInfo->pRes->info.rows == 0 ? NULL : pInfo->pRes;
}

static SSDataBlock* doSysTableScan(SOperatorInfo* pOperator, bool* newgroup) {
  // build message and send to mnode to fetch the content of system tables.
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;

  // retrieve local table list info from vnode
811 812
  const char* name = tNameGetTableName(&pInfo->name);
  if (strncasecmp(name, TSDB_INS_TABLE_USER_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
H
Haojun Liao 已提交
813 814 815 816 817 818 819 820 821
    if (pInfo->pCur == NULL) {
      pInfo->pCur = metaOpenTbCursor(pInfo->readHandle);
    }

    blockDataCleanup(pInfo->pRes);

    int32_t          tableNameSlotId = 1;
    SColumnInfoData* pTableNameCol = taosArrayGet(pInfo->pRes->pDataBlock, tableNameSlotId);

822
    char*   tb = NULL;
H
Haojun Liao 已提交
823 824 825
    int32_t numOfRows = 0;

    char n[TSDB_TABLE_NAME_LEN] = {0};
H
Hongze Cheng 已提交
826 827
    while (metaTbCursorNext(pInfo->pCur) == 0) {
      STR_TO_VARSTR(n, pInfo->pCur->mr.me.name);
H
Haojun Liao 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841
      colDataAppend(pTableNameCol, numOfRows, n, false);
      numOfRows += 1;
      if (numOfRows >= pInfo->capacity) {
        break;
      }

      for (int32_t i = 0; i < pInfo->pRes->info.numOfCols; ++i) {
        if (i == tableNameSlotId) {
          continue;
        }

        SColumnInfoData* pColInfoData = taosArrayGet(pInfo->pRes->pDataBlock, i);
        int64_t          tmp = 0;
        char             t[10] = {0};
842
        STR_TO_VARSTR(t, "_");  // TODO
H
Haojun Liao 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
        if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
          colDataAppend(pColInfoData, numOfRows, t, false);
        } else {
          colDataAppend(pColInfoData, numOfRows, (char*)&tmp, false);
        }
      }
    }

    pInfo->loadInfo.totalRows += numOfRows;
    pInfo->pRes->info.rows = numOfRows;

    //    pInfo->elapsedTime;
    //    pInfo->totalBytes;
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  } else {  // load the meta from mnode of the given epset
    if (pOperator->status == OP_EXEC_DONE) {
      return NULL;
    }

862 863 864
    while (1) {
      int64_t startTs = taosGetTimestampUs();
      strncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));
H
Haojun Liao 已提交
865

866 867 868 869 870
      if (pInfo->showRewrite) {
        char dbName[TSDB_DB_NAME_LEN] = {0};
        getDBNameFromCondition(pInfo->pCondition, dbName);
        sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
      }
H
Haojun Liao 已提交
871

872 873 874 875 876 877 878 879 880 881 882
      int32_t contLen = tSerializeSRetrieveTableReq(NULL, 0, &pInfo->req);
      char*   buf1 = taosMemoryCalloc(1, contLen);
      tSerializeSRetrieveTableReq(buf1, contLen, &pInfo->req);

      // 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_QRY_OUT_OF_MEMORY;
        return NULL;
      }
H
Haojun Liao 已提交
883

884 885 886 887 888
      pMsgSendInfo->param = pOperator;
      pMsgSendInfo->msgInfo.pData = buf1;
      pMsgSendInfo->msgInfo.len = contLen;
      pMsgSendInfo->msgType = TDMT_MND_SYSTABLE_RETRIEVE;
      pMsgSendInfo->fp = loadSysTableContentCb;
H
Haojun Liao 已提交
889

890 891 892
      int64_t transporterId = 0;
      int32_t code = asyncSendMsgToServer(pInfo->pTransporter, &pInfo->epSet, &transporterId, pMsgSendInfo);
      tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
893

894 895 896 897 898
      if (pTaskInfo->code) {
        qDebug("%s load meta data from mnode failed, totalRows:%" PRIu64 ", code:%s", GET_TASKID(pTaskInfo),
               pInfo->loadInfo.totalRows, tstrerror(pTaskInfo->code));
        return NULL;
      }
H
Haojun Liao 已提交
899

900 901
      SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
      pInfo->req.showId = pRsp->handle;
H
Haojun Liao 已提交
902

903 904 905 906
      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);
H
Haojun Liao 已提交
907

908 909 910 911
        if (pRsp->numOfRows == 0) {
          return NULL;
        }
      }
H
Haojun Liao 已提交
912

913 914 915
      SRetrieveMetaTableRsp* pTableRsp = pInfo->pRsp;
      setSDataBlockFromFetchRsp(pInfo->pRes, &pInfo->loadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                pTableRsp->compLen, pOperator->numOfOutput, startTs, NULL, pInfo->scanCols);
H
Haojun Liao 已提交
916

917 918 919 920 921
      // todo log the filter info
      doFilterResult(pInfo);
      if (pInfo->pRes->info.rows > 0) {
        return pInfo->pRes;
      }
922
    }
H
Haojun Liao 已提交
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  }
}

SOperatorInfo* createSysTableScanOperatorInfo(void* pSysTableReadHandle, SSDataBlock* pResBlock, const SName* pName,
                                              SNode* pCondition, SEpSet epset, SArray* colList,
                                              SExecTaskInfo* pTaskInfo, bool showRewrite, int32_t accountId) {
  SSysTableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

938
  pInfo->accountId = accountId;
H
Haojun Liao 已提交
939
  pInfo->showRewrite = showRewrite;
940 941 942 943
  pInfo->pRes = pResBlock;
  pInfo->capacity = 4096;
  pInfo->pCondition = pCondition;
  pInfo->scanCols = colList;
H
Haojun Liao 已提交
944 945

  tNameAssign(&pInfo->name, pName);
946 947
  const char* name = tNameGetTableName(&pInfo->name);
  if (strncasecmp(name, TSDB_INS_TABLE_USER_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
H
Haojun Liao 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    pInfo->readHandle = pSysTableReadHandle;
    blockDataEnsureCapacity(pInfo->pRes, pInfo->capacity);
  } else {
    tsem_init(&pInfo->ready, 0, 0);
    pInfo->epSet = epset;

#if 1
    {  // todo refactor
      SRpcInit rpcInit;
      memset(&rpcInit, 0, sizeof(rpcInit));
      rpcInit.localPort = 0;
      rpcInit.label = "DB-META";
      rpcInit.numOfThreads = 1;
      rpcInit.cfp = qProcessFetchRsp;
      rpcInit.sessions = tsMaxConnections;
      rpcInit.connType = TAOS_CONN_CLIENT;
      rpcInit.user = (char*)"root";
      rpcInit.idleTime = tsShellActivityTimer * 1000;
      rpcInit.ckey = "key";
      rpcInit.spi = 1;
      rpcInit.secret = (char*)"dcc5bed04851fec854c035b2e40263b6";

      pInfo->pTransporter = rpcOpen(&rpcInit);
      if (pInfo->pTransporter == NULL) {
        return NULL;  // todo
      }
    }
#endif
  }

978
  pOperator->name = "SysTableScanOperator";
H
Haojun Liao 已提交
979 980
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN;
  pOperator->blockingOptr = false;
981 982 983
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = pResBlock->info.numOfCols;
984 985
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSysTableScan, NULL, NULL, destroySysScanOperator,
                                         NULL, NULL, NULL);
986
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
987 988 989

  return pOperator;
}
H
Haojun Liao 已提交
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 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 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 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 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

static SSDataBlock* doTagScan(SOperatorInfo* pOperator, bool* newgroup) {
#if 0
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  int32_t maxNumOfTables = (int32_t)pResultInfo->capacity;

  STagScanInfo *pInfo = pOperator->info;
  SSDataBlock  *pRes = pInfo->pRes;
  *newgroup = false;

  int32_t count = 0;
  SArray* pa = GET_TABLEGROUP(pRuntimeEnv, 0);

  int32_t functionId = getExprFunctionId(&pOperator->pExpr[0]);
  if (functionId == FUNCTION_TID_TAG) { // return the tags & table Id
    assert(pQueryAttr->numOfOutput == 1);

    SExprInfo* pExprInfo = &pOperator->pExpr[0];
    int32_t rsize = pExprInfo->base.resSchema.bytes;

    count = 0;

    int16_t bytes = pExprInfo->base.resSchema.bytes;
    int16_t type  = pExprInfo->base.resSchema.type;

    for(int32_t i = 0; i < pQueryAttr->numOfTags; ++i) {
      if (pQueryAttr->tagColList[i].colId == pExprInfo->base.pColumns->info.colId) {
        bytes = pQueryAttr->tagColList[i].bytes;
        type = pQueryAttr->tagColList[i].type;
        break;
      }
    }

    SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, 0);

    while(pInfo->curPos < pInfo->totalTables && count < maxNumOfTables) {
      int32_t i = pInfo->curPos++;
      STableQueryInfo *item = taosArrayGetP(pa, i);

      char *output = pColInfo->pData + count * rsize;
      varDataSetLen(output, rsize - VARSTR_HEADER_SIZE);

      output = varDataVal(output);
      STableId* id = TSDB_TABLEID(item->pTable);

      *(int16_t *)output = 0;
      output += sizeof(int16_t);

      *(int64_t *)output = id->uid;  // memory align problem, todo serialize
      output += sizeof(id->uid);

      *(int32_t *)output = id->tid;
      output += sizeof(id->tid);

      *(int32_t *)output = pQueryAttr->vgId;
      output += sizeof(pQueryAttr->vgId);

      char* data = NULL;
      if (pExprInfo->base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
        data = tsdbGetTableName(item->pTable);
      } else {
        data = tsdbGetTableTagVal(item->pTable, pExprInfo->base.pColumns->info.colId, type, bytes);
      }

      doSetTagValueToResultBuf(output, data, type, bytes);
      count += 1;
    }

    //qDebug("QInfo:0x%"PRIx64" create (tableId, tag) info completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
  } else if (functionId == FUNCTION_COUNT) {// handle the "count(tbname)" query
    SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, 0);
    *(int64_t*)pColInfo->pData = pInfo->totalTables;
    count = 1;

    pOperator->status = OP_EXEC_DONE;
    //qDebug("QInfo:0x%"PRIx64" create count(tbname) query, res:%d rows:1", GET_TASKID(pRuntimeEnv), count);
  } else {  // return only the tags|table name etc.
    SExprInfo* pExprInfo = &pOperator->pExpr[0];  // todo use the column list instead of exprinfo

    count = 0;
    while(pInfo->curPos < pInfo->totalTables && count < maxNumOfTables) {
      int32_t i = pInfo->curPos++;

      STableQueryInfo* item = taosArrayGetP(pa, i);

      char *data = NULL, *dst = NULL;
      int16_t type = 0, bytes = 0;
      for(int32_t j = 0; j < pOperator->numOfOutput; ++j) {
        // not assign value in case of user defined constant output column
        if (TSDB_COL_IS_UD_COL(pExprInfo[j].base.pColumns->flag)) {
          continue;
        }

        SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, j);
        type  = pExprInfo[j].base.resSchema.type;
        bytes = pExprInfo[j].base.resSchema.bytes;

        if (pExprInfo[j].base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
          data = tsdbGetTableName(item->pTable);
        } else {
          data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.pColumns->info.colId, type, bytes);
        }

        dst  = pColInfo->pData + count * pExprInfo[j].base.resSchema.bytes;
        doSetTagValueToResultBuf(dst, data, type, bytes);
      }

      count += 1;
    }

    if (pInfo->curPos >= pInfo->totalTables) {
      pOperator->status = OP_EXEC_DONE;
    }

    //qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
  }

  if (pOperator->status == OP_EXEC_DONE) {
    setTaskStatus(pOperator->pRuntimeEnv, TASK_COMPLETED);
  }

  pRes->info.rows = count;
  return (pRes->info.rows == 0)? NULL:pInfo->pRes;

#endif
  return TSDB_CODE_SUCCESS;
}

static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
}

1127 1128 1129
SOperatorInfo* createTagScanOperatorInfo(void* pReaderHandle, SExprInfo* pExpr, int32_t numOfOutput,
                                         SExecTaskInfo* pTaskInfo) {
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
1130 1131 1132 1133 1134
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

1135 1136 1137 1138 1139 1140 1141
  pInfo->pReader = pReaderHandle;
  pInfo->curPos = 0;
  pOperator->name = "TagScanOperator";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
  pOperator->blockingOptr = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
1142 1143 1144

  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doTagScan, NULL, NULL, destroyTagScanOperatorInfo, NULL, NULL, NULL);
1145 1146 1147
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
1148 1149

  return pOperator;
1150
_error:
H
Haojun Liao 已提交
1151 1152 1153 1154 1155
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}